Repository navigation
feat: relay + GrpcRelayTransport behind SH_REMOTE_SANDBOX (ST3, #86) - #93
Conversation
…tl#86) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…octl#86) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…tl#86) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…tl#86) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
- packages/k8s-sandbox/src/index.ts: replace the wildcard `export * from "./gen/sandbox/v1/sandbox.js";` with a named re-export of exactly the gen symbols consumed across ST3 (WorkerFrame, ServerFrame, Hello, Exec, Abort, Chunk, End, ExecError, ExecEvent, ExecRequest, AbortRequest, AbortResponse, Stream, SandboxWorkerService, SandboxExecService, SandboxExecClient, and type-only SandboxWorkerServer/ SandboxExecServer), matching the file's curated named-export style instead of dumping codecs/helpers/protobufPackage onto the public barrel. - packages/sandbox-relay/src/relay.ts: add .catch() logging to the fire-and-forget presence put/remove calls so a transient Redis failure can't surface as an unhandled rejection in the single-replica relay process; control flow is unchanged. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
teardown only removed the parked session on Attach stream end/error; it
never notified live sinks, so any in-flight routeExec generator stayed
parked on its internal await with no frame ever arriving. Per async-
generator semantics an external .return() during that suspension does
not run finally until the promise settles, so the sink leaked and the
only backstop was the harness-side 120s deadline (fail-slow).
teardown now pushes a synthetic {error: {message: "worker disconnected"}}
ExecEvent into every live sink for the session before removing it, so
each in-flight routeExec generator yields the error, returns, and its
finally cleans up the sink promptly.
Adds a regression test that parks a worker, starts an in-flight
routeExec, disconnects the worker stream, and asserts the generator
terminates fast with the synthetic error (fails/times out against
pre-fix code).
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ST3, rossoctl#86) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…lled The remoteSandbox flag-OFF test in select-sandbox.test.ts passed regardless of whether the remoteOn gate in select-sandbox.ts actually skipped RecordStore.list() (the #1 inertness gate) -- it relied on the pod outsorting the grpc record on a load tie, so a dropped gate would still pass silently. Add a vi.fn() spy on RecordStore.list() in the flag-OFF test and assert it is never called, in addition to the existing transport/pod assertions. Verified the strengthened assertion fails if the remoteOn ternary in select-sandbox.ts is removed (records.list() is invoked unconditionally), confirming the test now guards the invariant. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…ctl#86) Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
pdettori
left a comment
There was a problem hiding this comment.
(Self-review — GitHub blocks self-approval, so posting as a comment; verdict would be APPROVE: findings below are all non-blocking.)
ST3 looks solid — clean flag gate (the flag-off inertness is explicitly tested: RedisRecordStore never constructed, .list() never called), correct finish()-centralized dedup/deadline/abort in the transport, and correct transport-blind close-once in run-leaf. Proto/Go/TS changes are additive and backward-compatible.
Non-blocking notes below, all on the flag-on / future-worker path. The two I'd most encourage before ST4 lands a real worker: the fail-open token default (main.ts) and the no-op close() that leaks the gRPC channel (grpc-relay-transport.ts, which defeats the close-once design). The Redis connection leak, dup-id session takeover, and unused capacityMax are lower.
Already tracked in your follow-ups (not re-flagged): no relay-side deadline after Abort, and the deferred mTLS/SPIFFE posture (relay is createInsecure() + no Exec-caller auth — fine as an ST4/ST5 non-goal).
Assisted-By: Claude Code
| const deps = opts.deps ?? { | ||
| records: new RedisRecordStore(), | ||
| validateToken: (token, sandboxId) => | ||
| token === process.env[`SH_RELAY_TOKEN_${sandboxId}`] || token === process.env.SH_RELAY_TOKEN, |
There was a problem hiding this comment.
suggestion — default validateToken fails open. With neither SH_RELAY_TOKEN_<id> nor SH_RELAY_TOKEN set, both sides are undefined, and a worker that sends no authorization header yields token === undefined (see bearer() in relay.ts) ⇒ undefined === undefined ⇒ authenticated. The shipped relay-deployment.yaml sets neither var, so the default is open. Cheap to make fail-closed now (reject when no token is configured) before ST4 wires a real worker. Non-blocking for this inert slice.
There was a problem hiding this comment.
Fixed in f083140 — fail-closed now. Extracted makeDefaultValidateToken(env); it computes expected = env[SH_RELAY_TOKEN_<id>] ?? env.SH_RELAY_TOKEN and returns expected !== undefined && token === expected, so with no token configured every worker (including a tokenless one) is rejected. Unit test covers no-token / global / per-sandbox-override precedence. (An explicitly-set SH_RELAY_TOKEN="" still matches an empty token — treated as intentional operator config, not fail-open.)
|
|
||
| return { | ||
| exec, | ||
| async close() { |
There was a problem hiding this comment.
suggestion — close() is a no-op; it never releases the gRPC channel that defaultExecClient opens per leased record (ExecClientLike doesn't even expose a close method). So run-leaf's careful "close exactly once" still leaks a channel/FDs on every grpc leaf run in the long-lived harness process. Consider adding close() to ExecClientLike and calling it here. Non-blocking (flag-on path only).
There was a problem hiding this comment.
Fixed in fd491ac — added an optional close?(): void to ExecClientLike; GrpcRelayTransport.close() now calls client.close?.(), guarded by the existing closed flag so it fires exactly once and stays idempotent. Scripted fakes (no close) are unaffected via the optional chain, and the conformance idempotency test still passes.
| // Inertness: when the flag is off, never construct a RedisRecordStore or call .list() — | ||
| // the pod path must stay byte-for-byte identical to today (no extra Redis connection). | ||
| const remoteOn = opts.remoteSandbox === true; | ||
| const grpcRecs: SandboxRecord[] = remoteOn ? await (deps.records ?? new RedisRecordStore(env.REDIS_URL)).list() : []; |
There was a problem hiding this comment.
suggestion — the ad-hoc new RedisRecordStore(env.REDIS_URL) (flag-on, no injected store) is used for a single .list() and then discarded; its Redis connection is never .close()d. Accumulates one connection per selection. Pairs with the transport channel leak. Non-blocking (flag-on path only).
There was a problem hiding this comment.
Fixed in d3d10a7 — the ad-hoc RedisRecordStore is now .close()d after .list(), but only in the not-injected branch (an injected deps.records keeps its caller-owned lifecycle). Flag-off inertness is unchanged — nothing is constructed when remoteSandbox is off.
| return; | ||
| } | ||
| sandboxId = id; | ||
| sessions.set(id, { stream, sinks: new Map() }); |
There was a problem hiding this comment.
suggestion — sessions.set(id, …) overwrites unconditionally. If two workers claim the same sandboxId, the map points at worker-2, but worker-1's later teardown does sessions.get(id) and evicts/fails worker-2's live session + presence. A 1:1 worker↔id is expected, so this is an edge case, but the takeover handling is actively wrong — consider rejecting a Hello whose id is already parked.
There was a problem hiding this comment.
Fixed in f083140 — a Hello whose sandboxId is already parked is now rejected (stream.end(); return) before any sessions.set, so worker-2 can no longer silently take over worker-1. Presence is untouched on the rejected path, and its per-stream teardown is a no-op (its sandboxId was never assigned). Genuine reconnect still works: worker-1 disconnect runs teardown and removes the session before a new Hello for that id is parked.
| sandboxId: id, | ||
| labels: frame.hello.labels, | ||
| capabilities: frame.hello.capabilities, | ||
| capacityMax: frame.hello.capacityMax, |
There was a problem hiding this comment.
nit — capacityMax is mirrored into the record but never read; select-sandbox leases against opts.cap only, so the advertised worker capacity is dead data today. Fine to defer, but worth a comment or wiring it into leasing in a later slice.
There was a problem hiding this comment.
Addressed in f083140 — added a comment noting capacityMax is advertised by the worker but not yet used for leasing (select-sandbox leases against opts.cap today); wiring it into leasing is a later slice.
PR rossoctl#93 self-review findings (ST3, SandboxTransport epic): - Fix 1 (security): startRelay's default validateToken compared two undefineds equal when no SH_RELAY_TOKEN[_<id>] was configured, authenticating a tokenless worker. Extract the default into makeDefaultValidateToken(env), a pure function that computes `expected = env[SH_RELAY_TOKEN_<id>] ?? env.SH_RELAY_TOKEN` and only accepts an exact, defined match -- fail-closed when no token is set. - Fix 4 (correctness): onAttach's Hello handling overwrote sessions.set(id, ...) unconditionally. A second worker claiming an already-parked sandboxId would let worker-1's later disconnect teardown evict worker-2's live session and its presence record. Reject the duplicate (stream.end(), no overwrite, no presence touch) before parking; a genuine reconnect is unaffected since worker-1's own teardown already removed its session first. - Fix 5 (doc): note that capacityMax is advertised by the worker but not yet consulted for leasing (select-sandbox still leases against opts.cap) -- wiring it in is a later slice. Tests added (RED before fix, GREEN after): - test/main-default-token.test.ts: no-token-configured rejects any token incl. undefined; SH_RELAY_TOKEN exact-match only; per-sandbox SH_RELAY_TOKEN_<id> override precedence and fail-closed fallback. - test/relay-attach.test.ts: duplicate Attach for an already-parked sandboxId is ended and does not replace the first session; presence and the original session survive. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
PR rossoctl#93 self-review finding (ST3, SandboxTransport epic). close() only flipped a `closed` flag and never released the per-lease SandboxExecClient created by select-sandbox's defaultExecClient, leaking a gRPC channel on every sandbox release/reselect. Add an optional close?() to ExecClientLike (the real generated SandboxExecClient extends grpc-js's Client, which has close(); the scripted test fakes have none). GrpcRelayTransport's close() now guards on the existing `closed` flag before calling `client.close?.()`, staying idempotent -- a second close() is a no-op and the conformance battery's "close() resolves and is idempotent" test still passes against fakes with no close() at all. Tests added (RED before fix, GREEN after) in test/grpc-relay-transport.test.ts: - close() calls client.close() exactly once - calling close() twice still calls client.close() at most once - close() is a safe no-op when the client exposes no close() Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
PR rossoctl#93 self-review finding (ST3, SandboxTransport epic). `deps.records ?? new RedisRecordStore(env.REDIS_URL)).list()` built a RedisRecordStore (which eagerly opens a Redis connection in its constructor) purely to call .list() and discard it, leaking one Redis connection per sandbox selection when the remote-sandbox flag is on and no records store is injected. Restructure the remoteOn branch: when deps.records is injected, the caller owns its lifecycle and we only call .list(). When we construct our own RedisRecordStore, we alone own it and now call .close() after listing. RecordStore (the injected type) intentionally has no close(), so only the concrete RedisRecordStore we construct locally is ever closed. The flag-OFF inertness path is unchanged: no store is constructed and .list() is never called. Test added (RED before fix, GREEN after) in test/select-sandbox.test.ts, using vi.mock + vi.hoisted on ../src/pool-records.js to spy on the RedisRecordStore constructor without opening a real Redis connection: - not-injected branch: our own store's list() and close() are each called exactly once - injected branch: no RedisRecordStore is ever constructed (so nothing of the caller's is touched) Existing tests (flag-off inertness, flag-on with an injected fake records store) remain green and were not modified. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
ST3 — Relay + GrpcRelayTransport + presence mirror + dispatch (behind
SH_REMOTE_SANDBOX)Closes #86 (epic #89). Third slice of the SandboxTransport gRPC epic — the first behavior-adding one. Everything is gated behind
SH_REMOTE_SANDBOX(off by default); with the flag off, the pod path is byte-for-byte unchanged and no new code path activates until a worker connects.Builds on ST1 (proto/codegen, #84) and ST2 (
SandboxTransportseam, #85), both already onmain.What's in it
Streamdiscriminator (STREAM_UNSPECIFIED/STDOUT/STDERR) +Chunk.streamfield soGrpcRelayTransportcan honor theSandboxTransportstdout/stderr split. Additive, backward-compatible (default0⇒ stdout); TS + Go stubs regenerated and drift-checked.GrpcRelayTransport(@sh/k8s-sandbox): oneexec()→ oneSandboxExec.Exec, reassembles theExecEventstream, correlates byreqId, dedups late frames, harness-side deadline, per-exec output cap →Abort+[output truncated]. Passes the full sharedrunConformancebattery — proving parity withKubectlTransport.@sh/sandbox-relay, new package): single-replica, presence-only gRPC byte-bridge. Worker dialsSandboxWorker.Attach; the relay validates the bearer token ↔sandbox_id, parks the stream, mirrors a presence record into the Redis pool on connect and removes it on stream close (the stream is the registration). Routes harnessSandboxExec.Exec/Abortto the parked worker stream. On worker disconnect, in-flight execs fail fast (spec §10). Reuses the shared image via arelayentrypoint;deploy/knative/relay-deployment.yaml(1 replica) wired into base + OCP kustomizations.select-sandboxdispatch: single flag gate (opts.remoteSandbox, read fromSH_REMOTE_SANDBOXinrun-leaf). Off ⇒ pods only, transport undefined, the record store is never even constructed. On ⇒ leases across pods + mirrored grpc records and returns a readyGrpcRelayTransportfor a leased grpc record.run-leafmade transport-blind:selected.transport ?? KubectlTransport(config); the grpc transport is shared across converge + agent tools + cleanup and closed exactly once.Testing
GrpcRelayTransportthrough the shared conformance battery + dedup/output-cap/deadline; relay Attach/presence + Exec/Abort routing + disconnect (in-memory, no live worker);select-sandboxdispatch (flag on/off, with the flag-off test asserting the record store is never touched);run-leafpod-path-unchanged + grpc-path close-once; a pure-parse manifest-shape vitest for the relay Deployment.pnpm -r testgreen; typecheck clean across all workspaces;bufcodegen drift-free (TS + Go).Explicitly deferred (non-goals)
The Go reference worker (ST4/#87), the live-worker/real-network gate +
leaf-smoke.shrelay path (ST5/#88), SPIFFE/mTLS, multi-replica/HA relay, private mesh, extra-language workers.Follow-ups (non-blocking; noted by the final review)
GrpcRelayTransport'stimeout:0reject message with the actual deadline treatment oftimeout === 0.STREAM_UNSPECIFIEDrouting, native-endfallback).handlersmap) — pinned by the lockfile, but worth a public-surface assertion later.Abort(bounded today only by worker disconnect) — hardening for ST4/ST5.pool-recordstestclose()/multi-record coverage;REDIS_URLFQDN vs short form.Assisted-By: Claude Code