ha: serialize sidecar enable with HA record creation
Hold the existing app lock across enable validation and its manifest CAS. Recheck the original manifest etag under that lock before either HA sidecar create arm writes, and log strict-list failures. Cover both race orders, legacy compatibility and refusal errors; retain P3 findings as follow-ups. Targeted and race tests, vet, cross-builds and census pass. The single full console run hit its default 10-minute limit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/superpowers/notes/region-ha-followups-p3.md+11 −0internal/console/apisidecars.go+38 −7internal/console/hostsused.go+4 −1internal/console/sidecar_enable_ha_test.go+291 −0
CI failed — run details
Intent
<task-notification> <task-id>bfrkqyvka</task-id> <tool-use-id>toolu_0129fdkyLfwiLTZ1ouVaCTaG</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a26a0e24-c72d-4660-abab-b54e6b2b72b5/tasks/bfrkqyvka.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-s/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties; L=$W/task-B6-astra-b.log; prev=0; idle=0; while [ ! -f $W/task-B6-astra-b.done ]; do sleep 120; s=$(stat -c %s $L); if [ "$s" = "$prev" ]; then idle=$((idle+1)); else idle=0; fi; prev=$s; [ $idle -ge 15 ] && { echo STALLED; exit 0; }; done; cat $W/task-B6-astra-b.done" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a81c3a4d4af78d79b</task-id> <tool-use-id>toolu_01Eq4GqAPqrzVfzoiLxgLJnS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a26a0e24-c72d-4660-abab-b54e6b2b72b5/tasks/a81c3a4d4af78d79b.output</output-file> <status>completed</status> <summary>Agent "Opus review of Task B6" 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>Verdict: **READY AFTER FIXES**. Spec ✅ compliant with three ⚠️ items. Task quality: Needs fixes. Counts: P1 0, P2 1, P3 8. - **P2-1:** The enable door's "HA sidecar without hibernation" guard (`apisidecars.go:747-759`) has no test, races with create, and returns 502 on a failed record list without logging it. If the race lands, a stamped sidecar ends up under a `hibernate:false` manifest. It then never runs again, its departures stay open and keep paging, and the member got a 201. It fails safe, but the outcome is permanent and silent. Fault family: HA-shape invariant at the console manifest door. The three ⚠️ items are: - whether the per-host callback socket is reachable only from its own tenant's unit, which rests on the root witness and the run-mount comment; - the census overlay, which is still a proposal awaiting the independent verdict on #280; - mixed-version rollout (P3-1). The full review, with all eight P3s and the checks I ran, is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-s/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/task-B6-review-opus.md`.</result> <usage><subagent_tokens>214196</subagent_tokens><tool_uses>50</tool_uses><duration_ms>482763</duration_ms></usage> </task-notification>
<task-notification> <task-id>brwdqfhg4</task-id> <tool-use-id>toolu_013ZQZwCqr9kDdWNcx2WUjpM</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a26a0e24-c72d-4660-abab-b54e6b2b72b5/tasks/brwdqfhg4.output</output-file> <status>completed</status> <summary>Background command "cd /home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-s; echo "Task B6: Opus task review r1 dispatched (package review-19f36f44..0f3eaad8.diff)" >> .superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/progress.md; amadan task set 557 -status Done | tail -1; amadan task set 558 -status Started | tail -1; until amadan ci status carlos/platform -branch region-ha-p1b3b-s-build >/dev/null 2>&1; [ $? -ne 2 ] && [ $? -ne 3 ]; do sleep 60; done; amadan ci status carlos/platform -branch region-ha-p1b3b-s-build 2>&1 | grep -v "go: downloading" | tail -40" completed (exit code 0)</summary> </task-notification>
<task-notification> <task-id>a604d78b131b0b97a</task-id> <tool-use-id>toolu_01Ne9urHmwQ4ZTHMkqUJT2s1</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a26a0e24-c72d-4660-abab-b54e6b2b72b5/tasks/a604d78b131b0b97a.output</output-file> <status>completed</status> <summary>Agent "Opus census review region-ha-p1b3b-s" 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>**Overall: APPROVED** for tip `0f3eaad8`. **Verdicts:** 33, all approved: - 16 changed units: 8 body, 8 sites. - 11 new dispositions: 6 new units, 5 reads. - 6 envelopes: activator, edge, edgesfile, host, provision, registry. **Census card:** `make census-card` reports "Nothing to approve: the census is clean (seal `05f08ede…a35ad6`)", which matches the card's seal. The five census tests all pass on a clean `git archive` export of `0f3eaad8`. I deleted that export afterwards. **P1 and P2:** none. **One thing to pass on before merge (P3-3):** the author's uncommitted console edits (`internal/console/apisidecars.go` and `hostsused.go`) make `TestPlan9B8RecordWriteCensus` fail in the live worktree. The failing site is `hostsused.go:Server.createSidecarMarked`. Console is outside the root-read census but inside the record-write census walk, so when that in-flight fix lands it needs its own reviewed inventory update, not just a new digest. My approval covers `0f3eaad8` only. The other two P3 notes need no change before merge: - **P3-1:** `KillHost` and `EmptyHost` choose the new stop proof by the row's layout, not by how the worker was started. Only an operator-written sidecar row could hit the mismatch. Suggested fix: also require `rt.HA && rt.Provisioned && rt.Socket == ""` in both guards. - **P3-2:** the per-host `agent.sock` is created and then given its permissions by path, rather than with the safer set-before-bind helper the edge uses. It runs as `carlos`, not root, on the nosymfollow mount, and the per-wake token is the real check. The full review, with line citations and explicit answers to all five questions, is at `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p1b3b-s/.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/census-review-opus.md`. The tests needed the sandbox off: the Go build cache is read-only inside it, so `make census-card` failed there. I didn't record the verdict on #280; the author or orchestrator needs to post it with reviewer and tip.</result> <usage><subagent_tokens>162810</subagent_tokens><tool_uses>50</tool_uses><duration_ms>532400</duration_ms></usage> </task-notification>
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="487576af-49df-419a-867c-6167e3166535"> Agent manager 8a3d302: FYI, slice S should be merged before v0.34.6 is cut, so its sidecar rows ride G2 drill 1 (G2-CARD T9). No change to your process; tell me when it merges. </paseo-system>
Attributed to this commit: 9.29 g CO₂e (1,151,814 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p1b3b-s-build, 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/superpowers/notes/region-ha-followups-p3.md b/docs/superpowers/notes/region-ha-followups-p3.md| index 7bcc5766c..e057dd907 100644 |
| --- a/docs/superpowers/notes/region-ha-followups-p3.md |
| +++ b/docs/superpowers/notes/region-ha-followups-p3.md |
| @@ -19,3 +19,14 @@ From the per-task and branch reviews of branch region-ha-followups (2026-11-03/0 |
| - Branch r1 P1-1 (fixed as docs): Ruling P17 assumed an operator could replace `control/boxes/<ref>.json`; the bucket policy `BoxRecordsAreNeverDeleted` forbids it. The runbook now says a recreated fixed box takes a new reference. If reusing a reference is ever needed, it needs a ruling to lift that policy statement. |
| - Branch r2 P3-1: records of departed fixed references stay in the bucket for good; boxes that never bound one re-read it on each identity walk (backoff up to 300 s). |
| - Branch r2 P3-2: the runbook's SSM scope sentence depends on `ssm_parameter_arn`; the role-level copy route does not mention KMS decrypt for a parameter encrypted in another region. |
| + |
| +## P1b-3b slice S (B6) follow-ups |
| + |
| +- P3-1: Record the required rollout order in the merge/release note: upgrade every box reading the bucket before enabling console HA stamping for sidecars; a pre-B6 box can mint a flat-path row that stays stuck after upgrade (`internal/provision/sidecar_reconcile.go`, `internal/activator/hawake.go`). |
| +- P3-2: Give sidecar adoption refusals sidecar wording and separate placement/unknown-manifest reason codes; the current page says instance and blames the pool (`internal/host/hadepartures_wiring.go`). |
| +- P3-3: Share the sidecar placement predicate or pin its copies against reconcile with a table test (`internal/provision/sidecar_reconcile.go`, `internal/host/hadepartures.go`, `internal/edge/wakeplacement.go`, `internal/console/hacapacity.go`, `internal/sim/regionha/duties_model_test.go`). |
| +- P3-4: Share the pool grammar or test that evidence validation agrees with `provision.ValidPool` (`internal/edgesfile/servedpools.go`, `internal/provision/provision.go`). |
| +- P3-5: Obtain the raw HRW winner from boxchoice or assert the unfiltered production decision instead of copying the hash calculation (`internal/edge/sidecar_ha_test.go`, `internal/boxchoice`). |
| +- P3-6: Retain the tests-first exception in the task ledger: `TestSidecarNeverAdvertisedOrDialled` has mutation RED evidence, not pre-implementation RED (`internal/host/sidecar_ha_test.go`, `.superpowers/sdd/2026-11-03-region-ha-p1b3b-duties/task-B6-report.md`). |
| +- P3-7: Record the visible create-policy change in the merge/release note: HA regions now refuse always-on sidecars with 400 and pooled sidecars with 409 (`internal/console/apisidecars.go`, `internal/console/sidecar_ha_test.go`). |
| +- P3-8: Document the stopped-unit/nosymfollow invariant beside the listener's path-based chmod, and explain that raw inbound evidence distinguishes absence from false (`internal/activator/sidecar_ha.go`, `internal/edge/homemap.go`). |
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go| index 1718c3e24..52427fa95 100644 |
| --- a/internal/console/apisidecars.go |
| +++ b/internal/console/apisidecars.go |
| @@ -94,24 +94,46 @@ const sidecarMaxSeconds = 30 * 24 * 60 * 60 |
| // tell an app its feature had been switched off. The 409 names SIDECARS' own |
| // enable verb: an app with instances enabled and sidecars not is the ordinary |
| // state, so pointing at the other family's verb would be actively wrong. |
| -func (s *Server) sidecarManifest(ctx context.Context, w http.ResponseWriter, acct *Account, app string) (*provision.SidecarManifest, bool) { |
| - m, err := provision.GetSidecarManifest(ctx, s.cfg.Releases, acct.Sqid, app) |
| +func (s *Server) sidecarManifest(ctx context.Context, w http.ResponseWriter, acct *Account, app string) (*provision.SidecarManifest, string, bool) { |
| + m, etag, err := provision.GetSidecarManifestETag(ctx, s.cfg.Releases, acct.Sqid, app) |
| switch { |
| case err == nil: |
| - return m, true |
| + return m, etag, true |
| case errors.Is(err, os.ErrNotExist): |
| // Membership (or binding) is already proven, so this may name its |
| // cause and the act that fixes it. |
| jsonError(w, http.StatusConflict, |
| "sidecars are not enabled for "+app+" — enable them first (carlos sidecars enable -app "+app+")") |
| - return nil, false |
| + return nil, "", false |
| default: |
| log.Printf("console: api sidecars manifest %s/%s: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusBadGateway, "could not read sidecar settings") |
| - return nil, false |
| + return nil, "", false |
| } |
| } |
| +// recheckSidecarHAManifest runs under the app lock, before any create |
| +// writes. Enable holds that lock through its record check and manifest CAS: |
| +// if create wins, enable sees the stamp; if enable wins, create rejects the |
| +// changed manifest. Comparing etags also refuses stale placement policy. |
| +func (s *Server) recheckSidecarHAManifest(ctx context.Context, rec provision.SidecarRecord, etag string) *doorRefusal { |
| + if !rec.HA { |
| + return nil |
| + } |
| + m, current, err := provision.GetSidecarManifestETag(ctx, s.cfg.Releases, rec.Account, rec.App) |
| + if err != nil { |
| + log.Printf("console: api sidecars manifest %s/%s: %v", rec.Account, rec.App, err) |
| + return &doorRefusal{Status: http.StatusBadGateway, Msg: "could not read sidecar settings"} |
| + } |
| + if !m.HibernateOrDefault() { |
| + return &doorRefusal{Status: http.StatusBadRequest, Msg: "high availability sidecars must allow hibernation."} |
| + } |
| + if current != etag { |
| + return &doorRefusal{Status: http.StatusConflict, Msg: "sidecar settings changed while this request was in flight — try again"} |
| + } |
| + return nil |
| +} |
| + |
| // sidecarListRecord wraps provision.SidecarRecord with the console's own |
| // running-version join, kept OFF the record for the same reason |
| // instanceListRecord keeps staged_version off provision.Record: the record is |
| @@ -230,7 +252,7 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request) |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| defer cancel() |
| - m, ok := s.sidecarManifest(ctx, w, acct, app) |
| + m, manifestETag, ok := s.sidecarManifest(ctx, w, acct, app) |
| if !ok { |
| return |
| } |
| @@ -443,6 +465,10 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| defer unlock() |
| + if ref := s.recheckSidecarHAManifest(claimCtx, rec, manifestETag); ref != nil { |
| + jsonError(w, ref.Status, ref.Msg) |
| + return |
| + } |
| if ref := s.copiesSidecarRefusal(claimCtx, acct.Sqid, app); ref != nil { |
| jsonError(w, ref.Status, ref.Msg) |
| return |
| @@ -468,7 +494,7 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request) |
| } else { |
| // Always the direct writer, lifetimes on or off: the hostname |
| // history's mark, then the create-only write (hostsused.go). |
| - recordWriteErr = s.createSidecarMarked(ctx, rec) |
| + recordWriteErr = s.createSidecarMarked(ctx, rec, manifestETag) |
| } |
| if err := recordWriteErr; err != nil { |
| var used *hostsUsedError |
| @@ -715,6 +741,10 @@ func (s *Server) handleAPISidecarEnable(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| } |
| + // Serialize the manifest read, HA record check and CAS with record |
| + // creation. Create revalidates its earlier manifest under this same |
| + // app lock before either write arm. See applocks.go's one-console rule. |
| + defer s.lockApp(acct.Sqid, app)() |
| m, etag, err := provision.GetSidecarManifestETag(ctx, s.cfg.Releases, acct.Sqid, app) |
| switch { |
| case errors.Is(err, os.ErrNotExist): |
| @@ -753,6 +783,7 @@ func (s *Server) handleAPISidecarEnable(w http.ResponseWriter, r *http.Request) |
| if !m.HibernateOrDefault() { |
| recs, err := provision.ListSidecarRecordsStrict(ctx, s.cfg.Releases, acct.Sqid, app) |
| if err != nil { |
| + log.Printf("console: api sidecars enable list %s/%s: %v", acct.Sqid, app, err) |
| jsonError(w, http.StatusBadGateway, "could not read the sidecar") |
| return |
| } |
diff --git a/internal/console/hostsused.go b/internal/console/hostsused.go| index 9e329d6c7..184b03994 100644 |
| --- a/internal/console/hostsused.go |
| +++ b/internal/console/hostsused.go |
| @@ -695,8 +695,11 @@ func (s *Server) createRecordMarkedLocked(ctx context.Context, rec provision.Rec |
| // createSidecarMarked is the sidecar door's create: a sidecar is always a |
| // data kind, admitted (gateDataCreate) and marked at its host, then |
| // provision.CreateSidecarRecord. |
| -func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarRecord) error { |
| +func (s *Server) createSidecarMarked(ctx context.Context, rec provision.SidecarRecord, manifestETag string) error { |
| defer s.lockApp(rec.Account, rec.App)() // record writes hold the app lock (recordlock.go) |
| + if ref := s.recheckSidecarHAManifest(ctx, rec, manifestETag); ref != nil { |
| + return &hostsUsedError{*ref} |
| + } |
| defer s.copiesCreateNameLock(ctx)() |
| if ref := s.copiesSidecarRefusal(ctx, rec.Account, rec.App); ref != nil { |
| return &hostsUsedError{*ref} |
diff --git a/internal/console/sidecar_enable_ha_test.go b/internal/console/sidecar_enable_ha_test.go| new file mode 100644 |
| index 000000000..31c6617ef |
| --- /dev/null |
| +++ b/internal/console/sidecar_enable_ha_test.go |
| @@ -0,0 +1,291 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "log" |
| + "net/http" |
| + "os" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +func sidecarEnableHAFixture(t *testing.T) *leftoverFx { |
| + t.Helper() |
| + fx := haCreateHome(t) |
| + createCapacityEvidence(t, fx.srv, "allow", func(m map[string]any) { m["served_pools"] = []string{""} }) |
| + enableSidecars(t, fx.consoleFixture, "titogo", provision.SidecarManifest{Schema: 1, App: "titogo", Args: []string{"work"}}) |
| + return fx |
| +} |
| + |
| +func TestSidecarHAEnableGuard(t *testing.T) { |
| + for _, stamped := range []bool{true, false} { |
| + name := "legacy-allowed" |
| + if stamped { |
| + name = "stamped-refused" |
| + } |
| + t.Run(name, func(t *testing.T) { |
| + fx := sidecarEnableHAFixture(t) |
| + if !stamped { |
| + fx.srv.cfg.HARegions = nil |
| + } |
| + code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot"}`) |
| + if code != http.StatusCreated { |
| + t.Fatalf("create: %d %s", code, out) |
| + } |
| + fx.srv.cfg.HARegions = []string{"ie"} |
| + key := provision.SidecarManifestKey("bab", "titogo") |
| + before, _, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + recordKey := provision.SidecarRecordKey("bab", "titogo", "bot") |
| + recordBefore, _, err := fx.rel.Get(context.Background(), recordKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + code, _, out = rawReq(t, http.MethodPut, sidecarEnableURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"hibernate":false}`) |
| + after, _, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if stamped { |
| + if code != http.StatusBadRequest || ltErr(out) != "high availability sidecars must allow hibernation." { |
| + t.Errorf("enable: %d %s", code, out) |
| + } |
| + if !bytes.Equal(before, after) { |
| + t.Error("refused enable changed manifest bytes") |
| + } |
| + } else { |
| + if code != http.StatusOK { |
| + t.Fatalf("enable: %d %s", code, out) |
| + } |
| + m, err := provision.GetSidecarManifest(context.Background(), fx.rel, "bab", "titogo") |
| + if err != nil || m.HibernateOrDefault() { |
| + t.Fatalf("legacy-only manifest: %+v, %v", m, err) |
| + } |
| + } |
| + recordAfter, _, err := fx.rel.Get(context.Background(), recordKey) |
| + if err != nil || !bytes.Equal(recordBefore, recordAfter) { |
| + t.Fatalf("enable changed record: %s, %v", recordAfter, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type sidecarEnableListFailure struct{ release.Store } |
| + |
| +func (s *sidecarEnableListFailure) List(ctx context.Context, prefix string) ([]string, error) { |
| + if prefix == provision.SidecarsPrefix("bab", "titogo") { |
| + return nil, errors.New("sidecar-list-injected-failure") |
| + } |
| + return s.Store.List(ctx, prefix) |
| +} |
| + |
| +func TestSidecarHAEnableListError(t *testing.T) { |
| + fx := sidecarEnableHAFixture(t) |
| + key := provision.SidecarManifestKey("bab", "titogo") |
| + before, _, err := fx.rel.Get(context.Background(), key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tracked := &haCreateStore{Store: &sidecarEnableListFailure{Store: fx.srv.cfg.Releases}} |
| + fx.srv.cfg.Releases = tracked |
| + var logs bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(old) |
| + code, _, out := rawReq(t, http.MethodPut, sidecarEnableURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"hibernate":false}`) |
| + if code != http.StatusBadGateway || ltErr(out) != "could not read the sidecar" { |
| + t.Errorf("enable: %d %s", code, out) |
| + } |
| + if !strings.Contains(logs.String(), "sidecar-list-injected-failure") || !strings.Contains(logs.String(), "bab/titogo") { |
| + t.Errorf("missing contextual list failure log: %s", logs.String()) |
| + } |
| + if n, _ := tracked.counts(); n != 0 { |
| + t.Errorf("list error attempted %d writes", n) |
| + } |
| + after, _, err := fx.rel.Get(context.Background(), key) |
| + if err != nil || !bytes.Equal(before, after) { |
| + t.Fatalf("list error changed manifest: %s, %v", after, err) |
| + } |
| +} |
| + |
| +type sidecarEnableBarrierStore struct { |
| + release.Store |
| + key string |
| + entered chan struct{} |
| + resume chan struct{} |
| + once sync.Once |
| +} |
| + |
| +func (s *sidecarEnableBarrierStore) Put(ctx context.Context, key string, body []byte, etag string) (string, error) { |
| + if key == s.key { |
| + s.once.Do(func() { |
| + close(s.entered) |
| + select { |
| + case <-s.resume: |
| + case <-ctx.Done(): |
| + } |
| + }) |
| + } |
| + return s.Store.Put(ctx, key, body, etag) |
| +} |
| + |
| +func TestSidecarHAEnableCreateRace(t *testing.T) { |
| + for _, first := range []string{"create", "enable"} { |
| + t.Run(first+"-writes-first", func(t *testing.T) { |
| + fx := sidecarEnableHAFixture(t) |
| + key := provision.SidecarRecordKey("bab", "titogo", "bot") |
| + if first == "enable" { |
| + key = provision.SidecarManifestKey("bab", "titogo") |
| + } |
| + barrier := &sidecarEnableBarrierStore{Store: fx.srv.cfg.Releases, key: key, entered: make(chan struct{}), resume: make(chan struct{})} |
| + fx.srv.cfg.Releases = barrier |
| + var resumeOnce sync.Once |
| + resume := func() { resumeOnce.Do(func() { close(barrier.resume) }) } |
| + defer resume() |
| + type response struct { |
| + code int |
| + body string |
| + } |
| + create, enable := make(chan response, 1), make(chan response, 1) |
| + startCreate := func() { |
| + go func() { |
| + code, _, body := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot"}`) |
| + create <- response{code, body} |
| + }() |
| + } |
| + startEnable := func() { |
| + go func() { |
| + code, _, body := rawReq(t, http.MethodPut, sidecarEnableURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"hibernate":false}`) |
| + enable <- response{code, body} |
| + }() |
| + } |
| + if first == "create" { |
| + startCreate() |
| + } else { |
| + startEnable() |
| + } |
| + select { |
| + case <-barrier.entered: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("first request never reached its write") |
| + } |
| + waiting := make(chan struct{}) |
| + var waitOnce sync.Once |
| + hook := func(kind, key, event string) { |
| + if kind == "app" && key == "bab/titogo" && event == lockWaiting { |
| + waitOnce.Do(func() { close(waiting) }) |
| + } |
| + } |
| + lifetimeLockHook.Store(&hook) |
| + defer lifetimeLockHook.Store(nil) |
| + second := enable |
| + if first == "create" { |
| + startEnable() |
| + } else { |
| + second = create |
| + startCreate() |
| + } |
| + // The second request either reaches the shared lock or exposes |
| + // the old race by completing before the first write is released. |
| + select { |
| + case <-waiting: |
| + case got := <-second: |
| + second <- got |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("second request neither waited nor answered") |
| + } |
| + resume() |
| + get := func(ch <-chan response) response { |
| + select { |
| + case got := <-ch: |
| + return got |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("request did not finish") |
| + return response{} |
| + } |
| + } |
| + c, e := get(create), get(enable) |
| + if first == "create" { |
| + if c.code != 201 || e.code != 400 || ltErr(e.body) != "high availability sidecars must allow hibernation." { |
| + t.Errorf("create=%+v enable=%+v", c, e) |
| + } |
| + } else if e.code != 200 || c.code != 400 || ltErr(c.body) != "high availability sidecars must allow hibernation." { |
| + t.Errorf("create=%+v enable=%+v", c, e) |
| + } |
| + m, err := provision.GetSidecarManifest(context.Background(), fx.rel, "bab", "titogo") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, err := provision.GetSidecarRecord(context.Background(), fx.rel, "bab", "titogo", "bot") |
| + if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + t.Fatal(err) |
| + } |
| + if rec != nil && rec.HA && !m.HibernateOrDefault() { |
| + t.Error("accepted manifest stranded a stamped sidecar without hibernation") |
| + } |
| + if first == "enable" && rec != nil { |
| + t.Error("refused create left a record") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +type sidecarManifestRecheckStore struct { |
| + release.Store |
| + reads int |
| + fail bool |
| +} |
| + |
| +func (s *sidecarManifestRecheckStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if key == provision.SidecarManifestKey("bab", "titogo") { |
| + s.reads++ |
| + if s.reads == 2 { |
| + if s.fail { |
| + return nil, "", errors.New("sidecar-manifest-recheck-failure") |
| + } |
| + m, etag, err := provision.GetSidecarManifestETag(ctx, s.Store, "bab", "titogo") |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + m.Placement = provision.PlacementNoInbound |
| + if err := provision.PutSidecarManifestIfMatch(ctx, s.Store, "bab", "titogo", *m, etag); err != nil { |
| + return nil, "", err |
| + } |
| + } |
| + } |
| + return s.Store.Get(ctx, key) |
| +} |
| + |
| +func TestSidecarHAEnableCreateRecheck(t *testing.T) { |
| + for _, fail := range []bool{false, true} { |
| + name, want := "stale-etag", http.StatusConflict |
| + if fail { |
| + name, want = "read-error", http.StatusBadGateway |
| + } |
| + t.Run(name, func(t *testing.T) { |
| + fx := sidecarEnableHAFixture(t) |
| + interleave := &sidecarManifestRecheckStore{Store: fx.srv.cfg.Releases, fail: fail} |
| + tracked := &haCreateStore{Store: interleave} |
| + fx.srv.cfg.Releases = tracked |
| + code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot"}`) |
| + if code != want { |
| + t.Errorf("create: %d %s, want %d", code, out, want) |
| + } |
| + if n, _ := tracked.counts(); n != 0 { |
| + t.Errorf("refused create attempted %d writes", n) |
| + } |
| + if _, err := provision.GetSidecarRecord(context.Background(), fx.rel, "bab", "titogo", "bot"); !errors.Is(err, os.ErrNotExist) { |
| + t.Fatalf("refused create left a record: %v", err) |
| + } |
| + }) |
| + } |
| +} |