carlos / platform Public

fix: amend the replica floor and harden the drill (#511 T5 round 1)

Task 5 fix round 1, after the Astra and Fable reviews.

R16 amendment: the heartbeat gains apply_finished (root's apply journal
is absent), filled by the status tick. A box counts at the replicas floor
when its release is at the floor and either prev_release is at the floor
or "none", or its last apply finished. Missing is unfinished.

R13 closed up front: the copies door refuses copies above 1 for an app
with no live instance (SR-4-C77), and every create door refuses a new
instance in an app whose copies are above 1 (SR-4-C78). Four copies tests
that created instances into copies 2 now assert the refusal.

Drill tooling: view checks fail when the state never appears and note
every CLI error; scale-down is read from the console's copy state and the
traffic; a closed stdin stops the drill; load runs through the confirmed
action plus an observation window; one websocket per box, closed on
stop, bounded handshake, a missing connect or reconnect fails, and the
stopped box's socket must drop; any non-2xx fails, a cut needs a 2xx
stream, every issued request needs a sample, every window needs complete
reads and the stop window reads from the survivor; ordering comes from the
boxes' generation events; the survivor's heartbeat is read after the
stop; unsaved evidence fails the run; the tip comes from carlos fleets
show. Window rules live in drillRules/judgeWindow and are tested.

Census overlay stateless-replicas-4-task5 re-proposed; record-write
census entry moved to drill.untilView.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a186d5be1675385d36a7aec983da4d56ab708cdf parent aa1de62
21 files changed, +1,153 −436
  • docs/site/stateless-replicas.md +2 −2
  • docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md +5 −4
  • docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md +4 −2
  • internal/console/appcopies.go +4 −4
  • internal/console/appcopies_test.go +3 −2
  • internal/console/copies_upload_test.go +1 −1
  • internal/console/copiespublication.go +5 −0
  • internal/console/copiespublication_test.go +21 −17
  • internal/console/fleetbox.go +8 −4
  • internal/console/replicafloor.go +17 −1
  • internal/console/replicafloor_test.go +48 −2
  • internal/host/agent.go +5 −1
  • internal/host/replica_apply_finished_test.go +40 −0
  • internal/host/systemprobe.go +14 −0
  • internal/provision/stateless_replicas_4_task5_census_test.go +4 −4
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv +9 −7
  • internal/status/snapshot.go +7 −2
  • scripts/stateless-replicas-drill/accounting.go +168 −71
  • scripts/stateless-replicas-drill/accounting_test.go +275 −67
  • scripts/stateless-replicas-drill/main.go +512 −244

CI failed — run details

Intent

Human

<task-notification> <task-id>a1759874a712527fe</task-id> <tool-use-id>toolu_01KG2pS7iP7vRC3Fo2ZRUhZi</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/a1759874a712527fe.output</output-file> <status>completed</status> <summary>Agent "Implement Plan 4 Task 5 (trimmed)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>- **Status:** DONE_WITH_CONCERNS - **Commits:** `10175284 fix: log an unchanged held release once per change (#511 F11)` and `aa1de62e feat: gate replica activation and add the dev drill`. Both are local and not pushed. No live drill, no infrastructure, no candidate build. - **Tests:** all new tests failed first and pass now (a build failure was the drill's starting point). All 7 deliberate code breaks were caught. The required test runs, census checks and three cross-compiles pass. The census is clean. - **Two-install rule:** carlos.prev survives a successful update, so a box needs two installs at or above v0.35.0 before it allows copies. This hits the drill boxes and the first user; please confirm it is intended. - **New heartbeat field:** the prev rule needed a new `prev_release` field in the box status report, because fleet boxes had no way to report it. - **Git incident:** I ran `git worktree prune` inside the sandbox by mistake. It deleted the git metadata of 17 entries under `.git/worktrees`; the 17 names are in the report. I recreated `commondir` placeholders so sandboxed commands work again. I found no live checkout pointing at them, but any I missed has lost its git metadata. - **Baseline check:** "deploy once, then set copies" was not done by Task 1. It is added at the copies door only, not the create door. - **Drill tooling:** never run live, and only its accounting is tested. The operator exports the request records by hand, because I found no command that exports them. - **Copy:** all copy rows are provisional, pending Paul's review. - **Unrelated failure:** the host test `TestClaimServingAssemblyWithoutMoves` fails the same way without these changes. - **Report:** /home/paulca/amadan.net/carlos/platform/.claude/worktrees/stateless-replicas-4/.superpowers/sdd/2026-11-01-stateless-replicas-4-deploy-and-drill/task-5-report.md</result> <usage><subagent_tokens>439793</subagent_tokens><tool_uses>179</tool_uses><duration_ms>3335234</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bjui2qaub</task-id> <tool-use-id>toolu_01VjLhDdbCX5kPrsdh8Aj53t</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bjui2qaub.output</output-file> <status>completed</status> <summary>Background command "Astra review of Task 5" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bm4yl9ptd</task-id> <tool-use-id>toolu_01RCRLKVEdJ9AcvJcjT476LY</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bm4yl9ptd.output</output-file> <status>completed</status> <summary>Background command "Fable review of Task 5" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 34.5 g CO₂e (4,344,947 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/stateless-replicas.md b/docs/site/stateless-replicas.md
index c2a3810c7..8295344db 100644
--- a/docs/site/stateless-replicas.md
+++ b/docs/site/stateless-replicas.md
@@ -6,9 +6,9 @@ A stateless app can run more than one copy of each instance, each on a different
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.
+More than one copy needs every box of the fleet and the console on platform v0.35.0 or later. While a box's platform update is still finishing, its 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.
+An app needs at least one instance, and each instance needs one successful deploy of its stateless release, before the app can have more than one copy. Deploy once, then set copies. An app with more than one copy takes no new instances: set copies to 1, create the instance and deploy it once, then raise copies again.
## Setting the count
diff --git a/docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md
index 5bd9d1e2a..689cd4350 100644
--- a/docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md
+++ b/docs/superpowers/notes/census-proposal-stateless-replicas-4-task5.md
@@ -1,14 +1,14 @@
# 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).
+Ruling `census-ruling-stateless-replicas-4-task5`. The independent reviewer approves or rejects every change below, 2 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/host/agent.go` `statusLoop` | body | unchanged (6) | Task 5 fix round 1 (#511 R16 amendment): the status tick also fills Probes.ApplyFinished from systemApplyFinished(release.OptDir()), an Lstat of root's apply journal <opt>/system/router/journal.json in the root-owned, world-readable state directory: finished only when the journal is absent, any other answer unknown and so unfinished. Round 0: Probes.PrevRelease from prevReleaseOf (carlos.prev and carlos.prev.version, the files withMovesFields already reads). Reported in the private BoxMetrics block; no bucket request or cadence change. |
+| `internal/status/snapshot.go` `CollectBox` | body | unchanged (28) | Task 5 (#511 R16 and its amendment): copies Probes.PrevRelease and Probes.ApplyFinished into BoxMetrics (json prev_release and apply_finished, omitempty; private, like Release) and counts them 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. |
@@ -29,7 +29,8 @@ Recorded dispositions, which each change must still satisfy:
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
+- new `internal/host/systemprobe.go:systemApplyFinished`: reads +file:Lstat; written legacy, accepted-legacy, frozen
-Seal: `45b27ac0e2f2152497e3c01f277c2230defaeb3be363170ea61b05d72f0a6782` → `39becc512079522a9ce16be0883e163a818bedf6c42e40708ec4388ba6aed9d3`.
+Seal: `45b27ac0e2f2152497e3c01f277c2230defaeb3be363170ea61b05d72f0a6782` → `159baf68e260b8870dcf2fa852244ab330a1a7b33cd7b839fc9daf1a3b7fd0c4`.
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 32f760fea..624222919 100644
--- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
+++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md
@@ -135,8 +135,8 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| 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-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. While a box's platform update is still finishing, its 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 as amended, only while an update is finishing, and R4's published channels; fix round 1 reworded it; awaiting Paul's copy review) |
+| SR-4-C65 | docs/site/stateless-replicas.md | An app needs at least one instance, and each instance needs one successful deploy of its stateless release, before the app can have more than one copy. Deploy once, then set copies. An app with more than one copy takes no new instances: set copies to 1, create the instance and deploy it once, then raise copies again. | pending (added by Plan 4 Task 5: R13 for the docs page; fix round 1 added the empty-app and create refusals; 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) |
@@ -148,3 +148,5 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text.
| 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) |
+| SR-4-C77 | internal/console/replicafloor.go | this app has no instances yet. create one and deploy it once, then set copies | pending (added by Plan 4 Task 5 fix round 1: the copies door's refusal for an app with no live instance, R13 closed up front, copiesNoInstances; awaiting Paul's copy review) |
+| SR-4-C78 | internal/console/replicafloor.go | this app runs more than one copy of each instance, so a new instance cannot be added now. set copies to 1, create the instance and deploy it once, then raise copies again | pending (added by Plan 4 Task 5 fix round 1: the create door's refusal at copies above 1, R13 closed up front, copiesCreateAtCopies; awaiting Paul's copy review) |
diff --git a/internal/console/appcopies.go b/internal/console/appcopies.go
index 192e72ebc..8b9400784 100644
--- a/internal/console/appcopies.go
+++ b/internal/console/appcopies.go
@@ -35,15 +35,15 @@ func atReplicaFloor(build string) bool {
}
// 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).
+// a fleet read whole at StatelessReplicasFloor, each box fresh and with no
+// automatic rollback below the floor left to it (RollbackAtReplicaFloor;
+// R16 and its amendment: only an unfinished 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 || !b.PrevAtReplicaFloor {
+ if !b.Fresh || !b.AtReplicaFloor || !b.RollbackAtReplicaFloor {
return false
}
}
diff --git a/internal/console/appcopies_test.go b/internal/console/appcopies_test.go
index d37c3c148..367c39230 100644
--- a/internal/console/appcopies_test.go
+++ b/internal/console/appcopies_test.go
@@ -95,7 +95,8 @@ func copiesBeat(t *testing.T, fx *consoleFixture, box, rel string, at time.Time)
// 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) {
+// finished, when given, is the heartbeat's apply_finished.
+func writeCopiesBeat(t *testing.T, fx *consoleFixture, box, rel, prev string, at time.Time, finished ...bool) {
t.Helper()
hosts := map[string]status.HostRollout{}
host := "a.example.com"
@@ -107,7 +108,7 @@ func writeCopiesBeat(t *testing.T, fx *consoleFixture, box, rel, prev string, at
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, PrevRelease: prev, RootfsReady: true, Rollout: &status.RolloutReport{Hosts: hosts}}}
+ b := status.Box{Label: box, GeneratedAt: at, Metrics: &status.BoxMetrics{Release: rel, PrevRelease: prev, ApplyFinished: len(finished) > 0 && finished[0], 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/copies_upload_test.go b/internal/console/copies_upload_test.go
index 7b001b97f..8f226c24e 100644
--- a/internal/console/copies_upload_test.go
+++ b/internal/console/copies_upload_test.go
@@ -263,7 +263,7 @@ func TestCopiesClaimFinishRechecksAfterStorage(t *testing.T) {
t.Fatal(err)
}
w := httptest.NewRecorder()
- if fx.srv.finishCopiesClaimCreate(w, q, acct, "shop") || w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), copiesRelease) {
+ if fx.srv.finishCopiesClaimCreate(w, q, acct, "shop") || w.Code != http.StatusConflict || !strings.Contains(w.Body.String(), copiesCreateAtCopies) {
t.Fatalf("finish reused admission from before storage: %d %s", w.Code, w.Body.String())
}
if fx.srv.appLocks.held(fx.sqid + "/shop") {
diff --git a/internal/console/copiespublication.go b/internal/console/copiespublication.go
index cf820de4b..4ec5f787a 100644
--- a/internal/console/copiespublication.go
+++ b/internal/console/copiespublication.go
@@ -163,6 +163,11 @@ func (s *Server) copiesRecordRefusal(ctx context.Context, acct *Account, rec pro
}
configErr := err
n := appconfig.CopiesOf(&cfg.manifest)
+ if create && configErr == nil && n > 1 {
+ // R13 closed up front: an instance born into copies above 1 would
+ // have no successful deploy behind it (SR-4-C78).
+ return &doorRefusal{Status: http.StatusConflict, Msg: copiesCreateAtCopies}
+ }
if n > 1 {
if rec.Demo != nil || (s.cfg.Demo.Fleet != "" && rec.Region == registry.PlacementTarget(s.cfg.Demo.Fleet)) || !rec.DerivesPaths() || rec.HA || rec.Role != "" || rec.Pool != "" || len(rec.Replicas) != 0 {
return &doorRefusal{Status: http.StatusConflict, Msg: copiesManaged}
diff --git a/internal/console/copiespublication_test.go b/internal/console/copiespublication_test.go
index 70f1d3a0c..b911b8c1c 100644
--- a/internal/console/copiespublication_test.go
+++ b/internal/console/copiespublication_test.go
@@ -60,8 +60,13 @@ func TestCopiesPublicationDoors(t *testing.T) {
}
code, out := copiesCall(t, fx, token, door)
want := copiesRelease
- if door.name == "hold" {
+ switch door.name {
+ case "hold":
want = copiesOverlap
+ case "create":
+ // R13 closed up front: no instance is created at copies
+ // above 1, whatever its release.
+ want = copiesCreateAtCopies
}
if code != 409 || !strings.Contains(out, want) {
t.Fatalf("publication: %d %s, want %s", code, out, want)
@@ -212,26 +217,24 @@ func TestCopiesPublicationEvidence(t *testing.T) {
}
}
+// A fresh instance no longer inherits a count above 1 (R13 closed up
+// front, Task 5 fix round 1): the create is refused (SR-4-C78) and the
+// app keeps its count.
func TestCopiesFreshInstanceInheritsCount(t *testing.T) {
fx, token := copiesWorld(t)
if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 {
t.Fatalf("count: %d %s", code, out)
}
code, out := createShop(t, fx, token, `{"host":"new.example.com","channel":"edge"}`)
- if code != 201 {
+ if code != 409 || !strings.Contains(out, copiesCreateAtCopies) {
t.Fatalf("create: %d %s", code, out)
}
- var reply provision.Record
- if err := json.Unmarshal([]byte(out), &reply); err != nil || reply.Hibernate == nil || *reply.Hibernate {
- t.Fatalf("create reply lost inherited always-on setting: %s (%v)", out, err)
- }
- rec, _ := storedShop(t, fx, "new.example.com")
- if rec.Hibernate == nil || *rec.Hibernate {
- t.Fatal("new replicated instance did not inherit always-on")
+ if _, _, err := fx.rel.Get(context.Background(), provision.RecordKey(fx.sqid, "shop", "new.example.com")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("refused create wrote a record: %v", err)
}
m, _ := appconfig.Get(context.Background(), fx.rel, fx.sqid, "shop")
if appconfig.CopiesOf(m) != 2 {
- t.Fatal("new instance lost app count")
+ t.Fatal("refused create changed the app count")
}
}
@@ -600,14 +603,15 @@ func TestCopiesFreshRootfsChecksEveryDestination(t *testing.T) {
if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "shop", "edge", "v1"); err != nil {
t.Fatal(err)
}
- if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 {
- t.Fatalf("count: %d %s", code, out)
+ // R13 closed up front (Task 5 fix round 1): an app with no instance
+ // cannot be set to copies above 1, so a first rootfs instance is never
+ // created into two copies; it is created at one, deployed, then raised
+ // through the copies door, which checks every box.
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 409 || !strings.Contains(out, copiesNoInstances) {
+ t.Fatalf("count on an empty app: %d %s", code, out)
}
code, out := createShop(t, fx, token, `{"host":"first.example.com","channel":"edge"}`)
- if code != 409 || !strings.Contains(out, "2 copies need 2 eligible boxes") {
- t.Fatalf("rootfs copies admitted without two ready boxes: %d %s", code, out)
- }
- if _, _, err := fx.rel.Get(context.Background(), provision.RecordKey(fx.sqid, "shop", "first.example.com")); !errors.Is(err, os.ErrNotExist) {
- t.Fatalf("refused create wrote a record: %v", err)
+ if strings.Contains(out, copiesCreateAtCopies) {
+ t.Fatalf("create at copies 1 refused as replicated: %d %s", code, out)
}
}
diff --git a/internal/console/fleetbox.go b/internal/console/fleetbox.go
index c07919ad7..fdd43b284 100644
--- a/internal/console/fleetbox.go
+++ b/internal/console/fleetbox.go
@@ -74,9 +74,13 @@ 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
+ // RollbackAtReplicaFloor: no automatic rollback can put this box below
+ // StatelessReplicasFloor (#511 R16 and its amendment): its heartbeat's
+ // prev_release (carlos.prev) is at the floor or "none", or its last
+ // system apply has finished (apply_finished), since only an unfinished
+ // apply restores carlos.prev. An unknown prev and a missing
+ // apply_finished are neither.
+ RollbackAtReplicaFloor bool
}
// fleetBoxViewOf is an active registry box before its heartbeat is read.
@@ -112,7 +116,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)
+ boxes[i].RollbackAtReplicaFloor = b.Metrics.PrevRelease == "none" || atReplicaFloor(b.Metrics.PrevRelease) || b.Metrics.ApplyFinished
}
}
return unheard
diff --git a/internal/console/replicafloor.go b/internal/console/replicafloor.go
index 70590ebd9..9c4ec40cc 100644
--- a/internal/console/replicafloor.go
+++ b/internal/console/replicafloor.go
@@ -51,6 +51,14 @@ const copiesChannelBelow = "this deployment's %s channel is on %s, below %s. cop
// 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"
+// copiesNoInstances (SR-4-C77, provisional; R13 closed up front): copies
+// above 1 on an app with no live instance.
+const copiesNoInstances = "this app has no instances yet. create one and deploy it once, then set copies"
+
+// copiesCreateAtCopies (SR-4-C78, provisional; R13 closed up front): a new
+// instance in an app whose copies are above 1.
+const copiesCreateAtCopies = "this app runs more than one copy of each instance, so a new instance cannot be added now. set copies to 1, create the instance and deploy it once, then raise copies again"
+
// errReplicaFloorPromotion is a promotion the replicas floor refused.
var errReplicaFloorPromotion = errors.New("stateless replicas floor")
@@ -231,16 +239,21 @@ func (s *Server) replicaPolicyBarrier(ctx context.Context) *doorRefusal {
// 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.
+// An app with no live instance is refused too (SR-4-C77): nothing has
+// deployed, and the create door refuses a new instance at copies above 1
+// (copiesCreateAtCopies), so no instance is ever born replicated without a
+// baseline. 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}
}
+ live := 0
for _, rec := range recs {
if rec.Retired {
continue
}
+ live++
entry, err := provision.LifetimeEntryOf(rec)
if err != nil {
return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: copiesUnread}
@@ -250,5 +263,8 @@ func (s *Server) copiesBaselineRefusal(ctx context.Context, acct *Account, app s
}
return &doorRefusal{Status: http.StatusConflict, Msg: copiesNoBaseline}
}
+ if live == 0 {
+ return &doorRefusal{Status: http.StatusConflict, Msg: copiesNoInstances}
+ }
return nil
}
diff --git a/internal/console/replicafloor_test.go b/internal/console/replicafloor_test.go
index 0d83a8a99..7287e5994 100644
--- a/internal/console/replicafloor_test.go
+++ b/internal/console/replicafloor_test.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
+ "os"
"strings"
"testing"
"time"
@@ -38,6 +39,12 @@ func rfBeat(t *testing.T, fx *consoleFixture, box, prev string) {
copiesBeatPrev(t, fx, box, release.StatelessReplicasFloor, prev, time.Now())
}
+// rfBeatApply is rfBeat with the heartbeat's apply_finished.
+func rfBeatApply(t *testing.T, fx *consoleFixture, box, prev string, finished bool) {
+ t.Helper()
+ writeCopiesBeat(t, fx, box, release.StatelessReplicasFloor, prev, time.Now(), finished)
+}
+
// rfCopies is the app's configured copy count.
func rfCopies(t *testing.T, fx *consoleFixture) int {
t.Helper()
@@ -93,11 +100,19 @@ func TestReplicaFloorEnablesOnlyCompleteFleet(t *testing.T) {
}{
{"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},
+ // R16 amendment: a prev below the floor is harmless once the last
+ // apply finished; with the apply unfinished, or not reported
+ // (apply_finished absent), it refuses.
+ {"prev-below-apply-unfinished", func(t *testing.T, fx *consoleFixture) { rfBeat(t, fx, "pi-2", replicaBelow) }, 409, floorMsg},
+ {"prev-below-apply-finished", func(t *testing.T, fx *consoleFixture) { rfBeatApply(t, fx, "pi-2", replicaBelow, true) }, 200, ""},
+ {"prev-unknown-apply-unknown", func(t *testing.T, fx *consoleFixture) { rfBeat(t, fx, "pi-2", "") }, 409, floorMsg},
+ {"prev-unknown-apply-finished", func(t *testing.T, fx *consoleFixture) { rfBeatApply(t, fx, "pi-2", "", true) }, 200, ""},
{"old-box", func(t *testing.T, fx *consoleFixture) {
copiesBeatPrev(t, fx, "pi-2", replicaBelow, "none", time.Now())
}, 409, floorMsg},
+ {"old-box-apply-finished", func(t *testing.T, fx *consoleFixture) {
+ writeCopiesBeat(t, fx, "pi-2", replicaBelow, "none", time.Now(), true)
+ }, 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},
@@ -129,6 +144,13 @@ func TestReplicaFloorEnablesOnlyCompleteFleet(t *testing.T) {
{"no-baseline", func(t *testing.T, fx *consoleFixture) {
rfRecord(t, fx, "b.example.com", func(r *provision.Record) { r.ReplicaDeploy.Phase = "failed" })
}, 409, copiesNoBaseline},
+ // R13 closed up front: an app with no live instance has nothing
+ // deployed (SR-4-C77).
+ {"no-instances", func(t *testing.T, fx *consoleFixture) {
+ for _, host := range []string{"a.example.com", "b.example.com"} {
+ rfRecord(t, fx, host, func(r *provision.Record) { r.Retired = true })
+ }
+ }, 409, copiesNoInstances},
{"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
@@ -391,3 +413,27 @@ func copiesBeatPrev(t *testing.T, fx *consoleFixture, box, rel, prev string, at
t.Helper()
writeCopiesBeat(t, fx, box, rel, prev, at)
}
+
+// TestReplicaFloorCreateRefusedAtCopies (R13 closed up front): a new
+// instance in an app whose copies are above 1 is refused (SR-4-C78), with
+// no record written, so no instance is born replicated without a
+// successful deploy. At copies 1 the same create is not refused for that.
+func TestReplicaFloorCreateRefusedAtCopies(t *testing.T) {
+ fx, token := rfWorld(t)
+ if code, out := copiesPut(t, fx, token, `{"copies":2}`); code != 200 {
+ t.Fatalf("copies 2 = %d %s", code, out)
+ }
+ code, out := createShop(t, fx, token, `{"host":"c.example.com","channel":"edge"}`)
+ if code != http.StatusConflict || !strings.Contains(out, copiesCreateAtCopies) {
+ t.Fatalf("create at copies 2 = %d %s", code, out)
+ }
+ if _, _, err := fx.rel.Get(context.Background(), provision.RecordKey(fx.sqid, "shop", "c.example.com")); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("refused create wrote a record: %v", err)
+ }
+ if code, out := copiesPut(t, fx, token, `{"copies":1}`); code != 200 {
+ t.Fatalf("copies 1 = %d %s", code, out)
+ }
+ if code, out := createShop(t, fx, token, `{"host":"c.example.com","channel":"edge"}`); strings.Contains(out, copiesCreateAtCopies) {
+ t.Fatalf("create at copies 1 refused as replicated: %d %s", code, out)
+ }
+}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index 55b13566a..047526a67 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -4988,7 +4988,11 @@ func statusLoop(reg *registry.Registry, svc *activator.Service, buildStates func
// failed apply here could restore a build below the
// stateless replicas floor (#511 R16).
PrevRelease: prevReleaseOf(release.OptDir()),
- Platform: runtime.GOOS + "-" + runtime.GOARCH,
+ // Whether the last system apply finished (no open journal): a
+ // finished apply can no longer put carlos.prev back (R16
+ // amendment).
+ ApplyFinished: systemApplyFinished(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/replica_apply_finished_test.go b/internal/host/replica_apply_finished_test.go
new file mode 100644
index 000000000..97e82f781
--- /dev/null
+++ b/internal/host/replica_apply_finished_test.go
@@ -0,0 +1,40 @@
+package host
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+// The heartbeat's apply_finished (#511 R16 amendment): finished only when
+// root's apply journal is absent. An open journal is unfinished; a state
+// directory the agent cannot read is unknown, which reads as unfinished.
+func TestReplicaFloorApplyFinished(t *testing.T) {
+ opt := t.TempDir()
+ if !systemApplyFinished(opt) {
+ t.Fatal("no journal read as unfinished")
+ }
+ dir := systemRootDir(opt)
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ journal := filepath.Join(dir, "journal.json")
+ if err := os.WriteFile(journal, []byte(`{}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ if systemApplyFinished(opt) {
+ t.Fatal("an open journal read as finished")
+ }
+ if err := os.Remove(journal); err != nil {
+ t.Fatal(err)
+ }
+ if os.Geteuid() != 0 {
+ if err := os.Chmod(dir, 0o000); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(dir, 0o755)
+ if systemApplyFinished(opt) {
+ t.Fatal("an unreadable state directory read as finished")
+ }
+ }
+}
diff --git a/internal/host/systemprobe.go b/internal/host/systemprobe.go
index a9677bc22..e1329dd46 100644
--- a/internal/host/systemprobe.go
+++ b/internal/host/systemprobe.go
@@ -1,6 +1,9 @@
package host
import (
+ "errors"
+ "os"
+ "path/filepath"
"strings"
"github.com/carlosframework/platform/internal/release"
@@ -46,3 +49,14 @@ func systemStateProbe(optDir string) *status.SystemState {
}
return &status.SystemState{Channel: r.Channel, Version: r.Version, PromotedAt: r.PromotedAt, Outcome: r.Outcome, Reason: r.Reason, At: r.At}
}
+
+// systemApplyFinished reports whether this box's last system apply has
+// finished: root's apply journal (<opt>/system/router/journal.json, in the
+// root-owned, world-readable state directory) is absent. While it exists
+// an apply is open, and a failed one may still put carlos.prev back. Any
+// error but its absence is unknown, which reads as not finished (#511 R16
+// amendment).
+func systemApplyFinished(optDir string) bool {
+ _, err := os.Lstat(filepath.Join(systemRootDir(optDir), "journal.json"))
+ return errors.Is(err, os.ErrNotExist)
+}
diff --git a/internal/provision/stateless_replicas_4_task5_census_test.go b/internal/provision/stateless_replicas_4_task5_census_test.go
index 924540be3..04a011df2 100644
--- a/internal/provision/stateless_replicas_4_task5_census_test.go
+++ b/internal/provision/stateless_replicas_4_task5_census_test.go
@@ -8,9 +8,9 @@ package provision
// 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
+// - drill.untilView (scripts/stateless-replicas-drill; drill.untilCopies
+// before fix round 1): "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
@@ -19,7 +19,7 @@ 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"},
+ {"scripts/stateless-replicas-drill/main.go", "drill.untilView", "key-site", "lit:instances", "0e76284a368f974ff9fee9ef3e875bcf6873dafa691770fda6fac5ce121d482e"},
} {
replaced := false
for i, e := range entries {
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 1b9aacc59..36eb009d1 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -178,4 +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
+plan14-root-reads-stateless-replicas-4-task5.tsv 159baf68e260b8870dcf2fa852244ab330a1a7b33cd7b839fc9daf1a3b7fd0c4
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
index 56a6d6f93..5514f690d 100644
--- a/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv
+++ b/internal/provision/testdata/plan14-root-reads-stateless-replicas-4-task5.tsv
@@ -1,20 +1,22 @@
# 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.
+# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 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 78cfecfa52c471dbc338be793877c99b9e49e5031c31548332961b96faae4ad5 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 fix round 1 (#511 R16 amendment): the status tick also fills Probes.ApplyFinished from systemApplyFinished(release.OptDir()), an Lstat of root's apply journal <opt>/system/router/journal.json in the root-owned, world-readable state directory: finished only when the journal is absent, any other answer unknown and so unfinished. Round 0: Probes.PrevRelease from prevReleaseOf (carlos.prev and carlos.prev.version, the files withMovesFields already reads). Reported in the private BoxMetrics block; no bucket request or cadence change. whole:Route@10554,whole:Route@12368,whole:Route@12649,whole:Route@6583,whole:Route@6610,whole:Route@7918 6c5b1e88344d38b05546a3281a41971a32b146ee9885c973ce526a4a6cd436ab
+@legacy 9e7e811fdcf7dad9bcd837549f30a0c9628cea33c96a38db4cafd22c591cbfbb 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 and its amendment): copies Probes.PrevRelease and Probes.ApplyFinished into BoxMetrics (json prev_release and apply_finished, omitempty; private, like Release) and counts them 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 c446ee77d98e2f0f10686ff57de4f7d7bb3d87a17cc9e66aba0216e01a522eb0
@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 33782f96a47e9db63337492890994c7d3240edd4d773d8d5ace5d11ed73e7c77 internal/host/systemprobe.go systemApplyFinished legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 fix round 1 (#511 R16 amendment): new. One Lstat of <opt>/system/router/journal.json, root's apply journal, in the root-owned, world-readable state directory (systemRootDir): true only when it is absent; present or any other error reads as not finished. The agent (carlos-edge.service, user carlos), not root; reads no file content. file:Lstat@58 61e9d2d30a82a563943f474d25241005df5241af890461cb939e98b1fc2d2320
@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/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 fix round 1 (#511 R16 amendment): the status tick also fills Probes.ApplyFinished from systemApplyFinished(release.OptDir()), an Lstat of root's apply journal <opt>/system/router/journal.json in the root-owned, world-readable state directory: finished only when the journal is absent, any other answer unknown and so unfinished. Round 0: Probes.PrevRelease from prevReleaseOf (carlos.prev and carlos.prev.version, the files withMovesFields already reads). Reported in the private BoxMetrics block; no bucket request or cadence change. whole:Route@10554,whole:Route@12368,whole:Route@12649,whole:Route@6583,whole:Route@6610,whole:Route@7918 6c5b1e88344d38b05546a3281a41971a32b146ee9885c973ce526a4a6cd436ab
+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 and its amendment): copies Probes.PrevRelease and Probes.ApplyFinished into BoxMetrics (json prev_release and apply_finished, omitempty; private, like Release) and counts them 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 c446ee77d98e2f0f10686ff57de4f7d7bb3d87a17cc9e66aba0216e01a522eb0
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/host/systemprobe.go systemApplyFinished legacy accepted-legacy accepted-legacy;rev3=census-ruling-stateless-replicas-4-task5;basis=Task 5 fix round 1 (#511 R16 amendment): new. One Lstat of <opt>/system/router/journal.json, root's apply journal, in the root-owned, world-readable state directory (systemRootDir): true only when it is absent; present or any other error reads as not finished. The agent (carlos-edge.service, user carlos), not root; reads no file content. file:Lstat@58 61e9d2d30a82a563943f474d25241005df5241af890461cb939e98b1fc2d2320
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
+@coverage internal/host b9f0e1ff09a3b0e09364d1efec0e87393e544e1e86957fbee1118a5a2f5c585e
+@coverage internal/status dab0e07b13fd57fa2be0592001de8e28fc471cf7d038ebde1d9350ff69a02655
diff --git a/internal/status/snapshot.go b/internal/status/snapshot.go
index 71a35eb79..222022e9d 100644
--- a/internal/status/snapshot.go
+++ b/internal/status/snapshot.go
@@ -132,6 +132,10 @@ type Probes struct {
// 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
+ // ApplyFinished: the box's last system apply has finished (root's
+ // apply journal is absent), so a failed apply can no longer restore
+ // carlos.prev. False is unfinished or unknown (#511 R16 amendment).
+ ApplyFinished bool
// 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
@@ -587,6 +591,7 @@ type BoxMetrics struct {
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
+ ApplyFinished bool `json:"apply_finished,omitempty"` // no open system apply journal; absent: unfinished or unknown
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
@@ -1197,7 +1202,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.PrevRelease != "" || p.Tunnel != "" ||
+ p.DiskFreeBytes != nil || p.DiskFullETAHours != nil || p.Release != "" || p.PrevRelease != "" || p.ApplyFinished || 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 != "" ||
@@ -1228,7 +1233,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, PrevRelease: p.PrevRelease, Tunnel: p.Tunnel, GeoIP: p.GeoIP, HeldStreams: p.HeldStreams,
+ Release: p.Release, PrevRelease: p.PrevRelease, ApplyFinished: p.ApplyFinished, 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
index 9bff8164b..edbe5e0d3 100644
--- a/scripts/stateless-replicas-drill/accounting.go
+++ b/scripts/stateless-replicas-drill/accounting.go
@@ -1,6 +1,7 @@
package main
import (
+ "errors"
"fmt"
"sort"
"strconv"
@@ -49,39 +50,49 @@ type sample struct {
Err string `json:"err,omitempty"`
}
+// ok2xx is whether status is a success.
+func ok2xx(status int) bool { return status >= 200 && status < 300 }
+
// 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).
+// reconciled with the requests the drill issued and 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
+ // Samples is the complete 2xx 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 is reads that failed before a response started, or
+ // that the hub answered with a server error.
PreHeaderFailures int
- // StreamCuts is responses that started and were cut before their end,
- // reported on their own.
+ // HTTPErrors is any other answer that is not 2xx.
+ HTTPErrors int
+ // Truncated is a 2xx answer that was not streamed and was cut.
+ Truncated int
+ // StreamCuts is a streamed 2xx answer that started and was cut before
+ // its end, reported on its own and never a failure.
StreamCuts int
- // ProbeRequests is warm-up, probe or other non-window traffic that
- // reached the window's counts. It must be zero.
+ // Lost is a request the drill issued that has no sample at all.
+ Lost int
+ // ProbeRequests is warm-up, probe or other non-window traffic tagged as
+ // the window's. It must be zero.
ProbeRequests int
- // Problems is every way the client's table and the records disagree.
- // Any problem fails the window.
+ // Problems is every way the client's table, the issued requests and
+ // the records disagree.
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 {
+// account tallies the window of phase, whose requests 0 to issued-1 the
+// drill sent. Only samples of that phase count; every issued request must
+// have exactly one sample, so a request the client lost cannot leave a
+// passing window behind; only records whose id is of that phase are
+// reconciled, and each of them must have a sample. 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, issued int, 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]
+ prefix := strings.TrimSuffix(sampleID(phase, 0), "0")
seen := map[string]bool{}
problem := func(format string, args ...any) { t.Problems = append(t.Problems, fmt.Sprintf(format, args...)) }
for _, s := range samples {
@@ -100,13 +111,23 @@ func account(samples []sample, hub, boxes map[string]string, cfg drillConfig, ph
continue
}
seen[s.ID] = true
+ if n, err := strconv.Atoi(strings.TrimPrefix(s.ID, prefix)); err != nil || n < 0 || n >= issued {
+ problem("sample %s was never issued", s.ID)
+ continue
+ }
switch {
case !s.Started || s.Status == 0 || s.Status >= 500:
t.PreHeaderFailures++
continue
- case !s.Complete:
+ case !ok2xx(s.Status):
+ t.HTTPErrors++
+ continue
+ case !s.Complete && s.Stream:
t.StreamCuts++
continue
+ case !s.Complete:
+ t.Truncated++
+ continue
}
t.Samples++
if s.Box != cfg.BoxA && s.Box != cfg.BoxB {
@@ -129,6 +150,12 @@ func account(samples []sample, hub, boxes map[string]string, cfg drillConfig, ph
}
}
}
+ for n := 0; n < issued; n++ {
+ if id := sampleID(phase, n); !seen[id] {
+ t.Lost++
+ problem("request %s was issued and has no sample", id)
+ }
+ }
for _, records := range []map[string]string{hub, boxes} {
for id := range records {
if strings.HasPrefix(id, prefix) && !seen[id] {
@@ -143,76 +170,146 @@ func account(samples []sample, hub, boxes map[string]string, cfg drillConfig, ph
// 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) {
+// windowRule is what one measured window must show to pass.
+type windowRule struct {
+ Phase string
+ // MinReads is the fewest complete 2xx reads the window counts over; a
+ // window always needs at least one.
+ MinReads int
+ // Spread: each drill box served 45%-55% of the complete reads.
+ Spread bool
+ // Survivor, when set, must serve at least MinSurvivor complete reads
+ // sent at or after Since (the stop window: the box still running).
+ Survivor string
+ Since time.Time
+ MinSurvivor int
+ // SingleBox: every complete read came from one box (scale-down to 1).
+ SingleBox bool
+ // Builds, when set, is every build a complete read may name.
+ Builds []string
+}
+
+// minWindowReads is the fewest complete reads a stop, deploy, failing or
+// scale-down window counts over.
+const minWindowReads = 20
+
+// drillRules is every measured window's rule. stopAt is when the operator
+// confirmed box B stopped; from and to are the good deploy's builds.
+func drillRules(cfg drillConfig, stopAt time.Time, from, to string) []windowRule {
+ return []windowRule{
+ {Phase: phaseSpread, MinReads: minSpreadReads, Spread: true},
+ {Phase: phaseStop, MinReads: minWindowReads, Survivor: cfg.BoxA, Since: stopAt, MinSurvivor: minWindowReads},
+ {Phase: phaseReturn, MinReads: minSpreadReads, Spread: true},
+ {Phase: phaseDeploy, MinReads: minWindowReads, Builds: []string{from, to}},
+ {Phase: phaseFailing, MinReads: minWindowReads, Builds: []string{to}},
+ {Phase: phaseScaleDown, MinReads: minWindowReads, SingleBox: true},
+ }
+}
+
+// judgeWindow accounts r's window and says whether it passed: nil, or why
+// not. A missing, failed, erroneous or cut read fails it, except a cut
+// stream; so do too few complete reads, any table problem, and whatever
+// the rule asks that the reads do not show.
+func judgeWindow(samples []sample, issued int, hub, boxes map[string]string, cfg drillConfig, r windowRule) (tally, error) {
+ t := account(samples, issued, hub, boxes, cfg, r.Phase)
+ min := max(r.MinReads, 1)
switch {
case len(t.Problems) > 0:
- return false, fmt.Sprintf("%d request record problems, first: %s", len(t.Problems), t.Problems[0])
+ return t, fmt.Errorf("%s: %d request record problems, first: %s", r.Phase, len(t.Problems), t.Problems[0])
case t.ProbeRequests != 0:
- return false, fmt.Sprintf("%d probe requests were counted", t.ProbeRequests)
+ return t, fmt.Errorf("%s: %d probe requests were counted", r.Phase, 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)
+ return t, fmt.Errorf("%s: %d reads failed before their headers", r.Phase, t.PreHeaderFailures)
+ case t.HTTPErrors != 0:
+ return t, fmt.Errorf("%s: %d reads were answered with an error", r.Phase, t.HTTPErrors)
+ case t.Truncated != 0:
+ return t, fmt.Errorf("%s: %d responses that were not streamed were cut", r.Phase, t.Truncated)
+ case t.Samples < min:
+ return t, fmt.Errorf("%s: %d complete reads, fewer than %d", r.Phase, 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)
+ if r.Spread {
+ for _, box := range []string{cfg.BoxA, cfg.BoxB} {
+ share := float64(t.ByBox[box]) / float64(t.Samples)
+ if share < spreadLow || share > spreadHigh {
+ return t, fmt.Errorf("%s: %s served %.1f%% of reads", r.Phase, 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{}
+ if r.SingleBox && len(t.ByBox) != 1 {
+ return t, fmt.Errorf("%s: %d boxes served reads, not one", r.Phase, len(t.ByBox))
+ }
+ survivor, builds := 0, map[string]bool{}
+ for _, b := range r.Builds {
+ builds[b] = true
+ }
for _, s := range samples {
- if !s.Complete {
+ if s.Phase != r.Phase || !s.Complete || !ok2xx(s.Status) {
continue
}
- boxes[s.Box] = true
- switch s.Build {
- case from:
- if s.At.After(lastOld[s.Box]) {
- lastOld[s.Box] = s.At
+ if r.Survivor != "" && s.Box == r.Survivor && !s.At.Before(r.Since) {
+ survivor++
+ }
+ if len(builds) > 0 && !builds[s.Build] {
+ return t, fmt.Errorf("%s: read %s served build %q", r.Phase, s.ID, s.Build)
+ }
+ }
+ if r.Survivor != "" && (r.Since.IsZero() || survivor < max(r.MinSurvivor, 1)) {
+ return t, fmt.Errorf("%s: %s served %d complete reads after the stop, fewer than %d", r.Phase, r.Survivor, survivor, max(r.MinSurvivor, 1))
+ }
+ return t, nil
+}
+
+// genEvent is one box's generation transition, from that box's own
+// journal (the authoritative evidence of a switch): Build started serving
+// ("serving") or stopped ("retired") At, by the box's clock.
+type genEvent struct {
+ Box string `json:"box"`
+ Build string `json:"build"`
+ Event string `json:"event"`
+ At time.Time `json:"at"`
+}
+
+// orderedSwitch is whether the boxes' generation events show a deploy's
+// copies switching from build from to build to one box at a time: each of
+// the boxes started serving to and retired from, and ordered by when they
+// started serving to, every earlier box had retired from before the next
+// one started serving to. Two boxes serving the new build while an earlier
+// one still serves the old is not ordered, however the client's reads
+// fell.
+func orderedSwitch(events []genEvent, boxes []string, from, to string) (bool, string) {
+ started, retired := map[string]time.Time{}, map[string]time.Time{}
+ for _, e := range events {
+ switch {
+ case e.Event == "serving" && e.Build == to:
+ if s, ok := started[e.Box]; !ok || e.At.Before(s) {
+ started[e.Box] = e.At
}
- case to:
- if f, ok := firstNew[s.Box]; !ok || s.At.Before(f) {
- firstNew[s.Box] = s.At
+ case e.Event == "retired" && e.Build == from:
+ if r, ok := retired[e.Box]; !ok || e.At.After(r) {
+ retired[e.Box] = e.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)
+ for _, box := range boxes {
+ if _, ok := started[box]; !ok {
+ return false, fmt.Sprintf("%s never started serving %s", box, to)
+ }
+ if _, ok := retired[box]; !ok {
+ return false, fmt.Sprintf("%s never retired %s", box, from)
+ }
}
- sort.Slice(order, func(i, j int) bool { return firstNew[order[i]].Before(firstNew[order[j]]) })
+ order := append([]string(nil), boxes...)
+ sort.SliceStable(order, func(i, j int) bool { return started[order[i]].Before(started[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)
+ if !retired[earlier].Before(started[order[i]]) {
+ return false, fmt.Sprintf("%s retired %s at %s, not before %s started %s at %s", earlier, from,
+ retired[earlier].Format(time.RFC3339Nano), order[i], to, started[order[i]].Format(time.RFC3339Nano))
}
}
}
return true, ""
}
+
+// errNotFound is a live-view check that never saw the state it waited for.
+var errNotFound = errors.New("not found")
diff --git a/scripts/stateless-replicas-drill/accounting_test.go b/scripts/stateless-replicas-drill/accounting_test.go
index 137772507..1d4f0ee86 100644
--- a/scripts/stateless-replicas-drill/accounting_test.go
+++ b/scripts/stateless-replicas-drill/accounting_test.go
@@ -1,23 +1,30 @@
package main
import (
- "fmt"
+ "bufio"
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
"strings"
"testing"
"time"
)
+var drillT0 = time.Unix(1_800_000_000, 0)
+
// 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)
+// drill never sent as a sample. It returns how many spread requests were
+// issued.
+func drillFixture() ([]sample, int, map[string]string, map[string]string) {
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)
+ s.At = drillT0.Add(time.Duration(len(samples)) * 50 * time.Millisecond)
samples = append(samples, s)
}
for i := 0; i < 5; i++ {
@@ -31,27 +38,29 @@ func drillFixture() ([]sample, map[string]string, map[string]string) {
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"
+ add(sample{ID: sampleID(phaseSpread, 40), Phase: phaseSpread, Err: "connection reset before headers"})
+ cut := sampleID(phaseSpread, 41)
+ add(sample{ID: cut, Phase: phaseSpread, Status: 200, Started: true, Stream: true, Box: "b", Err: "unexpected EOF"})
+ hub[cut], boxes[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
+ hub[sampleID(phaseProbe, 0)], boxes[sampleID(phaseProbe, 0)] = "b", "b"
+ add(sample{ID: sampleID(phaseProbe, 0), Phase: phaseProbe, Status: 200, Started: true, Complete: true, Box: "b"})
+ return samples, 42, hub, boxes
}
func TestReplicaDrillAccounting(t *testing.T) {
cfg := drillConfig{BoxA: "a", BoxB: "b"}
- samples, hub, boxes := drillFixture()
- got := account(samples, hub, boxes, cfg, phaseSpread)
+ spread := windowRule{Phase: phaseSpread, MinReads: 40, Spread: true}
+ samples, issued, hub, boxes := drillFixture()
+ got := account(samples, issued, 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 {
+ if got.Samples != 40 || got.ByBox["a"] != 20 || got.ByBox["b"] != 20 || len(got.Problems) != 0 || got.Lost != 0 {
t.Fatalf("window = %+v", got)
}
// Per-box and hub counts reconcile with the client's.
@@ -61,63 +70,195 @@ func TestReplicaDrillAccounting(t *testing.T) {
}
}
// 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)
+ if _, err := judgeWindow(samples, issued, hub, boxes, cfg, spread); err == nil || !strings.Contains(err.Error(), "failed before") {
+ t.Fatalf("a pre-header failure passed: %v", err)
}
- // 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)
+ // The clean window: the failed read made good. Each table error,
+ // missing sample, error answer or cut never turns into a pass.
+ clean := func() ([]sample, int, map[string]string, map[string]string) {
+ s, n, h, b := drillFixture()
+ for i := range s {
+ if s[i].ID == sampleID(phaseSpread, 40) {
+ s[i] = sample{ID: s[i].ID, Phase: phaseSpread, At: s[i].At, Status: 200, Started: true, Complete: true, Box: "a"}
+ h[s[i].ID], b[s[i].ID] = "a", "a"
}
}
- 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
- }
+ return s, n, h, b
+ }
+ s, n, h, b := clean()
+ if _, err := judgeWindow(s, n, h, b, cfg, spread); err != nil {
+ t.Fatalf("the clean window failed: %v", err)
+ }
+ type edit func(s *[]sample, n *int, h, b map[string]string)
+ at := func(s []sample, id string) *sample {
+ for i := range s {
+ if s[i].ID == id {
+ return &s[i]
}
+ }
+ panic(id)
+ }
+ for name, e := range map[string]edit{
+ "hub record missing": func(_ *[]sample, _ *int, h, _ map[string]string) { delete(h, sampleID(phaseSpread, 7)) },
+ "box record missing": func(_ *[]sample, _ *int, _, b map[string]string) { delete(b, sampleID(phaseSpread, 8)) },
+ "records disagree": func(_ *[]sample, _ *int, h, _ map[string]string) { h[sampleID(phaseSpread, 9)] = "a" },
+ "record without a sample": func(s *[]sample, _ *int, _, _ map[string]string) {
+ *s = dropSample(*s, sampleID(phaseSpread, 11))
+ },
+ // The drill issued a request whose sample, and every record of
+ // it, is gone: only the issued count shows it.
+ "lost sample with no records": func(s *[]sample, _ *int, h, b map[string]string) {
+ id := sampleID(phaseSpread, 12)
+ *s = dropSample(*s, id)
+ delete(h, id)
+ delete(b, id)
},
- "unknown box": func(s *[]sample, h, b map[string]string) {
- (*s)[10].Box, h[(*s)[10].ID], b[(*s)[10].ID] = "c", "c", "c"
+ "sample never issued": func(_ *[]sample, n *int, _, _ map[string]string) { *n = 40 },
+ "unknown box": func(s *[]sample, _ *int, h, b map[string]string) {
+ x := at(*s, sampleID(phaseSpread, 10))
+ x.Box, h[x.ID], b[x.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) {
+ "a 404 answer": func(s *[]sample, _ *int, _, _ map[string]string) {
+ at(*s, sampleID(phaseSpread, 13)).Status = 404
+ },
+ "a 429 cut stream": func(s *[]sample, _ *int, _, _ map[string]string) {
+ x := at(*s, sampleID(phaseSpread, 41))
+ x.Status = 429
+ },
+ "a cut that was not streamed": func(s *[]sample, _ *int, _, _ map[string]string) {
+ x := at(*s, sampleID(phaseSpread, 14))
+ x.Complete = false
+ },
+ "a 503 from the hub": func(s *[]sample, _ *int, _, _ map[string]string) {
+ at(*s, sampleID(phaseSpread, 15)).Status = 503
+ },
+ "too few samples": func(s *[]sample, n *int, _, _ map[string]string) {
+ *s, *n = (*s)[:20], 15
+ },
+ "uneven spread": func(s *[]sample, _ *int, h, b map[string]string) { unevenSpread(*s, h, b) },
+ "empty table": func(s *[]sample, n *int, _, _ map[string]string) { *s, *n = nil, 0 },
+ "no hub records": func(_ *[]sample, _ *int, h, _ map[string]string) {
+ clear(h)
+ },
+ "stream cut, no reads": func(s *[]sample, _ *int, _, _ map[string]string) { onlyCuts(*s) },
+ "probe tagged as the window": func(s *[]sample, _ *int, 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 {
+ s, n, h, b := clean()
+ e(&s, &n, h, b)
+ if _, err := judgeWindow(s, n, h, b, cfg, spread); err == nil {
t.Fatalf("passed with %s", name)
- } else if why == "" {
- t.Fatal("refused without a reason")
}
})
}
}
+// TestReplicaDrillWindowRules: the stop, deploy, failing and scale-down
+// windows' rules (drillRules) refuse what they must, over the clean
+// window's reads.
+func TestReplicaDrillWindowRules(t *testing.T) {
+ cfg := drillConfig{BoxA: "a", BoxB: "b"}
+ stopAt := drillT0.Add(10 * time.Second)
+ rules := map[string]windowRule{}
+ for _, r := range drillRules(cfg, stopAt, "v1", "v2") {
+ rules[r.Phase] = r
+ }
+ // window is n complete reads of phase, alternating boxes before at and
+ // on box a from at, all on build; the records agree.
+ window := func(phase string, n int, build string) ([]sample, int, map[string]string, map[string]string) {
+ var s []sample
+ h, b := map[string]string{}, map[string]string{}
+ for i := 0; i < n; i++ {
+ when := drillT0.Add(time.Duration(i) * time.Second)
+ box := []string{"a", "b"}[i%2]
+ if !when.Before(stopAt) {
+ box = "a"
+ }
+ id := sampleID(phase, i)
+ s = append(s, sample{ID: id, Phase: phase, At: when, Status: 200, Started: true, Complete: true, Box: box, Build: build})
+ h[id], b[id] = box, box
+ }
+ return s, n, h, b
+ }
+ for _, c := range []struct {
+ name string
+ phase string
+ edit func(s []sample, n *int, h, b map[string]string) []sample
+ pass bool
+ }{
+ {"stop window passes", phaseStop, nil, true},
+ {"stop window empty", phaseStop, func(s []sample, n *int, _, _ map[string]string) []sample { *n = 0; return nil }, false},
+ {"stop window all cut", phaseStop, func(s []sample, _ *int, _, _ map[string]string) []sample {
+ for i := range s {
+ s[i].Complete, s[i].Stream = false, true
+ }
+ return s
+ }, false},
+ {"stop window all 404", phaseStop, func(s []sample, _ *int, _, _ map[string]string) []sample {
+ for i := range s {
+ s[i].Status = 404
+ }
+ return s
+ }, false},
+ {"stop window, no survivor reads after the stop", phaseStop, func(s []sample, n *int, _, _ map[string]string) []sample {
+ var kept []sample
+ for _, x := range s {
+ if x.At.Before(stopAt) {
+ kept = append(kept, x)
+ }
+ }
+ *n = len(kept)
+ return kept
+ }, false},
+ {"deploy window passes", phaseDeploy, nil, true},
+ {"deploy window, a third build", phaseDeploy, func(s []sample, _ *int, _, _ map[string]string) []sample {
+ s[3].Build = "v3"
+ return s
+ }, false},
+ {"failing window, the failing build served", phaseFailing, func(s []sample, _ *int, _, _ map[string]string) []sample {
+ s[5].Build = "v3"
+ return s
+ }, false},
+ {"failing window empty", phaseFailing, func(s []sample, n *int, _, _ map[string]string) []sample { *n = 0; return nil }, false},
+ {"scale-down from both boxes", phaseScaleDown, nil, false},
+ {"scale-down from one box", phaseScaleDown, func(s []sample, _ *int, h, b map[string]string) []sample {
+ for i := range s {
+ s[i].Box, h[s[i].ID], b[s[i].ID] = "a", "a", "a"
+ }
+ return s
+ }, true},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ build := "v2"
+ if c.phase == phaseDeploy {
+ build = "v1"
+ }
+ s, n, h, b := window(c.phase, 40, build)
+ if c.edit != nil {
+ s = c.edit(s, &n, h, b)
+ }
+ _, err := judgeWindow(s, n, h, b, cfg, rules[c.phase])
+ if (err == nil) != c.pass {
+ t.Fatalf("%s: pass %v, want %v (%v)", c.name, err == nil, c.pass, err)
+ }
+ })
+ }
+}
+
+func dropSample(s []sample, id string) []sample {
+ for i, x := range s {
+ if x.ID == id {
+ return append(s[:i:i], s[i+1:]...)
+ }
+ }
+ return s
+}
+
// unevenSpread moves the window's reads to 70% on a.
func unevenSpread(s []sample, h, b map[string]string) {
n := 0
@@ -138,27 +279,94 @@ func onlyCuts(s []sample) {
}
}
-// 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.
+// TestReplicaDrillOrderedSwitch: the boxes' own generation events decide
+// whether a deploy's copies switched one box at a time. Two boxes that
+// start the new build together are not ordered, however the client's
+// reads fell.
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}
+ ev := func(sec int, box, build, event string) genEvent {
+ return genEvent{Box: box, Build: build, Event: event, At: drillT0.Add(time.Duration(sec) * time.Second)}
}
- 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 {
+ boxes := []string{"a", "b"}
+ ordered := []genEvent{ev(2, "a", "v2", "serving"), ev(3, "a", "v1", "retired"), ev(5, "b", "v2", "serving"), ev(6, "b", "v1", "retired")}
+ if ok, why := orderedSwitch(ordered, boxes, "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 {
+ simultaneous := []genEvent{ev(2, "a", "v2", "serving"), ev(2, "b", "v2", "serving"), ev(3, "a", "v1", "retired"), ev(3, "b", "v1", "retired")}
+ if ok, _ := orderedSwitch(simultaneous, boxes, "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")
+ overlapping := []genEvent{ev(2, "a", "v2", "serving"), ev(4, "b", "v2", "serving"), ev(5, "a", "v1", "retired"), ev(6, "b", "v1", "retired")}
+ if ok, _ := orderedSwitch(overlapping, boxes, "v1", "v2"); ok {
+ t.Fatal("b started before a retired its old build and passed")
+ }
+ if ok, _ := orderedSwitch(ordered[:2], boxes, "v1", "v2"); ok {
+ t.Fatal("a deploy that never reached b passed")
+ }
+ if ok, _ := orderedSwitch(nil, boxes, "v1", "v2"); ok {
+ t.Fatal("no evidence passed")
+ }
+}
+
+// TestReplicaDrillViewAndInput: the live view reads copies from the copies
+// table and one copy from the main row; a closed operator input is an
+// error, never a confirmation; evidence the drill cannot save fails it.
+func TestReplicaDrillViewAndInput(t *testing.T) {
+ two := "HOST REGION CHANNEL\nshop.example.com fleet/pi stable running\n\nHOST BOX BUILD STATE HEALTH WORKERS\nshop.example.com pi-1 v1 running healthy 1/1\nshop.example.com pi-2 v1 down unhealthy -\n"
+ if v := copiesOf(two, "shop.example.com"); v.healthy != 1 || v.total != 2 {
+ t.Fatalf("1 of 2 read as %+v", v)
+ }
+ one := "HOST REGION CHANNEL\nshop.example.com fleet/pi stable running\n"
+ if v := copiesOf(one, "shop.example.com"); v.total != 0 || !v.mainRunning {
+ t.Fatalf("one copy read as %+v", v)
+ }
+ asleep := "HOST REGION CHANNEL\nshop.example.com fleet/pi stable asleep\n"
+ if v := copiesOf(asleep, "shop.example.com"); v.mainRunning {
+ t.Fatal("a main row that is not running read as one running copy")
+ }
+ d := &drill{in: bufio.NewReader(strings.NewReader("")), log: devNull(t)}
+ if err := d.operator("hard-stop b"); err == nil || !errors.Is(err, io.EOF) {
+ t.Fatalf("closed input confirmed: %v", err)
+ }
+ if r := (socketResult{}).verdict(false); r == "" {
+ t.Fatal("a socket that never connected passed")
+ }
+ if r := (socketResult{Connected: true}).verdict(true); r == "" {
+ t.Fatal("the stopped box's socket passed without a drop")
+ }
+ if r := (socketResult{Connected: true, Drops: 1, Open: true}).verdict(true); r == "" {
+ t.Fatal("a socket that never reconnected passed")
+ }
+ if r := (socketResult{Connected: true, Drops: 1}).verdict(true); r != "" {
+ t.Fatalf("a dropped and reconnected socket failed: %s", r)
}
- if ok, _ := orderedSwitch(append(ordered, read(6, "b", "v3")), "v1", "v2"); ok {
- t.Fatal("a third build passed")
+ // runDrill stops at the first missing piece and still cannot pass:
+ // here the boxes' build cannot be read (no carlos CLI on PATH), and an
+ // output directory that is a file cannot hold the evidence.
+ t.Setenv("PATH", t.TempDir())
+ out := t.TempDir()
+ rep, err := runDrill(context.Background(), drillConfig{Host: "shop.example.com", Fleet: "pi", BoxA: "a", BoxB: "b", OutputDir: out, Rate: 1, Duration: time.Second}, strings.NewReader(""))
+ if err == nil || rep.Passed {
+ t.Fatalf("a drill that could not read the build passed: %v %+v", err, rep)
+ }
+ if _, serr := os.Stat(filepath.Join(out, "report.json")); serr != nil {
+ t.Fatalf("the failed drill saved no report: %v", serr)
+ }
+ file := filepath.Join(t.TempDir(), "file")
+ if err := os.WriteFile(file, nil, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if rep, err := runDrill(context.Background(), drillConfig{Host: "shop.example.com", Fleet: "pi", BoxA: "a", BoxB: "b", OutputDir: file, Rate: 1, Duration: time.Second}, strings.NewReader("")); err == nil || rep.Passed {
+ t.Fatal("a drill with nowhere to save its evidence passed")
+ }
+}
+
+func devNull(t *testing.T) *os.File {
+ t.Helper()
+ f, err := os.Create(filepath.Join(t.TempDir(), "log"))
+ if err != nil {
+ t.Fatal(err)
}
+ t.Cleanup(func() { f.Close() })
+ return f
}
diff --git a/scripts/stateless-replicas-drill/main.go b/scripts/stateless-replicas-drill/main.go
index 360a3fe6d..a4ebea3af 100644
--- a/scripts/stateless-replicas-drill/main.go
+++ b/scripts/stateless-replicas-drill/main.go
@@ -5,9 +5,10 @@
// 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.
+// hard-stop and return of a box, the deploys and the scale-down. Each
+// action is confirmed on stdin; a closed stdin stops the drill as failed.
+// 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
@@ -18,20 +19,28 @@
// 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
+// GET /cable a websocket upgrade whose 101 answer
+// carries X-Drill-Box
//
// 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 fixture's environment. When the drill asks, the operator exports
+// three files into the output directory, one JSON object per line:
+//
+// hub-records.jsonl {"id": ..., "box": ...} the hub's selected box
+// box-records.jsonl {"id": ..., "box": ...} the box that served it
+// generations.jsonl {"box": ..., "build": ..., "event": "serving" or
+// "retired", "at": ...} each box's generation
+// transitions, from its own
+// journal
//
// 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.
+// with zero failed reads, 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 recorded as observations. A check that cannot be
+// made, a missing sample, an error or a timeout fails the drill; it never
+// passes.
package main
import (
@@ -51,6 +60,7 @@ import (
"os/exec"
"os/signal"
"path/filepath"
+ "slices"
"strings"
"sync"
"time"
@@ -66,12 +76,13 @@ type drillConfig struct {
}
// 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.
+// boxes run, as the console reports it. 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, by the boxes' own generation events. Passed is true only when
+// every check passed and the evidence was saved.
type drillReport struct {
Tip string
Samples, PreHeaderFailures, StreamCuts, ReleaseRuns int
@@ -84,6 +95,16 @@ type drillReport struct {
// counts over.
const minSpreadReads = 2000
+// The observation windows: load keeps running this long after the
+// operator confirms an action.
+const (
+ stopObserve = 2 * time.Minute
+ deployObserve = time.Minute
+ scaleObserve = time.Minute
+ viewBound = 10 * time.Minute
+ handshakeBound = 10 * time.Second
+)
+
// 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"
@@ -98,7 +119,7 @@ func main() {
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.BoxA, "box-a", "", "the first drill box's label, the one that keeps running")
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")
@@ -106,24 +127,19 @@ func main() {
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 {
+ report, err := runDrill(ctx, cfg, os.Stdin)
+ switch {
+ case err != nil:
fmt.Fprintf(os.Stderr, drillFailed+"\n", err)
os.Exit(1)
- }
- if !report.Passed {
+ case !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.
+// operator's input, the evidence log and every sample sent.
type drill struct {
cfg drillConfig
client *http.Client
@@ -132,15 +148,19 @@ type drill struct {
samples []sample
seq map[string]int
log *os.File
+ logErr error
+ failed []string
}
-// 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) {
+// runDrill runs the whole drill. It returns an error for anything that
+// stops the drill early, a closed operator input included; a check that
+// fails is recorded and the report says Passed false. The report is
+// written to report.json last; a run whose evidence (drill.log,
+// samples.json, report.json) was not saved never passes.
+func runDrill(ctx context.Context, cfg drillConfig, operatorInput io.Reader) (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 cfg.Host == "" || cfg.Fleet == "" || cfg.BoxA == "" || cfg.BoxB == "" || cfg.BoxA == cfg.BoxB || cfg.OutputDir == "" || cfg.Rate < 1 || cfg.Duration <= 0 {
+ return report, errors.New("set --host, --fleet, two different boxes, --out, a positive --rate and --duration")
}
if err := os.MkdirAll(cfg.OutputDir, 0o755); err != nil {
return report, err
@@ -150,154 +170,266 @@ func runDrill(ctx context.Context, cfg drillConfig) (drillReport, error) {
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 := &drill{cfg: cfg, client: &http.Client{Timeout: 30 * time.Second}, in: bufio.NewReader(operatorInput), seq: map[string]int{}, log: logf}
+ err = d.run(ctx, &report)
+ if err != nil {
+ d.fail("%v", err)
+ }
+ if raw, jerr := json.Marshal(d.all()); jerr != nil {
+ d.fail("samples.json: %v", jerr)
+ } else if werr := os.WriteFile(filepath.Join(cfg.OutputDir, "samples.json"), raw, 0o644); werr != nil {
+ d.fail("samples.json: %v", werr)
+ }
+ if serr := logf.Sync(); serr != nil && d.logErr == nil {
+ d.logErr = serr
+ }
+ if d.logErr != nil {
+ d.failed = append(d.failed, fmt.Sprintf("drill.log: %v", d.logErr))
}
- 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)
+ report.Passed = len(d.failed) == 0
+ raw, jerr := json.MarshalIndent(struct {
+ drillReport
+ Failed []string `json:"failed,omitempty"`
+ }{report, d.failed}, "", " ")
+ if jerr == nil {
+ jerr = os.WriteFile(filepath.Join(cfg.OutputDir, "report.json"), raw, 0o644)
}
+ if jerr != nil {
+ report.Passed = false
+ return report, fmt.Errorf("report.json was not saved: %w", jerr)
+ }
+ if err != nil {
+ return report, err
+ }
+ return report, nil
+}
+
+// run is the drill's sequence. An error stops it; a failed check is noted
+// (fail) and the drill goes on, so the evidence covers every step.
+func (d *drill) run(ctx context.Context, report *drillReport) error {
+ cfg := d.cfg
+ tip, err := d.tip(ctx)
+ if err != nil {
+ return fmt.Errorf("the boxes' build: %w", err)
+ }
+ report.Tip = tip
+ d.note("drill start: boxes run %s; %+v", tip, cfg)
// Readiness: probe traffic until both boxes have answered, never
// measured.
if err := d.ready(ctx); err != nil {
- return report, err
+ return 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)
+ // 2. Hard-stop box B under load: no failed read, the live view's 1 of
+ // 2, the survivor's worker heartbeats, the websockets' reconnect.
+ sockets := map[string]*socketWatch{}
+ for _, box := range []string{cfg.BoxA, cfg.BoxB} {
+ sockets[box] = d.watchSocket(ctx, box)
+ }
+ var stopAt time.Time
+ view := make(chan error, 1)
+ err = d.loadAround(ctx, phaseStop, stopObserve, func() error {
+ if err := d.operator("hard-stop %s now through the approved operator action, then press enter", cfg.BoxB); err != nil {
+ return err
+ }
+ stopAt = time.Now()
+ go func() { view <- d.untilCopies(ctx, stopAt, 1, 2) }()
+ return nil
+ })
if err != nil {
- return report, err
+ return err
+ }
+ if verr := <-view; verr != nil {
+ d.fail("the live view never showed 1 of 2 copies after the stop: %v", verr)
}
- 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
+ return 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)
+ if !after.Heartbeats[cfg.BoxA].After(stopAt) {
+ d.fail("the worker on %s recorded no heartbeat after %s was stopped at %s (last %s)", cfg.BoxA, cfg.BoxB, stopAt.Format(time.RFC3339), after.Heartbeats[cfg.BoxA].Format(time.RFC3339))
+ }
+ for _, box := range []string{cfg.BoxA, cfg.BoxB} {
+ res := sockets[box].stop()
+ d.note("websocket pinned to %s: %+v", box, res)
+ report.MaxReconnect = max(report.MaxReconnect, res.Longest)
+ if why := res.verdict(box == cfg.BoxB); why != "" {
+ d.fail("websocket pinned to %s: %s", box, why)
+ }
}
- 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))
+ if err := d.operator("start %s again through the approved operator action, and press enter once its agent and tunnel are back", cfg.BoxB); err != nil {
+ return err
+ }
+ if verr := d.untilCopies(ctx, time.Now(), 2, 2); verr != nil {
+ d.fail("the live view never showed 2 of 2 copies after the return: %v", verr)
+ }
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)
- })
+ before, err := d.state(ctx)
+ if err != nil {
+ return err
+ }
+ from := d.lastBuild(phaseReturn)
+ if err := d.loadAround(ctx, phaseDeploy, deployObserve, func() error {
+ return d.operator("deploy a new good build of %s now (carlos deploy), and press enter once the deploy has finished", cfg.App)
+ }); err != nil {
+ return err
+ }
deployed, err := d.state(ctx)
if err != nil {
- return report, err
+ return err
}
- report.ReleaseRuns = deployed.ReleaseCount - after.ReleaseCount
+ report.ReleaseRuns = deployed.ReleaseCount - before.ReleaseCount
if report.ReleaseRuns != 1 {
- fail("the good deploy's release command ran %d times, not once", report.ReleaseRuns)
+ d.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)
+ if to == "" || to == from {
+ d.fail("the good deploy did not change the build (%q to %q)", from, to)
}
- 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
- }
+ if err := d.loadAround(ctx, phaseFailing, deployObserve, func() error {
+ return d.operator("deploy a build of %s whose release command fails, and press enter once that deploy has stopped", cfg.App)
+ }); err != nil {
+ return err
}
+ failing, err := d.state(ctx)
+ if err != nil {
+ return err
+ }
+ d.note("the failing release's command ran %d times", failing.ReleaseCount-deployed.ReleaseCount)
- // 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))
+ // 5. Scale down to one copy, verified from the copies' state and from
+ // the traffic: every read comes from one box.
+ if err := d.operator("run: carlos apps set %s --copies 1, then press enter", cfg.App); err != nil {
+ return err
+ }
+ if verr := d.untilScaledDown(ctx, time.Now()); verr != nil {
+ d.fail("the live view never showed one copy after the scale-down: %v", verr)
+ }
+ d.load(ctx, phaseScaleDown, scaleObserve)
- // 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)
+ // The request records and generation events, then every window.
+ if err := d.operator("export the hub's and the boxes' request records and the boxes' generation events to %s, %s and %s, then press enter",
+ d.out("hub-records.jsonl"), d.out("box-records.jsonl"), d.out("generations.jsonl")); err != nil {
+ return err
+ }
+ hub, herr := readRecords(d.out("hub-records.jsonl"))
+ boxes, berr := readRecords(d.out("box-records.jsonl"))
+ events, gerr := readGenerations(d.out("generations.jsonl"))
+ if herr != nil || berr != nil || gerr != nil {
+ d.fail("evidence unreadable: %v %v %v", herr, berr, gerr)
+ }
+ ordered, why := orderedSwitch(events, []string{cfg.BoxA, cfg.BoxB}, from, to)
+ report.Ordered = ordered
+ if !ordered {
+ d.fail("the good deploy did not switch in order: %s", why)
}
all := d.all()
- for _, phase := range []string{phaseSpread, phaseStop, phaseReturn, phaseDeploy, phaseFailing} {
- t := account(all, hub, boxes, cfg, phase)
+ for _, rule := range drillRules(cfg, stopAt, from, to) {
+ t, jerr := judgeWindow(all, d.issued(rule.Phase), hub, boxes, cfg, rule)
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))
+ if rule.Phase == phaseSpread {
+ report.ByBox = t.ByBox
+ }
+ d.note("window %s: %d reads %v, hub %v, boxes %v, %d failed before headers, %d errors, %d cut, %d cut streams, %d lost, %d problems",
+ rule.Phase, t.Samples, t.ByBox, t.HubByBox, t.BoxRecords, t.PreHeaderFailures, t.HTTPErrors, t.Truncated, t.StreamCuts, t.Lost, 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 jerr != nil {
+ d.fail("%v", jerr)
}
}
- 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 {
+ if n := report.ByBox[cfg.BoxA] + report.ByBox[cfg.BoxB]; 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
+ return nil
}
-// note writes a timestamped line to drill.log and to the terminal.
+// out is a path in the output directory.
+func (d *drill) out(name string) string { return filepath.Join(d.cfg.OutputDir, name) }
+
+// note writes a timestamped line to drill.log and to the terminal. A
+// failed write is kept: the drill cannot pass without its log.
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)
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if _, err := fmt.Fprintln(d.log, line); err != nil && d.logErr == nil {
+ d.logErr = err
+ }
+}
+
+// fail records a failed check.
+func (d *drill) fail(format string, args ...any) {
+ msg := fmt.Sprintf(format, args...)
+ d.note("FAILED: %s", msg)
+ d.mu.Lock()
+ d.failed = append(d.failed, msg)
+ d.mu.Unlock()
}
-// operator waits for the operator's explicit action.
-func (d *drill) operator(format string, args ...any) {
+// operator waits for the operator's explicit confirmation. A closed or
+// failed input is an error: the action was never confirmed.
+func (d *drill) operator(format string, args ...any) error {
d.note("OPERATOR: "+format, args...)
- _, _ = d.in.ReadString('\n')
+ if _, err := d.in.ReadString('\n'); err != nil {
+ return fmt.Errorf("operator input: %w", err)
+ }
d.note("operator done")
+ return nil
+}
+
+// tip is the build both drill boxes run, from carlos fleets show (its BOX
+// STATE VERSION table). Boxes on different builds, or one the console
+// cannot name, is an error.
+func (d *drill) tip(ctx context.Context) (string, error) {
+ out, err := d.carlos(ctx, "fleets", "show", d.cfg.Fleet)
+ if err != nil {
+ return "", err
+ }
+ versions := map[string]string{}
+ for _, line := range strings.Split(out, "\n") {
+ f := strings.Fields(line)
+ if len(f) >= 3 && (f[0] == d.cfg.BoxA || f[0] == d.cfg.BoxB) {
+ versions[f[0]] = f[2]
+ }
+ }
+ a, b := versions[d.cfg.BoxA], versions[d.cfg.BoxB]
+ if a == "" || a == "unknown" || a != b {
+ return "", fmt.Errorf("%s runs %q and %s runs %q", d.cfg.BoxA, a, d.cfg.BoxB, b)
+ }
+ return a, nil
+}
+
+// carlos runs the operator's logged-in CLI with the drill's console and
+// account, and returns its output.
+func (d *drill) carlos(ctx context.Context, args ...string) (string, error) {
+ 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...).CombinedOutput()
+ if err != nil {
+ return string(out), fmt.Errorf("carlos %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(string(out)))
+ }
+ return string(out), nil
}
// ready sends probe reads until both boxes have answered one.
@@ -308,8 +440,7 @@ func (d *drill) ready(ctx context.Context) error {
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 {
+ if s := d.read(ctx, phaseProbe, false); s.Complete && ok2xx(s.Status) {
seen[s.Box] = true
}
select {
@@ -321,19 +452,24 @@ func (d *drill) ready(ctx context.Context) error {
return nil
}
-// load sends Rate reads a second of phase for dur; one in twenty is a
-// streamed read.
+// load sends Rate reads a second of phase for dur.
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()
+ d.loadUntil(ctx, phase)
+}
+
+// loadUntil sends Rate reads a second of phase until ctx ends, one in
+// twenty streamed, and returns once every read it sent has a sample.
+func (d *drill) loadUntil(ctx context.Context, phase string) {
+ d.note("load %s at %d/s", phase, d.cfg.Rate)
tick := time.NewTicker(time.Second / time.Duration(d.cfg.Rate))
defer tick.Stop()
var wg sync.WaitGroup
+ defer wg.Wait()
for n := 0; ; n++ {
select {
case <-ctx.Done():
- wg.Wait()
return
case <-tick.C:
}
@@ -345,15 +481,28 @@ func (d *drill) load(ctx context.Context, phase string, dur time.Duration) {
}
}
-// 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()) {
+// loadAround keeps phase's load running while act, the operator's step,
+// runs, and for observe after act confirms it. An error from act stops the
+// load and is returned.
+func (d *drill) loadAround(ctx context.Context, phase string, observe time.Duration, act func() error) error {
+ lctx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() {
- d.load(ctx, phase, dur)
+ d.loadUntil(lctx, phase)
close(done)
}()
- act()
+ err := act()
+ if err == nil {
+ d.note("observing %s for %s", phase, observe)
+ select {
+ case <-ctx.Done():
+ err = ctx.Err()
+ case <-time.After(observe):
+ }
+ }
+ cancel()
<-done
+ return err
}
// read sends one uniquely named read and records how it went.
@@ -389,6 +538,13 @@ func (d *drill) read(ctx context.Context, phase string, stream bool) sample {
return s
}
+// issued is how many requests of phase the drill sent.
+func (d *drill) issued(phase string) int {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.seq[phase]
+}
+
// all is every sample so far.
func (d *drill) all() []sample {
d.mu.Lock()
@@ -396,39 +552,17 @@ func (d *drill) all() []sample {
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 {
+// lastBuild is the build the last complete read of phase served.
+func (d *drill) lastBuild(phase string) string {
all := d.all()
for i := len(all) - 1; i >= 0; i-- {
- if all[i].Complete {
+ if all[i].Phase == phase && all[i].Complete && ok2xx(all[i].Status) {
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"`
@@ -445,174 +579,308 @@ func (d *drill) state(ctx context.Context) (fixtureState, error) {
req.Header.Set("Cache-Control", "no-cache")
res, err := d.client.Do(req)
if err != nil {
- return st, err
+ return st, fmt.Errorf("fixture state: %w", 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)
+ if err := json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&st); err != nil {
+ return st, fmt.Errorf("fixture state: %w", err)
+ }
d.note("fixture state: %+v", st)
- return st, err
+ return st, nil
}
// 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)
- }
+// total copies (copiesOf), and notes how long after since that took, as an
+// observation. It returns errNotFound, with the last CLI error, when the
+// state never appears within viewBound. Every CLI error is noted.
+func (d *drill) untilCopies(ctx context.Context, since time.Time, healthy, total int) error {
+ return d.untilView(ctx, since, fmt.Sprintf("%d of %d copies", healthy, total), func(out string) bool {
+ v := copiesOf(out, d.cfg.Host)
+ return v.healthy == healthy && v.total == total
+ })
+}
+
+// untilScaledDown polls until the host has no copies table and its main
+// row reads running: one copy, from the console's own state.
+func (d *drill) untilScaledDown(ctx context.Context, since time.Time) error {
+ return d.untilView(ctx, since, "one running copy", func(out string) bool {
+ v := copiesOf(out, d.cfg.Host)
+ return v.total == 0 && v.mainRunning
+ })
+}
+
+// untilView is the live-view poll behind untilCopies and untilScaledDown.
+func (d *drill) untilView(ctx context.Context, since time.Time, want string, found func(string) bool) error {
+ var last error
+ for time.Since(since) < viewBound {
+ out, err := d.carlos(ctx, "instances", "list", "--app", d.cfg.App, "--match", d.cfg.Host)
+ if err != nil {
+ last = err
+ d.note("live view: %v", err)
+ } else if found(out) {
+ d.note("observation: the live view showed %s %s after the action:\n%s", want, time.Since(since).Round(time.Millisecond), out)
+ return nil
}
select {
case <-ctx.Done():
- return time.Since(since)
+ return ctx.Err()
case <-time.After(250 * time.Millisecond):
}
}
- d.note("the live view never showed %d of %d copies", healthy, total)
- return time.Since(since)
+ if last != nil {
+ return fmt.Errorf("%w: %s within %s; last CLI error: %v", errNotFound, want, viewBound, last)
+ }
+ return fmt.Errorf("%w: %s within %s", errNotFound, want, viewBound)
+}
+
+// copyView is one host's rows in carlos instances list.
+type copyView struct {
+ healthy, total int // its rows in the copies table, and the healthy ones
+ mainRunning bool // its main row reads running
}
-// 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
+// copiesOf reads carlos instances list for host. The copies table's
+// columns are HOST BOX BUILD STATE HEALTH WORKERS (a missing copy shows
+// "-" for box and build); a host with one copy has no copies table.
+func copiesOf(out, host string) copyView {
+ var v copyView
+ inCopies := 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"
+ inCopies = len(f) >= 6 && f[1] == "BOX" && f[4] == "HEALTH"
continue
}
if f[0] != host {
continue
}
if !inCopies {
- mainRow = true
+ v.mainRunning = slices.Contains(f, "running")
continue
}
- total++
- if f[len(f)-2] == "healthy" {
- healthy++
+ if len(f) >= 5 {
+ v.total++
+ if f[4] == "healthy" {
+ v.healthy++
+ }
}
}
- if total == 0 && mainRow {
- return 1, 1
- }
- return healthy, total
+ return v
}
-// socketWatch holds a websocket to the fixture open, reconnecting when it
-// drops, and records the longest gap.
+// socketWatch holds a websocket to the fixture, first pinned to one box,
+// reconnecting when it drops, until stopped.
type socketWatch struct {
cancel context.CancelFunc
- done chan time.Duration
+ done chan socketResult
}
-func (w socketWatch) stop() time.Duration {
+// socketResult is what one websocket watch saw.
+type socketResult struct {
+ Box string // the box the first connection reached
+ Connected bool // the pinned box was reached at all
+ Drops int // connections that dropped while watched
+ Open bool // a drop was still waiting for its reconnect at the end
+ Longest time.Duration // the longest reconnect
+ Err string // the last dial error
+}
+
+// verdict is why the watch fails, or "": it never reached its box, or a
+// drop never reconnected, or (the stopped box's socket) it never dropped.
+func (r socketResult) verdict(stopped bool) string {
+ switch {
+ case !r.Connected:
+ return "never connected to its box: " + r.Err
+ case r.Open:
+ return "dropped and never reconnected: " + r.Err
+ case stopped && r.Drops == 0:
+ return "never dropped while its box was stopped"
+ }
+ return ""
+}
+
+// stop ends the watch and returns what it saw. It closes the open
+// connection, so it never waits on a healthy socket.
+func (w *socketWatch) stop() socketResult {
w.cancel()
- return <-w.done
+ select {
+ case r := <-w.done:
+ return r
+ case <-time.After(2 * handshakeBound):
+ return socketResult{Err: "the websocket watch did not stop"}
+ }
}
-// watchSocket keeps a websocket to /cable open until stopped.
-func (d *drill) watchSocket(ctx context.Context) socketWatch {
+// watchSocket opens a websocket pinned to box: it dials /cable until the
+// upgrade's X-Drill-Box names box (for up to a minute), then holds it and
+// reconnects, to any copy, whenever it drops.
+func (d *drill) watchSocket(ctx context.Context, box string) *socketWatch {
ctx, cancel := context.WithCancel(ctx)
- w := socketWatch{cancel: cancel, done: make(chan time.Duration, 1)}
+ w := &socketWatch{cancel: cancel, done: make(chan socketResult, 1)}
+ var mu sync.Mutex
+ var current net.Conn
go func() {
- var longest time.Duration
- var lost time.Time
- for ctx.Err() == nil {
- conn, err := d.dialSocket(ctx)
+ <-ctx.Done()
+ mu.Lock()
+ if current != nil {
+ current.Close()
+ }
+ mu.Unlock()
+ }()
+ hold := func(c net.Conn) {
+ mu.Lock()
+ current = c
+ mu.Unlock()
+ if ctx.Err() != nil {
+ c.Close()
+ }
+ _, _ = io.Copy(io.Discard, c) // returns when the connection drops or is closed
+ c.Close()
+ mu.Lock()
+ current = nil
+ mu.Unlock()
+ }
+ go func() {
+ r := socketResult{Box: box}
+ pinBy := time.Now().Add(time.Minute)
+ for ctx.Err() == nil && !r.Connected && time.Now().Before(pinBy) {
+ c, got, err := d.dialSocket(ctx)
if err != nil {
- if lost.IsZero() {
- lost = time.Now()
- }
+ r.Err = err.Error()
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{}
+ if got != box {
+ c.Close()
+ continue
}
- _, _ = io.Copy(io.Discard, conn) // returns when the connection drops
- conn.Close()
+ r.Connected = true
+ d.note("websocket connected to %s", box)
+ hold(c)
+ }
+ var lost time.Time
+ if r.Connected && ctx.Err() == nil {
+ lost = time.Now()
+ r.Drops++
+ d.note("websocket pinned to %s dropped", box)
+ }
+ for r.Connected && ctx.Err() == nil {
+ c, got, err := d.dialSocket(ctx)
+ if err != nil {
+ r.Err = err.Error()
+ time.Sleep(100 * time.Millisecond)
+ continue
+ }
+ gap := time.Since(lost)
+ r.Longest = max(r.Longest, gap)
+ d.note("observation: websocket pinned to %s reconnected to %s after %s", box, got, gap)
+ lost = time.Time{}
+ hold(c)
if ctx.Err() == nil {
lost = time.Now()
- d.note("websocket dropped")
+ r.Drops++
+ d.note("websocket pinned to %s dropped again", box)
}
}
- w.done <- longest
+ r.Open = !lost.IsZero()
+ w.done <- r
}()
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) {
+// the upgrade request and a 101 answer, within handshakeBound. It returns
+// the box the 101 answer names.
+func (d *drill) dialSocket(ctx context.Context) (net.Conn, string, error) {
+ dctx, cancel := context.WithTimeout(ctx, handshakeBound)
+ defer cancel()
dialer := &tls.Dialer{Config: &tls.Config{ServerName: d.cfg.Host}}
- conn, err := dialer.DialContext(ctx, "tcp", d.cfg.Host+":443")
+ conn, err := dialer.DialContext(dctx, "tcp", d.cfg.Host+":443")
if err != nil {
- return nil, err
+ return nil, "", err
+ }
+ if err := conn.SetDeadline(time.Now().Add(handshakeBound)); err != nil {
+ conn.Close()
+ 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))
+ if _, err := 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)); err != nil {
+ conn.Close()
+ return nil, "", err
+ }
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
conn.Close()
- return nil, err
+ return nil, "", err
}
if res.StatusCode != http.StatusSwitchingProtocols {
conn.Close()
- return nil, fmt.Errorf("websocket upgrade: %s", res.Status)
+ return nil, "", fmt.Errorf("websocket upgrade: %s", res.Status)
}
- return conn, nil
+ if err := conn.SetDeadline(time.Time{}); err != nil {
+ conn.Close()
+ return nil, "", err
+ }
+ return conn, res.Header.Get("X-Drill-Box"), 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) {
+ out := map[string]string{}
+ err := readJSONLines(path, func(n int, line []byte) error {
+ var r struct{ ID, Box string }
+ if err := json.Unmarshal(line, &r); err != nil || r.ID == "" || r.Box == "" {
+ return fmt.Errorf("%s:%d: not a request record", path, n)
+ }
+ if _, dup := out[r.ID]; dup {
+ return fmt.Errorf("%s:%d: request %s recorded twice", path, n, r.ID)
+ }
+ out[r.ID] = r.Box
+ return nil
+ })
+ return out, err
+}
+
+// readGenerations reads the boxes' exported generation events.
+func readGenerations(path string) ([]genEvent, error) {
+ var out []genEvent
+ err := readJSONLines(path, func(n int, line []byte) error {
+ var e genEvent
+ if err := json.Unmarshal(line, &e); err != nil || e.Box == "" || e.Build == "" || e.At.IsZero() || (e.Event != "serving" && e.Event != "retired") {
+ return fmt.Errorf("%s:%d: not a generation event", path, n)
+ }
+ out = append(out, e)
+ return nil
+ })
+ return out, err
+}
+
+// readJSONLines calls each for every non-blank line of path.
+func readJSONLines(path string, each func(n int, line []byte) error) error {
f, err := os.Open(path)
if err != nil {
- return nil, err
+ return 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 err := each(n, []byte(line)); err != nil {
+ return err
}
- 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()
+ return sc.Err()
}