carlos / platform Public

drill: real CLI labels, one failing release, hub minute counts (#511)

Final-wave item 9 of stateless replicas Plan 4.

(a) The live view is parsed by column from the CLI's real output: the
copies table's capitalised Running/Healthy labels, the main row's HEALTH
and its REASON cell. The parser is tested against testdata/view, which
the root package's TestReplicaDrillViewFixturesMatchRenderer renders with
printInstancesList and keeps in sync. The lower-case fixtures are gone.

(b) The failing-release step (failingRelease) requires the fixture's
release counter to move by exactly one, and the live view to show the
console's failed deploy state after the good deploy showed complete.

(c) B3: the hub keeps no per-request records, only per-minute counts.
The per-request record exports are dropped. The drill reads the hub's
kind=minute records through carlos logs and reconciles them with every
response the client saw (state reads and websocket dials included):
per minute within clockSkew (2 s) of a minute's edge, exactly over the
whole drill, a missing minute or an unexplained 5xx failing. Each read's
box and build is checked against the boxes' generation events.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e763088c34aed706973519bada7e5218a319ec62 parent 7056416
14 files changed, +1,227 −253
  • instances_copies_drill_fixture_test.go +82 −0
  • scripts/stateless-replicas-drill/accounting.go +25 −43
  • scripts/stateless-replicas-drill/accounting_test.go +294 −115
  • scripts/stateless-replicas-drill/evidence.go +308 −0
  • scripts/stateless-replicas-drill/main.go +202 −95
  • scripts/stateless-replicas-drill/testdata/view/one-copy-asleep.txt +2 −0
  • scripts/stateless-replicas-drill/testdata/view/one-copy-not-responding.txt +2 −0
  • scripts/stateless-replicas-drill/testdata/view/one-copy.txt +2 −0
  • scripts/stateless-replicas-drill/testdata/view/one-of-two-missing.txt +6 −0
  • scripts/stateless-replicas-drill/testdata/view/one-of-two.txt +6 −0
  • scripts/stateless-replicas-drill/testdata/view/two-of-two-done.txt +7 −0
  • scripts/stateless-replicas-drill/testdata/view/two-of-two-failed.txt +6 −0
  • scripts/stateless-replicas-drill/view.go +147 −0
  • scripts/stateless-replicas-drill/view_test.go +138 −0
diff --git a/instances_copies_drill_fixture_test.go b/instances_copies_drill_fixture_test.go
new file mode 100644
index 000000000..3331c1861
--- /dev/null
+++ b/instances_copies_drill_fixture_test.go
@@ -0,0 +1,82 @@
+package main
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/replicas"
+)
+
+// drillViewFixtures are the carlos instances list outputs the stateless
+// replicas drill (scripts/stateless-replicas-drill) parses, rendered by the
+// real printInstancesList. The drill is its own program and cannot import
+// this package, so its parser is tested against these files, and this test
+// keeps them equal to what the renderer prints today: a change to the
+// table's labels or layout fails here until the fixtures are rewritten
+// (CARLOS_DRILL_FIXTURES_UPDATE=1) and the drill's parser tests pass again.
+func drillViewFixtures() map[string][]apiInstanceRecord {
+ no, yes := false, true
+ host := "shop.example.com"
+ copy := func(box, version, state string, healthy bool) replicas.Copy {
+ return replicas.Copy{Box: box, Version: version, State: state, Healthy: healthy, WorkersRunning: 1, WorkersDeclared: 1}
+ }
+ base := func(health, status string, copies ...replicas.Copy) apiInstanceRecord {
+ return apiInstanceRecord{Host: host, Region: "fleet/pi", Channel: "stable", Health: health, Runtime: "rootfs-v1",
+ Hibernate: &no, DesiredCopies: len(copies), Copies: copies, DeployStatus: status, CreatedAt: "2026-11-11", CreatedBy: "ops"}
+ }
+ other := apiInstanceRecord{Host: "other.example.com", Region: "fleet/pi", Channel: "stable", Health: "Running", Hibernate: &no}
+ asleep := base("Asleep", "")
+ asleep.Hibernate = &yes
+ return map[string][]apiInstanceRecord{
+ // The hard-stop: one copy running and healthy, the other down.
+ "one-of-two.txt": {base("Running", "", copy("pi-1", "v1", "running", true), copy("pi-2", "v1", "down", false))},
+ // A copy whose box is not assigned yet.
+ "one-of-two-missing.txt": {base("Running", "", copy("pi-1", "v1", "running", true), replicas.Copy{State: "missing"})},
+ // Both copies back, after a good deploy.
+ "two-of-two-done.txt": {base("Running", "deploy complete", copy("pi-1", "v2", "running", true), copy("pi-2", "v2", "running", true)), other},
+ // The failing release: no copy moved.
+ "two-of-two-failed.txt": {base("Running", "the release command failed, so no copy switched to the new build", copy("pi-1", "v2", "running", true), copy("pi-2", "v2", "running", true))},
+ // Scaled down to one copy: no copies table.
+ "one-copy.txt": {base("Running", "")},
+ // One copy that is not running.
+ "one-copy-asleep.txt": {asleep},
+ "one-copy-not-responding.txt": {base("Not responding", "")},
+ }
+}
+
+func TestReplicaDrillViewFixturesMatchRenderer(t *testing.T) {
+ dir := filepath.Join("scripts", "stateless-replicas-drill", "testdata", "view")
+ update := os.Getenv("CARLOS_DRILL_FIXTURES_UPDATE") == "1"
+ for name, recs := range drillViewFixtures() {
+ var buf bytes.Buffer
+ printInstancesList(&buf, recs)
+ path := filepath.Join(dir, name)
+ if update {
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, buf.Bytes(), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ continue
+ }
+ want, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("%s: %v (rewrite with CARLOS_DRILL_FIXTURES_UPDATE=1)", name, err)
+ }
+ if !bytes.Equal(want, buf.Bytes()) {
+ t.Fatalf("%s is not what carlos instances list prints now; rewrite it with CARLOS_DRILL_FIXTURES_UPDATE=1 and rerun the drill's tests:\n--- fixture\n%s--- renderer\n%s", name, want, buf.Bytes())
+ }
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, e := range entries {
+ if _, ok := drillViewFixtures()[e.Name()]; !ok {
+ t.Fatalf("%s: a fixture no renderer case produces", e.Name())
+ }
+ }
+}
diff --git a/scripts/stateless-replicas-drill/accounting.go b/scripts/stateless-replicas-drill/accounting.go
index d841b93b7..0a707c01b 100644
--- a/scripts/stateless-replicas-drill/accounting.go
+++ b/scripts/stateless-replicas-drill/accounting.go
@@ -11,8 +11,12 @@ import (
// The drill's phases. Warm-up and probe traffic is never measured: it is
// sent before readiness, or to check readiness, and the hub's own health
-// probes are not drill traffic at all.
+// probes are not drill traffic at all. State reads (GET /drill/state) and
+// websocket dials are samples too, never a window's: the hub counts them
+// in its minutes like any other response (judgeEvidence).
const (
+ phaseState = "state"
+ phaseSocket = "socket"
phaseWarmup = "warmup"
phaseProbe = "probe"
phaseSpread = "spread"
@@ -24,9 +28,8 @@ const (
)
// sampleID is the unique request id of request n of phase. It rides on
-// the request (a query parameter, so no cache can answer it) and the hub
-// and box request records name it, so every record can be traced to its
-// phase without the client's table.
+// the request as a query parameter, so no cache can answer it, and every
+// sample can be traced to its phase.
func sampleID(phase string, n int) string {
return "drill-" + phase + "-" + strconv.Itoa(n)
}
@@ -36,6 +39,10 @@ type sample struct {
ID string `json:"id"`
Phase string `json:"phase"`
At time.Time `json:"at"`
+ // Done is when the client finished with it: its body read, or its
+ // error. The hub files a response in the minute it finished, so the
+ // minute counts are reconciled by Done.
+ Done time.Time `json:"done"`
// Status is the response status, 0 when no response header arrived.
Status int `json:"status"`
// Started: the response headers arrived. Complete: the whole body did,
@@ -54,15 +61,13 @@ type sample struct {
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 requests the drill issued and with the hub's and
-// the boxes' request records (request id to the box that served it).
+// reconciled with the requests the drill issued.
type tally struct {
Phase string
// 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
+ // response named.
+ Samples int
+ ByBox map[string]int
// PreHeaderFailures is reads that failed before a response started, or
// that the hub answered with a server error.
PreHeaderFailures int
@@ -78,20 +83,19 @@ type tally struct {
// 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, the issued requests and
- // the records disagree.
+ // Problems is every way the client's table and the issued requests
+ // disagree.
Problems []string
}
// 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{}}
+// passing window behind. Each complete read must name one of the two drill
+// boxes. The hub's per-minute counts and the boxes' generation events are
+// reconciled over every window together (judgeEvidence).
+func account(samples []sample, issued int, cfg drillConfig, phase string) tally {
+ t := tally{Phase: phase, ByBox: map[string]int{}}
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...)) }
@@ -134,21 +138,6 @@ func account(samples []sample, issued int, hub, boxes map[string]string, cfg dri
problem("sample %s names box %q, not %s or %s", s.ID, s.Box, cfg.BoxA, cfg.BoxB)
}
t.ByBox[s.Box]++
- for _, r := range []struct {
- name string
- records map[string]string
- count map[string]int
- }{{"hub", hub, t.HubByBox}, {"box", boxes, t.BoxRecords}} {
- box, ok := r.records[s.ID]
- switch {
- case !ok:
- problem("sample %s has no %s record", s.ID, r.name)
- case box != s.Box:
- problem("sample %s: the %s record names %s, the response %s", s.ID, r.name, box, s.Box)
- default:
- r.count[box]++
- }
- }
}
for n := 0; n < issued; n++ {
if id := sampleID(phase, n); !seen[id] {
@@ -156,13 +145,6 @@ func account(samples []sample, issued int, hub, boxes map[string]string, cfg dri
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] {
- problem("record %s has no sample", id)
- }
- }
- }
sort.Strings(t.Problems)
return t
}
@@ -210,12 +192,12 @@ func drillRules(cfg drillConfig, stopAt time.Time, from, to string) []windowRule
// 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)
+func judgeWindow(samples []sample, issued int, cfg drillConfig, r windowRule) (tally, error) {
+ t := account(samples, issued, cfg, r.Phase)
min := max(r.MinReads, 1)
switch {
case len(t.Problems) > 0:
- return t, fmt.Errorf("%s: %d request record problems, first: %s", r.Phase, len(t.Problems), t.Problems[0])
+ return t, fmt.Errorf("%s: %d sample problems, first: %s", r.Phase, len(t.Problems), t.Problems[0])
case t.ProbeRequests != 0:
return t, fmt.Errorf("%s: %d probe requests were counted", r.Phase, t.ProbeRequests)
case t.PreHeaderFailures != 0:
diff --git a/scripts/stateless-replicas-drill/accounting_test.go b/scripts/stateless-replicas-drill/accounting_test.go
index 871d5e2eb..07fa5a6a3 100644
--- a/scripts/stateless-replicas-drill/accounting_test.go
+++ b/scripts/stateless-replicas-drill/accounting_test.go
@@ -21,45 +21,33 @@ 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. It returns how many spread requests were
-// issued.
-func drillFixture() ([]sample, int, map[string]string, map[string]string) {
+// failed before any header, and one stream cut after its headers. It
+// returns how many spread requests were issued.
+func drillFixture() ([]sample, int) {
var samples []sample
- hub, boxes := map[string]string{}, map[string]string{}
add := func(s sample) {
s.At = drillT0.Add(time.Duration(len(samples)) * 50 * time.Millisecond)
+ s.Done = s.At.Add(20 * time.Millisecond)
samples = append(samples, s)
}
for i := 0; i < 5; i++ {
- id := sampleID(phaseWarmup, i)
- add(sample{ID: id, Phase: phaseWarmup, Status: 200, Started: true, Complete: true, Box: "a"})
- hub[id], boxes[id] = "a", "a"
+ add(sample{ID: sampleID(phaseWarmup, i), Phase: phaseWarmup, Status: 200, Started: true, Complete: true, Box: "a"})
}
for i := 0; i < 40; i++ {
- id := sampleID(phaseSpread, i)
box := []string{"a", "b"}[i%2]
- add(sample{ID: id, Phase: phaseSpread, Status: 200, Started: true, Complete: true, Box: box})
- hub[id], boxes[id] = box, box
+ add(sample{ID: sampleID(phaseSpread, i), Phase: phaseSpread, Status: 200, Started: true, Complete: true, Box: box})
}
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[sampleID(phaseProbe, 0)], boxes[sampleID(phaseProbe, 0)] = "b", "b"
+ add(sample{ID: sampleID(phaseSpread, 41), Phase: phaseSpread, Status: 200, Started: true, Stream: true, Box: "b", Err: "unexpected EOF"})
add(sample{ID: sampleID(phaseProbe, 0), Phase: phaseProbe, Status: 200, Started: true, Complete: true, Box: "b"})
- return samples, 42, hub, boxes
+ return samples, 42
}
func TestReplicaDrillAccounting(t *testing.T) {
cfg := drillConfig{BoxA: "a", BoxB: "b"}
spread := windowRule{Phase: phaseSpread, MinReads: 40, Spread: true}
- samples, issued, hub, boxes := drillFixture()
- got := account(samples, issued, hub, boxes, cfg, phaseSpread)
+ samples, issued := drillFixture()
+ got := account(samples, issued, cfg, phaseSpread)
preHeaderFailures, streamCuts, probeRequests := got.PreHeaderFailures, got.StreamCuts, got.ProbeRequests
// TestReplicaDrillAccounting
if preHeaderFailures != 1 || streamCuts != 1 || probeRequests != 0 {
@@ -68,34 +56,31 @@ func TestReplicaDrillAccounting(t *testing.T) {
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.
- for _, box := range []string{"a", "b"} {
- if got.HubByBox[box] != got.ByBox[box] || got.BoxRecords[box] != got.ByBox[box] {
- t.Fatalf("%s: client %d hub %d box %d", box, got.ByBox[box], got.HubByBox[box], got.BoxRecords[box])
- }
- }
// A failed read fails the window, though the spread is even.
- if _, err := judgeWindow(samples, issued, hub, boxes, cfg, spread); err == nil || !strings.Contains(err.Error(), "failed before") {
+ if _, err := judgeWindow(samples, issued, cfg, spread); err == nil || !strings.Contains(err.Error(), "failed before") {
t.Fatalf("a pre-header failure passed: %v", err)
}
// 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()
+ clean := func() ([]sample, int) {
+ s, n := 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"
+ s[i] = sample{ID: s[i].ID, Phase: phaseSpread, At: s[i].At, Done: s[i].Done, Status: 200, Started: true, Complete: true, Box: "a"}
}
}
- return s, n, h, b
+ return s, n
}
- s, n, h, b := clean()
- if _, err := judgeWindow(s, n, h, b, cfg, spread); err != nil {
+ s, n := clean()
+ if _, err := judgeWindow(s, n, cfg, spread); err != nil {
t.Fatalf("the clean window failed: %v", err)
}
- type edit func(s *[]sample, n *int, h, b map[string]string)
+ // The clean window reconciles with hub minutes that count it.
+ if p := judgeEvidence(s, hubCounts(s), nil, map[string]bool{phaseSpread: true}, nil); len(p) != 0 {
+ t.Fatalf("the clean window's evidence disagrees: %v", p)
+ }
+ type edit func(s *[]sample, n *int)
at := func(s []sample, id string) *sample {
for i := range s {
if s[i].ID == id {
@@ -105,64 +90,274 @@ func TestReplicaDrillAccounting(t *testing.T) {
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 is gone: only the
+ // issued count shows it.
+ "lost sample": func(s *[]sample, _ *int) { *s = dropSample(*s, sampleID(phaseSpread, 12)) },
+ "sample never issued": func(_ *[]sample, n *int) { *n = 40 },
+ "sample twice": func(s *[]sample, _ *int) {
+ *s = append(*s, *at(*s, sampleID(phaseSpread, 3)))
},
- // 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)
- },
- "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"
- },
- "a 404 answer": func(s *[]sample, _ *int, _, _ map[string]string) {
+ "unknown box": func(s *[]sample, _ *int) { at(*s, sampleID(phaseSpread, 10)).Box = "c" },
+ "a 404 answer": func(s *[]sample, _ *int) {
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 429 cut stream": func(s *[]sample, _ *int) {
+ at(*s, sampleID(phaseSpread, 41)).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 cut that was not streamed": func(s *[]sample, _ *int) {
+ at(*s, sampleID(phaseSpread, 14)).Complete = false
},
- "a 503 from the hub": func(s *[]sample, _ *int, _, _ map[string]string) {
+ "a 503 from the hub": func(s *[]sample, _ *int) {
at(*s, sampleID(phaseSpread, 15)).Status = 503
},
- "too few samples": func(s *[]sample, n *int, _, _ map[string]string) {
+ "too few samples": func(s *[]sample, n *int) {
*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"
+ "uneven spread": func(s *[]sample, _ *int) { unevenSpread(*s) },
+ "empty table": func(s *[]sample, n *int) { *s, *n = nil, 0 },
+ "stream cut, no reads": func(s *[]sample, _ *int) { onlyCuts(*s) },
+ "probe tagged as the window": func(s *[]sample, _ *int) {
+ *s = append(*s, sample{ID: sampleID(phaseProbe, 9), Phase: phaseSpread, Status: 200, Started: true, Complete: true, Box: "a"})
},
} {
t.Run(name, func(t *testing.T) {
- s, n, h, b := clean()
- e(&s, &n, h, b)
- if _, err := judgeWindow(s, n, h, b, cfg, spread); err == nil {
+ s, n := clean()
+ e(&s, &n)
+ if _, err := judgeWindow(s, n, cfg, spread); err == nil {
t.Fatalf("passed with %s", name)
}
})
}
}
+// hubCounts is the hub's minute records for samples, each response filed
+// in the minute the client finished it.
+func hubCounts(samples []sample) map[time.Time]hubMinute {
+ out := map[time.Time]hubMinute{}
+ for _, s := range samples {
+ if !s.Started || s.Status < 200 {
+ continue
+ }
+ m := minuteOf(s.Done)
+ h := out[m]
+ h.Minute = m
+ switch {
+ case ok2xx(s.Status):
+ h.S2xx++
+ case s.Status >= 500:
+ h.S5xx++
+ default:
+ h.Other++
+ }
+ out[m] = h
+ }
+ return out
+}
+
+// minuteLoad is a steady load over three whole minutes from drillT1, one
+// read a second of phase on alternating boxes, each finished 300 ms after
+// it was sent, with a state read and a websocket dial in the middle minute.
+var drillT1 = time.Date(2026, 11, 11, 22, 0, 0, 0, time.UTC)
+
+func minuteLoad(phase string) []sample {
+ var s []sample
+ for i := 0; i < 180; i++ {
+ at := drillT1.Add(time.Duration(i) * time.Second)
+ s = append(s, sample{ID: sampleID(phase, i), Phase: phase, At: at, Done: at.Add(300 * time.Millisecond),
+ Status: 200, Started: true, Complete: true, Box: []string{"a", "b"}[i%2], Build: "v1"})
+ }
+ mid := drillT1.Add(90 * time.Second)
+ s = append(s, sample{ID: sampleID(phaseState, 0), Phase: phaseState, At: mid, Done: mid.Add(time.Second), Status: 200, Started: true})
+ s = append(s, sample{ID: sampleID(phaseSocket, 0), Phase: phaseSocket, At: mid, Done: mid.Add(time.Second), Status: 101, Started: true, Box: "a"})
+ return s
+}
+
+// TestReplicaDrillHubMinutes (B3): the hub keeps no record of each
+// request, so the client's table is corroborated by the hub's per-minute
+// 2xx and 5xx counts. They must reconcile minute by minute within
+// clockSkew of a minute's edge; a missing minute, a server error the
+// client cannot account for, or counts outside the tolerance fail.
+func TestReplicaDrillHubMinutes(t *testing.T) {
+ measured := map[string]bool{phaseSpread: true}
+ m0, m1, m2 := drillT1, drillT1.Add(time.Minute), drillT1.Add(2*time.Minute)
+ for _, c := range []struct {
+ name string
+ edit func(s []sample, hub map[time.Time]hubMinute) []sample
+ pass bool
+ }{
+ {"reconciled minutes", nil, true},
+ {"a response near a minute's edge counted in the next minute", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ // Read 59 finished at 59.3 s; at 59.9 s it is within clockSkew
+ // of the edge, and the hub may file it at 1:00.
+ s[59].Done = m0.Add(59900 * time.Millisecond)
+ h0, h1 := hub[m0], hub[m1]
+ h0.S2xx--
+ h1.S2xx++
+ hub[m0], hub[m1] = h0, h1
+ return s
+ }, true},
+ {"more responses moved to the next minute than finished near the edge", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ // Reads 0, 1, 58 and 59 of the first minute finished within
+ // clockSkew of an edge; five counts moved is one too many.
+ h0, h1 := hub[m0], hub[m1]
+ h0.S2xx -= 5
+ h1.S2xx += 5
+ hub[m0], hub[m1] = h0, h1
+ return s
+ }, false},
+ {"responses near the edge moved to the next minute", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ h0, h1 := hub[m0], hub[m1]
+ h0.S2xx -= 2
+ h1.S2xx += 2
+ hub[m0], hub[m1] = h0, h1
+ return s
+ }, true},
+ {"one 2xx more in an unmeasured minute of the drill", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ for i := range s {
+ if s[i].Phase == phaseSpread && s[i].At.Before(m1) {
+ s[i].Phase = phaseWarmup
+ }
+ }
+ h := hub[m0]
+ h.S2xx++
+ hub[m0] = h
+ return s
+ }, false},
+ {"a missing minute", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ delete(hub, m1)
+ return s
+ }, false},
+ {"the last minute missing", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ delete(hub, m2)
+ return s
+ }, false},
+ {"one 2xx more at the hub", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ h := hub[m1]
+ h.S2xx++
+ hub[m1] = h
+ return s
+ }, false},
+ {"one 2xx fewer at the hub", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ h := hub[m1]
+ h.S2xx--
+ hub[m1] = h
+ return s
+ }, false},
+ {"a 5xx in a hub minute the client never saw", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ h := hub[m1]
+ h.S5xx++
+ hub[m1] = h
+ return s
+ }, false},
+ {"a read answered 5xx, counted by the hub", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ s[100].Status, s[100].Complete = 503, false
+ h := hub[m1]
+ h.S2xx--
+ h.S5xx++
+ hub[m1] = h
+ return s
+ }, false},
+ {"a websocket dial the client saw answered 5xx", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ s[len(s)-1].Status = 502
+ h := hub[m1]
+ h.S5xx++
+ hub[m1] = h
+ return s
+ }, true},
+ {"a measured response with no finish time", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ s[10].Done = time.Time{}
+ return s
+ }, false},
+ {"no hub records at all", func(s []sample, hub map[time.Time]hubMinute) []sample {
+ clear(hub)
+ return s
+ }, false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ s := minuteLoad(phaseSpread)
+ hub := hubCounts(s)
+ if c.edit != nil {
+ s = c.edit(s, hub)
+ }
+ problems := judgeEvidence(s, hub, nil, measured, nil)
+ if (len(problems) == 0) != c.pass {
+ t.Fatalf("%s: pass %v, want %v: %v", c.name, len(problems) == 0, c.pass, problems)
+ }
+ })
+ }
+ // Minutes with no measured traffic are not judged: warm-up only.
+ warm := minuteLoad(phaseWarmup)
+ if p := judgeEvidence(warm, nil, nil, measured, nil); len(p) != 0 {
+ t.Fatalf("unmeasured minutes were judged: %v", p)
+ }
+}
+
+// TestReplicaDrillParseHubMinutes: the counts are read from carlos logs'
+// own lines; a record missing a count, a minute twice or a cut listing is
+// an error, never fewer minutes.
+func TestReplicaDrillParseHubMinutes(t *testing.T) {
+ line := func(minute string, s2xx, s5xx int) string {
+ return fmt.Sprintf("2026-11-11 22:01:05 [edge] minute %s kind=minute m_get=%d minute=%s s2xx=%d s3xx=0 s404=0 s4xx=0 s5xx=%d wakes=0", minute, s2xx+s5xx, minute, s2xx, s5xx)
+ }
+ out := line("2026-11-11T22:00:00Z", 58, 0) + "\n" + line("2026-11-11T22:01:00Z", 60, 1) + "\n"
+ got, err := parseHubMinutes(out)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if h := got[drillT1.Add(time.Minute)]; len(got) != 2 || h.S2xx != 60 || h.S5xx != 1 || got[drillT1].S2xx != 58 {
+ t.Fatalf("minutes %+v", got)
+ }
+ if got, err := parseHubMinutes("no log lines in this window\n"); err != nil || len(got) != 0 {
+ t.Fatalf("an empty window: %v %v", got, err)
+ }
+ for name, bad := range map[string]string{
+ "no s2xx": "2026-11-11 22:01:05 [edge] minute x kind=minute minute=2026-11-11T22:00:00Z s5xx=0",
+ "no s5xx": "2026-11-11 22:01:05 [edge] minute x kind=minute minute=2026-11-11T22:00:00Z s2xx=4",
+ "no minute": "2026-11-11 22:01:05 [edge] minute x kind=minute s2xx=4 s5xx=0",
+ "not a minute": "2026-11-11 22:01:05 [edge] minute x kind=minute minute=2026-11-11T22:00:30Z s2xx=4 s5xx=0",
+ "bad count": "2026-11-11 22:01:05 [edge] minute x kind=minute minute=2026-11-11T22:00:00Z s2xx=-1 s5xx=0",
+ "minute twice": line("2026-11-11T22:00:00Z", 1, 0) + "\n" + line("2026-11-11T22:00:00Z", 1, 0),
+ "cut short": line("2026-11-11T22:00:00Z", 1, 0) + "\n(showing the newest 5000 lines of this window — narrow it, or raise -n)",
+ } {
+ if _, err := parseHubMinutes(bad); err == nil {
+ t.Errorf("%s: parsed", name)
+ }
+ }
+}
+
+// TestReplicaDrillGenerations: each read's box and build is corroborated
+// by that box's own generation events.
+func TestReplicaDrillGenerations(t *testing.T) {
+ measured := map[string]bool{phaseDeploy: true}
+ read := func(sec int, box, build string) sample {
+ at := drillT1.Add(time.Duration(sec) * time.Second)
+ return sample{ID: sampleID(phaseDeploy, sec), Phase: phaseDeploy, At: at, Done: at.Add(300 * time.Millisecond), 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: drillT1.Add(time.Duration(sec) * time.Second)}
+ }
+ events := []genEvent{ev(10, "a", "v2", "serving"), ev(12, "a", "v1", "retired"), ev(20, "b", "v2", "serving"), ev(22, "b", "v1", "retired")}
+ for _, c := range []struct {
+ name string
+ s sample
+ pass bool
+ }{
+ {"old build before the switch (no earlier event)", read(5, "a", "v1"), true},
+ {"old build as it retires", read(11, "a", "v1"), true},
+ {"new build after it started", read(15, "a", "v2"), true},
+ {"old build long after its box retired it", read(30, "a", "v1"), false},
+ {"new build before its box started it", read(5, "b", "v2"), false},
+ {"new build on a box with no events for it", read(5, "c", "v2"), false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ p := judgeEvidence([]sample{c.s}, map[time.Time]hubMinute{drillT1: {Minute: drillT1, S2xx: 1}}, events, measured, []string{"v2"})
+ if (len(p) == 0) != c.pass {
+ t.Fatalf("pass %v, want %v: %v", len(p) == 0, c.pass, p)
+ }
+ })
+ }
+}
+
// TestReplicaDrillWindowRules: the stop, deploy, failing and scale-down
// windows' rules (drillRules) refuse what they must, over the clean
// window's reads.
@@ -174,43 +369,40 @@ func TestReplicaDrillWindowRules(t *testing.T) {
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) {
+ // on box a from at, all on build.
+ window := func(phase string, n int, build string) ([]sample, int) {
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
+ s = append(s, sample{ID: sampleID(phase, i), Phase: phase, At: when, Status: 200, Started: true, Complete: true, Box: box, Build: build})
}
- return s, n, h, b
+ return s, n
}
for _, c := range []struct {
name string
phase string
- edit func(s []sample, n *int, h, b map[string]string) []sample
+ edit func(s []sample, n *int) []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 {
+ {"stop window empty", phaseStop, func(s []sample, n *int) []sample { *n = 0; return nil }, false},
+ {"stop window all cut", phaseStop, func(s []sample, _ *int) []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 {
+ {"stop window all 404", phaseStop, func(s []sample, _ *int) []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 {
+ {"stop window, no survivor reads after the stop", phaseStop, func(s []sample, n *int) []sample {
var kept []sample
for _, x := range s {
if x.At.Before(stopAt) {
@@ -221,19 +413,19 @@ func TestReplicaDrillWindowRules(t *testing.T) {
return kept
}, false},
{"deploy window passes", phaseDeploy, nil, true},
- {"deploy window, a third build", phaseDeploy, func(s []sample, _ *int, _, _ map[string]string) []sample {
+ {"deploy window, a third build", phaseDeploy, func(s []sample, _ *int) []sample {
s[3].Build = "v3"
return s
}, false},
- {"failing window, the failing build served", phaseFailing, func(s []sample, _ *int, _, _ map[string]string) []sample {
+ {"failing window, the failing build served", phaseFailing, func(s []sample, _ *int) []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},
+ {"failing window empty", phaseFailing, func(s []sample, n *int) []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 {
+ {"scale-down from one box", phaseScaleDown, func(s []sample, _ *int) []sample {
for i := range s {
- s[i].Box, h[s[i].ID], b[s[i].ID] = "a", "a", "a"
+ s[i].Box = "a"
}
return s
}, true},
@@ -243,11 +435,11 @@ func TestReplicaDrillWindowRules(t *testing.T) {
if c.phase == phaseDeploy {
build = "v1"
}
- s, n, h, b := window(c.phase, 40, build)
+ s, n := window(c.phase, 40, build)
if c.edit != nil {
- s = c.edit(s, &n, h, b)
+ s = c.edit(s, &n)
}
- _, err := judgeWindow(s, n, h, b, cfg, rules[c.phase])
+ _, err := judgeWindow(s, n, cfg, rules[c.phase])
if (err == nil) != c.pass {
t.Fatalf("%s: pass %v, want %v (%v)", c.name, err == nil, c.pass, err)
}
@@ -265,11 +457,11 @@ func dropSample(s []sample, id string) []sample {
}
// unevenSpread moves the window's reads to 70% on a.
-func unevenSpread(s []sample, h, b map[string]string) {
+func unevenSpread(s []sample) {
n := 0
for i := range s {
if s[i].Phase == phaseSpread && s[i].Complete && s[i].Box == "b" && n < 8 {
- s[i].Box, h[s[i].ID], b[s[i].ID] = "a", "a", "a"
+ s[i].Box = "a"
n++
}
}
@@ -330,22 +522,9 @@ func TestReplicaDrillOrderedSwitch(t *testing.T) {
}
}
-// 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")
- }
+// TestReplicaDrillInput: a closed operator input is an error, never a
+// confirmation; evidence the drill cannot save fails it.
+func TestReplicaDrillInput(t *testing.T) {
d := &drill{in: bufio.NewReader(strings.NewReader("")), log: devNull(t)}
if err := d.operator(context.Background(), "hard-stop b"); err == nil || !errors.Is(err, io.EOF) {
t.Fatalf("closed input confirmed: %v", err)
diff --git a/scripts/stateless-replicas-drill/evidence.go b/scripts/stateless-replicas-drill/evidence.go
new file mode 100644
index 000000000..2abf35543
--- /dev/null
+++ b/scripts/stateless-replicas-drill/evidence.go
@@ -0,0 +1,308 @@
+package main
+
+import (
+ "fmt"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// The hub keeps no record of each request (#511 B3). What it files is one
+// count record per app and minute (internal/reqrec, kind "minute"): the
+// responses it served that minute by status class, stamped by its own
+// clock when each response finished. The edge that forwards a request
+// over a box's tunnel files it, and the box's edge files nothing, so each
+// drill request is counted once. The drill reads them through the
+// operator's CLI (carlos logs --stream edge --field kind=minute) and
+// corroborates the client's own table with them, minute by minute,
+// together with the boxes' generation events (judgeEvidence).
+//
+// The counts are per app, not per host: the drill's fixture app holds only
+// the drill host, so any other traffic to it makes the hub's counts larger
+// than the client's, and the drill fails.
+
+// clockSkew is how far apart the operator's clock (the client's Done
+// times) and the hub's or a box's clock may be when the drill compares
+// them, one-way latency included. Both are NTP-synchronised, which keeps
+// them well under a second apart; 2 s leaves room for that and for a
+// response the hub finished just before the client read its last byte.
+// Only a response that finished within clockSkew of a minute's edge may be
+// counted in the minute beside the client's; every other response must be
+// in the client's minute, so this is the whole of the counts' tolerance.
+const clockSkew = 2 * time.Second
+
+// hubMinute is the hub's count record for one minute of the app.
+type hubMinute struct {
+ Minute time.Time
+ S2xx, S5xx int
+ // Other is the responses of every other class (3xx, 4xx).
+ Other int
+}
+
+// parseHubMinutes reads carlos logs output for the app's edge minute
+// records: one line a record, its fields printed as key=value after the
+// message. Every kind=minute line must name its minute and its s2xx and
+// s5xx counts; a line that does not, a minute recorded twice, or the CLI's
+// note that it left lines out, is an error: the counts are evidence.
+func parseHubMinutes(out string) (map[time.Time]hubMinute, error) {
+ minutes := map[time.Time]hubMinute{}
+ for n, line := range strings.Split(out, "\n") {
+ if strings.Contains(line, "(showing the newest") {
+ return nil, fmt.Errorf("the hub's minute counts were cut short: %s", strings.TrimSpace(line))
+ }
+ fields := map[string]string{}
+ for _, tok := range strings.Fields(line) {
+ if k, v, ok := strings.Cut(tok, "="); ok {
+ fields[k] = v
+ }
+ }
+ if fields["kind"] != "minute" {
+ continue
+ }
+ at, err := time.Parse(time.RFC3339, fields["minute"])
+ if err != nil || !at.Equal(at.Truncate(time.Minute)) {
+ return nil, fmt.Errorf("line %d: a minute record with no minute: %s", n+1, line)
+ }
+ count := func(k string) (int, error) {
+ v, ok := fields[k]
+ if !ok {
+ return 0, fmt.Errorf("line %d: a minute record with no %s count: %s", n+1, k, line)
+ }
+ x, err := strconv.Atoi(v)
+ if err != nil || x < 0 {
+ return 0, fmt.Errorf("line %d: %s=%q is not a count", n+1, k, v)
+ }
+ return x, nil
+ }
+ m := hubMinute{Minute: at.UTC()}
+ if m.S2xx, err = count("s2xx"); err != nil {
+ return nil, err
+ }
+ if m.S5xx, err = count("s5xx"); err != nil {
+ return nil, err
+ }
+ for _, k := range []string{"s3xx", "s4xx", "s404"} {
+ if _, ok := fields[k]; ok {
+ x, err := count(k)
+ if err != nil {
+ return nil, err
+ }
+ m.Other += x
+ }
+ }
+ if _, dup := minutes[m.Minute]; dup {
+ return nil, fmt.Errorf("line %d: minute %s recorded twice", n+1, m.Minute.Format(time.RFC3339))
+ }
+ minutes[m.Minute] = m
+ }
+ return minutes, nil
+}
+
+// minuteOf is the UTC minute t falls in.
+func minuteOf(t time.Time) time.Time { return t.UTC().Truncate(time.Minute) }
+
+// nearEdge is whether t is within clockSkew of the start or the end of
+// its own minute.
+func nearEdge(t time.Time) bool {
+ m := minuteOf(t)
+ return t.Sub(m) < clockSkew || m.Add(time.Minute).Sub(t) <= clockSkew
+}
+
+// clientMinute is the client's counts for one minute: every response it
+// finished in the minute (lo is those well inside it, which the hub must
+// count in this minute too), and those it finished within clockSkew of
+// the minute's edges in the minutes beside it (out, which the hub may
+// count here).
+type clientMinute struct {
+ lo2xx, in2xx, out2xx int
+ socket5xxIn, socket5xxOut int
+ loAny int
+}
+
+// judgeEvidence corroborates the client's table with the hub's minute
+// counts and the boxes' generation events. It returns every disagreement;
+// none is a pass.
+//
+// Minutes: every minute in which a measured window's request finished is
+// checked, counting every response the client saw in it, whatever its
+// phase (warm-up, probe, state reads and websocket dials included). In
+// each:
+// - the hub must have a record, unless every response the client
+// finished in it is within clockSkew of an edge;
+// - the hub's 2xx count must be at least the client's 2xx responses well
+// inside the minute, and at most every 2xx the client finished in it
+// or within clockSkew of its edges;
+// - every 5xx the hub counted must be a websocket dial the client saw
+// answered with a server error, in or within clockSkew of the minute.
+// A read the hub answered with a server error is never excused: the
+// client may not have seen it as one.
+//
+// Totals: a shift at a minute's edge moves a count between two minutes but
+// never makes or loses one, so over every minute the client's responses
+// can have been filed in (each response's minute, give or take clockSkew)
+// the hub's 2xx count must equal the client's exactly, and its 5xx count
+// must not exceed the websocket dials the client saw fail. One request
+// more or fewer anywhere fails, whatever minute it was filed in.
+//
+// Generations: a complete read that names a box and a build must not come
+// from a generation its box had retired more than clockSkew before the
+// read was sent and not started again by the time it finished; and a read
+// of a build in fresh (one that first ran during the drill: the good
+// deploy's target) must not finish more than clockSkew before its box
+// first started serving that build.
+func judgeEvidence(samples []sample, hub map[time.Time]hubMinute, events []genEvent, measured map[string]bool, fresh []string) []string {
+ var problems []string
+ problem := func(format string, args ...any) { problems = append(problems, fmt.Sprintf(format, args...)) }
+ checked := map[time.Time]bool{}
+ counts := map[time.Time]*clientMinute{}
+ at := func(m time.Time) *clientMinute {
+ c := counts[m]
+ if c == nil {
+ c = &clientMinute{}
+ counts[m] = c
+ }
+ return c
+ }
+ for _, s := range samples {
+ if s.Done.IsZero() {
+ if measured[s.Phase] {
+ problem("sample %s has no finish time", s.ID)
+ }
+ continue
+ }
+ m := minuteOf(s.Done)
+ if measured[s.Phase] {
+ checked[m] = true
+ }
+ if !s.Started || s.Status < 200 {
+ continue // no response the hub counts in a class
+ }
+ c := at(m)
+ edge := nearEdge(s.Done)
+ if !edge {
+ c.loAny++
+ }
+ switch {
+ case ok2xx(s.Status):
+ c.in2xx++
+ if !edge {
+ c.lo2xx++
+ }
+ case s.Status >= 500 && s.Phase == phaseSocket:
+ c.socket5xxIn++
+ }
+ if !edge {
+ continue
+ }
+ // Within clockSkew of an edge: the hub may have counted it in the
+ // minute beside.
+ beside := m.Add(-time.Minute)
+ if s.Done.Sub(m) >= clockSkew {
+ beside = m.Add(time.Minute)
+ }
+ b := at(beside)
+ switch {
+ case ok2xx(s.Status):
+ b.out2xx++
+ case s.Status >= 500 && s.Phase == phaseSocket:
+ b.socket5xxOut++
+ }
+ }
+ minutes := make([]time.Time, 0, len(checked))
+ for m := range checked {
+ minutes = append(minutes, m)
+ }
+ sort.Slice(minutes, func(i, j int) bool { return minutes[i].Before(minutes[j]) })
+ for _, m := range minutes {
+ c := at(m)
+ h, ok := hub[m]
+ when := m.Format(time.RFC3339)
+ if !ok {
+ if c.loAny > 0 {
+ problem("minute %s: the hub has no count record, and the client finished %d responses in it", when, c.loAny)
+ }
+ continue
+ }
+ if lo, hi := c.lo2xx, c.in2xx+c.out2xx; h.S2xx < lo || h.S2xx > hi {
+ problem("minute %s: the hub counted %d 2xx responses, the client %d (%d to %d within %s of the minute's edges)", when, h.S2xx, c.in2xx, lo, hi, clockSkew)
+ }
+ if allowed := c.socket5xxIn + c.socket5xxOut; h.S5xx > allowed {
+ problem("minute %s: the hub answered %d server errors, %d of them websocket dials the client saw fail", when, h.S5xx, allowed)
+ }
+ }
+ if len(checked) > 0 {
+ var client2xx, socket5xx, hub2xx, hub5xx int
+ span := map[time.Time]bool{}
+ for _, s := range samples {
+ if s.Done.IsZero() || !s.Started || s.Status < 200 {
+ continue
+ }
+ span[minuteOf(s.Done.Add(-clockSkew))] = true
+ span[minuteOf(s.Done.Add(clockSkew))] = true
+ switch {
+ case ok2xx(s.Status):
+ client2xx++
+ case s.Status >= 500 && s.Phase == phaseSocket:
+ socket5xx++
+ }
+ }
+ for m := range span {
+ hub2xx += hub[m].S2xx
+ hub5xx += hub[m].S5xx
+ }
+ if hub2xx != client2xx {
+ problem("over the drill the hub counted %d 2xx responses and the client %d", hub2xx, client2xx)
+ }
+ if hub5xx > socket5xx {
+ problem("over the drill the hub answered %d server errors, %d of them websocket dials the client saw fail", hub5xx, socket5xx)
+ }
+ }
+ problems = append(problems, judgeGenerations(samples, events, measured, fresh)...)
+ sort.Strings(problems)
+ return problems
+}
+
+// judgeGenerations is judgeEvidence's generation check.
+func judgeGenerations(samples []sample, events []genEvent, measured map[string]bool, fresh []string) []string {
+ type key struct{ box, build string }
+ byGen := map[key][]genEvent{}
+ for _, e := range events {
+ k := key{e.Box, e.Build}
+ byGen[k] = append(byGen[k], e)
+ }
+ for k := range byGen {
+ sort.SliceStable(byGen[k], func(i, j int) bool { return byGen[k][i].At.Before(byGen[k][j].At) })
+ }
+ var problems []string
+ for _, s := range samples {
+ if !measured[s.Phase] || !s.Complete || !ok2xx(s.Status) || s.Box == "" || s.Build == "" {
+ continue
+ }
+ evs := byGen[key{s.Box, s.Build}]
+ var last *genEvent
+ for i := range evs {
+ if evs[i].At.After(s.Done.Add(clockSkew)) {
+ break
+ }
+ last = &evs[i]
+ }
+ switch {
+ case last != nil && last.Event == "retired" && last.At.Before(s.At.Add(-clockSkew)):
+ problems = append(problems, fmt.Sprintf("read %s: %s served %s, which it retired at %s, before the read was sent at %s",
+ s.ID, s.Box, s.Build, last.At.Format(time.RFC3339Nano), s.At.Format(time.RFC3339Nano)))
+ case last == nil && contains(fresh, s.Build):
+ problems = append(problems, fmt.Sprintf("read %s: %s served %s before its generation events show it serving that build", s.ID, s.Box, s.Build))
+ }
+ }
+ return problems
+}
+
+func contains(list []string, v string) bool {
+ for _, x := range list {
+ if x == v {
+ return true
+ }
+ }
+ return false
+}
diff --git a/scripts/stateless-replicas-drill/main.go b/scripts/stateless-replicas-drill/main.go
index ec3e4e679..6b7f4a1ea 100644
--- a/scripts/stateless-replicas-drill/main.go
+++ b/scripts/stateless-replicas-drill/main.go
@@ -10,9 +10,9 @@
// A run is one booked window on a pre-approved drill fleet (D12); it never
// stops an HA group member or a fixed HA box.
//
-// The fixture app (a small Rails app with external Postgres and Redis, a
-// worker that records heartbeats, a repeat-safe release counter and a
-// websocket endpoint) answers:
+// The fixture app (a small app with external state, a worker that records
+// heartbeats, a repeat-safe release counter and a websocket endpoint)
+// answers:
//
// GET /drill?id=<id> 200, headers X-Drill-Box and X-Drill-Build,
// a body ending "\nend\n"
@@ -23,21 +23,31 @@
// 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. When the drill asks, the operator exports
-// three files into the output directory, one JSON object per line:
+// the fixture's environment. The release counter counts every run of the
+// release command, a failing one included: the failing build's release
+// command adds its run to the counter and then exits non-zero. The app
+// holds only the drill host.
+//
+// The hub keeps no record of each request (#511 B3); it files per-minute
+// counts by status class (evidence.go). The drill reads those through the
+// CLI (carlos logs) and, when it asks, the operator exports one file 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 client's table is corroborated by both (judgeEvidence): the hub's
+// minute counts against every response the client saw, and each read's
+// box and build against that box's generations.
+//
// The drill measures the trimmed list (R17): the even spread; a hard-stop
// 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
+// order) and one failing release (its command runs exactly once, the
+// deploy reaches failed, and no copy moves); 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.
@@ -60,7 +70,7 @@ import (
"os/exec"
"os/signal"
"path/filepath"
- "slices"
+ "strconv"
"strings"
"sync"
"time"
@@ -78,14 +88,19 @@ type drillConfig struct {
// drillReport is the drill's result. Tip is the platform build the drill
// 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.
+// good deploy's release command ran, FailingReleaseRuns the failing
+// one's, and FailingReached whether the live view then showed that
+// deploy failed; ByBox is the even-spread window's complete reads by box;
+// HubMinutes is how many of the hub's minute count records were read;
+// 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
+ FailingReleaseRuns, HubMinutes int
+ FailingReached bool
ByBox map[string]int
MaxReconnect time.Duration
Ordered, Passed bool
@@ -103,6 +118,10 @@ const (
scaleObserve = time.Minute
viewBound = 10 * time.Minute
handshakeBound = 10 * time.Second
+ // hubMinuteWait bounds the wait for the hub's last minute count
+ // record to reach the logs: it is filed after its minute ends and
+ // shipped on the agent's log loop.
+ hubMinuteWait = 5 * time.Minute
)
// drillSummary (SR-4-C32, provisional) takes box A's share, box A, box B's
@@ -159,6 +178,19 @@ type drill struct {
// the system roots, server name host).
socketAddr string
socketTLS *tls.Config
+ // baseURL and viewWait are test seams: the fixture's origin (default
+ // https://<host>) and how long a live-view poll waits (default
+ // viewBound).
+ baseURL string
+ viewWait time.Duration
+}
+
+// origin is the fixture's origin.
+func (d *drill) origin() string {
+ if d.baseURL != "" {
+ return d.baseURL
+ }
+ return "https://" + d.cfg.Host
}
// runDrill runs the whole drill. It returns an error for anything that
@@ -311,16 +343,19 @@ func (d *drill) run(ctx context.Context, report *drillReport) error {
if to == "" || to == from {
d.fail("the good deploy did not change the build (%q to %q)", from, to)
}
+ // The good deploy finished before the failing one starts, so a failed
+ // state seen afterwards is the failing deploy's own.
+ if verr := d.untilStatus(ctx, time.Now(), deployDoneStatus); verr != nil {
+ d.fail("the live view never showed the good deploy complete: %v", verr)
+ }
if err := d.loadAround(ctx, phaseFailing, deployObserve, func() error {
return d.operator(ctx, "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 {
+ if err := d.failingRelease(ctx, report, deployed); err != nil {
return err
}
- d.note("the failing release's command ran %d times", failing.ReleaseCount-deployed.ReleaseCount)
// 5. Scale down to one copy, verified from the copies' state and from
// the traffic: every read comes from one box.
@@ -332,33 +367,49 @@ func (d *drill) run(ctx context.Context, report *drillReport) error {
}
d.load(ctx, phaseScaleDown, scaleObserve)
- // The request records and generation events, then every window.
- if err := d.operator(ctx, "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 {
+ // The generation events, the hub's minute counts, then every window.
+ if err := d.operator(ctx, "export the boxes' generation events to %s, then press enter", 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)
+ if gerr != nil {
+ d.fail("generation events unreadable: %v", gerr)
+ }
+ all := d.all()
+ hub, herr := d.hubMinutes(ctx, all)
+ if herr != nil {
+ d.fail("the hub's minute counts: %v", herr)
}
+ report.HubMinutes = len(hub)
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 _, rule := range drillRules(cfg, stopAt, from, to) {
- t, jerr := judgeWindow(all, d.issued(rule.Phase), hub, boxes, cfg, rule)
+ rules := drillRules(cfg, stopAt, from, to)
+ measured := map[string]bool{}
+ for _, rule := range rules {
+ measured[rule.Phase] = true
+ }
+ if herr == nil && gerr == nil {
+ problems := judgeEvidence(all, hub, events, measured, []string{to})
+ for _, p := range problems {
+ d.note(" %s", p)
+ }
+ if len(problems) > 0 {
+ d.fail("the hub's minute counts or the boxes' generations disagree with the client: %d problems, first: %s", len(problems), problems[0])
+ }
+ }
+ for _, rule := range rules {
+ t, jerr := judgeWindow(all, d.issued(rule.Phase), cfg, rule)
report.Samples += t.Samples
report.PreHeaderFailures += t.PreHeaderFailures
report.StreamCuts += t.StreamCuts
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))
+ d.note("window %s: %d reads %v, %d failed before headers, %d errors, %d cut, %d cut streams, %d lost, %d problems",
+ rule.Phase, t.Samples, t.ByBox, t.PreHeaderFailures, t.HTTPErrors, t.Truncated, t.StreamCuts, t.Lost, len(t.Problems))
for _, p := range t.Problems {
d.note(" %s", p)
}
@@ -594,16 +645,13 @@ func (d *drill) loadAround(ctx context.Context, phase string, observe time.Durat
// read sends one uniquely named read and records how it went.
func (d *drill) read(ctx context.Context, phase string, stream bool) sample {
- d.mu.Lock()
- id := sampleID(phase, d.seq[phase])
- d.seq[phase]++
- d.mu.Unlock()
+ id := d.nextID(phase)
path := "/drill"
if stream {
path = "/drill/stream"
}
s := sample{ID: id, Phase: phase, At: time.Now(), Stream: stream}
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+d.cfg.Host+path+"?id="+id, nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.origin()+path+"?id="+id, nil)
if err == nil {
req.Header.Set("Cache-Control", "no-cache")
var res *http.Response
@@ -619,10 +667,28 @@ func (d *drill) read(ctx context.Context, phase string, stream bool) sample {
if err != nil {
s.Err = err.Error()
}
+ s.Done = time.Now()
+ d.record(s)
+ return s
+}
+
+// record keeps a sample.
+func (d *drill) record(s sample) {
d.mu.Lock()
d.samples = append(d.samples, s)
d.mu.Unlock()
- return s
+}
+
+// nextID names the next request of phase.
+func (d *drill) nextID(phase string) string {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if d.seq == nil {
+ d.seq = map[string]int{}
+ }
+ id := sampleID(phase, d.seq[phase])
+ d.seq[phase]++
+ return id
}
// issued is how many requests of phase the drill sent.
@@ -650,24 +716,53 @@ func (d *drill) lastBuild(phase string) string {
return ""
}
+// failingRelease is the failing deploy's evidence, after its window: its
+// release command ran exactly once (the fixture's counter moved by one
+// from deployed, read after the good deploy), and the attempt reached
+// failed (the live view shows the failed deploy state; the good deploy
+// showed complete before this one began, so the state is this attempt's).
+// The window's rule checks that no copy moved. A failed check is noted;
+// an unreadable counter is an error.
+func (d *drill) failingRelease(ctx context.Context, report *drillReport, deployed fixtureState) error {
+ failing, err := d.state(ctx)
+ if err != nil {
+ return err
+ }
+ report.FailingReleaseRuns = failing.ReleaseCount - deployed.ReleaseCount
+ if report.FailingReleaseRuns != 1 {
+ d.fail("the failing deploy's release command ran %d times, not once", report.FailingReleaseRuns)
+ }
+ if verr := d.untilStatus(ctx, time.Now(), deployFailedStatus); verr != nil {
+ d.fail("the live view never showed the failing deploy as failed: %v", verr)
+ } else {
+ report.FailingReached = true
+ }
+ return nil
+}
+
// fixtureState is the fixture's GET /drill/state.
type fixtureState struct {
ReleaseCount int `json:"release_count"`
Heartbeats map[string]time.Time `json:"heartbeats"`
}
-// state reads the fixture's release counter and worker heartbeats.
+// state reads the fixture's release counter and worker heartbeats. The
+// read is a sample of phaseState: the hub counts it in its minute.
func (d *drill) state(ctx context.Context) (fixtureState, error) {
var st fixtureState
- req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://"+d.cfg.Host+"/drill/state", nil)
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, d.origin()+"/drill/state", nil)
if err != nil {
return st, err
}
req.Header.Set("Cache-Control", "no-cache")
+ s := sample{ID: d.nextID(phaseState), Phase: phaseState, At: time.Now()}
+ defer func() { s.Done = time.Now(); d.record(s) }()
res, err := d.client.Do(req)
if err != nil {
+ s.Err = err.Error()
return st, fmt.Errorf("fixture state: %w", err)
}
+ s.Started, s.Status = true, res.StatusCode
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return st, fmt.Errorf("fixture state: %s", res.Status)
@@ -690,8 +785,16 @@ func (d *drill) untilCopies(ctx context.Context, since time.Time, healthy, total
})
}
+// untilStatus polls until the host's REASON cell reads status: the
+// replicated deploy's state, as the console says it.
+func (d *drill) untilStatus(ctx context.Context, since time.Time, status string) error {
+ return d.untilView(ctx, since, "the deploy state "+strconv.Quote(status), func(out string) bool {
+ return copiesOf(out, d.cfg.Host).reason == status
+ })
+}
+
// untilScaledDown polls until the host has no copies table and its main
-// row reads running: one copy, from the console's own state.
+// 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)
@@ -699,10 +802,15 @@ func (d *drill) untilScaledDown(ctx context.Context, since time.Time) error {
})
}
-// untilView is the live-view poll behind untilCopies and untilScaledDown.
+// untilView is the live-view poll behind untilCopies, untilStatus 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 {
+ bound := viewBound
+ if d.viewWait > 0 {
+ bound = d.viewWait
+ }
+ for time.Since(since) < bound {
out, err := d.carlos(ctx, d.argv([]string{"instances", "list"}, []string{"--app", d.cfg.App, "--match", d.cfg.Host}))
if err != nil {
last = err
@@ -718,47 +826,9 @@ func (d *drill) untilView(ctx context.Context, since time.Time, want string, fou
}
}
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 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) >= 6 && f[1] == "BOX" && f[4] == "HEALTH"
- continue
- }
- if f[0] != host {
- continue
- }
- if !inCopies {
- v.mainRunning = slices.Contains(f, "running")
- continue
- }
- if len(f) >= 5 {
- v.total++
- if f[4] == "healthy" {
- v.healthy++
- }
- }
+ return fmt.Errorf("%w: %s within %s; last CLI error: %v", errNotFound, want, bound, last)
}
- return v
+ return fmt.Errorf("%w: %s within %s", errNotFound, want, bound)
}
// socketWatch holds a websocket to the fixture, first pinned to one box,
@@ -938,6 +1008,10 @@ func (d *drill) watchSocket(ctx context.Context, box string) *socketWatch {
func (d *drill) dialSocket(ctx context.Context) (net.Conn, string, error) {
dctx, cancel := context.WithTimeout(ctx, handshakeBound)
defer cancel()
+ // Each dial is a sample of phaseSocket: an upgrade the hub answered is
+ // counted in its minute, a server error among them (judgeEvidence).
+ s := sample{ID: d.nextID(phaseSocket), Phase: phaseSocket, At: time.Now()}
+ defer func() { s.Done = time.Now(); d.record(s) }()
cfg, addr := d.socketTLS, d.socketAddr
if cfg == nil {
cfg = &tls.Config{ServerName: d.cfg.Host}
@@ -964,8 +1038,10 @@ func (d *drill) dialSocket(ctx context.Context) (net.Conn, string, error) {
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
if err != nil {
conn.Close()
+ s.Err = err.Error()
return nil, "", err
}
+ s.Started, s.Status, s.Box = true, res.StatusCode, res.Header.Get("X-Drill-Box")
if res.StatusCode != http.StatusSwitchingProtocols {
conn.Close()
return nil, "", fmt.Errorf("websocket upgrade: %s", res.Status)
@@ -982,23 +1058,54 @@ func (d *drill) dialSocket(ctx context.Context) (net.Conn, string, error) {
return conn, 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)
+// hubMinutes reads the hub's minute count records for the app through the
+// operator's CLI, from the minute before the first sample to the minute
+// after the last, and keeps the output as hub-minutes.txt. It waits, up
+// to hubMinuteWait, for the record of the last minute the client
+// finished a response in; a minute still missing then is judged missing
+// (judgeEvidence). A CLI error or output it cannot read is an error.
+func (d *drill) hubMinutes(ctx context.Context, samples []sample) (map[time.Time]hubMinute, error) {
+ var first, last time.Time
+ for _, s := range samples {
+ if s.Done.IsZero() {
+ continue
}
- if _, dup := out[r.ID]; dup {
- return fmt.Errorf("%s:%d: request %s recorded twice", path, n, r.ID)
+ if first.IsZero() || s.At.Before(first) {
+ first = s.At
}
- out[r.ID] = r.Box
- return nil
- })
- return out, err
+ if s.Done.After(last) {
+ last = s.Done
+ }
+ }
+ if first.IsZero() {
+ return nil, errors.New("no samples to reconcile")
+ }
+ since, until := minuteOf(first).Add(-time.Minute), minuteOf(last).Add(2*time.Minute)
+ args := d.argv([]string{"logs"}, []string{"--app", d.cfg.App, "--stream", "edge", "--field", "kind=minute",
+ "--since", since.Format(time.RFC3339), "--until", until.Format(time.RFC3339), "-n", "5000"})
+ deadline := time.Now().Add(hubMinuteWait)
+ for {
+ out, err := d.carlos(ctx, args)
+ if err != nil {
+ return nil, err
+ }
+ minutes, perr := parseHubMinutes(out)
+ if werr := os.WriteFile(d.out("hub-minutes.txt"), []byte(out), 0o644); werr != nil {
+ return nil, fmt.Errorf("hub-minutes.txt: %w", werr)
+ }
+ if perr != nil {
+ return nil, perr
+ }
+ if _, ok := minutes[minuteOf(last)]; ok || time.Now().After(deadline) {
+ d.note("the hub's minute counts: %d records from %s to %s", len(minutes), since.Format(time.RFC3339), until.Format(time.RFC3339))
+ return minutes, nil
+ }
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ case <-time.After(15 * time.Second):
+ }
+ }
}
// readGenerations reads the boxes' exported generation events.
diff --git a/scripts/stateless-replicas-drill/testdata/view/one-copy-asleep.txt b/scripts/stateless-replicas-drill/testdata/view/one-copy-asleep.txt
new file mode 100644
index 000000000..b7ac831c7
--- /dev/null
+++ b/scripts/stateless-replicas-drill/testdata/view/one-copy-asleep.txt
@@ -0,0 +1,2 @@
+HOST REGION CHANNEL POOL INSTALLED SERVING HEALTH UPSTREAMS DB EGRESS CREATED BY REASON SEED RUNTIME WORKERS
+shop.example.com fleet/pi stable — Asleep - - - 2026-11-11 ops - rootfs, hibernates -
diff --git a/scripts/stateless-replicas-drill/testdata/view/one-copy-not-responding.txt b/scripts/stateless-replicas-drill/testdata/view/one-copy-not-responding.txt
new file mode 100644
index 000000000..b2f925b25
--- /dev/null
+++ b/scripts/stateless-replicas-drill/testdata/view/one-copy-not-responding.txt
@@ -0,0 +1,2 @@
+HOST REGION CHANNEL POOL INSTALLED SERVING HEALTH UPSTREAMS DB EGRESS CREATED BY REASON SEED RUNTIME WORKERS
+shop.example.com fleet/pi stable — Not responding - - - 2026-11-11 ops - rootfs -
diff --git a/scripts/stateless-replicas-drill/testdata/view/one-copy.txt b/scripts/stateless-replicas-drill/testdata/view/one-copy.txt
new file mode 100644
index 000000000..ffee2f860
--- /dev/null
+++ b/scripts/stateless-replicas-drill/testdata/view/one-copy.txt
@@ -0,0 +1,2 @@
+HOST REGION CHANNEL POOL INSTALLED SERVING HEALTH UPSTREAMS DB EGRESS CREATED BY REASON SEED RUNTIME WORKERS
+shop.example.com fleet/pi stable — Running - - - 2026-11-11 ops - rootfs -
diff --git a/scripts/stateless-replicas-drill/testdata/view/one-of-two-missing.txt b/scripts/stateless-replicas-drill/testdata/view/one-of-two-missing.txt
new file mode 100644
index 000000000..a8a2837f6
--- /dev/null
+++ b/scripts/stateless-replicas-drill/testdata/view/one-of-two-missing.txt
@@ -0,0 +1,6 @@
+HOST REGION CHANNEL POOL INSTALLED SERVING HEALTH UPSTREAMS DB EGRESS CREATED BY REASON SEED RUNTIME WORKERS
+shop.example.com fleet/pi stable — Running - - - 2026-11-11 ops - rootfs -
+
+HOST BOX BUILD STATE HEALTH WORKERS
+shop.example.com pi-1 v1 Running Healthy 1/1
+shop.example.com - - Missing - -
diff --git a/scripts/stateless-replicas-drill/testdata/view/one-of-two.txt b/scripts/stateless-replicas-drill/testdata/view/one-of-two.txt
new file mode 100644
index 000000000..d61600846
--- /dev/null
+++ b/scripts/stateless-replicas-drill/testdata/view/one-of-two.txt
@@ -0,0 +1,6 @@
+HOST REGION CHANNEL POOL INSTALLED SERVING HEALTH UPSTREAMS DB EGRESS CREATED BY REASON SEED RUNTIME WORKERS
+shop.example.com fleet/pi stable — Running - - - 2026-11-11 ops - rootfs -
+
+HOST BOX BUILD STATE HEALTH WORKERS
+shop.example.com pi-1 v1 Running Healthy 1/1
+shop.example.com pi-2 v1 Down Unhealthy 1/1
diff --git a/scripts/stateless-replicas-drill/testdata/view/two-of-two-done.txt b/scripts/stateless-replicas-drill/testdata/view/two-of-two-done.txt
new file mode 100644
index 000000000..33a5e73e9
--- /dev/null
+++ b/scripts/stateless-replicas-drill/testdata/view/two-of-two-done.txt
@@ -0,0 +1,7 @@
+HOST REGION CHANNEL POOL INSTALLED SERVING HEALTH UPSTREAMS DB EGRESS CREATED BY REASON SEED RUNTIME WORKERS
+shop.example.com fleet/pi stable — Running - - - 2026-11-11 ops deploy complete - rootfs -
+other.example.com fleet/pi stable — Running - - - - binary -
+
+HOST BOX BUILD STATE HEALTH WORKERS
+shop.example.com pi-1 v2 Running Healthy 1/1
+shop.example.com pi-2 v2 Running Healthy 1/1
diff --git a/scripts/stateless-replicas-drill/testdata/view/two-of-two-failed.txt b/scripts/stateless-replicas-drill/testdata/view/two-of-two-failed.txt
new file mode 100644
index 000000000..404c79774
--- /dev/null
+++ b/scripts/stateless-replicas-drill/testdata/view/two-of-two-failed.txt
@@ -0,0 +1,6 @@
+HOST REGION CHANNEL POOL INSTALLED SERVING HEALTH UPSTREAMS DB EGRESS CREATED BY REASON SEED RUNTIME WORKERS
+shop.example.com fleet/pi stable — Running - - - 2026-11-11 ops the release command failed, so no copy switched to the new build - rootfs -
+
+HOST BOX BUILD STATE HEALTH WORKERS
+shop.example.com pi-1 v2 Running Healthy 1/1
+shop.example.com pi-2 v2 Running Healthy 1/1
diff --git a/scripts/stateless-replicas-drill/view.go b/scripts/stateless-replicas-drill/view.go
new file mode 100644
index 000000000..fee2c7cf0
--- /dev/null
+++ b/scripts/stateless-replicas-drill/view.go
@@ -0,0 +1,147 @@
+package main
+
+import "strings"
+
+// The words carlos instances list prints that the drill reads. They are
+// the CLI's printed labels, not the console's wire states: the copies
+// table's State and Health cells (instances_copies.go, copyLabelRunning
+// and copyHealthy, rows SR-4-C07 and SR-4-C49) and the main table's
+// HEALTH cell (internal/console healthWord). The parser is tested against
+// testdata/view, which the root package's
+// TestReplicaDrillViewFixturesMatchRenderer keeps equal to the real
+// renderer's output.
+const (
+ viewRunning = "Running"
+ viewHealthy = "Healthy"
+)
+
+// The replicated deploy's state, as the REASON cell prints it
+// (internal/console/replicadeploy.go replicaDeployDone and
+// replicaDeployFailed, rows SR-4-C37 and SR-4-C15).
+// TestReplicaDrillDeployStatusWords checks they are still the console's.
+const (
+ deployDoneStatus = "deploy complete"
+ deployFailedStatus = "the release command failed, so no copy switched to the new build"
+)
+
+// cliTable is one table carlos printed: its header's column names and the
+// rune column each starts at, and its rows as cells. The CLI's tables come
+// from a tabwriter that pads every cell of a column to one width, counting
+// runes, so a row's cell is the text under its header word. That keeps a
+// cell of several words ("Not responding", a REASON sentence) or an empty
+// one (POOL) in its own column.
+type cliTable struct {
+ cols []string
+ starts []int
+ rows [][]string
+}
+
+// col is the index of the column named name, or -1.
+func (t cliTable) col(name string) int {
+ for i, c := range t.cols {
+ if c == name {
+ return i
+ }
+ }
+ return -1
+}
+
+// cell is row's cell in the column named name, or "".
+func (t cliTable) cell(row []string, name string) string {
+ if i := t.col(name); i >= 0 && i < len(row) {
+ return row[i]
+ }
+ return ""
+}
+
+// parseTables reads every table in out whose header starts with HOST: its
+// rows are the lines under it up to a blank line or the end. A line after a
+// table that is not one (a note under it) is never read as a row by the
+// drill, which only reads rows whose HOST cell is its host.
+func parseTables(out string) []cliTable {
+ var tables []cliTable
+ var cur *cliTable
+ for _, line := range strings.Split(out, "\n") {
+ if strings.TrimSpace(line) == "" {
+ cur = nil
+ continue
+ }
+ if f := strings.Fields(line); len(f) > 1 && f[0] == "HOST" && strings.HasPrefix(line, "HOST") {
+ tables = append(tables, headerOf(line))
+ cur = &tables[len(tables)-1]
+ continue
+ }
+ if cur == nil {
+ continue
+ }
+ runes := []rune(line)
+ row := make([]string, len(cur.starts))
+ for i, start := range cur.starts {
+ end := len(runes)
+ if i+1 < len(cur.starts) {
+ end = min(cur.starts[i+1], len(runes))
+ }
+ if start < end {
+ row[i] = strings.TrimSpace(string(runes[start:end]))
+ }
+ }
+ cur.rows = append(cur.rows, row)
+ }
+ return tables
+}
+
+// headerOf is a header line's columns. A header word is separated from the
+// next by at least two spaces (the tabwriter's padding), so a column name
+// of two words ("LAST ERROR") stays one.
+func headerOf(line string) cliTable {
+ var t cliTable
+ runes := []rune(line)
+ for i := 0; i < len(runes); {
+ if runes[i] == ' ' {
+ i++
+ continue
+ }
+ j := i
+ for j < len(runes) && !(runes[j] == ' ' && (j+1 >= len(runes) || runes[j+1] == ' ')) {
+ j++
+ }
+ t.cols = append(t.cols, string(runes[i:j]))
+ t.starts = append(t.starts, i)
+ i = j
+ }
+ return t
+}
+
+// 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's HEALTH reads Running
+ reason string // its main row's REASON cell
+}
+
+// copiesOf reads carlos instances list for host. The copies table is the
+// one whose header has BOX and HEALTH (HOST BOX BUILD STATE HEALTH
+// WORKERS; a missing copy shows "-" for box and build); a host with one
+// copy has none. A copy is healthy only when its State is Running and its
+// Health is Healthy.
+func copiesOf(out, host string) copyView {
+ var v copyView
+ for _, t := range parseTables(out) {
+ copies := t.col("BOX") >= 0 && t.col("STATE") >= 0
+ for _, row := range t.rows {
+ if len(row) == 0 || row[0] != host {
+ continue
+ }
+ if !copies {
+ v.mainRunning = t.cell(row, "HEALTH") == viewRunning
+ v.reason = t.cell(row, "REASON")
+ continue
+ }
+ v.total++
+ if t.cell(row, "STATE") == viewRunning && t.cell(row, "HEALTH") == viewHealthy {
+ v.healthy++
+ }
+ }
+ }
+ return v
+}
diff --git a/scripts/stateless-replicas-drill/view_test.go b/scripts/stateless-replicas-drill/view_test.go
new file mode 100644
index 000000000..7facd246e
--- /dev/null
+++ b/scripts/stateless-replicas-drill/view_test.go
@@ -0,0 +1,138 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+)
+
+// viewFixture is a carlos instances list output in testdata/view, written
+// by the real renderer: the root package's
+// TestReplicaDrillViewFixturesMatchRenderer keeps every file equal to what
+// printInstancesList prints today.
+func viewFixture(t *testing.T, name string) string {
+ t.Helper()
+ b, err := os.ReadFile(filepath.Join("testdata", "view", name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+// TestReplicaDrillViewParsesRenderer (Astra I5): the live view is read
+// from the CLI's actual output, its capitalised State and Health labels
+// included: copies from the copies table, one copy from the main row's
+// HEALTH, the deploy state from its REASON.
+func TestReplicaDrillViewParsesRenderer(t *testing.T) {
+ const host = "shop.example.com"
+ for _, c := range []struct {
+ file string
+ healthy, total int
+ mainRunning bool
+ reason string
+ }{
+ {"one-of-two.txt", 1, 2, true, ""},
+ {"one-of-two-missing.txt", 1, 2, true, ""},
+ {"two-of-two-done.txt", 2, 2, true, deployDoneStatus},
+ {"two-of-two-failed.txt", 2, 2, true, deployFailedStatus},
+ {"one-copy.txt", 0, 0, true, ""},
+ {"one-copy-asleep.txt", 0, 0, false, ""},
+ {"one-copy-not-responding.txt", 0, 0, false, ""},
+ } {
+ t.Run(c.file, func(t *testing.T) {
+ v := copiesOf(viewFixture(t, c.file), host)
+ if v.healthy != c.healthy || v.total != c.total || v.mainRunning != c.mainRunning || v.reason != c.reason {
+ t.Fatalf("read %+v, want healthy %d total %d running %v reason %q", v, c.healthy, c.total, c.mainRunning, c.reason)
+ }
+ })
+ }
+ // Another host's rows are never this host's.
+ if v := copiesOf(viewFixture(t, "two-of-two-done.txt"), "other.example.com"); v.total != 0 || !v.mainRunning || v.reason != "" {
+ t.Fatalf("other host read as %+v", v)
+ }
+ // The labels the drill matches are the renderer's: lower-case words
+ // (the console's wire states) are not.
+ lower := strings.NewReplacer("Running", "running", "Healthy", "healthy").Replace(viewFixture(t, "one-of-two.txt"))
+ if v := copiesOf(lower, host); v.healthy != 0 || v.mainRunning {
+ t.Fatalf("lower-case words read as %+v", v)
+ }
+}
+
+// TestReplicaDrillDeployStatusWords: the deploy states the drill waits for
+// are still the console's own words.
+func TestReplicaDrillDeployStatusWords(t *testing.T) {
+ src, err := os.ReadFile(filepath.Join("..", "..", "internal", "console", "replicadeploy.go"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, word := range map[string]string{"replicaDeployDone": deployDoneStatus, "replicaDeployFailed": deployFailedStatus} {
+ if !regexp.MustCompile(`\b` + name + `\s*=\s*` + regexp.QuoteMeta(strconv.Quote(word))).Match(src) {
+ t.Errorf("internal/console/replicadeploy.go no longer has %s = %q", name, word)
+ }
+ }
+}
+
+// TestReplicaDrillFailingRelease (Astra I6): the failing release step
+// passes only when the release command ran exactly once and the live view
+// shows the deploy failed.
+func TestReplicaDrillFailingRelease(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ runs int
+ view string
+ fails int
+ }{
+ {"ran once, reached failed", 1, "two-of-two-failed.txt", 0},
+ {"never ran", 0, "two-of-two-failed.txt", 1},
+ {"ran twice", 2, "two-of-two-failed.txt", 1},
+ {"ran once, never reached failed", 1, "two-of-two-done.txt", 1},
+ {"never ran, never reached failed", 0, "two-of-two-done.txt", 2},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/drill/state" {
+ http.NotFound(w, r)
+ return
+ }
+ json.NewEncoder(w).Encode(fixtureState{ReleaseCount: 7 + c.runs})
+ }))
+ defer srv.Close()
+ bin := t.TempDir()
+ script := "#!/bin/sh\ncat " + strconv.Quote(filepath.Join(mustAbs(t, "testdata"), "view", c.view)) + "\n"
+ if err := os.WriteFile(filepath.Join(bin, "carlos"), []byte(script), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
+ d := &drill{cfg: drillConfig{App: "shop", Host: "shop.example.com"}, client: srv.Client(), baseURL: srv.URL,
+ log: devNull(t), viewWait: 300 * time.Millisecond}
+ var report drillReport
+ if err := d.failingRelease(context.Background(), &report, fixtureState{ReleaseCount: 7}); err != nil {
+ t.Fatal(err)
+ }
+ if len(d.failed) != c.fails || report.FailingReleaseRuns != c.runs || report.FailingReached != (c.view == "two-of-two-failed.txt") {
+ t.Fatalf("failed %v, report %+v", d.failed, report)
+ }
+ // The counter read is a sample the hub counts.
+ if all := d.all(); len(all) != 1 || all[0].Phase != phaseState || all[0].Status != 200 || all[0].Done.IsZero() {
+ t.Fatalf("state read samples %+v", all)
+ }
+ })
+ }
+}
+
+func mustAbs(t *testing.T, p string) string {
+ t.Helper()
+ a, err := filepath.Abs(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return a
+}