Repository navigation
fix(harness): close the gRPC channel that /turn opens (#894) - #896
Conversation
The sync `/turn` path leaked one gRPC channel per turn. `GrpcRelayTransport.close()` already existed and `run-leaf.ts` called it at six sites, but `AcquiredTurnSandbox` exposed no way to reach it, so the one caller that owns the transport it opened never closed it. Measured at ~15-19 KB per turn per worker on the P6 rig, ~10 GB/hour at 149 turns/s, which is what made every RSS-derived capacity figure for this tier unusable. `closeTransport` is a separate member rather than part of `release` so the injected path is a pair of no-ops instead of a conditional: a prompt leaf keeps using the transport it injected after this turn hands the lease back, and closing it here would both break run-leaf's "closes it exactly once" contract and cancel the leaf's converge and cleanup execs. Two details beyond the original fix: - It is `async`, not `() => selected.transport.close()`. A close that throws SYNCHRONOUSLY has no promise for the caller's `.catch` to attach to, so it would replace the error that explains the turn's failure with its own — which is exactly what two existing turn-placement-on-throw tests caught against the direct form. - The template-seed failure path closes its own channel. A throwing acquire never returns a `closeTransport` for anyone to call, so without it a failing seed leaks one channel per attempt, on the path that retries hardest (a failed seed leaves no marker and is re-run). Both halves of the test are shown capable of failing: dropping the `finally` call fails the three structural tests, and wiring `closeTransport` to a no-op fails the two behavioural close tests. The structural half exists because the original defect was not a wrong `close()` but a correct one that nothing invoked — a test that only drove `closeTransport()` directly would have passed against the leaking build. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Author: cwiklik (MEMBER — maintainer)
Areas reviewed: TypeScript harness — executeTurn teardown and acquireTurnSandbox in harness/src/run-turn.ts, the new harness/test/grpc-channel-per-turn.test.ts, and the transport's close semantics in @moca/k8s-sandbox
Agent/IDE config (.claude/.vscode): none
Commits: 1, signed off (DCO pass)
CI status: 17/17 green at 30427da (base 156530f7; main is now 28db50d6, 2 commits ahead, and the branch merges clean with it; mergeable: true)
The fix is right, and complete for the caller it names. I verified independently:
- the ownership split — injected ⇒
closeTransportis a noop, leased ⇒ it closes the transporttake()built — matches whereselectPoolSandboxbuilds it (select-sandbox.ts:775-778), and the sixrun-leaf.tsclose sites quoted in the comments are at exactly those lines (:713 :903 :968 :1118 :1191 :1319); GrpcRelayTransport'sclosedflag (packages/k8s-sandbox/src/grpc-relay-transport.ts:213-217) makes the "close twice is safe" claim true, including through the optionalclient.close?.()that test fakes omit;SandboxTransport.close(): Promise<void>is required, so the addedawaitis right;- no pre-
tryexit can strand a live transport: theassertServerSandboxcatch throws only whenacquired.sandboxis null (where the close is a noop anyway), andleaseTimings/intEnvcannot throw; selectPoolSandboxthrowing frommakeExecClientdoes so while evaluatingmake()'s argument, before a transport exists, sotake()'s release-and-rethrow path cannot lose one either;- the
finallyorder is right:attached.detach()(a remote exec) → clear timer →release()→closeTransport(), andwithWorkspacePatch's patch capture runs inside thetry, so the transport is still open for it.
One adjacent path still drops a transport it built, without closing it — it is not in this diff, so it is noted here rather than inline:
suggestion (follow-up, not blocking) — harness/src/select-sandbox.ts:935-936. In the first-turn affinity claim race, the loser does await got.release() and then either throws SandboxAffinityPendingError (raced) or recurses into select() at :937. got was built by take() (:763-795), so its SandboxExecClient — and its channel — is dropped unclosed. That is the same defect this PR fixes, one caller up, and the raced branch is reached from a 503 the client retries, so it accumulates per retry under first-turn concurrency. await got.transport.close().catch(() => {}) beside the release() would close it; take() neither seeds nor execs, so nothing is outstanding on that transport. Worth its own issue rather than widening this PR.
Not re-measured, and not required here: the ~15-19 KB/turn figure. The PR's own negative controls (drop the finally call / no-op the closeTransport) are the right evidence that the new tests can fail.
Assisted-By: Claude Code
`take()` builds a gRPC channel per lease, so the loser of the first-turn affinity claim race gave the LEASE back and dropped a live channel: neither exit closed it, since the `raced` branch throws and the recursion takes a fresh lease and a fresh transport. That branch is reached from a 503 the client retries, so it accumulates one channel per retry under first-turn concurrency. Same defect as #894, one caller up, found by the review of #896 rather than by a measurement. Closing there is safe because `take()` neither seeds nor execs, so nothing is outstanding on the transport it just built. Best effort like the release beside it: a failed close must not stop the loser converging on the winner. `:935` is the only such site. `remember()` is best-effort and never throws, so no affinity write can skip a `return got`, and the affinity-prior path either returns `got` or throws from the `!got` branch, where no transport exists. The test distinguishes the two transports rather than counting closes, so it also pins that the close does NOT reach the winner's channel, and it was shown capable of failing: with the close removed it reports `expected [] to deeply equal [ 'm-0' ]`. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Closes #894.
The defect
selectPoolSandboxbuilds oneSandboxExecClientper lease, i.e. per turn(
harness/src/select-sandbox.ts:775-800→makeRelayExecClient,:503), and grpc-js gives eachclient its own channel — it does not pool them across
Clientinstances (probed: two clients to thesame target with the same credentials return distinct channel objects).
GrpcRelayTransport.close()exists, is idempotent, and the leaf path calls it at six sites(
harness/src/run-leaf.ts:713,:903,:968,:1118,:1191,:1319). The sync/turnpathcould not:
AcquiredTurnSandboxexposedsandbox,leased,heartbeat,releaseandplacement,and nothing that reached the transport it opened. So the one caller that owns the transport never
closed it.
This was not a wrong
close()— it was a correctclose()that nothing invoked.Measured on the P6 rig, heap-diffing one worker across ~2,400 turns: snapshot A held 0
InternalChannels, snapshot B held exactly 2,406. ~15-19 KB per turn per worker, ~10 GB/hour at 149turns/s. The retention is invisible to fd- and connection-count checks, because grpc-js shares
subchannels globally by target+credentials: 2,406 dead channels held only 4 sockets, while one
permanently-live
Subchannel'sstateListenersSet accumulated an entry — and a whole channel graph— per turn. It is why no RSS-derived capacity figure for this tier was usable while it stood.
The fix
closeTransport: () => Promise<void>onAcquiredTurnSandbox, wired at all three constructionsites, and called in
executeTurn'sfinallyafterrelease()with.catch(() => {}).It is a separate member rather than part of
releaseso the injected path is a pair of no-opsinstead of a conditional: a prompt leaf keeps using the transport it injected after this turn hands
the lease back, and closing it here would both break run-leaf's "closes it exactly once" contract and
cancel the leaf's converge and cleanup execs.
Two details beyond the fix as originally written on an unmerged branch, both found by tests rather
than by reading:
async. The direct form() => selected.transport.close()throwssynchronously when close fails, so there is no promise for the caller's
.catchto attach to,and the close error replaces the error that explains the turn's failure. Two existing tests
(
turn-placement-on-throw.test.ts) failed against that form withCannot read properties of undefined (reading 'close')where they expectedboom.closeTransportfor anyone to call, so without it a failing seed leaks one channel per attempt —on the path that retries hardest, since a failed seed leaves no marker and is re-run next turn.
Release before close, matching run-leaf: by the time the
finallyruns the turn has fully unwoundand no exec is outstanding on either path, so the only real difference between the orders is
consistency — and keeping them identical means an ordering bug, if there is one, is one bug in two
places rather than a divergence to explain. The close is swallowed for the same reason
release()is:a failed close costs this worker one retained channel, where throwing costs a turn that did its work
and reports an error.
Tests
harness/test/grpc-channel-per-turn.test.ts, nine cases in two halves. The behavioural half pins theseam (leased path closes exactly once; idempotent under a second teardown; an injected transport
is never closed; a no-op when nothing resolved; the seed-failure path closes its own channel). The
structural half pins the call inside
executeTurn'sfinally— because a test that only drovecloseTransport()directly would have passed against the leaking build.Both halves are shown capable of failing:
finallycallcloseTransportto a no-opVerification
vitest run --root harness test/grpc-channel-per-turn.test.tsvitest run --root harnessvitest run --root packages/servermake typecheckSKIP=hadolint-docker make lintThe 3 harness failures are pre-existing and were checked, not assumed: with
harness/src/run-turn.tsreverted to
mainthe samepromote.test.tsprojectRootcase andcontext-overlay.test.ts"in a real shell" cases still fail, and neither file imports anything this PR touches.
context-overlaygave 1 failure on one run and 2 on another, so it is also flaky.Not re-measured: the ~15-19 KB/turn figure. This proves the channel is now closed, not what the fix
recovers under load.
Assisted-By: Claude Code