fix: close the create fallback and pin drill evidence (#511 T5 round 2)
Task 5 fix round 2, after the round 1 re-reviews. R13: a create that cannot read the app's copies config is refused 503 with Retry-After, never admitted by the stateless always-on fallback. The create-time branches the round 1 refusal made unreachable are gone and two test names now say what they test. Drill: a websocket counts only a drop after the stop, on a connection to the stopped box, followed by a reconnect to the survivor within a minute; every upgrade must name a drill box; redials back off. operator() reads stdin in one goroutine and returns on cancellation. Ordering follows the ruled invariant A.newStart < A.oldRetire <= B.newStart < B.oldRetire. The tip reads only the BOX STATE VERSION rows, and every carlos command line puts flags before positional arguments. Docs: the not-prevented paragraph also covers an operator rolling a box back to its previous build after a finished update.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/site/stateless-replicas.md+1 −1docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md+1 −1internal/console/apiinstances.go+2 −2internal/console/copiespublication.go+24 −12internal/console/copiespublication_test.go+6 −3internal/console/replicafloor_test.go+41 −0internal/provision/stateless_replicas_4_task5_census_test.go+1 −1scripts/stateless-replicas-drill/accounting.go+22 −11scripts/stateless-replicas-drill/accounting_test.go+143 −12scripts/stateless-replicas-drill/main.go+216 −89
CI cancelled — superseded by a newer push — run details
Intent
<task-notification> <task-id>a1759874a712527fe</task-id> <tool-use-id>toolu_01JapRKnMw6a47UY3eLUmv4h</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 - **Commit:** `a186d5be fix: amend the replica floor and harden the drill (#511 T5 round 1)`, local, not pushed. - **Tests:** the new tests and the targeted console, host, drill, census, grouproll and region HA runs pass, as do all three cross-compiles. All 5 deliberate code breaks were caught. The only failure is the deferred `TestClaimServingAssemblyWithoutMoves`. The census was re-proposed under the same name and is clean. - **R16:** boxes now report `apply_finished` in the heartbeat. A box is at the floor when its release is at the floor and either its previous build is (or there is none) or its last apply finished. Docs line 9 and SR-4-C64 are reworded. - **R13:** copies above 1 are refused for an app with no instances (SR-4-C77), and a new instance is refused while copies are above 1 (SR-4-C78). Four older copies tests that created an instance at copies 2 now expect the refusal. Docs line 11 and SR-4-C65 match. - **Drill:** every Astra and Fable item is fixed. The stop, deploy, failing and scale-down rules now live in one function, covered by `TestReplicaDrillWindowRules`. - **Audit:** a row for `release.PublishSystemIdentity` is added. - **Concerns:** - "Apply finished" means only that the box's apply journal is absent. I left out the guard's `update-begun.json` because I couldn't confirm the agent can read that directory. - The drill now needs more from the live setup: the websocket answer must name its box, someone must export each box's generation events, and `carlos fleets show` must report each box's version. If that command shows "unknown", the drill fails before any load. - The old create-time checks for copies above 1 can no longer be reached, so they are dead code. I left them in place. - **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 (fix round 1 section at the end).</result> <usage><subagent_tokens>541041</subagent_tokens><tool_uses>47</tool_uses><duration_ms>2103545</duration_ms></usage> </task-notification>
<task-notification> <task-id>btjipk252</task-id> <tool-use-id>toolu_01NauSueWBphidydDkH8kTen</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/btjipk252.output</output-file> <status>completed</status> <summary>Background command "Fable re-review of T5 round 1" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>bys626qmy</task-id> <tool-use-id>toolu_01W3ynj3Ez3AkaMm61KmUMp7</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/72128d15-58b8-452f-9f7e-8e864e8854d2/tasks/bys626qmy.output</output-file> <status>completed</status> <summary>Background command "Astra re-review of T5 round 1" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 8.88 g CO₂e (1,105,719 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 8295344db..57e26bc01 100644 |
| --- a/docs/site/stateless-replicas.md |
| +++ b/docs/site/stateless-replicas.md |
| @@ -44,4 +44,4 @@ An instance with more than one copy keeps a separate page cache on each copy's b |
| ## What the platform does not prevent |
| -The console will not move the platform below v0.35.0 while any app has more than one copy. It cannot stop someone with root on a box from installing an older platform build there by hand. A box downgraded that way keeps serving, but its copies may switch builds out of turn, or start again on an older build, until the box is updated again. |
| +The console will not move the platform below v0.35.0 while any app has more than one copy. It cannot stop an operator putting an older platform build back on a box, either by installing one by hand or by rolling the box back to its previous build after an update has finished. A box downgraded either way keeps serving, but its copies may switch builds out of turn, or start again on an older build, until the box is updated again. |
diff --git a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md| index 624222919..9a48a58d7 100644 |
| --- a/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md |
| +++ b/docs/superpowers/plans/2026-11-01-stateless-replicas-copy.md |
| @@ -139,7 +139,7 @@ copy too. Internal wire enums are not an excuse to expose unreviewed text. |
| | 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) | |
| +| 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 an operator putting an older platform build back on a box, either by installing one by hand or by rolling the box back to its previous build after an update has finished. A box downgraded either 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; fix round 2 added an operator rollback to the previous build over a finished update, such as the group roll's rollback; awaiting Paul's copy review) | |
| | SR-4-C69 | docs/site/cli.md | [Stateless replicas](/docs/stateless-replicas) covers what an app needs before it runs more than one copy, how deploys switch copies, and what happens when a box stops. | pending (added by Plan 4 Task 5: the CLI reference's cross-link under carlos apps set --copies; awaiting Paul's copy review) | |
| | SR-4-C70 | docs/site/nav.json | Run more than one copy of each instance across your fleet, and what happens when a box stops. | pending (added by Plan 4 Task 5: the page's blurb in the Guides section; awaiting Paul's copy review) | |
| | SR-4-C71 | docs/site/stateless-replicas.md | Before you set copies | pending (added by Plan 4 Task 5: heading; awaiting Paul's copy review) | |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index 5572ecbd1..9198aacc2 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -2522,7 +2522,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| if err := s.copiesCreateCheck(createContext, &rec); err != nil { |
| var selection *statelessSelectionError |
| if errors.As(err, &selection) { |
| - jsonError(w, selection.ref.Status, selection.ref.Msg) |
| + writeDoorRefusal(w, selection.ref) |
| return |
| } |
| jsonError(w, http.StatusServiceUnavailable, copiesUnread) |
| @@ -2622,7 +2622,7 @@ func (s *Server) handleAPIInstanceCreate(w http.ResponseWriter, r *http.Request) |
| if err := recordWriteErr; err != nil { |
| var selection *statelessSelectionError |
| if errors.As(err, &selection) { |
| - jsonError(w, selection.ref.Status, selection.ref.Msg) |
| + writeDoorRefusal(w, selection.ref) |
| return |
| } |
| if writeOwnedBindingRefusal(w, err) { |
diff --git a/internal/console/copiespublication.go b/internal/console/copiespublication.go| index 4ec5f787a..0040d113e 100644 |
| --- a/internal/console/copiespublication.go |
| +++ b/internal/console/copiespublication.go |
| @@ -6,6 +6,7 @@ import ( |
| "errors" |
| "net/http" |
| "os" |
| + "strconv" |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/provision" |
| @@ -46,6 +47,22 @@ func copiesUnavailable() *doorRefusal { |
| return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: copiesUnread} |
| } |
| +// copiesRetryAfter is the seconds a copies 503 asks a client to wait. |
| +const copiesRetryAfter = 5 |
| + |
| +// writeDoorRefusal writes ref, with Retry-After on a 503: its own wait, or |
| +// copiesRetryAfter. |
| +func writeDoorRefusal(w http.ResponseWriter, ref *doorRefusal) { |
| + if ref.Status == http.StatusServiceUnavailable { |
| + after := ref.haCapacityRetryAfter |
| + if after <= 0 { |
| + after = copiesRetryAfter |
| + } |
| + w.Header().Set("Retry-After", strconv.Itoa(after)) |
| + } |
| + jsonError(w, ref.Status, ref.Msg) |
| +} |
| + |
| func (s *Server) copiesStillApp(ctx context.Context, acct *Account, app string) *doorRefusal { |
| admitted, present := ctx.Value(copiesAdmissionKey{}).(copiesAdmission) |
| if !present { |
| @@ -163,7 +180,12 @@ func (s *Server) copiesRecordRefusal(ctx context.Context, acct *Account, rec pro |
| } |
| configErr := err |
| n := appconfig.CopiesOf(&cfg.manifest) |
| - if create && configErr == nil && n > 1 { |
| + if create && configErr != nil { |
| + // R13 closed up front fails closed: a create that cannot read the |
| + // app's count might be one into copies above 1 (503, Retry-After). |
| + return copiesUnavailable() |
| + } |
| + if create && 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} |
| @@ -199,14 +221,7 @@ func (s *Server) copiesRecordRefusal(ctx context.Context, acct *Account, rec pro |
| } |
| return copiesUnavailable() |
| } |
| - if ref := s.copiesRefusal(ctx, acct, rec.App, n, target); ref != nil { |
| - return ref |
| - } |
| - if create && n > 1 { |
| - ctx = context.WithValue(ctx, copiesRootfsCreateKey{}, target.Kind == release.KindRootfs) |
| - return s.copiesRefusal(ctx, acct, rec.App, n, nil) |
| - } |
| - return nil |
| + return s.copiesRefusal(ctx, acct, rec.App, n, target) |
| } |
| func (s *Server) copiesCreateCheck(ctx context.Context, rec *provision.Record) error { |
| @@ -231,9 +246,6 @@ func (s *Server) copiesCreateCheck(ctx context.Context, rec *provision.Record) e |
| return &statelessSelectionError{copiesUnavailable()} |
| } |
| } |
| - if configErr == nil && appconfig.CopiesOf(&cfg.manifest) > 1 && rec.Runtime == "" && rec.Hibernate == nil && rec.DerivesPaths() { |
| - rec.Hibernate = new(bool) |
| - } |
| if ref := s.copiesRecordRefusal(ctx, acct, *rec, true); ref != nil { |
| return &statelessSelectionError{ref} |
| } |
diff --git a/internal/console/copiespublication_test.go b/internal/console/copiespublication_test.go| index b911b8c1c..ba4544803 100644 |
| --- a/internal/console/copiespublication_test.go |
| +++ b/internal/console/copiespublication_test.go |
| @@ -217,10 +217,10 @@ func TestCopiesPublicationEvidence(t *testing.T) { |
| } |
| } |
| -// A fresh instance no longer inherits a count above 1 (R13 closed up |
| +// A fresh instance is never created into 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) { |
| +func TestCopiesFreshInstanceRefusedAtCount(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) |
| @@ -591,7 +591,10 @@ func TestCopiesCannotAddSidecarAfterAdmission(t *testing.T) { |
| } |
| } |
| -func TestCopiesFreshRootfsChecksEveryDestination(t *testing.T) { |
| +// An app with no instance cannot be set above one copy (R13 closed up |
| +// front, SR-4-C77), so a first rootfs instance is created at one copy, |
| +// and the create is not refused as replicated. |
| +func TestCopiesEmptyRootfsAppRefusesCount(t *testing.T) { |
| fx, token, _ := fleetBoxWorld(t, "copies-first-rootfs", "pi-1", "pi-2") |
| fx.srv.consoleBuild = release.StatelessReplicasFloor |
| piBeat(t, fx, "pi-1", true, time.Now(), release.StatelessReplicasFloor) |
diff --git a/internal/console/replicafloor_test.go b/internal/console/replicafloor_test.go| index 7287e5994..f2830f9ec 100644 |
| --- a/internal/console/replicafloor_test.go |
| +++ b/internal/console/replicafloor_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "errors" |
| "fmt" |
| "net/http" |
| + "net/http/httptest" |
| "os" |
| "strings" |
| "testing" |
| @@ -437,3 +438,43 @@ func TestReplicaFloorCreateRefusedAtCopies(t *testing.T) { |
| t.Fatalf("create at copies 1 refused as replicated: %d %s", code, out) |
| } |
| } |
| + |
| +// TestReplicaFloorCreateFailsClosedOnUnreadableCount (R13, fix round 2): a |
| +// create that cannot read the app's copies config might be one into copies |
| +// above 1, so it is refused 503 with Retry-After, and writes no record. |
| +func TestReplicaFloorCreateFailsClosedOnUnreadableCount(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) |
| + } |
| + key := appconfig.Key(fx.sqid, "shop") |
| + _, tag, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(context.Background(), key, []byte("broken"), tag); err != nil { |
| + t.Fatal(err) |
| + } |
| + code, hdr, out := rawReq(t, http.MethodPost, instancesURL(fx, fx.sqid, "shop"), token, `{"host":"c.example.com","channel":"edge"}`) |
| + if code != http.StatusServiceUnavailable || !strings.Contains(out, copiesUnread) || hdr.Get("Retry-After") == "" { |
| + t.Fatalf("create over an unreadable count = %d %q %s", code, hdr.Get("Retry-After"), 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) |
| + } |
| + // The case the old fallback admitted: an always-on record whose target |
| + // is a stateless, always-on release (edge's v1), exactly what a |
| + // replicated app runs. Every create door asks copiesCreateCheck. |
| + acct, err := fx.st.AccountBySqid(fx.sqid) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r := httptest.NewRequest(http.MethodPost, "/", nil) |
| + fx.srv.captureCopiesAdmission(r, acct, "shop") |
| + rec := provision.Record{Schema: 1, Account: fx.sqid, App: "shop", Host: "d.example.com", Slug: "d", Region: "fleet/pi", Channel: "edge", Hibernate: new(bool)} |
| + err = fx.srv.copiesCreateCheck(withWriteMemo(r.Context()), &rec) |
| + var selection *statelessSelectionError |
| + if !errors.As(err, &selection) || selection.ref.Status != http.StatusServiceUnavailable { |
| + t.Fatalf("always-on create over an unreadable count = %v", err) |
| + } |
| +} |
diff --git a/internal/provision/stateless_replicas_4_task5_census_test.go b/internal/provision/stateless_replicas_4_task5_census_test.go| index 04a011df2..db717eb46 100644 |
| --- a/internal/provision/stateless_replicas_4_task5_census_test.go |
| +++ b/internal/provision/stateless_replicas_4_task5_census_test.go |
| @@ -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.untilView", "key-site", "lit:instances", "0e76284a368f974ff9fee9ef3e875bcf6873dafa691770fda6fac5ce121d482e"}, |
| + {"scripts/stateless-replicas-drill/main.go", "drill.untilView", "key-site", "lit:instances", "94467066c6aa2e0fff809e4a68a6fa5663ecd216ebfbae77cf09d0f6d80e07c1"}, |
| } { |
| replaced := false |
| for i, e := range entries { |
diff --git a/scripts/stateless-replicas-drill/accounting.go b/scripts/stateless-replicas-drill/accounting.go| index edbe5e0d3..d841b93b7 100644 |
| --- a/scripts/stateless-replicas-drill/accounting.go |
| +++ b/scripts/stateless-replicas-drill/accounting.go |
| @@ -270,12 +270,17 @@ type genEvent struct { |
| } |
| // 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. |
| +// copies switching from build from to build to one box at a time |
| +// (controller ruling, fix round 2). Ordered by when each box started |
| +// serving to, with A before B: |
| +// |
| +// A.newStart < A.oldRetire <= B.newStart < B.oldRetire |
| +// |
| +// Each box overlaps its own two generations (it starts the new one before |
| +// it retires the old), and the boxes switch strictly one after the other: |
| +// a box starts the new build only once the box before it has retired the |
| +// old one. Two boxes starting together, a box that retires its old build |
| +// before starting the new one, or missing evidence is not ordered. |
| 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 { |
| @@ -297,15 +302,21 @@ func orderedSwitch(events []genEvent, boxes []string, from, to string) (bool, st |
| if _, ok := retired[box]; !ok { |
| return false, fmt.Sprintf("%s never retired %s", box, from) |
| } |
| + if !started[box].Before(retired[box]) { |
| + return false, fmt.Sprintf("%s retired %s at %s, not after it started %s at %s", box, from, |
| + retired[box].Format(time.RFC3339Nano), to, started[box].Format(time.RFC3339Nano)) |
| + } |
| } |
| 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 !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)) |
| - } |
| + prev, next := order[i-1], order[i] |
| + if !started[prev].Before(started[next]) { |
| + return false, fmt.Sprintf("%s and %s started %s together at %s", prev, next, to, started[next].Format(time.RFC3339Nano)) |
| + } |
| + if retired[prev].After(started[next]) { |
| + return false, fmt.Sprintf("%s retired %s at %s, after %s started %s at %s", prev, from, |
| + retired[prev].Format(time.RFC3339Nano), next, to, started[next].Format(time.RFC3339Nano)) |
| } |
| } |
| return true, "" |
diff --git a/scripts/stateless-replicas-drill/accounting_test.go b/scripts/stateless-replicas-drill/accounting_test.go| index 1d4f0ee86..8baf67dfc 100644 |
| --- a/scripts/stateless-replicas-drill/accounting_test.go |
| +++ b/scripts/stateless-replicas-drill/accounting_test.go |
| @@ -3,12 +3,17 @@ package main |
| import ( |
| "bufio" |
| "context" |
| + "crypto/tls" |
| "errors" |
| + "fmt" |
| "io" |
| + "net/http" |
| + "net/http/httptest" |
| "os" |
| "path/filepath" |
| "strings" |
| "testing" |
| + "text/tabwriter" |
| "time" |
| ) |
| @@ -300,6 +305,23 @@ func TestReplicaDrillOrderedSwitch(t *testing.T) { |
| if ok, _ := orderedSwitch(overlapping, boxes, "v1", "v2"); ok { |
| t.Fatal("b started before a retired its old build and passed") |
| } |
| + // The boundary the ruling allows: B starts as A retires. |
| + boundary := []genEvent{ev(2, "a", "v2", "serving"), ev(3, "a", "v1", "retired"), ev(3, "b", "v2", "serving"), ev(4, "b", "v1", "retired")} |
| + if ok, why := orderedSwitch(boundary, boxes, "v1", "v2"); !ok { |
| + t.Fatalf("B starting as A retires refused: %s", why) |
| + } |
| + // Astra's counterexample: both old builds retire at T1, both new |
| + // builds start together at T2. |
| + astra := []genEvent{ev(1, "a", "v1", "retired"), ev(1, "b", "v1", "retired"), ev(2, "a", "v2", "serving"), ev(2, "b", "v2", "serving")} |
| + if ok, _ := orderedSwitch(astra, boxes, "v1", "v2"); ok { |
| + t.Fatal("both retired at T1 and both started at T2, and passed") |
| + } |
| + // Sequential starts, but a box retired its old build before its new |
| + // one started: no overlap on that box. |
| + gap := []genEvent{ev(1, "a", "v1", "retired"), ev(2, "a", "v2", "serving"), ev(3, "b", "v2", "serving"), ev(4, "b", "v1", "retired")} |
| + if ok, _ := orderedSwitch(gap, boxes, "v1", "v2"); ok { |
| + t.Fatal("a box with no overlap passed") |
| + } |
| if ok, _ := orderedSwitch(ordered[:2], boxes, "v1", "v2"); ok { |
| t.Fatal("a deploy that never reached b passed") |
| } |
| @@ -325,20 +347,25 @@ func TestReplicaDrillViewAndInput(t *testing.T) { |
| 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) { |
| + if err := d.operator(context.Background(), "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) |
| + // Cancellation never waits on stdin. |
| + pr, pw := io.Pipe() |
| + defer pw.Close() |
| + d = &drill{in: bufio.NewReader(pr), log: devNull(t)} |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + got := make(chan error, 1) |
| + go func() { got <- d.operator(ctx, "hard-stop b") }() |
| + time.Sleep(20 * time.Millisecond) |
| + cancel() |
| + select { |
| + case err := <-got: |
| + if !errors.Is(err, context.Canceled) { |
| + t.Fatalf("cancelled operator wait = %v", err) |
| + } |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("operator() held up cancellation") |
| } |
| // 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 |
| @@ -370,3 +397,107 @@ func devNull(t *testing.T) *os.File { |
| t.Cleanup(func() { f.Close() }) |
| return f |
| } |
| + |
| +// TestReplicaDrillSocketEvidence: only a drop that happens after the stop, |
| +// on a connection to the stopped box, followed by a reconnect to the |
| +// survivor within reconnectBound, exercises the stop. Every upgrade must |
| +// name a drill box. |
| +func TestReplicaDrillSocketEvidence(t *testing.T) { |
| + cfg := drillConfig{BoxA: "a", BoxB: "b"} |
| + stopAt := drillT0.Add(time.Minute) |
| + at := func(sec int) time.Time { return drillT0.Add(time.Duration(sec) * time.Second) } |
| + conn := func(box string, from, drop int) socketConn { |
| + c := socketConn{Box: box, Connected: at(from)} |
| + if drop >= 0 { |
| + c.Dropped = at(drop) |
| + } |
| + return c |
| + } |
| + for _, c := range []struct { |
| + name string |
| + r socketResult |
| + pass bool |
| + }{ |
| + {"drop after the stop, back on the survivor", socketResult{Pinned: "b", Conns: []socketConn{conn("b", 0, 61), conn("a", 63, -1)}}, true}, |
| + {"drop before the stop only", socketResult{Pinned: "b", Conns: []socketConn{conn("b", 0, 30), conn("a", 32, -1)}}, false}, |
| + {"drop after the stop, back on the stopped box", socketResult{Pinned: "b", Conns: []socketConn{conn("b", 0, 61), conn("b", 63, -1)}}, false}, |
| + {"drop after the stop, reconnect too late", socketResult{Pinned: "b", Conns: []socketConn{conn("b", 0, 61), conn("a", 61+int(reconnectBound/time.Second)+1, -1)}}, false}, |
| + {"pre-stop move to the survivor, then nothing", socketResult{Pinned: "b", Conns: []socketConn{conn("b", 0, 10), conn("a", 11, -1)}}, false}, |
| + {"never reconnected", socketResult{Pinned: "b", Conns: []socketConn{conn("b", 0, 61)}}, false}, |
| + {"never connected", socketResult{Pinned: "b"}, false}, |
| + {"pinned elsewhere first", socketResult{Pinned: "b", Conns: []socketConn{conn("a", 0, -1)}}, false}, |
| + {"survivor socket held throughout", socketResult{Pinned: "a", Conns: []socketConn{conn("a", 0, -1)}}, true}, |
| + {"survivor socket dropped and never came back", socketResult{Pinned: "a", Conns: []socketConn{conn("a", 0, 70)}}, false}, |
| + } { |
| + t.Run(c.name, func(t *testing.T) { |
| + why := c.r.verdict(cfg, stopAt) |
| + if (why == "") != c.pass { |
| + t.Fatalf("verdict %q, want pass %v", why, c.pass) |
| + } |
| + }) |
| + } |
| + // N3: an upgrade naming no drill box is a failed dial. |
| + for _, named := range []string{"a", "", "c"} { |
| + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + hj, _ := w.(http.Hijacker) |
| + c, buf, err := hj.Hijack() |
| + if err != nil { |
| + return |
| + } |
| + defer c.Close() |
| + buf.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nX-Drill-Box: " + named + "\r\n\r\n") |
| + buf.Flush() |
| + })) |
| + pool := srv.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs |
| + d := &drill{cfg: drillConfig{Host: "example.com", BoxA: "a", BoxB: "b"}, socketAddr: srv.Listener.Addr().String(), |
| + socketTLS: &tls.Config{ServerName: "example.com", RootCAs: pool}} |
| + c, box, err := d.dialSocket(context.Background()) |
| + if c != nil { |
| + c.Close() |
| + } |
| + srv.Close() |
| + if (err == nil) != (named == "a") || (err == nil && box != "a") { |
| + t.Fatalf("upgrade naming %q: box %q err %v", named, box, err) |
| + } |
| + } |
| +} |
| + |
| +// TestReplicaDrillFleetVersions: the tip is read from the rows of the BOX |
| +// STATE VERSION table only. carlos fleets show prints each box's checks |
| +// under it (" <box> <key>: <state> <reason>"); those never stand in for a |
| +// version. |
| +func TestReplicaDrillFleetVersions(t *testing.T) { |
| + var out strings.Builder |
| + out.WriteString("pi\n") |
| + tw := tabwriter.NewWriter(&out, 0, 4, 2, ' ', 0) |
| + fmt.Fprintln(tw, "BOX\tSTATE\tVERSION\tLAST ERROR") |
| + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", "box-a", "active", "v0.35.0", "") |
| + fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n", "box-b", "active", "unknown", "") |
| + tw.Flush() |
| + fmt.Fprintf(&out, " %s %s: %s %s\n", "box-a", "version", "pass", "") |
| + fmt.Fprintf(&out, " %s %s: %s %s\n", "box-b", "version", "pass", "v0.35.0") |
| + v := fleetVersions(out.String()) |
| + if v["box-a"] != "v0.35.0" || v["box-b"] != "unknown" || len(v) != 2 { |
| + t.Fatalf("versions %v from\n%s", v, out.String()) |
| + } |
| + if got := fleetVersions("box-a version: pass\nbox-b version: pass\n"); len(got) != 0 { |
| + t.Fatalf("lines outside the table read as versions: %v", got) |
| + } |
| +} |
| + |
| +// TestReplicaDrillArgv: every carlos command line puts its flags, the |
| +// drill's account and console included, before its positional arguments. |
| +func TestReplicaDrillArgv(t *testing.T) { |
| + d := &drill{cfg: drillConfig{App: "shop", Host: "shop.example.com", Fleet: "pi", Account: "bab", Console: "https://console.example.com"}} |
| + for _, c := range []struct { |
| + got, want []string |
| + }{ |
| + {d.argv([]string{"fleets", "show"}, nil, "pi"), []string{"fleets", "show", "--account", "bab", "--console", "https://console.example.com", "pi"}}, |
| + {d.argv([]string{"instances", "list"}, []string{"--app", "shop", "--match", "shop.example.com"}), |
| + []string{"instances", "list", "--app", "shop", "--match", "shop.example.com", "--account", "bab", "--console", "https://console.example.com"}}, |
| + } { |
| + if strings.Join(c.got, " ") != strings.Join(c.want, " ") { |
| + t.Fatalf("argv %q, want %q", c.got, c.want) |
| + } |
| + } |
| +} |
diff --git a/scripts/stateless-replicas-drill/main.go b/scripts/stateless-replicas-drill/main.go| index a4ebea3af..6d9969567 100644 |
| --- a/scripts/stateless-replicas-drill/main.go |
| +++ b/scripts/stateless-replicas-drill/main.go |
| @@ -150,6 +150,15 @@ type drill struct { |
| log *os.File |
| logErr error |
| failed []string |
| + |
| + linesOnce sync.Once |
| + lines chan operatorLine |
| + |
| + // socketAddr and socketTLS are test seams for dialSocket: the address |
| + // to dial (default <host>:443) and the TLS configuration (default: |
| + // the system roots, server name host). |
| + socketAddr string |
| + socketTLS *tls.Config |
| } |
| // runDrill runs the whole drill. It returns an error for anything that |
| @@ -234,7 +243,7 @@ func (d *drill) run(ctx context.Context, report *drillReport) error { |
| 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 { |
| + if err := d.operator(ctx, "hard-stop %s now through the approved operator action, then press enter", cfg.BoxB); err != nil { |
| return err |
| } |
| stopAt = time.Now() |
| @@ -257,15 +266,15 @@ func (d *drill) run(ctx context.Context, report *drillReport) error { |
| 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 != "" { |
| + report.MaxReconnect = max(report.MaxReconnect, res.longest()) |
| + if why := res.verdict(cfg, stopAt); why != "" { |
| d.fail("websocket pinned to %s: %s", box, why) |
| } |
| } |
| d.note("observation: the longest websocket reconnect was %s", report.MaxReconnect) |
| // 3. Box B returns; the spread evens again. |
| - 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 { |
| + if err := d.operator(ctx, "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 { |
| @@ -281,7 +290,7 @@ func (d *drill) run(ctx context.Context, report *drillReport) error { |
| } |
| 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) |
| + return d.operator(ctx, "deploy a new good build of %s now (carlos deploy), and press enter once the deploy has finished", cfg.App) |
| }); err != nil { |
| return err |
| } |
| @@ -298,7 +307,7 @@ func (d *drill) run(ctx context.Context, report *drillReport) error { |
| d.fail("the good deploy did not change the build (%q to %q)", from, to) |
| } |
| 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) |
| + 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 |
| } |
| @@ -310,7 +319,7 @@ func (d *drill) run(ctx context.Context, report *drillReport) error { |
| // 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 { |
| + if err := d.operator(ctx, "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 { |
| @@ -319,7 +328,7 @@ 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("export the hub's and the boxes' request records and the boxes' generation events to %s, %s and %s, then press enter", |
| + 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 { |
| return err |
| } |
| @@ -384,47 +393,103 @@ func (d *drill) fail(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 { |
| +// failed input is an error: the action was never confirmed. So is the |
| +// drill's cancellation, which never waits on stdin: the input is read by |
| +// one goroutine (operatorLines), and this selects on it and on ctx. |
| +func (d *drill) operator(ctx context.Context, format string, args ...any) error { |
| d.note("OPERATOR: "+format, args...) |
| - if _, err := d.in.ReadString('\n'); err != nil { |
| - return fmt.Errorf("operator input: %w", err) |
| + select { |
| + case <-ctx.Done(): |
| + return fmt.Errorf("operator input: %w", ctx.Err()) |
| + case l := <-d.operatorLines(): |
| + if l.err != nil { |
| + return fmt.Errorf("operator input: %w", l.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. |
| +// operatorLine is one line of the operator's input, or why there is none. |
| +type operatorLine struct { |
| + text string |
| + err error |
| +} |
| + |
| +// operatorLines starts, once, the goroutine that reads the operator's |
| +// input a line at a time and stops at its first error. |
| +func (d *drill) operatorLines() <-chan operatorLine { |
| + d.linesOnce.Do(func() { |
| + d.lines = make(chan operatorLine) |
| + go func() { |
| + for { |
| + text, err := d.in.ReadString('\n') |
| + d.lines <- operatorLine{text, err} |
| + if err != nil { |
| + return |
| + } |
| + } |
| + }() |
| + }) |
| + return d.lines |
| +} |
| + |
| +// tip is the build both drill boxes run, from carlos fleets show |
| +// (fleetVersions). Boxes on different builds, or one the console cannot |
| +// name, is an error, before any load. |
| func (d *drill) tip(ctx context.Context) (string, error) { |
| - out, err := d.carlos(ctx, "fleets", "show", d.cfg.Fleet) |
| + out, err := d.carlos(ctx, d.argv([]string{"fleets", "show"}, nil, d.cfg.Fleet)) |
| if err != nil { |
| return "", err |
| } |
| + versions := fleetVersions(out) |
| + 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 |
| +} |
| + |
| +// fleetVersions reads the BOX STATE VERSION table of carlos fleets show: |
| +// the rows under that header, up to the end of the table (a blank line or |
| +// an indented line, such as a box's check results, " <box> <key>: ..."), |
| +// as box to version. Nothing outside the table is read. |
| +func fleetVersions(out string) map[string]string { |
| versions := map[string]string{} |
| + in := false |
| 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) { |
| + if !in { |
| + in = len(f) >= 3 && f[0] == "BOX" && f[1] == "STATE" && f[2] == "VERSION" |
| + continue |
| + } |
| + if len(f) == 0 || line[0] == ' ' || line[0] == '\t' { |
| + break |
| + } |
| + if len(f) >= 3 { |
| 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 |
| + return versions |
| } |
| -// 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) { |
| +// argv is a carlos command line: the command, its flags, the drill's |
| +// account and console, and only then the positional arguments, since the |
| +// CLI's flag parser stops at the first positional one. |
| +func (d *drill) argv(command, flags []string, positional ...string) []string { |
| + args := append(append([]string(nil), command...), flags...) |
| if d.cfg.Account != "" { |
| args = append(args, "--account", d.cfg.Account) |
| } |
| if d.cfg.Console != "" { |
| args = append(args, "--console", d.cfg.Console) |
| } |
| + return append(args, positional...) |
| +} |
| + |
| +// carlos runs the operator's logged-in CLI with args (argv), and returns |
| +// its output. |
| +func (d *drill) carlos(ctx context.Context, args []string) (string, error) { |
| 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))) |
| @@ -616,7 +681,7 @@ func (d *drill) untilScaledDown(ctx context.Context, since time.Time) error { |
| 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) |
| + out, err := d.carlos(ctx, d.argv([]string{"instances", "list"}, []string{"--app", d.cfg.App, "--match", d.cfg.Host})) |
| if err != nil { |
| last = err |
| d.note("live view: %v", err) |
| @@ -681,26 +746,69 @@ type socketWatch struct { |
| done chan socketResult |
| } |
| +// socketConn is one connection a watch held: the drill box its upgrade |
| +// named, when it connected, and when it dropped (zero: it was still open |
| +// when the watch stopped, or the watch closed it). |
| +type socketConn struct { |
| + Box string `json:"box"` |
| + Connected time.Time `json:"connected"` |
| + Dropped time.Time `json:"dropped,omitzero"` |
| +} |
| + |
| // 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 |
| + Pinned string // the box the watch pinned its first connection to |
| + Conns []socketConn // every connection it held, in order |
| + Err string // the last dial or upgrade error |
| +} |
| + |
| +// reconnectBound is the longest a dropped websocket may take to reconnect |
| +// to the surviving box for the stop to count as exercised. The time it |
| +// took is recorded as an observation. |
| +const reconnectBound = time.Minute |
| + |
| +// stopReconnect is the reconnect that exercised the stop: a connection on |
| +// stopped that dropped at or after stopAt, followed by the next |
| +// connection, on survivor, within reconnectBound. It returns that gap. |
| +func (r socketResult) stopReconnect(stopped, survivor string, stopAt time.Time) (time.Duration, bool) { |
| + for i := 0; i+1 < len(r.Conns); i++ { |
| + c, next := r.Conns[i], r.Conns[i+1] |
| + if c.Box != stopped || c.Dropped.IsZero() || c.Dropped.Before(stopAt) || next.Box != survivor { |
| + continue |
| + } |
| + if gap := next.Connected.Sub(c.Dropped); gap <= reconnectBound { |
| + return gap, true |
| + } |
| + } |
| + return 0, false |
| } |
| -// 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 { |
| +// longest is the longest gap between a drop and the next connection. |
| +func (r socketResult) longest() time.Duration { |
| + var l time.Duration |
| + for i := 0; i+1 < len(r.Conns); i++ { |
| + if !r.Conns[i].Dropped.IsZero() { |
| + l = max(l, r.Conns[i+1].Connected.Sub(r.Conns[i].Dropped)) |
| + } |
| + } |
| + return l |
| +} |
| + |
| +// verdict is why the watch fails, or "": it never reached its pinned box, |
| +// or its last connection dropped and never came back, or, for the socket |
| +// pinned to the stopped box, no drop after stopAt was followed by a |
| +// reconnect to the survivor within reconnectBound. |
| +func (r socketResult) verdict(cfg drillConfig, stopAt time.Time) string { |
| switch { |
| - case !r.Connected: |
| + case len(r.Conns) == 0 || r.Conns[0].Box != r.Pinned: |
| return "never connected to its box: " + r.Err |
| - case r.Open: |
| + case !r.Conns[len(r.Conns)-1].Dropped.IsZero(): |
| return "dropped and never reconnected: " + r.Err |
| - case stopped && r.Drops == 0: |
| - return "never dropped while its box was stopped" |
| + } |
| + if r.Pinned == cfg.BoxB { |
| + if _, ok := r.stopReconnect(cfg.BoxB, cfg.BoxA, stopAt); !ok { |
| + return fmt.Sprintf("no drop on %s after the stop was followed by a reconnect to %s within %s", cfg.BoxB, cfg.BoxA, reconnectBound) |
| + } |
| } |
| return "" |
| } |
| @@ -717,9 +825,25 @@ func (w *socketWatch) stop() socketResult { |
| } |
| } |
| -// 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. |
| +// redial is the pause before the next dial: from 100 ms, doubling to 2 s, |
| +// and back to 100 ms after a connection is held. It returns false when ctx |
| +// ends first. |
| +type redial struct{ wait time.Duration } |
| + |
| +func (b *redial) pause(ctx context.Context) bool { |
| + b.wait = min(max(2*b.wait, 100*time.Millisecond), 2*time.Second) |
| + select { |
| + case <-ctx.Done(): |
| + return false |
| + case <-time.After(b.wait): |
| + return true |
| + } |
| +} |
| + |
| +// watchSocket opens a websocket pinned to box: it dials /cable until an |
| +// upgrade names box (for up to a minute), then holds it and reconnects, to |
| +// whichever copy answers, whenever it drops. Every upgrade must name a |
| +// drill box (dialSocket); one that does not is a failed dial. |
| func (d *drill) watchSocket(ctx context.Context, box string) *socketWatch { |
| ctx, cancel := context.WithCancel(ctx) |
| w := &socketWatch{cancel: cancel, done: make(chan socketResult, 1)} |
| @@ -733,75 +857,73 @@ func (d *drill) watchSocket(ctx context.Context, box string) *socketWatch { |
| } |
| 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} |
| + r := socketResult{Pinned: box} |
| + var b redial |
| pinBy := time.Now().Add(time.Minute) |
| - for ctx.Err() == nil && !r.Connected && time.Now().Before(pinBy) { |
| + for ctx.Err() == nil { |
| + if len(r.Conns) == 0 && time.Now().After(pinBy) { |
| + break |
| + } |
| c, got, err := d.dialSocket(ctx) |
| if err != nil { |
| r.Err = err.Error() |
| - time.Sleep(100 * time.Millisecond) |
| + if !b.pause(ctx) { |
| + break |
| + } |
| continue |
| } |
| - if got != box { |
| + if len(r.Conns) == 0 && got != box { |
| c.Close() |
| + if !b.pause(ctx) { |
| + break |
| + } |
| continue |
| } |
| - 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 |
| + b = redial{} |
| + r.Conns = append(r.Conns, socketConn{Box: got, Connected: time.Now()}) |
| + if n := len(r.Conns); n > 1 { |
| + d.note("observation: websocket pinned to %s reconnected to %s after %s", box, got, r.Conns[n-1].Connected.Sub(r.Conns[n-2].Dropped)) |
| + } else { |
| + d.note("websocket connected to %s", got) |
| } |
| - 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) |
| + 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() |
| if ctx.Err() == nil { |
| - lost = time.Now() |
| - r.Drops++ |
| - d.note("websocket pinned to %s dropped again", box) |
| + r.Conns[len(r.Conns)-1].Dropped = time.Now() |
| + d.note("websocket pinned to %s dropped its connection to %s", box, got) |
| } |
| } |
| - 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, within handshakeBound. It returns |
| -// the box the 101 answer names. |
| +// the upgrade request and a 101 answer, within handshakeBound. The answer |
| +// must name one of the drill boxes in X-Drill-Box; an empty or other name |
| +// is an error, so it never counts as a connection. |
| 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(dctx, "tcp", d.cfg.Host+":443") |
| + cfg, addr := d.socketTLS, d.socketAddr |
| + if cfg == nil { |
| + cfg = &tls.Config{ServerName: d.cfg.Host} |
| + } |
| + if addr == "" { |
| + addr = d.cfg.Host + ":443" |
| + } |
| + dialer := &tls.Dialer{Config: cfg} |
| + conn, err := dialer.DialContext(dctx, "tcp", addr) |
| if err != nil { |
| return nil, "", err |
| } |
| @@ -825,11 +947,16 @@ func (d *drill) dialSocket(ctx context.Context) (net.Conn, string, error) { |
| conn.Close() |
| return nil, "", fmt.Errorf("websocket upgrade: %s", res.Status) |
| } |
| + box := res.Header.Get("X-Drill-Box") |
| + if box != d.cfg.BoxA && box != d.cfg.BoxB { |
| + conn.Close() |
| + return nil, "", fmt.Errorf("websocket upgrade named box %q, not %s or %s", box, d.cfg.BoxA, d.cfg.BoxB) |
| + } |
| if err := conn.SetDeadline(time.Time{}); err != nil { |
| conn.Close() |
| return nil, "", err |
| } |
| - return conn, res.Header.Get("X-Drill-Box"), nil |
| + return conn, box, nil |
| } |
| // readRecords reads an exported request record file: one JSON object a |