carlos / platform Public

ha: preserve duties for native sidecars born HA

Implement B6a steps 1-3: stamp native sidecars at birth, retain their canonical lifetimes, and use the contained HA worker, files, duty and adoption paths. Publish exact served-pool evidence without adding public sidecar hosts.

Capture RED/GREEN and mutation evidence, update record/name/read censuses, and verify targeted tests, race checks, vet and production cross-builds. Full host tests reproduce baseline claims-provider failures; the non-Linux test suites have existing helper/build-tag failures. The root witness and I6 extension remain B6b.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 746caf425de3b2cd49421184eeea9d33100efffe parent 19f36f4
44 files changed, +1,612 −87
  • docs/superpowers/notes/census-proposal-region-ha-p1b3b-s.md +63 −0
  • docs/superpowers/notes/census-region-ha-p1b3b-s-claims.tsv +27 −0
  • internal/activator/activator.go +10 −1
  • internal/activator/backend_exec.go +20 −0
  • internal/activator/genbackend.go +6 −0
  • internal/activator/haduties.go +1 −1
  • internal/activator/hawake.go +22 −4
  • internal/activator/layout.go +1 −1
  • internal/activator/prepare.go +1 −1
  • internal/activator/sidecar_ha.go +123 −0
  • internal/activator/sidecar_ha_test.go +269 −0
  • internal/activator/unitproc.go +27 −9
  • internal/console/apisidecars.go +20 −1
  • internal/console/createleftovers.go +8 −3
  • internal/console/ha_born_test.go +9 −9
  • internal/console/hacapacity.go +34 −4
  • internal/console/hacreatecapacity_test.go +15 −2
  • internal/console/hap2_wiring_test.go +3 −4
  • internal/console/nocapacity.go +2 −2
  • internal/console/sidecar_ha_test.go +135 −0
  • internal/edge/homemap.go +7 −5
  • internal/edge/sidecar_ha_test.go +129 −0
  • internal/edge/wakeplacement.go +33 −2
  • internal/edgesfile/servedpools.go +53 −0
  • internal/edgesfile/servedpools_test.go +33 −0
  • internal/edgesfile/snapshot.go +6 −5
  • internal/host/agent.go +31 −1
  • internal/host/edgesfile.go +20 −3
  • internal/host/group_names_test.go +14 −11
  • internal/host/hadepartures.go +10 −4
  • internal/host/hadepartures_wiring.go +3 −3
  • internal/host/sidecar_ha_test.go +240 −0
  • internal/provision/departure_inventory.go +3 −2
  • internal/provision/lifetimeindex.go +35 −3
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/region_ha_sidecars_census_test.go +19 −0
  • internal/provision/run_keys_test.go +5 −0
  • internal/provision/sidecar.go +21 −0
  • internal/provision/sidecar_ha_test.go +55 −0
  • internal/provision/sidecar_reconcile.go +28 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-s.tsv +62 −0
  • internal/registry/ha_departures.go +4 −3
  • internal/registry/ha_duties.go +3 −1

CI failed — run details

Intent

Attributed to this commit: 28.1 g CO₂e (1,549,003 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/census-proposal-region-ha-p1b3b-s.md b/docs/superpowers/notes/census-proposal-region-ha-p1b3b-s.md
new file mode 100644
index 000000000..a34cd0e89
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-p1b3b-s.md
@@ -0,0 +1,63 @@
+# Census approval: region-ha-p1b3b-s
+
+Ruling `census-ruling-region-ha-p1b3b-s`. The independent reviewer approves or rejects every change below, 11 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/activator/activator.go` `Service.SleepWorker` | body | unchanged (3) | Refuse an idle-triggered worker stop while producer work holds the existing inflight lease reference; no new read or start authority. |
+| `internal/activator/haduties.go` `Service.WithDuty` | body | unchanged (5) | Include stamped provisioned sidecars in the existing restricted singleflight wake before producer work. Legacy sidecars remain inline. No new acquire or import protocol. |
+| `internal/activator/prepare.go` `ExecBackend.prepareKeyedAt` | body | unchanged (13) | Native sidecar run units use the existing nested secrets preparation and acknowledged sealed publication, but bind no app control listener. Existing run and seed reads unchanged. |
+| `internal/activator/unitproc.go` `ExecBackend.newUnitProcFor` | body | unchanged (5) | Attach optional per-worker API closers to the existing unit observer before starting it; unit naming and systemd/cgroup proof reads unchanged. |
+| `internal/host/hadepartures_wiring.go` `armHADepartures` | body | unchanged (17) | Carry the actual provisionTickConfig pools and inbound posture into CanAdopt; stamped sidecars use the existing production adopter. Legacy unresolved paging remains. No wider tenancy or new remote source. |
+| `internal/provision/sidecar_reconcile.go` `ReconcileSidecars` | body | unchanged (47) | Derive canonical sidecar lifetimes from account/app/synthetic host/CreatedAt; collect HA and manifest placement for departures before scope filtering; update a separate family in the existing lifetime index. Existing record reads, key parsing and removal authority remain. |
+| `internal/registry/ha_departures.go` `Registry.ImportHAWake` | body | unchanged (42) | Permit stamped provisioned hibernating socketless native sidecars through the shared SQL kind predicate while preserving transaction, Pair, lifetime, revision, receipt and binding checks. Import still grants no authority. |
+| `internal/registry/ha_duties.go` `Registry.BindHADuty` | body | unchanged (10) | Use the shared kind predicate to include only stamped provisioned hibernating socketless native sidecars. Existing captured-revision and Pair CAS remain. |
+| `internal/activator/activator.go` `Service.begin` | sites | +whole:Route | Construct a worker entry for sidecar producer wakes inside the same singleflight and inflight reference machinery; passes whole route to newWorkerEntry, no new data read. |
+| `internal/activator/backend_exec.go` `ExecBackend.StartWorkerStaged` | sites | +registry:Host ×2, +whole:Route ×3 | Require acquired HA lifetime and containment for stamped sidecars; after the existing staged build verification, dispatch their worker launch through startHAWorker. Legacy worker exec and parent co-spawn remain unchanged. |
+| `internal/activator/genbackend.go` `ExecBackend.EmptyHost` | sites | +whole:Route ×2 | For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone instead of treating its flat cgroup as its process tree; other shapes retain prior proof. |
+| `internal/activator/genbackend.go` `ExecBackend.KillHost` | sites | +whole:Route ×2 | For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone; no new root verb or new unit naming. Flat workers retain the existing cgroup proof. |
+| `internal/activator/hawake.go` `ExecBackend.acquireClassified` | sites | +whole:Route | Before any HA sidecar write require a known canonical lifetime, files store and valid shared sealer; unstamped sidecars cannot upgrade from an HA lock. Reuse existing containment, AcquireHAForDuty, restore and release paths. |
+| `internal/activator/unitproc.go` `ExecBackend.observe` | sites | +whole:Route | Retain the already-read advisory exit record for native sidecars after the same systemd and cgroup termination proof; crash classification never substitutes for stop proof. No new read source. |
+| `internal/edge/wakeplacement.go` `homeMap.wakeSnapshot` | sites | -registry:App, -registry:Host | Delegate to the shared cached projection with no sidecar policy supplied; unknown sidecar policy denies local duty. Ordinary instance candidate policy unchanged. |
+| `internal/host/agent.go` `haRecordFacts` | sites | +registry:App ×2, +registry:Host ×2, +whole:Route ×2 | For sidecars validate synthetic host identity, read the corresponding sidecar record and manifest from the existing deployment store, derive the canonical lifetime and restrictive placement. Failed reads refuse; instance judged reads unchanged. |
+
+Envelopes re-pinned: `internal/activator`, `internal/edge`, `internal/edgesfile`, `internal/host`, `internal/provision`, `internal/registry`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/activator/activator.go` `Service.SleepWorker`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved
+- `internal/activator/haduties.go` `Service.WithDuty`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Read route host for owned-awake checks and pass provisioned managed instances to restricted singleflight wake before producer writes, including cached legacy rows that discover sticky HA at acquire. Other route kinds keep their path; no authority bypass.
+- `internal/activator/prepare.go` `ExecBackend.prepareKeyedAt`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged;rev3=census-ruling-rootfs-fleet-followups;basis=names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 8: the cmd role three exceptions (no env read, the replica gate left to StartCmd, no app-log listener) now cover every one-shot role, instancectl.OneShot(role): cmd and tty; before, the tty role fell to the sidecar env-file read and an app-log listener on its handoff socket path; no read added, one removed for tty
+- `internal/activator/unitproc.go` `ExecBackend.newUnitProcFor`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;basis=the unit is named by unitNameFor(rt, role, gen), one more Route site (+whole:Route), and a role with no unit of the row's kind is refused before anything watches ""; no new read kind and no file read
+- `internal/host/hadepartures_wiring.go` `armHADepartures`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3 fix r1: Install proof adapter, adoption identity and suspicion callbacks before asynchronous startup. Lazily retry the same deployment/data clients; lifetime callback reads only the current host through ExecBackend.TerminationLifetime. Add bounded structured paging for unresolved per-iid records. No new bucket, tenant input path or acquire bypass. B4: Wire the shared lock reader and existing AdoptHost entry. Read local route, Pair and duty revision only after authoritative inventory eligibility; bind its record lifetime and refuse missing/mismatched local routes. No route synthesis or pool widening. B5: Publish the armed controller to the existing metrics sampler. No new loop, remote source or process authority.;rev3=census-ruling-region-ha-followups;basis=Inject the existing PageOperator function into the backend when HA departures are armed; no new read or paging transport.;rev3=census-ruling-region-ha-p3b;basis=Require group admission/BeginWork callbacks and pass them into the sole departure consumer, including the production adoption closure. Same store, identity and registry reads; consumer Started remains a lifecycle fact, not duty authority.
+- `internal/provision/sidecar_reconcile.go` `ReconcileSidecars`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the record walk and its sidecars manifest lookup move unchanged into the pass's scan closure (over a store argument) and the removal phase into its retire closure; over a record view snapshot, a pass that reaches a removal candidate (a sidecar gone or no longer placeable here) removes nothing on the snapshot's word: it runs scan again over the bucket (freshStore) and decides every removal that pass from that walk, by the walk's own rules (unusable records protected before scope, hosts matched across every key, placement from the bucket's record and sidecars manifest against this box's inbound); a walk that cannot read cleanly keeps every row; with no candidate, or disarmed, nothing is read again; the registry sites are main's, moved; relative to main's single walk a removal can only be withheld, never added;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: retain validated sidecar records before scope/manifest filtering for coverage, including hidden/out-of-pool records. No new object reads or sidecar HA authority.
+- `internal/registry/ha_departures.go` `Registry.ImportHAWake`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Validate all state then transactionally compare current Pair, lifetime, binding, revision and receipt before replacing rows and recording pending authority. Replays never replace rows. B2 fix r1: find replay receipts only within the current binding; an older binding remains history and permits a new guarded import. Preserve Pair/lifetime/revision checks and no authority from import.
+- `internal/registry/ha_duties.go` `Registry.BindHADuty`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Compare active route Pair and captured revision before changing its authoritative lifetime binding; clear basis and suppression on change.
+- `internal/activator/activator.go` `Service.begin`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: before an entry is made, a resident inside its backoff answers errResidentBackoff, and a rootfs row must pass the locked admission (rootfsRefusalLocked) and then the backend's rootfs gates off a.mu (rootfsStartRefusal, within the request's wait bound) before Acquire, Restore or the live link; the gate key is recorded on the entry; adds refusals before the lease only;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p1b3b-t;basis=Carry background-duty provenance into a new singleflight entry; a visitor waiting on its deferred refusal retries with ordinary visitor authority. No read added.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: check local tenant admission and start permission before lease/restore, preserving already-awake reuse during drain and existing serialization. Whole Route passes to the local predicate; no new filesystem or store read.
+- `internal/activator/backend_exec.go` `ExecBackend.StartWorkerStaged`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read.
+- `internal/activator/genbackend.go` `ExecBackend.EmptyHost`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=fix1-merge-review;basis=Checks agent-owned host cleanup before lease release; no root authority is derived from it.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 N1: refuses a row with a runtime first (refuseHostCgroupProof); the cgroup open moves into openHostCgroup (same delegation check and OpenCleanup, with the test seam); reads Runtime
+- `internal/activator/genbackend.go` `ExecBackend.KillHost`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 N1: refuses a row with a runtime first (refuseHostCgroupProof); the cgroup open moves into openHostCgroup (same delegation check and OpenCleanup); reads Runtime
+- `internal/activator/hawake.go` `ExecBackend.acquireClassified`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the acquire's classification: a legacy route (sidecar, hand-added or not an instance) takes lease.Acquire and refuses on an HA-format lock; otherwise isHA (a record read error fails the wake, never falls back to legacy); not HA takes lease.Acquire, and an HA-format lock there marks the host HA for good and continues; HA requires haContained before any lock request, then lease.AcquireHA with the same-box proof; held and refused leases map to errLeaseHeld and errLeaseRefused (leaseError); +registry:Host, +whole:Route x7;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: the HA acquire's Proofs gain OwnerTerminated (b.ownerTerminated(ctx, rt)) beside SameBoxEmpty; one more whole:Route site passes the route to ownerTerminated; nothing new is read; the proof is consulted only by hafresh.DecideAcquire for another box's expired HA lock;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 7, two-box fleet test): the two legacy acquires call b.acquireLegacy(ctx, prefix), which is acquireLegacyLease exactly when ExecBackend.LeaseIdentity is nil and LeaseTTL is 0 (the agent never sets them), otherwise lease.AcquireAs with that identity and TTL. The classification, the HA path and every refusal are unchanged. Read sites unchanged (9). Agent, not root.;rev3=census-ruling-region-ha-p1b3b-t;basis=Select the restriction-only AcquireHAForDuty for background contexts, including sticky HA reclassification; observe successful ordinary acquires to clear stale suppression. Add a whole-route observer argument; no new authority. B2 binds the current authoritative lifetime and advances local revision before HA acquire, invalidating concurrent adoption I/O. Ordinary lease authority and restore ordering remain unchanged. B2 fix r1: advance the local duty revision with an unconditional registry UPDATE before acquire; remove pre-acquire lifetime CAS and basis clearing. Failed acquire preserves adopted state. Existing lease validation and successful-acquire observer remain. B3: pass the same optional durable termination proof adapter to visitor and duty acquires. Nil retains the existing path until controller arming; configured proof failures refuse, with no fallback to a live boolean. No new read in this unit. Final fix P2-1: copy the shared proof adapter per acquire to attach the existing takeover telemetry; retain a live confirmer fallback for unverified identities. Existing classified owner, lifetime, expiry and CAS guards remain.;rev3=census-ruling-agent-start-demo-1;basis=Reads demo shape/layout and takes the existing legacy renewing lease for demos; never falls through to HA acquisition. Merge integration against origin/main 9bd45488 retains main's HA duty/termination proof wiring after the demo legacy-lease branch; the added whole-route passes are main's existing checks.
+- `internal/activator/unitproc.go` `ExecBackend.observe`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=final fix I3: the process observer's termination proof for a rootfs handle (Runtime, the new kind, one site) goes through unitEvents (two more Route sites): the host slice's cgroup.events and, for a rootfs unit, the group systemd reports when that is elsewhere, so a foreign invocation root placed outside the slice and could not stop is never read as gone from the absent expected path; a failed stop of a foreign invocation leaves it unstopped, asked again next poll, completion pending; a binary handle's proof is unchanged (cgroup.events under the host slice); the agent decides only whether it keeps a handle and a launch file; no root decision; re-digested at the merge of origin/main 3c33f2eb: main's own change to the observer is in the body, this branch's rootfs-aware evidence and the rootfs-only failed-stop retry (merge prep N1: a binary handle behaves exactly as main) on top; the kinds are the union;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: for a worker handle (p.worker != "") the observer keeps the exit record it read (workerExit, workerExitOK) for the supervisor instead of wording a member event, and says nothing for a replaced-after-stop or restarted-outside end; the termination evidence (cgroup.events via unitEvents, the foreign-invocation rule) and the record's single-use removal are unchanged and apply to a worker as to a generation; a binary or generation handle behaves exactly as before; the same 22 read sites, no read added;rev3=census-ruling-rootfs-worker-exit;basis=an exit record with an empty code (read and bounded as before) is filled by unitMainExitOf before it is kept for a worker or worded for the member; the termination proof (UnitState, cgroup evidence, the foreign-invocation rule) and the record's single-use removal are unchanged; the same 22 read sites, no read added
+- `internal/edge/wakeplacement.go` `homeMap.wakeSnapshot`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Project cold-wake candidates from one immutable cached edges fold using the local route's canonical host, release.RouteAccount and app. Reads only in-memory route fields, cached publication additions and mirrored signing keys; no filesystem, registry, store or root authority added. Reject malformed placement evidence independently of the unchanged holder decoder; preserve explicit local safety denials even when stale.;rev3=census-ruling-region-ha-home-placement;basis=none: accepts the omitted/empty home placement, refuses explicit null; same in-memory fold reads, no new read;rev3=census-ruling-region-ha-p1b3b-t;basis=Expose fresh compatible peer membership separately from per-host eligible serving entries for suppression invalidation. Existing home/pool/scope filtering remains; no new reads.
+- `internal/host/agent.go` `haRecordFacts`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new (region HA P1a), the agent as carlos: activator.Config.Record, the closure the HA classification calls on a lifetime index miss: opens the deployment store once (openDeployStore, kept under a mutex) and reads the host's record through judgedRecord(store, judge, release.RouteAccount(rt), rt.App, rt.Host) (CI fix: provision.ReadRecordJudged under the box's lifetime judge, which also GETs the host's incarnation slot control/host-incarnations/<host>.json from the same deployment store; a record the slot no longer vouches for, or a tombstone, reads as os.ErrNotExist; a nil judge, host claims on, is provision.GetRecord exactly), turned into a lifetime entry by provision.LifetimeEntryOf; the reads are the row it is handed (registry:App, registry:Host, whole:Route); the record is the console-written deployment record the reconcile passes already read; an open or read error is returned and the wake fails closed; root never calls it;rev3=census-ruling-stateless-replicas-1;basis=Return RecordFacts with lifetime identity, Coordinator and ReplicaDeploy from the same judged record object; same store and record reads, no extra GET.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/activator/sidecar_ha.go:ExecBackend.listenWorkerAPI`: reads +registry:Host; written legacy, accepted-legacy, frozen
+- new `internal/activator/sidecar_ha.go:ExecBackend.startHAWorker`: reads +registry:Host ×5, +whole:Route ×8; written legacy, accepted-legacy, frozen
+- new `internal/activator/unitproc.go:unitProc.Crashed`: reads +whole:Route; written legacy, accepted-legacy, frozen
+- new `internal/edge/wakeplacement.go:Edge.SidecarDutySnapshot`: reads +whole:Route; written legacy, accepted-legacy, frozen
+- new `internal/edge/wakeplacement.go:homeMap.dutySnapshot`: reads +registry:App, +registry:Host, +whole:Route ×3; written legacy, accepted-legacy, frozen
+- new `internal/edge/wakeplacement.go:sidecarBoxEligible`: reads +registry:Account, +registry:Addr, +registry:App, +registry:HA, +registry:Host, +registry:Pool, +registry:Provisioned, +registry:Region, +registry:Replica, +registry:Socket, +registry:Tunnel; written legacy, accepted-legacy, frozen
+- reads `internal/activator/hawake.go:ExecBackend.haContained`: +registry:Addr, +registry:Hibernate, +registry:Provisioned, +registry:Replica, +registry:Runtime, +registry:Seed, +registry:SeedSource, +registry:Socket, +registry:Tunnel; keeps legacy, task accepted-legacy
+- reads `internal/activator/hawake.go:haLegacyRoute`: +registry:HA; keeps legacy, task accepted-legacy
+- reads `internal/activator/layout.go:Classify`: +registry:Addr, +registry:HA, +registry:Provisioned, +registry:Socket; keeps legacy, task accepted-legacy
+- reads `internal/host/agent.go:runAgent`: +registry:Host, +whole:Route ×2; keeps authority, task B,C,D,F
+- reads `internal/provision/sidecar_reconcile.go:convergeSidecar`: +registry:HA ×2; keeps legacy, task accepted-legacy
+
+Seal: `1b5ef39b210f3c7db69e589da8a467ac4d4a4f218e1d97fb4706cd277a27eae1` → `05f08edeb46837a18f1abca302ad21d8c7782edef8af00cc4082f5ed4ea35ad6`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-s.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-region-ha-p1b3b-s-claims.tsv b/docs/superpowers/notes/census-region-ha-p1b3b-s-claims.tsv
new file mode 100644
index 000000000..a5d51a667
--- /dev/null
+++ b/docs/superpowers/notes/census-region-ha-p1b3b-s-claims.tsv
@@ -0,0 +1,27 @@
+internal/activator/activator.go:Service.SleepWorker Refuse an idle-triggered worker stop while producer work holds the existing inflight lease reference; no new read or start authority.
+internal/activator/haduties.go:Service.WithDuty Include stamped provisioned sidecars in the existing restricted singleflight wake before producer work. Legacy sidecars remain inline. No new acquire or import protocol.
+internal/activator/prepare.go:ExecBackend.prepareKeyedAt Native sidecar run units use the existing nested secrets preparation and acknowledged sealed publication, but bind no app control listener. Existing run and seed reads unchanged.
+internal/activator/unitproc.go:ExecBackend.newUnitProcFor Attach optional per-worker API closers to the existing unit observer before starting it; unit naming and systemd/cgroup proof reads unchanged.
+internal/host/hadepartures_wiring.go:armHADepartures Carry the actual provisionTickConfig pools and inbound posture into CanAdopt; stamped sidecars use the existing production adopter. Legacy unresolved paging remains. No wider tenancy or new remote source.
+internal/provision/sidecar_reconcile.go:ReconcileSidecars Derive canonical sidecar lifetimes from account/app/synthetic host/CreatedAt; collect HA and manifest placement for departures before scope filtering; update a separate family in the existing lifetime index. Existing record reads, key parsing and removal authority remain.
+internal/registry/ha_departures.go:Registry.ImportHAWake Permit stamped provisioned hibernating socketless native sidecars through the shared SQL kind predicate while preserving transaction, Pair, lifetime, revision, receipt and binding checks. Import still grants no authority.
+internal/registry/ha_duties.go:Registry.BindHADuty Use the shared kind predicate to include only stamped provisioned hibernating socketless native sidecars. Existing captured-revision and Pair CAS remain.
+internal/activator/activator.go:Service.begin Construct a worker entry for sidecar producer wakes inside the same singleflight and inflight reference machinery; passes whole route to newWorkerEntry, no new data read.
+internal/activator/backend_exec.go:ExecBackend.StartWorkerStaged Require acquired HA lifetime and containment for stamped sidecars; after the existing staged build verification, dispatch their worker launch through startHAWorker. Legacy worker exec and parent co-spawn remain unchanged.
+internal/activator/genbackend.go:ExecBackend.EmptyHost For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone instead of treating its flat cgroup as its process tree; other shapes retain prior proof.
+internal/activator/genbackend.go:ExecBackend.KillHost For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone; no new root verb or new unit naming. Flat workers retain the existing cgroup proof.
+internal/activator/hawake.go:ExecBackend.acquireClassified Before any HA sidecar write require a known canonical lifetime, files store and valid shared sealer; unstamped sidecars cannot upgrade from an HA lock. Reuse existing containment, AcquireHAForDuty, restore and release paths.
+internal/edge/wakeplacement.go:homeMap.wakeSnapshot Delegate to the shared cached projection with no sidecar policy supplied; unknown sidecar policy denies local duty. Ordinary instance candidate policy unchanged.
+internal/host/agent.go:haRecordFacts For sidecars validate synthetic host identity, read the corresponding sidecar record and manifest from the existing deployment store, derive the canonical lifetime and restrictive placement. Failed reads refuse; instance judged reads unchanged.
+internal/activator/sidecar_ha.go:ExecBackend.listenWorkerAPI Bind only the current host run directory agent.sock using the existing nosymfollow nested mount. Restrict claimed host to that route and reuse agentsock token authorization and request limits; no public listener or outbound tenant dial. Unit observer closes it.
+internal/activator/sidecar_ha.go:ExecBackend.startHAWorker Require nested HA sidecar shape and closed worker identity environment; prepare and acknowledge sealed secrets before writing the existing run launch file. Start the previously verified staged executable through existing root StartExe, mark uncertain starts for stop proof, and observe the same run unit. No health dial or new root verb.
+internal/edge/wakeplacement.go:Edge.SidecarDutySnapshot Pass local route and authoritative cached sidecar manifest policy to the existing edges fold projection; no store or request-time membership reads.
+internal/edge/wakeplacement.go:homeMap.dutySnapshot Keep instance host-evidence selection unchanged; sidecars require exact validated served_pools and local policy, compatible fresh scope/bucket/key and admission evidence. No sidecar public Hosts entry or tenant dial.
+internal/edge/wakeplacement.go:sidecarBoxEligible Read in-memory route identity, HA/provisioned bit, scope and pool; require canonical socketless native shape, exact served_pools and restrictive inbound policy. Unknown or malformed pool/placement evidence refuses.
+internal/activator/hawake.go:ExecBackend.haContained Refuse HA sidecars with unprovisioned/nonhibernating, dialable, replica, tunnel, runtime or seed shapes before nested containment checks. No fallback or new path read.
+internal/activator/hawake.go:haLegacyRoute Only stamped provisioned native sidecars join instance classification; unstamped and unprovisioned sidecars remain legacy and cannot take an HA-shaped lock.
+internal/activator/layout.go:Classify Recognize a stamped provisioned socketless sidecar only at its canonical NestedDBPath, retaining collision and layout fences. No dummy socket added.
+internal/host/agent.go:runAgent Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains.
+internal/provision/sidecar_reconcile.go:convergeSidecar Converge only the sticky HA bit with SetHA when the record is stamped; no database-path migration or record rewriting.
+internal/activator/unitproc.go:ExecBackend.observe Retain the already-read advisory exit record for native sidecars after the same systemd and cgroup termination proof; crash classification never substitutes for stop proof. No new read source.
+internal/activator/unitproc.go:unitProc.Crashed For native sidecars only, classify the retained exit record through workerExitStatus after done closes; intentional stops and unknown outcomes are not crashes. No process or lease authority.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 046a94d10..2f90feeab 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -70,6 +70,7 @@ import (
"sync/atomic"
"time"
+ "github.com/carlosframework/platform/internal/agentsock"
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/hafresh"
@@ -77,6 +78,7 @@ import (
"github.com/carlosframework/platform/internal/hostwrite"
"github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/replicas"
@@ -1664,6 +1666,9 @@ func New(cfg Config, backend Backend, due DueStore) *Service {
if u, ok := backend.(entryFilesUser); ok {
u.useEntryFiles(a.entryFilesFor)
}
+ if b := adoptionBackend(backend, registry.Route{Kind: provision.SidecarKind}); b != nil {
+ b.workerAPI = agentsock.New(a).Handler()
+ }
a.drainBudget = residentDrainBudget
return a
}
@@ -1820,6 +1825,10 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req
// and two restore attempts per request (#184, seen only as a
// loaded-suite test flake because the window is that narrow).
e = &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{}), rootfsAdmittedKey: admitted, duty: ctx.Value(dutyContextKey{}) != nil}
+ if rt.IsSidecar() {
+ e = a.newWorkerEntry(rt)
+ e.duty = ctx.Value(dutyContextKey{}) != nil
+ }
a.putEntryLocked(rt.Host, e)
go a.wake(e)
edge.MarkWoke(req)
@@ -4614,7 +4623,7 @@ func (a *Service) SleepWorker(host string) {
a.mu.Lock()
defer a.mu.Unlock()
e := a.entries[host]
- if e == nil || !e.worker || e.state != actAwake {
+ if e == nil || !e.worker || e.state != actAwake || e.inflight > 0 {
return
}
if !e.route.Hibernate {
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go
index 69c1ad312..a43a2ec6e 100644
--- a/internal/activator/backend_exec.go
+++ b/internal/activator/backend_exec.go
@@ -77,6 +77,7 @@ const quarantineSuffix = ".corrupt"
// `<DataDir>/<host>.env` EnvironmentFile.
type ExecBackend struct {
TenantStartAllowed func(registry.Route) bool
+ workerAPI http.Handler
// Coordination is the agent-owned client; serving never acquires through it.
Coordination *CoordinationClient
Cfg Config
@@ -3425,6 +3426,20 @@ func (b *ExecBackend) StartWorkerStaged(ctx context.Context, rt registry.Route,
if err := b.tenantStartRefusal(rt); err != nil {
return nil, release.StagedIdentity{}, err
}
+ if err := b.haSpawnGate(rt); err != nil {
+ return nil, release.StagedIdentity{}, err
+ }
+ if rt.IsSidecar() {
+ _, ha, err := b.isHA(ctx, rt)
+ if err != nil {
+ return nil, release.StagedIdentity{}, err
+ }
+ if ha {
+ if _, acquired := b.haAcquired(rt.Host); !acquired {
+ return nil, release.StagedIdentity{}, errors.New("ha_worker_lease_missing")
+ }
+ }
+ }
var argv []string
if err := json.Unmarshal([]byte(rt.Args), &argv); err != nil || len(argv) == 0 {
return nil, release.StagedIdentity{}, fmt.Errorf("worker %s: no runnable argv in args %q", rt.Host, rt.Args)
@@ -3457,6 +3472,11 @@ func (b *ExecBackend) StartWorkerStaged(ctx context.Context, rt registry.Route,
id = *onto
}
+ if _, ha := b.haAcquired(rt.Host); ha && rt.IsSidecar() {
+ proc, err := b.startHAWorker(ctx, rt, extra, id, argv)
+ return proc, id, err
+ }
+
// One read gives the env and the layer its CARLOS_INSTANCE_KEY came
// from, for the replica gate below (ruling 29). A worker never mints
// (ruling 12): the key is whatever the env files already deliver.
diff --git a/internal/activator/genbackend.go b/internal/activator/genbackend.go
index ed0873579..2d05c8399 100644
--- a/internal/activator/genbackend.go
+++ b/internal/activator/genbackend.go
@@ -689,6 +689,9 @@ func (b *ExecBackend) openHostCgroup(host string) (hostCleanup, error) {
//
// A row with a runtime is refused first (errRootfsKillHost).
func (b *ExecBackend) KillHost(ctx context.Context, rt registry.Route) error {
+ if rt.IsSidecar() && b.pathsFor(rt).layout == LayoutNested {
+ return b.LegacyRunGone(ctx, rt)
+ }
if err := refuseHostCgroupProof(rt); err != nil {
return err
}
@@ -736,6 +739,9 @@ func (b *SplitBackend) KillHost(ctx context.Context, rt registry.Route) error {
//
// A row with a runtime is refused first (errRootfsKillHost).
func (b *ExecBackend) EmptyHost(ctx context.Context, rt registry.Route) error {
+ if rt.IsSidecar() && b.pathsFor(rt).layout == LayoutNested {
+ return b.LegacyRunGone(ctx, rt)
+ }
if err := refuseHostCgroupProof(rt); err != nil {
return err
}
diff --git a/internal/activator/haduties.go b/internal/activator/haduties.go
index 243c90962..f6af19d9d 100644
--- a/internal/activator/haduties.go
+++ b/internal/activator/haduties.go
@@ -360,7 +360,7 @@ func (a *Service) WithDuty(ctx context.Context, rt registry.Route, work func(con
// A provisioned instance can discover sticky HA only at its lock read.
// Complete that ordinary wake before producer writes even when the cached
// record currently says legacy. Other route kinds retain their old path.
- if haLegacyRoute(rt) || !rt.ActivatorOwned() {
+ if haLegacyRoute(rt) || (!rt.ActivatorOwned() && !rt.IsSidecar()) {
return work(call)
}
done, err := a.begin(call, rt, false, nil)
diff --git a/internal/activator/hawake.go b/internal/activator/hawake.go
index d80942749..beec9d69a 100644
--- a/internal/activator/hawake.go
+++ b/internal/activator/hawake.go
@@ -71,11 +71,11 @@ var (
)
// haLegacyRoute reports a route that is legacy before any record lookup
-// (r3.4): a sidecar, a route the provision pass did not mint (hand-added),
-// or any kind but an instance. It keeps today's acquire, and an HA-format
+// (r3.4): an unstamped sidecar, a route the provision pass did not mint,
+// or a kind other than an instance or native sidecar. It keeps today's acquire, and an HA-format
// lock under it refuses the wake.
func haLegacyRoute(rt registry.Route) bool {
- return rt.IsSidecar() || !rt.Provisioned || rt.Kind != "instance"
+ return !rt.Provisioned || (rt.IsSidecar() && !rt.HA) || (rt.Kind != "instance" && !rt.IsSidecar())
}
// isHA is the HA classification, its one place: record facts only, never
@@ -148,6 +148,9 @@ func (b *ExecBackend) TerminationLifetime(ctx context.Context, host string) (str
// every rootfs row, because it guards the binary launch, and a rootfs row
// is nested under root's control service too (its start asks nestedReady).
func (b *ExecBackend) haContained(rt registry.Route) error {
+ if rt.IsSidecar() && (!rt.Provisioned || !rt.Hibernate || rt.Socket != "" || rt.Addr != "" || rt.Replica || rt.Tunnel != "" || rt.Runtime != "" || rt.Seed != "" || rt.SeedSource != "") {
+ return errors.New("unsupported HA sidecar shape")
+ }
if rt.Backing == registry.BackingUnit {
return errors.New("the row is unit-backed")
}
@@ -345,7 +348,11 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route)
if err != nil {
var hl *lease.HALockError
if errors.As(err, &hl) {
- return nil, &errLeaseRefused{reason: "ha lock on a route with no instance record"}
+ reason := "ha lock on a route with no instance record"
+ if rt.IsSidecar() {
+ reason = "ha lock on an unstamped sidecar"
+ }
+ return nil, &errLeaseRefused{reason: reason}
}
return nil, leaseError(err)
}
@@ -375,6 +382,17 @@ func (b *ExecBackend) acquireClassified(ctx context.Context, rt registry.Route)
if err := b.haContained(rt); err != nil {
return nil, refusedUncontained(err)
}
+ if rt.IsSidecar() {
+ if entry.ID == "" {
+ return nil, &errLeaseRefused{reason: "ha_lifetime_missing"}
+ }
+ if b.FilesStore == nil {
+ return nil, &errLeaseRefused{reason: "no files store configured"}
+ }
+ if _, err := b.sealerFor(rt); err != nil {
+ return nil, err
+ }
+ }
if b.Registry != nil {
if err := b.Registry.AdvanceHADuty(ctx, host); err != nil {
return nil, err
diff --git a/internal/activator/layout.go b/internal/activator/layout.go
index 81d27b0e4..dc0c9069b 100644
--- a/internal/activator/layout.go
+++ b/internal/activator/layout.go
@@ -121,7 +121,7 @@ func Classify(rt registry.Route, in LayoutInputs) (Layout, string) {
switch {
case rt.DBPath == provision.DefaultDBPath(in.DataDir, rt.Host) && rt.Socket == flatSock:
return LayoutFlat, ""
- case rt.DBPath == provision.NestedDBPath(in.DataDir, rt.Host) && rt.Socket == nestedSock:
+ case rt.DBPath == provision.NestedDBPath(in.DataDir, rt.Host) && (rt.Socket == nestedSock || (rt.IsSidecar() && rt.Provisioned && rt.HA && rt.Socket == "" && rt.Addr == "")):
return LayoutNested, ""
}
return LayoutForeign, fmt.Sprintf("db %q socket %q are neither the flat nor the nested defaults", rt.DBPath, rt.Socket)
diff --git a/internal/activator/prepare.go b/internal/activator/prepare.go
index de01d8ed6..34b9216af 100644
--- a/internal/activator/prepare.go
+++ b/internal/activator/prepare.go
@@ -131,7 +131,7 @@ func (b *ExecBackend) prepareKeyedAt(rt registry.Route, role instancectl.Role, s
}
}
var ctl *edge.ControlListener
- if role == instancectl.RoleRun {
+ if role == instancectl.RoleRun && !rt.IsSidecar() {
// Nothing is running: either this is the first invocation of this
// role for this host, or the unit is not active (Start would not
// have reached prepare otherwise), so any file at rt.Socket is a
diff --git a/internal/activator/sidecar_ha.go b/internal/activator/sidecar_ha.go
new file mode 100644
index 000000000..d11882d84
--- /dev/null
+++ b/internal/activator/sidecar_ha.go
@@ -0,0 +1,123 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// startHAWorker uses the host's run unit without a public socket or health dial.
+func (b *ExecBackend) startHAWorker(ctx context.Context, rt registry.Route, extra map[string]string, id release.StagedIdentity, argv []string) (Proc, error) {
+ if err := b.haContained(rt); err != nil {
+ return nil, refusedUncontained(err)
+ }
+ name, _, _ := strings.Cut(rt.Host, ".")
+ if extra["CARLOS_SIDECAR_HOST"] != rt.Host || extra["CARLOS_SIDECAR_NAME"] != name || extra["CARLOS_SIDECAR_TOKEN"] == "" {
+ return nil, errors.New("ha_worker_identity")
+ }
+ for key := range extra {
+ switch key {
+ case "CARLOS_AGENT_SOCKET", "CARLOS_SIDECAR_HOST", "CARLOS_SIDECAR_NAME", "CARLOS_SIDECAR_TOKEN":
+ default:
+ return nil, errors.New("ha_worker_environment")
+ }
+ }
+ if b.workerAPI == nil {
+ return nil, errors.New("ha_worker_api_missing")
+ }
+ if err := runBeforeExec(ctx, id); err != nil {
+ return nil, err
+ }
+ p, ctl, logs, env, err := b.prepare(rt, instancectl.RoleRun)
+ if err != nil {
+ return nil, err
+ }
+ if ctl != nil {
+ ctl.Close()
+ logs.Close()
+ return nil, errors.New("ha_worker_socket")
+ }
+ api, socket, err := b.listenWorkerAPI(rt, p)
+ if err != nil {
+ logs.Close()
+ return nil, err
+ }
+ fail := func(err error) (Proc, error) { _ = api.Close(); logs.Close(); return nil, err }
+ for k, v := range extra {
+ env = withVar(env, k, v)
+ }
+ env = withVar(env, "CARLOS_AGENT_SOCKET", socket)
+ if err = b.writeLaunch(p, instancectl.RoleRun, rt.Host, append([]string{b.liveLink(rt.Host)}, argv...), childEnv(storageVars(rt, env))); err != nil {
+ return fail(err)
+ }
+ if err = b.haSpawnGate(rt); err != nil {
+ return fail(err)
+ }
+ if err = runExecGate(ctx); err != nil {
+ return fail(err)
+ }
+ inv, err := b.startRole(ctx, rt, instancectl.RoleRun, 0, stagedExeOf(id), b.GenTier(rt, id.Version))
+ if err != nil {
+ if !errors.Is(err, errNoStagedExeControl) && !errors.Is(err, instancectl.ErrStagedExe) {
+ err = markLegacyStartUncertain(err)
+ }
+ return fail(err)
+ }
+ if inv == "" {
+ return fail(markLegacyStartUncertain(fmt.Errorf("%s: worker exited before it was observed", rt.Host)))
+ }
+ up, err := b.newUnitProcFor(rt, instancectl.RoleRun, 0, p, inv, nil, logs, api)
+ if err != nil {
+ return fail(markLegacyStartUncertain(err))
+ }
+ return up, nil
+}
+
+type workerAPIListener struct {
+ server *http.Server
+ done chan struct{}
+}
+
+func (l *workerAPIListener) Close() error { err := l.server.Close(); <-l.done; return err }
+
+func (b *ExecBackend) listenWorkerAPI(rt registry.Route, p instancePaths) (*workerAPIListener, string, error) {
+ socket := filepath.Join(p.runDir, "agent.sock")
+ // The directory is the host's existing nosymfollow run mount. A live listener
+ // is never replaced; stale socket removal follows the existing agent door.
+ if conn, err := net.DialTimeout("unix", socket, 250*time.Millisecond); err == nil {
+ conn.Close()
+ return nil, "", errors.New("ha_worker_api_in_use")
+ }
+ if err := os.Remove(socket); err != nil && !errors.Is(err, os.ErrNotExist) {
+ return nil, "", err
+ }
+ ln, err := net.Listen("unix", socket)
+ if err != nil {
+ return nil, "", err
+ }
+ if err = os.Chmod(socket, 0o660); err != nil {
+ ln.Close()
+ return nil, "", err
+ }
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Carlos-Sidecar-Host") != rt.Host {
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ b.workerAPI.ServeHTTP(w, r)
+ })
+ srv := &http.Server{Handler: handler, ReadHeaderTimeout: 2 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 30 * time.Second, MaxHeaderBytes: 1 << 14}
+ l := &workerAPIListener{server: srv, done: make(chan struct{})}
+ go func() { defer close(l.done); _ = srv.Serve(ln) }()
+ return l, socket, nil
+}
diff --git a/internal/activator/sidecar_ha_test.go b/internal/activator/sidecar_ha_test.go
new file mode 100644
index 000000000..a25da53db
--- /dev/null
+++ b/internal/activator/sidecar_ha_test.go
@@ -0,0 +1,269 @@
+package activator
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxchoice"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func haSidecarService(t *testing.T) *haSvc {
+ t.Helper()
+ s := haService(t, "bot.shop.bac.sidecar.internal")
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ s.a.Shutdown(ctx)
+ })
+ ctx := context.Background()
+ st := release.NewDirStore(t.TempDir())
+ if _, err := st.Put(ctx, "accounts/bac/account.json", []byte(`{"id":2,"sqid":"bac","name":"Shop","created_at":"2026-10-26T09:00:00Z"}`), ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.PutSidecarManifest(ctx, st, "bac", "shop", provision.SidecarManifest{Schema: 1, App: "shop", Args: []string{"work"}}); err != nil {
+ t.Fatal(err)
+ }
+ raw := []byte(`{"schema":1,"account":"bac","app":"shop","name":"bot","host":"bot.shop.bac.sidecar.internal","channel":"stable","created_at":"2026-10-26T09:00:00Z","ha":true}`)
+ var rec provision.SidecarRecord
+ if err := json.Unmarshal(raw, &rec); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.CreateSidecarRecord(ctx, st, rec); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.b.Registry.Delete(s.rt.Host); err != nil {
+ t.Fatal(err)
+ }
+ s.b.Lifetimes = &provision.LifetimeIndex{}
+ if err := provision.ReconcileSidecars(ctx, st, s.b.Registry, provision.ReconcileConfig{DataDir: s.b.DataDir, Lifetimes: s.b.Lifetimes}); err != nil {
+ t.Fatal(err)
+ }
+ rt, err := s.b.Registry.Get(rec.Host)
+ if err != nil || rt == nil {
+ t.Fatalf("reconcile: %v %v", rt, err)
+ }
+ s.rt = *rt
+ s.ctl.onStart = func() {
+ if err := ensureDB(s.b.pathsFor(s.rt).dbPath); err != nil {
+ t.Error(err)
+ }
+ m, ok, err := hostfiles.Load(ctx, s.b.FilesStore, s.b.filesPrefix(s.rt.Host))
+ if err != nil || !ok {
+ t.Errorf("no manifest before start: %v", err)
+ }
+ if _, ok := m.Platform[hostfiles.SealedEnvItem]; !ok {
+ t.Error("worker started before sealed env publication")
+ }
+ s.unit.started("inv1")
+ s.a.NoteWorkerReady(s.rt.Host, "v1")
+ }
+ s.a.DutyStore = s.b.Registry
+ s.a.SetDutyView(func(_ registry.Route) boxchoice.WakeSnapshot {
+ return boxchoice.WakeSnapshot{Usable: true, Serving: []boxchoice.Candidate{{BoxID: lease.CurrentSelf().Ref}}}
+ })
+ return s
+}
+
+func TestSidecarHADutyLifecycle(t *testing.T) {
+ s := haSidecarService(t)
+ ctx := context.Background()
+ if !s.rt.HA || !s.rt.IsSidecar() || s.rt.Socket != "" {
+ t.Fatalf("not a born HA worker: %+v", s.rt)
+ }
+ if err := s.a.WakeWorker(s.rt); err != nil {
+ t.Fatal(err)
+ }
+ due := time.Now().Add(time.Hour).Unix()
+ req, err := http.NewRequest(http.MethodPost, "http://carlos/v1/next-due", strings.NewReader(fmt.Sprintf(`{"at":%d}`, due)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Carlos-Sidecar-Host", s.rt.Host)
+ req.Header.Set("Authorization", "Bearer "+s.a.WorkerToken(s.rt.Host))
+ client := socketClient(filepath.Join(s.b.pathsFor(s.rt).runDir, "agent.sock"))
+ response, err := client.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ response.Body.Close()
+ if response.StatusCode != http.StatusNoContent {
+ t.Fatalf("worker callback %d", response.StatusCode)
+ }
+ deadline := time.Now().Add(4 * time.Second)
+ synced := false
+ for time.Now().Before(deadline) {
+ m, _, _ := hostfiles.Load(ctx, s.b.FilesStore, s.b.filesPrefix(s.rt.Host))
+ ws, ok, _ := hostfiles.LoadWake(ctx, s.b.FilesStore, s.b.filesPrefix(s.rt.Host), m, nil)
+ if ok && ws.NextDue == due {
+ synced = true
+ break
+ }
+ time.Sleep(50 * time.Millisecond)
+ }
+ if !synced {
+ t.Fatal("worker next_due did not sync through real publisher")
+ }
+ s.a.mu.Lock()
+ e := s.a.entries[s.rt.Host]
+ s.a.mu.Unlock()
+ s.stopForTest(e)
+ v, err := lease.ReadLock(ctx, s.b.Cfg.Bucket, s.b.Cfg.hibernatePrefix(s.rt.Host), s.b.Cfg.Region)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if v.Lock.Release == nil || v.Lock.Release.Lifetime == "" {
+ t.Fatalf("no sleep marker: %+v", v)
+ }
+ life := v.Lock.Release.Lifetime
+ lease.SetSelf(hafresh.Self{Ref: "b", IID: "i-b", Account: "111122223333", Region: "eu-west-1"})
+ s2 := s.peer(t)
+ t.Cleanup(func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ s2.a.Shutdown(ctx)
+ })
+ s2.a.DutyStore = s.b.Registry
+ state, err := s.b.Registry.LoadDuty(ctx, s.rt.Host, life)
+ if err != nil {
+ t.Fatal(err)
+ }
+ result, err := s2.a.AdoptHost(ctx, s.rt, Adoption{Departure: "dead-a", Ref: "a", IID: "i-a", Lifetime: life, Observed: v, Revision: state.Revision})
+ if err != nil || result != Adopted {
+ t.Fatalf("adopt %v %v", result, err)
+ }
+ v = s2.lockView(t)
+ if v.Lock.Release == nil || v.Lock.Release.Box != "b" || v.Lock.Release.Clean {
+ t.Fatalf("not unclean self marker: %+v", v)
+ }
+ s.ctl.onStart = func() {
+ if err := ensureDB(s2.b.pathsFor(s2.rt).dbPath); err != nil {
+ t.Error(err)
+ }
+ s.unit.started("inv1")
+ s2.a.NoteWorkerReady(s.rt.Host, "v1")
+ }
+ s2.a.now = func() time.Time { return time.Unix(due+1, 0) }
+ s2.a.sweepOnce()
+ deadline = time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ if s2.a.HoldsAwake(s.rt.Host) {
+ break
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ if !s2.a.HoldsAwake(s.rt.Host) {
+ t.Fatal("adopted sidecar did not due wake")
+ }
+ row, _ := s2.b.Registry.Get(s.rt.Host)
+ if row.NextDue != 0 {
+ t.Fatalf("due occurrence not consumed: %d", row.NextDue)
+ }
+ s2.a.mu.Lock()
+ entry := s2.a.entries[s.rt.Host]
+ s2.a.mu.Unlock()
+ s2.stopForTest(entry)
+
+}
+
+func TestSidecarHARefusals(t *testing.T) {
+ for _, mode := range []string{"uncontained", "unknown-lifetime", "no-key", "unstamped-lock"} {
+ t.Run(mode, func(t *testing.T) {
+ s := haSidecarService(t)
+ switch mode {
+ case "uncontained":
+ s.rt.DBPath = provision.DefaultDBPath(s.b.DataDir, s.rt.Host)
+ case "unknown-lifetime":
+ s.b.Lifetimes = &provision.LifetimeIndex{}
+ s.b.Cfg.Record = nil
+ case "no-key":
+ s.b.EscrowKey = nil
+ case "unstamped-lock":
+ s.rt.HA = false
+ s.b.Lifetimes = &provision.LifetimeIndex{}
+ s.b.Cfg.Record = nil
+ putLockFor(t, s.b, s.rt, haAdoptMarker(t, "b", "i-b", haFixOf(s.b).lifetime, 5, false))
+ }
+ before := len(s.fx.Requests())
+ lockBefore := string(s.fx.LockBody(s.b.Cfg.hibernatePrefix(s.rt.Host)))
+ l, err := s.b.Acquire(context.Background(), s.rt)
+ if err == nil {
+ if l != nil {
+ _ = l.Release(context.Background())
+ }
+ t.Fatal("unsupported sidecar acquired")
+ }
+ if mode == "unstamped-lock" && string(s.fx.LockBody(s.b.Cfg.hibernatePrefix(s.rt.Host))) != lockBefore {
+ t.Fatal("unstamped lock changed")
+ }
+ for _, r := range s.fx.Requests()[before:] {
+ if mode != "unstamped-lock" && (strings.HasPrefix(r, "PUT ") || strings.HasPrefix(r, "DELETE ")) {
+ t.Fatalf("refusal wrote %s", r)
+ }
+ }
+ })
+ }
+}
+
+func TestSidecarHADutyLifecycleProducer(t *testing.T) {
+ s := haSidecarService(t)
+ err := s.a.WithDuty(t.Context(), s.rt, func(context.Context) error {
+ if !s.a.HoldsAwake(s.rt.Host) {
+ t.Error("producer ran without worker lease")
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestSidecarHARefusalsEnvironment(t *testing.T) {
+ s := haSidecarService(t)
+ extra := workerEnv("/unused", s.rt.Host, "token")
+ extra["CARLOS_INSTANCE_KEY"] = "override"
+ before := len(s.fx.Requests())
+ if _, err := s.b.startHAWorker(t.Context(), s.rt, extra, release.StagedIdentity{}, []string{"work"}); err == nil {
+ t.Fatal("unpublished secret override accepted")
+ }
+ if len(s.fx.Requests()) != before {
+ t.Fatal("bad environment touched the store")
+ }
+}
+
+func TestSidecarHADutyLifecycleCrash(t *testing.T) {
+ for _, code := range []string{"0", "1"} {
+ t.Run(code, func(t *testing.T) {
+ s := haSidecarService(t)
+ if err := s.a.WakeWorker(s.rt); err != nil {
+ t.Fatal(err)
+ }
+ s.a.mu.Lock()
+ e := s.a.entries[s.rt.Host]
+ p := e.proc.(*unitProc)
+ s.a.mu.Unlock()
+ raw, _ := json.Marshal(instancectl.ExitRecord{Invocation: p.invocation, Code: "exited", Status: code})
+ if err := os.WriteFile(filepath.Join(p.runDir, p.recordName()), raw, 0o600); err != nil {
+ t.Fatal(err)
+ }
+ s.unit.stopped()
+ waitFor(t, "worker exit", p.Exited)
+ if got := procCrashed(p); got != (code != "0") {
+ t.Fatalf("crashed=%v for exit %s", got, code)
+ }
+ })
+ }
+}
diff --git a/internal/activator/unitproc.go b/internal/activator/unitproc.go
index 1ce55bd80..33dead22c 100644
--- a/internal/activator/unitproc.go
+++ b/internal/activator/unitproc.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"log"
"os"
"path/filepath"
@@ -41,13 +42,14 @@ type unitProc struct {
runDir string
// gen is the generation of a carlos-instance-gen@ unit, 0 for the
// original templates; dataDir holds its launch file.
- gen uint64
- dataDir string
- ctl *edge.ControlListener
- logs *logListener
- exited atomic.Bool
- done chan struct{}
- closeOnce atomic.Bool
+ gen uint64
+ dataDir string
+ ctl *edge.ControlListener
+ logs *logListener
+ extraListeners []io.Closer
+ exited atomic.Bool
+ done chan struct{}
+ closeOnce atomic.Bool
// listenersArmed guards the done-watcher goroutine Stop's ctx.Done
// branch starts: several callers bound their wait on Stop shorter than
// the unit may actually take to die (a sidecar co-stop, a discarded
@@ -135,13 +137,13 @@ func (b *ExecBackend) newUnitProc(rt registry.Route, role instancectl.Role, p in
// (unitNameFor: a rootfs row's is the rootfs template's). A role with no
// unit of the row's kind (a worker, rootfs apps plan 2) is refused before
// anything watches "".
-func (b *ExecBackend) newUnitProcFor(rt registry.Route, role instancectl.Role, gen uint64, p instancePaths, inv string, ctl *edge.ControlListener, logs *logListener) (*unitProc, error) {
+func (b *ExecBackend) newUnitProcFor(rt registry.Route, role instancectl.Role, gen uint64, p instancePaths, inv string, ctl *edge.ControlListener, logs *logListener, extra ...io.Closer) (*unitProc, error) {
unit := unitNameFor(rt, role, gen)
if unit == "" {
return nil, fmt.Errorf("%s: role %s has no unit to observe", rt.Host, role)
}
up := &unitProc{b: b, rt: rt, role: role, gen: gen, unit: unit, slice: instancectl.SliceName(rt.Host),
- invocation: inv, runDir: p.runDir, dataDir: p.dataDir, ctl: ctl, logs: logs, done: make(chan struct{})}
+ invocation: inv, runDir: p.runDir, dataDir: p.dataDir, ctl: ctl, logs: logs, extraListeners: extra, done: make(chan struct{})}
go b.observe(up)
return up, nil
}
@@ -347,6 +349,9 @@ func (p *unitProc) closeListeners() {
if p.logs != nil {
p.logs.Close()
}
+ for _, l := range p.extraListeners {
+ _ = l.Close()
+ }
p.listenersClosed.Store(true)
}
@@ -472,6 +477,9 @@ func (b *ExecBackend) observe(p *unitProc) {
if ok && rec.Code == "" {
rec = b.unitMainExitOf(p, rec)
}
+ if p.rt.IsSidecar() {
+ p.workerExit, p.workerExitOK = rec, ok
+ }
if p.worker != "" {
// A worker's end is the supervisor's to tell (W1b):
// the record is kept for it, never worded here.
@@ -696,3 +704,13 @@ func (b *ExecBackend) cgroupRoot() string {
}
return "/sys/fs/cgroup"
}
+
+// Crashed preserves native worker supervision after a proven unit exit.
+func (p *unitProc) Crashed() bool {
+ if !p.rt.IsSidecar() || p.stopRequested.Load() || !p.Exited() {
+ return false
+ }
+ <-p.done
+ code, known := workerExitStatus(p)
+ return known && code != 0
+}
diff --git a/internal/console/apisidecars.go b/internal/console/apisidecars.go
index 01ea95ea2..2377b5796 100644
--- a/internal/console/apisidecars.go
+++ b/internal/console/apisidecars.go
@@ -344,6 +344,11 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
// The shape rails, at the door — the same door the box's reconcile pass
// re-checks them at, because neither side trusts the other about what is
// in the bucket. The message is ValidateSidecarShape's own.
+ rec.HA = s.haRegion(rec.Region)
+ if rec.HA && !m.HibernateOrDefault() {
+ jsonError(w, http.StatusBadRequest, "high availability sidecars must allow hibernation")
+ return
+ }
if err := provision.ValidateSidecarShape(rec); err != nil {
jsonError(w, http.StatusBadRequest, err.Error())
return
@@ -401,6 +406,7 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
// is derived from its name, so a name reused after a delete lands on the
// deleted sidecar's replica. Refused, after every validation above.
if ref := s.leftoverReplicaRefusal(r.Context(), leftoverCreate{
+ HAData: rec.HA, sidecar: true,
logTag: "api sidecars create " + acct.Sqid + "/" + app,
host: rec.Host, region: region, pool: rec.Pool,
exists: func(ctx context.Context) (bool, error) {
@@ -419,7 +425,7 @@ func (s *Server) handleAPISidecarCreate(w http.ResponseWriter, r *http.Request)
jsonError(w, ref.Status, ref.Msg)
return
}
- if ref := s.requireHACreateCapacity(ctx, region, rec.Pool); ref != nil {
+ if ref := s.requireHACreateCapacity(ctx, region, rec.Pool, provision.SidecarPlacement(rec, *m)); ref != nil {
setNoCapacityRetryAfter(w, ref)
jsonError(w, ref.Status, ref.Msg)
return
@@ -744,6 +750,19 @@ func (s *Server) handleAPISidecarEnable(w http.ResponseWriter, r *http.Request)
// for it above, and a manifest whose App disagreed with its own key would
// be a record family that lies about its identity.
m.Schema, m.App = 1, app
+ if !m.HibernateOrDefault() {
+ recs, err := provision.ListSidecarRecordsStrict(ctx, s.cfg.Releases, acct.Sqid, app)
+ if err != nil {
+ jsonError(w, http.StatusBadGateway, "could not read the sidecar")
+ return
+ }
+ for _, rec := range recs {
+ if rec.HA {
+ jsonError(w, http.StatusBadRequest, "high availability sidecars must allow hibernation")
+ return
+ }
+ }
+ }
if err := provision.PutSidecarManifestIfMatch(ctx, s.cfg.Releases, acct.Sqid, app, *m, etag); err != nil {
if errors.Is(err, release.ErrCASConflict) {
jsonError(w, http.StatusConflict,
diff --git a/internal/console/createleftovers.go b/internal/console/createleftovers.go
index ad12d788c..468e940e7 100644
--- a/internal/console/createleftovers.go
+++ b/internal/console/createleftovers.go
@@ -110,6 +110,7 @@ func anyLTXFile(ctx context.Context, rd replicaReader, level int) (bool, error)
// leftoverCreate is one create as the rail needs it.
type leftoverCreate struct {
+ sidecar bool
HAData bool // prospective plain HA socket, before stamping
logTag string // "api instances create <sqid>/<app>"
host, region, pool string
@@ -159,11 +160,15 @@ func (s *Server) leftoverReplicaRefusal(parent context.Context, c leftoverCreate
taken := c.taken
var held bool
if c.HAData {
+ kind := "instance"
+ if c.sidecar {
+ kind = "sidecar"
+ }
name := s.offlineName(c.region)
if s.homeRegionIn(c.region) != "" || c.pool != "" {
return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf("high availability data creation is not available yet in %s. use the console's home region without a pool.", name)}
}
- unsure = fmt.Sprintf("could not check this instance's data in %s. nothing was created. try again. persistent failures may require an operator to check home data access.", name)
+ unsure = fmt.Sprintf("could not check this %s's data in %s. nothing was created. try again. persistent failures may require an operator to check home data access.", kind, name)
if s.cfg.SeedData == nil || !s.leftoverCheckApplies(c.region, c.pool) {
return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: unsure}
}
@@ -174,12 +179,12 @@ func (s *Server) leftoverReplicaRefusal(parent context.Context, c leftoverCreate
return &doorRefusal{Status: http.StatusServiceUnavailable, Msg: unsure}
}
if class != "" {
- return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf("%s still holds %s from a deleted instance. choose another address, or ask an operator to purge it.", c.host, class)}
+ return &doorRefusal{Status: http.StatusConflict, Msg: fmt.Sprintf("%s still holds %s from a deleted %s. choose another address, or ask an operator to purge it.", c.host, class, kind)}
}
// The whole-prefix proof covered every instance level. Move staging
// remains a separate prefix and must still be checked at all levels.
held, err = s.replicaPrefixesHoldData(ctx, strings.TrimSuffix(activator.MovesPrefix(c.host), "/"))
- taken = fmt.Sprintf("%s still holds replica from a deleted instance. choose another address, or ask an operator to purge it.", c.host)
+ taken = fmt.Sprintf("%s still holds replica from a deleted %s. choose another address, or ask an operator to purge it.", c.host, kind)
} else {
held, err = s.hostHoldsReplicaData(ctx, c.host)
}
diff --git a/internal/console/ha_born_test.go b/internal/console/ha_born_test.go
index 5e68a0e6d..b94d6e568 100644
--- a/internal/console/ha_born_test.go
+++ b/internal/console/ha_born_test.go
@@ -84,8 +84,8 @@ func TestCreateStampsBornHA(t *testing.T) {
}
}
-// Seeds and sidecars are never stamped in P1a (G12), even in an HA region.
-func TestSeedsAndSidecarsAreNeverStampedHA(t *testing.T) {
+// Seed copies retain P1a behavior; B6 stamps only new native sidecars.
+func TestSeedsRemainLegacyAndSidecarsBornHA(t *testing.T) {
f := newFromFixture(t, 1)
f.fx.srv.cfg.HomeRegion = "ie"
f.fx.srv.cfg.HARegions = []string{"ie"}
@@ -103,20 +103,20 @@ func TestSeedsAndSidecarsAreNeverStampedHA(t *testing.T) {
}
fx, token := instanceFixture(t, "code-ha-sidecar")
- fx.srv.cfg.HomeRegion = "ie"
fx.srv.cfg.HARegions = []string{"ie"}
- createCapacityEvidence(t, fx.srv, "allow", func(m map[string]any) { m["named_pools"] = []string{"tito"} })
+ haEmptyHomeData(t, fx.srv)
+ createCapacityEvidence(t, fx.srv, "allow", nil)
m := titoSidecarManifest()
- m.Regions = nil
+ m.Regions, m.Pool = nil, ""
enableSidecars(t, fx, "titogo", m)
if c, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx, "bab", "titogo"), token, `{"name":"bot"}`); c != http.StatusCreated {
t.Fatalf("sidecar create = %d %s", c, out)
}
- for k, v := range bucketState(t, fx.rel) {
- if strings.Contains(k, "sidecar") && strings.Contains(v, `"ha"`) {
- t.Fatalf("%s carries an ha mark: %s", k, v)
- }
+ sidecar, err := provision.GetSidecarRecord(context.Background(), fx.rel, "bab", "titogo", "bot")
+ if err != nil || !sidecar.HA || sidecar.Region != "" {
+ t.Fatalf("sidecar birth = %+v, %v", sidecar, err)
}
+
}
func TestMoveDoorsRefuseHAHostBeforeAnyWrite(t *testing.T) {
diff --git a/internal/console/hacapacity.go b/internal/console/hacapacity.go
index 6a47ee716..9da297f15 100644
--- a/internal/console/hacapacity.go
+++ b/internal/console/hacapacity.go
@@ -15,6 +15,7 @@ import (
"github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/boxid"
+ "github.com/carlosframework/platform/internal/edgesfile"
"github.com/carlosframework/platform/internal/objstore"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/status"
@@ -276,8 +277,8 @@ func (o *HACapacityObservation) Regional(region string, now time.Time) HACapacit
// Decide takes a normalized placement code (the named home, not wire "") and
// the pool ("" means shared). It performs no I/O and grants no box authority.
-func (o *HACapacityObservation) Decide(region, pool string, now time.Time) HACapacityDecision {
- n, complete, onlyPools := o.project(region, pool, true, now)
+func (o *HACapacityObservation) Decide(region, pool string, now time.Time, sidecarPlacement ...string) HACapacityDecision {
+ n, complete, onlyPools := o.project(region, pool, true, now, sidecarPlacement...)
if n > 0 {
return HACapacityDecision{Kind: HACapacityAllow}
}
@@ -286,7 +287,7 @@ func (o *HACapacityObservation) Decide(region, pool string, now time.Time) HACap
}
return HACapacityDecision{Kind: HACapacityUnknown, MissingNamedPoolsOnly: onlyPools}
}
-func (o *HACapacityObservation) project(region, pool string, narrow bool, now time.Time) (count int, complete, onlyPools bool) {
+func (o *HACapacityObservation) project(region, pool string, narrow bool, now time.Time, sidecarPlacement ...string) (count int, complete, onlyPools bool) {
if !o.available(now) || !slices.Contains(o.config.universe, region) {
return 0, false, false
}
@@ -295,7 +296,11 @@ func (o *HACapacityObservation) project(region, pool string, narrow bool, now ti
for _, f := range o.files {
eligible, known, code := o.classify(f, region, now)
if eligible && narrow {
- eligible, known, code = haPool(f.fields, pool)
+ if len(sidecarPlacement) > 0 {
+ eligible, known, code = haSidecarPool(f.fields, pool, sidecarPlacement[0])
+ } else {
+ eligible, known, code = haPool(f.fields, pool)
+ }
}
if eligible {
count++
@@ -520,3 +525,28 @@ func haPool(fields haFields, pool string) (eligible, known bool, code string) {
}
return slices.Contains(pools, pool), true, ""
}
+
+func haSidecarPool(fields haFields, pool, placement string) (bool, bool, string) {
+ pools, known := edgesfile.PoolEvidence(fields["served_pools"]).Pools()
+ if !known {
+ return false, false, "served_pools_unknown"
+ }
+ if !slices.Contains(pools, pool) {
+ return false, true, "pool_excluded"
+ }
+ switch placement {
+ case provision.PlacementAny:
+ return true, true, ""
+ case provision.PlacementNoInbound:
+ inbound, known := haField[bool](fields, "accepts_inbound")
+ if !known {
+ return false, false, "inbound_unknown"
+ }
+ if inbound {
+ return false, true, "inbound_excluded"
+ }
+ return true, true, ""
+ default:
+ return false, false, "sidecar_placement_unknown"
+ }
+}
diff --git a/internal/console/hacreatecapacity_test.go b/internal/console/hacreatecapacity_test.go
index 2bf99d825..fb7db0964 100644
--- a/internal/console/hacreatecapacity_test.go
+++ b/internal/console/hacreatecapacity_test.go
@@ -48,6 +48,7 @@ func createCapacityEvidence(t *testing.T, s *Server, evidence string, edit func(
haPut(t, store, "control/edges/leo.json", haEdit(t, haGolden(t), func(m map[string]any) {
m["generation"] = now.Format(time.RFC3339Nano)
m["serves_shared_pool"] = true
+ m["served_pools"] = []string{"", "hapair", "cohort1"}
if target != "ie" {
m["placement"] = target
}
@@ -182,8 +183,8 @@ func TestHACreateCapacityDoors(t *testing.T) {
t.Fatal(err)
}
b, _ := json.Marshal(rec)
- if strings.Contains(string(b), `"ha":true`) {
- t.Fatal("sidecar stamped HA")
+ if !strings.Contains(string(b), `"ha":true`) {
+ t.Fatal("sidecar missing birth HA stamp")
}
}
return
@@ -383,6 +384,18 @@ func TestHACreateCapacityNamedPools(t *testing.T) {
f.fx.srv.cfg.Releases = control
local := capacityLocalWrites(t, f.fx)
code, hdr, body := f.request(t, door)
+ if door == "sidecar" {
+ if code != 409 || !strings.Contains(errorText(body), "without a pool") {
+ t.Fatalf("HA sidecar data scope: %d %s", code, body)
+ }
+ if n, _ := control.counts(); n != 0 {
+ t.Fatalf("refused sidecar wrote %d", n)
+ }
+ local()
+ expectPages(t, pages)
+ return
+ }
+
switch scenario {
case "new", "mixed-positive":
if code != 201 {
diff --git a/internal/console/hap2_wiring_test.go b/internal/console/hap2_wiring_test.go
index 3c315c1ef..b38496ab2 100644
--- a/internal/console/hap2_wiring_test.go
+++ b/internal/console/hap2_wiring_test.go
@@ -519,7 +519,6 @@ func TestHAP2RequestBudget(t *testing.T) {
m.Pool = ""
m.Regions = nil
enableSidecars(t, fx.consoleFixture, "titogo", m)
- proof = false
case "object":
keys = []string{"instances/" + host + "/lock.json"}
wantStatus, levels = 409, 0
@@ -582,8 +581,8 @@ func TestHAP2RequestBudget(t *testing.T) {
if err := json.Unmarshal(raw, &fields); err != nil {
t.Fatal(err)
}
- if fields["ha"] != nil {
- t.Error("standalone sidecar was stamped HA")
+ if string(fields["ha"]) != "true" {
+ t.Error("standalone sidecar is missing its HA birth stamp")
}
} else {
rec, err := provision.GetRecord(context.Background(), fx.rel, "bab", "titogo", host)
@@ -635,7 +634,7 @@ func TestHAP2RequestBudget(t *testing.T) {
want = append(want, "instances/"+host+"/")
}
}
- if mode == "legacy" || mode == "sidecar" {
+ if mode == "legacy" {
for level := 0; level < 10; level++ {
want = append(want, fmt.Sprintf("instances/%s/%04x/", host, level))
}
diff --git a/internal/console/nocapacity.go b/internal/console/nocapacity.go
index b8f57385b..3c6869719 100644
--- a/internal/console/nocapacity.go
+++ b/internal/console/nocapacity.go
@@ -45,14 +45,14 @@ const haCapacityPoolRefusal = "Capacity for pool %s in %s could not be checked.
// requireHACreateCapacity reads the shared observation before a new create's
// first mutation. It selects no executor and grants no runtime authority.
-func (s *Server) requireHACreateCapacity(ctx context.Context, region, pool string) *doorRefusal {
+func (s *Server) requireHACreateCapacity(ctx context.Context, region, pool string, sidecarPlacement ...string) *doorRefusal {
if !s.haRegion(region) {
return nil
}
name := s.homeRegionOut(region)
decision := HACapacityDecision{Kind: HACapacityUnknown}
if obs, available := s.HACapacity(); available {
- decision = obs.Decide(name, pool, s.haCapacity.Load().clock.Now())
+ decision = obs.Decide(name, pool, s.haCapacity.Load().clock.Now(), sidecarPlacement...)
}
switch decision.Kind {
case HACapacityAllow:
diff --git a/internal/console/sidecar_ha_test.go b/internal/console/sidecar_ha_test.go
new file mode 100644
index 000000000..695d2a96a
--- /dev/null
+++ b/internal/console/sidecar_ha_test.go
@@ -0,0 +1,135 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/provision"
+ "net/http"
+ "testing"
+)
+
+func TestSidecarHABirthOnly(t *testing.T) {
+ for _, region := range []string{"", "ie"} {
+ t.Run("home-"+region, func(t *testing.T) {
+ 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"}})
+ code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot","region":"`+region+`"}`)
+ if code != 201 {
+ t.Fatalf("create %d %s", code, out)
+ }
+ raw, _, err := fx.rel.Get(context.Background(), provision.SidecarRecordKey("bab", "titogo", "bot"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var rec map[string]any
+ _ = json.Unmarshal(raw, &rec)
+ if rec["ha"] != true || rec["region"] != nil && rec["region"] != "" {
+ t.Fatalf("birth stamp: %s", raw)
+ }
+ })
+ }
+ t.Run("enable preserves legacy", func(t *testing.T) {
+ fx := haCreateHome(t)
+ createCapacityEvidence(t, fx.srv, "allow", func(m map[string]any) { m["served_pools"] = []string{""} })
+ fx.srv.cfg.HARegions = nil
+ enableSidecars(t, fx.consoleFixture, "titogo", provision.SidecarManifest{Schema: 1, App: "titogo", Args: []string{"work"}})
+ code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot"}`)
+ if code != 201 {
+ t.Fatalf("legacy %d %s", code, out)
+ }
+ key := provision.SidecarRecordKey("bab", "titogo", "bot")
+ before, _, _ := fx.rel.Get(context.Background(), key)
+ fx.srv.cfg.HARegions = []string{"ie"}
+ code, _, out = rawReq(t, http.MethodPut, sidecarEnableURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"args":["work"]}`)
+ if code != 200 {
+ t.Fatalf("enable %d %s", code, out)
+ }
+ after, _, _ := fx.rel.Get(context.Background(), key)
+ if string(before) != string(after) {
+ t.Fatal("enable migrated record")
+ }
+ var rec map[string]any
+ _ = json.Unmarshal(after, &rec)
+ if _, ok := rec["ha"]; ok {
+ t.Fatal("legacy has stamp")
+ }
+ })
+}
+
+func TestSidecarHARefusals(t *testing.T) {
+ for _, mode := range []string{"no-hibernate", "pool", "remote", "files", "lock", "unknown-data", "no-capacity"} {
+ t.Run(mode, func(t *testing.T) {
+ fx := haCreateHome(t)
+ createCapacityEvidence(t, fx.srv, "allow", func(m map[string]any) { m["served_pools"] = []string{""} })
+ m := provision.SidecarManifest{Schema: 1, App: "titogo", Args: []string{"work"}}
+ region := ""
+ want := 409
+ switch mode {
+ case "no-hibernate":
+ v := false
+ m.Hibernate = &v
+ want = 400
+ case "pool":
+ m.Pool = "hapair"
+ case "remote":
+ region = "uk"
+ fx.srv.cfg.HARegions = append(fx.srv.cfg.HARegions, "uk")
+ case "unknown-data":
+ fx.srv.cfg.SeedData = nil
+ want = 503
+ case "no-capacity":
+ createCapacityEvidence(t, fx.srv, "zero", func(m map[string]any) { m["served_pools"] = []string{""} })
+ want = 503
+ default:
+ key := activator.HibernatePrefix(fx.srv.cfg.HibernatePrefix, botHost) + "/lock.json"
+ if mode == "files" {
+ key = activator.HibernatePrefix(fx.srv.cfg.HibernatePrefix, botHost) + "/files/0/manifest.json"
+ }
+ if _, err := fx.srv.cfg.SeedData.Put(context.Background(), key, []byte("old"), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ enableSidecars(t, fx.consoleFixture, "titogo", m)
+ control := &haCreateStore{Store: fx.srv.cfg.Releases}
+ fx.srv.cfg.Releases = control
+ code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot","region":"`+region+`"}`)
+ if code != want {
+ t.Errorf("%s got %d %s want %d", mode, code, out, want)
+ }
+ if n, _ := control.counts(); n != 0 {
+ t.Errorf("refusal attempted %d writes", n)
+ }
+ })
+ }
+}
+
+func TestSidecarHABirthOnlyPlacement(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ placement string
+ edit func(map[string]any)
+ want int
+ }{
+ {"no-inbound", provision.PlacementNoInbound, func(m map[string]any) { m["accepts_inbound"] = false }, 201},
+ {"inbound-refused", provision.PlacementNoInbound, func(m map[string]any) { m["accepts_inbound"] = true }, 503},
+ {"unknown-pools", provision.PlacementAny, func(m map[string]any) { delete(m, "served_pools") }, 503},
+ {"null-pools", provision.PlacementAny, func(m map[string]any) { m["served_pools"] = nil }, 503},
+ {"malformed-pools", provision.PlacementAny, func(m map[string]any) { m["served_pools"] = []any{nil} }, 503},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ fx := haCreateHome(t)
+ enableSidecars(t, fx.consoleFixture, "titogo", provision.SidecarManifest{Schema: 1, App: "titogo", Placement: tc.placement, Args: []string{"work"}})
+ createCapacityEvidence(t, fx.srv, "allow", func(m map[string]any) { m["served_pools"] = []string{""}; tc.edit(m) })
+ control, data := haCreateTrack(fx)
+ code, _, out := rawReq(t, http.MethodPost, sidecarsURL(fx.consoleFixture, "bab", "titogo"), fx.token, `{"name":"bot"}`)
+ if code != tc.want {
+ t.Fatalf("create %d %s want %d", code, out, tc.want)
+ }
+ if tc.want != 201 {
+ haCreateNoWrites(t, control, data)
+ }
+ })
+ }
+}
diff --git a/internal/edge/homemap.go b/internal/edge/homemap.go
index 3730c65f9..6643074d5 100644
--- a/internal/edge/homemap.go
+++ b/internal/edge/homemap.go
@@ -134,11 +134,13 @@ var (
// decoder ignores, which is the point.
type edgesFileView struct {
edgesfile.AdmissionFields
- etag string
- V int `json:"v"`
- Box string `json:"box"`
- EIP string `json:"eip"`
- Hosts map[string]edgesHostView `json:"hosts"`
+ ServedPools edgesfile.PoolEvidence `json:"served_pools"`
+ AcceptsInbound json.RawMessage `json:"accepts_inbound"`
+ etag string
+ V int `json:"v"`
+ Box string `json:"box"`
+ EIP string `json:"eip"`
+ Hosts map[string]edgesHostView `json:"hosts"`
// PrivateIP, PrivateCIDR, Region and Placement choose the dial address
// (region HA spec 2 §6, edgesfile.Reader.Dial). All are absent from a writer that
// predates them, and the dial is then EIP, as before.
diff --git a/internal/edge/sidecar_ha_test.go b/internal/edge/sidecar_ha_test.go
new file mode 100644
index 000000000..b37214a27
--- /dev/null
+++ b/internal/edge/sidecar_ha_test.go
@@ -0,0 +1,129 @@
+package edge
+
+import (
+ "bytes"
+ "crypto/sha256"
+ "fmt"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "reflect"
+ "testing"
+)
+
+func TestSidecarDutyPoolProjection(t *testing.T) {
+ rt := registry.Route{Host: "bot.shop.bab.sidecar.internal", Account: "bab", App: "shop", Kind: provision.SidecarKind, Provisioned: true, HA: true, Pool: "hapair"}
+ file := func(ref string, pools any) map[string]any {
+ f := wakeFile(ref)
+ delete(f, "placement")
+ f["hosts"] = map[string]any{}
+ f["served_pools"] = pools
+ f["accepts_inbound"] = true
+ return f
+ }
+ for _, tc := range []struct {
+ name string
+ pools any
+ want bool
+ }{
+ {"named", []string{"hapair"}, true}, {"shared-only", []string{""}, false}, {"empty", []string{}, false}, {"null", nil, false}, {"absent", "absent", false}, {"wrong-type", 12, false}, {"null-entry", []any{nil, "hapair"}, false}, {"space", []string{" hapair"}, false}, {"case", []string{"HAPAIR"}, false}, {"duplicate", []string{"hapair", "hapair"}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ peer := file("peer", tc.pools)
+ if tc.name == "absent" {
+ delete(peer, "served_pools")
+ }
+ m := wakeMap(t, file("self", []string{"", "hapair"}), peer)
+ snap := m.dutySnapshot(rt, wakeNow, provision.PlacementAny)
+ want := []string{"self"}
+ if tc.want {
+ want = []string{"peer", "self"}
+ }
+ if !snap.Usable || !reflect.DeepEqual(wakeRefs(snap), want) {
+ t.Fatalf("projection %+v want %v", snap, want)
+ }
+ if len(m.Hosts()) != 0 || len(m.ServedHosts()) != 0 {
+ t.Fatal("synthetic public host")
+ }
+ })
+ }
+}
+
+func TestSidecarDutyPoolProjectionPlacement(t *testing.T) {
+ rt := registry.Route{Host: "bot.shop.bab.sidecar.internal", Account: "bab", App: "shop", Kind: provision.SidecarKind, Provisioned: true, HA: true}
+ file := func(ref string) map[string]any {
+ f := wakeFile(ref)
+ f["hosts"] = map[string]any{}
+ delete(f, "placement")
+ f["served_pools"] = []string{""}
+ return f
+ }
+ for _, tc := range []struct {
+ name string
+ value any
+ present bool
+ want bool
+ }{
+ {"no-inbound", false, true, true}, {"inbound", true, true, false}, {"unknown", nil, false, false}, {"null", nil, true, false}, {"malformed", "false", true, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ self, peer := file("self"), file("peer")
+ self["accepts_inbound"] = false
+ if tc.present {
+ peer["accepts_inbound"] = tc.value
+ }
+ m := wakeMap(t, self, peer)
+ s := m.dutySnapshot(rt, wakeNow, provision.PlacementNoInbound)
+ want := []string{"self"}
+ if tc.want {
+ want = []string{"peer", "self"}
+ }
+ if !reflect.DeepEqual(wakeRefs(s), want) {
+ t.Fatalf("%v want %v", wakeRefs(s), want)
+ }
+ })
+ }
+ for _, field := range []string{"served_pools", "placement", "box_role"} {
+ t.Run("local-refusal-"+field, func(t *testing.T) {
+ self := file("self")
+ self["accepts_inbound"] = false
+ if field == "served_pools" {
+ delete(self, field)
+ } else if field == "box_role" {
+ self[field] = "booting"
+ } else {
+ self[field] = nil
+ }
+ if !wakeMap(t, self).dutySnapshot(rt, wakeNow, provision.PlacementAny).LocalDenied {
+ t.Fatal("unknown or excluded local policy allowed duty")
+ }
+ })
+ }
+}
+
+func TestSidecarDutyPoolProjectionRawWinner(t *testing.T) {
+ rt := registry.Route{Host: "never.shop.bab.sidecar.internal", Account: "bab", App: "shop", Kind: provision.SidecarKind, Provisioned: true, HA: true, Pool: "hapair"}
+ ownScore := sha256.Sum256([]byte(rt.Host + "\x00self"))
+ peer := ""
+ for n := 0; n < 10000; n++ {
+ ref := fmt.Sprintf("shared%d", n)
+ score := sha256.Sum256([]byte(rt.Host + "\x00" + ref))
+ if bytes.Compare(score[:], ownScore[:]) > 0 {
+ peer = ref
+ break
+ }
+ }
+ if peer == "" {
+ t.Fatal("no raw winner found")
+ }
+ own, other := wakeFile("self"), wakeFile(peer)
+ for _, f := range []map[string]any{own, other} {
+ delete(f, "placement")
+ f["hosts"] = map[string]any{}
+ }
+ own["served_pools"] = []string{"hapair"}
+ other["served_pools"] = []string{""}
+ got := wakeMap(t, own, other).dutySnapshot(rt, wakeNow, provision.PlacementAny)
+ if !reflect.DeepEqual(wakeRefs(got), []string{"self"}) {
+ t.Fatalf("raw shared winner entered HRW: %+v", got)
+ }
+}
diff --git a/internal/edge/wakeplacement.go b/internal/edge/wakeplacement.go
index c0d606326..51d127559 100644
--- a/internal/edge/wakeplacement.go
+++ b/internal/edge/wakeplacement.go
@@ -8,6 +8,7 @@ import (
"github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -101,7 +102,11 @@ func (p wakePlacementFields) candidate(f edgesFileView) boxchoice.Candidate {
// wakeSnapshot projects one immutable fold for a local route. No membership,
// registry or signing-key reads are made on the request path.
func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeSnapshot {
- var out boxchoice.WakeSnapshot
+ return m.dutySnapshot(rt, now, "")
+}
+
+func (m *homeMap) dutySnapshot(rt registry.Route, now time.Time, sidecarPlacement string) boxchoice.WakeSnapshot {
+ out := boxchoice.WakeSnapshot{LocalDenied: rt.IsSidecar()}
if m == nil {
return out
}
@@ -128,6 +133,9 @@ func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeS
}
p := decodeWakePlacement(own)
out.LocalDenied = p.localDenied
+ if rt.IsSidecar() {
+ out.LocalDenied = out.LocalDenied || !sidecarBoxEligible(own, rt, sidecarPlacement)
+ }
out.Region = own.Region
// Missing identity declines toward Base. An empty placement is not missing
// identity: it is the home region's placement scope (CARLOS_REGION unset,
@@ -166,7 +174,11 @@ func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeS
if fields.localDenied {
continue
}
- if ref != m.self {
+ if rt.IsSidecar() {
+ if !sidecarBoxEligible(f, rt, sidecarPlacement) {
+ continue
+ }
+ } else if ref != m.self {
if !hasKey || reader.Dial(f.dialPoint()) == "" {
continue
}
@@ -187,3 +199,22 @@ func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeS
func (e *Edge) DutySnapshot(rt registry.Route) boxchoice.WakeSnapshot {
return e.homes.Load().wakeSnapshot(rt, time.Now())
}
+
+func sidecarBoxEligible(f edgesFileView, rt registry.Route, placement string) bool {
+ if !rt.Provisioned || !rt.HA || rt.Socket != "" || rt.Addr != "" || rt.Tunnel != "" || rt.Replica || rt.Region != f.Placement || f.placementNull || !provision.ValidSidecarHost(rt.Host, rt.App, rt.Account) || !f.ServedPools.Serves(rt.Pool) {
+ return false
+ }
+ switch placement {
+ case provision.PlacementAny:
+ return true
+ case provision.PlacementNoInbound:
+ var inbound bool
+ return len(f.AcceptsInbound) > 0 && placementField(f.AcceptsInbound, &inbound) && !inbound
+ default:
+ return false
+ }
+}
+
+func (e *Edge) SidecarDutySnapshot(rt registry.Route, placement string) boxchoice.WakeSnapshot {
+ return e.homes.Load().dutySnapshot(rt, time.Now(), placement)
+}
diff --git a/internal/edgesfile/servedpools.go b/internal/edgesfile/servedpools.go
new file mode 100644
index 000000000..a00bc6664
--- /dev/null
+++ b/internal/edgesfile/servedpools.go
@@ -0,0 +1,53 @@
+package edgesfile
+
+import (
+ "bytes"
+ "encoding/json"
+ "slices"
+)
+
+// PoolEvidence preserves unknown and malformed membership without losing holder evidence.
+type PoolEvidence json.RawMessage
+
+func (p PoolEvidence) Pools() ([]string, bool) {
+ if len(p) == 0 || bytes.Equal(bytes.TrimSpace(p), []byte("null")) {
+ return nil, false
+ }
+ var raw []json.RawMessage
+ if json.Unmarshal(p, &raw) != nil || raw == nil {
+ return nil, false
+ }
+ out := make([]string, 0, len(raw))
+ for _, item := range raw {
+ var pool string
+ if bytes.Equal(bytes.TrimSpace(item), []byte("null")) || json.Unmarshal(item, &pool) != nil {
+ return nil, false
+ }
+ if len(pool) > 16 {
+ return nil, false
+ }
+ for _, c := range pool {
+ if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') {
+ return nil, false
+ }
+ }
+ if slices.Contains(out, pool) {
+ return nil, false
+ }
+ out = append(out, pool)
+ }
+ return out, true
+}
+
+func (p PoolEvidence) Serves(pool string) bool {
+ pools, known := p.Pools()
+ return known && slices.Contains(pools, pool)
+}
+
+func (p *PoolEvidence) UnmarshalJSON(raw []byte) error { *p = append((*p)[:0], raw...); return nil }
+func (p PoolEvidence) MarshalJSON() ([]byte, error) {
+ if len(p) == 0 {
+ return []byte("null"), nil
+ }
+ return p, nil
+}
diff --git a/internal/edgesfile/servedpools_test.go b/internal/edgesfile/servedpools_test.go
new file mode 100644
index 000000000..951376d39
--- /dev/null
+++ b/internal/edgesfile/servedpools_test.go
@@ -0,0 +1,33 @@
+package edgesfile
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+)
+
+func TestSidecarDutyPoolProjection(t *testing.T) {
+ for _, tc := range []struct {
+ raw string
+ want []string
+ known bool
+ }{
+ {`{}`, nil, false}, {`{"served_pools":null}`, nil, false},
+ {`{"served_pools":[]}`, []string{}, true}, {`{"served_pools":[""]}`, []string{""}, true},
+ {`{"served_pools":["","hapair"]}`, []string{"", "hapair"}, true},
+ {`{"served_pools":[null]}`, nil, false}, {`{"served_pools":["HAPAIR"]}`, nil, false},
+ {`{"served_pools":["hapair "]}`, nil, false}, {`{"served_pools":["",""]}`, nil, false},
+ {`{"served_pools":42}`, nil, false}, {`{"served_pools":["abcdefghijklmnopq"]}`, nil, false},
+ } {
+ t.Run(tc.raw, func(t *testing.T) {
+ var f PlacementView
+ if err := json.Unmarshal([]byte(tc.raw), &f); err != nil {
+ t.Fatal(err)
+ }
+ got, known := f.ServedPools.Pools()
+ if known != tc.known || !reflect.DeepEqual(got, tc.want) {
+ t.Fatalf("%v %v want %v %v", got, known, tc.want, tc.known)
+ }
+ })
+ }
+}
diff --git a/internal/edgesfile/snapshot.go b/internal/edgesfile/snapshot.go
index e721b32a7..56885908f 100644
--- a/internal/edgesfile/snapshot.go
+++ b/internal/edgesfile/snapshot.go
@@ -29,11 +29,12 @@ import (
// write home" (that is the home map's question, internal/edge).
type PlacementView struct {
AdmissionFields
- V int `json:"v"`
- Box string `json:"box"`
- EIP string `json:"eip"`
- Region string `json:"region"`
- Placement string `json:"placement"`
+ ServedPools PoolEvidence `json:"served_pools,omitempty"`
+ V int `json:"v"`
+ Box string `json:"box"`
+ EIP string `json:"eip"`
+ Region string `json:"region"`
+ Placement string `json:"placement"`
// PrivateIP and PrivateCIDR are the box's private address and its
// region network (region HA spec 2 §6), absent from a writer that
// predates them. Read only by the home election (ElectHomes), which
diff --git a/internal/host/agent.go b/internal/host/agent.go
index c8d4edd0c..d0f3d3ecf 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -183,6 +183,7 @@ import (
"github.com/carlosframework/platform/internal/apperr"
"github.com/carlosframework/platform/internal/applog"
"github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/caps"
"github.com/carlosframework/platform/internal/cgroup"
"github.com/carlosframework/platform/internal/controlsock"
@@ -1189,7 +1190,16 @@ func runAgent(args []string, buildClaims ClaimFactory) {
if act != nil {
act.SetHeldWakeHook(e.HeldWake)
if svc != nil {
- svc.SetDutyView(e.DutySnapshot)
+ svc.SetDutyView(func(rt registry.Route) boxchoice.WakeSnapshot {
+ if rt.IsSidecar() {
+ entry, ok := boxLifetimes.Lookup(rt.Host)
+ if !ok {
+ return boxchoice.WakeSnapshot{LocalDenied: true}
+ }
+ return e.SidecarDutySnapshot(rt, entry.SidecarPlacement)
+ }
+ return e.DutySnapshot(rt)
+ })
}
}
go tunnelLoop(e)
@@ -3890,6 +3900,26 @@ func haRecordFacts(open func(context.Context) (release.Store, error), judge *pro
store = s
}
mu.Unlock()
+ if rt.IsSidecar() {
+ if !provision.ValidSidecarHost(rt.Host, rt.App, release.RouteAccount(rt)) {
+ return activator.RecordFacts{}, errors.New("ha_sidecar_identity")
+ }
+ name, _, _ := strings.Cut(rt.Host, ".")
+ rec, err := provision.GetSidecarRecord(ctx, s, release.RouteAccount(rt), rt.App, name)
+ if err != nil {
+ return activator.RecordFacts{}, err
+ }
+ e, err := provision.SidecarLifetimeEntryOf(*rec)
+ if err != nil {
+ return activator.RecordFacts{}, err
+ }
+ m, err := provision.GetSidecarManifest(ctx, s, rec.Account, rec.App)
+ if err != nil {
+ return activator.RecordFacts{}, err
+ }
+ e.SidecarPlacement = provision.SidecarPlacement(*rec, *m)
+ return activator.RecordFacts{LifetimeEntry: e}, nil
+ }
rec, err := judgedRecord(ctx, s, judge, release.RouteAccount(rt), rt.App, rt.Host)
if err != nil {
return activator.RecordFacts{}, err
diff --git a/internal/host/edgesfile.go b/internal/host/edgesfile.go
index 07b75e09f..97c1894f2 100644
--- a/internal/host/edgesfile.go
+++ b/internal/host/edgesfile.go
@@ -332,9 +332,10 @@ type edgesFile struct {
// an AUTOMATIC choice of this box's region; explicit requests ignore
// them. Computed from the same ReconcileConfig the reconcile pass uses
// (edgesFileEligibility), never a second reading of the environment.
- ServesSharedPool bool `json:"serves_shared_pool"`
- AcceptsInbound bool `json:"accepts_inbound"`
- NamedPools []string `json:"named_pools"`
+ ServesSharedPool bool `json:"serves_shared_pool"`
+ AcceptsInbound bool `json:"accepts_inbound"`
+ NamedPools []string `json:"named_pools"`
+ ServedPools edgesfile.PoolEvidence `json:"served_pools,omitempty"`
// BurstNotices says this box's edge answers probe-burst notices itself
// (internal/edge burst_notice.go), so the other edges may send them
// here. Set by every pass of this build (edgesFileWriteClaims), never
@@ -1194,6 +1195,7 @@ func edgesFileLoop(reg *registry.Registry, lifetimes bool, assets *assetPolicy)
ServesSharedPool: sharedPool,
AcceptsInbound: inbound,
NamedPools: namedPools,
+ ServedPools: edgesFileServedPools(provisionTickConfig(os.Getenv)),
SecretsKeyFP: edgesFileSecretsFP(os.Getenv),
BoxID: box,
Capabilities: edgesFileCapabilities(os.Getenv),
@@ -1390,3 +1392,18 @@ func (s *edgesFileSchedule) done(now time.Time, ok bool) {
// that is a steady drip of bucket reads on every box, sitting ahead of the
// adopt leg inside a two-second convergence promise. See domains.ClaimCache.
var aliasClaimCache domains.ClaimCache
+
+func edgesFileServedPools(cfg provision.ReconcileConfig) edgesfile.PoolEvidence {
+ pools := make([]string, 0, len(cfg.Pools))
+ if len(cfg.Pools) == 0 {
+ pools = append(pools, "")
+ }
+ for _, p := range cfg.Pools {
+ if p == "" || provision.ValidPool(p) {
+ pools = append(pools, p)
+ }
+ }
+ slices.Sort(pools)
+ body, _ := json.Marshal(slices.Compact(pools))
+ return edgesfile.PoolEvidence(body)
+}
diff --git a/internal/host/group_names_test.go b/internal/host/group_names_test.go
index 63aa467fc..5b1c153ab 100644
--- a/internal/host/group_names_test.go
+++ b/internal/host/group_names_test.go
@@ -366,17 +366,20 @@ var groupNameProducerInventory = map[string]string{
"../edge/assetcatch.go:*Edge.serveAssetFar": "7d358ec272ae74c05764504550bad461096a09d0bfcc108dcbe5485f8f68d643",
// Demo protections wrap existing proxies and retain refusal-only names.
// They do not derive or publish a new group-name class.
- "../edge/edge.go:*Edge.Reload": "1030be6dfba6a0737bc47a41d465376a03e5b3cd552dbbdb9026a1c60151d1b2",
- "../edge/platformalias.go:PlatformAliasFold": "a18e4963cf88320ef3fb94b666b02838dc12cc3e9b2df3f2cbe2576ca682735f",
- "../edge/regional.go:*Edge.foldRegional": "b413fad6a8e17530ce0e99c79c521e0a6782b82c04d61d256442b8defe6a427b",
- "../provision/forward.go:forwardRowFor": "e7294d6a3c96e51646257200f5cedb26aaf491afea23be3d943b3e3f742c4db4",
- "../provision/reconcile.go:Reconcile": "d4b6447577c170d4d0999caced11931cdf13fef135da2c9a3331a5dda275c030",
- "../provision/reconcile.go:RouteFor": "cc7d8bccdf858e21d39f9b1275f7cf673a4ce8015b62bb7885d5cf52e28cb770",
- "../provision/reconcile.go:mintHeld": "9fe4ad876c727af36cc06bd0105baf344748c61e6f21ced48e5288a323851344",
- "../provision/seedreconcile.go:purgeAbortedFromLocal": "889e93e6fbd74adf614ba184bcd2f554196eccc4506829c65326a3502e98d89a",
- "../provision/seedrollback.go:removeOrphanedLocal": "6dd05836ac1d346de23ad555d50bb6c8fcd574cf05b6dfbf916eb0b220d88586",
- "../provision/sidecar_reconcile.go:ReconcileSidecars": "6dd1733236c4b2e2114f895b3f0c59cb4d6216d70dd43390a33cab637f887539",
- "../provision/sidecar_reconcile.go:sidecarRouteFor": "71f4f6298081b670a1bc6bfcb1f3f92cc1ceffc0960714caa0743b9519de0b13",
+ "../edge/edge.go:*Edge.Reload": "1030be6dfba6a0737bc47a41d465376a03e5b3cd552dbbdb9026a1c60151d1b2",
+ "../edge/platformalias.go:PlatformAliasFold": "a18e4963cf88320ef3fb94b666b02838dc12cc3e9b2df3f2cbe2576ca682735f",
+ "../edge/regional.go:*Edge.foldRegional": "b413fad6a8e17530ce0e99c79c521e0a6782b82c04d61d256442b8defe6a427b",
+ "../provision/forward.go:forwardRowFor": "e7294d6a3c96e51646257200f5cedb26aaf491afea23be3d943b3e3f742c4db4",
+ "../provision/reconcile.go:Reconcile": "d4b6447577c170d4d0999caced11931cdf13fef135da2c9a3331a5dda275c030",
+ "../provision/reconcile.go:RouteFor": "cc7d8bccdf858e21d39f9b1275f7cf673a4ce8015b62bb7885d5cf52e28cb770",
+ "../provision/reconcile.go:mintHeld": "9fe4ad876c727af36cc06bd0105baf344748c61e6f21ced48e5288a323851344",
+ "../provision/seedreconcile.go:purgeAbortedFromLocal": "889e93e6fbd74adf614ba184bcd2f554196eccc4506829c65326a3502e98d89a",
+ "../provision/seedrollback.go:removeOrphanedLocal": "6dd05836ac1d346de23ad555d50bb6c8fcd574cf05b6dfbf916eb0b220d88586",
+ // B6 retains the synthetic sidecar name and Kind. HA affects lifetime and
+ // nested DB paths only; TestSidecarNeverAdvertisedOrDialled exercises the
+ // real stamped record/reconcile/publication path as well as the legacy row.
+ "../provision/sidecar_reconcile.go:ReconcileSidecars": "36b82e9b7ce96372c51f8b88c57a3118ad2da0f1ea0999a9449c29d91023f196",
+ "../provision/sidecar_reconcile.go:sidecarRouteFor": "c8cc26bdb7a0aff550219b1c095fd0289392620465b659cd29e5ef4e7895028a",
"claimretire_transport.go:ClaimRootHTTP.retire": "a60c74d0e0461e0a432f9a338aa25799cc0cd9d163c7b6eb803cfb33d55d7c2a",
"claimunit_binding.go:claimUnitShape.route": "f38fd6e10aba680354ee908c255fd34e731fe2d1a22fffd41ac449e8b763dd2c",
"claimunit_policy.go:claimUnitShapeCheck": "45f16830e5ed834995ca573a710f1e390a504b7eb78c3c0465ac70e7f306e50c",
diff --git a/internal/host/hadepartures.go b/internal/host/hadepartures.go
index 12c4424fd..4191ebee4 100644
--- a/internal/host/hadepartures.go
+++ b/internal/host/hadepartures.go
@@ -25,15 +25,21 @@ import (
var errDepartureScope = errors.New("ha_departure_scope_invalid")
type LocalPolicy struct {
- Scope hadeparture.Scope
- Pools []string
- Denied bool
+ Scope hadeparture.Scope
+ Pools []string
+ Denied bool
+ Inbound string
}
func CanAdopt(h provision.DepartureHost, p LocalPolicy) bool {
- if p.Denied || h.Kind != "instance" || !h.HA || h.Lifetime == "" || h.Placement != p.Scope.Placement {
+ if p.Denied || (h.Kind != "instance" && h.Kind != provision.SidecarKind) || !h.HA || h.Lifetime == "" || h.Placement != p.Scope.Placement {
return false
}
+ if h.Kind == provision.SidecarKind {
+ if h.SidecarPlacement != provision.PlacementAny && !(h.SidecarPlacement == provision.PlacementNoInbound && p.Inbound == provision.InboundNone) {
+ return false
+ }
+ }
if len(p.Pools) == 0 {
return h.Pool == ""
}
diff --git a/internal/host/hadepartures_wiring.go b/internal/host/hadepartures_wiring.go
index c1c9a8230..33c804083 100644
--- a/internal/host/hadepartures_wiring.go
+++ b/internal/host/hadepartures_wiring.go
@@ -111,18 +111,18 @@ func armHADepartures(ctx context.Context, a departureArm) (*Controller, hadepart
}
}
c, err := NewController(DepartureConfig{Admitted: a.Admitted, BeginWork: a.BeginWork, Registry: a.Registry, OpenStore: a.OpenStore, NewReader: defaultDepartureReader, Prefix: func(host string) string { return activator.HibernatePrefix(a.Backend.Cfg.Prefix, host) }, Identities: repo, Confirmer: a.Confirmer, Cache: cache, ProofStore: a.ProofStore, Self: a.Self, DeploymentBucket: a.Getenv("CARLOS_DEPLOYMENT_BUCKET"), Inventory: func() provision.InventorySnapshot { return departureInventorySnapshot(a.Inventory) }, Policy: func() LocalPolicy {
- return LocalPolicy{Scope: a.Self.Scope, Pools: provision.ParseBoxPools(a.Getenv("CARLOS_POOLS"))}
+ return LocalPolicy{Scope: a.Self.Scope, Pools: provisionTickConfig(a.Getenv).Pools, Inbound: provisionTickConfig(a.Getenv).Inbound}
}, Invalidate: a.Service.InvalidateDutyHolder, PageIdentity: func(ctx context.Context, h registry.HAPendingTermination, code string) error {
return PageOperator(ctx, alerting.LevelWarning, "ha_departure_pending", fmt.Sprintf("code=%s account=%s region=%s iid=%s", code, h.Account, h.Region, h.IID))
}, Page: func(ctx context.Context, d registry.HADeparture, hosts []provision.DepartureHost) error {
messages := []string{fmt.Sprintf("Duties from box %s have not been recovered. The scan will retry automatically. Check the box's wake state before removing its records.", d.Box.Ref)}
for _, h := range hosts {
- if h.Kind != "sidecar" {
+ if h.Kind != "sidecar" || h.HA {
if h.Placement != a.Self.Scope.Placement {
messages = append(messages, fmt.Sprintf("host=%s code=placement", h.Host))
continue
}
- policy := LocalPolicy{Scope: a.Self.Scope, Pools: provision.ParseBoxPools(a.Getenv("CARLOS_POOLS"))}
+ policy := LocalPolicy{Scope: a.Self.Scope, Pools: provisionTickConfig(a.Getenv).Pools, Inbound: provisionTickConfig(a.Getenv).Inbound}
if CanAdopt(h, policy) {
messages = append(messages, fmt.Sprintf("host=%s code=unsupported_wake", h.Host))
continue
diff --git a/internal/host/sidecar_ha_test.go b/internal/host/sidecar_ha_test.go
new file mode 100644
index 000000000..190334666
--- /dev/null
+++ b/internal/host/sidecar_ha_test.go
@@ -0,0 +1,240 @@
+package host
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/edgesfile"
+ "github.com/carlosframework/platform/internal/hadeparture"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/hostfiles"
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/lease/locktest"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func sidecarHARecords(t *testing.T, st release.Store, reg *registry.Registry, data string, cfg provision.ReconcileConfig) provision.InventorySnapshot {
+ t.Helper()
+ ctx := t.Context()
+ raw := []byte(`{"id":2,"sqid":"bac","name":"Shop","created_at":"2026-10-26T09:00:00Z"}`)
+ if _, err := st.Put(ctx, "accounts/bac/account.json", raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ for _, app := range []string{"shop", "legacy"} {
+ if err := provision.PutSidecarManifest(ctx, st, "bac", app, provision.SidecarManifest{Schema: 1, App: app, Args: []string{"work"}}); err != nil {
+ t.Fatal(err)
+ }
+ rec := provision.SidecarRecord{HA: app == "shop", Schema: 1, Name: "bot", Host: provision.SidecarHost("bot", app, "bac"), Account: "bac", App: app, Channel: "stable", CreatedAt: time.Date(2026, 10, 26, 9, 0, 0, 0, time.UTC)}
+ if err := provision.CreateSidecarRecord(ctx, st, rec); err != nil {
+ t.Fatal(err)
+ }
+ }
+ inv := &provision.DepartureInventory{}
+ now := time.Now().Add(time.Second)
+ cfg.Departures = inv.Begin("fresh", now, now, true)
+ cfg.DataDir = data
+ if err := provision.Reconcile(ctx, st, reg, cfg); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.ReconcileSidecars(ctx, st, reg, cfg); err != nil {
+ t.Fatal(err)
+ }
+ return inv.Snapshot()
+}
+
+func TestSidecarNeverAdvertisedOrDialled(t *testing.T) {
+ st, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t)
+ sidecarHARecords(t, st, reg, t.TempDir(), provision.ReconcileConfig{})
+ rt, err := reg.Get("bot.shop.bac.sidecar.internal")
+ if err != nil || rt == nil || !rt.HA || !rt.IsSidecar() || rt.Socket != "" || rt.Addr != "" {
+ t.Fatalf("route %+v %v", rt, err)
+ }
+ ident := edgesFile{Box: "self", ServedPools: edgesFileServedPools(provision.ReconcileConfig{})}
+ var last []byte
+ if err = edgesFilePass(t.Context(), st, reg, ident, "203.0.113.1", &last); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, err := st.Get(t.Context(), edgesFileKey("self"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var file edgesFile
+ if err = json.Unmarshal(raw, &file); err != nil {
+ t.Fatal(err)
+ }
+ if len(file.Hosts) != 0 {
+ t.Fatalf("public hosts %+v", file.Hosts)
+ }
+ if _, ok, err := edge.FoldedHome(map[string][]byte{edgesFileKey("self"): raw}, "peer", rt.Host); err != nil || ok {
+ t.Fatalf("dial target %v %v", ok, err)
+ }
+ e, err := edge.New(reg, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = e.Reload(); err != nil {
+ t.Fatal(err)
+ }
+ req := httptest.NewRequest(http.MethodGet, "http://"+rt.Host+"/", nil)
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, req)
+ if w.Code != http.StatusNotFound || e.Allowed(rt.Host) {
+ t.Fatalf("sidecar ingress %d", w.Code)
+ }
+}
+
+func TestSidecarDutyPoolProjection(t *testing.T) {
+ for _, inbound := range []string{"", provision.InboundNone} {
+ for _, pools := range [][]string{nil, {""}, {"hapair"}, {"", "hapair"}} {
+ cfg := provision.ReconcileConfig{Pools: pools, Inbound: inbound}
+ ident := edgesFile{Box: "self", ServedPools: edgesFileServedPools(cfg)}
+ _, ident.AcceptsInbound = cfg.SharedInstanceEligibility()
+ st, reg := release.NewDirStore(t.TempDir()), edgesTestRegistry(t)
+ var last []byte
+ if err := edgesFilePass(t.Context(), st, reg, ident, "", &last); err != nil {
+ t.Fatal(err)
+ }
+ raw, _, _ := st.Get(t.Context(), edgesFileKey("self"))
+ var view edgesfile.PlacementView
+ if err := json.Unmarshal(raw, &view); err != nil {
+ t.Fatal(err)
+ }
+ got, known := view.ServedPools.Pools()
+ if !known {
+ t.Fatalf("pool evidence unknown: %s", raw)
+ }
+ want := pools
+ if len(want) == 0 {
+ want = []string{""}
+ }
+ if !slices.Equal(got, want) {
+ t.Fatalf("pools %v want %v", got, want)
+ }
+ for _, pool := range []string{"", "hapair", "other"} {
+ for _, placement := range []string{provision.PlacementAny, provision.PlacementNoInbound, ""} {
+ h := provision.DepartureHost{Kind: provision.SidecarKind, HA: true, Lifetime: "life", Pool: pool, SidecarPlacement: placement}
+ want := slices.Contains(got, pool) && (placement == provision.PlacementAny || placement == provision.PlacementNoInbound && inbound == provision.InboundNone)
+ if CanAdopt(h, LocalPolicy{Pools: pools, Inbound: inbound}) != want {
+ t.Fatalf("adopt policy %+v %v", h, cfg)
+ }
+ }
+ }
+ }
+ }
+}
+
+func TestSidecarHADutyLifecycle(t *testing.T) {
+ t.Cleanup(lease.ProcessStateForTest())
+ fx := locktest.NewLockFixture(t)
+ a, _, _ := departureArmFixture(t)
+ st, openErr := a.OpenStore(t.Context())
+ if openErr != nil {
+ t.Fatal(openErr)
+ }
+ a.Self.Scope.DataBucket = fx.Bucket
+ a.ProofStore = nil
+ b := a.Backend
+ b.Cfg.Bucket = fx.Bucket
+ b.Registry = a.Registry
+ b.DataDir = filepath.Join(t.TempDir(), "data")
+ b.RunDirOverride = filepath.Join(t.TempDir(), "run")
+ b.Control = instancectl.NewClient("/unused/control.sock")
+ b.Lifetimes = &provision.LifetimeIndex{}
+ b.Cfg.Record = haRecordFacts(func(context.Context) (release.Store, error) { return st, nil }, nil)
+ inv := sidecarHARecords(t, st, a.Registry, b.DataDir, provision.ReconcileConfig{Lifetimes: b.Lifetimes})
+ if !inv.Complete || len(inv.Records) != 2 {
+ t.Fatalf("inventory %+v", inv)
+ }
+ rt, err := a.Registry.Get("bot.shop.bac.sidecar.internal")
+ if err != nil || rt == nil {
+ t.Fatal(rt, err)
+ }
+ lifeEntry, found := b.Lifetimes.Lookup(rt.Host)
+ if !found || !lifeEntry.HA {
+ t.Fatal(lifeEntry, found)
+ }
+ // An index miss takes the production sidecar record reader, including manifest policy.
+ facts, err := b.Cfg.Record(t.Context(), *rt)
+ if err != nil || facts.ID != lifeEntry.ID || !facts.HA || facts.SidecarPlacement != provision.PlacementAny {
+ t.Fatal(facts, err)
+ }
+ files, err := lease.NewFilesStore(t.Context(), fx.Bucket, "eu-west-1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ b.FilesStore = files
+ a.Service = activator.New(b.Cfg, b, a.Registry)
+ a.Service.DutyStore = a.Registry
+ lease.SetSelf(hafresh.Self{Ref: a.Self.Ref, IID: a.Self.InstanceID, Account: a.Self.Account, Region: a.Self.Scope.CloudRegion})
+ if err = lease.SetObligationDir(t.TempDir()); err != nil {
+ t.Fatal(err)
+ }
+ prefix := activator.HibernatePrefix(b.Cfg.Prefix, rt.Host)
+ pub, err := hostfiles.Open(t.Context(), files, prefix+"/files/0/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = hostfiles.StageWake(t.Context(), pub, hostfiles.WakeState{V: 1, Host: rt.Host, NextDue: 9999999999}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = pub.Commit(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ marker, _ := hafresh.MarkerBody(5, hafresh.Marker{V: 1, Box: "dead", IID: "i-1123456789abcdef0", Lifetime: lifeEntry.ID})
+ fx.PutLock(prefix, marker)
+ c, consumer, err := armHADepartures(t.Context(), a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = consumer.Stop(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ obs, err := c.cfg.Identities.Observe(t.Context(), hadeparture.BoxObservation{Known: true, Box: hadeparture.Box{Ref: "dead", Scope: a.Self.Scope}, EdgesKey: "control/edges/dead.json", EdgesETag: "exact"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = c.Enqueue(t.Context(), obs); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ inv.WalkStartedAt = now.Add(time.Second)
+ inv.SourceReadStartedAt = inv.WalkStartedAt
+ c.cfg.Now = func() time.Time { return now }
+ c.cfg.Inventory = func() provision.InventorySnapshot { return inv }
+ c.cfg.ValidateSuccessor = func(_ context.Context, ref, iid string) (bool, error) {
+ return ref == a.Self.Ref && iid == a.Self.InstanceID, nil
+ }
+ for i := 0; i < 3; i++ {
+ if _, err = c.ScanPass(t.Context()); err != nil {
+ t.Fatal(err)
+ }
+ now = now.Add(31 * time.Second)
+ }
+ duty, ok, err := a.Registry.HADuty(rt.Host, lifeEntry.ID)
+ if err != nil || !ok || duty.Basis != "adopted" {
+ t.Fatal(duty, ok, err)
+ }
+ got, _ := a.Registry.Get(rt.Host)
+ if got.NextDue != 9999999999 {
+ t.Fatal("due state not imported", got)
+ }
+ v, err := lease.ReadLock(t.Context(), fx.Bucket, prefix, "eu-west-1")
+ if err != nil || v.Lock.Release == nil || v.Lock.Release.Box != a.Self.Ref || v.Lock.Release.Clean {
+ t.Fatal(v, err)
+ }
+ d, err := a.Registry.Departure(t.Context(), departureID(c.cfg.DeploymentBucket, obs.Box))
+ if err != nil || d.Phase == "complete" {
+ t.Fatal("legacy sidecar must keep its own departure unresolved", d, err)
+ }
+}
diff --git a/internal/provision/departure_inventory.go b/internal/provision/departure_inventory.go
index 54541c69a..11bcfbd91 100644
--- a/internal/provision/departure_inventory.go
+++ b/internal/provision/departure_inventory.go
@@ -13,6 +13,7 @@ import (
type DepartureHost struct {
Account, App, Host, Kind, Placement, Pool, Lifetime, Revision string
HA bool
+ SidecarPlacement string
}
type InventorySnapshot struct {
Generation string
@@ -102,8 +103,8 @@ func departureInstance(rec Record, raw []byte) (DepartureHost, bool) {
return DepartureHost{Account: rec.Account, App: rec.App, Host: rec.Host, Kind: rec.KindOrDefault(), Placement: rec.Region, Pool: rec.Pool, Lifetime: life.ID, Revision: fmt.Sprintf("%x", sha256.Sum256(raw)), HA: rec.HA}, err == nil && !departureNullRegion(raw)
}
func departureSidecar(rec SidecarRecord, raw []byte) (DepartureHost, bool) {
- life, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
- return DepartureHost{Account: rec.Account, App: rec.App, Host: rec.Host, Kind: SidecarKind, Placement: rec.Region, Pool: rec.Pool, Lifetime: life, Revision: fmt.Sprintf("%x", sha256.Sum256(raw))}, err == nil && !departureNullRegion(raw)
+ life, err := SidecarLifetimeEntryOf(rec)
+ return DepartureHost{Account: rec.Account, App: rec.App, Host: rec.Host, Kind: SidecarKind, Placement: rec.Region, Pool: rec.Pool, Lifetime: life.ID, HA: rec.HA, Revision: fmt.Sprintf("%x", sha256.Sum256(raw))}, err == nil && !departureNullRegion(raw)
}
func departureNullRegion(raw []byte) bool {
var o map[string]json.RawMessage
diff --git a/internal/provision/lifetimeindex.go b/internal/provision/lifetimeindex.go
index 34c38a1d1..2b0142d4e 100644
--- a/internal/provision/lifetimeindex.go
+++ b/internal/provision/lifetimeindex.go
@@ -1,6 +1,7 @@
package provision
import (
+ "fmt"
"slices"
"sync"
"time"
@@ -11,9 +12,10 @@ import (
// is HA. ID is Incarnation(account, app, host, CreatedAt), the lifetime a
// release marker names and the keep decision compares.
type LifetimeEntry struct {
- ID string
- Created time.Time
- HA bool
+ ID string
+ Created time.Time
+ HA bool
+ SidecarPlacement string
}
// LifetimeEntryOf is rec's entry: the one place a record becomes one, for
@@ -39,6 +41,7 @@ func LifetimeEntryOf(rec Record) (LifetimeEntry, error) {
// activator answers with a record read of its own.
type LifetimeIndex struct {
mu sync.Mutex
+ sidecars map[string]LifetimeEntry
m map[string]LifetimeEntry
ha map[string]bool
replicaRecords map[string]Record
@@ -85,6 +88,9 @@ func (x *LifetimeIndex) Lookup(host string) (LifetimeEntry, bool) {
x.mu.Lock()
defer x.mu.Unlock()
e, ok := x.m[host]
+ if !ok {
+ e, ok = x.sidecars[host]
+ }
if x.ha[host] {
e.HA = true
ok = true
@@ -152,3 +158,29 @@ func replicaRecordSnapshot(rec Record) Record {
}
return snapshot
}
+
+func SidecarLifetimeEntryOf(rec SidecarRecord) (LifetimeEntry, error) {
+ if err := ValidateSidecarShape(rec); err != nil {
+ return LifetimeEntry{}, err
+ }
+ if rec.Host != SidecarHost(rec.Name, rec.App, rec.Account) {
+ return LifetimeEntry{}, fmt.Errorf("sidecar record disagrees with its own path")
+ }
+ id, err := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if err != nil {
+ return LifetimeEntry{}, err
+ }
+ return LifetimeEntry{ID: id, Created: rec.CreatedAt, HA: rec.HA}, nil
+}
+
+func (x *LifetimeIndex) Sidecars(entries map[string]LifetimeEntry, complete bool) {
+ x.mu.Lock()
+ defer x.mu.Unlock()
+ if complete || x.sidecars == nil {
+ x.sidecars = map[string]LifetimeEntry{}
+ }
+ for host, e := range entries {
+ x.sidecars[host] = e
+ }
+ x.stickLocked(entries)
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index a8aea2c8c..5e26c812d 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := agentStartDemo2WriteCensusInventory()
+ inventory := regionHASidecarsWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/region_ha_sidecars_census_test.go b/internal/provision/region_ha_sidecars_census_test.go
new file mode 100644
index 000000000..cd7d4432a
--- /dev/null
+++ b/internal/provision/region_ha_sidecars_census_test.go
@@ -0,0 +1,19 @@
+package provision
+
+// B6 keeps ReconcileSidecars a key-site: the same sidecar record key parser
+// and claim-install reference, with no bucket record writes. The new work
+// reads manifest policy into departure entries and the in-memory lifetime
+// index before minting or converging the record's sticky HA bit.
+func regionHASidecarsWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), agentStartDemo2WriteCensusInventory()...)
+ for i, e := range entries {
+ if e.File == "internal/provision/sidecar_reconcile.go" && e.Unit == "ReconcileSidecars" {
+ if e.Class != "key-site" || e.Kinds != "key:ParseSidecarKey,key:SidecarRecordKey,lit:sidecars" {
+ panic("sidecar census class or sites changed")
+ }
+ entries[i].Digest = "6e5e0ac9d95dd6d1da61bbe6cda9175e18d53cad4016b083340522f32c92b7f3"
+ return entries
+ }
+ }
+ panic("sidecar census unit missing")
+}
diff --git a/internal/provision/run_keys_test.go b/internal/provision/run_keys_test.go
index d63d3b225..b2fbac663 100644
--- a/internal/provision/run_keys_test.go
+++ b/internal/provision/run_keys_test.go
@@ -397,6 +397,11 @@ func TestOnlyRunAdmitWritesRunKeys(t *testing.T) {
t.Errorf("%s: %s assigns RunKeys; only RunAdmit may", fset.Position(l.Pos()), fn.Name.Name)
}
case *ast.StarExpr:
+ // SidecarRecord has no RunKeys. Its JSON decoder initializes
+ // that distinct wire type, not an existing instance record.
+ if file == "sidecar.go" && fn.Name.Name == "UnmarshalJSON" && fn.Recv != nil && len(fn.Recv.List) == 1 && censusRecvName(fn.Recv.List[0].Type) == "SidecarRecord" {
+ return true
+ }
if id, ok := l.X.(*ast.Ident); ok && (id.Name == "rec" || id.Name == "r") {
t.Errorf("%s: %s overwrites a whole record through *%s", fset.Position(l.Pos()), fn.Name.Name, id.Name)
}
diff --git a/internal/provision/sidecar.go b/internal/provision/sidecar.go
index 6bdbcf8c2..adb794683 100644
--- a/internal/provision/sidecar.go
+++ b/internal/provision/sidecar.go
@@ -10,6 +10,7 @@
package provision
import (
+ "bytes"
"context"
"encoding/json"
"errors"
@@ -69,7 +70,9 @@ type SidecarManifest struct {
// identity is never guessed at, the same discipline GetRecord applies to
// instances.
type SidecarRecord struct {
+ placementNull bool
// RecordSeq is advanced by every record writer once present; absent is legacy zero.
+ HA bool `json:"ha,omitempty"`
RecordSeq uint64 `json:"record_seq,omitempty"`
Acquisition string `json:"acq,omitempty"`
Schema int `json:"schema"` // 1
@@ -207,6 +210,9 @@ func (m SidecarManifest) PlacementOrDefault() string {
// it is written or materialized — the rails live at the door, exactly as
// ValidateShape's do for instance records.
func ValidateSidecarShape(rec SidecarRecord) error {
+ if rec.placementNull {
+ return errors.New("sidecar region must not be null")
+ }
if rec.Schema > 1 {
return fmt.Errorf("schema %d is newer than this binary understands — upgrade carlos", rec.Schema)
}
@@ -449,3 +455,18 @@ func PutSidecarManifestIfMatch(ctx context.Context, s release.Store, acct, app s
})
return
}
+
+func (rec *SidecarRecord) UnmarshalJSON(raw []byte) error {
+ type record SidecarRecord
+ var value record
+ if err := json.Unmarshal(raw, &value); err != nil {
+ return err
+ }
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &fields); err != nil {
+ return err
+ }
+ value.placementNull = bytes.Equal(bytes.TrimSpace(fields["region"]), []byte("null"))
+ *rec = SidecarRecord(value)
+ return nil
+}
diff --git a/internal/provision/sidecar_ha_test.go b/internal/provision/sidecar_ha_test.go
new file mode 100644
index 000000000..78f588383
--- /dev/null
+++ b/internal/provision/sidecar_ha_test.go
@@ -0,0 +1,55 @@
+package provision
+
+import (
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+func TestSidecarHABirthOnly(t *testing.T) {
+ for _, stamped := range []bool{false, true} {
+ t.Run(map[bool]string{false: "legacy", true: "born-HA"}[stamped], func(t *testing.T) {
+ f := sidecarSetup(t)
+ f.putManifest(t, "shop", SidecarManifest{Schema: 1, App: "shop", Args: []string{"work"}})
+ rec := SidecarRecord{Schema: 1, Name: "bot", Host: f.host("bot", "shop"), App: "shop", Account: f.sqid, Channel: "stable", CreatedAt: time.Now().UTC()}
+ raw, _ := json.Marshal(rec)
+ var fields map[string]any
+ _ = json.Unmarshal(raw, &fields)
+ if stamped {
+ fields["ha"] = true
+ }
+ raw, _ = json.Marshal(fields)
+ if _, err := f.store.Put(ctx, SidecarRecordKey(f.sqid, "shop", "bot"), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ index := &LifetimeIndex{}
+ inv := &DepartureInventory{}
+ pass := inv.Begin("one", time.Now(), time.Now(), true)
+ pass.family("instance", nil, true)
+ f.reconcile(t, ReconcileConfig{Lifetimes: index, Departures: pass})
+ rt := hasRoute(t, f.reg, rec.Host, "sidecar missing")
+ if rt.HA != stamped {
+ t.Errorf("HA=%v, want %v", rt.HA, stamped)
+ }
+ if !rt.IsSidecar() || rt.Socket != "" || rt.Addr != "" {
+ t.Fatalf("dialable sidecar: %+v", rt)
+ }
+ if stamped && rt.DBPath != NestedDBPath(f.dir, rec.Host) {
+ t.Errorf("HA sidecar is not nested: %s", rt.DBPath)
+ }
+ life, ok := index.Lookup(rec.Host)
+ want, _ := Incarnation(rec.Account, rec.App, rec.Host, rec.CreatedAt)
+ if !ok || life.ID != want || life.HA != stamped {
+ t.Errorf("lifetime %+v, found %v", life, ok)
+ }
+ snapshot := inv.Snapshot()
+ if !snapshot.Complete || len(snapshot.Records) != 1 || snapshot.Records[0].HA != stamped {
+ t.Errorf("inventory %+v", snapshot)
+ }
+ index.Replace(nil)
+ if got, ok := index.Lookup(rec.Host); !ok || got.ID != want {
+ t.Errorf("instance pass discarded sidecar lifetime: %+v %v", got, ok)
+ }
+ })
+ }
+}
diff --git a/internal/provision/sidecar_reconcile.go b/internal/provision/sidecar_reconcile.go
index 0fb7ccfe9..a48e37306 100644
--- a/internal/provision/sidecar_reconcile.go
+++ b/internal/provision/sidecar_reconcile.go
@@ -129,7 +129,12 @@ func placeable(rec SidecarRecord, m SidecarManifest, cfg ReconcileConfig) bool {
// the activator's sweeper never needs a bucket read to decide a worker has
// outrun its limits.
func sidecarRouteFor(rec SidecarRecord, m SidecarManifest, dataDir string) registry.Route {
+ dbPath := DefaultDBPath(dataDir, rec.Host)
+ if rec.HA {
+ dbPath = NestedDBPath(dataDir, rec.Host)
+ }
return registry.Route{
+ HA: rec.HA,
Host: rec.Host, Slug: rec.Name, Kind: SidecarKind,
App: rec.App, Account: rec.Account, Pool: rec.Pool, Region: rec.Region,
// The RECORD's channel, never the manifest's: a record that reached
@@ -138,7 +143,7 @@ func sidecarRouteFor(rec SidecarRecord, m SidecarManifest, dataDir string) regis
// nothing here for a manifest-side fallback to rescue. The manifest's
// Channel is the console door's default at CREATE time.
Channel: rec.Channel, Environment: rec.Environment,
- DBPath: DefaultDBPath(dataDir, rec.Host),
+ DBPath: dbPath,
Hibernate: m.HibernateOrDefault(),
Args: sidecarArgsJSON(m),
IdleSeconds: int(m.IdleOrDefault() / time.Second),
@@ -344,6 +349,9 @@ func ReconcileSidecars(ctx context.Context, s release.Store, reg *registry.Regis
}
if cfg.Departures != nil {
h, ok := departureSidecar(rec, raw)
+ if m, known := manifestFor(acct, app); known {
+ h.SidecarPlacement = sidecarPlacement(rec, m)
+ }
sc.departureRecords = append(sc.departureRecords, h)
sc.departureInvalid = sc.departureInvalid || !ok
}
@@ -388,6 +396,18 @@ func ReconcileSidecars(ctx context.Context, s release.Store, reg *registry.Regis
return err
}
recs, protect, manifestFor := sc.recs, sc.protect, sc.manifestFor
+ if cfg.Lifetimes != nil && !cfg.DryRun {
+ entries := map[string]LifetimeEntry{}
+ for host, rec := range recs {
+ if e, err := SidecarLifetimeEntryOf(rec); err == nil {
+ if m, known := manifestFor(rec.Account, rec.App); known {
+ e.SidecarPlacement = sidecarPlacement(rec, m)
+ }
+ entries[host] = e
+ }
+ }
+ cfg.Lifetimes.Sidecars(entries, !sc.readFailed && len(sc.protect) == 0)
+ }
trashed := trashGate(ctx, s, "sidecar")
@@ -573,6 +593,11 @@ func ReconcileSidecars(ctx context.Context, s release.Store, reg *registry.Regis
// nothing saying so is the failure class behind #130 seen from the outside.
func convergeSidecar(reg *registry.Registry, existing registry.Route, rec SidecarRecord, m SidecarManifest, cfg ReconcileConfig) {
want := sidecarRouteFor(rec, m, cfg.DataDir)
+ if want.HA && !existing.HA && !cfg.DryRun {
+ if err := reg.SetHA(rec.Host); err != nil {
+ log.Printf("provision: converge HA on %s: %v", rec.Host, err)
+ }
+ }
if want.Channel != "" && existing.Channel != want.Channel {
if cfg.DryRun {
@@ -637,3 +662,5 @@ func convergeSidecar(reg *registry.Registry, existing registry.Route, rec Sideca
rec.Host, existing.DBPath, want.DBPath, existing.Socket, existing.Addr)
}
}
+
+func SidecarPlacement(rec SidecarRecord, m SidecarManifest) string { return sidecarPlacement(rec, m) }
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 0ba9feb20..7c7d243b7 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -95,3 +95,4 @@ plan14-root-reads-region-ha-p3b1-f4.tsv 71bbbf68863266ffab90211a00aff2f1b694bf39
plan14-root-reads-agent-start-demo-2.tsv 1daafee8030f9d370adf5541b5e87313523073c4afdc022d4238c3a7bc1a60ba
plan14-root-reads-hosts-floor-release.tsv 1daafee8030f9d370adf5541b5e87313523073c4afdc022d4238c3a7bc1a60ba
plan14-root-reads-region-ha-p3b2.tsv 1b5ef39b210f3c7db69e589da8a467ac4d4a4f218e1d97fb4706cd277a27eae1
+plan14-root-reads-region-ha-p1b3b-s.tsv 05f08edeb46837a18f1abca302ad21d8c7782edef8af00cc4082f5ed4ea35ad6
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-s.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-s.tsv
new file mode 100644
index 000000000..801642a46
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3b-s.tsv
@@ -0,0 +1,62 @@
+# Census overlay region-ha-p1b3b-s, written by census-propose (#369). census-ruling-region-ha-p1b3b-s, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p1b3b-s.md.
+# 8 body, 8 sites, 6 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 11 new dispositions: 5 reads re-frozen at their disposition with the claim, 6 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 5490ffeb6e8cb3f498f6ca3becf4e389e1223b91a6a51b62dfdff1442754c186 internal/activator/activator.go Service.SleepWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-region-ha-p1b3b-s;basis=Refuse an idle-triggered worker stop while producer work holds the existing inflight lease reference; no new read or start authority. registry:Hibernate@187,whole:Route@189,whole:Route@347 1d66d8c4673607ced902c678b139816cdfd98074cf49c29cdf09367ac0fd044b
+@legacy 4928090e8ddd317e0d13455adaf7293cbe6973f64e5629d2ecd8e9fd01b353ce internal/activator/haduties.go Service.WithDuty legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Read route host for owned-awake checks and pass provisioned managed instances to restricted singleflight wake before producer writes, including cached legacy rows that discover sticky HA at acquire. Other route kinds keep their path; no authority bypass.;rev3=census-ruling-region-ha-p1b3b-s;basis=Include stamped provisioned sidecars in the existing restricted singleflight wake before producer work. Legacy sidecars remain inline. No new acquire or import protocol. registry:Host@605,registry:Host@694,whole:Route@143,whole:Route@422,whole:Route@524 045e968bc8571eea436bdbaf4c34e1661aad9b5d57cc9cb2ec4abf899341a770
+@legacy 0398b7e5da1d04cd35081626a9f5f3f86bee118be8eb8460ec120501f3f7cf9d internal/activator/prepare.go ExecBackend.prepareKeyedAt legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged;rev3=census-ruling-rootfs-fleet-followups;basis=names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 8: the cmd role three exceptions (no env read, the replica gate left to StartCmd, no app-log listener) now cover every one-shot role, instancectl.OneShot(role): cmd and tty; before, the tty role fell to the sidecar env-file read and an app-log listener on its handoff socket path; no read added, one removed for tty;rev3=census-ruling-region-ha-p1b3b-s;basis=Native sidecar run units use the existing nested secrets preparation and acknowledged sealed publication, but bind no app control listener. Existing run and seed reads unchanged. file:ReadDir@2965,registry:Host@1783,registry:Host@1995,registry:Host@5905,registry:Host@6103,registry:Host@612,whole:Route@1674,whole:Route@1885,whole:Route@2116,whole:Route@320,whole:Route@4697,whole:Route@5246,whole:Route@5939 c1ba81e8b4a4173d772a8290739122cd30eb9e7807a70ec09e47bccaa4d2ac6f
+@legacy 6936460cba074d102ca13ad01c0b9de40e523369bc2a85e6d229ca15bd84813f internal/activator/unitproc.go ExecBackend.newUnitProcFor legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;basis=the unit is named by unitNameFor(rt, role, gen), one more Route site (+whole:Route), and a role with no unit of the row's kind is refused before anything watches ""; no new read kind and no file read;rev3=census-ruling-region-ha-p1b3b-s;basis=Attach optional per-worker API closers to the existing unit observer before starting it; unit naming and systemd/cgroup proof reads unchanged. registry:Host@323,registry:Host@435,whole:Route@228,whole:Route@364,whole:Route@368 0adbe2c9498f8b2b7848db6765a9af719ccb898f7d077df395cbbabb126c2286
+@legacy cb1057e5df0d11f822fb1c85c04f81443b67a9fef931fa407fcc35c8f45a9acf internal/host/hadepartures_wiring.go armHADepartures legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3 fix r1: Install proof adapter, adoption identity and suspicion callbacks before asynchronous startup. Lazily retry the same deployment/data clients; lifetime callback reads only the current host through ExecBackend.TerminationLifetime. Add bounded structured paging for unresolved per-iid records. No new bucket, tenant input path or acquire bypass. B4: Wire the shared lock reader and existing AdoptHost entry. Read local route, Pair and duty revision only after authoritative inventory eligibility; bind its record lifetime and refuse missing/mismatched local routes. No route synthesis or pool widening. B5: Publish the armed controller to the existing metrics sampler. No new loop, remote source or process authority.;rev3=census-ruling-region-ha-followups;basis=Inject the existing PageOperator function into the backend when HA departures are armed; no new read or paging transport.;rev3=census-ruling-region-ha-p3b;basis=Require group admission/BeginWork callbacks and pass them into the sole departure consumer, including the production adoption closure. Same store, identity and registry reads; consumer Started remains a lifecycle fact, not duty authority.;rev3=census-ruling-region-ha-p1b3b-s;basis=Carry the actual provisionTickConfig pools and inbound posture into CanAdopt; stamped sidecars use the existing production adopter. Legacy unresolved paging remains. No wider tenancy or new remote source. registry:Account@3700,registry:Account@7462,registry:App@7489,registry:IID@3721,registry:Incarnation@7649,registry:Pool@7508,registry:Region@3711,registry:Region@7529,registry:Revision@7884,registry:Revision@8281,registry:ServingSeq@7677,whole:DutyState@8003,whole:Pair@7866,whole:Pair@8259,whole:Pair@8265,whole:Route@7449,whole:Route@8158 038ee80fa252d105e9f26ec5449083eb038b3a219c7a888b4068c62221b35ca8
+@legacy 6445f12812e14fe2d66dfcd4cc3af37ed78d4165c69d7f4502892c9326f118f3 internal/provision/sidecar_reconcile.go ReconcileSidecars legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the record walk and its sidecars manifest lookup move unchanged into the pass's scan closure (over a store argument) and the removal phase into its retire closure; over a record view snapshot, a pass that reaches a removal candidate (a sidecar gone or no longer placeable here) removes nothing on the snapshot's word: it runs scan again over the bucket (freshStore) and decides every removal that pass from that walk, by the walk's own rules (unusable records protected before scope, hosts matched across every key, placement from the bucket's record and sidecars manifest against this box's inbound); a walk that cannot read cleanly keeps every row; with no candidate, or disarmed, nothing is read again; the registry sites are main's, moved; relative to main's single walk a removal can only be withheld, never added;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: retain validated sidecar records before scope/manifest filtering for coverage, including hidden/out-of-pool records. No new object reads or sidecar HA authority.;rev3=census-ruling-region-ha-p1b3b-s;basis=Derive canonical sidecar lifetimes from account/app/synthetic host/CreatedAt; collect HA and manifest placement for departures before scope filtering; update a separate family in the existing lifetime index. Existing record reads, key parsing and removal authority remain. registry:Account@12676,registry:Account@12915,registry:Account@13868,registry:Account@14618,registry:App@12649,registry:App@12901,registry:App@13841,registry:App@14604,registry:Args@13493,registry:Args@13764,registry:Channel@13481,registry:ClaimOwnership@13294,registry:Host@10270,registry:Host@15954,registry:Host@16001,registry:Host@16124,registry:Host@16301,registry:Host@16450,registry:Host@16557,registry:Kind@12590,registry:Kind@12864,registry:Kind@13781,registry:Kind@14567,registry:Kind@15787,registry:Pool@15905,registry:Provisioned@12622,registry:Provisioned@12879,registry:Provisioned@13813,registry:Provisioned@14582,registry:Provisioned@15814,registry:Region@15855,whole:ClaimOwnership@13297,whole:ClaimOwnership@13314,whole:Route@10252,whole:Route@10263,whole:Route@10281,whole:Route@10467,whole:Route@10836,whole:Route@10845,whole:Route@12278,whole:Route@13139,whole:Route@13146,whole:Route@13214,whole:Route@13549,whole:Route@13926,whole:Route@15772,whole:Route@16367 6e5e0ac9d95dd6d1da61bbe6cda9175e18d53cad4016b083340522f32c92b7f3
+@legacy 6792e3e31bb9be7edfce6fc76bdc99643f4d33fc4461586e3463f79b5032ec1c internal/registry/ha_departures.go Registry.ImportHAWake legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Validate all state then transactionally compare current Pair, lifetime, binding, revision and receipt before replacing rows and recording pending authority. Replays never replace rows. B2 fix r1: find replay receipts only within the current binding; an older binding remains history and permits a new guarded import. Preserve Pair/lifetime/revision checks and no authority from import.;rev3=census-ruling-region-ha-p1b3b-s;basis=Permit stamped provisioned hibernating socketless native sidecars through the shared SQL kind predicate while preserving transaction, Pair, lifetime, revision, receipt and binding checks. Import still grants no authority. file:QueryRowContext@1469,file:QueryRowContext@853,registry:DepartureIID@1863,registry:DepartureIID@2524,registry:DepartureIID@394,registry:DepartureRef@1829,registry:DepartureRef@2508,registry:DepartureRef@370,registry:Import@266,registry:Incarnation@1096,registry:Lifetime@1291,registry:Lifetime@1659,registry:Lifetime@2431,registry:Lifetime@418,registry:LockETag@1765,registry:LockETag@2443,registry:LockETag@457,registry:LockGeneration@1793,registry:LockGeneration@2455,registry:LockGeneration@499,registry:Receipt@1642,registry:Receipt@2414,registry:Receipt@438,registry:Receipt@588,registry:Revision@2040,registry:Sequence@2487,registry:ServingSeq@1115,registry:WakeDigest@2473,registry:WakeDigest@477,registry:remote@125,registry:remote@157,whole:HAWakeImport@2124,whole:HAWakeImport@242,whole:HAWakeImport@248,whole:HAWakeImport@317,whole:Pair@1305,whole:Pair@1313,whole:Pair@226,whole:Pair@232,whole:claimTransaction@2114,whole:remoteClient@127,whole:remoteClient@159 8ac56c38e1bcdbb28ef9e62de4e751046d06bb087fbd9fbedbc6400dcb6d9432
+@legacy a74672fc4f38dad2234b80e65d977385ec4255adb39e69c68cba2b1fd41ab48f internal/registry/ha_duties.go Registry.BindHADuty legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Compare active route Pair and captured revision before changing its authoritative lifetime binding; clear basis and suppression on change.;rev3=census-ruling-region-ha-p1b3b-s;basis=Use the shared kind predicate to include only stamped provisioned hibernating socketless native sidecars. Existing captured-revision and Pair CAS remain. registry:Changed@295,registry:Incarnation@774,registry:ServingSeq@792,registry:remote@129,registry:remote@161,registry:sql@381,whole:Pair@228,whole:Pair@234,whole:remoteClient@131,whole:remoteClient@163 d870f8b396e7f7362c03de114b72f6ebc2827c92bc5a0bdc16deb7925190d56e
+@legacy 7653aa63918f187c7afc7f45108af516a2927a4cf2e7b06f753d87c73c3ebce9 internal/activator/sidecar_ha.go ExecBackend.listenWorkerAPI legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Bind only the current host run directory agent.sock using the existing nosymfollow nested mount. Restrict claimed host to that route and reuse agentsock token authorization and request limits; no public listener or outbound tenant dial. Unit observer closes it. registry:Host@864 9a6a61887d833f1817723c3386a9b5ef5f7634f5a08ac800aaf76601660cc2d4
+@legacy eefc3fc589f18cacd2323f13ea0b1d8163b437516d0c5461b9e8a1f8c29b63f5 internal/activator/sidecar_ha.go ExecBackend.startHAWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Require nested HA sidecar shape and closed worker identity environment; prepare and acknowledge sealed secrets before writing the existing run launch file. Start the previously verified staged executable through existing root StartExe, mark uncertain starts for stop proof, and observe the same run unit. No health dial or new root verb. registry:Host@1355,registry:Host@1391,registry:Host@1992,registry:Host@270,registry:Host@320,whole:Route@1049,whole:Route@1433,whole:Route@1504,whole:Route@1637,whole:Route@1692,whole:Route@184,whole:Route@2035,whole:Route@853 81ecef01a88e9d25519464c9a099b6d38fca6bab3b5d5083a60cd1fcadbb4715
+@legacy 8472f2b0473ba0b78d65abff115cdd4cf3d59dd25eae43ebd24de917e0ff26dd internal/activator/unitproc.go unitProc.Crashed legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=For native sidecars only, classify the retained exit record through workerExitStatus after done closes; intentional stops and unknown outcomes are not crashes. No process or lease authority. whole:Route@43 cfddb3d41614ff3dddc86a16550fca701ada3aa5363d781e0d41961261d767aa
+@legacy 871ae9cb8e6858ef2be584db9a3714339d60172fdbf3520d635d850888bab181 internal/edge/wakeplacement.go Edge.SidecarDutySnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Pass local route and authoritative cached sidecar manifest policy to the existing edges fold projection; no store or request-time membership reads. whole:Route@133 93faaaca0c599fe1925821b8ac6aa39a72ec43f5d925b81c7f33ff4b9dcf6737
+@legacy 9cc795bddc874cb0a1f1a20854dff75ec6372e940ad71f88f743d9cef075490f internal/edge/wakeplacement.go homeMap.dutySnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Keep instance host-evidence selection unchanged; sidecars require exact validated served_pools and local policy, compatible fresh scope/bucket/key and admission evidence. No sidecar public Hosts entry or tenant dial. registry:App@2633,registry:Host@1575,whole:Route@1606,whole:Route@2350,whole:Route@810 784c976234f5438bf0075af70a76ff596625fd6fd136de2e14eb78c57377118c
+@legacy 00cbe54a970e5327484d54443d696c8e9e1e35ec50b68fbbd6eb2317223b83b1 internal/edge/wakeplacement.go sidecarBoxEligible legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Read in-memory route identity, HA/provisioned bit, scope and pool; require canonical socketless native shape, exact served_pools and restrictive inbound policy. Unknown or malformed pool/placement evidence refuses. registry:Account@279,registry:Addr@137,registry:App@271,registry:HA@109,registry:Host@262,registry:Pool@316,registry:Provisioned@90,registry:Region@187,registry:Replica@173,registry:Socket@118,registry:Tunnel@154 e81f6d601f1e0677bce821832a849f8369f24304ed2c59bd408769182dbe0d29
+@legacy b35dfedd00f1836312ce3aa377b17d66034f8d4a1fe26fe620afc336615d6a45 internal/activator/hawake.go ExecBackend.haContained legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the containment admission: refuses a unit-backed row (+registry:Backing), a row whose layout is not nested, and a box whose nested gate fails (nestedReady); +whole:Route x2; only refuses;rev3=census-ruling-region-ha-p1b3b-s;basis=Refuse HA sidecars with unprovisioned/nonhibernating, dialable, replica, tunnel, runtime or seed shapes before nested containment checks. No fallback or new path read. registry:Addr@139,registry:Backing@308,registry:Hibernate@104,registry:Provisioned@85,registry:Replica@156,registry:Runtime@189,registry:Seed@209,registry:SeedSource@226,registry:Socket@120,registry:Tunnel@170,whole:Route@414,whole:Route@609 b81c997922fabb3dcf8054419cd992c3018334684a9585fe5ec4baec083ca181
+@legacy 97050ac4d86997df23a41242da43dfe8609ec1e35c2cce8934b61a3384ab19c2 internal/activator/hawake.go haLegacyRoute legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: a route is legacy for HA (sidecar, not provisioned, or a kind other than instance); +registry:Kind, +registry:Provisioned; pure;rev3=census-ruling-region-ha-p1b3b-s;basis=Only stamped provisioned native sidecars join instance classification; unstamped and unprovisioned sidecars remain legacy and cannot take an HA-shaped lock. registry:HA@92,registry:Kind@103,registry:Provisioned@54 cc4a3f5811bf262a82ccb4162156a1c32778ba43a503e8efe1d655ec9d6502a5
+@legacy 8f4c10711aa67d08e59481874268e9fcc61a55e6356e0cd6c14cc588c5a2219a internal/activator/layout.go Classify legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: a row with a runtime (LayoutExempt) is never fenced by a layout journal; the journal check now asks LayoutExempt first; the binary path is unchanged;rev3=census-ruling-region-ha-p1b3b-s;basis=Recognize a stamped provisioned socketless sidecar only at its canonical NestedDBPath, retaining collision and layout fences. No dummy socket added. registry:Addr@1457,registry:DBPath@1190,registry:DBPath@1304,registry:DBPath@1602,registry:HA@1429,registry:Host@1103,registry:Host@1165,registry:Host@1239,registry:Host@126,registry:Host@1352,registry:Host@237,registry:Host@853,registry:Host@914,registry:Host@924,registry:Host@963,registry:Host@971,registry:Provisioned@1411,registry:Socket@1251,registry:Socket@1365,registry:Socket@1438,registry:Socket@1613,whole:Route@87,whole:Route@899,whole:Route@952 c08d62fdb590d8445c4a7bc478d83626c42386c0690c60bd0a62e3185b406374
+@legacy 094078b373d05999d9ff9fecd27bceccc0159feef596ffaa5f36eac366924426 internal/provision/sidecar_reconcile.go convergeSidecar legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-region-ha-p1b3b-s;basis=Converge only the sticky HA bit with SetHA when the record is stamped; no database-path migration or record rewriting. registry:Addr@3573,registry:Addr@3915,registry:Args@1798,registry:Args@1815,registry:Args@1932,registry:Args@1947,registry:Args@1999,registry:Args@2183,registry:Args@2198,registry:Channel@345,registry:Channel@367,registry:Channel@387,registry:Channel@510,registry:Channel@528,registry:Channel@586,registry:Channel@779,registry:Channel@797,registry:DBPath@3514,registry:DBPath@3533,registry:DBPath@3868,registry:DBPath@3885,registry:Environment@1065,registry:Environment@1270,registry:Environment@1292,registry:Environment@822,registry:Environment@846,registry:Environment@977,registry:Environment@999,registry:HA@181,registry:HA@193,registry:Hibernate@1321,registry:Hibernate@1343,registry:Hibernate@1470,registry:Hibernate@1490,registry:Hibernate@1552,registry:Hibernate@1751,registry:Hibernate@1771,registry:IdleSeconds@2495,registry:IdleSeconds@2519,registry:IdleSeconds@2705,registry:IdleSeconds@2751,registry:IdleSeconds@2838,registry:IdleSeconds@3067,registry:IdleSeconds@3113,registry:MaxRunSeconds@2539,registry:MaxRunSeconds@2565,registry:MaxRunSeconds@2727,registry:MaxRunSeconds@2769,registry:MaxRunSeconds@2856,registry:MaxRunSeconds@3089,registry:MaxRunSeconds@3131,registry:Socket@3548,registry:Socket@3898 42a17311a1e34741d2bf588aebd132827a694984df4f5cf81b8b443e840ac2ec
+@legacy 53177501483d6420608309e5e89a62b538c6de6a8612039752d948fb801cee21 internal/activator/activator.go Service.begin legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: before an entry is made, a resident inside its backoff answers errResidentBackoff, and a rootfs row must pass the locked admission (rootfsRefusalLocked) and then the backend's rootfs gates off a.mu (rootfsStartRefusal, within the request's wait bound) before Acquire, Restore or the live link; the gate key is recorded on the entry; adds refusals before the lease only;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p1b3b-t;basis=Carry background-duty provenance into a new singleflight entry; a visitor waiting on its deferred refusal retries with ordinary visitor authority. No read added.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: check local tenant admission and start permission before lease/restore, preserving already-awake reuse during drain and existing serialization. Whole Route passes to the local predicate; no new filesystem or store read.;rev3=census-ruling-region-ha-p1b3b-s;basis=Construct a worker entry for sidecar producer wakes inside the same singleflight and inflight reference machinery; passes whole route to newWorkerEntry, no new data read. registry:Host@1240,registry:Host@1780,registry:Host@3836,registry:Host@4098,registry:Host@656,whole:Route@1302,whole:Route@1413,whole:Route@177,whole:Route@2334,whole:Route@2421,whole:Route@2502,whole:Route@2763,whole:Route@2873,whole:Route@3047,whole:Route@3845,whole:Route@3852,whole:Route@4021 5bbcaf73959e3a648ce9dd2e7d58e452c494e607585729d28e91d782969cf698
+@legacy 2378fa105fb6eba457c9b9d0e3eb4cc2c38c72059c9ce848250dc9ced2b07168 internal/activator/backend_exec.go ExecBackend.StartWorkerStaged legacy accepted-legacy accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read.;rev3=census-ruling-region-ha-p1b3b-s;basis=Require acquired HA lifetime and containment for stamped sidecars; after the existing staged build verification, dispatch their worker launch through startHAWorker. Legacy worker exec and parent co-spawn remain unchanged. file:Command@4150,registry:Args@727,registry:Args@878,registry:Host@1089,registry:Host@1185,registry:Host@1888,registry:Host@1963,registry:Host@3253,registry:Host@4289,registry:Host@5175,registry:Host@561,registry:Host@869,registry:Host@973,whole:Route@1648,whole:Route@2032,whole:Route@206,whole:Route@2335,whole:Route@242,whole:Route@2881,whole:Route@332,whole:Route@4102,whole:Route@4220,whole:Route@4250,whole:Route@446,whole:Route@5016,whole:Route@5106 0944d09366a4f90c8ac7086c1d5a56c07eb95950840e4b2dac08df9bcda822bd
+@legacy 9a46a76fbded0e9601f5e2bfbc071a4dceb1f46020861982431161e721f41412 internal/activator/genbackend.go ExecBackend.EmptyHost legacy accepted-legacy accepted-legacy;rev3=fix1-merge-review;basis=Checks agent-owned host cleanup before lease release; no root authority is derived from it.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 N1: refuses a row with a runtime first (refuseHostCgroupProof); the cgroup open moves into openHostCgroup (same delegation check and OpenCleanup, with the test seam); reads Runtime;rev3=census-ruling-region-ha-p1b3b-s;basis=For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone instead of treating its flat cgroup as its process tree; other shapes retain prior proof. registry:Host@274,registry:Host@524,whole:Route@113,whole:Route@172,whole:Route@212 e3e5fc9557cbea81c44acd4a4f45a58336a51e43c758566ad99c67f069a57ad2
+@legacy 0353134572a47ba9a7edbe047e0bde8dca60aec9675bb0acf852b01b7d527f60 internal/activator/genbackend.go ExecBackend.KillHost legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 N1: refuses a row with a runtime first (refuseHostCgroupProof); the cgroup open moves into openHostCgroup (same delegation check and OpenCleanup); reads Runtime;rev3=census-ruling-region-ha-p1b3b-s;basis=For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone; no new root verb or new unit naming. Flat workers retain the existing cgroup proof. registry:Host@273,whole:Route@112,whole:Route@171,whole:Route@211 58bfd9405f7dfbac4bee75fc67b26650929b11b7486b369a99c2c8f926deba5b
+@legacy 4cae456b17f31294ef276bb70d17b873b3b4ad3f174256bac186fdf7ed98ebcf internal/activator/hawake.go ExecBackend.acquireClassified legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the acquire's classification: a legacy route (sidecar, hand-added or not an instance) takes lease.Acquire and refuses on an HA-format lock; otherwise isHA (a record read error fails the wake, never falls back to legacy); not HA takes lease.Acquire, and an HA-format lock there marks the host HA for good and continues; HA requires haContained before any lock request, then lease.AcquireHA with the same-box proof; held and refused leases map to errLeaseHeld and errLeaseRefused (leaseError); +registry:Host, +whole:Route x7;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: the HA acquire's Proofs gain OwnerTerminated (b.ownerTerminated(ctx, rt)) beside SameBoxEmpty; one more whole:Route site passes the route to ownerTerminated; nothing new is read; the proof is consulted only by hafresh.DecideAcquire for another box's expired HA lock;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 7, two-box fleet test): the two legacy acquires call b.acquireLegacy(ctx, prefix), which is acquireLegacyLease exactly when ExecBackend.LeaseIdentity is nil and LeaseTTL is 0 (the agent never sets them), otherwise lease.AcquireAs with that identity and TTL. The classification, the HA path and every refusal are unchanged. Read sites unchanged (9). Agent, not root.;rev3=census-ruling-region-ha-p1b3b-t;basis=Select the restriction-only AcquireHAForDuty for background contexts, including sticky HA reclassification; observe successful ordinary acquires to clear stale suppression. Add a whole-route observer argument; no new authority. B2 binds the current authoritative lifetime and advances local revision before HA acquire, invalidating concurrent adoption I/O. Ordinary lease authority and restore ordering remain unchanged. B2 fix r1: advance the local duty revision with an unconditional registry UPDATE before acquire; remove pre-acquire lifetime CAS and basis clearing. Failed acquire preserves adopted state. Existing lease validation and successful-acquire observer remain. B3: pass the same optional durable termination proof adapter to visitor and duty acquires. Nil retains the existing path until controller arming; configured proof failures refuse, with no fallback to a live boolean. No new read in this unit. Final fix P2-1: copy the shared proof adapter per acquire to attach the existing takeover telemetry; retain a live confirmer fallback for unverified identities. Existing classified owner, lifetime, expiry and CAS guards remain.;rev3=census-ruling-agent-start-demo-1;basis=Reads demo shape/layout and takes the existing legacy renewing lease for demos; never falls through to HA acquisition. Merge integration against origin/main 9bd45488 retains main's HA duty/termination proof wiring after the demo legacy-lease branch; the added whole-route passes are main's existing checks.;rev3=census-ruling-region-ha-p1b3b-s;basis=Before any HA sidecar write require a known canonical lifetime, files store and valid shared sealer; unstamped sidecars cannot upgrade from an HA lock. Reuse existing containment, AcquireHAForDuty, restore and release paths. registry:Host@106,whole:Route@1064,whole:Route@1115,whole:Route@1365,whole:Route@1668,whole:Route@1964,whole:Route@2181,whole:Route@221,whole:Route@2226,whole:Route@2381,whole:Route@278,whole:Route@3182,whole:Route@3278,whole:Route@589,whole:Route@627 39023dbc194a371ed5f5318f3bc28adbcac4f281577b0ad30a091d3727897d56
+@legacy 14b60ced879dbb405464c6f9bd10f2385ab3a60b4409fbb28789b97bfa96d631 internal/activator/unitproc.go ExecBackend.observe legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=final fix I3: the process observer's termination proof for a rootfs handle (Runtime, the new kind, one site) goes through unitEvents (two more Route sites): the host slice's cgroup.events and, for a rootfs unit, the group systemd reports when that is elsewhere, so a foreign invocation root placed outside the slice and could not stop is never read as gone from the absent expected path; a failed stop of a foreign invocation leaves it unstopped, asked again next poll, completion pending; a binary handle's proof is unchanged (cgroup.events under the host slice); the agent decides only whether it keeps a handle and a launch file; no root decision; re-digested at the merge of origin/main 3c33f2eb: main's own change to the observer is in the body, this branch's rootfs-aware evidence and the rootfs-only failed-stop retry (merge prep N1: a binary handle behaves exactly as main) on top; the kinds are the union;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: for a worker handle (p.worker != "") the observer keeps the exit record it read (workerExit, workerExitOK) for the supervisor instead of wording a member event, and says nothing for a replaced-after-stop or restarted-outside end; the termination evidence (cgroup.events via unitEvents, the foreign-invocation rule) and the record's single-use removal are unchanged and apply to a worker as to a generation; a binary or generation handle behaves exactly as before; the same 22 read sites, no read added;rev3=census-ruling-rootfs-worker-exit;basis=an exit record with an empty code (read and bounded as before) is filled by unitMainExitOf before it is kept for a worker or worded for the member; the termination proof (UnitState, cgroup evidence, the foreign-invocation rule) and the record's single-use removal are unchanged; the same 22 read sites, no read added;rev3=census-ruling-region-ha-p1b3b-s;basis=Retain the already-read advisory exit record for native sidecars after the same systemd and cgroup termination proof; crash classification never substitutes for stop proof. No new read source. registry:Host@1222,registry:Host@3062,registry:Host@3252,registry:Host@3599,registry:Host@3825,registry:Host@4529,registry:Host@6006,registry:Runtime@2414,registry:Runtime@806,whole:Route@1224,whole:Route@2222,whole:Route@2416,whole:Route@3064,whole:Route@3254,whole:Route@3601,whole:Route@3827,whole:Route@4531,whole:Route@4787,whole:Route@5080,whole:Route@5558,whole:Route@6008,whole:Route@808,whole:Route@972 af7f350e623184734d2ba99964a3c39b3d34775f04238f906efca436c335bb79
+@legacy 04ef40e3d9c8395f3fdca8915dd96ec4e2f3d0325c78f128c5613a50c5ff3cd4 internal/edge/wakeplacement.go homeMap.wakeSnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Project cold-wake candidates from one immutable cached edges fold using the local route's canonical host, release.RouteAccount and app. Reads only in-memory route fields, cached publication additions and mirrored signing keys; no filesystem, registry, store or root authority added. Reject malformed placement evidence independently of the unchanged holder decoder; preserve explicit local safety denials even when stale.;rev3=census-ruling-region-ha-home-placement;basis=none: accepts the omitted/empty home placement, refuses explicit null; same in-memory fold reads, no new read;rev3=census-ruling-region-ha-p1b3b-t;basis=Expose fresh compatible peer membership separately from per-host eligible serving entries for suppression invalidation. Existing home/pool/scope filtering remains; no new reads.;rev3=census-ruling-region-ha-p1b3b-s;basis=Delegate to the shared cached projection with no sidecar policy supplied; unknown sidecar policy denies local duty. Ordinary instance candidate policy unchanged. whole:Route@113 550614dc3232bad217462474f382bcc67d6fa45410154babf4bd60033bca50d7
+@legacy 28f04298fb1257fe776a1658e917a06646aa5eda74340cc63215943a2ecde332 internal/host/agent.go haRecordFacts legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new (region HA P1a), the agent as carlos: activator.Config.Record, the closure the HA classification calls on a lifetime index miss: opens the deployment store once (openDeployStore, kept under a mutex) and reads the host's record through judgedRecord(store, judge, release.RouteAccount(rt), rt.App, rt.Host) (CI fix: provision.ReadRecordJudged under the box's lifetime judge, which also GETs the host's incarnation slot control/host-incarnations/<host>.json from the same deployment store; a record the slot no longer vouches for, or a tombstone, reads as os.ErrNotExist; a nil judge, host claims on, is provision.GetRecord exactly), turned into a lifetime entry by provision.LifetimeEntryOf; the reads are the row it is handed (registry:App, registry:Host, whole:Route); the record is the console-written deployment record the reconcile passes already read; an open or read error is returned and the wake fails closed; root never calls it;rev3=census-ruling-stateless-replicas-1;basis=Return RecordFacts with lifetime identity, Coordinator and ReplicaDeploy from the same judged record object; same store and record reads, no extra GET.;rev3=census-ruling-region-ha-p1b3b-s;basis=For sidecars validate synthetic host identity, read the corresponding sidecar record and manifest from the existing deployment store, derive the canonical lifetime and restrictive placement. Failed reads refuse; instance judged reads unchanged. registry:App@1341,registry:App@593,registry:App@823,registry:Host@1349,registry:Host@584,registry:Host@733,whole:Route@1336,whole:Route@622,whole:Route@818 cc373c98ae8baae08212220c0c9a69f608d0430eff7b6826c93b0a40a49e04bf
+internal/activator/activator.go Service.SleepWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-region-ha-p1b3b-s;basis=Refuse an idle-triggered worker stop while producer work holds the existing inflight lease reference; no new read or start authority. registry:Hibernate@187,whole:Route@189,whole:Route@347 1d66d8c4673607ced902c678b139816cdfd98074cf49c29cdf09367ac0fd044b
+internal/activator/haduties.go Service.WithDuty legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Read route host for owned-awake checks and pass provisioned managed instances to restricted singleflight wake before producer writes, including cached legacy rows that discover sticky HA at acquire. Other route kinds keep their path; no authority bypass.;rev3=census-ruling-region-ha-p1b3b-s;basis=Include stamped provisioned sidecars in the existing restricted singleflight wake before producer work. Legacy sidecars remain inline. No new acquire or import protocol. registry:Host@605,registry:Host@694,whole:Route@143,whole:Route@422,whole:Route@524 045e968bc8571eea436bdbaf4c34e1661aad9b5d57cc9cb2ec4abf899341a770
+internal/activator/prepare.go ExecBackend.prepareKeyedAt legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling zddr4, with no further change from this branch beyond carrying main's new early return into the six-value signature. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): body of the frozen prepareAt, which is now its wrapper; it also returns the instance key's layer and reads no env for the cmd role; same reads, same nested launch paths;rev3=census-ruling-wake-latency-2;basis=takes an optional timer and marks its steps with time.Now() (dirs, admin token, instance key, env, control socket, key gate, logs); no read added or moved;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos, run and seed roles only, under a 30 s context (haSecretsBudget): the token producer is ensureAdminTokenFor(hctx, rt, p) (on this nested path the same beneath producer, EnsureAdminTokenBeneath's, plus the HA mint decision inside it); ensureInstanceKeyFor now gets hctx instead of context.Background(), so the key's bucket read is bounded by 30 s as well as configReadTimeout; the env is launchEnvLayer(hctx, rt) (instanceEnvLayer for a non-HA host; for an HA host one capture, published and acknowledged); a test seam (haLaunchHooks.afterGate, nil in production) is called before the producers. The separate haMintGate and haSecretsReady calls are gone (final fix F2). Sites against main: -registry:Host (the rt.Host+".env" argument EnsureAdminTokenBeneath took) and +whole:Route (rt to launchEnvLayer); the cmd role and a non-HA host are unchanged;rev3=census-ruling-rootfs-fleet-followups;basis=names the process for the role log listener: release.ProcessWeb when rt.Rootfs() and the role is run, else none, passed to logEmitter; reads rt.Runtime through Rootfs(); no file, path or env read added or moved;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 8: the cmd role three exceptions (no env read, the replica gate left to StartCmd, no app-log listener) now cover every one-shot role, instancectl.OneShot(role): cmd and tty; before, the tty role fell to the sidecar env-file read and an app-log listener on its handoff socket path; no read added, one removed for tty;rev3=census-ruling-region-ha-p1b3b-s;basis=Native sidecar run units use the existing nested secrets preparation and acknowledged sealed publication, but bind no app control listener. Existing run and seed reads unchanged. file:ReadDir@2965,registry:Host@1783,registry:Host@1995,registry:Host@5905,registry:Host@6103,registry:Host@612,whole:Route@1674,whole:Route@1885,whole:Route@2116,whole:Route@320,whole:Route@4697,whole:Route@5246,whole:Route@5939 c1ba81e8b4a4173d772a8290739122cd30eb9e7807a70ec09e47bccaa4d2ac6f
+internal/activator/unitproc.go ExecBackend.newUnitProcFor legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;basis=the unit is named by unitNameFor(rt, role, gen), one more Route site (+whole:Route), and a role with no unit of the row's kind is refused before anything watches ""; no new read kind and no file read;rev3=census-ruling-region-ha-p1b3b-s;basis=Attach optional per-worker API closers to the existing unit observer before starting it; unit naming and systemd/cgroup proof reads unchanged. registry:Host@323,registry:Host@435,whole:Route@228,whole:Route@364,whole:Route@368 0adbe2c9498f8b2b7848db6765a9af719ccb898f7d077df395cbbabb126c2286
+internal/host/hadepartures_wiring.go armHADepartures legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=B3 fix r1: Install proof adapter, adoption identity and suspicion callbacks before asynchronous startup. Lazily retry the same deployment/data clients; lifetime callback reads only the current host through ExecBackend.TerminationLifetime. Add bounded structured paging for unresolved per-iid records. No new bucket, tenant input path or acquire bypass. B4: Wire the shared lock reader and existing AdoptHost entry. Read local route, Pair and duty revision only after authoritative inventory eligibility; bind its record lifetime and refuse missing/mismatched local routes. No route synthesis or pool widening. B5: Publish the armed controller to the existing metrics sampler. No new loop, remote source or process authority.;rev3=census-ruling-region-ha-followups;basis=Inject the existing PageOperator function into the backend when HA departures are armed; no new read or paging transport.;rev3=census-ruling-region-ha-p3b;basis=Require group admission/BeginWork callbacks and pass them into the sole departure consumer, including the production adoption closure. Same store, identity and registry reads; consumer Started remains a lifecycle fact, not duty authority.;rev3=census-ruling-region-ha-p1b3b-s;basis=Carry the actual provisionTickConfig pools and inbound posture into CanAdopt; stamped sidecars use the existing production adopter. Legacy unresolved paging remains. No wider tenancy or new remote source. registry:Account@3700,registry:Account@7462,registry:App@7489,registry:IID@3721,registry:Incarnation@7649,registry:Pool@7508,registry:Region@3711,registry:Region@7529,registry:Revision@7884,registry:Revision@8281,registry:ServingSeq@7677,whole:DutyState@8003,whole:Pair@7866,whole:Pair@8259,whole:Pair@8265,whole:Route@7449,whole:Route@8158 038ee80fa252d105e9f26ec5449083eb038b3a219c7a888b4068c62221b35ca8
+internal/provision/sidecar_reconcile.go ReconcileSidecars legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=PROPOSED-s3-change-index;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=the record walk and its sidecars manifest lookup move unchanged into the pass's scan closure (over a store argument) and the removal phase into its retire closure; over a record view snapshot, a pass that reaches a removal candidate (a sidecar gone or no longer placeable here) removes nothing on the snapshot's word: it runs scan again over the bucket (freshStore) and decides every removal that pass from that walk, by the walk's own rules (unusable records protected before scope, hosts matched across every key, placement from the bucket's record and sidecars manifest against this box's inbound); a walk that cannot read cleanly keeps every row; with no candidate, or disarmed, nothing is read again; the registry sites are main's, moved; relative to main's single walk a removal can only be withheld, never added;rev3=census-ruling-region-ha-p1b3b-t;basis=B3b: retain validated sidecar records before scope/manifest filtering for coverage, including hidden/out-of-pool records. No new object reads or sidecar HA authority.;rev3=census-ruling-region-ha-p1b3b-s;basis=Derive canonical sidecar lifetimes from account/app/synthetic host/CreatedAt; collect HA and manifest placement for departures before scope filtering; update a separate family in the existing lifetime index. Existing record reads, key parsing and removal authority remain. registry:Account@12676,registry:Account@12915,registry:Account@13868,registry:Account@14618,registry:App@12649,registry:App@12901,registry:App@13841,registry:App@14604,registry:Args@13493,registry:Args@13764,registry:Channel@13481,registry:ClaimOwnership@13294,registry:Host@10270,registry:Host@15954,registry:Host@16001,registry:Host@16124,registry:Host@16301,registry:Host@16450,registry:Host@16557,registry:Kind@12590,registry:Kind@12864,registry:Kind@13781,registry:Kind@14567,registry:Kind@15787,registry:Pool@15905,registry:Provisioned@12622,registry:Provisioned@12879,registry:Provisioned@13813,registry:Provisioned@14582,registry:Provisioned@15814,registry:Region@15855,whole:ClaimOwnership@13297,whole:ClaimOwnership@13314,whole:Route@10252,whole:Route@10263,whole:Route@10281,whole:Route@10467,whole:Route@10836,whole:Route@10845,whole:Route@12278,whole:Route@13139,whole:Route@13146,whole:Route@13214,whole:Route@13549,whole:Route@13926,whole:Route@15772,whole:Route@16367 6e5e0ac9d95dd6d1da61bbe6cda9175e18d53cad4016b083340522f32c92b7f3
+internal/registry/ha_departures.go Registry.ImportHAWake legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Validate all state then transactionally compare current Pair, lifetime, binding, revision and receipt before replacing rows and recording pending authority. Replays never replace rows. B2 fix r1: find replay receipts only within the current binding; an older binding remains history and permits a new guarded import. Preserve Pair/lifetime/revision checks and no authority from import.;rev3=census-ruling-region-ha-p1b3b-s;basis=Permit stamped provisioned hibernating socketless native sidecars through the shared SQL kind predicate while preserving transaction, Pair, lifetime, revision, receipt and binding checks. Import still grants no authority. file:QueryRowContext@1469,file:QueryRowContext@853,registry:DepartureIID@1863,registry:DepartureIID@2524,registry:DepartureIID@394,registry:DepartureRef@1829,registry:DepartureRef@2508,registry:DepartureRef@370,registry:Import@266,registry:Incarnation@1096,registry:Lifetime@1291,registry:Lifetime@1659,registry:Lifetime@2431,registry:Lifetime@418,registry:LockETag@1765,registry:LockETag@2443,registry:LockETag@457,registry:LockGeneration@1793,registry:LockGeneration@2455,registry:LockGeneration@499,registry:Receipt@1642,registry:Receipt@2414,registry:Receipt@438,registry:Receipt@588,registry:Revision@2040,registry:Sequence@2487,registry:ServingSeq@1115,registry:WakeDigest@2473,registry:WakeDigest@477,registry:remote@125,registry:remote@157,whole:HAWakeImport@2124,whole:HAWakeImport@242,whole:HAWakeImport@248,whole:HAWakeImport@317,whole:Pair@1305,whole:Pair@1313,whole:Pair@226,whole:Pair@232,whole:claimTransaction@2114,whole:remoteClient@127,whole:remoteClient@159 8ac56c38e1bcdbb28ef9e62de4e751046d06bb087fbd9fbedbc6400dcb6d9432
+internal/registry/ha_duties.go Registry.BindHADuty legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-t;basis=Compare active route Pair and captured revision before changing its authoritative lifetime binding; clear basis and suppression on change.;rev3=census-ruling-region-ha-p1b3b-s;basis=Use the shared kind predicate to include only stamped provisioned hibernating socketless native sidecars. Existing captured-revision and Pair CAS remain. registry:Changed@295,registry:Incarnation@774,registry:ServingSeq@792,registry:remote@129,registry:remote@161,registry:sql@381,whole:Pair@228,whole:Pair@234,whole:remoteClient@131,whole:remoteClient@163 d870f8b396e7f7362c03de114b72f6ebc2827c92bc5a0bdc16deb7925190d56e
+internal/activator/sidecar_ha.go ExecBackend.listenWorkerAPI legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Bind only the current host run directory agent.sock using the existing nosymfollow nested mount. Restrict claimed host to that route and reuse agentsock token authorization and request limits; no public listener or outbound tenant dial. Unit observer closes it. registry:Host@864 9a6a61887d833f1817723c3386a9b5ef5f7634f5a08ac800aaf76601660cc2d4
+internal/activator/sidecar_ha.go ExecBackend.startHAWorker legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Require nested HA sidecar shape and closed worker identity environment; prepare and acknowledge sealed secrets before writing the existing run launch file. Start the previously verified staged executable through existing root StartExe, mark uncertain starts for stop proof, and observe the same run unit. No health dial or new root verb. registry:Host@1355,registry:Host@1391,registry:Host@1992,registry:Host@270,registry:Host@320,whole:Route@1049,whole:Route@1433,whole:Route@1504,whole:Route@1637,whole:Route@1692,whole:Route@184,whole:Route@2035,whole:Route@853 81ecef01a88e9d25519464c9a099b6d38fca6bab3b5d5083a60cd1fcadbb4715
+internal/activator/unitproc.go unitProc.Crashed legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=For native sidecars only, classify the retained exit record through workerExitStatus after done closes; intentional stops and unknown outcomes are not crashes. No process or lease authority. whole:Route@43 cfddb3d41614ff3dddc86a16550fca701ada3aa5363d781e0d41961261d767aa
+internal/edge/wakeplacement.go Edge.SidecarDutySnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Pass local route and authoritative cached sidecar manifest policy to the existing edges fold projection; no store or request-time membership reads. whole:Route@133 93faaaca0c599fe1925821b8ac6aa39a72ec43f5d925b81c7f33ff4b9dcf6737
+internal/edge/wakeplacement.go homeMap.dutySnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Keep instance host-evidence selection unchanged; sidecars require exact validated served_pools and local policy, compatible fresh scope/bucket/key and admission evidence. No sidecar public Hosts entry or tenant dial. registry:App@2633,registry:Host@1575,whole:Route@1606,whole:Route@2350,whole:Route@810 784c976234f5438bf0075af70a76ff596625fd6fd136de2e14eb78c57377118c
+internal/edge/wakeplacement.go sidecarBoxEligible legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3b-s;basis=Read in-memory route identity, HA/provisioned bit, scope and pool; require canonical socketless native shape, exact served_pools and restrictive inbound policy. Unknown or malformed pool/placement evidence refuses. registry:Account@279,registry:Addr@137,registry:App@271,registry:HA@109,registry:Host@262,registry:Pool@316,registry:Provisioned@90,registry:Region@187,registry:Replica@173,registry:Socket@118,registry:Tunnel@154 e81f6d601f1e0677bce821832a849f8369f24304ed2c59bd408769182dbe0d29
+internal/activator/hawake.go ExecBackend.haContained legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the containment admission: refuses a unit-backed row (+registry:Backing), a row whose layout is not nested, and a box whose nested gate fails (nestedReady); +whole:Route x2; only refuses;rev3=census-ruling-region-ha-p1b3b-s;basis=Refuse HA sidecars with unprovisioned/nonhibernating, dialable, replica, tunnel, runtime or seed shapes before nested containment checks. No fallback or new path read. registry:Addr@139,registry:Backing@308,registry:Hibernate@104,registry:Provisioned@85,registry:Replica@156,registry:Runtime@189,registry:Seed@209,registry:SeedSource@226,registry:Socket@120,registry:Tunnel@170,whole:Route@414,whole:Route@609 b81c997922fabb3dcf8054419cd992c3018334684a9585fe5ec4baec083ca181
+internal/activator/hawake.go haLegacyRoute legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: a route is legacy for HA (sidecar, not provisioned, or a kind other than instance); +registry:Kind, +registry:Provisioned; pure;rev3=census-ruling-region-ha-p1b3b-s;basis=Only stamped provisioned native sidecars join instance classification; unstamped and unprovisioned sidecars remain legacy and cannot take an HA-shaped lock. registry:HA@92,registry:Kind@103,registry:Provisioned@54 cc4a3f5811bf262a82ccb4162156a1c32778ba43a503e8efe1d655ec9d6502a5
+internal/activator/layout.go Classify legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 5: a row with a runtime (LayoutExempt) is never fenced by a layout journal; the journal check now asks LayoutExempt first; the binary path is unchanged;rev3=census-ruling-region-ha-p1b3b-s;basis=Recognize a stamped provisioned socketless sidecar only at its canonical NestedDBPath, retaining collision and layout fences. No dummy socket added. registry:Addr@1457,registry:DBPath@1190,registry:DBPath@1304,registry:DBPath@1602,registry:HA@1429,registry:Host@1103,registry:Host@1165,registry:Host@1239,registry:Host@126,registry:Host@1352,registry:Host@237,registry:Host@853,registry:Host@914,registry:Host@924,registry:Host@963,registry:Host@971,registry:Provisioned@1411,registry:Socket@1251,registry:Socket@1365,registry:Socket@1438,registry:Socket@1613,whole:Route@87,whole:Route@899,whole:Route@952 c08d62fdb590d8445c4a7bc478d83626c42386c0690c60bd0a62e3185b406374
+internal/host/agent.go runAgent authority B,C,D,F rev3=census-ruling-self-serve-moves-1;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): builds the box's lifetime judge once (newBoxJudge, nil with host claims on) and hands it to the seed placement, the moves and runs workers and every loop it starts; read sites unchanged, offsets moved; B,C,D,F authority retained; self-serve moves 1 Task 8: derives the box's lifetimes switch from the judge once (lifetimes := boxJudge != nil) and hands it to the edges file loop; read sites unchanged, offsets moved;rev3=census-ruling-plans-4d-lapse;basis=arms two more plans hooks from the same snapshot: e.SetPlanDisabledFor(planDisabledFor) beside SetPlanGovernedFor, and svc.SetDisabledFor(planDisabledRoute) beside SetMaxRunFor (plans 4d); the reads live in those units (plans-4d-units decision); read sites unchanged, offsets moved;rev3=census-ruling-rootfs-apps-2;basis=main's body as of the merge of origin/main 9b81d97b (with main's plan rate ceiling, edge request records, regional box names, self-serve moves plan 1, plans 4d-1 lapse and its other later changes under main's own census rulings) plus the rootfs placement wiring in the activator start: an agentRootfs built from eb.NestedOK, CARLOS_DEPLOYMENT_SINGLE_TENANT, CARLOS_POOLS, the claim flag, swapArming's answer, the control client's /ready/rootfs and, on a fleet box whose identity resolved, fleetOwnerCheck over the deploy store main already opens for the fleet label (fleetStore), then arm and armedRootfs.Store; this body reads nothing new itself; the closures it wires read later, at a rootfs wake and each status tick: GET /ready/rootfs over the control socket, NestedOK's checks, and release.FleetOwnerKey for the judged row's own account and this box's fleet from the deploy store;rev3=census-ruling-instance-egress-sizes-328-329;basis=#328 plan 2 Tasks 7 and 11, #329 plan 3 Task 7 and plan 1 Task 7's policy cache: the control client is built once and handed to eb.Control, to the status tick (egressStatus) and to a new egressNudgeLoop goroutine; armSizeSource(svc, "/sys/fs/cgroup") after the activator Service; armPolicyCache() after armChangeIndex; statusLoop takes egressStatus. The reads are those units' own (decision rows); this body reads nothing new: the same five sites, offsets moved, in the agent; B,C,D,F authority retained.;rev3=census-ruling-remote-instance-metrics;basis=builds the metrics loop's owners closure (metricsOwners over the agent's registry, the activator and cgm.Leftover) when an activator exists and hands it to metricsLoop; reads nothing new itself;rev3=census-ruling-edge-asset-cache-3;basis=adds file:Statfs. runAgent keeps its authority (B,C,D,F). The new site is assetcache.Statfs, an exported assetcache.FS interface value (var Statfs FS = statfsFS{}), not a function value and not a call in runAgent: the ready hook passes it to armEdgeAssetCache as the store's filesystem, and armEdgeAssetCache calls its Space method on the configured data directory (dataDir(): $CARLOS_DATA_DIR, else /data), which calls unix.Statfs there (statfsFS.Space, accepted legacy at census-ruling-edge-asset-cache-2). No request-supplied pathname reaches it.;rev3=census-ruling-remote-metrics-nested;basis=main's body (merged origin/main acfa4f80, under main's own census rulings) plus: snapshots the nested layout (snapshotNestedUnits over /sys/fs/cgroup/carlos.slice/carlos-instances.slice) once at start, before the activator, and hands the metrics loop a unitSources struct (stamped units, routeHostNames, that root and the snapshot); reads nothing new itself;rev3=census-ruling-region-ha-p1a;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): wires region HA P1a into the activator: cfg.Record = haRecordFacts(openDeployStore, boxJudge) (the box's lifetime judge this body already builds with newBoxJudge, nil with host claims on; CI fix) and cfg.Self = lease.CurrentSelf; eb.Lifetimes (the process's lifetime index), eb.Registry, eb.StartupSwept (seedSweptAtStart.Load), eb.FilesStore from newProductionFilesStore (now lease.NewFilesStore, rootaws-loaded, a log line on failure) and lease.SetObligationDir(<data>/.ha-owed) (logged on failure; HA acquires then refuse); this body reads nothing new itself, the same five sites; the reads are those units' own (haRecordFacts and lease's SetObligationDir are new rows on this card); merge of origin/main d7ae1d76: main's own later changes to this body are kept as main has them, under main's rulings (census-ruling-remote-instance-metrics: the metricsOwners closure for metricsLoop; census-ruling-edge-asset-cache-3: the +file:Statfs site, assetcache.Statfs handed to the asset ready hook); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: builds one termfence.Confirmer (Self from lease.CurrentSelf at each call, EC2 DescribeInstances method only, client from rootaws.LoadDefaultConfig with retries off, built lazily on first use) and sets eb.OwnerTerminated; this body reads nothing new itself, the same six sites;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Task 7: the startup Sweep literal hands its answer to startupSwept, which logs as before and, only on a clean sweep, marks rootfs admission swept (MarkRootfsSwept); same Sweep call, no read added;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): sets svc.Fleet = fleetWakeFor(os.Getenv, identity, identErr, fleetStore) from the identity it already resolves once and the deployment store the fleet loops already opened, and logs an ERROR naming the identity error when the box is on a fleet with an invalid identity. fleetWakeFor reads CARLOS_REGION and CARLOS_FLEET from the same environment. Read sites unchanged (6). Agent, not root; a platform box is unchanged.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 12: one call more beside armRunsPass, armInteractivePass(svc, reg, rolloutSink, boxJudge), in the same activator Configure hook, handing it the same box judge; fix round 1 (Astra P2, shutdown): after svc.Shutdown(ctx), shutdownInteractive(ctx) ends and joins every interactive session under the same shutdown budget; the worker's own reads are its units' (interactive.go); this body reads nothing new, the same six sites; merge of origin/main 6f1f6ca6: main's svc.Fleet = fleetWakeFor(...) and its invalid-identity ERROR line are kept as main has them (census-ruling-managed-fleets-1b); this branch's change is the same as above; read sites unchanged (6);rev3=census-ruling-fix-set-aside-exdev;basis=set-aside EXDEV fix: one field more on the agent ExecBackend literal, RawInstanceDir: layout.RawInstanceDir (a pure path join: <dataDir>/.instances/<InstanceID(host)>), so the start rule set-aside moves a copy out through the raw directory instead of through the nosymfollow bind; this body reads nothing new, the same six sites;rev3=census-ruling-durability-3a-escrow;basis=durability 3a Task 3: one more assignment beside eb.FilesStore: eb.EscrowKey = haEscrowKey(os.Getenv("CARLOS_SECRETS_KEY")), the agent's own environment parsed by appconfig.ParsePrivateKey as the moves pass parses it (unset or unparseable: a log line and nil, and HA publication refuses on the box). No path is opened or read, no read site added; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 4: one more goroutine beside configSyncLoop: go escrowLoop(agentCtx, reg, svc), the escrow sweep every 30 s over the same registry and Service. This body reads nothing new itself; the same six sites, offsets moved; B,C,D,F authority retained. Durability 3a Task 5: one more call beside eb.EscrowKey: wireRawSecretPages(eb, PageOperator, metricsBoxLabel(os.Getenv, readMachineID())), which sets eb.OnRawSecret to page an operator (alerting.Page through PageOperator, LevelIncident) on its own goroutine with a 20 s timeout; metricsBoxLabel and readMachineID are the reads this body already makes for the moves refusal log; no new read site; the same six sites, offsets moved; B,C,D,F authority retained. Merge of origin/main 90c4d3aa: main's own later changes to this body are kept as main has them, under main's rulings; this branch's change is the same as above. Merge of origin/main 00bf5b8c (fleet set-aside EXDEV fix): main's change to this body is kept as main has it, under its own census ruling; this branch's change is unchanged.;rev3=census-ruling-probe-burst-limit;basis=two more sink wirings beside setAnalyticsSink: setProtectionSink(e.SetProtectionRecordOnly) and setAssetOwnersSource(e.AssetOwners), function values the telemetry pass calls; this body reads nothing new, the same six sites; authority B,C,D,F retained; no new root read or write kind;rev3=census-ruling-region-ha-p1b3a;basis=Arm HA placement exactly once on the existing Service before activatorStart and edges publication, wiring AwakeApps and the PageOperator callback; existing six read sites unchanged, no new root authority.;rev3=census-ruling-stateless-replicas-1;basis=Final review I3: start the concrete coordinator's renewal worker with agent setup; existing closeReplicaCoordinator shutdown cancels and joins it before release. No new read sites or credentials. Merge origin/main c59715e7: retain main's armHAPlacement(svc, PageOperator) wiring beside the existing activator setup; stateless coordinator and shutdown wiring remain. Same read sites; no new root read or credential.;rev3=census-ruling-edge-held-streams;basis=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): in the edge-ready callback, calls act.SetHeldWakeHook(e.HeldWake) when act is non-nil (installing the non-blocking wake callback) and stores e.HeldStreamsForStatus in heldStreamsSource. Wiring of in-memory callbacks only; no read added.;rev3=census-ruling-region-ha-p1b3b-t;basis=Wire Service.SetDutyView to the live edge DutySnapshot in the ready callback. No new read; no new loop or cloud operation. B2 wires the registry as the persistent DutyStore before service startup; no new cloud or filesystem path. B3b: arm one journal-backed termination consumer before service startup using agentCtx and the shared confirmer; expose edge tick and join at edge shutdown. No new direct read sites.;rev3=census-ruling-agent-start-demo-1;basis=Passes the existing registry, data store and hibernation prefix into the demo worker, and the existing instance-control client into the demo before-exec hook. No alternate data store or polling loop. Merge resolution against origin/main 9bd45488 retains main's HA departure controller, lifecycle and duty wiring alongside the demo data store and worker; no read site added by the resolution.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: install closed fixed admission before every launch source, bind activator/backend and edge, wire the real termination Started lifecycle and role reader after the change index; close before cancellation/child shutdown. No new external reads or cloud authority. Fix R1: move bind/lifecycle/edge-option wiring into wireAgentAdmission and worker listing into runWorkerBootPassAfterAdmission. Worker boot waits for admission before listing then uses unchanged bounded wakes and per-host serialization; whole Route read moves to the helper. No new storage, cloud, or root execution authority. Preserve merged main's agent wiring and census basis; the branch removes one whole Route use by moving worker iteration to the helper, with no added read kind.;rev3=census-ruling-stateless-replicas-2;basis=Slice 3b: arms a fleet-only worker using the existing registry, activator, backend and authenticated console transport. Owned worker stops and joins at shutdown. No new bucket reader. merge of origin/main 9b8b2c50: retain HA duty/departure lifecycle, wake-slot and existing agent wiring alongside the replica placement worker; no new read introduced by resolution. merge of origin/main 6be08467: Retain main demo configuration, admission, build and expiry wiring alongside the replica worker; merge-only body change, no additional read. merge of origin/main 7920cccf: Retain main box-role/group admission wiring and boot publication beside the owned replica worker and shutdown; main moves the boot registry List into runWorkerBootPassAfterAdmission, removing its inline whole Route site. No new read introduced by conflict resolution.;rev3=census-ruling-stateless-replicas-3;basis=Task 1 fix round 1 M3: retain the private snapshot source and cancel/join ownership, but use the replica-health-specific retry loop. It logs its first failure only and retains the existing exponential backoff capped at 30 seconds; unsupported builds return nil. Existing five direct read sites unchanged; no new credentials, bucket reader or app lifecycle action. Fix round 1 Q20: publish Edge.ReplicaSnapshots as a separate in-memory status source, leaving the tenant-visible Upstreams source unchanged. No new external reader or authority.;rev3=census-ruling-region-ha-p3b;basis=Load root-written group marker/configuration, configure signed boot binding and agent receipt completer, wire cancellable admission into departure work and expose cached GroupReaderSnapshot. New indirect boot reads use protected root files; agent-owned receipt controls duplicate initial completion only, never root restart permission. Same five direct sites. Merge 45cebde4 retains the replica health socket lifecycle and setReplicaSource beside GroupReaderSnapshot; no extra read beyond main.;rev3=census-ruling-agent-start-demo-2;basis=agent.go:309-329 opens demo-traffic.db beside the operator-configured registry when a demo domain exists, closes it at shutdown and wires drain-before-purge; :1010-1019 shares the worker and write gate; :1164-1177 installs the fleet identity and closed-until-worker serving callback. One added whole Route pass; the new indirect filesystem/SQL reads are claimed in openDemoTraffic and worker/store units. No request chooses the database pathname.;rev3=census-ruling-region-ha-p1b3b-s;basis=Wire the service duty view to authoritative cached sidecar manifest placement in LifetimeIndex and the edge sidecar projection; missing policy denies duty. Existing instance duty wiring remains. file:Exec@19019,file:Open@1707,file:Statfs@49766,registry:App@12731,registry:Host@45848,whole:Route@12723,whole:Route@45050,whole:Route@45971,whole:Route@46033 88a9612d2800531fc084c91cf2c4deda22128925226e1d49fcf46fcfecf441e4
+internal/provision/sidecar_reconcile.go convergeSidecar legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-region-ha-p1b3b-s;basis=Converge only the sticky HA bit with SetHA when the record is stamped; no database-path migration or record rewriting. registry:Addr@3573,registry:Addr@3915,registry:Args@1798,registry:Args@1815,registry:Args@1932,registry:Args@1947,registry:Args@1999,registry:Args@2183,registry:Args@2198,registry:Channel@345,registry:Channel@367,registry:Channel@387,registry:Channel@510,registry:Channel@528,registry:Channel@586,registry:Channel@779,registry:Channel@797,registry:DBPath@3514,registry:DBPath@3533,registry:DBPath@3868,registry:DBPath@3885,registry:Environment@1065,registry:Environment@1270,registry:Environment@1292,registry:Environment@822,registry:Environment@846,registry:Environment@977,registry:Environment@999,registry:HA@181,registry:HA@193,registry:Hibernate@1321,registry:Hibernate@1343,registry:Hibernate@1470,registry:Hibernate@1490,registry:Hibernate@1552,registry:Hibernate@1751,registry:Hibernate@1771,registry:IdleSeconds@2495,registry:IdleSeconds@2519,registry:IdleSeconds@2705,registry:IdleSeconds@2751,registry:IdleSeconds@2838,registry:IdleSeconds@3067,registry:IdleSeconds@3113,registry:MaxRunSeconds@2539,registry:MaxRunSeconds@2565,registry:MaxRunSeconds@2727,registry:MaxRunSeconds@2769,registry:MaxRunSeconds@2856,registry:MaxRunSeconds@3089,registry:MaxRunSeconds@3131,registry:Socket@3548,registry:Socket@3898 42a17311a1e34741d2bf588aebd132827a694984df4f5cf81b8b443e840ac2ec
+internal/activator/activator.go Service.begin legacy accepted-legacy accepted-legacy;rev3=census-ruling-carlos-run;basis=Re-digested at the pre-land merge: the body includes main's own change under census ruling 292, with no further change from this branch. the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos): main's body; the stop now carries its reason for a run it interrupts (beginStopLocked's why argument); read sites unchanged, offsets moved;rev3=census-ruling-edge-request-records;basis=gains a req *http.Request parameter and one edge.MarkWoke(req) call on the path that starts a wake, so the edge's request record can say which request woke the app; no read added;rev3=census-ruling-remote-instance-metrics;basis=the entries-map insertion goes through putEntryLocked (which also notes the route's tenant in memory for the metrics sampler); no read added;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: before an entry is made, a resident inside its backoff answers errResidentBackoff, and a rootfs row must pass the locked admission (rootfsRefusalLocked) and then the backend's rootfs gates off a.mu (rootfsStartRefusal, within the request's wait bound) before Acquire, Restore or the live link; the gate key is recorded on the entry; adds refusals before the lease only;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Read serving lease health through servingError: stateless generations use local lifecycle/process supervision, while stateful generations keep the existing lease checks. No new I/O.;rev3=census-ruling-region-ha-p1b3b-t;basis=Carry background-duty provenance into a new singleflight entry; a visitor waiting on its deferred refusal retries with ordinary visitor authority. No read added.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: check local tenant admission and start permission before lease/restore, preserving already-awake reuse during drain and existing serialization. Whole Route passes to the local predicate; no new filesystem or store read.;rev3=census-ruling-region-ha-p1b3b-s;basis=Construct a worker entry for sidecar producer wakes inside the same singleflight and inflight reference machinery; passes whole route to newWorkerEntry, no new data read. registry:Host@1240,registry:Host@1780,registry:Host@3836,registry:Host@4098,registry:Host@656,whole:Route@1302,whole:Route@1413,whole:Route@177,whole:Route@2334,whole:Route@2421,whole:Route@2502,whole:Route@2763,whole:Route@2873,whole:Route@3047,whole:Route@3845,whole:Route@3852,whole:Route@4021 5bbcaf73959e3a648ce9dd2e7d58e452c494e607585729d28e91d782969cf698
+internal/activator/backend_exec.go ExecBackend.StartWorkerStaged legacy accepted-legacy accepted-legacy;rev3=census-ruling-zddr3;basis=Census ruling zddr3: changed legacy row (comment-only change describing the shim placement); the same class as the accepted-legacy Manager.startIn and placementLive under fix1-merge-review (existing agent delegated-cgroup management remains legacy); no root decision; no registry, /data, release or claim reads. Boundary: the agent's own delegated cgroup subtree (including its scratch probe child), /proc/self, and pipes to and from its own parent, running as carlos.;rev3=census-ruling-stateless-replicas-1;basis=Task 3a: Use the verified generation/launch mode to remove CARLOS_DB after environment merges and omit the binary --db argument where applicable. Existing runtime, layout, secrets and exec gates remain; route reads are mode projection only.;rev3=census-ruling-region-ha-p3a;basis=P3a Task 3: add/recheck the local start prohibition on generation, worker, sidecar, command or root-control launch, including retained leases; preserve existing lease/ownership checks and fixed-unit exemptions. Whole Route passes to the in-memory predicate; no new filesystem/store read.;rev3=census-ruling-region-ha-p1b3b-s;basis=Require acquired HA lifetime and containment for stamped sidecars; after the existing staged build verification, dispatch their worker launch through startHAWorker. Legacy worker exec and parent co-spawn remain unchanged. file:Command@4150,registry:Args@727,registry:Args@878,registry:Host@1089,registry:Host@1185,registry:Host@1888,registry:Host@1963,registry:Host@3253,registry:Host@4289,registry:Host@5175,registry:Host@561,registry:Host@869,registry:Host@973,whole:Route@1648,whole:Route@2032,whole:Route@206,whole:Route@2335,whole:Route@242,whole:Route@2881,whole:Route@332,whole:Route@4102,whole:Route@4220,whole:Route@4250,whole:Route@446,whole:Route@5016,whole:Route@5106 0944d09366a4f90c8ac7086c1d5a56c07eb95950840e4b2dac08df9bcda822bd
+internal/activator/genbackend.go ExecBackend.EmptyHost legacy accepted-legacy accepted-legacy;rev3=fix1-merge-review;basis=Checks agent-owned host cleanup before lease release; no root authority is derived from it.;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 N1: refuses a row with a runtime first (refuseHostCgroupProof); the cgroup open moves into openHostCgroup (same delegation check and OpenCleanup, with the test seam); reads Runtime;rev3=census-ruling-region-ha-p1b3b-s;basis=For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone instead of treating its flat cgroup as its process tree; other shapes retain prior proof. registry:Host@274,registry:Host@524,whole:Route@113,whole:Route@172,whole:Route@212 e3e5fc9557cbea81c44acd4a4f45a58336a51e43c758566ad99c67f069a57ad2
+internal/activator/genbackend.go ExecBackend.KillHost legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 N1: refuses a row with a runtime first (refuseHostCgroupProof); the cgroup open moves into openHostCgroup (same delegation check and OpenCleanup); reads Runtime;rev3=census-ruling-region-ha-p1b3b-s;basis=For a nested native sidecar, stop and prove its existing run unit via LegacyRunGone; no new root verb or new unit naming. Flat workers retain the existing cgroup proof. registry:Host@273,whole:Route@112,whole:Route@171,whole:Route@211 58bfd9405f7dfbac4bee75fc67b26650929b11b7486b369a99c2c8f926deba5b
+internal/activator/hawake.go ExecBackend.acquireClassified legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new: the acquire's classification: a legacy route (sidecar, hand-added or not an instance) takes lease.Acquire and refuses on an HA-format lock; otherwise isHA (a record read error fails the wake, never falls back to legacy); not HA takes lease.Acquire, and an HA-format lock there marks the host HA for good and continues; HA requires haContained before any lock request, then lease.AcquireHA with the same-box proof; held and refused leases map to errLeaseHeld and errLeaseRefused (leaseError); +registry:Host, +whole:Route x7;rev3=census-ruling-region-ha-p1b1;basis=region HA P1b-1: the HA acquire's Proofs gain OwnerTerminated (b.ownerTerminated(ctx, rt)) beside SameBoxEmpty; one more whole:Route site passes the route to ownerTerminated; nothing new is read; the proof is consulted only by hafresh.DecideAcquire for another box's expired HA lock;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (Task 7, two-box fleet test): the two legacy acquires call b.acquireLegacy(ctx, prefix), which is acquireLegacyLease exactly when ExecBackend.LeaseIdentity is nil and LeaseTTL is 0 (the agent never sets them), otherwise lease.AcquireAs with that identity and TTL. The classification, the HA path and every refusal are unchanged. Read sites unchanged (9). Agent, not root.;rev3=census-ruling-region-ha-p1b3b-t;basis=Select the restriction-only AcquireHAForDuty for background contexts, including sticky HA reclassification; observe successful ordinary acquires to clear stale suppression. Add a whole-route observer argument; no new authority. B2 binds the current authoritative lifetime and advances local revision before HA acquire, invalidating concurrent adoption I/O. Ordinary lease authority and restore ordering remain unchanged. B2 fix r1: advance the local duty revision with an unconditional registry UPDATE before acquire; remove pre-acquire lifetime CAS and basis clearing. Failed acquire preserves adopted state. Existing lease validation and successful-acquire observer remain. B3: pass the same optional durable termination proof adapter to visitor and duty acquires. Nil retains the existing path until controller arming; configured proof failures refuse, with no fallback to a live boolean. No new read in this unit. Final fix P2-1: copy the shared proof adapter per acquire to attach the existing takeover telemetry; retain a live confirmer fallback for unverified identities. Existing classified owner, lifetime, expiry and CAS guards remain.;rev3=census-ruling-agent-start-demo-1;basis=Reads demo shape/layout and takes the existing legacy renewing lease for demos; never falls through to HA acquisition. Merge integration against origin/main 9bd45488 retains main's HA duty/termination proof wiring after the demo legacy-lease branch; the added whole-route passes are main's existing checks.;rev3=census-ruling-region-ha-p1b3b-s;basis=Before any HA sidecar write require a known canonical lifetime, files store and valid shared sealer; unstamped sidecars cannot upgrade from an HA lock. Reuse existing containment, AcquireHAForDuty, restore and release paths. registry:Host@106,whole:Route@1064,whole:Route@1115,whole:Route@1365,whole:Route@1668,whole:Route@1964,whole:Route@2181,whole:Route@221,whole:Route@2226,whole:Route@2381,whole:Route@278,whole:Route@3182,whole:Route@3278,whole:Route@589,whole:Route@627 39023dbc194a371ed5f5318f3bc28adbcac4f281577b0ad30a091d3727897d56
+internal/activator/unitproc.go ExecBackend.observe legacy accepted-legacy accepted-legacy;rev3=J1;basis=root-route;rev3=census-ruling-rootfs-apps-2;identity=the agent (/opt/carlos/carlos agent, carlos-edge.service, user carlos);basis=final fix I3: the process observer's termination proof for a rootfs handle (Runtime, the new kind, one site) goes through unitEvents (two more Route sites): the host slice's cgroup.events and, for a rootfs unit, the group systemd reports when that is elsewhere, so a foreign invocation root placed outside the slice and could not stop is never read as gone from the absent expected path; a failed stop of a foreign invocation leaves it unstopped, asked again next poll, completion pending; a binary handle's proof is unchanged (cgroup.events under the host slice); the agent decides only whether it keeps a handle and a launch file; no root decision; re-digested at the merge of origin/main 3c33f2eb: main's own change to the observer is in the body, this branch's rootfs-aware evidence and the rootfs-only failed-stop retry (merge prep N1: a binary handle behaves exactly as main) on top; the kinds are the union;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W, W1: for a worker handle (p.worker != "") the observer keeps the exit record it read (workerExit, workerExitOK) for the supervisor instead of wording a member event, and says nothing for a replaced-after-stop or restarted-outside end; the termination evidence (cgroup.events via unitEvents, the foreign-invocation rule) and the record's single-use removal are unchanged and apply to a worker as to a generation; a binary or generation handle behaves exactly as before; the same 22 read sites, no read added;rev3=census-ruling-rootfs-worker-exit;basis=an exit record with an empty code (read and bounded as before) is filled by unitMainExitOf before it is kept for a worker or worded for the member; the termination proof (UnitState, cgroup evidence, the foreign-invocation rule) and the record's single-use removal are unchanged; the same 22 read sites, no read added;rev3=census-ruling-region-ha-p1b3b-s;basis=Retain the already-read advisory exit record for native sidecars after the same systemd and cgroup termination proof; crash classification never substitutes for stop proof. No new read source. registry:Host@1222,registry:Host@3062,registry:Host@3252,registry:Host@3599,registry:Host@3825,registry:Host@4529,registry:Host@6006,registry:Runtime@2414,registry:Runtime@806,whole:Route@1224,whole:Route@2222,whole:Route@2416,whole:Route@3064,whole:Route@3254,whole:Route@3601,whole:Route@3827,whole:Route@4531,whole:Route@4787,whole:Route@5080,whole:Route@5558,whole:Route@6008,whole:Route@808,whole:Route@972 af7f350e623184734d2ba99964a3c39b3d34775f04238f906efca436c335bb79
+internal/edge/wakeplacement.go homeMap.wakeSnapshot legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Project cold-wake candidates from one immutable cached edges fold using the local route's canonical host, release.RouteAccount and app. Reads only in-memory route fields, cached publication additions and mirrored signing keys; no filesystem, registry, store or root authority added. Reject malformed placement evidence independently of the unchanged holder decoder; preserve explicit local safety denials even when stale.;rev3=census-ruling-region-ha-home-placement;basis=none: accepts the omitted/empty home placement, refuses explicit null; same in-memory fold reads, no new read;rev3=census-ruling-region-ha-p1b3b-t;basis=Expose fresh compatible peer membership separately from per-host eligible serving entries for suppression invalidation. Existing home/pool/scope filtering remains; no new reads.;rev3=census-ruling-region-ha-p1b3b-s;basis=Delegate to the shared cached projection with no sidecar policy supplied; unknown sidecar policy denies local duty. Ordinary instance candidate policy unchanged. whole:Route@113 550614dc3232bad217462474f382bcc67d6fa45410154babf4bd60033bca50d7
+internal/host/agent.go haRecordFacts legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1a;basis=new (region HA P1a), the agent as carlos: activator.Config.Record, the closure the HA classification calls on a lifetime index miss: opens the deployment store once (openDeployStore, kept under a mutex) and reads the host's record through judgedRecord(store, judge, release.RouteAccount(rt), rt.App, rt.Host) (CI fix: provision.ReadRecordJudged under the box's lifetime judge, which also GETs the host's incarnation slot control/host-incarnations/<host>.json from the same deployment store; a record the slot no longer vouches for, or a tombstone, reads as os.ErrNotExist; a nil judge, host claims on, is provision.GetRecord exactly), turned into a lifetime entry by provision.LifetimeEntryOf; the reads are the row it is handed (registry:App, registry:Host, whole:Route); the record is the console-written deployment record the reconcile passes already read; an open or read error is returned and the wake fails closed; root never calls it;rev3=census-ruling-stateless-replicas-1;basis=Return RecordFacts with lifetime identity, Coordinator and ReplicaDeploy from the same judged record object; same store and record reads, no extra GET.;rev3=census-ruling-region-ha-p1b3b-s;basis=For sidecars validate synthetic host identity, read the corresponding sidecar record and manifest from the existing deployment store, derive the canonical lifetime and restrictive placement. Failed reads refuse; instance judged reads unchanged. registry:App@1341,registry:App@593,registry:App@823,registry:Host@1349,registry:Host@584,registry:Host@733,whole:Route@1336,whole:Route@622,whole:Route@818 cc373c98ae8baae08212220c0c9a69f608d0430eff7b6826c93b0a40a49e04bf
+@coverage internal/activator 1ad9943b783987ece2afe52f7417a47ee2d5a32c8c5124d98ecc96bb4969f530
+@coverage internal/edge 165bbbed17bb51e76725b95e5372ba03350d60c7da875dbc2f019c62991c17a1
+@coverage internal/edgesfile a2041337925238e99e717e2f0a6d560a2690fe155c5b878761cc2fb76b525305
+@coverage internal/host ffda39cd16b5ee11667f458b7dc0fece15c42ea647425175dbe6c178087ee85c
+@coverage internal/provision 0543f5b5b878f39845e049a46017fc7db52d5367ce4c5d46a813639f5b993519
+@coverage internal/registry fa4521155ba95536f03982765e2097a80168c5b98ac4758dfc2eb043504bdba6
diff --git a/internal/registry/ha_departures.go b/internal/registry/ha_departures.go
index 9a9879534..9a85936f8 100644
--- a/internal/registry/ha_departures.go
+++ b/internal/registry/ha_departures.go
@@ -236,15 +236,16 @@ func (r *Registry) ImportHAWake(ctx context.Context, host string, expected Pair,
var active bool
var binding uint64
var pair Pair
- var hold, kind string
- err = tx.QueryRowContext(ctx, `SELECT d.lifetime,d.revision,d.active,d.binding,r.incarnation,r.serving_seq,r.hold_op,r.kind FROM ha_duties d JOIN routes r ON r.host=d.host WHERE d.host=?`, host).Scan(&life, &revision, &active, &binding, &pair.Incarnation, &pair.ServingSeq, &hold, &kind)
+ var hold string
+ var supported bool
+ err = tx.QueryRowContext(ctx, `SELECT d.lifetime,d.revision,d.active,d.binding,r.incarnation,r.serving_seq,r.hold_op,`+haDutyKindSQL+` FROM ha_duties d JOIN routes r ON r.host=d.host WHERE d.host=?`, host).Scan(&life, &revision, &active, &binding, &pair.Incarnation, &pair.ServingSeq, &hold, &supported)
if errors.Is(err, sql.ErrNoRows) {
return ImportDeferred, nil
}
if err != nil {
return ImportDeferred, err
}
- if !active || life != s.Lifetime || pair != expected || hold != "" || kind != "instance" {
+ if !active || life != s.Lifetime || pair != expected || hold != "" || !supported {
return ImportDeferred, nil
}
var etag string
diff --git a/internal/registry/ha_duties.go b/internal/registry/ha_duties.go
index b20aff9ff..839b2c96f 100644
--- a/internal/registry/ha_duties.go
+++ b/internal/registry/ha_duties.go
@@ -7,6 +7,8 @@ import (
"time"
)
+const haDutyKindSQL = "(kind='instance' OR (kind='sidecar' AND ha=1 AND provisioned=1 AND hibernate=1 AND socket='' AND addr='' AND tunnel='' AND replica=0 AND backing='' AND runtime='' AND import_gate=''))"
+
var ErrHAChanged = errors.New("ha_state_changed")
type DutyState struct {
@@ -102,7 +104,7 @@ func (r *Registry) BindHADuty(ctx context.Context, host string, pair Pair, lifet
return false, ErrHAChanged
}
res, err := r.sql.ExecContext(ctx, `UPDATE ha_duties SET lifetime=?,revision=revision+1,binding=binding+1,basis='',holder_ref='',holder_iid='',view_key='',holder_epoch=0,not_before=''
- WHERE host=? AND active=1 AND revision=? AND lifetime<>? AND EXISTS(SELECT 1 FROM routes WHERE host=? AND incarnation=? AND serving_seq=? AND kind='instance' AND hold_op='')`, lifetime, host, revision, lifetime, host, pair.Incarnation, pair.ServingSeq)
+ WHERE host=? AND active=1 AND revision=? AND lifetime<>? AND EXISTS(SELECT 1 FROM routes WHERE host=? AND incarnation=? AND serving_seq=? AND `+haDutyKindSQL+` AND hold_op='')`, lifetime, host, revision, lifetime, host, pair.Incarnation, pair.ServingSeq)
if err != nil {
return false, err
}