Skip to content

fix(harness): close the gRPC channel that /turn opens (#894) - #896

Merged
cwiklik merged 1 commit into
rossoctl:mainfrom
cwiklik:fix/894-close-turn-grpc-channel
Nov 18, 2026
Merged

cwiklik merged 1 commit into
rossoctl:mainfrom
cwiklik:fix/894-close-turn-grpc-channel

Conversation

@cwiklik

@cwiklik cwiklik commented Nov 18, 2026

Copy link
Copy Markdown
Contributor

Closes #894.

The defect

selectPoolSandbox builds one SandboxExecClient per lease, i.e. per turn
(harness/src/select-sandbox.ts:775-800 → makeRelayExecClient, :503), and grpc-js gives each
client its own channel — it does not pool them across Client instances (probed: two clients to the
same 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 /turn path
could not: AcquiredTurnSandbox exposed sandbox, leased, heartbeat, release and placement,
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 correct close() 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 149
turns/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's stateListeners Set 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> on AcquiredTurnSandbox, wired at all three construction
sites, and called in executeTurn's finally after release() with .catch(() => {}).

It 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 fix as originally written on an unmerged branch, both found by tests rather
than by reading:

  1. It has to be async. The direct form () => selected.transport.close() throws
    synchronously when close fails, so there is no promise for the caller's .catch to 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 with
    Cannot read properties of undefined (reading 'close') where they expected boom.
  2. 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, since a failed seed leaves no marker and is re-run next turn.

Release before close, matching run-leaf: by the time the finally runs the turn has fully unwound
and 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 the
seam (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's finally — because a test that only drove
closeTransport() directly would have passed against the leaking build.

Both halves are shown capable of failing:

Negative control Result
Drop the finally call the 3 structural tests fail
Wire closeTransport to a no-op the 2 behavioural close tests fail

Verification

Check Result
vitest run --root harness test/grpc-channel-per-turn.test.ts 9 passed
vitest run --root harness 950 passed, 3 pre-existing failures
vitest run --root packages/server 602 passed
make typecheck clean
SKIP=hadolint-docker make lint clean (hadolint skipped, no Docker)

The 3 harness failures are pre-existing and were checked, not assumed: with harness/src/run-turn.ts
reverted to main the same promote.test.ts projectRoot case and context-overlay.test.ts
"in a real shell" cases still fail, and neither file imports anything this PR touches.
context-overlay gave 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

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]>
@cwiklik
cwiklik requested a review from pdettori as a code owner November 18, 2026 19:05
@pdettori pdettori added the ready-for-ai-review Request automated AI code review from clawgenti label Nov 18, 2026

@ingpaolodettori-dev ingpaolodettori-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ⇒ closeTransport is a noop, leased ⇒ it closes the transport take() built — matches where selectPoolSandbox builds it (select-sandbox.ts:775-778), and the six run-leaf.ts close sites quoted in the comments are at exactly those lines (:713 :903 :968 :1118 :1191 :1319);
  • GrpcRelayTransport's closed flag (packages/k8s-sandbox/src/grpc-relay-transport.ts:213-217) makes the "close twice is safe" claim true, including through the optional client.close?.() that test fakes omit; SandboxTransport.close(): Promise<void> is required, so the added await is right;
  • no pre-try exit can strand a live transport: the assertServerSandbox catch throws only when acquired.sandbox is null (where the close is a noop anyway), and leaseTimings/intEnv cannot throw;
  • selectPoolSandbox throwing from makeExecClient does so while evaluating make()'s argument, before a transport exists, so take()'s release-and-rethrow path cannot lose one either;
  • the finally order is right: attached.detach() (a remote exec) → clear timer → release() → closeTransport(), and withWorkspacePatch's patch capture runs inside the try, 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

@cwiklik
cwiklik merged commit fe0073f into rossoctl:main Nov 18, 2026
17 checks passed
cwiklik added a commit that referenced this pull request Nov 18, 2026
`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]>
@pdettori pdettori added this to the v0.11.0 milestone Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-ai-review Request automated AI code review from clawgenti

Projects

None yet

Development

Successfully merging this pull request may close these issues.

/turn leaks one gRPC channel per turn: the transport it opens has no close path

3 participants