Repository navigation
Description
ST4 — Worker: Go reference worker
Part of the SandboxTransport epic (see epic #89). Worker track (Go / sandbox side) — a separate contributor from the backend. Depends only on ST1 (the published sandbox/v1 proto); builds in parallel with ST2/ST3.
Spec: docs/specs/2026-07-08-sandbox-transport-grpc-design.md §7, §8.
Problem
The contract is language-neutral (ST1), but nothing yet proves it: we need one worker that a) implements the SandboxWorker.Attach client, and b) is deliberately not TypeScript — the honest proof the seam isn't secretly TS-shaped (driver #2, §2). A Go static binary drops into any sandbox image with no runtime dependency.
Goal
Ship a thin, single-purpose Go static binary that holds no LLM key and no orchestration — it only executes commands and returns bytes (what makes "central brain" trust-correct, §7). Behavior per §7:
- On start: read
SANDBOX_ID,RELAY_ADDR,SANDBOX_TOKENfrom env; dialSandboxWorker.Attachover TLS:443(HTTP/2) withAuthorization: Bearer <token>. - Send
Hello(id, labels, capabilities,capacity_max,trust). - Loop on
ServerFrame:Exec→ runbash -c <command>locally, feedingstdin. Ifstreaming: emitChunk* thenEnd{exit_code}. Else: a singleEndcarrying full stdout. Enforcetimeout_slocally (SIGKILL on expiry).Abort→ SIGKILL the in-flight child for thatreq_id.
- Send
Heartbeatperiodically (liveness + NAT/proxy keepalive). - Maintain a bounded
req_id → Enddedup cache; on a redeliveredreq_id, re-emit the cached result instead of re-running (at-least-once + dedup, §8).
Persistent-shell semantics (one long-lived bash preserving cwd/env across execs) are an internal choice; the wire only requires ordered, one-in-flight execs (§7).
Non-goals (this task)
- The relay and
GrpcRelayTransport(ST3 — backend). - mTLS / SPIFFE (bearer token only day-one, §9); additional-language workers (§13.4).
- Any orchestration or credential handling in the worker.
Acceptance
- Go
contracttest (Go test, real Attach against a relay, worker pointed at local bash) round-trips read/write/bash/grep, plus abort mid-stream, timeout (worker SIGKILLs child), and reconnect → dedup (redeliveredreq_idre-emits cachedEnd, no re-run). - Static binary, no runtime deps; drops into a sandbox image.
- Chunk size capped so a single frame stays small (backpressure, §8).
Touches
New Go module for the worker (e.g. worker/ or a dedicated repo dir), consuming ST1's generated Go stubs; a minimal container build for the static binary; Go unit + contract tests.
Next step
Join ST3 for the ST5 live gate (real worker pod → in-cluster relay on :443). Worker plan lives locally in docs/plans/, authored by the worker contributor.
Activity
docs: register SandboxTransport (ST) track in the milestone registry
pdettori commentedon Jul 10, 2026
Testing the Go worker against the ST3 backend
ST3 (#86, PR #93) is merged, so the relay +
GrpcRelayTransportare available to test against now — you don't need to wait for ST5. There are two levels; Level 1 is the fast inner loop and exercises everything the worker must get right.Level 1 — worker ↔ relay contract loop (no harness needed)
1. Redis + relay:
2. Worker connects: dial
localhost:8443(h2c / insecure), openSandboxWorker.Attach, attach metadataauthorization: Bearer dev-token, and sendWorkerFrame{hello:{sandbox_id:"sbx-dev-1", ...}}as the first frame. The token must matchSH_RELAY_TOKEN(or setSH_RELAY_TOKEN_sbx-dev-1for a per-sandbox token) — auth is fail-closed: if no token is configured for the sandbox, or it doesn't match, the Attach is rejected before the stream is parked.3. Verify presence — the live Attach stream is the registration:
4. Drive an exec from the harness-facing side — two options:
(a) The real harness client (recommended — it's the exact code the harness runs):
Run it with
tsx. This proves the whole relay→worker→relay round-trip and the stdout/stderr split in one shot.(b) grpcurl (the relay does not register gRPC reflection, so pass the proto):
grpcurl -plaintext -proto proto/sandbox/v1/sandbox.proto \ -d '{"sandbox_id":"sbx-dev-1","exec":{"req_id":1,"command":"echo hi","timeout_s":10,"streaming":true}}' \ localhost:8443 sandbox.v1.SandboxExec/ExecThe wire contract the worker must satisfy
From
proto/sandbox/v1/sandbox.proto(§8) and whatGrpcRelayTransportexpects:Chunk{stream: STREAM_STDOUT}(collected into the returnedstdout); stderr →Chunk{stream: STREAM_STDERR}(streamed toonData, excluded from the returned stdout). This is the reason ST3 addedChunk.stream.End{req_id, exit_code};exit_code < 0means signal/none (the harness maps it tonull). Failures →ExecError{req_id, message}.ServerFrame{abort}, SIGKILL the child and emit a terminal frame for thatreq_id.exec.timeout_s(the harness enforces its own deadline too — dual-ended).req_id → End; on a redeliveredreq_idafter a reconnect, re-emit the cached terminal result rather than re-running.exec.stdinbytes to the child's stdin.Heartbeatframes are liveness-only (the harness owns lease counts).Level 2 — full path (worker ↔ relay ↔ harness)
Run the harness with
SH_REMOTE_SANDBOX=1andSH_RELAY_ADDRpointed at the relay; with a grpc pool record present,select-sandboxleases it andrun-leafdrives a real leaf throughGrpcRelayTransport. The end-to-end leaf-smoke for this (extendingdeploy/knative/leaf-smoke.shwith the relay path) is ST5 (#88)'s deliverable — so Level 1 is what unblocks worker development now; Level 2 lands with ST5.Reference pointers
proto/sandbox/v1/sandbox.proto(§4 messages/services, §8 wire semantics).gen/go/sandbox/v1/(modulegithub.com/kagenti/serverless-harness/gen/go) — there's already acontract_test.gothere.packages/sandbox-relay/src/relay.ts(park / presence / routing).packages/k8s-sandbox/src/grpc-relay-transport.ts(reqId correlation,Chunk.streamsplit, dedup, deadline, per-exec output cap).Assisted-By: Claude Code
pdettori commentedon Aug 26, 2026
Status check — code vs. acceptance (as of
docs/turn-sse-streaming-spec, 2026-08-26)A worker exists in
remote-worker/but it is the HELLO WORLD proof-of-connectivity stub (landed in9c78d78 feat(remote-worker): HELLO WORLD SandboxTransport worker), not onmain. Its own header says "It runs no shell and holds no secrets." It proves the frame flow but does not yet satisfy the §7 behavior or the acceptance battery.Done ✅
SandboxWorker.Attach(TLS or h2c) withAuthorization: Bearer <token>—remote-worker/main.go:51-68Hellofirst frame (id / capabilities / capacity_max / trust) —main.go:83-92Heartbeat(15s) —main.go:96-107req_id → Enddedup cache; redeliveredreq_idre-emits cachedEnd—main.go:110-142remote-worker/DockerfileMissing ❌
bash -c <command>— the core of the worker. It emits fixed"HELLO WORLD"chunks + an echo; there is no child process.main.go:146-153timeout_senforcement / SIGKILL on expiry.Abortis stubbed —main.go:128: "Nothing long-running to kill in the stub; emit a signalled terminal." No real child to kill.Endcarrying full stdout when!streaming).contracttest absent.gen/go/sandbox/v1/contract_test.goonly does proto marshal/unmarshal round-trips (TestHelloRoundTrip,TestExecNegativeExitCode). None of the required battery: realAttachagainst a relay with the worker pointed at local bash, round-tripping read/write/bash/grep, abort mid-stream, timeout (worker SIGKILLs child), reconnect → dedup.Also
main— it lives only on feature branches (this branch is 111 commits ahead ofmain;remote-worker/is absent frommain).Net: connectivity + framing + dedup are proven; real command execution, timeout, abort, and the contract test remain. This blocks the #88 live gate — no leaf can complete through the remote path until the worker actually runs commands.
pdettori commentedon Aug 27, 2026
ST4 findings — four discrepancies worth other tracks' attention
Surfaced while implementing the reference worker in
remote-worker/against§3/§4/§6/§7 of the design. Design doc:
docs/specs/2026-08-26-st4-go-reference-worker-design.md.1.
req_idis not unique per worker (affects ST1/ST3)harness/src/select-sandbox.ts:60deliberately shares sandboxes ("pickleast-loaded under the soft cap"). Each leaf builds its own
GrpcRelayTransportfor the samesandbox_id, andpackages/k8s-sandbox/src/grpc-relay-transport.ts:22seedsreqCounter = 0at module scope — per harness process. Knative scales the harness to
multiple replicas, and the relay (
packages/sandbox-relay/src/relay.ts)multiplexes all of them onto the one Attach stream it keeps per
sandbox_id(one
Parkedentry per sandbox,reqId-keyed sinks registered onto it —relay.ts:105-125), so replica A and replica B both sendreq_id: 1, 2, 3…to the same worker.
A
req_id-keyed dedup cache would therefore answer replica B'scat /awiththe cached terminal frame from replica A's unrelated command — a silent wrong
result.
Worker-side mitigation (shipped): the cache
(
remote-worker/internal/session/cache.go) compares a SHA-256 fingerprint ofcommand+stdinas well asreq_id(Fingerprint,cache.go:15). Agenuine redelivery is byte-identical and re-emits the cached frame; a
collision has a different fingerprint, runs fresh, and logs a warning
(
internal/session/loop.go'saccept, thecollisionbranch). The samefingerprint is also carried on the in-flight slot, which is where the collision
window is widest: while the original is still running the cache cannot see it at
all, so a matching fingerprint is coalesced as a redelivery and a mismatching one
is refused with an
ExecErrorrather than silently swallowed.Proposed real fix: make
req_idglobally unique — a random 64-bit seedper transport instance, or a replica-scoped prefix. The worker guard is
defense-in-depth, not a substitute.
Worth noting the hazard the dedup cache was built for does not exist yet: the
relay never redelivers (it fails in-flight execs on stream close with
{ error: { reqId, message: "worker disconnected" } },relay.ts:87-98) and the harness never retries areq_id.2. §7's non-streaming shape is not expressible in
sandbox/v1(doc fix)§7 and §8 of the parent spec say non-streaming ops return "a single
Endcarrying full stdout", but the wire message is
message End { uint64 req_id = 1; sint32 exit_code = 2; }(
proto/sandbox/v1/sandbox.proto:67) — there is no data field to carryoutput on.
GrpcRelayTransport.execalso always sendsstreaming: trueregardless of caller intent (
grpc-relay-transport.ts:51), so the flag iscurrently dead on the wire in both directions.
The worker honors the flag's observable intent — no incremental delivery
while the process is running — without inventing a new field: for
streaming: falseit buffers stdout/stderr until the process exits, thenemits them as
Chunkframes capped atChunkSize(32 KiB,internal/exec/runner.go:24) per stream. Small output still round-trips asexactly one
Chunkper stream; output larger than the cap goes out asseveral
Chunks in that same post-exit burst, since a single frame must stayunder the wire's 32 KiB cap regardless of the streaming flag
(
internal/exec/runner.go'semitBuffered, exercised byTestNonStreamingChunksAtExitandTestNonStreamingSmallOutputIsOneChunkPerStreamin
internal/exec/runner_test.go). Addingbytes stdouttoEndwasrejected: it changes a published contract other tracks build against, for a
field the harness never reads, and creates two ways to return the same
bytes. Suggest correcting the prose in the parent spec to describe delivery
timing ("all at once, after exit") rather than frame shape ("a single
Endcarrying stdout").
3. Neither worker image had a shell (fixed here)
remote-worker/Dockerfilebuilt its final stage ongcr.io/distroless/static-debian12:nonroot, andremote-worker/Dockerfile.runtimeon
registry.access.redhat.com/ubi9/ubi-micro:latest. Once the workeractually runs
bash -c <command>per exec, every exec would fail withENOENT in those images. Both now use
registry.access.redhat.com/ubi9/ubi-minimal:latestwithbash,coreutils-single(base64, used bywriteFile),findutils, andfile(image MIME sniffing) installed via
microdnf. Both images were built andrun (verified on the change that swapped the base, not repeated for this
write-up) to confirm
bash,base64, andfileare present and that thenon-root
USER 1001takes effect.This does not weaken "static binary, no runtime deps": the build stage still
runs
CGO_ENABLED=0 go build(remote-worker/Dockerfile), so the binaryitself stays CGO-free and statically linked.
bashis a dependency of thecommands the worker execs, not of the worker binary. In production the
binary drops into a sandbox image that already has a shell — it is the two
standalone demo images (built directly from this repo, not from a sandbox
image) that needed the base swap.
4. A cache hit re-emits only the terminal frame, never the output chunks (contract gap)
The dedup cache (
internal/session/cache.go) stores exactly one*pb.WorkerFrameperreq_id— the terminal frame (EndorExecError)that
runOneproduced the first time. On a redelivery,acceptininternal/session/loop.golooks the frame up and sends it straight back(
trySend(frame)) without ever callingrunOneagain — so noChunkframes are re-emitted, because none were ever cached. A redelivered
streaming exec therefore returns its correct exit code with zero
output. For
cat filethat meansEnd{exit_code: 0}with noChunkeversent — the caller sees a successful exit and empty content, a silently
wrong answer.
The worker is spec-compliant here: the design's own dedup table says a
fingerprint match should "re-emit cached terminal frame, do not run"
(§6.3), and
Endhas nowhere to put output even if the worker wanted toresend it (see finding 2 —
Endcarries onlyreq_idandexit_code). Sothe gap is in the contract, not in this implementation.
Why it is not a real bug today: it is unreachable — nothing in the
system redelivers a
req_id(see finding 1's last paragraph: the relayfails in-flight execs rather than replaying them, and the harness does not
retry). It is listed here anyway because it is the same class of problem as
finding 1: both are latent consequences of dedup being specified only in
terms of
req_idand a terminal frame, with no accounting for what astreaming exec's redelivery should return.
Proposed real fix: if redelivery becomes reachable (e.g. a future
retrying relay), the contract needs either (a) an explicit statement that a
cache hit answers with the terminal frame only and callers must not expect
output on a redelivered streaming exec, or (b) a cache that also replays
buffered
Chunks, which requires bounding how much output a cache entry mayhold. Today's worker takes the cheapest correct-by-contract option: it does
exactly what the spec says and nothing more.
Assisted-By: Claude (Anthropic AI) [email protected]
pdettori commentedon Aug 27, 2026
ST4 acceptance — where each criterion is covered
All tests below live under
remote-worker/and were re-run for thiswrite-up:
go test -race ./...—EXIT:0, 46 passed, 2 skipped (bothskips explained below; neither is a failure). Contract tests run over a
real gRPC connection to an in-process fake relay
(
remote-worker/internal/relaytest) driving a realbash, not mocks.TestContractRead(internal/session/contract_test.go) —cat <file>TestContractWrite(internal/session/contract_test.go) —base64 -d > <file>with stdin, asserts file content on diskTestContractBash(internal/session/contract_test.go) — stdout/stderr split across streams +exit 7TestContractGrepStreamsMultipleChunks(internal/session/contract_test.go) — ~149 KiB of matches, asserts ≥2 chunks and every chunk ≤ChunkSizeTestContractAbortMidStream(internal/session/contract_test.go) — aborts after a real chunk arrives; assertsEnd{exit_code:-1}and that a sentinel file the child was appending to stops growing (proves the whole process group died, not just that reads stopped)TestContractTimeout(internal/session/contract_test.go) —sleep 30withtimeout_s: 1→ExecError{message:"timeout:1"}, asserts it took under 10sTestContractReconnectDedup(internal/session/contract_test.go) — runsreq_id 7, drops the stream, reattaches on the sameSession, resendsreq_id 7; asserts the cachedEnd{0}comes back and that a marker file the command appends to still has exactly one line (the command did not re-run)remote-worker/Dockerfile's build stage:CGO_ENABLED=0 go build -trimpath -ldflags "-s -w". Both runtime images (Dockerfile,Dockerfile.runtime) were built and run, withbash,base64, andfilechecked present andUSER 1001confirmed, when the base image was swapped — a one-time build+run check done for that change, not a repeatable CI gateTestChunkCapSplitsLargeOutput(internal/exec/runner_test.go, unit) +TestContractGrepStreamsMultipleChunksabove (contract-level)All nine rows above run in CI with no Redis, node, or pnpm — they are pure
Go and need only a real
bashon PATH.Two things intentionally not counted as passing evidence yet:
SH_LIVE_RELAY=1gated interop has never been run in this work.TestLiveRelayInterop(internal/session/live_test.go) drives read,write, and bash through the real TypeScript relay via
SandboxExec.Exec— the one thing the self-authored fake relay cannotvouch for. It skips (
t.Skip("SH_LIVE_RELAY!=1: ...")) unless that envvar is set, and it was not set for any run in this task. It exists and
compiles; it has not exercised the real relay. Full interop remains
ST5 (ST5: integration & live gate — cross-transport conformance + end-to-end leaf (Kind → OCP) #88)'s gate.
TestRunReturnsWhenPipeHolderEscapesGroup(internal/exec/runner_test.go)covers a pipe holder (e.g. a backgrounded grandchild) that detaches from
the process group and survives the group's
SIGKILL; it needs thesetsidbinary to simulate that, and skips witht.Skip("no setsid: ...")when
setsidis not on PATH — which is the case on macOS, where thisworker was built and tested. It has run only in principle here; CI
(
.github/workflows/ci.yml's "Build and test remote-worker" step, onubuntu-latest, which shipssetsid) is where it actually executes.This is distinct from
TestContractAbortMidStreamandTestContractTimeoutabove, both ofwhich kill the whole process group via
Setpgid+Kill(-pid, ...)directly and do run (and pass) on macOS — the escape test is specifically
about a pipe holder that has left that group.
Two behaviors worth flagging as deliberate, both argued in the design doc
(
docs/specs/2026-08-26-st4-go-reference-worker-design.md):ExecError{"timeout:<n>"}, notEnd{-1}. All threeexisting harness transports reject with exactly that string
(
packages/k8s-sandbox/src/exec.ts:79,packages/k8s-sandbox/src/persistent-exec.ts:129, andGrpcRelayTransport's own deadline path), and the worker's own timernormally fires first, so its choice is what the caller sees.
End{-1}would make a timeout resolve as a success with partial output.
timeout, not an abort (
internal/session/loop.go'srunOne: thecacheableflag is set for theerr == nilandErrTimeoutbranchesonly, not for
ErrAborted). CachingEnd{-1}for an abort would makeevery later redelivery of that
req_idanswer-1forever, even thoughthe command never actually ran to completion.
Assisted-By: Claude (Anthropic AI) [email protected]
pdettori commentedon Aug 27, 2026
Correction to finding 1 and finding 4 — the fingerprint now covers
timeout_sandstreamingPR review turned up a real gap in the guard I described in finding 1. The fingerprint
covered
command+stdinonly, so two axes of the cross-replica collision wentstraight through it:
The second delivery had ten times the budget it needed and was failed off the cache in
649µs. Not a cosmetic wrong-message defect — a spurious failure for work that would have
succeeded. Same shape on the streaming flag:
Both fields are now in the hash. A genuine redelivery carries the same
Execmessage,so they are stable across it and including them costs nothing on the path dedup is
actually for — while excluding them let a collision differing only in budget or
delivery mode be answered from the wrong entry.
This also closes the flag-flip half of finding 4 locally, without waiting on the
contract change: a redelivery that flips
streamingnow runs fresh instead of beinganswered by a cached terminal frame with no chunks. The rest of finding 4 stands — a
same-shape redelivery still re-emits the terminal frame with no output, because
Endhas nowhere to put output.
The behavior is pinned by a contract test that asserts the redelivery runs (~3s,
End{0}) rather than merely returning a different frame. Mutation-checked: excludingtimeout_sfrom the hash fails it in 1.01s withtimeout_s must be part of the fingerprint.Finding 1's real fix is unchanged and still upstream: make
req_idgloballyunique. The worker's guard is defense-in-depth, and this PR only widened what it
covers.
Assisted-By: Claude Code
fix(remote-worker): fold timeout_s and streaming into the dedup finge…
docs(notes): move the ST4 write-ups out of the repo and into the issues
docs(st4): design for the Go reference worker
refactor(remote-worker): move entrypoint to cmd/worker, wire Go into CI
feat(remote-worker): exec runner with stdout/stderr split and chunk cap
fix(remote-worker): serialize Sink.Chunk calls in exec runner
test(remote-worker): pin stdin EOF and non-streaming buffering
test(remote-worker): bound the stdin tests so regressions fail fast
test(remote-worker): pin timeout and process-group kill
feat(remote-worker): bounded dedup cache with fingerprint guard
feat(remote-worker): session loop with dispatch pool and terminal map…
test(remote-worker): pin abort routing, queue overflow, and disconnect
test(remote-worker): fix TestSendFailureDoesNotWedgeTeardown false pass
test(remote-worker): fake relay plus read/write/bash/grep contract tests
test(remote-worker): abort, timeout, dedup contract tests + gated liv…
feat(remote-worker): real worker entrypoint, replacing the HELLO WORL…
fix(remote-worker): shell-bearing runtime images; rewrite DESIGN.md
docs(notes): findings and acceptance write-up for issue #87
docs(notes): record the deferred and parked items for ST4 review
pdettori commentedon Aug 27, 2026
Shipped and merged — PR #172, on
mainat84118c9Verified against merged
mainrather than the branch:go test -race ./...green acrossall three packages, 0 races.
Acceptance, item by item
TestContractRead—cat <file>TestContractWrite—base64 -d > <file>on stdin, asserts the bytes on diskTestContractBash— stdout/stderr on distinct stream enums, realexit 7TestContractGrepStreamsMultipleChunks— ~149 KiB → ≥2 chunks, each ≤32 KiBTestContractAbortMidStream— asserts a sentinel file stops growing, which proves the process group died rather than that reads merely stoppedTestContractTimeout—sleep 30attimeout_s: 1→ExecError{"timeout:1"}in ~1sTestContractReconnectDedup— drops the stream, reattaches, redeliversreq_id 7; asserts the cached terminal frame and that the marker file still holds one lineCGO_ENABLED=0build; the image was rebuilt and exercised — realbash,uid=1001,exit 7propagating,base64 -d > fileround-trippingChunkSize = 32 * 1024, which is also the pipe read sizeBeyond the letter of the list: the worker reconnects with jittered backoff while
preserving its dedup cache (the stub exited on the first receive error, so a restart
wiped it and made the dedup criterion unreachable by construction), and both container
images now ship a shell — they previously shipped none, so every exec would have failed
with ENOENT.
One thing this does not claim
The battery runs against an in-process Go relay written for these tests
(
remote-worker/internal/relaytest). That is a real gRPCAttachwith a real stream and areal
bash, and it is the only way to reach the redelivery path at all — the productionrelay is a pure bridge that cannot redeliver a
req_id. But it encodes this repo'sreading of the wire contract, so its agreement is not independent evidence.
The gated interop tier that would supply that (
TestLiveRelayInterop,SH_LIVE_RELAY=1,driving the real relay via
SandboxExec.Exec) exists and has never been run — CI has norelay. Running it is the cheapest first step of #88's live gate, and I have left a handover
there covering this and cross-transport equivalence.
Findings
Four discrepancies are written up above; the epic-level ones are on #89. Worker-specific
follow-ups that were deliberately not fixed are tracked in #173, audited against shipped
code — nothing there affects this battery or runtime correctness.
Closing: the acceptance criteria are met on
main. #88 owns what remains.Assisted-By: Claude Code