feat: gate replica activation and add the dev drill
Plan 4 Task 5, trimmed and ruled (D9, R4, R11, R13, R16, R17). Console publication judge: replicaFloorJudge refuses a system target below StatelessReplicasFloor while any app has copies above 1, or any live instance has more than one assigned box or a retiring one (SR-4-C23, no override). It runs in both branches of systemFloorSnapshot (update preflight, promote, rollback, first publication) and again under the new replicaFloorMu with the pointer write (replicaFloorPublish), nested between fleetFloorMu and regionalMu. Unreadable inventory refuses. A console with no fleet passes. Copies door barrier: copies above 1 take replicaFloorMu after the app lock, through the config write, and refuse while any published router channel pointer is below the floor (SR-4-C62, unreadable is a 503). A box counts at the floor only when its heartbeat release and its new prev_release (carlos.prev, reported by the agent's status tick) are at the floor or prev is none (R16). Each live instance must hold a last good build first (R13, SR-4-C61). No box-side backstop (R16). Docs: docs/site/stateless-replicas.md under Guides, a cross-link from the CLI reference, and provisional copy rows SR-4-C61 to C76 pending Paul's copy review. Drill tooling: scripts/stateless-replicas-drill (runDrill, drillConfig, drillReport) with the accounting tested by TestReplicaDrillAccounting. It holds no provider credentials; the operator acts at every change. Nothing live was run. Census overlay stateless-replicas-4-task5 proposed; record-write census layered for Task 5.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/site/cli.md+2 −0docs/site/nav.json+5 −0docs/site/stateless-replicas.md+47 −0docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md+35 −0docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md+27 −11internal/console/apisystemupdate.go+4 −4internal/console/appcopies.go+18 −1internal/console/appcopies_test.go+24 −1internal/console/copiespublication_test.go+1 −0internal/console/fleetbox.go+4 −0internal/console/fleetfloor_test.go+5 −3internal/console/hostactivation.go+23 −12internal/console/replicafloor.go+254 −0internal/console/replicafloor_test.go+393 −0internal/console/rootfs_test.go+1 −1internal/console/rootfsfloor.go+14 −5internal/console/server.go+10 −0internal/host/agent.go+5 −1internal/host/movesfloor.go+14 −6internal/provision/plan9_b8_census_test.go+1 −1internal/provision/stateless_replicas_4_task5_census_test.go+36 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv+20 −0internal/status/snapshot.go+8 −2scripts/stateless-replicas-drill/accounting.go+218 −0scripts/stateless-replicas-drill/accounting_test.go+164 −0scripts/stateless-replicas-drill/main.go+618 −0
CI failed — run details
Intent
<paseo-system version="1" kind="agent-message" source-agent-id="58a6481f-ac92-4d29-8cf5-21bd318a7e0c" message-id="9fe92268-d60f-4ada-a260-431b15ace390" source-agent-title="CI fleet: fix carlos/platform env failures (#897)"> From 58a6481: activator-settle-wait is on main as 27d3f50. waitBackground(t, a) and Service.background are available to merge into stateless-replicas-4. </paseo-system>
<paseo-system version="1" kind="agent-message" source-agent-id="82664493-e48e-4bd2-bfe5-5ea92f288c9e" message-id="99131db3-752f-4b74-a104-59d912e917be" source-agent-title="Release v0.34.41 (HA-only) resumed"> From the v0.34.46 release agent (job from 8a3d302): v0.34.46 is PUBLISHED and Latest: https://github.com/carlosframework/releases/releases/tag/v0.34.46 (tag -> 27d3f501; 24 assets, signatures verified; Homebrew tap updated). Contents: linked deployments (dormant until a home box links), optional statistics retention (off unless CARLOS_ANALYTICS_RETENTION_DAYS is set), group roll verb fixes, a demo serving fix. apt follows later today. Tito can roll its own staging now. </paseo-system>
Attributed to this commit: 57.9 g CO₂e (7,297,581 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on stateless-replicas-4, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/site/cli.md b/docs/site/cli.md| index 721585e3f..5d6258dd7 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -242,6 +242,8 @@ Set the count with carlos apps set shop --copies 2. Each instance of shop gets t |
| If a box is lost or detached, the requested count stays the same. The platform uses a distinct spare when one is available, otherwise the app runs short until a suitable box returns. |
| +[Stateless replicas](/docs/stateless-replicas) covers what an app needs before it runs more than one copy, how deploys switch copies, and what happens when a box stops. |
| + |
| System operators can also set an app's instance policy: which private addresses its instances may reach and the size each instance runs at. `carlos apps show` reads it back. |
| ```sh |
diff --git a/docs/site/nav.json b/docs/site/nav.json| index 2d5b175dc..c1d33967e 100644 |
| --- a/docs/site/nav.json |
| +++ b/docs/site/nav.json |
| @@ -23,6 +23,11 @@ |
| "label": "Rootfs apps", |
| "blurb": "What a rootfs app's image is started with, what it can write, and where it may run." |
| }, |
| + { |
| + "slug": "stateless-replicas", |
| + "label": "Stateless replicas", |
| + "blurb": "Run more than one copy of each instance across your fleet, and what happens when a box stops." |
| + }, |
| { |
| "slug": "pdfs", |
| "label": "PDFs", |
diff --git a/docs/site/stateless-replicas.md b/docs/site/stateless-replicas.md| new file mode 100644 |
| index 000000000..c2a3810c7 |
| --- /dev/null |
| +++ b/docs/site/stateless-replicas.md |
| @@ -0,0 +1,47 @@ |
| +# Stateless replicas |
| + |
| +A stateless app can run more than one copy of each instance, each on a different box of your fleet. If one box stops, the other copies keep serving. |
| + |
| +## Before you set copies |
| + |
| +Ship with --stateless when your app keeps its data outside its box. The release gets no local database, CARLOS_DB or Litestream. You provide and operate its database and other data services. |
| + |
| +More than one copy needs every box of the fleet and the console on platform v0.35.0 or later. Each box's previous platform build must be v0.35.0 or later too, because a failed update puts that build back. Every platform release channel must also be on v0.35.0 or later. |
| + |
| +Each instance needs one successful deploy of its stateless release before it can have more than one copy. Deploy once, then set copies. |
| + |
| +## Setting the count |
| + |
| +```sh |
| +carlos apps set shop --copies 2 |
| +``` |
| + |
| +Each instance of shop gets two copies on different eligible fleet boxes. The command refuses a count larger than the eligible fleet. |
| + |
| +More than one copy needs an always-on release. Set --copies 1 and wait for removed copies to stop before selecting a hibernating release or one with a local database. Switching to stateless leaves the old database and replica untouched. |
| + |
| +## Deploys |
| + |
| +A deploy runs the release command once per instance, then switches its copies one box at a time. Your migrations must allow old and new code to serve together. Each copy runs every declared worker. |
| + |
| +If the box running the release command disappears, its result may be unknown. The deploy stops and the previous build keeps serving. Deploying again runs the command again, so release commands must be safe to repeat. Rails migrations record completed migrations in schema_migrations. |
| + |
| +Deploy your apps one at a time. While a copy switches, its box runs the old and the new build side by side, and the platform does not yet check that a box has room for several apps switching at once. |
| + |
| +An app that runs more than one copy of an instance refuses `carlos restart --app` and `--environment`, because every copy would restart at the same time. Deploy a new build instead: its copies switch one box at a time. |
| + |
| +## When a box stops |
| + |
| +Copies survive the loss of a fleet box. Traffic still enters through one hub, so this version does not survive losing that hub. |
| + |
| +Reads can retry on another copy before a response starts. A response already streaming when its box dies is cut. Websockets disconnect and their clients reconnect to a healthy copy. |
| + |
| +## Seeing your copies |
| + |
| +For an instance with more than one copy, `carlos instances list` prints a second table with one row per copy: its box, build, state, health and workers. The app's overview page counts the copies running out of the copies wanted. The [CLI reference](/docs/cli#carlos-instances) has the details. |
| + |
| +An instance with more than one copy keeps a separate page cache on each copy's box. A purge clears only the cache of the copy that sent it, so another copy can serve its own saved page until it expires or that copy purges it too. |
| + |
| +## What the platform does not prevent |
| + |
| +The console will not move the platform below v0.35.0 while any app has more than one copy. It cannot stop someone with root on a box from installing an older platform build there by hand. A box downgraded that way keeps serving, but its copies may switch builds out of turn, or start again on an older build, until the box is updated again. |
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md| new file mode 100644 |
| index 000000000..5bd9d1e2a |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md |
| @@ -0,0 +1,35 @@ |
| +# Census approval: stateless-replicas-4-task5 |
| + |
| +Ruling `census-ruling-stateless-replicas-4-task5`. The independent reviewer approves or rejects every change below, 1 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/activator/activator.go` `Service.wake` | body | unchanged (16) | Task 5 first commit (#511 F11 log dedupe): before a failed wake's member event, noteHeldWake (in-memory, per host, under the leaf wakeFailMu) tells whether the failure is held by a release attempt with no backoff and is the same (attempt ID, error class) as the host's last one; a repeat writes no event, a first or changed one writes one journal line and the event. Reads only the error in hand; no read site added. | |
| +| `internal/activator/activator.go` `type Service` | body | unchanged (0) | Task 5 first commit (#511 F11): one in-memory field, heldSeen (host to the last held release attempt, error class and when it was met), under the existing wakeFailMu. Declaration only, no read. | |
| +| `internal/activator/stateless.go` `Service.prepareStateless` | body | unchanged (43) | Task 5 first commit (#511 F11): a failed release preparation's error is wrapped with the attempt ID prepareStatelessRelease returned (withAttempt); the text and every errors.Is answer are unchanged. No read, write or authority added. | |
| +| `internal/host/agent.go` `statusLoop` | body | unchanged (6) | Task 5 (#511 R16): the status tick fills Probes.PrevRelease from prevReleaseOf(release.OptDir()): a Stat of carlos.prev and a read of carlos.prev.version, the files the agent already reads for the edges file (withMovesFields). Reported in the private BoxMetrics block so the console counts a box at the stateless replicas floor only when its rollback binary is too. No bucket request or cadence change. | |
| +| `internal/status/snapshot.go` `CollectBox` | body | unchanged (28) | Task 5 (#511 R16): copies Probes.PrevRelease into BoxMetrics.PrevRelease (json prev_release, omitempty; private, like Release) and counts it in the condition that builds Metrics; the same 28 sites, no read added. | |
| +| `internal/activator/rootfs_service.go` `Service.residentJob` | sites | +registry:Host | Task 5 first commit (#511 F11): the "starting it" journal line is written only when heldNow(rt.Host) is false, an in-memory lookup of the host's held note; the added registry:Host site is that host string. No gate, read or start changes. | |
| +| `internal/host/movesfloor.go` `withMovesFields` | sites | -file:Stat | Task 5 (#511 R16): the carlos.prev Stat and version read move into prevReleaseOf, called here with the same opt dir; the same answers (none, unknown, or the version line). -file:Stat here is the same Stat inside prevReleaseOf. | |
| + |
| +Envelopes re-pinned: `internal/activator`, `internal/host`, `internal/status`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Recorded dispositions, which each change must still satisfy: |
| + |
| +- `internal/activator/activator.go` `Service.wake`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=logs that timer's breakdown to the journal after a successful wake (w.steps.String(), e.host, w.wakeTook); no read added;rev3=census-ruling-plans-4d-lapse;basis=cancels a wake whose row the turned-off hook names, like a fence, unless it is a move's active probe (plans 4d). One more whole-row read: the row handed to the hook (a.disabled). Only refuses.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: a refusal before the lease is reported once per change (noteRootfsRefusal) instead of a wake-failure event; the proc, generation and replica are installed through installProcLocked (which puts a resident under its lease watch before the fence); residency notes the outcome (noteResidentWakeLocked); same generation values;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R [pf R3.5]: the wake's context ceiling is wakeCeilingFor(e.route): the old 5 minutes for a binary row, 5 minutes plus runs.MaxTimeout for a rootfs row (room for a release inside the wake); new site +whole:Route (e.route to wakeCeilingFor, which reads Runtime only); no other change;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (branch review R1 P1-1): the wake's context is also cancelled before doWake when RetireExcept has marked the entry retired (e.retired, in memory under a.mu), as it is for a fence or a shutdown. Read sites unchanged (13). Agent, not root; it only refuses more.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry successful hold preparation into its wake, preserve actual mode in the generation and OnWake projection, and project serving version/mode through the narrow registry writer before releasing wake waiters. Final review I1: SetServingMode only for non-worker successful wakes with a nonempty spawned version and either a stateless generation or a mode transition from the route. Ordinary stateful wakes leave rollout status and the wake critical path unchanged.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds a.cancelHeldLegsLocked(e, 0) on the failed-wake path before the entry is deleted, and after close(e.ready) on success calls a.noteHeldAdmissible(e.host), the non-blocking held wake callback, outside a.mu. No read added.;rev3=census-ruling-wake-storm-cap;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): waits for a box-wide wake slot (acquireWakeSlot, an in-memory buffered channel) before doWake; the fence/shutdown/retired/disabled refusals move into refuseWakeLocked and are asked again after admission (one fewer direct whole-Route read here: a.disabled(e.route) now runs inside refuseWakeLocked, same value); e.wakeStart is set at admission and e.admitted marks it. Only waits and refuses more; no new read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Install the successful-acquire observer and restrict due, worker and resident starts before doWake, off a.mu. Add a whole-route argument to restriction; refused work has known-no-start evidence.;rev3=census-ruling-region-ha-g2-fixes;basis=Bind recovery wakes to the service lifetime; no new read.;rev3=census-ruling-edge-page-cache-1;basis=the generation-current call is now noteCurrent(e) instead of noteCurrent(e.host, e.gen.N), so the new noteCurrent can also publish the process's page cache launch inputs; read sites unchanged (16); no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: a failed wake that journalledWakeFailure counts as a real failure is logged through logWakeFailure (rate-limited per host, in memory); a successful wake calls clearWakeFailure. Agent, not root; reads the error already in hand; no read added |
| +- `internal/activator/activator.go` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Add the B2 DutyStore interface field and process-local duty view, suppression and invalidation state. No read added. B2 adds the verified-successor identity callback; no read in the declaration. B3b adds a nonblocking departure-suspicion callback, invoked only after an accepted holder-forward failure and after cache locks release; it cannot authorize a take.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: immutable callbacks installed before Start for tenant admission, local start permission, fixed route exemptions and shutdown closure; nil callbacks preserve switch-off behavior; no new reads. Fix R1: add an immutable startup-phase callback for response copy, set before service startup. No new read or execution authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Add in-memory HA loss state and pool withdrawal jobs; no new read.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 1: one new field, drain (drainSources: two atomic func pointers for this box's and peers' drain state); no read added. region HA held-requests Task 2: one new field, moves (moveTable: per-host move state, hold counts and admission tickets in memory, under mu); no read added;rev3=census-ruling-held-move-speed;basis=the agent as carlos: one new field, moveStreams (per-host in-memory set of edge.StreamEnd for requests in flight, own mutex), for the move's early stream cut; actEntry gains drainRelease (bool, under a.mu), set by DrainStop; declarations only, no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: two fields, wakeFailMu and wakeFailLogged (per-host in-memory note of the last journalled wake failure); declaration only, no read;rev3=census-ruling-w6-ingress-drain;basis=new field TenantStartsClosed func() bool; when it answers true tenantStartRefusal refuses every start, exempt routes included. Wired only by fixedAdmission.bind to the ingress drain's closed flag. Struct field only; no read added.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: one field, replicaPolicies (host to the newest observed replica deploy and this box label, under mu), set only by SetReplicaDeploy; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: one more in-memory field, replicaFailed (host to the permit whose successor failed here, under mu), so that step only proves what it kept; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F fix round 3 (#511 F11): two hook fields, MarkReplicaRelease and ReplicaReleaseMark (the failure book's per-host release mark on this box's disk). No read site. |
| +- `internal/activator/stateless.go` `Service.prepareStateless`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Capture RecordFacts from the existing record source, obtain the durable FailureBook deploy ID, and call Task 2 PrepareStatelessRelease with the canonical verdict/digest carrier. Carry a successful attempt through its hold only after another current-record check; no serving lease or polling loop. Fix 3a round 1 I2: preparation uses reconcile observations and records the successful deploy ID. Carry prepared evidence through hold; fresh backend read must confirm that same released deploy before web runs.;rev3=census-ruling-stateless-failed-release-held;basis=For recovery onto a different installed version's exact committed good version and artifact digest, retain recovery evidence without selecting or writing another deploy. Adds the existing committedGood registry read, with its route and incarnation check. Canonical storage declaration and observed lifetime gates remain.;rev3=census-ruling-stateless-replicas-4-task1;basis=R1: no longer calls ReplicaDeployID before preparation; hands the same a.ReplicaDeployID selector to prepareStatelessRelease, which calls it only after coordinator term acquisition. The ObservedReplicaRelease call stays as a validity check. Same read sites; no new read, write or authority.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2 (D4): for a set row, prepares the record baseline with no release, and refuses a build the row Version does not name before any release; reads the route it is handed (FleetBoxes, Version). No store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: for a set row, a build its pointer does not name starts only as the record baseline or the committed permitted target, the latter adopted through prepareStatelessRelease durable path (never a new attempt); a named build, a rollback included, takes the release path. The added reads are the handed route (FleetBoxes, Version) and a copy of it with Stateless set for the adoption, as the release path already builds. No store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: for a set row the no-release start is decided per box from the record (this box baseline, or its permitted target adopted through the durable path), whatever the pointer says; only a build that is neither and that the pointer names begins a new attempt. Same reads (the handed route and its copy); no store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix3;basis=Task 2 fix round 3: this box baseline is checked before the adopt path, so a completed box restarts on the target while a retry is requested; for the passed target it calls the existing escrow initializer (prepareStatelessEscrow) that the adopt path ran, with the same route and identity. No new reader; no record write.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F (#511 F11): a hold's pinned wake carrying the swap's preparation, when the row it re-read differs from the prepared row, moves the preparation onto the wake's row only if the prepared row passes statelessCurrent against the registry, the two rows have the same Incarnation, ServingSeq, HoldOp and Version (sameRowLifetime, fix round 1), and the wake's row then passes statelessCurrent; otherwise it refuses with errStatelessRowChanged. The added sites are whole-Route comparisons and copies of the handed and prepared routes. No store read or write added; no new authority. |
| +- `internal/host/agent.go` `statusLoop`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's context carries the box's lifetime judge; read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 953b9fda (its later changes, regional box names and self-serve moves plan 1 among them, under main's own census rulings), where the tick fills rootfs_ready and rootfs_blocked from armedRootfs.Load().probe, which each tick runs NestedOK's checks and asks the control socket's GET /ready/rootfs (never the store); the same four direct sites;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: takes root's GET /egress reader and fills p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) and p.SizeCommittedMiB = sizeCommittedMiB(armedSizeSource.Load(), routes); the two added whole:Route sites are the tick's own registry list handed to those two units (decision rows), which read root's control socket and the activator's memory; no store request added; the four existing sites unchanged, offsets moved.;rev3=census-ruling-fleet-alerts-1;basis=the agent (carlos-edge.service, user carlos): the status tick passes os.Geteuid() to alertDeliveryProbe, which fills AlertDelivery.EngineBeat/EngineBeatWhy from engineBeatArmed (the env value and the euid only, no file access, root refused before the path is looked at), and fills Probes.DiskFullETAHours from diskETAProbe(&processDiskTrend, now), a Theil-Sen fit over the metrics loop's in-memory ring of disk readings; the same six sites, no read added, no store request added;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's Probes gain HeldStreams: heldStreamsState(), which calls the edge's in-memory counters function (nil until the edge is ready). No file, bucket or registry access added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: read the detached in-memory replica snapshot source into Probes.ReplicaCopies on the existing five-minute tick. Existing six direct read sites unchanged. No additional bucket request, changed cadence or app lifecycle action.;rev3=census-ruling-agent-start-demo-3;basis=Report moved capability only when the serving edge reports readiness; report claim-seed support only with CARLOS_DEMO_CLAIM=1. Reads the explicit capability flag from the process environment; no new filesystem or registry read. |
| +- `internal/status/snapshot.go` `CollectBox`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;basis=copies Probes.RootfsReady and RootfsBlocked into BoxMetrics (private, like Layout); the same 28 sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: copies Probes.Egress and Probes.SizeCommittedMiB into BoxMetrics (private, like Layout) and counts them in the condition that builds Metrics; the same 28 sites, no read added.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3: comment only, the Hibernate count is left as is (display);rev3=census-ruling-regional-domains-447;basis=#447 Task 7: copies Probes.AliasesRead into BoxMetrics.AliasesRead (json aliases_read, omitempty) and counts it in the condition that builds Metrics; the same 28 sites, no read added;rev3=census-ruling-fleet-alerts-1;basis=copies Probes.DiskFullETAHours into BoxMetrics.DiskFullETAHours (json disk_full_eta_hours, omitempty; private, like Layout) and counts it in the condition that builds Metrics; the same 28 sites, no read added;rev3=census-ruling-edge-held-streams;basis=copies Probes.HeldStreams into BoxMetrics.HeldStreams (json held_streams, omitempty, additive) and counts it in the condition that builds Metrics; the same 28 sites, no read added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: carry already-supplied ReplicaCopies into a separate optional private BoxMetrics replica_copies field; allow copy evidence alone to create the metrics block. Upstreams retains address probes only. Existing 28 Route read sites unchanged; no filesystem, bucket, console or CLI read.;rev3=census-ruling-agent-start-demo-3;basis=Report claim-seed protocol capability only when explicitly configured and runtime moved readiness only when armed; dormant status keeps its original JSON shape. Census read-site delta: unchanged (28). |
| +- `internal/activator/rootfs_service.go` `Service.residentJob`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: one proactive start of a resident: the same pre-lease admission as a request (rootfsStartRefusal, then the locked half under a.mu after re-checking the reservation, shutdown, hold and wait), then an ordinary wake of a resident entry; adds no gate a request does not pass |
| +- `internal/host/movesfloor.go` `withMovesFields`: authority, task F,J4. Basis: rev3=PROPOSED-p3;identity=carlos agent edgesFileLoop, carlos-edge.service uid carlos;basis=agent uses root-owned public projection when participating and its original writable mirror otherwise |
| + |
| +New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff: |
| + |
| +- new `internal/host/movesfloor.go:prevReleaseOf`: reads +file:Stat; written legacy, accepted-legacy, frozen |
| + |
| +Seal: `45b27ac0e2f2152497e3c01f277c2230defaeb3be363170ea61b05d72f0a6782` → `39becc512079522a9ce16be0883e163a818bedf6c42e40708ec4388ba6aed9d3`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md| index 518763a84..32f760fea 100644 |
| --- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md |
| +++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md |
| @@ -94,18 +94,18 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text. |
| | SR-4-C20 | internal/console/replicasize.go | this fleet size needs a complete memory report and a supported platform release on every possible destination. update the boxes and try again | pending | |
| | SR-4-C21 | internal/console/replicasize.go | <size> is available on owned fleet boxes only | pending | |
| | SR-4-C22 | internal/activator/replicadeploy.go | this box has too little free memory for an overlap swap. the current copy keeps serving | pending | |
| -| SR-4-C23 | internal/console/rootfsfloor.go | copies above 1 are in use, so the platform cannot move below <floor>. reduce the copy count and wait for other copies to stop first | pending | |
| -| SR-4-C24 | docs/site/stateless-replicas.md | Copies survive the loss of a fleet box. Traffic still enters through one hub, so this version does not survive losing that hub. | pending | |
| -| SR-4-C25 | docs/site/stateless-replicas.md | A deploy runs the release command once per instance, then switches its copies one box at a time. Your migrations must allow old and new code to serve together. Each copy runs every declared worker. | pending | |
| -| SR-4-C26 | docs/site/stateless-replicas.md | If the coordinator disappears during the release command, its result may be unknown. The deploy stops and the previous build keeps serving. Deploying again runs the command again, so release commands must be safe to repeat. Rails migrations record completed migrations in schema_migrations. | pending (built first as SR-1-C13 in docs/site/cli.md; Plan 4 reuses that text if it needs the sentence elsewhere) | |
| -| SR-4-C27 | docs/site/stateless-replicas.md | Reads can retry on another copy before a response starts. A response already streaming when its box dies is cut. Websockets disconnect and their clients reconnect to a healthy copy. | pending | |
| -| SR-4-C28 | docs/site/stateless-replicas.md | carlos instances list prints one row per copy with its box, build, state, health and workers. carlos run and carlos console choose a healthy copy; add --box <label> to choose one. An accepted command is not repeated on another box after a lost connection. | pending | |
| -| SR-4-C29 | docs/site/stateless-replicas.md | Fleet sizes add 6g, 12g, 24g, 48g, 96g and 192g, measured in GiB. Each copy leaves at least 1 GiB or one eighth of its box's memory for the box, whichever is larger. An overlap also needs room for the new generation. | pending | |
| -| SR-4-C30 | docs/site/stateless-replicas.md | More than one copy needs an always-on release. Set --copies 1 and wait for removed copies to stop before selecting a hibernating release or one with a local database. Switching to stateless leaves the old database and replica untouched. | pending | |
| +| SR-4-C23 | internal/console/replicafloor.go | copies above 1 are in use, so the platform cannot move below <floor>. reduce the copy count and wait for other copies to stop first | pending (built by Plan 4 Task 5 as consoleReplicaFloorRefusal, the publication judge's refusal; planned for rootfsfloor.go; awaiting Paul's copy review) | |
| +| SR-4-C24 | docs/site/stateless-replicas.md | Copies survive the loss of a fleet box. Traffic still enters through one hub, so this version does not survive losing that hub. | pending (built by Plan 4 Task 5 in the docs page; awaiting Paul's copy review) | |
| +| SR-4-C25 | docs/site/stateless-replicas.md | A deploy runs the release command once per instance, then switches its copies one box at a time. Your migrations must allow old and new code to serve together. Each copy runs every declared worker. | pending (built by Plan 4 Task 5 in the docs page; awaiting Paul's copy review) | |
| +| SR-4-C26 | docs/site/stateless-replicas.md | If the coordinator disappears during the release command, its result may be unknown. The deploy stops and the previous build keeps serving. Deploying again runs the command again, so release commands must be safe to repeat. Rails migrations record completed migrations in schema_migrations. | pending (not built: Plan 4 Task 5 reuses the approved SR-1-C13 text in docs/site/stateless-replicas.md, as this row planned) | |
| +| SR-4-C27 | docs/site/stateless-replicas.md | Reads can retry on another copy before a response starts. A response already streaming when its box dies is cut. Websockets disconnect and their clients reconnect to a healthy copy. | pending (built by Plan 4 Task 5 in the docs page; awaiting Paul's copy review) | |
| +| SR-4-C28 | docs/site/stateless-replicas.md | carlos instances list prints one row per copy with its box, build, state, health and workers. carlos run and carlos console choose a healthy copy; add --box <label> to choose one. An accepted command is not repeated on another box after a lost connection. | pending (not built: --box is deferred (R17); the page uses SR-4-C67 instead) | |
| +| SR-4-C29 | docs/site/stateless-replicas.md | Fleet sizes add 6g, 12g, 24g, 48g, 96g and 192g, measured in GiB. Each copy leaves at least 1 GiB or one eighth of its box's memory for the box, whichever is larger. An overlap also needs room for the new generation. | pending (not built: Task 4 (fleet sizes) is deferred (R17); the page says to deploy apps one at a time instead, SR-4-C66) | |
| +| SR-4-C30 | docs/site/stateless-replicas.md | More than one copy needs an always-on release. Set --copies 1 and wait for removed copies to stop before selecting a hibernating release or one with a local database. Switching to stateless leaves the old database and replica untouched. | pending (built by Plan 4 Task 5 in the docs page; awaiting Paul's copy review) | |
| | SR-4-C31 | internal/provision/replicadeploy.go | another deploy is still finishing a copy's switch. wait for it to finish before deploying again | pending | |
| -| SR-4-C32 | scripts/stateless-replicas-drill/main.go | spread: <a_percent>% on <box_a>, <b_percent>% on <box_b>; failed reads before headers: <failures>; cut streams: <cuts>; websocket reconnect: <seconds>s | pending | |
| -| SR-4-C33 | scripts/stateless-replicas-drill/main.go | the dev drill did not pass: <reason>. restore the stopped box and complete cleanup before closing this session | pending | |
| -| SR-4-C34 | docs/site/stateless-replicas.md | Stateless replicas | pending | |
| +| SR-4-C32 | scripts/stateless-replicas-drill/main.go | spread: <a_percent>% on <box_a>, <b_percent>% on <box_b>; failed reads before headers: <failures>; cut streams: <cuts>; websocket reconnect: <seconds>s | pending (built by Plan 4 Task 5 as drillSummary; awaiting Paul's copy review) | |
| +| SR-4-C33 | scripts/stateless-replicas-drill/main.go | the dev drill did not pass: <reason>. restore the stopped box and complete cleanup before closing this session | pending (built by Plan 4 Task 5 as drillFailed; awaiting Paul's copy review) | |
| +| SR-4-C34 | docs/site/stateless-replicas.md | Stateless replicas | pending (built by Plan 4 Task 5 in the docs page (also the nav label in docs/site/nav.json); awaiting Paul's copy review) | |
| | SR-4-C35 | internal/console/replicadeploy.go | release pending | pending | |
| | SR-4-C36 | internal/console/replicadeploy.go | release running | pending | |
| | SR-4-C37 | internal/console/replicadeploy.go | deploy complete | pending | |
| @@ -132,3 +132,19 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text. |
| | SR-4-C58 | internal/activator/stateless.go | the instance's route row no longer matches the one this start was prepared against, so nothing started | pending (added by Plan 4 Task 3F fix round 1: a stateless start whose route row changed after its preparation, which used to read as "maintenance fence active"; fix round 2 narrowed it from "settings changed" to what is known; awaiting Paul's copy review) | |
| | SR-4-C59 | internal/activator/statelessrelease.go | the release command did not start, and its attempt is closed. deploy again to retry it | pending (added by Plan 4 Task 3F fix round 3: an attempt this box moved to releasing and knows it never started, closed as unknown on the record; it used to read as an unknown result; awaiting Paul's copy review) | |
| | SR-4-C60 | internal/activator/statelessrelease.go | this box could not save its release step, so nothing started | pending (added by Plan 4 Task 3F fix round 3: the box's own evidence of a release step could not be saved, so the step was not taken; awaiting Paul's copy review) | |
| +| SR-4-C61 | internal/console/replicafloor.go | every instance needs one successful deploy of a stateless release before it can run more than one copy. deploy once, then set copies | pending (added by Plan 4 Task 5: the copies door's refusal for a record with no last good build (R13), copiesNoBaseline; awaiting Paul's copy review) | |
| +| SR-4-C62 | internal/console/replicafloor.go | this deployment's <channel> channel is on <release>, below <floor>. copies above 1 wait until every channel is on <floor> or later. try again after the deployment's next update | pending (added by Plan 4 Task 5: the copies door's refusal while a published system pointer is below the floor (R4), copiesChannelBelow; modelled on FPR-C06; awaiting Paul's copy review) | |
| +| SR-4-C63 | docs/site/stateless-replicas.md | A stateless app can run more than one copy of each instance, each on a different box of your fleet. If one box stops, the other copies keep serving. | pending (added by Plan 4 Task 5: the page's opening; awaiting Paul's copy review) | |
| +| SR-4-C64 | docs/site/stateless-replicas.md | More than one copy needs every box of the fleet and the console on platform v0.35.0 or later. Each box's previous platform build must be v0.35.0 or later too, because a failed update puts that build back. Every platform release channel must also be on v0.35.0 or later. | pending (added by Plan 4 Task 5: the floor, with R16's previous-build rule and R4's published channels; awaiting Paul's copy review) | |
| +| SR-4-C65 | docs/site/stateless-replicas.md | Each instance needs one successful deploy of its stateless release before it can have more than one copy. Deploy once, then set copies. | pending (added by Plan 4 Task 5: R13 for the docs page; awaiting Paul's copy review) | |
| +| SR-4-C66 | docs/site/stateless-replicas.md | Deploy your apps one at a time. While a copy switches, its box runs the old and the new build side by side, and the platform does not yet check that a box has room for several apps switching at once. | pending (added by Plan 4 Task 5: R17: deploy apps one at a time; awaiting Paul's copy review) | |
| +| SR-4-C67 | docs/site/stateless-replicas.md | For an instance with more than one copy, `carlos instances list` prints a second table with one row per copy: its box, build, state, health and workers. The app's overview page counts the copies running out of the copies wanted. The [CLI reference](/docs/cli#carlos-instances) has the details. | pending (added by Plan 4 Task 5: SR-4-C51's first and last sentences with a link to the CLI reference; the page also reuses SR-4-C52 and SR-4-C53 verbatim; awaiting Paul's copy review) | |
| +| SR-4-C68 | docs/site/stateless-replicas.md | The console will not move the platform below v0.35.0 while any app has more than one copy. It cannot stop someone with root on a box from installing an older platform build there by hand. A box downgraded that way keeps serving, but its copies may switch builds out of turn, or start again on an older build, until the box is updated again. | pending (added by Plan 4 Task 5: R16: a manual root downgrade is not prevented; awaiting Paul's copy review) | |
| +| SR-4-C69 | docs/site/cli.md | [Stateless replicas](/docs/stateless-replicas) covers what an app needs before it runs more than one copy, how deploys switch copies, and what happens when a box stops. | pending (added by Plan 4 Task 5: the CLI reference's cross-link under carlos apps set --copies; awaiting Paul's copy review) | |
| +| SR-4-C70 | docs/site/nav.json | Run more than one copy of each instance across your fleet, and what happens when a box stops. | pending (added by Plan 4 Task 5: the page's blurb in the Guides section; awaiting Paul's copy review) | |
| +| SR-4-C71 | docs/site/stateless-replicas.md | Before you set copies | pending (added by Plan 4 Task 5: heading; awaiting Paul's copy review) | |
| +| SR-4-C72 | docs/site/stateless-replicas.md | Setting the count | pending (added by Plan 4 Task 5: heading; awaiting Paul's copy review) | |
| +| SR-4-C73 | docs/site/stateless-replicas.md | Deploys | pending (added by Plan 4 Task 5: heading; awaiting Paul's copy review) | |
| +| SR-4-C74 | docs/site/stateless-replicas.md | When a box stops | pending (added by Plan 4 Task 5: heading; awaiting Paul's copy review) | |
| +| SR-4-C75 | docs/site/stateless-replicas.md | Seeing your copies | pending (added by Plan 4 Task 5: heading; awaiting Paul's copy review) | |
| +| SR-4-C76 | docs/site/stateless-replicas.md | What the platform does not prevent | pending (added by Plan 4 Task 5: heading; awaiting Paul's copy review) | |
diff --git a/internal/console/apisystemupdate.go b/internal/console/apisystemupdate.go| index feaa74940..1a2c0b5eb 100644 |
| --- a/internal/console/apisystemupdate.go |
| +++ b/internal/console/apisystemupdate.go |
| @@ -432,12 +432,12 @@ func (s *Server) handleAPISystemUpdate(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| } |
| - // The rootfs, regional and fleet forward floors, the same way, for a |
| - // named release: the job asks again before it reserves or writes |
| + // The rootfs, regional, fleet forward and stateless replicas floors, |
| + // the same way, for a named release: the job asks again before it reserves or writes |
| // (promoteHostUpdate), which also covers the latest release and an |
| // upload. |
| if in.Version != "" { |
| - if _, err := s.systemFloorGate(r.Context(), in.Component, in.Channel, in.Version, in.AllowBelowRootfsFloor, in.AllowBelowRegionalFloor, in.AllowBelowFleetForwardFloor); errors.Is(err, errRootfsFloorPromotion) || errors.Is(err, errRegionalFloorPromotion) || errors.Is(err, errFleetFloorPromotion) { |
| + if _, err := s.systemFloorGate(r.Context(), in.Component, in.Channel, in.Version, in.AllowBelowRootfsFloor, in.AllowBelowRegionalFloor, in.AllowBelowFleetForwardFloor); errors.Is(err, errRootfsFloorPromotion) || errors.Is(err, errRegionalFloorPromotion) || errors.Is(err, errFleetFloorPromotion) || errors.Is(err, errReplicaFloorPromotion) { |
| jsonError(w, http.StatusConflict, err.Error()) |
| return |
| } |
| @@ -972,7 +972,7 @@ func (s *Server) handleAPISystemRollback(w http.ResponseWriter, r *http.Request) |
| p, err := s.rollbackHostUpdate(r.Context(), in.Component, in.Channel, addr, in.AllowBelowRootfsFloor, in.AllowBelowRegionalFloor, in.AllowBelowFleetForwardFloor) |
| var held activationHeldError |
| switch { |
| - case errors.Is(err, errRootfsFloorPromotion), errors.Is(err, errRegionalFloorPromotion), errors.Is(err, errFleetFloorPromotion): |
| + case errors.Is(err, errRootfsFloorPromotion), errors.Is(err, errRegionalFloorPromotion), errors.Is(err, errFleetFloorPromotion), errors.Is(err, errReplicaFloorPromotion): |
| jsonError(w, http.StatusConflict, err.Error()) |
| return |
| case errors.Is(err, release.ErrCASConflict): |
diff --git a/internal/console/appcopies.go b/internal/console/appcopies.go| index 874f839e7..192e72ebc 100644 |
| --- a/internal/console/appcopies.go |
| +++ b/internal/console/appcopies.go |
| @@ -34,12 +34,16 @@ func atReplicaFloor(build string) bool { |
| return ok && valid && v.Compare(floor) >= 0 |
| } |
| +// replicasActive is count admission's floor: the console and every box of |
| +// a fleet read whole at StatelessReplicasFloor, each box fresh and with |
| +// its rollback binary at the floor too, or none (PrevAtReplicaFloor; R16: |
| +// a failed apply restores carlos.prev). |
| func (v *fleetView) replicasActive(consoleRelease string) bool { |
| if v == nil || !v.Complete || !atReplicaFloor(consoleRelease) { |
| return false |
| } |
| for _, b := range v.Boxes { |
| - if !b.Fresh || !b.AtReplicaFloor { |
| + if !b.Fresh || !b.AtReplicaFloor || !b.PrevAtReplicaFloor { |
| return false |
| } |
| } |
| @@ -92,7 +96,20 @@ func (s *Server) handleAPICopies(w http.ResponseWriter, r *http.Request) { |
| var ref *doorRefusal |
| var got int |
| err := s.claimAppMutation(ctx, acct, app, "copies", func(ctx context.Context) error { |
| + if *req.Copies > 1 { |
| + // The stateless replicas floor (replicafloor.go): from the |
| + // barrier through the config write under replicaFloorMu, so a |
| + // system publication below the floor and these copies cannot |
| + // both pass. |
| + defer s.lockReplicaFloor()() |
| + } |
| ref = s.copiesRefusal(ctx, acct, app, *req.Copies, nil) |
| + if ref == nil && *req.Copies > 1 { |
| + ref = s.replicaPolicyBarrier(ctx) |
| + } |
| + if ref == nil && *req.Copies > 1 { |
| + ref = s.copiesBaselineRefusal(ctx, acct, app) |
| + } |
| if ref != nil { |
| return &statelessSelectionError{ref} |
| } |
diff --git a/internal/console/appcopies_test.go b/internal/console/appcopies_test.go| index 1738f35be..d37c3c148 100644 |
| --- a/internal/console/appcopies_test.go |
| +++ b/internal/console/appcopies_test.go |
| @@ -11,6 +11,7 @@ import ( |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| "github.com/carlosframework/platform/internal/seeds" |
| "github.com/carlosframework/platform/internal/status" |
| ) |
| @@ -26,6 +27,7 @@ func copiesWorld(t *testing.T) (*consoleFixture, string) { |
| r.Hibernate = new(bool) |
| r.FleetBox = []string{"pi-1", "pi-2"}[i] |
| }) |
| + copiesBaseline(t, fx, host, []string{"v1", "v2"}[i]) |
| } |
| shipStatelessFloorRelease(t, fx, "shop", "v1") |
| shipStatelessFloorRelease(t, fx, "shop", "v2") |
| @@ -40,6 +42,20 @@ func copiesWorld(t *testing.T) (*consoleFixture, string) { |
| } |
| return fx, token |
| } |
| + |
| +// copiesBaseline gives host's record a legacy released deploy of ver: |
| +// the instance's last good build (R13), so copies above 1 may be set. |
| +func copiesBaseline(t *testing.T, fx *consoleFixture, host, ver string) { |
| + t.Helper() |
| + placementEdit(t, fx, host, func(r *provision.Record) { |
| + inc, err := provision.Incarnation(r.Account, r.App, r.Host, r.CreatedAt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.ReplicaDeploy = &replicas.Deploy{ID: "deploy-" + host, Incarnation: inc, Target: replicas.Build{Version: ver, Digest: "canonical"}, Phase: "released", Revision: 1} |
| + }) |
| +} |
| + |
| func copiesManifest(t *testing.T, fx *consoleFixture, stateless, hibernate bool, swap string) { |
| t.Helper() |
| ctx := context.Background() |
| @@ -73,6 +89,13 @@ func copiesManifest(t *testing.T, fx *consoleFixture, stateless, hibernate bool, |
| } |
| } |
| func copiesBeat(t *testing.T, fx *consoleFixture, box, rel string, at time.Time) { |
| + t.Helper() |
| + writeCopiesBeat(t, fx, box, rel, "none", at) |
| +} |
| + |
| +// writeCopiesBeat is box's heartbeat at release rel with its rollback |
| +// binary (carlos.prev) at prev: "none" when it has none, "" unknown. |
| +func writeCopiesBeat(t *testing.T, fx *consoleFixture, box, rel, prev string, at time.Time) { |
| t.Helper() |
| hosts := map[string]status.HostRollout{} |
| host := "a.example.com" |
| @@ -84,7 +107,7 @@ func copiesBeat(t *testing.T, fx *consoleFixture, box, rel string, at time.Time) |
| ver = "v2" |
| } |
| hosts[host] = status.HostRollout{Account: fx.sqid, App: "shop", Serving: ver, Installed: ver, Awake: true} |
| - b := status.Box{Label: box, GeneratedAt: at, Metrics: &status.BoxMetrics{Release: rel, RootfsReady: true, Rollout: &status.RolloutReport{Hosts: hosts}}} |
| + b := status.Box{Label: box, GeneratedAt: at, Metrics: &status.BoxMetrics{Release: rel, PrevRelease: prev, RootfsReady: true, Rollout: &status.RolloutReport{Hosts: hosts}}} |
| if err := status.WriteBox(context.Background(), release.NewPrefixStore(fx.rel, "fleets/pi/"), b); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/copiespublication_test.go b/internal/console/copiespublication_test.go| index b610a1c1e..70f1d3a0c 100644 |
| --- a/internal/console/copiespublication_test.go |
| +++ b/internal/console/copiespublication_test.go |
| @@ -494,6 +494,7 @@ func TestCopiesAdmissionSerializesShip(t *testing.T) { |
| r.Hibernate = new(bool) |
| r.FleetBox = []string{"pi-1", "pi-2"}[i] |
| }) |
| + copiesBaseline(t, fx, host, ver) |
| m := release.Manifest{Schema: 1, App: "shop", Version: ver, Kind: release.KindRootfs, Stateless: true, Processes: map[string]release.Process{"web": {Command: []string{"bin/web"}}}, Artifacts: map[string]release.Artifact{release.RootfsArtifactKey: {File: release.RootfsArtifactFile}}} |
| if err := release.Ship(context.Background(), fx.rel, fx.sqid, m, map[string][]byte{release.RootfsArtifactKey: []byte("rootfs image")}); err != nil { |
| t.Fatal(err) |
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go| index 6bc30ced3..c07919ad7 100644 |
| --- a/internal/console/fleetbox.go |
| +++ b/internal/console/fleetbox.go |
| @@ -74,6 +74,9 @@ type fleetBoxView struct { |
| Labelled bool |
| LastSeen, DrainingSince time.Time |
| Release string |
| + // PrevAtReplicaFloor: the heartbeat's prev_release (carlos.prev) is |
| + // at StatelessReplicasFloor, or "none" (#511 R16). Unknown is not. |
| + PrevAtReplicaFloor bool |
| } |
| // fleetBoxViewOf is an active registry box before its heartbeat is read. |
| @@ -109,6 +112,7 @@ func joinBeats(boxes []fleetBoxView, hbs []status.Box, now time.Time) (unheard b |
| boxes[i].TotalMiB = *b.Metrics.MemTotalBytes >> 20 |
| } |
| boxes[i].AtReplicaFloor = atReplicaFloor(b.Metrics.Release) |
| + boxes[i].PrevAtReplicaFloor = b.Metrics.PrevRelease == "none" || atReplicaFloor(b.Metrics.PrevRelease) |
| } |
| } |
| return unheard |
diff --git a/internal/console/fleetfloor_test.go b/internal/console/fleetfloor_test.go| index 4d154ffae..ed2c1fd53 100644 |
| --- a/internal/console/fleetfloor_test.go |
| +++ b/internal/console/fleetfloor_test.go |
| @@ -529,12 +529,14 @@ func TestFleetFloorListErrorRefuses(t *testing.T) { |
| if v := currentVersion(t, s, d); v != "v0.32.0" { |
| t.Fatalf("the pointer moved to %s", v) |
| } |
| - // Moves that pass on the version alone read no fleets. |
| - if _, err := s.systemFloorGate(t.Context(), "router", "canary", "v0.32.0", false, false, false); err != nil { |
| + // Moves that pass on the version alone read no fleets. Below the |
| + // stateless replicas floor that judge lists them too (replicafloor.go), |
| + // so these targets are at or above both floors. |
| + if _, err := s.systemFloorGate(t.Context(), "router", "canary", release.StatelessReplicasFloor, false, false, false); err != nil { |
| t.Fatalf("a first publication at the floor = %v", err) |
| } |
| unreserved(t, d) |
| - if p, err := s.promoteHostUpdate(t.Context(), fpRelease(target, "v0.33.0"), "router", "stable", release.SystemPromoteOptions{}); err != nil || p.Current.Version != "v0.33.0" { |
| + if p, err := s.promoteHostUpdate(t.Context(), fpRelease(target, "v0.35.1"), "router", "stable", release.SystemPromoteOptions{}); err != nil || p.Current.Version != "v0.35.1" { |
| t.Fatalf("a promotion above the floor = %+v, %v", p, err) |
| } |
| } |
diff --git a/internal/console/hostactivation.go b/internal/console/hostactivation.go| index 74be50d30..3fcb1858f 100644 |
| --- a/internal/console/hostactivation.go |
| +++ b/internal/console/hostactivation.go |
| @@ -225,11 +225,13 @@ func (s *Server) promoteHostUpdate(ctx context.Context, rel release.SystemReleas |
| // judges it too, the regional floor does not. |
| d := hostactors.Directory{Store: s.cfg.Releases, PublicKey: release.RootSigner(s.cfg.Key).RootPublicKey(), Bucket: s.cfg.Bucket} |
| return s.fleetFloorPublish(ctx, channel, judgedPointer(cur), rel.Version, options.AllowBelowFleetForwardFloor, func() (*release.SystemPointer, error) { |
| - return s.regionalFloorPublish(ctx, channel, judgedPointer(cur), rel.Version, options.AllowBelowRegionalFloor, func() (*release.SystemPointer, error) { |
| - if id == "" { |
| - return release.PromoteSystem(ctx, s.cfg.Releases, release.RootSigner(s.cfg.Key), component, channel, rel, options, etag) |
| - } |
| - return d.PublishActivation(ctx, id) |
| + return s.replicaFloorPublish(ctx, channel, judgedPointer(cur), rel.Version, func() (*release.SystemPointer, error) { |
| + return s.regionalFloorPublish(ctx, channel, judgedPointer(cur), rel.Version, options.AllowBelowRegionalFloor, func() (*release.SystemPointer, error) { |
| + if id == "" { |
| + return release.PromoteSystem(ctx, s.cfg.Releases, release.RootSigner(s.cfg.Key), component, channel, rel, options, etag) |
| + } |
| + return d.PublishActivation(ctx, id) |
| + }) |
| }) |
| }) |
| } |
| @@ -273,6 +275,8 @@ func (s *Server) rollbackHostUpdate(ctx context.Context, component, channel, act |
| // reason as the regional one (a fleet may have been created |
| // since), first, under fleetFloorMu; both judge the one read, |
| // since the CAS binds the publication to the pointer anyway. |
| + // So does the stateless replicas floor, under replicaFloorMu |
| + // between the two (copies may have been set since). |
| var standingRead bool |
| var standingPointer *release.SystemPointer |
| var standingErr error |
| @@ -287,8 +291,10 @@ func (s *Server) rollbackHostUpdate(ctx context.Context, component, channel, act |
| return standingPointer, standingErr |
| } |
| return s.fleetFloorPublish(ctx, channel, standing, held.Current.Version, allowBelowFleetForwardFloor, func() (*release.SystemPointer, error) { |
| - return s.regionalFloorPublish(ctx, channel, standing, held.Current.Version, allowBelowRegionalFloor, func() (*release.SystemPointer, error) { |
| - return d.PublishActivation(ctx, id) |
| + return s.replicaFloorPublish(ctx, channel, standing, held.Current.Version, func() (*release.SystemPointer, error) { |
| + return s.regionalFloorPublish(ctx, channel, standing, held.Current.Version, allowBelowRegionalFloor, func() (*release.SystemPointer, error) { |
| + return d.PublishActivation(ctx, id) |
| + }) |
| }) |
| }) |
| } |
| @@ -315,6 +321,9 @@ func (s *Server) rollbackHostUpdate(ctx context.Context, component, channel, act |
| if err := s.fleetForwardFloorJudge(ctx, channel, current, target.Version, allowBelowFleetForwardFloor); err != nil { |
| return nil, err |
| } |
| + if err := s.replicaFloorJudge(ctx, channel, current, target.Version); err != nil { |
| + return nil, err |
| + } |
| options := release.SystemPromoteOptions{Actor: actor, AllowBelowRootfsFloor: allowBelowRootfsFloor, AllowBelowRegionalFloor: allowBelowRegionalFloor, |
| AllowBelowFleetForwardFloor: allowBelowFleetForwardFloor} |
| id, err := s.reserveHostUpdate(ctx, &target, channel, "rollback", options, etag) |
| @@ -322,11 +331,13 @@ func (s *Server) rollbackHostUpdate(ctx context.Context, component, channel, act |
| return nil, err |
| } |
| return s.fleetFloorPublish(ctx, channel, judgedPointer(current), target.Version, allowBelowFleetForwardFloor, func() (*release.SystemPointer, error) { |
| - return s.regionalFloorPublish(ctx, channel, judgedPointer(current), target.Version, allowBelowRegionalFloor, func() (*release.SystemPointer, error) { |
| - if id == "" { |
| - return release.RollbackSystem(ctx, s.cfg.Releases, release.RootSigner(s.cfg.Key), component, channel, options, etag) |
| - } |
| - return d.PublishActivation(ctx, id) |
| + return s.replicaFloorPublish(ctx, channel, judgedPointer(current), target.Version, func() (*release.SystemPointer, error) { |
| + return s.regionalFloorPublish(ctx, channel, judgedPointer(current), target.Version, allowBelowRegionalFloor, func() (*release.SystemPointer, error) { |
| + if id == "" { |
| + return release.RollbackSystem(ctx, s.cfg.Releases, release.RootSigner(s.cfg.Key), component, channel, options, etag) |
| + } |
| + return d.PublishActivation(ctx, id) |
| + }) |
| }) |
| }) |
| } |
diff --git a/internal/console/replicafloor.go b/internal/console/replicafloor.go| new file mode 100644 |
| index 000000000..70590ebd9 |
| --- /dev/null |
| +++ b/internal/console/replicafloor.go |
| @@ -0,0 +1,254 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "os" |
| + "sort" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +// The stateless replicas floor at the console (#511 Plan 4 Task 5; rulings |
| +// D9, R4, R11, R16, R17). A box below release.StatelessReplicasFloor |
| +// cannot coordinate copies, so two doors are kept apart: |
| +// |
| +// - every system pointer publication (update, promote, rollback) is |
| +// refused a target below the floor while any app has copies above 1, |
| +// or any of its instances still has more than one assigned box or a |
| +// retiring one (replicaFloorJudge). There is no override flag; |
| +// - the copies door (handleAPICopies) refuses copies above 1 while any |
| +// published system channel pointer names a release below the floor |
| +// (replicaPolicyBarrier), on top of its console build and heartbeat |
| +// checks (copiesRefusal, replicasActive). |
| +// |
| +// The judge runs on the one pointer read the other floors judge |
| +// (systemFloorSnapshot) and again under s.replicaFloorMu with the pointer |
| +// write (replicaFloorPublish). The copies door holds the same mutex from |
| +// its barrier through its config write. So either the publication lands |
| +// first and the barrier reads it, or the copies are written first and the |
| +// binding judgment sees them. Lock order: fleetFloorMu, then |
| +// replicaFloorMu, then regionalMu; the copies door takes replicaFloorMu |
| +// after its app lock and takes neither of the others. |
| +// |
| +// The box itself has no backstop (R16): a manual root downgrade on a box |
| +// with copies is not prevented, and the docs say so. |
| + |
| +// consoleReplicaFloorRefusal (SR-4-C23, provisional) takes the floor. |
| +const consoleReplicaFloorRefusal = "copies above 1 are in use, so the platform cannot move below %s. reduce the copy count and wait for other copies to stop first" |
| + |
| +// copiesChannelBelow (SR-4-C62, provisional) takes the channel, its |
| +// release, the floor and the floor. |
| +const copiesChannelBelow = "this deployment's %s channel is on %s, below %s. copies above 1 wait until every channel is on %s or later. try again after the deployment's next update" |
| + |
| +// copiesNoBaseline (SR-4-C61, provisional; R13). |
| +const copiesNoBaseline = "every instance needs one successful deploy of a stateless release before it can run more than one copy. deploy once, then set copies" |
| + |
| +// errReplicaFloorPromotion is a promotion the replicas floor refused. |
| +var errReplicaFloorPromotion = errors.New("stateless replicas floor") |
| + |
| +type replicaFloorError struct{ msg string } |
| + |
| +func (e replicaFloorError) Error() string { return e.msg } |
| +func (e replicaFloorError) Unwrap() error { return errReplicaFloorPromotion } |
| + |
| +// replicaFloorHooks are test seams: beforeLock runs in replicaFloorPublish |
| +// after every earlier judgment and before replicaFloorMu is taken; locked |
| +// runs under it after the judgment and before the publication; |
| +// copiesBeforeLock runs in the copies door just before it takes the mutex. |
| +type replicaFloorHooks struct { |
| + beforeLock, locked, copiesBeforeLock func() |
| +} |
| + |
| +// replicaFloorJudge refuses moving channel from cur (nil: a first |
| +// publication) to target, a release below StatelessReplicasFloor or one |
| +// that does not parse, while copies are in use anywhere |
| +// (replicasInUse). A target at or above the floor, and a pointer that |
| +// already names target (nothing moves), pass without reading anything. |
| +// Copies live only on fleets, so a console with no fleet passes too. |
| +// Anything that cannot be read refuses: the console cannot tell whether |
| +// the move strands a copy. |
| +func (s *Server) replicaFloorJudge(ctx context.Context, channel string, cur *release.SystemPointer, target string) error { |
| + if atReplicaFloor(target) || (cur != nil && cur.Current.Version == target) { |
| + return nil |
| + } |
| + _, fleets, err := s.systemFleets() |
| + if err != nil { |
| + return fmt.Errorf("stateless replicas floor: cannot list fleets: %w", err) |
| + } |
| + if len(fleets) == 0 { |
| + return nil |
| + } |
| + inUse, err := s.replicasInUse(ctx) |
| + if err != nil { |
| + return fmt.Errorf("stateless replicas floor: cannot read the copy inventory: %w", err) |
| + } |
| + if !inUse { |
| + return nil |
| + } |
| + return replicaFloorError{msg: fmt.Sprintf(consoleReplicaFloorRefusal, release.StatelessReplicasFloor)} |
| +} |
| + |
| +// replicasInUse reports whether any app has copies above 1, or any of its |
| +// live instances has more than one assigned box or a retiring one. The |
| +// apps are those the copies door marked (markReplicaApp, written before |
| +// the copies config and kept until no instance has an assignment), each |
| +// read whole: its copies config and its records, strictly. A console with |
| +// no app store has no apps. |
| +func (s *Server) replicasInUse(ctx context.Context) (bool, error) { |
| + if s.store == nil { |
| + return false, nil |
| + } |
| + apps, err := s.store.replicaAppsAll(ctx) |
| + if err != nil { |
| + return false, err |
| + } |
| + for _, app := range apps { |
| + cfg, err := s.copiesDefault(ctx, app.Sqid, app.App) |
| + if err != nil { |
| + return false, err |
| + } |
| + if appconfig.CopiesOf(&cfg.manifest) > 1 { |
| + return true, nil |
| + } |
| + recs, err := placeRecords(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), app.Sqid, app.App) |
| + if err != nil { |
| + return false, err |
| + } |
| + for _, rec := range recs { |
| + if a := rec.ReplicaAssignment; !rec.Retired && a != nil && (a.Desired > 1 || len(a.Boxes) > 1 || len(a.Retiring) > 0) { |
| + return true, nil |
| + } |
| + } |
| + } |
| + return false, nil |
| +} |
| + |
| +// replicaAppsAll is every live app the copies door marked, on any fleet. |
| +func (st *Store) replicaAppsAll(ctx context.Context) ([]AppRef, error) { |
| + rows, err := st.db.QueryContext(ctx, `SELECT a.sqid,p.app FROM apps p JOIN accounts a ON a.id=p.account_id WHERE p.deleted_at=0 AND (p.copies_configured=1 OR p.copies_dirty=1) ORDER BY a.sqid,p.app`) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + var apps []AppRef |
| + for rows.Next() { |
| + var app AppRef |
| + if err := rows.Scan(&app.Sqid, &app.App); err != nil { |
| + return nil, err |
| + } |
| + apps = append(apps, app) |
| + } |
| + return apps, rows.Err() |
| +} |
| + |
| +// replicaFloorPublish runs publish, the conditional write of channel's |
| +// pointer, under s.replicaFloorMu, after judging the replicas floor again |
| +// on the pointer current returns (nil for none) moving to target. The |
| +// earlier judgment (systemFloorSnapshot) refuses early; this one binds. |
| +// Callers nest it inside fleetFloorPublish and pass their |
| +// regionalFloorPublish call as publish, so the lock order is fleet, |
| +// replica, regional. |
| +func (s *Server) replicaFloorPublish(ctx context.Context, channel string, current func() (*release.SystemPointer, error), target string, publish func() (*release.SystemPointer, error)) (*release.SystemPointer, error) { |
| + if hook := s.replicaFloorHooks.beforeLock; hook != nil { |
| + hook() |
| + } |
| + s.replicaFloorMu.Lock() |
| + defer s.replicaFloorMu.Unlock() |
| + cur, err := current() |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err := s.replicaFloorJudge(ctx, channel, cur, target); err != nil { |
| + return nil, err |
| + } |
| + if hook := s.replicaFloorHooks.locked; hook != nil { |
| + hook() |
| + } |
| + return publish() |
| +} |
| + |
| +// lockReplicaFloor takes replicaFloorMu for the copies door, after its |
| +// app lock, and returns its release. |
| +func (s *Server) lockReplicaFloor() func() { |
| + if hook := s.replicaFloorHooks.copiesBeforeLock; hook != nil { |
| + hook() |
| + } |
| + s.replicaFloorMu.Lock() |
| + return s.replicaFloorMu.Unlock |
| +} |
| + |
| +// replicaPolicyBarrier is the copies door's read of the published system |
| +// pointers, under replicaFloorMu (R4, R11): one listing of the router's |
| +// channel pointers and one GET per channel, as the fleet-create barrier |
| +// reads them (fleetCreateFloorRefusal). A pointer naming a release below |
| +// StatelessReplicasFloor, or one that does not parse, is a 409 naming the |
| +// first such channel in key order; no override passes it. A listing that |
| +// fails, or a pointer that cannot be read or verified, is a 503. A pointer |
| +// deleted between the listing and its GET, and no pointer at all, pass: |
| +// any later publication is judged under the same mutex with these copies |
| +// visible. |
| +func (s *Server) replicaPolicyBarrier(ctx context.Context) *doorRefusal { |
| + unread := &doorRefusal{Status: http.StatusServiceUnavailable, Msg: copiesUnread} |
| + prefix, _ := strings.CutSuffix(release.SystemPointerKey(release.SystemComponentRouter, ""), ".json") |
| + keys, err := s.cfg.Releases.List(ctx, prefix) |
| + if err != nil { |
| + log.Printf("console: copies barrier: list %s: %v", prefix, err) |
| + return unread |
| + } |
| + var channels []string |
| + for _, key := range keys { |
| + if ch, ok := systemChannelOf(prefix, key); ok { |
| + channels = append(channels, ch) |
| + } |
| + } |
| + sort.Strings(channels) |
| + for _, ch := range channels { |
| + p, _, err := release.GetSystemPointer(ctx, s.cfg.Releases, s.cfg.ReleasePub, release.SystemComponentRouter, ch) |
| + if errors.Is(err, os.ErrNotExist) { |
| + continue |
| + } |
| + if err != nil { |
| + log.Printf("console: copies barrier: system pointer %s: %v", ch, err) |
| + return unread |
| + } |
| + if !atReplicaFloor(p.Current.Version) { |
| + floor := release.StatelessReplicasFloor |
| + return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf(copiesChannelBelow, ch, p.Current.Version, floor, floor)} |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// copiesBaselineRefusal is R13: copies above 1 need every live instance |
| +// of the app to hold a durable last good build (replicas.CarryLastGood, |
| +// which reads a legacy released record as its own target), so a record |
| +// whose history is only a failed or unknown release deploys once first. |
| +// An unreadable record or lifetime refuses as unread. |
| +func (s *Server) copiesBaselineRefusal(ctx context.Context, acct *Account, app string) *doorRefusal { |
| + recs, err := placeRecords(ctx, s.cfg.Releases, provision.JudgeFrom(ctx), acct.Sqid, app) |
| + if err != nil { |
| + return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: copiesUnread} |
| + } |
| + for _, rec := range recs { |
| + if rec.Retired { |
| + continue |
| + } |
| + entry, err := provision.LifetimeEntryOf(rec) |
| + if err != nil { |
| + return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: copiesUnread} |
| + } |
| + if replicas.CarryLastGood(rec.ReplicaDeploy, entry.ID) != (replicas.Build{}) { |
| + continue |
| + } |
| + return &doorRefusal{Status: http.StatusConflict, Msg: copiesNoBaseline} |
| + } |
| + return nil |
| +} |
diff --git a/internal/console/replicafloor_test.go b/internal/console/replicafloor_test.go| new file mode 100644 |
| index 000000000..0d83a8a99 |
| --- /dev/null |
| +++ b/internal/console/replicafloor_test.go |
| @@ -0,0 +1,393 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/appconfig" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| +) |
| + |
| +// The stateless replicas floor (#511 Plan 4 Task 5; D9, R4, R11, R13, |
| +// R16). copiesWorld is a two-box fleet whose boxes and console are at the |
| +// floor, with no rollback binary, and whose instances each hold a legacy |
| +// released deploy; no system pointer is published unless a test says so. |
| + |
| +const replicaBelow = "v0.34.46" |
| + |
| +// rfWorld is copiesWorld with the console holding the system signing key, |
| +// so a test can publish system pointers through the real doors. |
| +func rfWorld(t *testing.T) (*consoleFixture, string) { |
| + t.Helper() |
| + fx, token := copiesWorld(t) |
| + fx.srv.cfg.Key = fx.priv |
| + return fx, token |
| +} |
| + |
| +// rfBeat rewrites box's heartbeat at the floor with its rollback binary at |
| +// prev ("" unknown, "none" no carlos.prev). |
| +func rfBeat(t *testing.T, fx *consoleFixture, box, prev string) { |
| + t.Helper() |
| + copiesBeatPrev(t, fx, box, release.StatelessReplicasFloor, prev, time.Now()) |
| +} |
| + |
| +// rfCopies is the app's configured copy count. |
| +func rfCopies(t *testing.T, fx *consoleFixture) int { |
| + t.Helper() |
| + m, err := appconfig.Get(context.Background(), fx.rel, fx.sqid, "shop") |
| + if err != nil { |
| + return 1 |
| + } |
| + return appconfig.CopiesOf(m) |
| +} |
| + |
| +// rfPublish publishes system release v on channel straight to the bucket. |
| +func rfPublish(t *testing.T, fx *consoleFixture, channel, v string) { |
| + t.Helper() |
| + if _, err := release.PromoteSystem(t.Context(), fx.rel, release.RootSigner(fx.priv), "router", channel, fcRelease(v), release.SystemPromoteOptions{}); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// rfPointer is channel's current release ("" when it has none). |
| +func rfPointer(t *testing.T, fx *consoleFixture, channel string) string { |
| + t.Helper() |
| + p, _, err := release.GetSystemPointer(t.Context(), fx.rel, fx.pub, "router", channel) |
| + if err != nil { |
| + return "" |
| + } |
| + return p.Current.Version |
| +} |
| + |
| +// rfRecord rewrites host's record with mut applied (placementEdit). |
| +func rfRecord(t *testing.T, fx *consoleFixture, host string, mut func(*provision.Record)) { |
| + t.Helper() |
| + placementEdit(t, fx, host, mut) |
| +} |
| + |
| +// rfFloorWant is SR-4-C23. |
| +func rfFloorWant() string { |
| + return fmt.Sprintf(consoleReplicaFloorRefusal, release.StatelessReplicasFloor) |
| +} |
| + |
| +// TestReplicaFloorEnablesOnlyCompleteFleet: copies above 1 need the console |
| +// and every box fresh at the floor, each box's rollback binary at the |
| +// floor or none (R16), every published system pointer at the floor (R4) |
| +// and every instance holding a last good build (R13). Anything below, |
| +// missing, stale or unknown refuses and writes no count; every complete |
| +// floor box allows 2. A count of 1 needs none of it. |
| +func TestReplicaFloorEnablesOnlyCompleteFleet(t *testing.T) { |
| + floorMsg := "copies above 1 need every fleet box and the console" |
| + cases := []struct { |
| + name string |
| + setup func(t *testing.T, fx *consoleFixture) |
| + code int |
| + want string |
| + }{ |
| + {"complete", func(*testing.T, *consoleFixture) {}, 200, ""}, |
| + {"prev-none-and-at-floor", func(t *testing.T, fx *consoleFixture) { rfBeat(t, fx, "pi-2", release.StatelessReplicasFloor) }, 200, ""}, |
| + {"prev-below", func(t *testing.T, fx *consoleFixture) { rfBeat(t, fx, "pi-2", replicaBelow) }, 409, floorMsg}, |
| + {"prev-unknown", func(t *testing.T, fx *consoleFixture) { rfBeat(t, fx, "pi-2", "") }, 409, floorMsg}, |
| + {"old-box", func(t *testing.T, fx *consoleFixture) { |
| + copiesBeatPrev(t, fx, "pi-2", replicaBelow, "none", time.Now()) |
| + }, 409, floorMsg}, |
| + {"stale-box", func(t *testing.T, fx *consoleFixture) { |
| + copiesBeatPrev(t, fx, "pi-2", release.StatelessReplicasFloor, "none", time.Now().Add(-time.Hour)) |
| + }, 409, floorMsg}, |
| + {"missing-box", func(t *testing.T, fx *consoleFixture) { |
| + if err := fx.rel.Delete(context.Background(), "fleets/pi/status/boxes/pi-2.json"); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, 0, ""}, |
| + {"old-console", func(t *testing.T, fx *consoleFixture) { fx.srv.consoleBuild = replicaBelow }, 409, floorMsg}, |
| + {"channel-at-floor", func(t *testing.T, fx *consoleFixture) { |
| + rfPublish(t, fx, "stable", replicaBelow) |
| + rfPublish(t, fx, "stable", release.StatelessReplicasFloor) |
| + }, 200, ""}, |
| + {"channel-below", func(t *testing.T, fx *consoleFixture) { |
| + rfPublish(t, fx, "stable", release.StatelessReplicasFloor) |
| + rfPublish(t, fx, "canary", replicaBelow) |
| + }, 409, fmt.Sprintf(copiesChannelBelow, "canary", replicaBelow, release.StatelessReplicasFloor, release.StatelessReplicasFloor)}, |
| + {"channel-unreadable", func(t *testing.T, fx *consoleFixture) { |
| + rfPublish(t, fx, "stable", release.StatelessReplicasFloor) |
| + key := release.SystemPointerKey("router", "stable") |
| + _, tag, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(context.Background(), key, []byte("broken"), tag); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, 503, copiesUnread}, |
| + {"no-baseline", func(t *testing.T, fx *consoleFixture) { |
| + rfRecord(t, fx, "b.example.com", func(r *provision.Record) { r.ReplicaDeploy.Phase = "failed" }) |
| + }, 409, copiesNoBaseline}, |
| + {"failed-after-good", func(t *testing.T, fx *consoleFixture) { |
| + rfRecord(t, fx, "b.example.com", func(r *provision.Record) { |
| + r.ReplicaDeploy.LastGood = r.ReplicaDeploy.Target |
| + r.ReplicaDeploy.Phase = "failed" |
| + }) |
| + }, 200, ""}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + fx, token := rfWorld(t) |
| + c.setup(t, fx) |
| + code, out := copiesPut(t, fx, token, `{"copies":2}`) |
| + if c.code == 0 { |
| + // A box with no heartbeat at all: the fleet is not read |
| + // whole, which refuses (409 or 503), never admits. |
| + if code == 200 { |
| + t.Fatalf("admitted with a box unheard: %s", out) |
| + } |
| + } else if code != c.code || !strings.Contains(out, c.want) { |
| + t.Fatalf("copies 2 = %d %s; want %d %q", code, out, c.code, c.want) |
| + } |
| + if want := map[bool]int{true: 2, false: 1}[code == 200]; rfCopies(t, fx) != want { |
| + t.Fatalf("copies config = %d, want %d", rfCopies(t, fx), want) |
| + } |
| + }) |
| + } |
| + t.Run("count-1", func(t *testing.T) { |
| + fx, token := rfWorld(t) |
| + copiesBeatPrev(t, fx, "pi-2", replicaBelow, replicaBelow, time.Now()) |
| + fx.srv.consoleBuild = replicaBelow |
| + rfPublish(t, fx, "canary", replicaBelow) |
| + rfRecord(t, fx, "b.example.com", func(r *provision.Record) { r.ReplicaDeploy.Phase = "failed" }) |
| + if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 { |
| + t.Fatalf("copies 1 = %d %s", code, out) |
| + } |
| + for _, host := range []string{"a.example.com", "b.example.com"} { |
| + rec, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "shop", host) |
| + if err != nil || rec.ReplicaAssignment != nil { |
| + t.Fatalf("%s after copies 1: %+v %v", host, rec, err) |
| + } |
| + } |
| + // A count of 1 everywhere leaves a downgrade alone. |
| + if _, err := fx.srv.systemFloorGate(t.Context(), "router", "stable", replicaBelow, false, false, false); err != nil { |
| + t.Fatalf("downgrade with one copy everywhere = %v", err) |
| + } |
| + }) |
| +} |
| + |
| +// TestReplicaFloorCannotDowngradeActiveCopies (console half; the root half |
| +// is dropped by R16): while copies above 1 are configured, or any instance |
| +// still has more than one assigned box or a retiring one, no system |
| +// target below the floor is published: a promote, a rollback, or a first |
| +// publication. No override flag lets it through. An unreadable inventory |
| +// refuses. A target at the floor still publishes. |
| +func TestReplicaFloorCannotDowngradeActiveCopies(t *testing.T) { |
| + setCopies := func(t *testing.T, fx *consoleFixture, token string) { |
| + t.Helper() |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Fatalf("copies 2 = %d %s", code, out) |
| + } |
| + } |
| + cases := []struct { |
| + name string |
| + setup func(t *testing.T, fx *consoleFixture, token string) |
| + }{ |
| + {"copies-configured", setCopies}, |
| + {"one-copy-two-boxes", func(t *testing.T, fx *consoleFixture, token string) { |
| + setCopies(t, fx, token) |
| + if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 { |
| + t.Fatalf("copies 1 = %d %s", code, out) |
| + } |
| + rfRecord(t, fx, "a.example.com", func(r *provision.Record) { |
| + r.ReplicaAssignment = &replicas.Assignment{Revision: 2, Desired: 1, Boxes: []string{"pi-1", "pi-2"}} |
| + }) |
| + }}, |
| + {"one-copy-retiring", func(t *testing.T, fx *consoleFixture, token string) { |
| + setCopies(t, fx, token) |
| + if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 { |
| + t.Fatalf("copies 1 = %d %s", code, out) |
| + } |
| + rfRecord(t, fx, "a.example.com", func(r *provision.Record) { |
| + r.ReplicaAssignment = &replicas.Assignment{Revision: 3, Desired: 1, Boxes: []string{"pi-1"}, Retiring: []string{"pi-2"}} |
| + }) |
| + }}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + fx, token := rfWorld(t) |
| + s := fx.srv |
| + // stable is at the floor with a below-floor release in its |
| + // history; canary has no pointer. |
| + rfPublish(t, fx, "stable", replicaBelow) |
| + rfPublish(t, fx, "stable", release.StatelessReplicasFloor) |
| + c.setup(t, fx, token) |
| + for _, allow := range []bool{false, true} { |
| + for _, ch := range []string{"stable", "canary"} { |
| + if _, err := s.systemFloorGate(t.Context(), "router", ch, replicaBelow, allow, allow, allow); !errors.Is(err, errReplicaFloorPromotion) || err.Error() != rfFloorWant() { |
| + t.Fatalf("gate %s below the floor (overrides %v) = %v", ch, allow, err) |
| + } |
| + o := release.SystemPromoteOptions{AllowBelowRootfsFloor: allow, AllowBelowRegionalFloor: allow, AllowBelowFleetForwardFloor: allow} |
| + if _, err := s.promoteHostUpdate(t.Context(), fcRelease(replicaBelow), "router", ch, o); !errors.Is(err, errReplicaFloorPromotion) { |
| + t.Fatalf("promote %s below the floor (overrides %v) = %v", ch, allow, err) |
| + } |
| + } |
| + if _, err := s.rollbackHostUpdate(t.Context(), "router", "stable", "operator", allow, allow, allow); !errors.Is(err, errReplicaFloorPromotion) { |
| + t.Fatalf("rollback below the floor (overrides %v) = %v", allow, err) |
| + } |
| + } |
| + if v := rfPointer(t, fx, "stable"); v != release.StatelessReplicasFloor { |
| + t.Fatalf("stable moved to %s", v) |
| + } |
| + if v := rfPointer(t, fx, "canary"); v != "" { |
| + t.Fatalf("canary was published at %s", v) |
| + } |
| + // A target at the floor, or one that does not move, is no |
| + // crossing. |
| + if _, err := s.promoteHostUpdate(t.Context(), fcRelease("v0.35.1"), "router", "canary", release.SystemPromoteOptions{}); err != nil { |
| + t.Fatalf("promote at the floor = %v", err) |
| + } |
| + }) |
| + } |
| + t.Run("unreadable-inventory", func(t *testing.T) { |
| + fx, token := rfWorld(t) |
| + setCopies(t, fx, token) |
| + key := appconfig.Key(fx.sqid, "shop") |
| + _, tag, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(context.Background(), key, []byte("broken"), tag); err != nil { |
| + t.Fatal(err) |
| + } |
| + _, err = fx.srv.promoteHostUpdate(t.Context(), fcRelease(replicaBelow), "router", "stable", release.SystemPromoteOptions{}) |
| + if err == nil || !strings.Contains(err.Error(), "cannot read the copy inventory") { |
| + t.Fatalf("promote over an unreadable inventory = %v", err) |
| + } |
| + if v := rfPointer(t, fx, "stable"); v != "" { |
| + t.Fatalf("published %s over an unreadable inventory", v) |
| + } |
| + }) |
| + t.Run("update-door-409", func(t *testing.T) { |
| + fx, token := rfWorld(t) |
| + setCopies(t, fx, token) |
| + code, _, out := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/system/update", token, `{"channel":"stable","version":"`+replicaBelow+`"}`) |
| + if code != http.StatusConflict || !strings.Contains(out, rfFloorWant()) { |
| + t.Fatalf("update door = %d %s", code, out) |
| + } |
| + }) |
| +} |
| + |
| +// TestReplicaFloorPublicationAndCopiesBothOrders: a first publication below |
| +// the floor and a copies 2 request, through the real doors, with the |
| +// heartbeats unchanged throughout (every box at the floor, prev none): |
| +// |
| +// - copies first: the copies door runs between the publication's |
| +// up-front judgment and replicaFloorMu, and is admitted (no pointer |
| +// yet); the publication judges again under the mutex, sees the copies, |
| +// and is refused; no pointer is written; |
| +// - publication first: the publication runs just before the copies door |
| +// takes the mutex and lands; the door's barrier reads it and refuses |
| +// (409); the count stays 1. |
| +func TestReplicaFloorPublicationAndCopiesBothOrders(t *testing.T) { |
| + t.Run("copies-first", func(t *testing.T) { |
| + fx, token := rfWorld(t) |
| + s := fx.srv |
| + ran := false |
| + s.replicaFloorHooks.beforeLock = func() { |
| + if ran { |
| + return |
| + } |
| + ran = true |
| + if fpHeld(&s.replicaFloorMu) || !fpHeld(&s.fleetFloorMu) { |
| + t.Error("beforeLock: replicaFloorMu held, or fleetFloorMu not held") |
| + } |
| + if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 { |
| + t.Errorf("copies with no pointer = %d %s", code, out) |
| + } |
| + } |
| + s.replicaFloorHooks.locked = func() { t.Error("the publication passed its judgment with copies set") } |
| + _, err := s.promoteHostUpdate(t.Context(), fcRelease(replicaBelow), "router", "stable", release.SystemPromoteOptions{}) |
| + if !ran { |
| + t.Fatal("beforeLock never ran") |
| + } |
| + if !errors.Is(err, errReplicaFloorPromotion) || err.Error() != rfFloorWant() { |
| + t.Fatalf("publication after the copies = %v", err) |
| + } |
| + if v := rfPointer(t, fx, "stable"); v != "" || rfCopies(t, fx) != 2 { |
| + t.Fatalf("pointer %q copies %d; want none and 2", v, rfCopies(t, fx)) |
| + } |
| + }) |
| + t.Run("publication-first", func(t *testing.T) { |
| + fx, token := rfWorld(t) |
| + s := fx.srv |
| + ran := false |
| + s.replicaFloorHooks.copiesBeforeLock = func() { |
| + ran = true |
| + if fpHeld(&s.replicaFloorMu) { |
| + t.Error("copiesBeforeLock ran with replicaFloorMu held") |
| + } |
| + if _, err := s.promoteHostUpdate(t.Context(), fcRelease(replicaBelow), "router", "stable", release.SystemPromoteOptions{}); err != nil { |
| + t.Errorf("publication with one copy = %v", err) |
| + } |
| + } |
| + code, out := copiesPut(t, fx, token, `{"copies":2}`) |
| + if !ran { |
| + t.Fatal("copiesBeforeLock never ran") |
| + } |
| + want := fmt.Sprintf(copiesChannelBelow, "stable", replicaBelow, release.StatelessReplicasFloor, release.StatelessReplicasFloor) |
| + if code != http.StatusConflict || !strings.Contains(out, want) { |
| + t.Fatalf("copies after the publication = %d %s", code, out) |
| + } |
| + if v := rfPointer(t, fx, "stable"); v != replicaBelow || rfCopies(t, fx) != 1 { |
| + t.Fatalf("pointer %q copies %d; want %s and 1", v, rfCopies(t, fx), replicaBelow) |
| + } |
| + }) |
| +} |
| + |
| +// TestReplicaFloorPublicationLockOrder: the publication takes fleetFloorMu, |
| +// then replicaFloorMu, then regionalMu, and holds all three at its write. |
| +func TestReplicaFloorPublicationLockOrder(t *testing.T) { |
| + for _, mode := range []string{"promote", "rollback"} { |
| + t.Run(mode, func(t *testing.T) { |
| + s, _, target := activationFixtureAt(t, "v0.32.0", "v0.31.0", "v0.28.0") |
| + var before, locked bool |
| + s.regionalFloorHooks.beforeLock = func() { |
| + before = true |
| + if !fpHeld(&s.fleetFloorMu) || !fpHeld(&s.replicaFloorMu) || fpHeld(&s.regionalMu) { |
| + t.Error("before regionalMu: fleetFloorMu and replicaFloorMu are not both held, or regionalMu is") |
| + } |
| + } |
| + s.replicaFloorHooks.beforeLock = func() { |
| + if !fpHeld(&s.fleetFloorMu) || fpHeld(&s.replicaFloorMu) { |
| + t.Error("before replicaFloorMu: fleetFloorMu not held, or replicaFloorMu already is") |
| + } |
| + } |
| + s.regionalFloorHooks.locked = func() { |
| + locked = true |
| + if !fpHeld(&s.replicaFloorMu) { |
| + t.Error("at the publication: replicaFloorMu is not held") |
| + } |
| + } |
| + var err error |
| + if mode == "rollback" { |
| + _, err = s.rollbackHostUpdate(t.Context(), "router", "stable", "operator", false, false, false) |
| + } else { |
| + _, err = s.promoteHostUpdate(t.Context(), target, "router", "stable", release.SystemPromoteOptions{}) |
| + } |
| + if err != nil || !before || !locked { |
| + t.Fatalf("%s = %v (hooks ran: %v, %v)", mode, err, before, locked) |
| + } |
| + if fpHeld(&s.replicaFloorMu) { |
| + t.Fatal("replicaFloorMu is still held after the publication") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// copiesBeatPrev is copiesBeat with the box's rollback binary at prev. |
| +func copiesBeatPrev(t *testing.T, fx *consoleFixture, box, rel, prev string, at time.Time) { |
| + t.Helper() |
| + writeCopiesBeat(t, fx, box, rel, prev, at) |
| +} |
diff --git a/internal/console/rootfs_test.go b/internal/console/rootfs_test.go| index 5275a8653..888967481 100644 |
| --- a/internal/console/rootfs_test.go |
| +++ b/internal/console/rootfs_test.go |
| @@ -60,7 +60,7 @@ func writeFleetBoxOn(t *testing.T, fx *consoleFixture, fleet, label, region stri |
| s = release.NewPrefixStore(fx.rel, "fleets/"+fleet+"/") |
| } |
| b := status.Box{GeneratedAt: at, Label: label, Region: region, |
| - Metrics: &status.BoxMetrics{Layout: &status.LayoutReport{Mode: "nested"}, RootfsReady: ready, Release: rel}} |
| + Metrics: &status.BoxMetrics{Layout: &status.LayoutReport{Mode: "nested"}, RootfsReady: ready, Release: rel, PrevRelease: "none"}} |
| if err := status.WriteBox(context.Background(), s, b); err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/rootfsfloor.go b/internal/console/rootfsfloor.go| index 264a70572..2575b06e4 100644 |
| --- a/internal/console/rootfsfloor.go |
| +++ b/internal/console/rootfsfloor.go |
| @@ -57,15 +57,21 @@ func (s *Server) systemFloorGate(ctx context.Context, component, channel, target |
| } |
| // systemFloorSnapshot is systemFloorGate returning the judged pointer too |
| -// (nil for none): promoteHostUpdate judges the fleet forward and regional |
| -// floors on it again under fleetFloorMu and regionalMu just before it |
| -// publishes (fleetFloorPublish, regionalFloorPublish). |
| +// (nil for none): promoteHostUpdate judges the fleet forward, replicas and |
| +// regional floors on it again under fleetFloorMu, replicaFloorMu and |
| +// regionalMu just before it publishes (fleetFloorPublish, |
| +// replicaFloorPublish, regionalFloorPublish). The stateless replicas floor |
| +// (replicaFloorJudge, no override) judges both a pointer and a first |
| +// publication. |
| func (s *Server) systemFloorSnapshot(ctx context.Context, component, channel, target string, allowRootfs, allowRegional, allowFleet bool) (*release.SystemPointer, string, error) { |
| cur, etag, err := release.GetSystemPointer(ctx, s.cfg.Releases, release.RootSigner(s.cfg.Key).RootPublicKey(), component, channel) |
| if errors.Is(err, os.ErrNotExist) { |
| // A first publication: the rootfs and regional floors have nothing |
| // to protect, the fleet forward floor still judges it (spec §9). |
| - return nil, etag, s.fleetForwardFloorJudge(ctx, channel, nil, target, allowFleet) |
| + if err := s.fleetForwardFloorJudge(ctx, channel, nil, target, allowFleet); err != nil { |
| + return nil, etag, err |
| + } |
| + return nil, etag, s.replicaFloorJudge(ctx, channel, nil, target) |
| } |
| if err != nil { |
| return nil, "", err |
| @@ -76,7 +82,10 @@ func (s *Server) systemFloorSnapshot(ctx context.Context, component, channel, ta |
| if err := s.regionalFloorJudge(ctx, channel, cur, target, allowRegional); err != nil { |
| return cur, etag, err |
| } |
| - return cur, etag, s.fleetForwardFloorJudge(ctx, channel, cur, target, allowFleet) |
| + if err := s.fleetForwardFloorJudge(ctx, channel, cur, target, allowFleet); err != nil { |
| + return cur, etag, err |
| + } |
| + return cur, etag, s.replicaFloorJudge(ctx, channel, cur, target) |
| } |
| // rootfsFloorJudge is the rootfs half of systemFloorGate's decision, on a |
diff --git a/internal/console/server.go b/internal/console/server.go| index 3840fe516..7f3dc6060 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1539,6 +1539,16 @@ type Server struct { |
| // fleetFloorHooks are test seams around fleetFloorPublish's and the |
| // fleet-create door's critical sections; nil in production. |
| fleetFloorHooks fleetFloorHooks |
| + // replicaFloorMu is the stateless replicas floor's mutex |
| + // (replicafloor.go): every system pointer publication holds it from |
| + // its last replicas floor judgment to its pointer write |
| + // (replicaFloorPublish), taken after fleetFloorMu and before |
| + // regionalMu, and the copies door holds it, after its app lock, from |
| + // its pointer barrier to its config write. The zero value is ready. |
| + replicaFloorMu sync.Mutex |
| + // replicaFloorHooks are test seams around those critical sections; |
| + // nil in production. |
| + replicaFloorHooks replicaFloorHooks |
| // The trash sweep's clock (lifetimes_purge.go) and the box floor |
| // watch's memory (lifetimes_floor.go). |
| trashSweepState |
diff --git a/internal/host/agent.go b/internal/host/agent.go| index 6c5e61035..55b13566a 100644 |
| --- a/internal/host/agent.go |
| +++ b/internal/host/agent.go |
| @@ -4984,7 +4984,11 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func |
| Load1: readLoad1(), |
| DiskFreeBytes: readDiskFreeBytes(), |
| Release: version.Build, |
| - Platform: runtime.GOOS + "-" + runtime.GOARCH, |
| + // carlos.prev's release, so the console can tell whether a |
| + // failed apply here could restore a build below the |
| + // stateless replicas floor (#511 R16). |
| + PrevRelease: prevReleaseOf(release.OptDir()), |
| + Platform: runtime.GOOS + "-" + runtime.GOARCH, |
| // The metrics loop's disk forecast, nil unless it is growing. |
| DiskFullETAHours: diskETAProbe(&processDiskTrend, time.Now()), |
| // The invalid-value line is newSystemLeg's to say, once at |
diff --git a/internal/host/movesfloor.go b/internal/host/movesfloor.go| index 41f8c38ae..16cd63c57 100644 |
| --- a/internal/host/movesfloor.go |
| +++ b/internal/host/movesfloor.go |
| @@ -523,12 +523,20 @@ func withMovesFields(f edgesFile, dataDir, optDir string) edgesFile { |
| if fl, err := readLocalFloor(dataDir); err == nil && fl != nil { |
| f.MovesFloorMinRelease = fl.MinRelease |
| } |
| - f.PrevRelease = "" |
| - if _, err := os.Stat(systemPrevPath(optDir)); errors.Is(err, os.ErrNotExist) { |
| - f.PrevRelease = "none" |
| - } else if err == nil { |
| - f.PrevRelease, _ = readLine(prevVersionPath(optDir)) |
| - } |
| + f.PrevRelease = prevReleaseOf(optDir) |
| f.PrevAllowedFor, _ = readLine(prevAllowedPath(optDir)) |
| return f |
| } |
| + |
| +// prevReleaseOf is carlos.prev's release, from its version record: "none" |
| +// when there is no carlos.prev, "" when it cannot be told. The edges file |
| +// (withMovesFields) and the box's status report (#511 R16) both say it. |
| +func prevReleaseOf(optDir string) string { |
| + if _, err := os.Stat(systemPrevPath(optDir)); errors.Is(err, os.ErrNotExist) { |
| + return "none" |
| + } else if err != nil { |
| + return "" |
| + } |
| + v, _ := readLine(prevVersionPath(optDir)) |
| + return v |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index 874acc180..52f3056f7 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := statelessReplicas4Task3FWriteCensusInventory() |
| + inventory := statelessReplicas4Task5WriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/stateless_replicas_4_task5_census_test.go b/internal/provision/stateless_replicas_4_task5_census_test.go| new file mode 100644 |
| index 000000000..924540be3 |
| --- /dev/null |
| +++ b/internal/provision/stateless_replicas_4_task5_census_test.go |
| @@ -0,0 +1,36 @@ |
| +package provision |
| + |
| +// statelessReplicas4Task5WriteCensusInventory is stateless replicas Plan 4 |
| +// Task 5's review of the record-write census, layered on Task 3F's. |
| +// Self-review only; the independent #280 verdict is the controller's. |
| +// |
| +// - prepareStateless (first commit, #511 F11 log dedupe): a failed |
| +// release preparation's error is wrapped with the attempt ID it acted |
| +// on (withAttempt). It writes no record; its record reference is still |
| +// the statelessRecordKey observation. |
| +// - drill.untilCopies (scripts/stateless-replicas-drill): "instances" is |
| +// the carlos CLI verb it runs (carlos instances list), not a record |
| +// key. The drill holds no store and writes nothing; it reads through |
| +// the operator's logged-in CLI. |
| +// - No new record writer. The console's copies-door barrier and the |
| +// system publication judge read records (placeRecords) and write only |
| +// what they wrote before (the app's copies config, the system pointer). |
| +func statelessReplicas4Task5WriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), statelessReplicas4Task3FWriteCensusInventory()...) |
| + for _, r := range []censusEntry{ |
| + {"internal/activator/stateless.go", "Service.prepareStateless", "reference", "key:statelessRecordKey", "02cc71302cf90444ce289154bef79663690d7fa9da83793b1640e79c61faba22"}, |
| + {"scripts/stateless-replicas-drill/main.go", "drill.untilCopies", "key-site", "lit:instances", "f61736a31df8d807f4a9258d9ff07c575d7b5c04d4bde1d801cf7d9a900b1968"}, |
| + } { |
| + replaced := false |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + entries[i], replaced = r, true |
| + break |
| + } |
| + } |
| + if !replaced { |
| + entries = append(entries, r) |
| + } |
| + } |
| + return entries |
| +} |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 4e454f351..1b9aacc59 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -178,3 +178,4 @@ plan14-root-reads-stateless-replicas-4-task2-fix2.tsv 5f83de2e018b47543789a8dbe2 |
| plan14-root-reads-stateless-replicas-4-task2-fix3.tsv bd25367161555e8a9c5b0df079ad2d8eb648ebaeae3f407e6c638f2f7f01605b |
| plan14-root-reads-stateless-replicas-4-task3.tsv bd25367161555e8a9c5b0df079ad2d8eb648ebaeae3f407e6c638f2f7f01605b |
| plan14-root-reads-stateless-replicas-4-task3f.tsv 45b27ac0e2f2152497e3c01f277c2230defaeb3be363170ea61b05d72f0a6782 |
| +plan14-root-reads-stateless-replicas-4-task5.tsv 39becc512079522a9ce16be0883e163a818bedf6c42e40708ec4388ba6aed9d3 |
diff --git a/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv| new file mode 100644 |
| index 000000000..56a6d6f93 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv |
| @@ -0,0 +1,20 @@ |
| +# Census overlay stateless-replicas-4-task5, written by census-propose (#369). census-ruling-stateless-replicas-4-task5, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md. |
| +# 5 body, 2 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other. |
| +@legacy 7c6106e084eab50cd72a14e7006b8ac180725aa80fdfdd4ffd18e454e893431d internal/activator/activator.go Service.wake legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=logs that timer's breakdown to the journal after a successful wake (w.steps.String(), e.host, w.wakeTook); no read added;rev3=census-ruling-plans-4d-lapse;basis=cancels a wake whose row the turned-off hook names, like a fence, unless it is a move's active probe (plans 4d). One more whole-row read: the row handed to the hook (a.disabled). Only refuses.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: a refusal before the lease is reported once per change (noteRootfsRefusal) instead of a wake-failure event; the proc, generation and replica are installed through installProcLocked (which puts a resident under its lease watch before the fence); residency notes the outcome (noteResidentWakeLocked); same generation values;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R [pf R3.5]: the wake's context ceiling is wakeCeilingFor(e.route): the old 5 minutes for a binary row, 5 minutes plus runs.MaxTimeout for a rootfs row (room for a release inside the wake); new site +whole:Route (e.route to wakeCeilingFor, which reads Runtime only); no other change;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (branch review R1 P1-1): the wake's context is also cancelled before doWake when RetireExcept has marked the entry retired (e.retired, in memory under a.mu), as it is for a fence or a shutdown. Read sites unchanged (13). Agent, not root; it only refuses more.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry successful hold preparation into its wake, preserve actual mode in the generation and OnWake projection, and project serving version/mode through the narrow registry writer before releasing wake waiters. Final review I1: SetServingMode only for non-worker successful wakes with a nonempty spawned version and either a stateless generation or a mode transition from the route. Ordinary stateful wakes leave rollout status and the wake critical path unchanged.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds a.cancelHeldLegsLocked(e, 0) on the failed-wake path before the entry is deleted, and after close(e.ready) on success calls a.noteHeldAdmissible(e.host), the non-blocking held wake callback, outside a.mu. No read added.;rev3=census-ruling-wake-storm-cap;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): waits for a box-wide wake slot (acquireWakeSlot, an in-memory buffered channel) before doWake; the fence/shutdown/retired/disabled refusals move into refuseWakeLocked and are asked again after admission (one fewer direct whole-Route read here: a.disabled(e.route) now runs inside refuseWakeLocked, same value); e.wakeStart is set at admission and e.admitted marks it. Only waits and refuses more; no new read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Install the successful-acquire observer and restrict due, worker and resident starts before doWake, off a.mu. Add a whole-route argument to restriction; refused work has known-no-start evidence.;rev3=census-ruling-region-ha-g2-fixes;basis=Bind recovery wakes to the service lifetime; no new read.;rev3=census-ruling-edge-page-cache-1;basis=the generation-current call is now noteCurrent(e) instead of noteCurrent(e.host, e.gen.N), so the new noteCurrent can also publish the process's page cache launch inputs; read sites unchanged (16); no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: a failed wake that journalledWakeFailure counts as a real failure is logged through logWakeFailure (rate-limited per host, in memory); a successful wake calls clearWakeFailure. Agent, not root; reads the error already in hand; no read added;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11 log dedupe): before a failed wake's member event, noteHeldWake (in-memory, per host, under the leaf wakeFailMu) tells whether the failure is held by a release attempt with no backoff and is the same (attempt ID, error class) as the host's last one; a repeat writes no event, a first or changed one writes one journal line and the event. Reads only the error in hand; no read site added. registry:Socket@8833,registry:Socket@8994,registry:Stateless@10328,registry:Stateless@11076,whole:Route@10319,whole:Route@10374,whole:Route@11078,whole:Route@1762,whole:Route@3315,whole:Route@3588,whole:Route@3745,whole:Route@466,whole:Route@7095,whole:Route@8786,whole:Route@8835,whole:Route@8996 07eb4613a131d4487b987e1040c125fb6f152801f9ab7b354f4bcdf5019805df |
| +@legacy adcc10d6f173ade7c8a1c5a04d6709340b3cfce5d5cd597543bc9500dd0b6207 internal/activator/stateless.go Service.prepareStateless legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Capture RecordFacts from the existing record source, obtain the durable FailureBook deploy ID, and call Task 2 PrepareStatelessRelease with the canonical verdict/digest carrier. Carry a successful attempt through its hold only after another current-record check; no serving lease or polling loop. Fix 3a round 1 I2: preparation uses reconcile observations and records the successful deploy ID. Carry prepared evidence through hold; fresh backend read must confirm that same released deploy before web runs.;rev3=census-ruling-stateless-failed-release-held;basis=For recovery onto a different installed version's exact committed good version and artifact digest, retain recovery evidence without selecting or writing another deploy. Adds the existing committedGood registry read, with its route and incarnation check. Canonical storage declaration and observed lifetime gates remain.;rev3=census-ruling-stateless-replicas-4-task1;basis=R1: no longer calls ReplicaDeployID before preparation; hands the same a.ReplicaDeployID selector to prepareStatelessRelease, which calls it only after coordinator term acquisition. The ObservedReplicaRelease call stays as a validity check. Same read sites; no new read, write or authority.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2 (D4): for a set row, prepares the record baseline with no release, and refuses a build the row Version does not name before any release; reads the route it is handed (FleetBoxes, Version). No store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: for a set row, a build its pointer does not name starts only as the record baseline or the committed permitted target, the latter adopted through prepareStatelessRelease durable path (never a new attempt); a named build, a rollback included, takes the release path. The added reads are the handed route (FleetBoxes, Version) and a copy of it with Stateless set for the adoption, as the release path already builds. No store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: for a set row the no-release start is decided per box from the record (this box baseline, or its permitted target adopted through the durable path), whatever the pointer says; only a build that is neither and that the pointer names begins a new attempt. Same reads (the handed route and its copy); no store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix3;basis=Task 2 fix round 3: this box baseline is checked before the adopt path, so a completed box restarts on the target while a retry is requested; for the passed target it calls the existing escrow initializer (prepareStatelessEscrow) that the adopt path ran, with the same route and identity. No new reader; no record write.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F (#511 F11): a hold's pinned wake carrying the swap's preparation, when the row it re-read differs from the prepared row, moves the preparation onto the wake's row only if the prepared row passes statelessCurrent against the registry, the two rows have the same Incarnation, ServingSeq, HoldOp and Version (sameRowLifetime, fix round 1), and the wake's row then passes statelessCurrent; otherwise it refuses with errStatelessRowChanged. The added sites are whole-Route comparisons and copies of the handed and prepared routes. No store read or write added; no new authority.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): a failed release preparation's error is wrapped with the attempt ID prepareStatelessRelease returned (withAttempt); the text and every errors.Is answer are unchanged. No read, write or authority added. registry:Account@284,registry:Account@310,registry:App@324,registry:App@346,registry:Digest@4803,registry:FleetBoxes@1967,registry:FleetBoxes@4446,registry:Host@250,registry:Host@273,registry:Stateless@3505,registry:Stateless@4030,registry:Stateless@5101,registry:Version@4338,registry:Version@4483,registry:Version@4773,whole:Route@1341,whole:Route@1348,whole:Route@1429,whole:Route@1437,whole:Route@1503,whole:Route@1623,whole:Route@1737,whole:Route@1844,whole:Route@259,whole:Route@2878,whole:Route@2885,whole:Route@293,whole:Route@333,whole:Route@3497,whole:Route@3584,whole:Route@4024,whole:Route@4110,whole:Route@4723,whole:Route@4867,whole:Route@4874,whole:Route@5097,whole:Route@5251,whole:Route@5378,whole:Route@5385,whole:Route@540,whole:Route@597,whole:Route@646,whole:Route@661 02cc71302cf90444ce289154bef79663690d7fa9da83793b1640e79c61faba22 |
| +@legacy 5034933d042bc3e8ad96c2940b08c6247260624671f8962e9c1d83f5d7846a74 internal/host/agent.go statusLoop legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's context carries the box's lifetime judge; read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 953b9fda (its later changes, regional box names and self-serve moves plan 1 among them, under main's own census rulings), where the tick fills rootfs_ready and rootfs_blocked from armedRootfs.Load().probe, which each tick runs NestedOK's checks and asks the control socket's GET /ready/rootfs (never the store); the same four direct sites;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: takes root's GET /egress reader and fills p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) and p.SizeCommittedMiB = sizeCommittedMiB(armedSizeSource.Load(), routes); the two added whole:Route sites are the tick's own registry list handed to those two units (decision rows), which read root's control socket and the activator's memory; no store request added; the four existing sites unchanged, offsets moved.;rev3=census-ruling-fleet-alerts-1;basis=the agent (carlos-edge.service, user carlos): the status tick passes os.Geteuid() to alertDeliveryProbe, which fills AlertDelivery.EngineBeat/EngineBeatWhy from engineBeatArmed (the env value and the euid only, no file access, root refused before the path is looked at), and fills Probes.DiskFullETAHours from diskETAProbe(&processDiskTrend, now), a Theil-Sen fit over the metrics loop's in-memory ring of disk readings; the same six sites, no read added, no store request added;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's Probes gain HeldStreams: heldStreamsState(), which calls the edge's in-memory counters function (nil until the edge is ready). No file, bucket or registry access added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: read the detached in-memory replica snapshot source into Probes.ReplicaCopies on the existing five-minute tick. Existing six direct read sites unchanged. No additional bucket request, changed cadence or app lifecycle action.;rev3=census-ruling-agent-start-demo-3;basis=Report moved capability only when the serving edge reports readiness; report claim-seed support only with CARLOS_DEMO_CLAIM=1. Reads the explicit capability flag from the process environment; no new filesystem or registry read.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 (#511 R16): the status tick fills Probes.PrevRelease from prevReleaseOf(release.OptDir()): a Stat of carlos.prev and a read of carlos.prev.version, the files the agent already reads for the edges file (withMovesFields). Reported in the private BoxMetrics block so the console counts a box at the stateless replicas floor only when its rollback binary is too. No bucket request or cadence change. whole:Route@10350,whole:Route@12164,whole:Route@12445,whole:Route@6583,whole:Route@6610,whole:Route@7918 58c8ab80612b1767e6c3f75d81f31bc91d73f31bc1a3dbf6cfa64b53c2dc6add |
| +@legacy e04e0893b47e99995d4781b0630f4002ddd65605d9c3aa1abdfb5630924edf5a internal/status/snapshot.go CollectBox legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;basis=copies Probes.RootfsReady and RootfsBlocked into BoxMetrics (private, like Layout); the same 28 sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: copies Probes.Egress and Probes.SizeCommittedMiB into BoxMetrics (private, like Layout) and counts them in the condition that builds Metrics; the same 28 sites, no read added.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3: comment only, the Hibernate count is left as is (display);rev3=census-ruling-regional-domains-447;basis=#447 Task 7: copies Probes.AliasesRead into BoxMetrics.AliasesRead (json aliases_read, omitempty) and counts it in the condition that builds Metrics; the same 28 sites, no read added;rev3=census-ruling-fleet-alerts-1;basis=copies Probes.DiskFullETAHours into BoxMetrics.DiskFullETAHours (json disk_full_eta_hours, omitempty; private, like Layout) and counts it in the condition that builds Metrics; the same 28 sites, no read added;rev3=census-ruling-edge-held-streams;basis=copies Probes.HeldStreams into BoxMetrics.HeldStreams (json held_streams, omitempty, additive) and counts it in the condition that builds Metrics; the same 28 sites, no read added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: carry already-supplied ReplicaCopies into a separate optional private BoxMetrics replica_copies field; allow copy evidence alone to create the metrics block. Upstreams retains address probes only. Existing 28 Route read sites unchanged; no filesystem, bucket, console or CLI read.;rev3=census-ruling-agent-start-demo-3;basis=Report claim-seed protocol capability only when explicitly configured and runtime moved readiness only when armed; dormant status keeps its original JSON shape. Census read-site delta: unchanged (28).;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 (#511 R16): copies Probes.PrevRelease into BoxMetrics.PrevRelease (json prev_release, omitempty; private, like Release) and counts it in the condition that builds Metrics; the same 28 sites, no read added. registry:Alias@4543,registry:CertExpiresAt@3160,registry:CertExpiresAt@3396,registry:CertExpiresAt@4658,registry:DBPath@2495,registry:DBPath@2553,registry:DNSCheckedAt@3365,registry:DNSCheckedAt@4627,registry:DNSStatus@3139,registry:DNSStatus@3334,registry:DNSStatus@4597,registry:Hibernate@3853,registry:Host@2295,registry:Host@2437,registry:Host@2666,registry:Host@3280,registry:Host@3315,registry:Host@4578,registry:Kind@2473,registry:Kind@3807,registry:Platform@2152,registry:ServingVersion@2324,registry:ServingVersion@2447,registry:Socket@4066,registry:Version@2186,registry:Version@2305,whole:Route@1581,whole:RouteAlias@4440 97987f62d0c54897da42c33cb9fa994bd316cdc9fc7813d7a1155d961f93afaa |
| +@legacy 21ca6fc17af62778bc0e7e3460e3de6cbc36e6a46a371f1fa82cf5848d9ff467 internal/host/movesfloor.go prevReleaseOf legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 (#511 R16): new, factored out of withMovesFields: Stat of <opt>/carlos.prev ("none" when absent, "" on another error) and readLine of <opt>/carlos.prev.version. The agent (carlos-edge.service, user carlos), not root; reads only root-written files under the opt dir, which withMovesFields already read. file:Stat@57 4d0f9e568555c0718bfce11731dfa8d76b5d4d1172b8824277309c51b6ae7176 |
| +@legacy a8c2e83866f72d334d00acc51d249012227578ae45d96f88cba8a945abc093f9 internal/activator/rootfs_service.go Service.residentJob legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: one proactive start of a resident: the same pre-lease admission as a request (rootfsStartRefusal, then the locked half under a.mu after re-checking the reservation, shutdown, hold and wait), then an ordinary wake of a resident entry; adds no gate a request does not pass;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): the "starting it" journal line is written only when heldNow(rt.Host) is false, an in-memory lookup of the host's held note; the added registry:Host site is that host string. No gate, read or start changes. registry:Host@1228,registry:Host@188,registry:Host@229,registry:Host@816,registry:Host@956,registry:Host@998,whole:Route@125,whole:Route@302,whole:Route@458,whole:Route@590,whole:Route@825,whole:Route@832,whole:Route@933 e18b39bd166c61e90fc9fdf7b972cd5df648fe5aa4c9e4094ac31edbd69bef15 |
| +internal/activator/activator.go Service.wake legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-wake-latency-1;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=logs that timer's breakdown to the journal after a successful wake (w.steps.String(), e.host, w.wakeTook); no read added;rev3=census-ruling-plans-4d-lapse;basis=cancels a wake whose row the turned-off hook names, like a fence, unless it is a move's active probe (plans 4d). One more whole-row read: the row handed to the hook (a.disabled). Only refuses.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: a refusal before the lease is reported once per change (noteRootfsRefusal) instead of a wake-failure event; the proc, generation and replica are installed through installProcLocked (which puts a resident under its lease watch before the fence); residency notes the outcome (noteResidentWakeLocked); same generation values;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R [pf R3.5]: the wake's context ceiling is wakeCeilingFor(e.route): the old 5 minutes for a binary row, 5 minutes plus runs.MaxTimeout for a rootfs row (room for a release inside the wake); new site +whole:Route (e.route to wakeCeilingFor, which reads Runtime only); no other change;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (branch review R1 P1-1): the wake's context is also cancelled before doWake when RetireExcept has marked the entry retired (e.retired, in memory under a.mu), as it is for a fence or a shutdown. Read sites unchanged (13). Agent, not root; it only refuses more.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Carry successful hold preparation into its wake, preserve actual mode in the generation and OnWake projection, and project serving version/mode through the narrow registry writer before releasing wake waiters. Final review I1: SetServingMode only for non-worker successful wakes with a nonempty spawned version and either a stateless generation or a mode transition from the route. Ordinary stateful wakes leave rollout status and the wake critical path unchanged.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds a.cancelHeldLegsLocked(e, 0) on the failed-wake path before the entry is deleted, and after close(e.ready) on success calls a.noteHeldAdmissible(e.host), the non-blocking held wake callback, outside a.mu. No read added.;rev3=census-ruling-wake-storm-cap;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): waits for a box-wide wake slot (acquireWakeSlot, an in-memory buffered channel) before doWake; the fence/shutdown/retired/disabled refusals move into refuseWakeLocked and are asked again after admission (one fewer direct whole-Route read here: a.disabled(e.route) now runs inside refuseWakeLocked, same value); e.wakeStart is set at admission and e.admitted marks it. Only waits and refuses more; no new read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Install the successful-acquire observer and restrict due, worker and resident starts before doWake, off a.mu. Add a whole-route argument to restriction; refused work has known-no-start evidence.;rev3=census-ruling-region-ha-g2-fixes;basis=Bind recovery wakes to the service lifetime; no new read.;rev3=census-ruling-edge-page-cache-1;basis=the generation-current call is now noteCurrent(e) instead of noteCurrent(e.host, e.gen.N), so the new noteCurrent can also publish the process's page cache launch inputs; read sites unchanged (16); no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: a failed wake that journalledWakeFailure counts as a real failure is logged through logWakeFailure (rate-limited per host, in memory); a successful wake calls clearWakeFailure. Agent, not root; reads the error already in hand; no read added;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11 log dedupe): before a failed wake's member event, noteHeldWake (in-memory, per host, under the leaf wakeFailMu) tells whether the failure is held by a release attempt with no backoff and is the same (attempt ID, error class) as the host's last one; a repeat writes no event, a first or changed one writes one journal line and the event. Reads only the error in hand; no read site added. registry:Socket@8833,registry:Socket@8994,registry:Stateless@10328,registry:Stateless@11076,whole:Route@10319,whole:Route@10374,whole:Route@11078,whole:Route@1762,whole:Route@3315,whole:Route@3588,whole:Route@3745,whole:Route@466,whole:Route@7095,whole:Route@8786,whole:Route@8835,whole:Route@8996 07eb4613a131d4487b987e1040c125fb6f152801f9ab7b354f4bcdf5019805df |
| +internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Add coordinator, existing-record observation callback and per-host preparation locks; no read in the declaration. Task 3a: Add optional canonical storage-selection and durable deploy-ID callbacks; declaration only, no read or authority in these fields.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): adds the heldLegs map to actEntry (legs by id, under a.mu) and heldWakeHook (atomic pointer to a callback) and heldLegSeq (atomic counter) to Service. State only, in memory; no read of tenant, app or box-agent-writable input.;rev3=census-ruling-wake-storm-cap;basis=the agent as carlos: one field, wakeSlots (chan struct{}, the wake semaphore made by New from Config.WakeSlots, default 4); declaration only, no read.;rev3=census-ruling-region-ha-p1b3b-t;basis=Add the B2 DutyStore interface field and process-local duty view, suppression and invalidation state. No read added. B2 adds the verified-successor identity callback; no read in the declaration. B3b adds a nonblocking departure-suspicion callback, invoked only after an accepted holder-forward failure and after cache locks release; it cannot authorize a take.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: immutable callbacks installed before Start for tenant admission, local start permission, fixed route exemptions and shutdown closure; nil callbacks preserve switch-off behavior; no new reads. Fix R1: add an immutable startup-phase callback for response copy, set before service startup. No new read or execution authority.;rev3=census-ruling-region-ha-g2-fixes;basis=Add in-memory HA loss state and pool withdrawal jobs; no new read.;rev3=census-ruling-region-ha-held-build;basis=region HA held-requests Task 1: one new field, drain (drainSources: two atomic func pointers for this box's and peers' drain state); no read added. region HA held-requests Task 2: one new field, moves (moveTable: per-host move state, hold counts and admission tickets in memory, under mu); no read added;rev3=census-ruling-held-move-speed;basis=the agent as carlos: one new field, moveStreams (per-host in-memory set of edge.StreamEnd for requests in flight, own mutex), for the move's early stream cut; actEntry gains drainRelease (bool, under a.mu), set by DrainStop; declarations only, no read added;rev3=census-ruling-fix-silent-start-kill-861;basis=#861: two fields, wakeFailMu and wakeFailLogged (per-host in-memory note of the last journalled wake failure); declaration only, no read;rev3=census-ruling-w6-ingress-drain;basis=new field TenantStartsClosed func() bool; when it answers true tenantStartRefusal refuses every start, exempt routes included. Wired only by fixedAdmission.bind to the ingress drain's closed flag. Struct field only; no read added.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2: one field, replicaPolicies (host to the newest observed replica deploy and this box label, under mu), set only by SetReplicaDeploy; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: one more in-memory field, replicaFailed (host to the permit whose successor failed here, under mu), so that step only proves what it kept; declaration only, no read.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F fix round 3 (#511 F11): two hook fields, MarkReplicaRelease and ReplicaReleaseMark (the failure book's per-host release mark on this box's disk). No read site.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): one in-memory field, heldSeen (host to the last held release attempt, error class and when it was met), under the existing wakeFailMu. Declaration only, no read. 54221521b08b5c6af7bc00b251703ee3825f874547ad64da48ac1bc182c5df8b |
| +internal/activator/stateless.go Service.prepareStateless legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Capture RecordFacts from the existing record source, obtain the durable FailureBook deploy ID, and call Task 2 PrepareStatelessRelease with the canonical verdict/digest carrier. Carry a successful attempt through its hold only after another current-record check; no serving lease or polling loop. Fix 3a round 1 I2: preparation uses reconcile observations and records the successful deploy ID. Carry prepared evidence through hold; fresh backend read must confirm that same released deploy before web runs.;rev3=census-ruling-stateless-failed-release-held;basis=For recovery onto a different installed version's exact committed good version and artifact digest, retain recovery evidence without selecting or writing another deploy. Adds the existing committedGood registry read, with its route and incarnation check. Canonical storage declaration and observed lifetime gates remain.;rev3=census-ruling-stateless-replicas-4-task1;basis=R1: no longer calls ReplicaDeployID before preparation; hands the same a.ReplicaDeployID selector to prepareStatelessRelease, which calls it only after coordinator term acquisition. The ObservedReplicaRelease call stays as a validity check. Same read sites; no new read, write or authority.;rev3=census-ruling-stateless-replicas-4-task2;basis=Task 2 (D4): for a set row, prepares the record baseline with no release, and refuses a build the row Version does not name before any release; reads the route it is handed (FleetBoxes, Version). No store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix1;basis=Task 2 fix round 1: for a set row, a build its pointer does not name starts only as the record baseline or the committed permitted target, the latter adopted through prepareStatelessRelease durable path (never a new attempt); a named build, a rollback included, takes the release path. The added reads are the handed route (FleetBoxes, Version) and a copy of it with Stateless set for the adoption, as the release path already builds. No store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix2;basis=Task 2 fix round 2: for a set row the no-release start is decided per box from the record (this box baseline, or its permitted target adopted through the durable path), whatever the pointer says; only a build that is neither and that the pointer names begins a new attempt. Same reads (the handed route and its copy); no store read or write added.;rev3=census-ruling-stateless-replicas-4-task2-fix3;basis=Task 2 fix round 3: this box baseline is checked before the adopt path, so a completed box restarts on the target while a retry is requested; for the passed target it calls the existing escrow initializer (prepareStatelessEscrow) that the adopt path ran, with the same route and identity. No new reader; no record write.;rev3=census-ruling-stateless-replicas-4-task3f;basis=Task 3F (#511 F11): a hold's pinned wake carrying the swap's preparation, when the row it re-read differs from the prepared row, moves the preparation onto the wake's row only if the prepared row passes statelessCurrent against the registry, the two rows have the same Incarnation, ServingSeq, HoldOp and Version (sameRowLifetime, fix round 1), and the wake's row then passes statelessCurrent; otherwise it refuses with errStatelessRowChanged. The added sites are whole-Route comparisons and copies of the handed and prepared routes. No store read or write added; no new authority.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): a failed release preparation's error is wrapped with the attempt ID prepareStatelessRelease returned (withAttempt); the text and every errors.Is answer are unchanged. No read, write or authority added. registry:Account@284,registry:Account@310,registry:App@324,registry:App@346,registry:Digest@4803,registry:FleetBoxes@1967,registry:FleetBoxes@4446,registry:Host@250,registry:Host@273,registry:Stateless@3505,registry:Stateless@4030,registry:Stateless@5101,registry:Version@4338,registry:Version@4483,registry:Version@4773,whole:Route@1341,whole:Route@1348,whole:Route@1429,whole:Route@1437,whole:Route@1503,whole:Route@1623,whole:Route@1737,whole:Route@1844,whole:Route@259,whole:Route@2878,whole:Route@2885,whole:Route@293,whole:Route@333,whole:Route@3497,whole:Route@3584,whole:Route@4024,whole:Route@4110,whole:Route@4723,whole:Route@4867,whole:Route@4874,whole:Route@5097,whole:Route@5251,whole:Route@5378,whole:Route@5385,whole:Route@540,whole:Route@597,whole:Route@646,whole:Route@661 02cc71302cf90444ce289154bef79663690d7fa9da83793b1640e79c61faba22 |
| +internal/host/agent.go statusLoop legacy accepted-legacy accepted-legacy;rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's context carries the box's lifetime judge; read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 953b9fda (its later changes, regional box names and self-serve moves plan 1 among them, under main's own census rulings), where the tick fills rootfs_ready and rootfs_blocked from armedRootfs.Load().probe, which each tick runs NestedOK's checks and asks the control socket's GET /ready/rootfs (never the store); the same four direct sites;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: takes root's GET /egress reader and fills p.Egress = egressStatusProbe(egressStatus, routes, provision.PolicyReadStates()) and p.SizeCommittedMiB = sizeCommittedMiB(armedSizeSource.Load(), routes); the two added whole:Route sites are the tick's own registry list handed to those two units (decision rows), which read root's control socket and the activator's memory; no store request added; the four existing sites unchanged, offsets moved.;rev3=census-ruling-fleet-alerts-1;basis=the agent (carlos-edge.service, user carlos): the status tick passes os.Geteuid() to alertDeliveryProbe, which fills AlertDelivery.EngineBeat/EngineBeatWhy from engineBeatArmed (the env value and the euid only, no file access, root refused before the path is looked at), and fills Probes.DiskFullETAHours from diskETAProbe(&processDiskTrend, now), a Theil-Sen fit over the metrics loop's in-memory ring of disk readings; the same six sites, no read added, no store request added;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): the status tick's Probes gain HeldStreams: heldStreamsState(), which calls the edge's in-memory counters function (nil until the edge is ready). No file, bucket or registry access added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: read the detached in-memory replica snapshot source into Probes.ReplicaCopies on the existing five-minute tick. Existing six direct read sites unchanged. No additional bucket request, changed cadence or app lifecycle action.;rev3=census-ruling-agent-start-demo-3;basis=Report moved capability only when the serving edge reports readiness; report claim-seed support only with CARLOS_DEMO_CLAIM=1. Reads the explicit capability flag from the process environment; no new filesystem or registry read.;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 (#511 R16): the status tick fills Probes.PrevRelease from prevReleaseOf(release.OptDir()): a Stat of carlos.prev and a read of carlos.prev.version, the files the agent already reads for the edges file (withMovesFields). Reported in the private BoxMetrics block so the console counts a box at the stateless replicas floor only when its rollback binary is too. No bucket request or cadence change. whole:Route@10350,whole:Route@12164,whole:Route@12445,whole:Route@6583,whole:Route@6610,whole:Route@7918 58c8ab80612b1767e6c3f75d81f31bc91d73f31bc1a3dbf6cfa64b53c2dc6add |
| +internal/status/snapshot.go CollectBox legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;basis=copies Probes.RootfsReady and RootfsBlocked into BoxMetrics (private, like Layout); the same 28 sites, no read added;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Task 11 and #329 plan 3 Task 7: copies Probes.Egress and Probes.SizeCommittedMiB into BoxMetrics (private, like Layout) and counts them in the condition that builds Metrics; the same 28 sites, no read added.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3: comment only, the Hibernate count is left as is (display);rev3=census-ruling-regional-domains-447;basis=#447 Task 7: copies Probes.AliasesRead into BoxMetrics.AliasesRead (json aliases_read, omitempty) and counts it in the condition that builds Metrics; the same 28 sites, no read added;rev3=census-ruling-fleet-alerts-1;basis=copies Probes.DiskFullETAHours into BoxMetrics.DiskFullETAHours (json disk_full_eta_hours, omitempty; private, like Layout) and counts it in the condition that builds Metrics; the same 28 sites, no read added;rev3=census-ruling-edge-held-streams;basis=copies Probes.HeldStreams into BoxMetrics.HeldStreams (json held_streams, omitempty, additive) and counts it in the condition that builds Metrics; the same 28 sites, no read added.;rev3=census-ruling-stateless-replicas-3;basis=Fix round 1 Q20: carry already-supplied ReplicaCopies into a separate optional private BoxMetrics replica_copies field; allow copy evidence alone to create the metrics block. Upstreams retains address probes only. Existing 28 Route read sites unchanged; no filesystem, bucket, console or CLI read.;rev3=census-ruling-agent-start-demo-3;basis=Report claim-seed protocol capability only when explicitly configured and runtime moved readiness only when armed; dormant status keeps its original JSON shape. Census read-site delta: unchanged (28).;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 (#511 R16): copies Probes.PrevRelease into BoxMetrics.PrevRelease (json prev_release, omitempty; private, like Release) and counts it in the condition that builds Metrics; the same 28 sites, no read added. registry:Alias@4543,registry:CertExpiresAt@3160,registry:CertExpiresAt@3396,registry:CertExpiresAt@4658,registry:DBPath@2495,registry:DBPath@2553,registry:DNSCheckedAt@3365,registry:DNSCheckedAt@4627,registry:DNSStatus@3139,registry:DNSStatus@3334,registry:DNSStatus@4597,registry:Hibernate@3853,registry:Host@2295,registry:Host@2437,registry:Host@2666,registry:Host@3280,registry:Host@3315,registry:Host@4578,registry:Kind@2473,registry:Kind@3807,registry:Platform@2152,registry:ServingVersion@2324,registry:ServingVersion@2447,registry:Socket@4066,registry:Version@2186,registry:Version@2305,whole:Route@1581,whole:RouteAlias@4440 97987f62d0c54897da42c33cb9fa994bd316cdc9fc7813d7a1155d961f93afaa |
| +internal/host/movesfloor.go prevReleaseOf legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 (#511 R16): new, factored out of withMovesFields: Stat of <opt>/carlos.prev ("none" when absent, "" on another error) and readLine of <opt>/carlos.prev.version. The agent (carlos-edge.service, user carlos), not root; reads only root-written files under the opt dir, which withMovesFields already read. file:Stat@57 4d0f9e568555c0718bfce11731dfa8d76b5d4d1172b8824277309c51b6ae7176 |
| +internal/activator/rootfs_service.go Service.residentJob legacy accepted-legacy accepted-legacy;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 8: one proactive start of a resident: the same pre-lease admission as a request (rootfsStartRefusal, then the locked half under a.mu after re-checking the reservation, shutdown, hold and wait), then an ordinary wake of a resident entry; adds no gate a request does not pass;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 first commit (#511 F11): the "starting it" journal line is written only when heldNow(rt.Host) is false, an in-memory lookup of the host's held note; the added registry:Host site is that host string. No gate, read or start changes. registry:Host@1228,registry:Host@188,registry:Host@229,registry:Host@816,registry:Host@956,registry:Host@998,whole:Route@125,whole:Route@302,whole:Route@458,whole:Route@590,whole:Route@825,whole:Route@832,whole:Route@933 e18b39bd166c61e90fc9fdf7b972cd5df648fe5aa4c9e4094ac31edbd69bef15 |
| +internal/host/movesfloor.go withMovesFields authority F,J4 rev3=PROPOSED-p3;identity=carlos agent edgesFileLoop, carlos-edge.service uid carlos;basis=agent uses root-owned public projection when participating and its original writable mirror otherwise;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 (#511 R16): the carlos.prev Stat and version read move into prevReleaseOf, called here with the same opt dir; the same answers (none, unknown, or the version line). -file:Stat here is the same Stat inside prevReleaseOf. file:Lstat@238 53263336c86217d3b62183d615c7d436bc0a52e5e5aacd32e8fbeb369a17cd9d |
| +@coverage internal/activator 54315c8cfbba36ab032295435d34f91cc1d0df35c62ffafd1745f6dbd6b8f88a |
| +@coverage internal/host a4af4c3597c4c40c8ad808e595a189456205faafc6f0716bb9cd8d24c155ff2c |
| +@coverage internal/status fc9c0f5a9e3774772a368a2e752327329d129c6557f84f37dfc2e8ace572617a |
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go| index c897bd149..71a35eb79 100644 |
| --- a/internal/status/snapshot.go |
| +++ b/internal/status/snapshot.go |
| @@ -127,6 +127,11 @@ type Probes struct { |
| // unknown/not-applicable for both, never a guess. |
| Release string |
| Tunnel string |
| + // PrevRelease is the release of the box's rollback binary |
| + // (carlos.prev): "none" when it has none, "" when unknown. The console |
| + // counts a box at the stateless replicas floor only when this is at |
| + // the floor too, or "none" (#511 R16): a failed apply restores it. |
| + PrevRelease string |
| // GeoIP is the edge's GeoIP mirror state (geoip spec §5.5); nil when |
| // the edge has not published one (no edge yet, or an older binary). |
| GeoIP *GeoIPState |
| @@ -581,6 +586,7 @@ type BoxMetrics struct { |
| Load1 *float64 `json:"load1,omitempty"` |
| DiskFreeBytes *int64 `json:"disk_free_bytes,omitempty"` |
| Release string `json:"release,omitempty"` // running binary's version.Build |
| + PrevRelease string `json:"prev_release,omitempty"` // carlos.prev's release; "none": no carlos.prev |
| Platform string `json:"platform,omitempty"` // runtime.GOOS-runtime.GOARCH |
| SystemChannel string `json:"system_channel,omitempty"` // CARLOS_SYSTEM_CHANNEL |
| System *SystemState `json:"system,omitempty"` // last self-update outcome |
| @@ -1191,7 +1197,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| // exception is AliasesRead (#447): a successful read of no alias rows IS |
| // something to say, so it attaches the block on its own. |
| if p.MemTotalBytes != nil || p.MemAvailBytes != nil || p.Load1 != nil || |
| - p.DiskFreeBytes != nil || p.DiskFullETAHours != nil || p.Release != "" || p.Tunnel != "" || |
| + p.DiskFreeBytes != nil || p.DiskFullETAHours != nil || p.Release != "" || p.PrevRelease != "" || p.Tunnel != "" || |
| p.InstanceID != "" || p.Platform != "" || p.SystemChannel != "" || p.System != nil || |
| len(routeVersions) > 0 || len(routeServing) > 0 || len(aliasReadings) > 0 || p.AliasesRead || len(p.Upstreams) > 0 || len(p.ReplicaCopies) > 0 || |
| len(routeDBBytes) > 0 || p.Layout != nil || len(p.ConfigRefusals) > 0 || len(p.ReleaseRefusals) > 0 || len(p.ProofWaits) > 0 || p.Rollout != nil || p.ConfigGuard != "" || |
| @@ -1222,7 +1228,7 @@ func CollectBox(routes []registry.Route, p Probes, now time.Time) Box { |
| MemTotalBytes: p.MemTotalBytes, MemAvailBytes: p.MemAvailBytes, |
| Load1: p.Load1, DiskFreeBytes: p.DiskFreeBytes, DiskFullETAHours: p.DiskFullETAHours, |
| - Release: p.Release, Tunnel: p.Tunnel, GeoIP: p.GeoIP, HeldStreams: p.HeldStreams, |
| + Release: p.Release, PrevRelease: p.PrevRelease, Tunnel: p.Tunnel, GeoIP: p.GeoIP, HeldStreams: p.HeldStreams, |
| Platform: p.Platform, SystemChannel: p.SystemChannel, System: p.System, |
| InstanceID: p.InstanceID, |
| Alerts: p.Alerts, |
diff --git a/scripts/stateless-replicas-drill/accounting.go b/scripts/stateless-replicas-drill/accounting.go| new file mode 100644 |
| index 000000000..9bff8164b |
| --- /dev/null |
| +++ b/scripts/stateless-replicas-drill/accounting.go |
| @@ -0,0 +1,218 @@ |
| +package main |
| + |
| +import ( |
| + "fmt" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// The drill's phases. Warm-up and probe traffic is never measured: it is |
| +// sent before readiness, or to check readiness, and the hub's own health |
| +// probes are not drill traffic at all. |
| +const ( |
| + phaseWarmup = "warmup" |
| + phaseProbe = "probe" |
| + phaseSpread = "spread" |
| + phaseStop = "stop" |
| + phaseReturn = "return" |
| + phaseDeploy = "deploy" |
| + phaseFailing = "failing" |
| + phaseScaleDown = "scaledown" |
| +) |
| + |
| +// sampleID is the unique request id of request n of phase. It rides on |
| +// the request (a query parameter, so no cache can answer it) and the hub |
| +// and box request records name it, so every record can be traced to its |
| +// phase without the client's table. |
| +func sampleID(phase string, n int) string { |
| + return "drill-" + phase + "-" + strconv.Itoa(n) |
| +} |
| + |
| +// sample is one request the drill sent, as the client saw it. |
| +type sample struct { |
| + ID string `json:"id"` |
| + Phase string `json:"phase"` |
| + At time.Time `json:"at"` |
| + // Status is the response status, 0 when no response header arrived. |
| + Status int `json:"status"` |
| + // Started: the response headers arrived. Complete: the whole body did, |
| + // ending with the fixture's end marker. |
| + Started bool `json:"started"` |
| + Complete bool `json:"complete"` |
| + // Stream: the request asked the fixture for a streamed response. |
| + Stream bool `json:"stream,omitempty"` |
| + // Box and Build are what the fixture's response headers named. |
| + Box string `json:"box,omitempty"` |
| + Build string `json:"build,omitempty"` |
| + Err string `json:"err,omitempty"` |
| +} |
| + |
| +// tally is one measured window: the client's samples of one phase, |
| +// reconciled with the hub's and the boxes' request records (request id to |
| +// the box that served it). |
| +type tally struct { |
| + Phase string |
| + // Samples is the complete reads; ByBox splits them by the box the |
| + // response named; HubByBox and BoxRecords count the same reads by the |
| + // box each record names. |
| + Samples int |
| + ByBox, HubByBox, BoxRecords map[string]int |
| + // PreHeaderFailures is reads that failed before a response started, |
| + // or answered with a server error: failures, whatever was retried. |
| + PreHeaderFailures int |
| + // StreamCuts is responses that started and were cut before their end, |
| + // reported on their own. |
| + StreamCuts int |
| + // ProbeRequests is warm-up, probe or other non-window traffic that |
| + // reached the window's counts. It must be zero. |
| + ProbeRequests int |
| + // Problems is every way the client's table and the records disagree. |
| + // Any problem fails the window. |
| + Problems []string |
| +} |
| + |
| +// account tallies the window of phase. Only samples of that phase count; |
| +// only records whose id is of that phase are reconciled, and each of them |
| +// must have a sample, so a request the client lost cannot leave a passing |
| +// window behind. Each complete read must name one of the two drill boxes, |
| +// and both records must exist and name the same box. |
| +func account(samples []sample, hub, boxes map[string]string, cfg drillConfig, phase string) tally { |
| + t := tally{Phase: phase, ByBox: map[string]int{}, HubByBox: map[string]int{}, BoxRecords: map[string]int{}} |
| + prefix := sampleID(phase, 0) |
| + prefix = prefix[:len(prefix)-1] |
| + seen := map[string]bool{} |
| + problem := func(format string, args ...any) { t.Problems = append(t.Problems, fmt.Sprintf(format, args...)) } |
| + for _, s := range samples { |
| + if s.Phase != phase { |
| + continue |
| + } |
| + if !strings.HasPrefix(s.ID, prefix) { |
| + // Warm-up or probe traffic tagged as the window's: never |
| + // measured, and the window fails. |
| + t.ProbeRequests++ |
| + problem("sample %s is not a %s request", s.ID, phase) |
| + continue |
| + } |
| + if seen[s.ID] { |
| + problem("sample %s appears twice", s.ID) |
| + continue |
| + } |
| + seen[s.ID] = true |
| + switch { |
| + case !s.Started || s.Status == 0 || s.Status >= 500: |
| + t.PreHeaderFailures++ |
| + continue |
| + case !s.Complete: |
| + t.StreamCuts++ |
| + continue |
| + } |
| + t.Samples++ |
| + if s.Box != cfg.BoxA && s.Box != cfg.BoxB { |
| + problem("sample %s names box %q, not %s or %s", s.ID, s.Box, cfg.BoxA, cfg.BoxB) |
| + } |
| + t.ByBox[s.Box]++ |
| + for _, r := range []struct { |
| + name string |
| + records map[string]string |
| + count map[string]int |
| + }{{"hub", hub, t.HubByBox}, {"box", boxes, t.BoxRecords}} { |
| + box, ok := r.records[s.ID] |
| + switch { |
| + case !ok: |
| + problem("sample %s has no %s record", s.ID, r.name) |
| + case box != s.Box: |
| + problem("sample %s: the %s record names %s, the response %s", s.ID, r.name, box, s.Box) |
| + default: |
| + r.count[box]++ |
| + } |
| + } |
| + } |
| + for _, records := range []map[string]string{hub, boxes} { |
| + for id := range records { |
| + if strings.HasPrefix(id, prefix) && !seen[id] { |
| + problem("record %s has no sample", id) |
| + } |
| + } |
| + } |
| + sort.Strings(t.Problems) |
| + return t |
| +} |
| + |
| +// spreadBounds are the even-spread window's limits on each box's share. |
| +const spreadLow, spreadHigh = 0.45, 0.55 |
| + |
| +// windowPassed is whether a measured window passes, and why not: no |
| +// problem in its table, no read failed before its headers, at least min |
| +// complete reads, and each drill box serving 45%-55% of them. A cut stream |
| +// is reported, not failed, unless the window has no complete read at all. |
| +func windowPassed(t tally, cfg drillConfig, min int) (bool, string) { |
| + switch { |
| + case len(t.Problems) > 0: |
| + return false, fmt.Sprintf("%d request record problems, first: %s", len(t.Problems), t.Problems[0]) |
| + case t.ProbeRequests != 0: |
| + return false, fmt.Sprintf("%d probe requests were counted", t.ProbeRequests) |
| + case t.PreHeaderFailures != 0: |
| + return false, fmt.Sprintf("%d reads failed before their headers", t.PreHeaderFailures) |
| + case t.Samples < min || t.Samples == 0: |
| + return false, fmt.Sprintf("%d complete reads, fewer than %d", t.Samples, min) |
| + } |
| + for _, box := range []string{cfg.BoxA, cfg.BoxB} { |
| + share := float64(t.ByBox[box]) / float64(t.Samples) |
| + if share < spreadLow || share > spreadHigh { |
| + return false, fmt.Sprintf("%s served %.1f%% of reads", box, 100*share) |
| + } |
| + } |
| + return true, "" |
| +} |
| + |
| +// orderedSwitch is whether a deploy's reads show its copies switching from |
| +// build from to build to one box at a time: every read names one of the |
| +// two builds, every box ends on to, and the boxes are ordered by their |
| +// first read of to so that each box's first new-build read comes after |
| +// every earlier box's last old-build read. Two boxes serving the new build |
| +// while an earlier one still serves the old is not ordered. |
| +func orderedSwitch(samples []sample, from, to string) (bool, string) { |
| + firstNew, lastOld := map[string]time.Time{}, map[string]time.Time{} |
| + boxes := map[string]bool{} |
| + for _, s := range samples { |
| + if !s.Complete { |
| + continue |
| + } |
| + boxes[s.Box] = true |
| + switch s.Build { |
| + case from: |
| + if s.At.After(lastOld[s.Box]) { |
| + lastOld[s.Box] = s.At |
| + } |
| + case to: |
| + if f, ok := firstNew[s.Box]; !ok || s.At.Before(f) { |
| + firstNew[s.Box] = s.At |
| + } |
| + default: |
| + return false, fmt.Sprintf("read %s served build %q", s.ID, s.Build) |
| + } |
| + } |
| + if len(boxes) < 2 { |
| + return false, "the deploy's reads reached fewer than two boxes" |
| + } |
| + order := make([]string, 0, len(boxes)) |
| + for box := range boxes { |
| + if _, ok := firstNew[box]; !ok { |
| + return false, fmt.Sprintf("%s never served %s", box, to) |
| + } |
| + // An old read on a box after its own first new one is that box's |
| + // overlap draining; it must still end before the next box starts. |
| + order = append(order, box) |
| + } |
| + sort.Slice(order, func(i, j int) bool { return firstNew[order[i]].Before(firstNew[order[j]]) }) |
| + for i := 1; i < len(order); i++ { |
| + for _, earlier := range order[:i] { |
| + if !lastOld[earlier].IsZero() && !lastOld[earlier].Before(firstNew[order[i]]) { |
| + return false, fmt.Sprintf("%s served %s until %s, after %s started %s", earlier, from, lastOld[earlier].Format(time.RFC3339Nano), order[i], to) |
| + } |
| + } |
| + } |
| + return true, "" |
| +} |
diff --git a/scripts/stateless-replicas-drill/accounting_test.go b/scripts/stateless-replicas-drill/accounting_test.go| new file mode 100644 |
| index 000000000..137772507 |
| --- /dev/null |
| +++ b/scripts/stateless-replicas-drill/accounting_test.go |
| @@ -0,0 +1,164 @@ |
| +package main |
| + |
| +import ( |
| + "fmt" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// drillFixture is a deterministic measured window over boxes a and b: |
| +// warm-up and probe traffic, 40 complete reads split 20/20, one read that |
| +// failed before any header, and one stream cut after its headers. The hub |
| +// and box request records hold every complete read, plus probe traffic the |
| +// drill never sent as a sample. |
| +func drillFixture() ([]sample, map[string]string, map[string]string) { |
| + at := time.Unix(1_800_000_000, 0) |
| + var samples []sample |
| + hub, boxes := map[string]string{}, map[string]string{} |
| + add := func(s sample) { |
| + s.At = at.Add(time.Duration(len(samples)) * 50 * time.Millisecond) |
| + samples = append(samples, s) |
| + } |
| + for i := 0; i < 5; i++ { |
| + id := sampleID(phaseWarmup, i) |
| + add(sample{ID: id, Phase: phaseWarmup, Status: 200, Started: true, Complete: true, Box: "a"}) |
| + hub[id], boxes[id] = "a", "a" |
| + } |
| + for i := 0; i < 40; i++ { |
| + id := sampleID(phaseSpread, i) |
| + box := []string{"a", "b"}[i%2] |
| + add(sample{ID: id, Phase: phaseSpread, Status: 200, Started: true, Complete: true, Box: box}) |
| + hub[id], boxes[id] = box, box |
| + } |
| + add(sample{ID: "drill-spread-fail", Phase: phaseSpread, Err: "connection reset before headers"}) |
| + add(sample{ID: "drill-spread-cut", Phase: phaseSpread, Status: 200, Started: true, Stream: true, Box: "b", Err: "unexpected EOF"}) |
| + hub["drill-spread-cut"], boxes["drill-spread-cut"] = "b", "b" |
| + // The hub's own health probes and a readiness probe the drill made: |
| + // in the records, never a sample of the window. |
| + hub["probe-1"], boxes["probe-1"] = "a", "a" |
| + hub["drill-probe-0"], boxes["drill-probe-0"] = "b", "b" |
| + add(sample{ID: "drill-probe-0", Phase: phaseProbe, Status: 200, Started: true, Complete: true, Box: "b"}) |
| + return samples, hub, boxes |
| +} |
| + |
| +func TestReplicaDrillAccounting(t *testing.T) { |
| + cfg := drillConfig{BoxA: "a", BoxB: "b"} |
| + samples, hub, boxes := drillFixture() |
| + got := account(samples, hub, boxes, cfg, phaseSpread) |
| + preHeaderFailures, streamCuts, probeRequests := got.PreHeaderFailures, got.StreamCuts, got.ProbeRequests |
| + // TestReplicaDrillAccounting |
| + if preHeaderFailures != 1 || streamCuts != 1 || probeRequests != 0 { |
| + t.Fatal("drill hid failures or counted probe traffic") |
| + } |
| + if got.Samples != 40 || got.ByBox["a"] != 20 || got.ByBox["b"] != 20 || len(got.Problems) != 0 { |
| + t.Fatalf("window = %+v", got) |
| + } |
| + // Per-box and hub counts reconcile with the client's. |
| + for _, box := range []string{"a", "b"} { |
| + if got.HubByBox[box] != got.ByBox[box] || got.BoxRecords[box] != got.ByBox[box] { |
| + t.Fatalf("%s: client %d hub %d box %d", box, got.ByBox[box], got.HubByBox[box], got.BoxRecords[box]) |
| + } |
| + } |
| + // A failed read fails the window, though the spread is even. |
| + if ok, why := windowPassed(got, cfg, 40); ok || !strings.Contains(why, "failed before") { |
| + t.Fatalf("a pre-header failure passed: %v %q", ok, why) |
| + } |
| + |
| + // Table errors never turn a missing sample into a pass. |
| + clean := func() ([]sample, map[string]string, map[string]string) { |
| + s, h, b := drillFixture() |
| + var kept []sample |
| + for _, x := range s { |
| + if x.ID != "drill-spread-fail" { |
| + kept = append(kept, x) |
| + } |
| + } |
| + return kept, h, b |
| + } |
| + s, h, b := clean() |
| + if ok, why := windowPassed(account(s, h, b, cfg, phaseSpread), cfg, 40); !ok { |
| + t.Fatalf("the clean window failed: %s", why) |
| + } |
| + for name, edit := range map[string]func(s *[]sample, h, b map[string]string){ |
| + "hub record missing": func(_ *[]sample, h, _ map[string]string) { delete(h, "drill-spread-7") }, |
| + "box record missing": func(_ *[]sample, _, b map[string]string) { delete(b, "drill-spread-8") }, |
| + "records disagree": func(_ *[]sample, h, _ map[string]string) { h["drill-spread-9"] = "a" }, |
| + "record without a sample": func(s *[]sample, _, _ map[string]string) { |
| + for i, x := range *s { |
| + if x.ID == "drill-spread-11" { |
| + *s = append((*s)[:i], (*s)[i+1:]...) |
| + break |
| + } |
| + } |
| + }, |
| + "unknown box": func(s *[]sample, h, b map[string]string) { |
| + (*s)[10].Box, h[(*s)[10].ID], b[(*s)[10].ID] = "c", "c", "c" |
| + }, |
| + "too few samples": func(s *[]sample, _, _ map[string]string) { *s = (*s)[:20] }, |
| + "uneven spread": func(s *[]sample, h, b map[string]string) { unevenSpread(*s, h, b) }, |
| + "empty table": func(s *[]sample, _, _ map[string]string) { *s = nil }, |
| + "no hub records": func(_ *[]sample, h, _ map[string]string) { clear(h) }, |
| + "stream cut, no reads": func(s *[]sample, _, _ map[string]string) { onlyCuts(*s) }, |
| + "probe tagged as the window": func(s *[]sample, h, b map[string]string) { |
| + id := sampleID(phaseProbe, 9) |
| + *s = append(*s, sample{ID: id, Phase: phaseSpread, Status: 200, Started: true, Complete: true, Box: "a"}) |
| + h[id], b[id] = "a", "a" |
| + }, |
| + } { |
| + t.Run(name, func(t *testing.T) { |
| + s, h, b := clean() |
| + edit(&s, h, b) |
| + if ok, why := windowPassed(account(s, h, b, cfg, phaseSpread), cfg, 40); ok { |
| + t.Fatalf("passed with %s", name) |
| + } else if why == "" { |
| + t.Fatal("refused without a reason") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// unevenSpread moves the window's reads to 70% on a. |
| +func unevenSpread(s []sample, h, b map[string]string) { |
| + n := 0 |
| + for i := range s { |
| + if s[i].Phase == phaseSpread && s[i].Complete && s[i].Box == "b" && n < 8 { |
| + s[i].Box, h[s[i].ID], b[s[i].ID] = "a", "a", "a" |
| + n++ |
| + } |
| + } |
| +} |
| + |
| +// onlyCuts makes every read of the window a cut stream. |
| +func onlyCuts(s []sample) { |
| + for i := range s { |
| + if s[i].Phase == phaseSpread { |
| + s[i].Complete, s[i].Stream = false, true |
| + } |
| + } |
| +} |
| + |
| +// TestReplicaDrillOrderedSwitch: a deploy's copies switch one box at a |
| +// time. The first box's last old-build read comes before the second box's |
| +// first new-build read; two boxes on the new build while neither finished |
| +// with the old one is not ordered. |
| +func TestReplicaDrillOrderedSwitch(t *testing.T) { |
| + at := time.Unix(1_800_000_000, 0) |
| + read := func(sec int, box, build string) sample { |
| + return sample{ID: fmt.Sprintf("drill-deploy-%d-%s", sec, box), Phase: phaseDeploy, At: at.Add(time.Duration(sec) * time.Second), Status: 200, Started: true, Complete: true, Box: box, Build: build} |
| + } |
| + ordered := []sample{read(1, "a", "v1"), read(1, "b", "v1"), read(2, "a", "v2"), read(3, "b", "v1"), read(4, "a", "v2"), read(5, "b", "v2")} |
| + if ok, why := orderedSwitch(ordered, "v1", "v2"); !ok { |
| + t.Fatalf("ordered switch refused: %s", why) |
| + } |
| + together := []sample{read(1, "a", "v1"), read(1, "b", "v1"), read(2, "a", "v2"), read(2, "b", "v2"), read(3, "a", "v1")} |
| + if ok, _ := orderedSwitch(together, "v1", "v2"); ok { |
| + t.Fatal("both boxes switched at once and passed") |
| + } |
| + if ok, _ := orderedSwitch(ordered[:2], "v1", "v2"); ok { |
| + t.Fatal("a deploy that never switched passed") |
| + } |
| + if ok, _ := orderedSwitch(append(ordered, read(6, "b", "v3")), "v1", "v2"); ok { |
| + t.Fatal("a third build passed") |
| + } |
| +} |
diff --git a/scripts/stateless-replicas-drill/main.go b/scripts/stateless-replicas-drill/main.go| new file mode 100644 |
| index 000000000..360a3fe6d |
| --- /dev/null |
| +++ b/scripts/stateless-replicas-drill/main.go |
| @@ -0,0 +1,618 @@ |
| +// Command stateless-replicas-drill runs the two-box dev drill for |
| +// stateless replicas (#511 Plan 4, rulings D12 and R17). It is isolated |
| +// tooling: nothing in the platform imports it. |
| +// |
| +// It holds no provider credential. It reads state only through the |
| +// operator's logged-in carlos CLI and the fixture app's public responses, |
| +// and it stops for the operator at every point that changes anything: the |
| +// hard-stop and return of a box, the deploys and the scale-down. A run is |
| +// one booked window on a pre-approved drill fleet (D12); it never stops an |
| +// HA group member or a fixed HA box. |
| +// |
| +// The fixture app (a small Rails app with external Postgres and Redis, a |
| +// worker that records heartbeats, a repeat-safe release counter and a |
| +// websocket endpoint) answers: |
| +// |
| +// GET /drill?id=<id> 200, headers X-Drill-Box and X-Drill-Build, |
| +// a body ending "\nend\n" |
| +// GET /drill/stream?id=<id> the same, streamed over about two seconds |
| +// GET /drill/state JSON {"release_count": n, |
| +// "heartbeats": {"<box>": "<RFC 3339>"}} |
| +// GET /cable a websocket upgrade |
| +// |
| +// X-Drill-Box is the label of the fleet box the copy runs on, as given to |
| +// the fixture's environment. The hub's and the boxes' request records are |
| +// exported by the operator, one JSON object per line ({"id": ..., "box": |
| +// ...}), to hub-records.jsonl and box-records.jsonl in the output |
| +// directory when the drill asks for them. |
| +// |
| +// The drill measures the trimmed list (R17): the even spread; a hard-stop |
| +// with zero failed reads before headers, the live "1 of 2", worker |
| +// heartbeats and websocket reconnect; the box's return and the spread |
| +// evening again; one good deploy under load (the release runs once, the |
| +// copies switch in order) and one failing release; and scale-down to one |
| +// copy. The view and reconnect times are observations, not limits. |
| +package main |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "os" |
| + "os/exec" |
| + "os/signal" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +// drillConfig names the drill's window: the console the operator's CLI is |
| +// logged in to, the fixture's account, app and instance host, the drill |
| +// fleet and its two boxes, where the evidence goes, and the load. |
| +type drillConfig struct { |
| + Console, Account, App, Host, Fleet, BoxA, BoxB, OutputDir string |
| + Duration time.Duration |
| + Rate int |
| +} |
| + |
| +// drillReport is the drill's result. Tip is the platform build the drill |
| +// ran against (its git tip). Samples, PreHeaderFailures and StreamCuts sum |
| +// every measured window; ReleaseRuns is how many times the good deploy's |
| +// release command ran; ByBox is the even-spread window's complete reads by |
| +// box; MaxReconnect is the longest websocket reconnect seen. Ordered is |
| +// whether the good deploy's copies switched one box at a time. Passed is |
| +// true only when every check passed. |
| +type drillReport struct { |
| + Tip string |
| + Samples, PreHeaderFailures, StreamCuts, ReleaseRuns int |
| + ByBox map[string]int |
| + MaxReconnect time.Duration |
| + Ordered, Passed bool |
| +} |
| + |
| +// minSpreadReads is the fewest complete reads an even-spread window |
| +// counts over. |
| +const minSpreadReads = 2000 |
| + |
| +// drillSummary (SR-4-C32, provisional) takes box A's share, box A, box B's |
| +// share, box B, the failed reads, the cut streams and the reconnect. |
| +const drillSummary = "spread: %.0f%% on %s, %.0f%% on %s; failed reads before headers: %d; cut streams: %d; websocket reconnect: %.1fs" |
| + |
| +// drillFailed (SR-4-C33, provisional) takes the reason. |
| +const drillFailed = "the dev drill did not pass: %s. restore the stopped box and complete cleanup before closing this session" |
| + |
| +func main() { |
| + var cfg drillConfig |
| + flag.StringVar(&cfg.Console, "console", "", "console the carlos CLI is logged in to") |
| + flag.StringVar(&cfg.Account, "account", "", "the fixture app's account") |
| + flag.StringVar(&cfg.App, "app", "shop", "the fixture app") |
| + flag.StringVar(&cfg.Host, "host", "", "the fixture instance's host, for example shop.example.com") |
| + flag.StringVar(&cfg.Fleet, "fleet", "", "the drill fleet") |
| + flag.StringVar(&cfg.BoxA, "box-a", "", "the first drill box's label") |
| + flag.StringVar(&cfg.BoxB, "box-b", "", "the second drill box's label, the one hard-stopped") |
| + flag.StringVar(&cfg.OutputDir, "out", "", "directory for the drill's evidence") |
| + flag.DurationVar(&cfg.Duration, "duration", 10*time.Minute, "length of each even-spread window") |
| + flag.IntVar(&cfg.Rate, "rate", 20, "GET requests a second") |
| + flag.Parse() |
| + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) |
| + defer stop() |
| + report, err := runDrill(ctx, cfg) |
| + if cfg.OutputDir != "" { |
| + if raw, jerr := json.MarshalIndent(report, "", " "); jerr == nil { |
| + _ = os.WriteFile(filepath.Join(cfg.OutputDir, "report.json"), raw, 0o644) |
| + } |
| + } |
| + if err != nil { |
| + fmt.Fprintf(os.Stderr, drillFailed+"\n", err) |
| + os.Exit(1) |
| + } |
| + if !report.Passed { |
| + fmt.Fprintf(os.Stderr, drillFailed+"\n", "a check failed; see report.json and drill.log") |
| + os.Exit(1) |
| + } |
| +} |
| + |
| +// drill is one run's state: the configuration, the HTTP client, the |
| +// evidence log and every sample sent. |
| +type drill struct { |
| + cfg drillConfig |
| + client *http.Client |
| + in *bufio.Reader |
| + mu sync.Mutex |
| + samples []sample |
| + seq map[string]int |
| + log *os.File |
| +} |
| + |
| +// runDrill runs the whole drill and returns its report. It returns an |
| +// error for anything that stops the drill early; a check that fails is a |
| +// report with Passed false and the reason in drill.log. |
| +func runDrill(ctx context.Context, cfg drillConfig) (drillReport, error) { |
| + report := drillReport{ByBox: map[string]int{}} |
| + if cfg.Host == "" || cfg.BoxA == "" || cfg.BoxB == "" || cfg.BoxA == cfg.BoxB || cfg.OutputDir == "" || cfg.Rate < 1 || cfg.Duration <= 0 { |
| + return report, errors.New("set --host, two different boxes, --out, a positive --rate and --duration") |
| + } |
| + if err := os.MkdirAll(cfg.OutputDir, 0o755); err != nil { |
| + return report, err |
| + } |
| + logf, err := os.Create(filepath.Join(cfg.OutputDir, "drill.log")) |
| + if err != nil { |
| + return report, err |
| + } |
| + defer logf.Close() |
| + d := &drill{cfg: cfg, client: &http.Client{Timeout: 30 * time.Second}, in: bufio.NewReader(os.Stdin), seq: map[string]int{}, log: logf} |
| + if out, err := exec.CommandContext(ctx, "git", "rev-parse", "HEAD").Output(); err == nil { |
| + report.Tip = strings.TrimSpace(string(out)) |
| + } |
| + d.note("drill start: tip %s, %+v", report.Tip, cfg) |
| + failed := []string{} |
| + fail := func(format string, args ...any) { |
| + msg := fmt.Sprintf(format, args...) |
| + failed = append(failed, msg) |
| + d.note("FAILED: %s", msg) |
| + } |
| + |
| + // Readiness: probe traffic until both boxes have answered, never |
| + // measured. |
| + if err := d.ready(ctx); err != nil { |
| + return report, err |
| + } |
| + d.load(ctx, phaseWarmup, 30*time.Second) |
| + |
| + // 1. The even spread. |
| + d.load(ctx, phaseSpread, cfg.Duration) |
| + |
| + // 2. Hard-stop box B under load: no failed read before headers, the |
| + // live view's 1 of 2, the survivor's worker heartbeats and the |
| + // websocket's reconnect. |
| + before, err := d.state(ctx) |
| + if err != nil { |
| + return report, err |
| + } |
| + ws := d.watchSocket(ctx) |
| + stopped := make(chan time.Time, 1) |
| + view := make(chan time.Duration, 1) |
| + go func() { |
| + at := <-stopped |
| + view <- d.untilCopies(ctx, at, 1, 2) |
| + }() |
| + d.loadAround(ctx, phaseStop, 2*time.Minute, func() { |
| + d.operator("hard-stop %s now through the approved operator action, then press enter", cfg.BoxB) |
| + stopped <- time.Now() |
| + }) |
| + d.note("observation: the live view showed 1 of 2 copies %s after the stop", <-view) |
| + after, err := d.state(ctx) |
| + if err != nil { |
| + return report, err |
| + } |
| + if !after.Heartbeats[cfg.BoxA].After(before.Heartbeats[cfg.BoxA]) { |
| + fail("the worker on %s recorded no heartbeat while %s was stopped", cfg.BoxA, cfg.BoxB) |
| + } |
| + report.MaxReconnect = ws.stop() |
| + d.note("observation: the longest websocket reconnect was %s", report.MaxReconnect) |
| + |
| + // 3. Box B returns; the spread evens again. |
| + d.operator("start %s again through the approved operator action, and press enter once its agent and tunnel are back", cfg.BoxB) |
| + back := time.Now() |
| + d.note("observation: the live view showed 2 of 2 copies %s after the return", d.untilCopies(ctx, back, 2, 2)) |
| + d.load(ctx, phaseReturn, cfg.Duration) |
| + |
| + // 4. One good deploy under load: the release runs once, the copies |
| + // switch in order. Then one failing release: no copy moves. |
| + from := d.servingBuild() |
| + d.loadAround(ctx, phaseDeploy, 5*time.Minute, func() { |
| + d.operator("deploy a new good build of %s now (carlos deploy), then press enter", cfg.App) |
| + }) |
| + deployed, err := d.state(ctx) |
| + if err != nil { |
| + return report, err |
| + } |
| + report.ReleaseRuns = deployed.ReleaseCount - after.ReleaseCount |
| + if report.ReleaseRuns != 1 { |
| + fail("the good deploy's release command ran %d times, not once", report.ReleaseRuns) |
| + } |
| + to := d.lastBuild(phaseDeploy) |
| + var why string |
| + report.Ordered, why = orderedSwitch(d.phase(phaseDeploy), from, to) |
| + if !report.Ordered { |
| + fail("the good deploy did not switch in order: %s", why) |
| + } |
| + d.loadAround(ctx, phaseFailing, 3*time.Minute, func() { |
| + d.operator("deploy a build of %s whose release command fails, then press enter once the deploy has stopped", cfg.App) |
| + }) |
| + for _, s := range d.phase(phaseFailing) { |
| + if s.Complete && s.Build != to { |
| + fail("read %s served build %q during the failing release", s.ID, s.Build) |
| + break |
| + } |
| + } |
| + |
| + // 5. Scale down to one copy. |
| + d.operator("run: carlos apps set %s --copies 1, then press enter", cfg.App) |
| + d.note("observation: the live view showed 1 of 1 copies %s after the scale-down", d.untilCopies(ctx, time.Now(), 1, 1)) |
| + |
| + // The request records, then the accounting of every measured window. |
| + d.operator("export the hub's and the boxes' request records for this window to %s and %s, then press enter", |
| + filepath.Join(cfg.OutputDir, "hub-records.jsonl"), filepath.Join(cfg.OutputDir, "box-records.jsonl")) |
| + hub, herr := readRecords(filepath.Join(cfg.OutputDir, "hub-records.jsonl")) |
| + boxes, berr := readRecords(filepath.Join(cfg.OutputDir, "box-records.jsonl")) |
| + if herr != nil || berr != nil { |
| + fail("request records unreadable: %v %v", herr, berr) |
| + } |
| + all := d.all() |
| + for _, phase := range []string{phaseSpread, phaseStop, phaseReturn, phaseDeploy, phaseFailing} { |
| + t := account(all, hub, boxes, cfg, phase) |
| + report.Samples += t.Samples |
| + report.PreHeaderFailures += t.PreHeaderFailures |
| + report.StreamCuts += t.StreamCuts |
| + d.note("window %s: %d reads %v, hub %v, boxes %v, %d failed before headers, %d cut streams, %d problems", |
| + phase, t.Samples, t.ByBox, t.HubByBox, t.BoxRecords, t.PreHeaderFailures, t.StreamCuts, len(t.Problems)) |
| + for _, p := range t.Problems { |
| + d.note(" %s", p) |
| + } |
| + switch phase { |
| + case phaseSpread, phaseReturn: |
| + if phase == phaseSpread { |
| + report.ByBox = t.ByBox |
| + } |
| + if ok, why := windowPassed(t, cfg, minSpreadReads); !ok { |
| + fail("%s window: %s", phase, why) |
| + } |
| + default: |
| + if len(t.Problems) > 0 || t.PreHeaderFailures > 0 || t.ProbeRequests > 0 { |
| + fail("%s window: %d problems, %d reads failed before headers", phase, len(t.Problems), t.PreHeaderFailures) |
| + } |
| + } |
| + } |
| + if raw, err := json.Marshal(all); err == nil { |
| + _ = os.WriteFile(filepath.Join(cfg.OutputDir, "samples.json"), raw, 0o644) |
| + } |
| + n := report.ByBox[cfg.BoxA] + report.ByBox[cfg.BoxB] |
| + if n > 0 { |
| + d.note(drillSummary, 100*float64(report.ByBox[cfg.BoxA])/float64(n), cfg.BoxA, 100*float64(report.ByBox[cfg.BoxB])/float64(n), cfg.BoxB, |
| + report.PreHeaderFailures, report.StreamCuts, report.MaxReconnect.Seconds()) |
| + } |
| + report.Passed = len(failed) == 0 |
| + return report, nil |
| +} |
| + |
| +// note writes a timestamped line to drill.log and to the terminal. |
| +func (d *drill) note(format string, args ...any) { |
| + line := time.Now().UTC().Format(time.RFC3339Nano) + " " + fmt.Sprintf(format, args...) |
| + fmt.Println(line) |
| + fmt.Fprintln(d.log, line) |
| +} |
| + |
| +// operator waits for the operator's explicit action. |
| +func (d *drill) operator(format string, args ...any) { |
| + d.note("OPERATOR: "+format, args...) |
| + _, _ = d.in.ReadString('\n') |
| + d.note("operator done") |
| +} |
| + |
| +// ready sends probe reads until both boxes have answered one. |
| +func (d *drill) ready(ctx context.Context) error { |
| + seen := map[string]bool{} |
| + deadline := time.Now().Add(5 * time.Minute) |
| + for !seen[d.cfg.BoxA] || !seen[d.cfg.BoxB] { |
| + if time.Now().After(deadline) { |
| + return fmt.Errorf("both boxes did not answer within 5 minutes (answered: %v)", seen) |
| + } |
| + s := d.read(ctx, phaseProbe, false) |
| + if s.Complete { |
| + seen[s.Box] = true |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-time.After(200 * time.Millisecond): |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// load sends Rate reads a second of phase for dur; one in twenty is a |
| +// streamed read. |
| +func (d *drill) load(ctx context.Context, phase string, dur time.Duration) { |
| + d.note("load %s for %s at %d/s", phase, dur, d.cfg.Rate) |
| + ctx, cancel := context.WithTimeout(ctx, dur) |
| + defer cancel() |
| + tick := time.NewTicker(time.Second / time.Duration(d.cfg.Rate)) |
| + defer tick.Stop() |
| + var wg sync.WaitGroup |
| + for n := 0; ; n++ { |
| + select { |
| + case <-ctx.Done(): |
| + wg.Wait() |
| + return |
| + case <-tick.C: |
| + } |
| + wg.Add(1) |
| + go func(stream bool) { |
| + defer wg.Done() |
| + d.read(context.WithoutCancel(ctx), phase, stream) |
| + }(n%20 == 19) |
| + } |
| +} |
| + |
| +// loadAround runs load for dur while act, the operator's step, runs. |
| +func (d *drill) loadAround(ctx context.Context, phase string, dur time.Duration, act func()) { |
| + done := make(chan struct{}) |
| + go func() { |
| + d.load(ctx, phase, dur) |
| + close(done) |
| + }() |
| + act() |
| + <-done |
| +} |
| + |
| +// read sends one uniquely named read and records how it went. |
| +func (d *drill) read(ctx context.Context, phase string, stream bool) sample { |
| + d.mu.Lock() |
| + id := sampleID(phase, d.seq[phase]) |
| + d.seq[phase]++ |
| + d.mu.Unlock() |
| + path := "/drill" |
| + if stream { |
| + path = "/drill/stream" |
| + } |
| + s := sample{ID: id, Phase: phase, At: time.Now(), Stream: stream} |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+d.cfg.Host+path+"?id="+id, nil) |
| + if err == nil { |
| + req.Header.Set("Cache-Control", "no-cache") |
| + var res *http.Response |
| + if res, err = d.client.Do(req); err == nil { |
| + s.Started, s.Status = true, res.StatusCode |
| + s.Box, s.Build = res.Header.Get("X-Drill-Box"), res.Header.Get("X-Drill-Build") |
| + var body []byte |
| + body, err = io.ReadAll(res.Body) |
| + res.Body.Close() |
| + s.Complete = err == nil && strings.HasSuffix(string(body), "\nend\n") |
| + } |
| + } |
| + if err != nil { |
| + s.Err = err.Error() |
| + } |
| + d.mu.Lock() |
| + d.samples = append(d.samples, s) |
| + d.mu.Unlock() |
| + return s |
| +} |
| + |
| +// all is every sample so far. |
| +func (d *drill) all() []sample { |
| + d.mu.Lock() |
| + defer d.mu.Unlock() |
| + return append([]sample(nil), d.samples...) |
| +} |
| + |
| +// phase is the samples of one phase. |
| +func (d *drill) phase(p string) []sample { |
| + var out []sample |
| + for _, s := range d.all() { |
| + if s.Phase == p { |
| + out = append(out, s) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// servingBuild is the build the latest complete read served. |
| +func (d *drill) servingBuild() string { |
| + all := d.all() |
| + for i := len(all) - 1; i >= 0; i-- { |
| + if all[i].Complete { |
| + return all[i].Build |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// lastBuild is the build the last complete read of phase served. |
| +func (d *drill) lastBuild(phase string) string { |
| + s := d.phase(phase) |
| + for i := len(s) - 1; i >= 0; i-- { |
| + if s[i].Complete { |
| + return s[i].Build |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// fixtureState is the fixture's GET /drill/state. |
| +type fixtureState struct { |
| + ReleaseCount int `json:"release_count"` |
| + Heartbeats map[string]time.Time `json:"heartbeats"` |
| +} |
| + |
| +// state reads the fixture's release counter and worker heartbeats. |
| +func (d *drill) state(ctx context.Context) (fixtureState, error) { |
| + var st fixtureState |
| + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+d.cfg.Host+"/drill/state", nil) |
| + if err != nil { |
| + return st, err |
| + } |
| + req.Header.Set("Cache-Control", "no-cache") |
| + res, err := d.client.Do(req) |
| + if err != nil { |
| + return st, err |
| + } |
| + defer res.Body.Close() |
| + if res.StatusCode != http.StatusOK { |
| + return st, fmt.Errorf("fixture state: %s", res.Status) |
| + } |
| + err = json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&st) |
| + d.note("fixture state: %+v", st) |
| + return st, err |
| +} |
| + |
| +// untilCopies polls carlos instances list until the host shows healthy of |
| +// total copies, and returns how long after since that took (an |
| +// observation; it gives up after 10 minutes). |
| +func (d *drill) untilCopies(ctx context.Context, since time.Time, healthy, total int) time.Duration { |
| + for time.Since(since) < 10*time.Minute { |
| + args := []string{"instances", "list", "--app", d.cfg.App, "--match", d.cfg.Host} |
| + if d.cfg.Account != "" { |
| + args = append(args, "--account", d.cfg.Account) |
| + } |
| + if d.cfg.Console != "" { |
| + args = append(args, "--console", d.cfg.Console) |
| + } |
| + out, err := exec.CommandContext(ctx, "carlos", args...).Output() |
| + if err == nil { |
| + h, n := copiesOf(string(out), d.cfg.Host) |
| + if h == healthy && n == total { |
| + d.note("carlos instances list:\n%s", out) |
| + return time.Since(since) |
| + } |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return time.Since(since) |
| + case <-time.After(250 * time.Millisecond): |
| + } |
| + } |
| + d.note("the live view never showed %d of %d copies", healthy, total) |
| + return time.Since(since) |
| +} |
| + |
| +// copiesOf reads carlos instances list's copies table (HOST BOX BUILD |
| +// STATE HEALTH WORKERS) for host: its healthy copies and all its rows. A |
| +// host with one copy has no copies table; it reads as 1 of 1 when its |
| +// main row is there. |
| +func copiesOf(out, host string) (healthy, total int) { |
| + inCopies, mainRow := false, false |
| + for _, line := range strings.Split(out, "\n") { |
| + f := strings.Fields(line) |
| + if len(f) == 0 { |
| + continue |
| + } |
| + if f[0] == "HOST" { |
| + inCopies = len(f) >= 5 && f[1] == "BOX" |
| + continue |
| + } |
| + if f[0] != host { |
| + continue |
| + } |
| + if !inCopies { |
| + mainRow = true |
| + continue |
| + } |
| + total++ |
| + if f[len(f)-2] == "healthy" { |
| + healthy++ |
| + } |
| + } |
| + if total == 0 && mainRow { |
| + return 1, 1 |
| + } |
| + return healthy, total |
| +} |
| + |
| +// socketWatch holds a websocket to the fixture open, reconnecting when it |
| +// drops, and records the longest gap. |
| +type socketWatch struct { |
| + cancel context.CancelFunc |
| + done chan time.Duration |
| +} |
| + |
| +func (w socketWatch) stop() time.Duration { |
| + w.cancel() |
| + return <-w.done |
| +} |
| + |
| +// watchSocket keeps a websocket to /cable open until stopped. |
| +func (d *drill) watchSocket(ctx context.Context) socketWatch { |
| + ctx, cancel := context.WithCancel(ctx) |
| + w := socketWatch{cancel: cancel, done: make(chan time.Duration, 1)} |
| + go func() { |
| + var longest time.Duration |
| + var lost time.Time |
| + for ctx.Err() == nil { |
| + conn, err := d.dialSocket(ctx) |
| + if err != nil { |
| + if lost.IsZero() { |
| + lost = time.Now() |
| + } |
| + time.Sleep(100 * time.Millisecond) |
| + continue |
| + } |
| + if !lost.IsZero() { |
| + gap := time.Since(lost) |
| + d.note("observation: websocket reconnected after %s", gap) |
| + longest = max(longest, gap) |
| + lost = time.Time{} |
| + } |
| + _, _ = io.Copy(io.Discard, conn) // returns when the connection drops |
| + conn.Close() |
| + if ctx.Err() == nil { |
| + lost = time.Now() |
| + d.note("websocket dropped") |
| + } |
| + } |
| + w.done <- longest |
| + }() |
| + return w |
| +} |
| + |
| +// dialSocket opens a websocket to the fixture's /cable: a TLS connection, |
| +// the upgrade request and a 101 answer. |
| +func (d *drill) dialSocket(ctx context.Context) (net.Conn, error) { |
| + dialer := &tls.Dialer{Config: &tls.Config{ServerName: d.cfg.Host}} |
| + conn, err := dialer.DialContext(ctx, "tcp", d.cfg.Host+":443") |
| + if err != nil { |
| + return nil, err |
| + } |
| + key := make([]byte, 16) |
| + _, _ = rand.Read(key) |
| + fmt.Fprintf(conn, "GET /cable HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n", |
| + d.cfg.Host, base64.StdEncoding.EncodeToString(key)) |
| + res, err := http.ReadResponse(bufio.NewReader(conn), nil) |
| + if err != nil { |
| + conn.Close() |
| + return nil, err |
| + } |
| + if res.StatusCode != http.StatusSwitchingProtocols { |
| + conn.Close() |
| + return nil, fmt.Errorf("websocket upgrade: %s", res.Status) |
| + } |
| + return conn, nil |
| +} |
| + |
| +// readRecords reads an exported request record file: one JSON object a |
| +// line, {"id": ..., "box": ...}. A line that does not parse, or names an |
| +// id twice, is an error: the records are evidence. |
| +func readRecords(path string) (map[string]string, error) { |
| + f, err := os.Open(path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer f.Close() |
| + out := map[string]string{} |
| + sc := bufio.NewScanner(f) |
| + for n := 1; sc.Scan(); n++ { |
| + line := strings.TrimSpace(sc.Text()) |
| + if line == "" { |
| + continue |
| + } |
| + var r struct{ ID, Box string } |
| + if err := json.Unmarshal([]byte(line), &r); err != nil || r.ID == "" { |
| + return nil, fmt.Errorf("%s:%d: not a request record", path, n) |
| + } |
| + if _, dup := out[r.ID]; dup { |
| + return nil, fmt.Errorf("%s:%d: request %s recorded twice", path, n, r.ID) |
| + } |
| + out[r.ID] = r.Box |
| + } |
| + return out, sc.Err() |
| +} |