carlos / platform Public

region-ha p1b-3a: route cold wakes through front-door choice

Apply the pure placement rule after existing holder and live-entry checks.
Retain bounded lock observations, track failed placement peers by epoch,
and preserve ordinary HA acquire and termination recovery. Wire awake-app
publication and throttled capacity pages before agent startup.

Validation: targeted tests and race pass; full activator/edge pass. Host
has the same 21 lifecycle-provider failures recorded under R3. Native,
darwin/arm64 and windows/amd64 builds, vet and census checks pass.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev ffc659c97b9da80ef839a56c85f69f8bfdb83c9b parent fd1bc15
20 files changed, +1,415 −126
  • docs/superpowers/notes/census-proposal-region-ha-p1b3a.md +17 −2
  • docs/superpowers/notes/census-region-ha-p1b3a-claims.md +5 −0
  • internal/activator/activator.go +4 −1
  • internal/activator/hacache.go +174 −51
  • internal/activator/haforward.go +58 −27
  • internal/activator/haforward_test.go +17 −17
  • internal/activator/haplacement.go +203 −0
  • internal/activator/haplacement_peers.go +101 −0
  • internal/activator/haplacement_test.go +595 −0
  • internal/activator/hasuspect_test.go +6 −6
  • internal/edge/forwardha.go +35 −5
  • internal/edge/forwardha_test.go +11 −8
  • internal/edge/haplacement_test.go +78 −0
  • internal/edge/wakeplacement.go +1 −0
  • internal/host/agent.go +1 −0
  • internal/host/haforward_wiring_test.go +1 −1
  • internal/host/haplacement.go +18 −0
  • internal/host/haplacement_wiring_test.go +74 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv +15 −7
diff --git a/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md b/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md
index ee32978f5..f3702304f 100644
--- a/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md
+++ b/docs/superpowers/notes/census-proposal-region-ha-p1b3a.md
@@ -1,16 +1,31 @@
# Census approval: region-ha-p1b3a
-Ruling `census-ruling-region-ha-p1b3a`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+Ruling `census-ruling-region-ha-p1b3a`. The independent reviewer approves or rejects every change below, 3 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` `type Service` | body | unchanged (0) | Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority. |
+| `internal/host/agent.go` `runAgent` | body | unchanged (6) | 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. |
+| `internal/activator/haforward.go` `Service.ForwardTarget` | sites | +registry:Host ×2, +whole:Route ×3 | Retain immutable lock observations and evaluate the pure placement rule after all existing bypass and positive-holder/suspect checks. Read in-memory route Host and whole Route for snapshot/decision only; same bounded lock read, no new store or filesystem operation and no acquire authority. |
+| `internal/edge/forwardha.go` `Edge.frontForwardHA` | sites | +whole:Route | Pass the existing route to a lazy cached wakeSnapshot closure, handle explicit local denial before all accounting, and refuse a disappeared Placement choice rather than falling through locally; whole Route read only, no new store or filesystem operation and no root authority. |
Envelopes re-pinned: `internal/activator`, `internal/boxchoice`, `internal/edge`, `internal/host`.
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` `type Service`: authority, task B,C,D,F,J4. Basis: rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above
+- `internal/host/agent.go` `runAgent`: authority, task B,C,D,F. Basis: 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
+- `internal/activator/haforward.go` `Service.ForwardTarget`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=Returns edge.ForwardDecision (Ref, Refuse, Gen) from holderCache.resolve, in memory only: a suspect holder refuses; a positive entry forwards under its generation; a failed read that revalidates an expired suspect keeps it suspect and refuses. The round-1 cache connection gate is removed. The same single bounded (2 s) lock.json read through readHolderView on a miss; no new read and no new S3 request; root never calls it.
+- `internal/edge/forwardha.go` `Edge.frontForwardHA`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it.
+
New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
- new `internal/activator/awakeapps.go:Service.AwakeApps`: reads +registry:App, +whole:Route ×2; written legacy, accepted-legacy, frozen
+- new `internal/activator/haplacement.go:DecidePlacement`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen
- new `internal/edge/wakeplacement.go:homeMap.wakeSnapshot`: reads +registry:App, +registry:Host, +whole:Route; written legacy, accepted-legacy, frozen
-Seal: `5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc` → `d7a408934310184a8a042d299cd6456060460a95d5707d03af6dd28d93484cc7`.
+Seal: `5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc` → `ff762f68961a754609f209d3a2e6f6ddef46f67eb860e511bd538c5a2ded2580`.
Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-region-ha-p1b3a-claims.md b/docs/superpowers/notes/census-region-ha-p1b3a-claims.md
index afef3b5dd..102f9fd54 100644
--- a/docs/superpowers/notes/census-region-ha-p1b3a-claims.md
+++ b/docs/superpowers/notes/census-region-ha-p1b3a-claims.md
@@ -1,2 +1,7 @@
internal/activator/awakeapps.go:Service.AwakeApps Count owned awake entries under the service mutex by release.RouteAccount(route)/route.App, validating the resolved account and app. Reads in-memory route values only; no store, registry or filesystem call and no new root authority.
internal/edge/wakeplacement.go:homeMap.wakeSnapshot 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.
+internal/activator/activator.go:type Service Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority.
+internal/host/agent.go:runAgent 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.
+internal/activator/haforward.go:Service.ForwardTarget Retain immutable lock observations and evaluate the pure placement rule after all existing bypass and positive-holder/suspect checks. Read in-memory route Host and whole Route for snapshot/decision only; same bounded lock read, no new store or filesystem operation and no acquire authority.
+internal/edge/forwardha.go:Edge.frontForwardHA Pass the existing route to a lazy cached wakeSnapshot closure, handle explicit local denial before all accounting, and refuse a disappeared Placement choice rather than falling through locally; whole Route read only, no new store or filesystem operation and no root authority.
+internal/activator/haplacement.go:DecidePlacement Pure applicability rule reads in-memory route Host/App and RouteAccount for capacity preference, self/expired-owner recovery and explicit LocalDenied refusal; no proof, acquire, store, filesystem or root authority, and no guessed free observation.
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index ec98f5ae3..7e82990a6 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1309,7 +1309,10 @@ type Service struct {
// holders is the region HA holder cache (hacache.go): for a born-HA
// host held by another box, which one, so the edge forwards there.
- holders holderCache
+ holders holderCache
+ peers placementPeers
+ placementLog placementDiagnostics
+ OnHAOverCapacity func(region, host, ref string)
// lifeCtx is cancelled by Shutdown: the seam that lets an in-flight worker
// spawn be TORN DOWN rather than waited out. See Shutdown for why waiting
diff --git a/internal/activator/hacache.go b/internal/activator/hacache.go
index 520e1b923..ccf618495 100644
--- a/internal/activator/hacache.go
+++ b/internal/activator/hacache.go
@@ -3,6 +3,8 @@ package activator
import (
"container/list"
"context"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
"sync"
"time"
)
@@ -56,7 +58,10 @@ type holderEntry struct {
expires time.Time
// gen is the entry's generation, new with every put and every answer
// from ref: a forward's failure counts only under it.
- gen uint64
+ gen uint64
+ view *hafresh.View
+ attempt string
+ kind edge.ForwardKind
}
// holderFlight is one lock read in flight for a host. stale is set when
@@ -68,6 +73,7 @@ type holderEntry struct {
type holderFlight struct {
done chan struct{}
ref string
+ view *hafresh.View
suspect string
refuse bool
cached bool
@@ -190,6 +196,8 @@ func (c *holderCache) putLocked(host, ref string, suspect bool, ttl time.Duratio
if el := c.holders[host]; el != nil {
e := el.Value.(*holderEntry)
e.ref, e.suspect, e.expires, e.gen = ref, suspect, expires, c.seq
+ e.view, e.attempt = nil, ""
+ e.kind = edge.Holder
c.order.MoveToBack(el)
return
}
@@ -214,23 +222,35 @@ func (c *holderCache) removeLocked(el *list.Element) {
// the box suspect for another window and refuses its callers; a read
// overtaken by news sends its callers to look again, within twice the
// read's timeout in all.
-func (c *holderCache) resolve(ctx context.Context, host string, read func() (ref string, ok bool)) (string, bool, uint64) {
+type holderRead struct {
+ Ref string
+ View *hafresh.View
+ Err error
+}
+type holderResolution struct {
+ Ref string
+ Refuse bool
+ Gen uint64
+ View *hafresh.View
+}
+
+func (c *holderCache) resolve(ctx context.Context, host string, read func() holderRead) holderResolution {
deadline := time.Now().Add(2 * holderReadTimeout)
for time.Now().Before(deadline) {
+ if ctx.Err() != nil {
+ return holderResolution{}
+ }
c.mu.Lock()
suspect := ""
if el := c.holders[host]; el != nil {
e := el.Value.(*holderEntry)
if c.clock().Before(e.expires) {
- ref, refuse, gen := e.ref, e.suspect, e.gen
+ r := holderResolution{Ref: e.ref, Refuse: e.suspect, Gen: e.gen, View: e.view}
c.mu.Unlock()
- if refuse {
- return "", true, 0
- }
- if ref == "" {
- return "", false, 0
+ if r.Refuse {
+ return holderResolution{Refuse: true}
}
- return ref, false, gen
+ return r
}
if e.suspect {
suspect = e.ref
@@ -238,59 +258,162 @@ func (c *holderCache) resolve(ctx context.Context, host string, read func() (ref
c.removeLocked(el)
}
f := c.flights[host]
- if f != nil {
- c.mu.Unlock()
- select {
- case <-f.done:
- case <-ctx.Done():
- return "", false, 0
+ if f == nil {
+ // Bound detached reads as well as completed observations.
+ if len(c.flights) >= holderCacheMax {
+ c.mu.Unlock()
+ return holderResolution{}
}
- } else {
f = &holderFlight{done: make(chan struct{}), suspect: suspect}
if c.flights == nil {
c.flights = map[string]*holderFlight{}
}
c.flights[host] = f
- c.mu.Unlock()
- c.runRead(host, f, read)
+ go c.runRead(host, f, read)
+ }
+ c.mu.Unlock()
+ select {
+ case <-f.done:
+ case <-ctx.Done():
+ return holderResolution{}
}
- switch {
- case f.refuse:
- return "", true, 0
- case f.cached, f.stale:
+ if f.refuse {
+ return holderResolution{Refuse: true}
+ }
+ if f.cached || f.stale {
continue
}
- return f.ref, false, 0
+ return holderResolution{Ref: f.ref, View: f.view}
}
- return "", false, 0
+ return holderResolution{}
}
-// runRead runs f's read for host and settles f: its answer cached, unless
-// news arrived while it ran (stale), or kept from caching when it could not
-// tell.
-func (c *holderCache) runRead(host string, f *holderFlight, read func() (string, bool)) {
- ref, ok := "", false
- defer func() {
- c.mu.Lock()
- // Out of the map first, so the puts below do not mark f stale.
- delete(c.flights, host)
- switch {
- case f.stale:
- case ok && ref != "":
- c.putLocked(host, ref, false, holderPositiveTTL)
- f.cached = true
- case ok:
- c.putLocked(host, "", false, holderNegativeTTL)
- f.cached = true
- case f.suspect != "":
- // A failed read proves no holder gone: the box that did not
- // answer stays suspect for another window.
- c.putLocked(host, f.suspect, true, holderSuspectTTL)
- f.refuse = true
+func (c *holderCache) runRead(host string, f *holderFlight, read func() holderRead) {
+ r := read()
+ c.mu.Lock()
+ delete(c.flights, host)
+ switch {
+ case f.stale:
+ case r.Err == nil && r.View != nil:
+ ttl := holderNegativeTTL
+ if r.Ref != "" {
+ ttl = holderPositiveTTL
}
- f.ref = ref
- c.mu.Unlock()
- close(f.done)
- }()
- ref, ok = read()
+ c.putLocked(host, r.Ref, false, ttl)
+ c.holders[host].Value.(*holderEntry).view = r.View
+ f.cached = true
+ case f.suspect != "":
+ c.putLocked(host, f.suspect, true, holderSuspectTTL)
+ f.refuse = true
+ }
+ f.ref, f.view = r.Ref, r.View
+ c.mu.Unlock()
+ close(f.done)
+}
+
+// placement correlates a hint without changing the observation's deadline.
+// A subsequent request always decides again, regardless of this attempt tag.
+func (c *holderCache) placement(host, ref string, kind edge.ForwardKind, gen uint64) uint64 {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ el := c.holders[host]
+ if el == nil {
+ return 0
+ }
+ e := el.Value.(*holderEntry)
+ if e.ref != "" || (e.gen != gen && (e.attempt != ref || e.kind != kind)) || !c.clock().Before(e.expires) {
+ return 0
+ }
+ if e.attempt != ref || e.kind != kind {
+ c.seq++
+ e.gen = c.seq
+ }
+ e.attempt, e.kind = ref, kind
+ return e.gen
+}
+
+// hintResult ignores outcomes superseded by another choice or local acquire.
+func (c *holderCache) hintResult(host, self string, res edge.ForwardResult, accepted func()) bool {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ el := c.holders[host]
+ if el == nil {
+ return false
+ }
+ e := el.Value.(*holderEntry)
+ if res.Gen == 0 || e.gen != res.Gen || e.ref != "" || e.attempt != res.Ref || e.kind != res.Kind || !c.clock().Before(e.expires) {
+ return false
+ }
+ if res.Holder != "" && res.Holder != holderNone {
+ if res.Holder == self {
+ c.removeLocked(el)
+ } else {
+ c.putLocked(host, res.Holder, false, holderPositiveTTL)
+ }
+ } else if res.Outcome == edge.ForwardDone && (res.Status == 101 || res.Status >= 200 && res.Status < 400) && res.Holder != holderNone {
+ c.seq++
+ e.gen = c.seq
+ }
+ accepted()
+ return true
+}
+
+// holderResult retains P1b-2 outcomes while rejecting superseded generations.
+func (c *holderCache) holderResult(host, self string, res edge.ForwardResult, accepted func()) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ el := c.holders[host]
+ if res.Gen != 0 && (el == nil || el.Value.(*holderEntry).gen != res.Gen) {
+ // P1b-2 lets a still-outstanding answer clear this same true holder's
+ // suspicion. A newer holder, negative observation or acquire stands.
+ if el == nil {
+ return
+ }
+ e := el.Value.(*holderEntry)
+ if !e.suspect || e.ref != res.Ref || res.Outcome != edge.ForwardDone || (res.Holder == "" && res.Status == 0) {
+ return
+ }
+ }
+ accepted()
+ drop := func() {
+ if el := c.holders[host]; el != nil {
+ c.removeLocked(el)
+ }
+ if f := c.flights[host]; f != nil {
+ f.stale = true
+ }
+ }
+ switch {
+ case res.Outcome == edge.ForwardNotInView:
+ drop()
+ case res.Outcome == edge.ForwardUnreachable:
+ if el != nil && res.Gen != 0 {
+ e := el.Value.(*holderEntry)
+ if e.ref != "" && !e.suspect {
+ c.putLocked(host, e.ref, true, holderSuspectTTL)
+ }
+ }
+ case res.Holder == holderNone:
+ drop()
+ case res.Holder != "":
+ if res.Holder == self {
+ drop()
+ } else {
+ c.putLocked(host, res.Holder, false, holderPositiveTTL)
+ }
+ case res.Status == 503:
+ drop()
+ case res.Status != 0 && res.Ref != "":
+ if el != nil {
+ e := el.Value.(*holderEntry)
+ if e.suspect {
+ c.putLocked(host, res.Ref, false, holderPositiveTTL)
+ } else if e.ref == res.Ref {
+ c.seq++
+ e.gen = c.seq
+ }
+ } else if f := c.flights[host]; f != nil && f.suspect != "" && !f.stale {
+ c.putLocked(host, res.Ref, false, holderPositiveTTL)
+ }
+ }
}
diff --git a/internal/activator/haforward.go b/internal/activator/haforward.go
index 9d0240102..b435fbfa6 100644
--- a/internal/activator/haforward.go
+++ b/internal/activator/haforward.go
@@ -8,6 +8,7 @@ import (
"sync/atomic"
"time"
+ "github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/edge"
"github.com/carlosframework/platform/internal/hafresh"
"github.com/carlosframework/platform/internal/lease"
@@ -23,7 +24,7 @@ import (
// X-Carlos-Holder, so the forwarding box can follow the lease
// (answerForwarded).
//
-// Nothing here can keep a host from being served for long. A named box
+// True holder entries retain P1b-2 behavior. A named box
// that is out of view, answers "none", or answers 503 without naming
// anyone is dropped at once, and the request is served here or retried
// against a fresh read; one that is unreachable is suspect for 10 s, and
@@ -105,7 +106,7 @@ var holderReadErrLogged atomic.Int64
// answers; a miss reads the lock once, however many requests miss
// together, and an unexpired HA lease of another box sets the entry,
// anything else the negative one. A read that fails caches nothing.
-func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) edge.ForwardDecision {
+func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot) edge.ForwardDecision {
if !rt.HA {
return edge.ForwardDecision{}
}
@@ -119,7 +120,7 @@ func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) edge.For
if here {
return edge.ForwardDecision{}
}
- ref, refuse, gen := a.holders.resolve(ctx, rt.Host, func() (string, bool) {
+ resolved := a.holders.resolve(ctx, rt.Host, func() holderRead {
// The read is every queued caller's, not only this one's: detached
// from this request's cancellation, so one visitor hanging up does
// not fail the rest, and bounded on its own.
@@ -131,24 +132,65 @@ func (a *Service) ForwardTarget(ctx context.Context, rt registry.Route) edge.For
if last := holderReadErrLogged.Load(); now.UnixNano()-last >= int64(time.Minute) && holderReadErrLogged.CompareAndSwap(last, now.UnixNano()) {
log.Printf("activator: %s: reading the holder: %v; serving here", rt.Host, err)
}
- return "", false
+ return holderRead{Err: err}
}
- self, _ := boxSelfRef(a.backend)
- return otherHolder(v, self, a.holders.clock()), true
+ return holderRead{Ref: otherHolder(v, r.self(), a.holders.clock()), View: &v}
})
- return edge.ForwardDecision{Ref: ref, Refuse: refuse, Gen: gen}
+ if resolved.Refuse {
+ return edge.ForwardDecision{Refuse: true}
+ }
+ if resolved.Ref != "" {
+ token, _ := a.peers.holderToken(resolved.Ref, a.holders.clock())
+ return edge.ForwardDecision{Ref: resolved.Ref, Gen: resolved.Gen, PeerGen: token}
+ }
+ var s boxchoice.WakeSnapshot
+ if snapshot != nil {
+ s = snapshot()
+ }
+ now := a.holders.clock()
+ pv := a.peers.snapshot(now)
+ d := DecidePlacement(rt, r.self(), resolved.View, s, pv, now)
+ var token uint64
+ if (d.Kind == Recovery || d.Kind == Place) && d.Ref != s.Self {
+ var admitted bool
+ token, admitted = a.peers.begin(d.Ref, now)
+ if !admitted {
+ // Re-evaluate under the same applicability rule after a concurrent
+ // reservation or failure changes the bounded peer state.
+ pv = a.peers.snapshot(now)
+ pv.Saturated = true
+ d = DecidePlacement(rt, r.self(), resolved.View, s, pv, now)
+ }
+ }
+ a.observePlacement(rt.Host, d, s, resolved.View, now)
+ if d.Kind == Refuse {
+ return edge.ForwardDecision{Unavailable: true}
+ }
+ if d.Kind == Base || d.Ref == s.Self {
+ return edge.ForwardDecision{}
+ }
+ kind := edge.Placement
+ if d.Kind == Recovery {
+ kind = edge.Recovery
+ }
+ gen := a.holders.placement(rt.Host, d.Ref, kind, resolved.Gen)
+ if gen == 0 {
+ fallback := DecidePlacement(rt, r.self(), nil, s, pv, now)
+ return edge.ForwardDecision{Unavailable: fallback.Kind == Refuse}
+ }
+ return edge.ForwardDecision{Ref: d.Ref, Kind: kind, Gen: gen, PeerGen: token}
}
// otherHolder is the box v names as holding the host, when that is an
// unexpired HA lease of a box other than self: "" for an absent lock, a
// release marker, an expired lease, a lock that is not in the HA box
// format, or this box's own.
-func otherHolder(v hafresh.View, self string, now time.Time) string {
- if v.Absent || v.Lock.Release != nil || !now.Before(v.Lock.ExpiresAt) {
+func otherHolder(v hafresh.View, self hafresh.Self, now time.Time) string {
+ if v.Absent || v.Lock.Release != nil || now.After(v.Lock.ExpiresAt) {
return ""
}
o, ok := hafresh.ParseOwner(v.Lock.Owner)
- if !ok || !o.HA || o.Ref == "" || o.Ref == self {
+ if !ok || !o.HA || o.Ref == "" || o.Ref == self.Ref || (self.IID != "" && o.IID == self.IID) {
return ""
}
return o.Ref
@@ -162,24 +204,13 @@ func otherHolder(v hafresh.View, self string, now time.Time) string {
// older than the entry's; any other answer from a box clears a suspect
// entry: that box is the holder.
func (a *Service) NoteForward(host string, res edge.ForwardResult) {
- switch {
- case res.Outcome == edge.ForwardNotInView:
- a.holders.drop(host)
- case res.Outcome == edge.ForwardUnreachable:
- a.holders.unreachable(host, res.Gen)
- case res.Holder == holderNone:
- a.holders.drop(host)
- case res.Holder != "":
- if self, ok := boxSelfRef(a.backend); ok && res.Holder == self {
- a.holders.drop(host)
- return
- }
- a.holders.set(host, res.Holder)
- case res.Status == http.StatusServiceUnavailable:
- a.holders.drop(host)
- case res.Status != 0:
- a.holders.answered(host, res.Ref)
+ self, _ := boxSelfRef(a.backend)
+ note := func() { a.peers.note(res, a.holders.clock()) }
+ if res.Kind != edge.Holder {
+ a.holders.hintResult(host, self, res, note)
+ return
}
+ a.holders.holderResult(host, self, res, note)
}
// answerForwarded is the holder diagnostic on the refusal err of a
diff --git a/internal/activator/haforward_test.go b/internal/activator/haforward_test.go
index d534f9f1c..08e68de67 100644
--- a/internal/activator/haforward_test.go
+++ b/internal/activator/haforward_test.go
@@ -50,14 +50,14 @@ func haHeldByB(t *testing.T) *haSvc {
func TestForwardTargetNamesTheHolder(t *testing.T) {
s := haHeldByB(t)
- d := s.a.ForwardTarget(context.Background(), s.rt)
+ d := s.a.ForwardTarget(context.Background(), s.rt, nil)
if d.Ref != "b" {
t.Fatalf("ForwardTarget = %+v, want b", d)
}
if n := lockGets(s.b, s.rt); n != 1 {
t.Fatalf("%d lock reads on a miss, want 1", n)
}
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "b" {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "b" {
t.Fatalf("ForwardTarget on a hit = %q, want b", got)
}
if n := lockGets(s.b, s.rt); n != 1 {
@@ -70,7 +70,7 @@ func TestForwardTargetServesHere(t *testing.T) {
s, _ := haServiceEntry(t, "shop.example.com")
s.rt.HA = true
before := lockGets(s.b, s.rt)
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" {
t.Fatalf("ForwardTarget for a host awake here = %q", got)
}
if n := lockGets(s.b, s.rt) - before; n != 0 {
@@ -83,18 +83,18 @@ func TestForwardTargetServesHere(t *testing.T) {
clk := &fakeClock{t: time.Now()}
s.a.holders.now = clk.now
putLockFor(t, s.b, s.rt, markerBody(t, "b", "i-b", haFixOf(s.b).lifetime, 5, true))
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" {
t.Fatalf("ForwardTarget over a release marker = %q", got)
}
if _, positive, found := s.a.holders.get(s.rt.Host); !found || positive {
t.Fatalf("no negative entry: found %v, positive %v", found, positive)
}
clk.advance(9 * time.Second)
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" || lockGets(s.b, s.rt) != 1 {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" || lockGets(s.b, s.rt) != 1 {
t.Fatalf("within 10 s: %q, %d reads, want \"\" and 1", got, lockGets(s.b, s.rt))
}
clk.advance(2 * time.Second)
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" || lockGets(s.b, s.rt) != 2 {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" || lockGets(s.b, s.rt) != 2 {
t.Fatalf("at 11 s: %q, %d reads, want \"\" and 2", got, lockGets(s.b, s.rt))
}
})
@@ -102,7 +102,7 @@ func TestForwardTargetServesHere(t *testing.T) {
s := haService(t, "shop.example.com")
s.rt.HA = true
putLockFor(t, s.b, s.rt, leaseBody(t, "box/v1;ref=a;iid=i-a;pid=99;ha=1", time.Now().Add(10*time.Minute)))
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" {
t.Fatalf("ForwardTarget over this box's own lease = %q", got)
}
})
@@ -110,21 +110,21 @@ func TestForwardTargetServesHere(t *testing.T) {
s := haService(t, "shop.example.com")
s.rt.HA = true
putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute)))
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" {
t.Fatalf("ForwardTarget over an expired lease = %q", got)
}
})
t.Run("legacy route", func(t *testing.T) {
s := haHeldByB(t)
s.rt.HA = false
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" || lockGets(s.b, s.rt) != 0 {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" || lockGets(s.b, s.rt) != 0 {
t.Fatalf("legacy route: %q, %d reads", got, lockGets(s.b, s.rt))
}
})
t.Run("read error", func(t *testing.T) {
s := haHeldByB(t)
s.fx.FailNext("GET", http.StatusForbidden)
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "" {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "" {
t.Fatalf("a failed read = %q", got)
}
if _, _, found := s.a.holders.get(s.rt.Host); found {
@@ -165,7 +165,7 @@ func TestForwardTargetSingleFlight(t *testing.T) {
// hasuspect_test.go.)
func TestHolderCacheDroppedOutOfView(t *testing.T) {
s := haHeldByB(t)
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "b" {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "b" {
t.Fatalf("ForwardTarget = %q, want b", got)
}
s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardNotInView, Ref: "b"})
@@ -182,7 +182,7 @@ func TestHolderCacheFollowsHolderHeader(t *testing.T) {
if ref, positive, _ := s.a.holders.get(host); ref != "c" || !positive {
t.Fatalf("after X-Carlos-Holder: c the entry is %q", ref)
}
- if got := s.a.ForwardTarget(context.Background(), s.rt).Ref; got != "c" || lockGets(s.b, s.rt) != 0 {
+ if got := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "c" || lockGets(s.b, s.rt) != 0 {
t.Fatalf("ForwardTarget = %q with %d reads, want c and none", got, lockGets(s.b, s.rt))
}
s.a.NoteForward(host, edge.ForwardResult{Outcome: edge.ForwardDone, Status: 503, Holder: "none"})
@@ -394,14 +394,14 @@ func TestScheduledTickNeverForwards(t *testing.T) {
func TestForwardTargetThroughSplitBackend(t *testing.T) {
s := haHeldByB(t)
a := New(Config{Bucket: s.b.Cfg.Bucket, Idle: time.Hour}, &SplitBackend{Exec: s.b, Unit: &UnitBackend{}}, s.b.Registry)
- d := a.ForwardTarget(context.Background(), s.rt)
+ d := a.ForwardTarget(context.Background(), s.rt, nil)
if d.Ref != "b" {
t.Fatalf("ForwardTarget through the split backend = %+v, want b", d)
}
if n := lockGets(s.b, s.rt); n != 1 {
t.Fatalf("%d lock reads on a miss, want 1", n)
}
- if got := a.ForwardTarget(context.Background(), s.rt).Ref; got != "b" || lockGets(s.b, s.rt) != 1 {
+ if got := a.ForwardTarget(context.Background(), s.rt, nil).Ref; got != "b" || lockGets(s.b, s.rt) != 1 {
t.Fatalf("a hit: %q with %d reads, want b and 1", got, lockGets(s.b, s.rt))
}
// This box's identity is the exec half's: an answer naming it drops.
@@ -411,7 +411,7 @@ func TestForwardTargetThroughSplitBackend(t *testing.T) {
}
unit := s.rt
unit.Host, unit.Backing = "unit.example.com", registry.BackingUnit
- if got := a.ForwardTarget(context.Background(), unit).Ref; got != "" {
+ if got := a.ForwardTarget(context.Background(), unit, nil).Ref; got != "" {
t.Fatalf("a unit-backed row = %q", got)
}
}
@@ -482,7 +482,7 @@ func TestForwardTargetStalledReadIsBounded(t *testing.T) {
start := time.Now()
got := make(chan string, 10)
for range cap(got) {
- go func() { got <- s.a.ForwardTarget(context.Background(), s.rt).Ref }()
+ go func() { got <- s.a.ForwardTarget(context.Background(), s.rt, nil).Ref }()
}
bound := time.After(holderReadTimeout + 2*time.Second)
for range cap(got) {
@@ -505,7 +505,7 @@ func TestForwardTargetStalledReadIsBounded(t *testing.T) {
t.Fatalf("%d flights left after the stalled read", flights)
}
t.Setenv("CARLOS_S3_ENDPOINT", s.fx.URL)
- if ref := s.a.ForwardTarget(context.Background(), s.rt).Ref; ref != "b" || lockGets(s.b, s.rt) != 1 {
+ if ref := s.a.ForwardTarget(context.Background(), s.rt, nil).Ref; ref != "b" || lockGets(s.b, s.rt) != 1 {
t.Fatalf("the lookup after the stall: %q with %d reads, want b and 1", ref, lockGets(s.b, s.rt))
}
}
diff --git a/internal/activator/haplacement.go b/internal/activator/haplacement.go
new file mode 100644
index 000000000..2d6099584
--- /dev/null
+++ b/internal/activator/haplacement.go
@@ -0,0 +1,203 @@
+package activator
+
+import (
+ "log"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxchoice"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+type PlacementKind uint8
+
+const (
+ Base PlacementKind = iota
+ Recovery
+ Place
+ Refuse
+)
+
+func (k PlacementKind) String() string {
+ switch k {
+ case Base:
+ return "Base"
+ case Recovery:
+ return "Recovery"
+ case Place:
+ return "Place"
+ case Refuse:
+ return "Refuse"
+ }
+ return "unknown"
+}
+
+type PlacementDecision struct {
+ Kind PlacementKind
+ Ref string
+ OverCapacity bool
+ Reason string
+}
+type PlacementPeerView struct {
+ Suspect map[string]bool
+ Saturated bool
+}
+
+// DecidePlacement supplies routing advice only. The selected box still acquires
+// through AcquireHA, including its emptiness and termination proofs.
+func DecidePlacement(rt registry.Route, self hafresh.Self, view *hafresh.View, s boxchoice.WakeSnapshot, peers PlacementPeerView, now time.Time) PlacementDecision {
+ base := func(reason string) PlacementDecision {
+ if s.Enabled && s.LocalDenied {
+ return PlacementDecision{Kind: Refuse, Reason: reason}
+ }
+ return PlacementDecision{Reason: reason}
+ }
+ if !s.Enabled {
+ return PlacementDecision{Reason: "base-switch-off"}
+ }
+ if view == nil {
+ return base("base-no-observation")
+ }
+ clean := ""
+ if !view.Absent {
+ if m := view.Lock.Release; m != nil {
+ if !view.HAOn() || m.V != 1 || m.Box == "" {
+ return base("base-invalid-marker")
+ }
+ if m.Clean {
+ clean = m.Box
+ }
+ } else {
+ owner, ok := hafresh.ParseOwner(view.Lock.Owner)
+ if !ok || !owner.HA {
+ return base("base-unknown-owner")
+ }
+ if owner.Ref == self.Ref || (self.IID != "" && owner.IID == self.IID) {
+ return base("base-self-owner")
+ }
+ if !now.After(view.Lock.ExpiresAt) {
+ return base("base-held-owner")
+ }
+ if peers.Suspect[owner.Ref] {
+ return base("peer-suspect")
+ }
+ if !peers.Saturated && s.Usable {
+ for _, c := range s.Serving {
+ if c.BoxID == owner.Ref && boxchoice.HeadroomFresh(c.Generation, now) {
+ return PlacementDecision{Kind: Recovery, Ref: owner.Ref, Reason: "owner-recovery"}
+ }
+ }
+ }
+ return base("base-owner-outside-view")
+ }
+ }
+ if !s.Usable || s.Self == "" {
+ return base("base-no-snapshot")
+ }
+ if peers.Saturated {
+ return base("base-peer-capacity")
+ }
+ filtered := s
+ filtered.Serving = nil
+ excluded := false
+ for _, c := range s.Serving {
+ if peers.Suspect[c.BoxID] {
+ excluded = true
+ continue
+ }
+ if s.LocalDenied && c.BoxID == s.Self {
+ continue
+ }
+ filtered.Serving = append(filtered.Serving, c)
+ }
+ choice, ok := boxchoice.ChooseColdWake(rt.Host, release.RouteAccount(rt)+"/"+rt.App, clean, filtered, now)
+ if !ok {
+ if excluded {
+ return base("peer-suspect")
+ }
+ return base("base-no-snapshot")
+ }
+ reason := "roomiest"
+ if choice.Ref == clean {
+ reason = "clean-releaser"
+ }
+ if choice.OverCapacity {
+ reason = "over-capacity"
+ }
+ return PlacementDecision{Kind: Place, Ref: choice.Ref, OverCapacity: choice.OverCapacity, Reason: reason}
+}
+
+type placementDiagnostics struct {
+ mu sync.Mutex
+ hosts map[string]time.Time
+ regions map[string]time.Time
+}
+
+// observe bounds decision logs and page throttles independently of lock reads.
+func (a *Service) observePlacement(host string, d PlacementDecision, s boxchoice.WakeSnapshot, view *hafresh.View, now time.Time) {
+ p := &a.placementLog
+ p.mu.Lock()
+ if p.hosts == nil {
+ p.hosts = map[string]time.Time{}
+ }
+ last, seen := p.hosts[host]
+ write := !seen || now.Sub(last) >= time.Minute
+ if write {
+ if len(p.hosts) >= holderCacheMax {
+ for h, at := range p.hosts {
+ if now.Sub(at) >= time.Minute {
+ delete(p.hosts, h)
+ }
+ }
+ }
+ if len(p.hosts) < holderCacheMax || seen {
+ p.hosts[host] = now
+ } else {
+ write = false
+ }
+ }
+ page := false
+ if d.OverCapacity && a.OnHAOverCapacity != nil {
+ if p.regions == nil {
+ p.regions = map[string]time.Time{}
+ }
+ at, ok := p.regions[s.Region]
+ if !ok || now.Sub(at) >= time.Hour {
+ if len(p.regions) >= holderCacheMax {
+ for r, t := range p.regions {
+ if now.Sub(t) >= time.Hour {
+ delete(p.regions, r)
+ }
+ }
+ }
+ if len(p.regions) < holderCacheMax || ok {
+ p.regions[s.Region] = now
+ page = true
+ }
+ }
+ }
+ p.mu.Unlock()
+ if write {
+ var gen int64
+ if view != nil {
+ gen = view.Lock.Generation
+ }
+ evidenceRef := d.Ref
+ if evidenceRef == "" {
+ evidenceRef = s.Self
+ }
+ generation := ""
+ for _, candidate := range s.Serving {
+ if candidate.BoxID == evidenceRef {
+ generation = candidate.Generation
+ break
+ }
+ }
+ log.Printf("activator: HA placement host=%s kind=%s ref=%s reason=%s generation=%s lock_generation=%d", host, d.Kind, d.Ref, d.Reason, generation, gen)
+ }
+ if page {
+ go a.OnHAOverCapacity(s.Region, host, d.Ref)
+ }
+}
diff --git a/internal/activator/haplacement_peers.go b/internal/activator/haplacement_peers.go
new file mode 100644
index 000000000..28aa22ef1
--- /dev/null
+++ b/internal/activator/haplacement_peers.go
@@ -0,0 +1,101 @@
+package activator
+
+import (
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+type placementPeer struct {
+ epoch uint64
+ until time.Time
+ idle time.Time
+}
+type placementPeers struct {
+ mu sync.Mutex
+ refs map[string]*placementPeer
+ seq uint64
+}
+
+func (p *placementPeers) reclaim(now time.Time) {
+ for ref, e := range p.refs {
+ if !now.Before(e.until) && !now.Before(e.idle) {
+ delete(p.refs, ref)
+ }
+ }
+}
+func (p *placementPeers) snapshot(now time.Time) PlacementPeerView {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ // Scan only when full; expired suspicion is also ignored below.
+ if len(p.refs) >= holderCacheMax {
+ p.reclaim(now)
+ }
+ v := PlacementPeerView{Suspect: map[string]bool{}, Saturated: len(p.refs) >= holderCacheMax}
+ for ref, e := range p.refs {
+ if now.Before(e.until) {
+ v.Suspect[ref] = true
+ }
+ }
+ return v
+}
+func (p *placementPeers) begin(ref string, now time.Time) (uint64, bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if e := p.refs[ref]; e != nil {
+ if now.Before(e.until) {
+ return 0, false
+ }
+ e.idle = now.Add(holderNegativeTTL)
+ return e.epoch, true
+ }
+ if len(p.refs) >= holderCacheMax {
+ p.reclaim(now)
+ }
+ if len(p.refs) >= holderCacheMax {
+ return 0, false
+ }
+ if p.refs == nil {
+ p.refs = map[string]*placementPeer{}
+ }
+ p.seq++
+ p.refs[ref] = &placementPeer{epoch: p.seq, idle: now.Add(holderNegativeTTL)}
+ return p.seq, true
+}
+
+// note is the sole classifier for reference-level wake failures (N-HA12).
+func (p *placementPeers) note(res edge.ForwardResult, now time.Time) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ e := p.refs[res.Ref]
+ if e == nil || res.PeerGen == 0 || e.epoch != res.PeerGen {
+ return
+ }
+ named := res.Holder != "" && res.Holder != holderNone
+ success := res.Outcome == edge.ForwardDone && (res.Status == 101 || res.Status >= 200 && res.Status < 400) && res.Holder != holderNone
+ failure := res.Kind != edge.Holder && (res.Holder == holderNone || res.Outcome != edge.ForwardDone || res.Status == 0 || res.Status == 502 || res.Status == 503)
+ if named || success {
+ e.until = time.Time{}
+ } else if failure {
+ e.until = now.Add(holderSuspectTTL)
+ } else {
+ return
+ }
+ p.seq++
+ e.epoch = p.seq
+ e.idle = now.Add(holderNegativeTTL)
+}
+
+// A true holder is still routed while a placement hint is suspect. Its answer
+// can clear that reference's suspicion without replacing lease authority.
+func (p *placementPeers) holderToken(ref string, now time.Time) (uint64, bool) {
+ p.mu.Lock()
+ if e := p.refs[ref]; e != nil {
+ token := e.epoch
+ p.mu.Unlock()
+ return token, true
+ }
+ p.mu.Unlock()
+ return p.begin(ref, now)
+}
diff --git a/internal/activator/haplacement_test.go b/internal/activator/haplacement_test.go
new file mode 100644
index 000000000..354cee17b
--- /dev/null
+++ b/internal/activator/haplacement_test.go
@@ -0,0 +1,595 @@
+package activator
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/boxchoice"
+ "github.com/carlosframework/platform/internal/edge"
+ "github.com/carlosframework/platform/internal/hafresh"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func placementSnapshot(now time.Time) boxchoice.WakeSnapshot {
+ candidate := func(ref string, free int64) boxchoice.Candidate {
+ return boxchoice.Candidate{BoxID: ref, Region: "ie", Generation: now.Format(time.RFC3339), MemFreeMiB: free, MemTotalMiB: 100, DiskFreeMiB: 50, DiskTotalMiB: 100}
+ }
+ return boxchoice.WakeSnapshot{Enabled: true, Usable: true, Self: "a", Region: "ie", Serving: []boxchoice.Candidate{candidate("a", 20), candidate("b", 80)}, Running: map[string]boxchoice.Load{}}
+}
+func placementResult(d edge.ForwardDecision, status int, holder string) edge.ForwardResult {
+ return edge.ForwardResult{Outcome: edge.ForwardDone, Ref: d.Ref, Kind: d.Kind, Gen: d.Gen, PeerGen: d.PeerGen, Status: status, Holder: holder}
+}
+func TestPlacementExpiredOwner(t *testing.T) {
+ now := time.Now()
+ s := placementSnapshot(now)
+ self := hafresh.Self{Ref: "a", IID: "i-a"}
+ rt := registry.Route{Host: "shop.example.com", HA: true}
+ for _, tc := range []struct {
+ name, owner string
+ expiry time.Time
+ want PlacementKind
+ }{
+ {"self expired", hafresh.OwnerFor(self, 1, true), now.Add(-time.Second), Base},
+ {"self equality", hafresh.OwnerFor(self, 1, true), now, Base},
+ {"same iid different ref", hafresh.OwnerFor(hafresh.Self{Ref: "old", IID: "i-a"}, 1, true), now.Add(-time.Second), Base},
+ {"peer expired", heldByB, now.Add(-time.Second), Recovery},
+ {"peer equality", heldByB, now, Base},
+ {"legacy", "legacy:2", now.Add(-time.Second), Base},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ v := &hafresh.View{Lock: hafresh.Lock{Owner: tc.owner, ExpiresAt: tc.expiry}}
+ d := DecidePlacement(rt, self, v, s, PlacementPeerView{}, now)
+ if d.Kind != tc.want {
+ t.Fatalf("%+v want %v", d, tc.want)
+ }
+ })
+ }
+ v := &hafresh.View{Lock: hafresh.Lock{Owner: heldByB, ExpiresAt: now.Add(-time.Second)}}
+ for _, low := range []bool{false, true} {
+ if low {
+ s.Serving[1].MemFreeMiB = 0
+ }
+ if d := DecidePlacement(rt, self, v, s, PlacementPeerView{}, now); d.Kind != Recovery || d.Ref != "b" {
+ t.Fatalf("recovery %+v", d)
+ }
+ }
+ if d := DecidePlacement(rt, self, v, s, PlacementPeerView{Suspect: map[string]bool{"b": true}}, now); d.Kind != Base {
+ t.Fatal(d)
+ }
+ s.Serving = s.Serving[:1]
+ if d := DecidePlacement(rt, self, v, s, PlacementPeerView{}, now); d.Kind != Base {
+ t.Fatal(d)
+ }
+}
+func TestPlacementApplicability(t *testing.T) {
+ now := time.Now()
+ rt := registry.Route{Host: "shop.example.com", HA: true}
+ self := hafresh.Self{Ref: "a"}
+ for _, tc := range []struct {
+ name string
+ v *hafresh.View
+ mutate func(*boxchoice.WakeSnapshot)
+ want PlacementKind
+ }{
+ {"switch off", &hafresh.View{Absent: true}, func(s *boxchoice.WakeSnapshot) { s.Enabled = false; s.LocalDenied = true }, Base},
+ {"no snapshot", &hafresh.View{Absent: true}, func(s *boxchoice.WakeSnapshot) { s.Usable = false }, Base},
+ {"probe failure", nil, func(*boxchoice.WakeSnapshot) {}, Base},
+ {"malformed marker", &hafresh.View{Lock: hafresh.Lock{Release: &hafresh.Marker{V: 2, Box: "b", Clean: true}}}, func(*boxchoice.WakeSnapshot) {}, Base},
+ {"clean releaser", &hafresh.View{Lock: hafresh.Lock{Release: &hafresh.Marker{V: 1, Box: "a", Clean: true}}}, func(*boxchoice.WakeSnapshot) {}, Place},
+ {"roomiest", &hafresh.View{Absent: true}, func(*boxchoice.WakeSnapshot) {}, Place},
+ {"denied no snapshot", nil, func(s *boxchoice.WakeSnapshot) { s.LocalDenied = true; s.Usable = false }, Refuse},
+ {"saturation", &hafresh.View{Absent: true}, func(*boxchoice.WakeSnapshot) {}, Base},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ s := placementSnapshot(now)
+ tc.mutate(&s)
+ p := PlacementPeerView{Saturated: tc.name == "saturation"}
+ d := DecidePlacement(rt, self, tc.v, s, p, now)
+ if d.Kind != tc.want {
+ t.Fatalf("%+v want %v", d, tc.want)
+ }
+ })
+ }
+}
+func TestPlacementRefusalMarksSuspect(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ outcome edge.ForwardOutcome
+ status int
+ holder string
+ }{
+ {"none", edge.ForwardDone, 503, "none"}, {"503", edge.ForwardDone, 503, ""}, {"502", edge.ForwardDone, 502, ""}, {"zero", edge.ForwardDone, 0, ""}, {"out of view", edge.ForwardNotInView, 0, ""}, {"dial", edge.ForwardUnreachable, 0, ""},
+ } {
+ for _, clean := range []bool{false, true} {
+ t.Run(fmt.Sprintf("%s/clean=%v", tc.name, clean), func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ if clean {
+ putLockFor(t, s.b, s.rt, markerBody(t, "b", "i-b", haFixOf(s.b).lifetime, 5, true))
+ }
+ clk := &fakeClock{t: time.Now()}
+ s.a.holders.now = clk.now
+ snap := placementSnapshot(clk.now())
+ project := func() boxchoice.WakeSnapshot { return snap }
+ d := s.a.ForwardTarget(context.Background(), s.rt, project)
+ if d.Ref != "b" || d.Kind != edge.Placement {
+ t.Fatalf("initial %+v", d)
+ }
+ r := placementResult(d, tc.status, tc.holder)
+ r.Outcome = tc.outcome
+ s.a.NoteForward(s.rt.Host, r)
+ if d = s.a.ForwardTarget(context.Background(), s.rt, project); d.Ref != "" || d.Refuse {
+ t.Fatalf("suspect %+v", d)
+ }
+ other := s.rt
+ other.Host = "other.example.com"
+ if d = s.a.ForwardTarget(context.Background(), other, project); d.Ref != "" {
+ t.Fatalf("cross host %+v", d)
+ }
+ if lockGets(s.b, s.rt) != 1 {
+ t.Fatal("failure discarded observation")
+ }
+ clk.advance(10 * time.Second)
+ if d = s.a.ForwardTarget(context.Background(), s.rt, project); d.Ref != "b" {
+ t.Fatalf("expiry %+v", d)
+ }
+ })
+ }
+ }
+}
+func TestPlacementCachesObservationNotChoice(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ clk := &fakeClock{t: time.Now()}
+ s.a.holders.now = clk.now
+ snap := placementSnapshot(clk.now())
+ project := func() boxchoice.WakeSnapshot { return snap }
+ d := s.a.ForwardTarget(context.Background(), s.rt, project)
+ s.a.NoteForward(s.rt.Host, placementResult(d, 200, ""))
+ snap.Serving[0].MemFreeMiB = 90
+ if d = s.a.ForwardTarget(context.Background(), s.rt, project); d.Ref != "" {
+ t.Fatalf("choice pinned %+v", d)
+ }
+ if n := lockGets(s.b, s.rt); n != 1 {
+ t.Fatalf("%d GETs", n)
+ }
+ snap.Serving[0].MemFreeMiB = 20
+ d = s.a.ForwardTarget(context.Background(), s.rt, project)
+ s.a.NoteForward(s.rt.Host, placementResult(d, 503, "b"))
+ snap.Serving = nil
+ clk.advance(11 * time.Second)
+ if d = s.a.ForwardTarget(context.Background(), s.rt, project); d.Ref != "b" || d.Kind != edge.Holder {
+ t.Fatal(d)
+ }
+ if n := lockGets(s.b, s.rt); n != 1 {
+ t.Fatal(n)
+ }
+ clk.advance(time.Hour)
+ s.a.ForwardTarget(context.Background(), s.rt, project)
+ if n := lockGets(s.b, s.rt); n != 2 {
+ t.Fatal(n)
+ }
+}
+func TestPlacementSnapshotIsLazy(t *testing.T) {
+ for _, mode := range []string{"cold", "positive", "suspect", "awake", "waking", "legacy"} {
+ t.Run(mode, func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ switch mode {
+ case "positive":
+ s.a.holders.set(s.rt.Host, "b")
+ case "suspect":
+ s.a.holders.set(s.rt.Host, "b")
+ s.a.holders.mu.Lock()
+ gen := s.a.holders.holders[s.rt.Host].Value.(*holderEntry).gen
+ s.a.holders.mu.Unlock()
+ s.a.holders.unreachable(s.rt.Host, gen)
+ case "awake":
+ s.a.entries[s.rt.Host] = &actEntry{state: actAwake}
+ case "waking":
+ s.a.entries[s.rt.Host] = &actEntry{state: actWaking}
+ case "legacy":
+ s.rt.HA = false
+ }
+ calls := 0
+ s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { calls++; return boxchoice.WakeSnapshot{} })
+ want := 0
+ if mode == "cold" {
+ want = 1
+ }
+ if calls != want {
+ t.Fatalf("projections %d want %d", calls, want)
+ }
+ })
+ }
+}
+func TestPlacementSingleFlight(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ old := readHolderLock
+ gate := make(chan struct{})
+ var reads atomic.Int32
+ readHolderLock = func(ctx context.Context, b, p, r string) (hafresh.View, error) {
+ reads.Add(1)
+ <-gate
+ return old(ctx, b, p, r)
+ }
+ t.Cleanup(func() { readHolderLock = old })
+ ctx, cancel := context.WithCancel(context.Background())
+ first := make(chan edge.ForwardDecision, 1)
+ go func() { first <- s.a.ForwardTarget(ctx, s.rt, nil) }()
+ waitFor(t, "read", func() bool { return reads.Load() == 1 })
+ got := make(chan edge.ForwardDecision, 20)
+ for range 20 {
+ go func() {
+ got <- s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) })
+ }()
+ }
+ cancel()
+ select {
+ case <-first:
+ case <-time.After(time.Second):
+ t.Fatal("canceled leader blocked")
+ }
+ close(gate)
+ for range 20 {
+ if d := recv(t, got); d.Ref != "b" {
+ t.Fatal(d)
+ }
+ }
+ if reads.Load() != 1 {
+ t.Fatal(reads.Load())
+ }
+}
+func TestPlacementProbeFailureUsesBase(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ old := readHolderLock
+ readHolderLock = func(context.Context, string, string, string) (hafresh.View, error) {
+ return hafresh.View{}, errors.New("unavailable")
+ }
+ t.Cleanup(func() { readHolderLock = old })
+ if d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) }); d != (edge.ForwardDecision{}) {
+ t.Fatal(d)
+ }
+}
+func TestPlacementHintIsNotAHolder(t *testing.T) {
+ for _, recovery := range []bool{false, true} {
+ for _, status := range []int{200, 404, 503} {
+ t.Run(http.StatusText(status)+map[bool]string{true: " recovery", false: " placement"}[recovery], func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ if recovery {
+ putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Second)))
+ }
+ snap := placementSnapshot(time.Now())
+ d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return snap })
+ s.a.NoteForward(s.rt.Host, placementResult(d, status, ""))
+ if _, pos, found := s.a.holders.get(s.rt.Host); pos || !found {
+ t.Fatal("hint became holder or lost observation")
+ }
+ })
+ }
+ }
+}
+
+func TestPlacementRecoveryFailurePreservesTermination(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(-time.Minute)))
+ oracle := &terminatedOracle{yes: map[string]bool{}}
+ s.b.OwnerTerminated = oracle.terminated
+ project := func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) }
+ d := s.a.ForwardTarget(context.Background(), s.rt, project)
+ if d.Kind != edge.Recovery {
+ t.Fatal(d)
+ }
+ if len(oracle.calls()) != 0 {
+ t.Fatal("routing invented a termination proof")
+ }
+ r := placementResult(d, 0, "")
+ r.Outcome = edge.ForwardUnreachable
+ s.a.NoteForward(s.rt.Host, r)
+ if d = s.a.ForwardTarget(context.Background(), s.rt, project); d.Ref != "" || d.Refuse {
+ t.Fatalf("recovery blackout %+v", d)
+ }
+ if _, err := s.b.Acquire(context.Background(), s.rt); err == nil {
+ t.Fatal("took alive peer's lock")
+ }
+ oracle.mu.Lock()
+ oracle.yes["i-b"] = true
+ oracle.mu.Unlock()
+ if d = s.a.ForwardTarget(context.Background(), s.rt, project); d.Ref != "" || d.Refuse {
+ t.Fatal(d)
+ }
+ l, err := s.b.Acquire(context.Background(), s.rt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ if n := lockGets(s.b, s.rt); n != 3 {
+ t.Fatalf("%d ingress+acquire reads, want 3", n)
+ }
+}
+func TestPlacementSwitchOff(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ s.a.OnHAOverCapacity = func(string, string, string) { t.Error("switch off paged") }
+ if d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return boxchoice.WakeSnapshot{} }); d != (edge.ForwardDecision{}) {
+ t.Fatal(d)
+ }
+ if _, err := s.wakeForTest(context.Background()); err != nil {
+ t.Fatalf("local HA wake: %v", err)
+ }
+ held := haHeldByB(t)
+ if d := held.a.ForwardTarget(context.Background(), held.rt, func() boxchoice.WakeSnapshot { t.Fatal("holder projected"); return boxchoice.WakeSnapshot{} }); d.Ref != "b" {
+ t.Fatal(d)
+ }
+}
+func TestPlacementRefusalKeepsObservation(t *testing.T) {
+ for _, header := range []string{"none", ""} {
+ t.Run("holder="+header, func(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ clk := &fakeClock{t: time.Now()}
+ s.a.holders.now = clk.now
+ project := func() boxchoice.WakeSnapshot { return placementSnapshot(clk.now()) }
+ d := s.a.ForwardTarget(context.Background(), s.rt, project)
+ s.a.NoteForward(s.rt.Host, placementResult(d, 503, header))
+ for i := 0; i < 4; i++ {
+ clk.advance(2 * time.Second)
+ if d = s.a.ForwardTarget(context.Background(), s.rt, project); d.Ref != "" || d.Refuse {
+ t.Fatal(d)
+ }
+ before := lockGets(s.b, s.rt)
+ l, err := s.b.Acquire(context.Background(), s.rt)
+ if i == 0 {
+ if err != nil {
+ t.Fatal(err)
+ }
+ releaseHALease(t, l)
+ } else {
+ var held *errLeaseHeld
+ if !errors.As(err, &held) {
+ t.Fatalf("local acquire must still validate the held lease: %v", err)
+ }
+ }
+ if n := lockGets(s.b, s.rt) - before; n != 1 {
+ t.Fatalf("acquire used %d GETs", n)
+ }
+ }
+ if n := lockGets(s.b, s.rt); n != 5 {
+ t.Fatalf("sliding observation: %d GETs, want 1+4", n)
+ }
+ clk.advance(2 * time.Second)
+ s.a.ForwardTarget(context.Background(), s.rt, project)
+ if n := lockGets(s.b, s.rt); n != 6 {
+ t.Fatalf("original deadline: %d", n)
+ }
+ })
+ }
+}
+func TestPlacementSuspectBox(t *testing.T) {
+ now := time.Now()
+ var p placementPeers
+ token, ok := p.begin("b", now)
+ if !ok {
+ t.Fatal("begin")
+ }
+ fail := edge.ForwardResult{Kind: edge.Placement, Ref: "b", PeerGen: token, Outcome: edge.ForwardDone, Status: 503, Holder: "none"}
+ p.note(fail, now)
+ lateToken, _ := p.holderToken("b", now)
+ p.note(edge.ForwardResult{Kind: edge.Placement, Ref: "b", PeerGen: lateToken, Outcome: edge.ForwardDone, Status: 404}, now)
+ if !p.snapshot(now).Suspect["b"] {
+ t.Fatal("ordinary error cleared suspicion")
+ }
+ p.note(fail, now.Add(9*time.Second))
+ if p.snapshot(now.Add(10 * time.Second)).Suspect["b"] {
+ t.Fatal("stale failure slid suspect deadline")
+ }
+ if _, ok := p.begin("b", now.Add(time.Second)); ok {
+ t.Fatal("suspect admitted")
+ }
+ s := placementSnapshot(now)
+ v := &hafresh.View{Lock: hafresh.Lock{Release: &hafresh.Marker{V: 1, Box: "b", Clean: true}}}
+ if d := DecidePlacement(registry.Route{Host: "shop.example.com"}, hafresh.Self{Ref: "a"}, v, s, p.snapshot(now), now); d.Ref != "a" {
+ t.Fatalf("suspect releaser chosen %+v", d)
+ }
+ token, _ = p.holderToken("b", now)
+ p.note(edge.ForwardResult{Kind: edge.Holder, Ref: "b", PeerGen: token, Outcome: edge.ForwardDone, Status: 503, Holder: "b"}, now)
+ p.note(fail, now.Add(time.Second))
+ if p.snapshot(now).Suspect["b"] {
+ t.Fatal("late failure poisoned holder answer")
+ }
+ token, _ = p.begin("b", now)
+ p.note(edge.ForwardResult{Kind: edge.Placement, Ref: "b", PeerGen: token, Outcome: edge.ForwardDone, Status: 200}, now)
+ p.note(edge.ForwardResult{Kind: edge.Placement, Ref: "b", PeerGen: token, Outcome: edge.ForwardUnreachable}, now)
+ if p.snapshot(now).Suspect["b"] {
+ t.Fatal("late failure poisoned success")
+ }
+ for i := 0; i < holderCacheMax; i++ {
+ p.begin(fmt.Sprintf("ref-%d", i), now)
+ }
+ if len(p.refs) != holderCacheMax {
+ t.Fatal(len(p.refs))
+ }
+ if _, ok := p.begin("overflow", now); ok {
+ t.Fatal("unbounded")
+ }
+ token, _ = p.begin("b", now)
+ p.note(edge.ForwardResult{Kind: edge.Placement, Ref: "b", PeerGen: token, Outcome: edge.ForwardUnreachable}, now)
+ if !p.snapshot(now.Add(9 * time.Second)).Suspect["b"] {
+ t.Fatal("active suspect evicted at bound")
+ }
+ if !p.snapshot(now).Saturated {
+ t.Fatal("not saturated")
+ }
+ if _, ok := p.begin("after-idle", now.Add(10*time.Second)); !ok {
+ t.Fatal("idle entries not reclaimed")
+ }
+}
+func TestPlacementStaleResultCannotPoisonAcquire(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) })
+ if _, err := s.wakeForTest(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ r := placementResult(d, 0, "")
+ r.Outcome = edge.ForwardUnreachable
+ s.a.NoteForward(s.rt.Host, r)
+ if s.a.peers.snapshot(time.Now()).Suspect["b"] {
+ t.Fatal("stale failure after acquire")
+ }
+ s.a.NoteForward(s.rt.Host, placementResult(d, 503, "b"))
+ if _, _, found := s.a.holders.get(s.rt.Host); found {
+ t.Fatal("stale header after acquire")
+ }
+}
+func TestPlacementNoCapacityStillWakes(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ clk := &fakeClock{t: time.Now()}
+ s.a.holders.now = clk.now
+ pages := make(chan string, 4)
+ s.a.OnHAOverCapacity = func(region, host, ref string) { pages <- region + "/" + host + "/" + ref }
+ snap := placementSnapshot(clk.now())
+ for i := range snap.Serving {
+ snap.Serving[i].MemFreeMiB = 0
+ snap.Serving[i].DiskFreeMiB = 0
+ }
+ snap.Serving = snap.Serving[:1]
+ project := func() boxchoice.WakeSnapshot { return snap }
+ for range 4 {
+ if d := s.a.ForwardTarget(context.Background(), s.rt, project); d != (edge.ForwardDecision{}) {
+ t.Fatal(d)
+ }
+ }
+ select {
+ case p := <-pages:
+ if p != "ie/shop.example.com/a" {
+ t.Fatal(p)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("no warning")
+ }
+ select {
+ case <-pages:
+ t.Fatal("page flood")
+ default:
+ }
+ if n := lockGets(s.b, s.rt); n != 1 {
+ t.Fatalf("page read store: %d", n)
+ }
+ clk.advance(time.Hour)
+ snap = placementSnapshot(clk.now())
+ snap.Serving = snap.Serving[:1]
+ snap.Serving[0].MemFreeMiB = 0
+ s.a.ForwardTarget(context.Background(), s.rt, project)
+ select {
+ case <-pages:
+ case <-time.After(time.Second):
+ t.Fatal("hour did not rearm")
+ }
+ if _, err := s.wakeForTest(context.Background()); err != nil {
+ t.Fatalf("capacity blocked wake: %v", err)
+ }
+}
+func TestPlacementDecisionLogIsBounded(t *testing.T) {
+ logs := captureLog(t)
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ for range 20 {
+ s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) })
+ }
+ if n := strings.Count(logs.String(), "HA placement host=shop.example.com"); n != 1 {
+ t.Fatalf("%d log lines", n)
+ }
+ if !strings.Contains(logs.String(), "reason=roomiest") || !strings.Contains(logs.String(), "ref=b") || !strings.Contains(logs.String(), "generation=") {
+ t.Fatal(logs.String())
+ }
+ for i := range holderCacheMax + 1 {
+ s.a.observePlacement(fmt.Sprintf("host-%d", i), PlacementDecision{Reason: "base-no-snapshot"}, boxchoice.WakeSnapshot{}, nil, time.Now())
+ }
+ if len(s.a.placementLog.hosts) > holderCacheMax {
+ t.Fatal("unbounded logs")
+ }
+ if n := lockGets(s.b, s.rt); n != 1 {
+ t.Fatalf("logging used %d reads", n)
+ }
+}
+
+func TestPlacementStaleSelfUsesBase(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ snap := placementSnapshot(time.Now())
+ snap.Usable = false
+ d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return snap })
+ if d != (edge.ForwardDecision{}) {
+ t.Fatal(d)
+ }
+ putLockFor(t, s.b, s.rt, leaseBody(t, heldByB, time.Now().Add(time.Minute)))
+ if _, err := s.b.Acquire(context.Background(), s.rt); err == nil {
+ t.Fatal("cached free observation bypassed held lease")
+ }
+ snap.LocalDenied = true
+ if d = s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return snap }); !d.Unavailable || s.wokeHere() {
+ t.Fatalf("explicit denial %+v", d)
+ }
+}
+func TestPlacementNoSnapshotUsesBase(t *testing.T) {
+ s := haService(t, "shop.example.com")
+ s.rt.HA = true
+ if d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return boxchoice.WakeSnapshot{Enabled: true} }); d != (edge.ForwardDecision{}) {
+ t.Fatal(d)
+ }
+ if _, err := s.wakeForTest(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+}
+func TestPlacementPrefersCleanReleaser(t *testing.T) {
+ now := time.Now()
+ snap := placementSnapshot(now)
+ rt := registry.Route{Host: "shop.example.com"}
+ v := &hafresh.View{Lock: hafresh.Lock{Release: &hafresh.Marker{V: 1, Box: "a", Clean: true}}}
+ if d := DecidePlacement(rt, hafresh.Self{Ref: "a"}, v, snap, PlacementPeerView{}, now); d.Ref != "a" || d.Reason != "clean-releaser" {
+ t.Fatal(d)
+ }
+ v.Lock.Release.Clean = false
+ if d := DecidePlacement(rt, hafresh.Self{Ref: "a"}, v, snap, PlacementPeerView{}, now); d.Ref != "b" || d.Reason != "roomiest" {
+ t.Fatal(d)
+ }
+ snap.LocalDenied = true
+ v.Lock.Release.Clean = true
+ if d := DecidePlacement(rt, hafresh.Self{Ref: "a"}, v, snap, PlacementPeerView{}, now); d.Ref != "b" {
+ t.Fatalf("non-serving self chosen %+v", d)
+ }
+}
+func TestPlacementChoosesRoomiest(t *testing.T) {
+ now := time.Now()
+ snap := placementSnapshot(now)
+ rt := registry.Route{Host: "shop.example.com", Account: "acct", App: "shop"}
+ if d := DecidePlacement(rt, hafresh.Self{Ref: "a"}, &hafresh.View{Absent: true}, snap, PlacementPeerView{}, now); d.Ref != "b" {
+ t.Fatal(d)
+ }
+ snap.Running["b"] = boxchoice.Load{Apps: map[string]int{"acct/shop": 1}}
+ if d := DecidePlacement(rt, hafresh.Self{Ref: "a"}, &hafresh.View{Absent: true}, snap, PlacementPeerView{}, now); d.Ref != "a" {
+ t.Fatal(d)
+ }
+}
+func TestPlacementHeldOwnerWins(t *testing.T) {
+ s := haHeldByB(t)
+ d := s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot {
+ t.Fatal("held owner reached placement")
+ return placementSnapshot(time.Now())
+ })
+ if d.Ref != "b" || d.Kind != edge.Holder {
+ t.Fatal(d)
+ }
+}
diff --git a/internal/activator/hasuspect_test.go b/internal/activator/hasuspect_test.go
index d567d1ab9..65cc9d306 100644
--- a/internal/activator/hasuspect_test.go
+++ b/internal/activator/hasuspect_test.go
@@ -28,7 +28,7 @@ import (
// TestForwardHADialFailureIs503RetryTen), or "here" (served on this box).
func (s *haSvc) frontDoor(t *testing.T, forwards *int) string {
t.Helper()
- d := s.a.ForwardTarget(context.Background(), s.rt)
+ d := s.a.ForwardTarget(context.Background(), s.rt, nil)
switch {
case d.Refuse:
if d.Ref != "" {
@@ -45,7 +45,7 @@ func (s *haSvc) frontDoor(t *testing.T, forwards *int) string {
// decide is one ForwardTarget for s's route.
func (s *haSvc) decide() edge.ForwardDecision {
- return s.a.ForwardTarget(context.Background(), s.rt)
+ return s.a.ForwardTarget(context.Background(), s.rt, nil)
}
// note is NoteForward for s's host of a forward decided as d.
@@ -380,7 +380,7 @@ func TestSuspectClearedByTakingTheLease(t *testing.T) {
if _, _, found := s.a.holders.get(s.rt.Host); found {
t.Fatal("the suspect entry survived this box taking the lease")
}
- if d := s.a.ForwardTarget(context.Background(), s.rt); d != (edge.ForwardDecision{}) {
+ if d := s.a.ForwardTarget(context.Background(), s.rt, nil); d != (edge.ForwardDecision{}) {
t.Fatalf("awake here: %+v, want served here", d)
}
}
@@ -414,7 +414,7 @@ func TestSuspectClearedByASuccessfulForward(t *testing.T) {
// A forward that came back with no answer (Status 0) proves nothing.
s, _ := suspectB(t)
s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardDone, Ref: "b"})
- if d := s.a.ForwardTarget(context.Background(), s.rt); !d.Refuse {
+ if d := s.a.ForwardTarget(context.Background(), s.rt, nil); !d.Refuse {
t.Fatalf("after a forward with no answer: %+v, want still refused", d)
}
}
@@ -430,7 +430,7 @@ func TestUnreachableKeepsNewerNews(t *testing.T) {
}
s.a.holders.setNegative(s.rt.Host)
s.a.NoteForward(s.rt.Host, edge.ForwardResult{Outcome: edge.ForwardUnreachable, Ref: "b"})
- if d := s.a.ForwardTarget(context.Background(), s.rt); d != (edge.ForwardDecision{}) {
+ if d := s.a.ForwardTarget(context.Background(), s.rt, nil); d != (edge.ForwardDecision{}) {
t.Fatalf("an old forward to b failed after a read found no holder: %+v, want served here", d)
}
}
@@ -475,7 +475,7 @@ func TestSuspectThenExpiredLeaseTakesOver(t *testing.T) {
if o, ok := hafresh.ParseOwner(v.Lock.Owner); !ok || !o.HA || o.Ref != "a" {
t.Fatalf("the lock is %+v, want this box's HA lease", v.Lock)
}
- if d := s.a.ForwardTarget(context.Background(), s.rt); d != (edge.ForwardDecision{}) {
+ if d := s.a.ForwardTarget(context.Background(), s.rt, nil); d != (edge.ForwardDecision{}) {
t.Fatalf("awake here after the takeover: %+v, want served here", d)
}
}
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go
index 103eba4d6..92e717e4d 100644
--- a/internal/edge/forwardha.go
+++ b/internal/edge/forwardha.go
@@ -25,6 +25,7 @@ import (
"sync"
"time"
+ "github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/registry"
)
@@ -38,13 +39,24 @@ import (
// follow it and ignore an outcome older than what it has learned since. host
// is rt.Host, the route's own host, never an alias the request named.
type HAForwarder interface {
- ForwardTarget(ctx context.Context, rt registry.Route) ForwardDecision
+ ForwardTarget(ctx context.Context, rt registry.Route, snapshot func() boxchoice.WakeSnapshot) ForwardDecision
NoteForward(host string, res ForwardResult)
}
-// ForwardDecision is ForwardTarget's answer. The zero value serves the request
-// here.
+// ForwardKind distinguishes lease holders from short-lived routing advice.
+type ForwardKind uint8
+
+const (
+ Holder ForwardKind = iota
+ Recovery
+ Placement
+)
+
+// ForwardDecision is ForwardTarget's answer. The zero value serves locally.
type ForwardDecision struct {
+ Kind ForwardKind
+ PeerGen uint64
+ Unavailable bool
// Ref is the box to forward the request to.
Ref string
// Refuse answers the request at the front door as an unreachable forward
@@ -79,6 +91,8 @@ const (
// answer came back from it (a hop this box refused, or a failure after
// connecting). Holder is the upstream's X-Carlos-Holder, "" when absent.
type ForwardResult struct {
+ Kind ForwardKind
+ PeerGen uint64
Outcome ForwardOutcome
Ref string
Gen uint64
@@ -155,7 +169,19 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin
if !ok {
return false
}
- d := fw.ForwardTarget(r.Context(), up.route)
+ d := fw.ForwardTarget(r.Context(), up.route, func() boxchoice.WakeSnapshot {
+ m := e.homes.Load()
+ if m == nil {
+ return boxchoice.WakeSnapshot{}
+ }
+ return m.wakeSnapshot(up.route, time.Now())
+ })
+ if d.Unavailable {
+ w.Header().Set("Retry-After", "10")
+ MarkAnswered(r)
+ http.Error(w, "This instance cannot wake right now. Please try again shortly.", http.StatusServiceUnavailable)
+ return true
+ }
if d.Refuse {
answerHolderUnreachable(w, r)
return true
@@ -165,6 +191,10 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin
}
res := e.forwardHA(w, r, host, d)
fw.NoteForward(up.route.Host, res)
+ if res.Outcome == ForwardNotInView && d.Kind == Placement {
+ answerHolderUnreachable(w, r)
+ return true
+ }
return res.Outcome != ForwardNotInView
}
@@ -179,7 +209,7 @@ func (e *Edge) frontForwardHA(w http.ResponseWriter, r *http.Request, host strin
// forwarding loop needs this line and frontForwardHA's to be wrong at once.
func (e *Edge) forwardHA(w http.ResponseWriter, r *http.Request, host string, d ForwardDecision) ForwardResult {
ref := d.Ref
- res := ForwardResult{Outcome: ForwardNotInView, Ref: ref, Gen: d.Gen}
+ res := ForwardResult{Outcome: ForwardNotInView, Ref: ref, Gen: d.Gen, Kind: d.Kind, PeerGen: d.PeerGen}
m := e.homes.Load()
if m == nil || hopVerified(r.Context()) {
return res
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go
index d5fd78a32..059b2282a 100644
--- a/internal/edge/forwardha_test.go
+++ b/internal/edge/forwardha_test.go
@@ -31,6 +31,7 @@ import (
"github.com/carlosframework/platform/internal/analytics"
"github.com/carlosframework/platform/internal/assetcache"
+ "github.com/carlosframework/platform/internal/boxchoice"
"github.com/carlosframework/platform/internal/gate"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/reqrec"
@@ -63,12 +64,14 @@ var fwHosts = []string{fwHost, fwGatedHost, fwAssetHost, fwRateHost, fwLegacyHos
// answers) and, as an HAForwarder, names target (or refuses, when refuse is
// set) and keeps every note.
type fwAct struct {
- target string
- refuse bool
- gen uint64
- asked atomic.Int64
- mu sync.Mutex
- notes []fwNote
+ target string
+ kind ForwardKind
+ unavailable bool
+ refuse bool
+ gen uint64
+ asked atomic.Int64
+ mu sync.Mutex
+ notes []fwNote
}
type fwNote struct {
@@ -91,9 +94,9 @@ func (a *fwAct) ServeHTTP(w http.ResponseWriter, r *http.Request, _ registry.Rou
return false
}
func (a *fwAct) RetireExcept(map[string]bool) {}
-func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route) ForwardDecision {
+func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route, _ func() boxchoice.WakeSnapshot) ForwardDecision {
a.asked.Add(1)
- return ForwardDecision{Ref: a.target, Refuse: a.refuse, Gen: a.gen}
+ return ForwardDecision{Ref: a.target, Refuse: a.refuse, Gen: a.gen, Kind: a.kind, Unavailable: a.unavailable}
}
func (a *fwAct) NoteForward(host string, res ForwardResult) {
diff --git a/internal/edge/haplacement_test.go b/internal/edge/haplacement_test.go
new file mode 100644
index 000000000..5298b595a
--- /dev/null
+++ b/internal/edge/haplacement_test.go
@@ -0,0 +1,78 @@
+package edge
+
+import (
+ "net/http"
+ "testing"
+ "time"
+)
+
+func TestFrontPlacementNeverFallsBack(t *testing.T) {
+ for _, keyLost := range []bool{false, true} {
+ t.Run(map[bool]string{false: "disappeared", true: "key lost"}[keyLost], func(t *testing.T) {
+ x := newFwScene(t, fwOpts{aTarget: "carol"})
+ x.aAct.kind = Placement
+ if keyLost {
+ x.a.homes.keyMu.Lock()
+ x.a.homes.keyCurrent = nil
+ x.a.homes.keyNext = nil
+ x.a.homes.keyMu.Unlock()
+ } else {
+ if err := x.seed.Delete(t.Context(), "control/edges/carol.json"); err != nil {
+ t.Fatal(err)
+ }
+ x.converge(t)
+ }
+ resp, _ := x.fetch(t, fwHost, "/")
+ if resp.StatusCode != 503 || resp.Header.Get("Retry-After") != "10" {
+ t.Fatal(resp.StatusCode, resp.Header)
+ }
+ notes := x.aAct.noted()
+ if len(notes) != 1 || notes[0].res.Outcome != ForwardNotInView || notes[0].res.Kind != Placement {
+ t.Fatal(notes)
+ }
+ a, b := x.take(t, fwHost)
+ if a.use.Requests != 0 || b.use.Requests != 0 {
+ t.Fatalf("accounted %v %v", a.use, b.use)
+ }
+ })
+ }
+}
+func TestFrontPlacementUnavailable(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ x.aAct.unavailable = true
+ resp, body := x.fetch(t, fwHost, "/")
+ if resp.StatusCode != http.StatusServiceUnavailable || resp.Header.Get("Retry-After") != "10" || body != "This instance cannot wake right now. Please try again shortly.\n" {
+ t.Fatal(resp.StatusCode, body)
+ }
+ a, b := x.take(t, fwHost)
+ if a.use.Requests != 0 || b.use.Requests != 0 {
+ t.Fatal("refusal metered")
+ }
+}
+func TestPlacementHopNeverRechooses(t *testing.T) {
+ x := newFwScene(t, fwOpts{})
+ x.aAct.kind = Placement
+ x.bAct.target = "annie"
+ x.bAct.kind = Placement
+ resp, _ := x.fetch(t, fwHost, "/")
+ if resp.StatusCode != 200 || x.aAct.asked.Load() != 1 || x.bAct.asked.Load() != 0 {
+ t.Fatalf("status %d asked %d/%d at %v", resp.StatusCode, x.aAct.asked.Load(), x.bAct.asked.Load(), time.Now())
+ }
+}
+
+func TestFrontPlacementRecoveryNotInViewKeepsBase(t *testing.T) {
+ x := newFwScene(t, fwOpts{aTarget: "carol"})
+ x.aAct.kind = Recovery
+ if err := x.seed.Delete(t.Context(), "control/edges/carol.json"); err != nil {
+ t.Fatal(err)
+ }
+ x.converge(t)
+ resp, _ := x.fetch(t, fwHost, "/")
+ if resp.StatusCode != 200 {
+ t.Fatal(resp.StatusCode)
+ }
+ notes := x.aAct.noted()
+ if len(notes) != 1 || notes[0].res.Kind != Recovery || notes[0].res.Outcome != ForwardNotInView {
+ t.Fatal(notes)
+ }
+}
diff --git a/internal/edge/wakeplacement.go b/internal/edge/wakeplacement.go
index 936a6ebc6..01f98883b 100644
--- a/internal/edge/wakeplacement.go
+++ b/internal/edge/wakeplacement.go
@@ -129,6 +129,7 @@ func (m *homeMap) wakeSnapshot(rt registry.Route, now time.Time) boxchoice.WakeS
p := decodeWakePlacement(own)
out.LocalDenied = p.localDenied
out.Region = own.Region
+ // A non-empty own placement is deliberate: missing identity declines toward Base.
if own.Region == "" || own.Placement == "" || own.DataBucket == "" || own.SecretsKeyFP == "" || !p.compatible(now) {
return out
}
diff --git a/internal/host/agent.go b/internal/host/agent.go
index aae636c84..491c38d3d 100644
--- a/internal/host/agent.go
+++ b/internal/host/agent.go
@@ -577,6 +577,7 @@ func runAgent(args []string, buildClaims ClaimFactory) {
Exec: eb,
Unit: &activator.UnitBackend{OptDir: release.OptDir()},
}, reg) // the registry satisfies activator.DueStore directly
+ armHAPlacement(svc, PageOperator)
// Sizes (#329): the provisioning passes' PolicyChanged tells this
// Service a row's size column moved, and the status tick reads each
// awake instance's size through it and the box's cgroupfs.
diff --git a/internal/host/haforward_wiring_test.go b/internal/host/haforward_wiring_test.go
index d190f4e01..b8b64598b 100644
--- a/internal/host/haforward_wiring_test.go
+++ b/internal/host/haforward_wiring_test.go
@@ -48,7 +48,7 @@ func TestAgentActivatorForwards(t *testing.T) {
if !ok {
t.Fatal("the activator the agent hands the edge is not an edge.HAForwarder")
}
- if got := fw.ForwardTarget(context.Background(), registry.Route{Host: "shop.example.com"}); got != (edge.ForwardDecision{}) {
+ if got := fw.ForwardTarget(context.Background(), registry.Route{Host: "shop.example.com"}, nil); got != (edge.ForwardDecision{}) {
t.Fatalf("a host that is not born HA forwards with %+v, want served here", got)
}
diff --git a/internal/host/haplacement.go b/internal/host/haplacement.go
new file mode 100644
index 000000000..ce89f267c
--- /dev/null
+++ b/internal/host/haplacement.go
@@ -0,0 +1,18 @@
+package host
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/carlosframework/platform/internal/activator"
+)
+
+func armHAPlacement(svc *activator.Service, page func(context.Context, string, string, string) error) {
+ setHAAwakeApps(svc.AwakeApps)
+ svc.OnHAOverCapacity = func(region, host, ref string) {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _ = page(ctx, "warning", fmt.Sprintf("Region %s needs more capacity", region), fmt.Sprintf("Region %s is short on spare capacity. Instance %s is waking on %s. Add capacity to the region.", region, host, ref))
+ }
+}
diff --git a/internal/host/haplacement_wiring_test.go b/internal/host/haplacement_wiring_test.go
new file mode 100644
index 000000000..dbfb18488
--- /dev/null
+++ b/internal/host/haplacement_wiring_test.go
@@ -0,0 +1,74 @@
+package host
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAgentArmsHAPlacement(t *testing.T) {
+ src, err := os.ReadFile("agent.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ body := string(src)
+ call := "armHAPlacement(svc, PageOperator)"
+ if strings.Count(body, call) != 1 {
+ t.Fatal("agent must arm the same Service once")
+ }
+ at := strings.Index(body, call)
+ for _, after := range []string{"startupDone = activatorStart{", "Start: svc.Start,", "go edgesFileLoop("} {
+ pos := strings.Index(body, after)
+ if pos < 0 || pos < at {
+ t.Fatalf("arming must precede %q", after)
+ }
+ }
+ if at < strings.Index(body, "svc = activator.New(") {
+ t.Fatal("armed before creation")
+ }
+}
+func TestHAPlacementPageWiring(t *testing.T) {
+ reg, _, svc, _ := wakeFixture(t, "shop.example.com", time.Hour, func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) })
+ type page struct {
+ level, subject, body string
+ remaining time.Duration
+ }
+ got := make(chan page, 2)
+ armHAPlacement(svc, func(ctx context.Context, level, subject, body string) error {
+ deadline, ok := ctx.Deadline()
+ if !ok {
+ t.Error("no deadline")
+ }
+ got <- page{level, subject, body, time.Until(deadline)}
+ return nil
+ })
+ t.Cleanup(func() { setHAAwakeApps(nil) })
+ if haAwakeApps() == nil {
+ t.Fatal("awake source not armed")
+ }
+ rt, err := reg.Get("shop.example.com")
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec := httptest.NewRecorder()
+ svc.ServeHTTP(rec, httptest.NewRequest("GET", "http://shop.example.com/", nil), *rt, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) }))
+ if rec.Code != 204 || haAwakeApps()["bab/app"] != 1 {
+ t.Fatalf("source does not read the armed Service: status %d apps %v", rec.Code, haAwakeApps())
+ }
+ if svc.OnHAOverCapacity == nil {
+ t.Fatal("callback not armed")
+ }
+ svc.OnHAOverCapacity("ie", "shop.example.com", "b")
+ select {
+ case p := <-got:
+ if p.level != "warning" || p.subject != "Region ie needs more capacity" || p.body != "Region ie is short on spare capacity. Instance shop.example.com is waking on b. Add capacity to the region." || p.remaining <= 0 || p.remaining > 5*time.Second {
+ t.Fatalf("page %+v", p)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("no page")
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 67cdf29b3..b7d19fffb 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -56,4 +56,4 @@ plan14-root-reads-fix-set-aside-exdev.tsv f9d3016cc6803338f9db19311f3f598e20c37c
plan14-root-reads-durability-3a-escrow.tsv 03a92257beb9b8aac421559e247d191bd69f28a0b26243397a1344a90d59fc2a
plan14-root-reads-rootfs-default-home.tsv 7a0a3da3d6fe7e3c77abb22676db000af2a276c3d13ccae0f038190f51287ed5
plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc
-plan14-root-reads-region-ha-p1b3a.tsv d7a408934310184a8a042d299cd6456060460a95d5707d03af6dd28d93484cc7
+plan14-root-reads-region-ha-p1b3a.tsv ff762f68961a754609f209d3a2e6f6ddef46f67eb860e511bd538c5a2ded2580
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv
index 6e2f3e80f..d5a3a24b9 100644
--- a/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p1b3a.tsv
@@ -1,11 +1,19 @@
# Census overlay region-ha-p1b3a, written by census-propose (#369). census-ruling-region-ha-p1b3a, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p1b3a.md.
-# 0 body, 0 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
-# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+# 2 body, 2 sites, 4 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 3 new dispositions: 0 reads re-frozen at their disposition with the claim, 3 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
@legacy 2ffbb58e2568a1ea38d893670ab9498c6581af1aeba74e5a4d78cc5327e531cd internal/activator/awakeapps.go Service.AwakeApps legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Count owned awake entries under the service mutex by release.RouteAccount(route)/route.App, validating the resolved account and app. Reads in-memory route values only; no store, registry or filesystem call and no new root authority. registry:App@242,whole:Route@234,whole:Route@244 1eb4a8a36fdcb246f031482676c6af586cb1ecbeabc07271c9d3021ecf355a60
-@legacy bcd9a0aa6e0e449a3900fba77c971ed0f5b06020c3d1d3af34660571f94539a5 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. registry:App@1984,registry:Host@1089,whole:Route@1120 4d138a61f816bdd353cbe52d0b3620040b6bb1b2ab04d9c13910460b92b819e3
+@legacy 653dd27f83091a121207d90a965a155e4319b70f1a6874994bdec69d35d8ab2f internal/activator/haplacement.go DecidePlacement legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Pure applicability rule reads in-memory route Host/App and RouteAccount for capacity preference, self/expired-owner recovery and explicit LocalDenied refusal; no proof, acquire, store, filesystem or root authority, and no guessed free observation. registry:App@1863,registry:Host@1825,whole:Route@1855 136b66955b351e71ec06326a564f25c7c4338ee8639fb7b6bef88adb062d7c1b
+@legacy 6e6ab5cce7e2052c11c68f2f2716f5916f4eb59d3a1603f6f9ceaa347e58998e 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. registry:App@2068,registry:Host@1173,whole:Route@1204 738a92d33ed1ff738f503f33aa33e29550f0ffb4ce66eeda9551ea83ae1b3bdc
+@legacy cf74a525f98bef3b391132d4ab21d8bf2c1c368965f9332f641469bdf0be1388 internal/activator/haforward.go Service.ForwardTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=Returns edge.ForwardDecision (Ref, Refuse, Gen) from holderCache.resolve, in memory only: a suspect holder refuses; a positive entry forwards under its generation; a failed read that revalidates an expired suspect keeps it suspect and refuses. The round-1 cache connection gate is removed. The same single bounded (2 s) lock.json read through readHolderView on a miss; no new read and no new S3 request; root never calls it.;rev3=census-ruling-region-ha-p1b3a;basis=Retain immutable lock observations and evaluate the pure placement rule after all existing bypass and positive-holder/suspect checks. Read in-memory route Host and whole Route for snapshot/decision only; same bounded lock read, no new store or filesystem operation and no acquire authority. registry:HA@140,registry:Host@1028,registry:Host@2046,registry:Host@2334,registry:Host@302,registry:Host@415,whole:Route@1563,whole:Route@1978,whole:Route@216,whole:Route@2415,whole:Route@769 2e50631e05a29ac96897ed7142e2100d585ccb7ab6d845956d571547dddd779c
+@legacy b10df392ce2033c88a0fb712b47a773f006403af65f681b5f42262cb1332a710 internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it.;rev3=census-ruling-region-ha-p1b3a;basis=Pass the existing route to a lazy cached wakeSnapshot closure, handle explicit local denial before all accounting, and refuse a disappeared Placement choice rather than falling through locally; whole Route read only, no new store or filesystem operation and no root authority. registry:HA@225,registry:Host@928,whole:Route@228,whole:Route@405,whole:Route@548,whole:Route@931 ae7b0d8715c18d05fdebfb3a65861b8b83cd051b6e0d25a60ea16cc4867a8fbc
+internal/activator/activator.go type Service authority B,C,D,F,J4 rev3=PROPOSED-seed; existing activator lifecycle and due-wake state plus owned seed exclusion and incarnation-keyed diagnostics; normal refusal and preparation ordering remain authoritative; PROPOSED-plans-2-box-limits adds the idleFor hook field, which only narrows idle windows;rev3=census-ruling-plans-4c-box-throttle;basis=gains the maxRunFor hook field beside idleFor (plans 4c). No read added.;rev3=census-ruling-plans-4d-lapse;basis=gains the disabledFor hook field beside maxRunFor (plans 4d). No read added.;rev3=census-ruling-remote-instance-metrics;basis=gains tenancySeq, hostTenants and hostMixed, in-memory fields for Tenancies; no read added;rev3=census-ruling-region-ha-p1a;basis=the agent as carlos: one more field, markers (markerRetry: an atomic running flag and the last log time) for retryOwedMarkers; no read added; merge of origin/main d7ae1d76: main's fields are kept as main has them (census-ruling-remote-instance-metrics: tenancySeq, hostTenants, hostMixed); this branch's change is the same as above;rev3=census-ruling-rootfs-apps-3;basis=rootfs Plan 3 Tasks 7 and 8: new fields for rootfs admission (rootfsArmed, rootfsSwept), the per-host gate ask and refusal memo, and residency state (lister, backoff, start ceiling, cursor, test seam); no read;rev3=census-ruling-rootfs-apps-3-release;basis=rootfs Plan 3 Group R: one new field, releaseOps (host to the in-memory release record, under a.mu); no read;rev3=census-ruling-rootfs-apps-3-workers;basis=rootfs Plan 3 Group W: one new field, leaseNow (a clock seam for a worker start's headroom against the lease deadline, nil is the real clock); no read;rev3=census-ruling-region-ha-p1b2;basis=region HA P1b-2: gains the holder cache and its single-flight state; no read;rev3=census-ruling-managed-fleets-1b;basis=managed fleets 1b (controller ruling after branch review R1, and Paul's R2 ruling): one field, Fleet (activator.FleetWake: the box's fleet state, not on a fleet by default, on a fleet with a known label and a record reader, or on a fleet with an invalid identity), set by the agent before Start and read only by routeCurrentUnderLease. No read in the declaration. Agent, not root.;rev3=census-ruling-rootfs-apps-6;basis=rootfs Plan 6 Task 7a fix round 1: one field, drainBudget (time.Duration), which New copies from residentDrainBudget and a rootfs entry's lease watch reads in its place, so a test's change of the package var never races a watch goroutine; declaration only, reads nothing; merge of origin/main 6f1f6ca6: main's one field, Fleet (activator.FleetWake), is kept as main has it (census-ruling-managed-fleets-1b); this branch's change is the same as above;rev3=census-ruling-region-ha-p1b3a;basis=Add bounded placement peer and diagnostic state and the over-capacity callback; no read in this declaration and no new root authority. e3f1f4dd7c3e94d923878e6bdb39e93416887d775f972a7f6a6674ba300292c4
+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. file:Exec@17617,file:Open@1150,file:Statfs@44473,registry:App@11372,whole:Route@11364,whole:Route@28441 025250d688e25a05823b2e168207acfd1c23dbec4a5f5c87e96d11b73c7456ae
internal/activator/awakeapps.go Service.AwakeApps legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Count owned awake entries under the service mutex by release.RouteAccount(route)/route.App, validating the resolved account and app. Reads in-memory route values only; no store, registry or filesystem call and no new root authority. registry:App@242,whole:Route@234,whole:Route@244 1eb4a8a36fdcb246f031482676c6af586cb1ecbeabc07271c9d3021ecf355a60
-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. registry:App@1984,registry:Host@1089,whole:Route@1120 4d138a61f816bdd353cbe52d0b3620040b6bb1b2ab04d9c13910460b92b819e3
-@coverage internal/activator b9b984a8634f6783c82923f8e4736ef41aa8087dc2e748fc6e30f8645eb0ce7f
+internal/activator/haplacement.go DecidePlacement legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b3a;basis=Pure applicability rule reads in-memory route Host/App and RouteAccount for capacity preference, self/expired-owner recovery and explicit LocalDenied refusal; no proof, acquire, store, filesystem or root authority, and no guessed free observation. registry:App@1863,registry:Host@1825,whole:Route@1855 136b66955b351e71ec06326a564f25c7c4338ee8639fb7b6bef88adb062d7c1b
+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. registry:App@2068,registry:Host@1173,whole:Route@1204 738a92d33ed1ff738f503f33aa33e29550f0ffb4ce66eeda9551ea83ae1b3bdc
+internal/activator/haforward.go Service.ForwardTarget legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's activator answers the edge with a holder box ref for an HA route not awake here, from its in-memory holder cache or one bounded (2 s) lock.json read through readHolderView; reads the route's HA flag and host from its own registry row; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=Returns edge.ForwardDecision (Ref, Refuse, Gen) from holderCache.resolve, in memory only: a suspect holder refuses; a positive entry forwards under its generation; a failed read that revalidates an expired suspect keeps it suspect and refuses. The round-1 cache connection gate is removed. The same single bounded (2 s) lock.json read through readHolderView on a miss; no new read and no new S3 request; root never calls it.;rev3=census-ruling-region-ha-p1b3a;basis=Retain immutable lock observations and evaluate the pure placement rule after all existing bypass and positive-holder/suspect checks. Read in-memory route Host and whole Route for snapshot/decision only; same bounded lock read, no new store or filesystem operation and no acquire authority. registry:HA@140,registry:Host@1028,registry:Host@2046,registry:Host@2334,registry:Host@302,registry:Host@415,whole:Route@1563,whole:Route@1978,whole:Route@216,whole:Route@2415,whole:Route@769 2e50631e05a29ac96897ed7142e2100d585ccb7ab6d845956d571547dddd779c
+internal/edge/forwardha.go Edge.frontForwardHA legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p1b2;basis=new (region HA P1b-2): the agent's edge decides at the front door whether to forward a visitor request: reads the route's HA flag and host from the box's own registry row and asks the activator; forwards only to a box in view over the existing signed hop; root never calls it;rev3=census-ruling-region-ha-dead-holder-backoff;basis=ForwardTarget returns a ForwardDecision (Ref, Refuse, Gen); a Refuse is answered at the front door with the existing unreachable answer (503, Retry-After: 10, same body, via answerHolderUnreachable), with no forward, dial, note or per-request step. A forward passes the decision to forwardHA and NoteForward carries Ref and Gen back. The round-1 connection callback (NoteConnected) is gone: the dial bound now lives in forwardTransport's forwardDialGate, which coalesces TCP dials per holder address in memory. The same 5 read sites; no new read; root never calls it.;rev3=census-ruling-region-ha-p1b3a;basis=Pass the existing route to a lazy cached wakeSnapshot closure, handle explicit local denial before all accounting, and refuse a disappeared Placement choice rather than falling through locally; whole Route read only, no new store or filesystem operation and no root authority. registry:HA@225,registry:Host@928,whole:Route@228,whole:Route@405,whole:Route@548,whole:Route@931 ae7b0d8715c18d05fdebfb3a65861b8b83cd051b6e0d25a60ea16cc4867a8fbc
+@coverage internal/activator 824f9d800d661913d15a0b09e65511d8d9c7d6b693c7c6a062c1327a32282872
@coverage internal/boxchoice 2461971eb41338ab53f0c7c77c0e01b1e0b854f657a1cecddfbaf6c142f0feed
-@coverage internal/edge 13a04521bd87e65f83c1cb041cc72fc997082f84881a94c8aa74fe6752b46180
-@coverage internal/host 827414424edca7b51415e327c5ce0c9d95a30a4bbe7f0eb418fdc03ddc77538b
+@coverage internal/edge be7b24797e5b0f87f01aafc728c77a8939571a77d8e17394b74b3b6cec29d89d
+@coverage internal/host 8e80c946443f5ec139b840d17a5e7e7e51a9b9a1645c08c1d50dfb275559cb47