Skip to content

pool: one rule tells a replaced record from a released one; a release follows the id through a resize; failover.go and claim.go split - #677

Merged
CMGS merged 37 commits into
mainfrom
pool-cleanup
Dec 1, 2026
Merged

CMGS merged 37 commits into
mainfrom
pool-cleanup

Conversation

@CMGS

@CMGS CMGS commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

One cleanup pass over sandboxd/pool after the resize work (#644, #653, #657, #674, #676) and the checklist (#675), plus the remaining structural steps of #419 and a modern-Go pass over engine, server, store, mcp and silkdtest.

Behaviour changes

  1. A call that meets a resize without waiting answers the retry, not 404. Renew, PUT/PATCH env, PUT tun (plan and commit) and a volume commit look a record up without a lock and check it under m.mu. A resize between the two answered 404 unknown sandbox although the claim still exists. They now answer 503 sandbox changed while the call waited; retry, and the resend reaches the new record.
  2. A release follows the id through a resize. Manager.Release resolves the id again with the same credential when its release finds the record replaced, and releases the record that holds the id: 204. Before, a node without archive_failover answered 404 (both SDKs' Close then did a lookup and a resend), and a node with archive_failover answered the 503 since sandboxd: a resize verb moves a hibernated claim to another pool size and cold-boots it from its disk #644, which defer sb.Close(), the LangChain close and the mcp shutdown drop: the resized claim then lived to its TTL.
  3. retireReplica and unrowExpired leave the registry row alone when they meet a replaced record. The old record keeps ReplicaCk, ArchiveCk and ArchiveEpoch, so these passes consumed the row the new record relies on; no peer could adopt the claim until the orphan sweep re-armed the row.

Not changed: the paths that take the transition lock with TryLock (lockServing's fast path, the passive dial, SetInstanceMetadata) read what main reads. Resize holds the old record's lock from before the swap until the cold boot has finished, so a caller reaches the old record there only if it stalls between its lookup and the lock for the whole resize. CHECKLIST.md keeps that row as an accepted gap.

The other sites that answer ErrReplaced (captureAllowed, beginWake, commitWake, settlePendingSnap, Resize and its reshape) are reached with the record's transition lock held, as on main, so no caller sees a different answer from them.

Every failed reason and error string is byte-identical; only the status of the calls in (1) and (2) changes. docs/sandboxd-api.md, docs/sdk.md and docs/sdk-python.md carry the new answers per route.

Consumers of (1) and (2), read at each call site: Go and Python SDK Renew / SetEnv / PatchEnv get a retryable 503 instead of a 404 that read as "gone"; sandbox-operator, vk-sandbox and cocoonbox read a release 404 as released and so left a resized claim running, and with (2) their delete releases it; SDK Close, the OpenAI and LangChain adapters and mcp get 204 through (2).

Structure

  • One rule for "is this record still the claimed one" (held.go): holdsLocked for passes, heldErrLocked for calls (ErrReplaced vs ErrUnknownSandbox), servingErrLocked for a record that must also not be paused for a move. They replace 44 inline compares of m.claimed[id] with a record; a source-scan test fails on a new compare outside held.go.
  • failover.go (837 lines) → archive_row.go, archive_intent.go, adopt.go; claim.go (830) → claim.go, release.go, dial.go, quota.go. Pure moves: the sorted lines of the package before and after each move differ only by package and import lines.
  • Manager fields 85 → 76: the replicate and unfence single-runner gates join sweeps; the heal peers, semaphore and flights join checkpointHeals; disk and memory pressure become one nodePressure value with its own checks (disk.go + memory.go → pressure.go).
  • Shared helpers where the same lines stood three or more times: sweepBounded, storeErr (7 sites), claimStore.commitOrRecommit (7 sites), volumeCatalog.addHolders, ownedTemplate with the digest, readJSONFile[T] (3 loaders), exitBlocker.
  • Outside the pool: engine runJSON[T] and silkdCollect, server handleBodyVerb[T], mcp generic put/drop and one JSON tool result, store ExportFiles, silkdtest request iterator and slices.Chunk.
  • CHECKLIST.md names the helpers and files as they are now; the two gaps this change closes are gone from it (15 accepted → 13), none open.

Tried and dropped

  • An identity check after TryLock on the three paths above: one more map lookup (and for two of them one more m.mu section) on every data-plane call, for a window no caller reaches. It landed early in the series and is reverted in it.
  • A templateCache type for the template fields: +28 production lines, six one-caller methods.
  • One entryErrLocked for Resize's entry checks: it cannot sit both before and after the checks that decide which error wins.
  • Field groups for volumes, failover and the admission counters: a prefix already groups them and a type would only add forwarding.
  • From the lens pass: a shared addCount on the claim path (== 0 vs <= 0), a generic appendAudit (one call and one time.Now per request with audit off), rewriteRowIf (flag arguments), readChunk through io.ReadFull (changes the error a short read gives).

Size

37 commits. Production Go +1378 −1434 (net −56), tests +258 −68 (net +190), comment lines +28 −28, docs +27 −27. Pool production files 50 → 55; the largest is pool.go at 833 lines (was failover.go 837, pool.go 831, claim.go 830).

Hot path

Target: nothing added against main on the claim path or the data plane. Measured against main f1e66f7 on one machine: go tool objdump of the pool test binary per function, and an A/B of both trees interleaved in one run (12 samples per arm, order swapped every round; Hot* are benchmarks written for this comparison, the others are in the tree).

Claim path and data plane:

  • Instruction streams identical to main: ClaimWarm, ClaimProvision, finalize, finalizeBatch, armIfRunning, admitOptions, quotaErr, resolve, byID, DialPort, dialPort, dialRunning, dialPassive, SetInstanceMetadata, wakeOrRead. heldErrLocked, holdsLocked and servingErrLocked inline at every site.
  • lockServing: 248 instructions (main 271), 10 calls (11), the same three map lookups. Renew: 634 (638), 26 calls (27).
  • capacityErr: 294 instructions (main 293). One ADD forms the address of the pressure group for diskErr, which is out of line in both; memoryErr inlines in both.
  • admitClaim: 223 instructions in the binary (main 212), because addHolders carries the drop-at-zero branch that adoptVolumes did not have. A claim without volumes runs none of them. A claim with volumes runs one more compare-and-branch pair per volume and never the delete.
                            main          head
QuotaErr/no_reservations    24.14n ±  5%  24.29n ± 17%  ~ (p=0.767 n=12)
QuotaErr/two_reservations   24.06n ± 14%  24.38n ± 12%  ~ (p=0.291 n=12)
VolumeAdmission             2.315µ ± 31%  2.395µ ± 13%  ~ (p=0.551 n=12)
HotLockServing              20.95n ± 28%  20.85n ±  3%  ~ (p=0.213 n=12)
HotDialPassive              112.7n ±200%  113.2n ±  8%  ~ (p=0.434 n=12)
HotDialToken                154.9n ± 29%  158.2n ± 13%  ~ (p=0.932 n=12)
HotSetInstanceMetadata      44.16n ±  6%  44.82n ± 18%  ~ (p=0.713 n=12)
HotRenew                    236.3µ ± 15%  253.2µ ± 47%  ~ (p=0.887 n=12)
HotClaimWarmRelease         458.8µ ± 40%  557.4µ ± 50%  ~ (p=0.799 n=12)
HotClaimProvisionRelease    472.8µ ± 21%  483.7µ ± 37%  ~ (p=0.551 n=12)
WakeRunningClaim/holders=0  134.7n ±  8%  136.0n ± 30%  ~ (p=0.671 n=12)

Allocations per op are equal on every row above. The machine also ran container tests during the samples, which is where the wide intervals come from; no row differs at p < 0.05.

Worse than main, off the claim path and the data plane, accepted:

  • An idle, archive or replicate pass that finds nothing (5 s tick) allocates 3 objects (104 to 136 B) where main allocated none: the logger and the item closure are built before sweepBounded sees an empty list. archiveOnce on an empty node: 2.088µ → 2.212µ (+5.9%, p=0.006).
  • The answer that tells a replaced record from a released one costs 10 to 19 instructions in beginWake, releaseResolved, commitTun and lockTransition (one errors.Is call), and Release is 23 instructions longer for its loop. Claim + release shows no difference.

Gates

sbx-gate.sh on a3ff8ae: golangci-lint v2.15.0 0 issues. ×10 (five modules, darwin and linux), asl and fmt clean, race tests green on darwin and in a linux/arm64 container.

Hardware

Two rounds on the testbed (one NUMA node, 24G slice), binaries built from this head (sandboxd devel-a3ff8aef98be) with main's binary (devel-f1e66f758d34) as the control. Every run checked that the listener was the arm's binary by sha.

cell result
repo e2e scripts: sandboxd-e2e, port-e2e, archive-e2e PASS (archive: archived in 37.6 s, woke in 112 ms)
resize: the main path, both refusals, a failed cold boot that recovers, a failed journal write that is undone PASS (resize 204 in 0.655 s; recovery 5.5 s after the 500)
renew and GET hammered across a resize PASS: 514 calls, 323 answered across the resize, none a 404 or another wrong status; no call landed in the window, so the 503 itself was not observed
two nodes: layout probe, live move, archive failover, replica failover, a restarted node that must not serve VALID and PASS (move downtime 264 ms; adoption 12.1 s after the kill)
a release that meets a resize on the second node PASS: the release was sent 0.463 s before the resize answered, waited 0.567 s, both 204; row 404, VM gone; usage claim,hibernate,resize,vmm_restart,release
warm-claim A/B against main, 18 rounds, main / head / main again in every order NO VERDICT overall by the rule fixed before the run: the two copies of main differ on cold boot ([+0.2, +3.85] ms) and on the 16-clone burst ([+0.85, +13.5] ms), so those two measures get no verdict. The other six pass: warm hit 0.400 ms vs 0.400 ms (head − main [+0.000, +0.050]), clone, fs_stat, fs_pull, burst wall, refill. No measure fails
archived wake on the S3 store (second round, this head only): hibernate, archive, an env change, wake PASS: archived after 52 s; wake 204 in 0.364 s by one clone from the archive, no retry and no restart; disk and memory markers kept, the env change in the guest, boot id unchanged; usage claim,hibernate,archive,unarchive,release; the archive's data gone from the store after the wake (its manifest stays, as on main); sandboxd logged no warning and no error

Not run: the egress, socks and credentials scripts (they need an uplink the round did not have). Not reached by any cell: change (3) above (the replica-retire and expired-row passes run only for a claim whose pool stopped replicating or whose lease lapsed), which rests on its unit tests. The two nodes shared one host, each in its own mount namespace.

Closes #419.

CMGS added 30 commits November 30, 2026 23:11
…lease, env and tun answer 503 for a replaced record

held.go holds the two answers to "is this record still the claimed one":
holdsLocked for passes and bools, heldErrLocked for calls, which tells a
replaced record (ErrReplaced) from a released one (ErrUnknownSandbox).
Every inline compare of m.claimed[id] with a record now goes through one of
them, and a test fails on any new compare outside held.go.

Renew, releaseResolved, writeEnv, planTun and commitTun check the record
under m.mu after a lookup that holds no lock; a resize between the two
answered 404 although the claim still exists. They now answer 503 and the
retry reaches the new record. commitVolumeRun answers like its sibling
checkVolumeRunLocked. The other heldErrLocked sites run under
lockTransition or lockServing, so their answer does not change.
… its doors alone

The old record of a resized claim keeps ReplicaCk, ArchiveCk and
ArchiveEpoch, so retireReplica and unrowExpired consumed the registry row
the new record relies on before commitIfLive found the record replaced:
no peer could adopt the claim until the orphan sweep re-armed the row.
Both now check the record under m.mu right after taking its lock and
return when another record or none holds the id; the swap needs that lock,
so the answer holds for the rest of the pass.

disarmIfReleased closed the doors at the id for any record that is not
the claimed one; Disarm is keyed by id, so for a replaced record it closed
the new record's doors. It now disarms only when no record holds the id.
lockServing's fast path, the passive branch of dialRunning and
SetInstanceMetadata served through the record they looked up once its
TryLock succeeded, so a caller that stalled across a resize reached the
old record. lockServing now reads heldErrLocked in the m.mu section that
already reads the move pause, before the TryLock, so the data plane keeps
one m.mu acquisition; the passive dial and SetInstanceMetadata check the
record under m.mu after the TryLock. Each answers ErrReplaced (503) for a
replaced record and ErrUnknownSandbox for a released one.

The resize test asserted that a wake through the replaced record reaches
the running guest; it now asserts ErrReplaced. The egress-lane wake test
passed records that were never claimed, which lockServing now refuses
first, so it registers them as claims.
…vmm exited"

Resize trimmed the "vmm exited; " prefix that coldBootBlocker added for the
liveness pass. The prefix now belongs to the two liveness callers, which add
it when the VM record exists, so every failed reason and error string stays
byte-identical and "vm record gone" keeps no prefix.
…y close

Section 1 names held.go and its two helpers, the 503 of the calls that
check the record after a lock-free lookup, the identity check of the
retire and unrow passes, and disarmIfReleased. Section 7 drops the 404
gap and the consumed-row gap, and narrows the TryLock gap to the window
lockServing keeps between its m.mu check and its TryLock.
Both SDKs' Close turned a release 404 into a lookup and a resend, which released the resized record. A 503 retry is returned to the caller instead, and defer-style callers (defer Close, the LangChain close, the mcp shutdown) drop it and leave the resized claim running until its TTL.
On a node with archive_failover the release already answered that 503 since #644: it waits for the whole resize in lockTransition and then finds the record replaced.

Release now resolves the id again with the same cred and releases the record that holds it whenever its release answers ErrReplaced. Each extra pass needs a resize that completed in between, so the loop is bounded by the resizes that ran. releaseRowed and releaseResolved still answer ErrReplaced to their caller.

Hot path: none. Release is not on the claim path, and the common release is still one resolve and one release.
CMGS added 7 commits December 1, 2026 01:00
…can reach

Resize takes the old record's Transition before it swaps the record and holds it until the cold boot of the new record has finished, so a TryLock on the old record succeeds only for a caller that stalled between its lookup and its TryLock for the whole resize. The checklist keeps that window as an accepted gap; lockServing keeps its check, which reads the record in the m.mu section it already takes.
…eplaced record there

The callers in archive.go, hibernate.go and liveness.go hold the record's Transition, which the swap needs, and the one in claim.go runs before the claim response is sent, so none meets a replaced record. retireReplica and unrowExpired keep their early return: those passes copy pointers and act later.
…the lock answers a replaced record

The identity check in lockServing's first m.mu section added one map lookup to every data-plane call (wake, dialPort, the agent relay, the non-passive dial) against main. Resize holds the old record's Transition from before the swap until the new record's cold boot has finished, so a caller that looked the old record up before the swap fails its TryLock and blocks, and the check after the lock answers ErrReplaced; only a caller that stalled for the whole resize gets the TryLock first.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pool: Manager carries most of the node's state machine

1 participant