Skip to content

ST4: Go reference worker — real exec, timeout, abort, dedup, reconnect - #172

Merged
pdettori merged 28 commits into
rossoctl:mainfrom
pdettori:feat/st4-go-worker
Aug 27, 2026
Merged

pdettori merged 28 commits into
rossoctl:mainfrom
pdettori:feat/st4-go-worker

Conversation

@pdettori

@pdettori pdettori commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

ST4 — Go reference worker

Replaces remote-worker/'s HELLO WORLD stub with a real reference worker. The stub
fabricated the literal bytes HELLO WORLD for every exec, ran no shell, ignored
timeout_s, had a no-op abort, and exited on the first receive error — so a restart
wiped its dedup cache and made one acceptance item unreachable by construction.

Design: docs/specs/2026-08-26-st4-go-reference-worker-design.md

What it does now

  • internal/exec — one bash -c child per exec in its own process group
    (Setpgid + Kill(-pid, SIGKILL)), stdout/stderr drained into 32 KiB Chunk
    payloads on distinct stream enums, stdin always closed (a write op is
    base64 -d > path on stdin, which only terminates at EOF), timeout_s enforced
    locally, and a watchdog that bounds the output drain — os/exec's WaitDelay
    cannot, because it closes *Pipe() descriptors only from inside cmd.Wait().
  • internal/session — Serve owns one connection, Session owns the dedup
    cache so it survives reconnects. A dedicated sender goroutine owns the stream;
    producers enqueue on a buffered channel; the receive goroutine uses a
    non-blocking send so it can never stall and miss an Abort. A fixed pool drains
    a bounded queue. A 256-entry LRU dedups redelivered req_ids, guarded by a
    command+stdin fingerprint.
  • cmd/worker — env config, capabilities probed from PATH (not hardcoded),
    TLS or h2c, gRPC keepalive, and a reconnect loop with jittered backoff that
    preserves one Session across connections.
  • Images — both Dockerfiles previously shipped no shell, so every exec would
    have failed with ENOENT. Now ubi9/ubi-minimal + bash/coreutils/file, USER 1001.

Acceptance

All seven items from #87 pass over real gRPC with a real bash. Mapping to the
tests that cover them is posted on #87, with the ST5 handover on #88.

go test -race ./... → 51 pass, 2 skip, 0 fail. Both skips are deliberate and
documented: the SH_LIVE_RELAY=1 interop tier (needs a running relay — never run),
and an escaped-process-group test that needs setsid (absent on macOS, present on
Linux CI). CI for this module runs go test -race ./....

Findings for other tracks

Four discrepancies found while implementing against §7/§8, written up on #87 (and
the epic-level ones on #89):

  1. req_id is not unique per worker — the harness seeds its counter at module
    scope (per process) while sandboxes are deliberately shared, so two replicas both
    send 1, 2, 3…. The worker ships a fingerprint guard as defense-in-depth; the
    real fix is a globally unique id upstream.
  2. §7's non-streaming shape is not expressible in sandbox/v1 — End has no
    data field. The worker buffers and emits capped Chunks at exit instead.
  3. Neither worker image had a shell — fixed here.
  4. A cache hit re-emits only the terminal frame, never the output chunks — so a
    redelivered streaming cat file returns exit 0 with empty content. The worker
    is spec-compliant; the gap is in the contract.

Known and deferred

Follow-ups that were seen, judged, and deliberately not fixed are tracked in #173,
audited against shipped code. Nothing there affects the acceptance battery or runtime
correctness.

The three items I had flagged as "worth a look before merging" are now closed in this
PR
, so the merge checklist is empty:

  • The non-streaming contract test passed even when the worker ignored streaming: false
    entirely — it asserted chunk count, cap, and completeness, all of which hold for
    incremental streaming too. It now pins the actual guarantee (nothing leaves before the
    process exits) and was mutation-checked: forcing Streaming=true fails it with the
    first chunk at ~19 ms against a ~700 ms floor.
  • Serve's documented failure mode claimed shutdown breaks "in either direction". Only
    one direction wedges — a stream created from a context nothing cancels. Handing Serve
    an unrelated context is harmless. Corrected.
  • The design spec had drifted from shipped code on the collision path: it said a collider
    "runs fresh", but an in-flight collider is refused, and its "cache consulted before
    enqueue" line omitted the in-flight check that now precedes it. Reconciled.

Follow-ups deliberately out of scope (detail in #173): restructuring frame egress so a
busy: queue full refusal cannot be dropped; MaxCallRecvMsgSize, where a >4 MiB base64
write payload kills the whole stream rather than one exec and which needs relay-side
coordination; SANDBOX_TOKEN as a literal env value in the Deployment (pre-existing, but
this PR makes the grant real, so it wants a secretKeyRef); and unifying the session's
state plumbing.

Note for squash

Two commit subjects are inaccurate and could not be amended (git commit --amend is
blocked by a local policy): 8b87a41 advertises non-streaming coverage it doesn't
contain, and 0c5648b says "~60 KiB grep" where the shipped test generates ~149 KiB.
Worth rewording if you squash.

Refs #87


Review round (PR #172)

Two review comments, both correct and both addressed:

  • Fingerprint omitted timeout_s and streaming, so a redelivery differing only in
    budget was failed off the cache without running — req_id 5 "sleep 3" at timeout_s=30
    answered in ~650 µs from a timeout:1 entry, ten times the budget it needed. Both fields
    are now hashed. Pinned by a contract test asserting the redelivery actually runs
    (~3 s, End{0}), mutation-checked by excluding timeout_s, which fails it in 1.01 s.
  • The in-repo deferred list was stale, advertising three blockers already fixed. Root
    cause: it was generated from an implementation ledger that recorded findings as raised and
    was never reconciled after the final review wave. The file is gone; ST4 worker: follow-ups deferred during review #173 carries the
    audited list.

Turns remote-worker/ from the HELLO WORLD connectivity stub into the §7
reference worker: real `bash -c` execution, stdout/stderr split, local
timeout_s enforcement, Abort killing the process group, fingerprint-guarded
dedup, honest Hello, and in-process reconnect — plus the Go unit + contract
test tiers the rossoctl#87 acceptance battery needs.

Records three discrepancies found while reading the code against §7/§8:
req_id is not unique per worker across harness replicas (shared sandboxes +
module-scoped counter), §7's "single End carrying full stdout" is not
expressible in sandbox/v1, and neither demo image ships a shell.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Pure move ahead of the ST4 rewrite: the binary builds from ./cmd/worker so
internal/ packages can land beside it. Adds gofmt/vet/test for the module to
the existing proto job (its setup-go already covers Go 1.25) and to make test,
which ran pnpm only and skipped Go entirely.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
BashRunner spawns `bash -c` per exec (no persistent shell — base64 -d needs a
per-exec stdin EOF), pumps both pipes into 32 KiB Chunks tagged STDOUT/STDERR,
and returns the child's exit code. Setpgid + killing -pid so pipelines with
grandchildren die with the parent. Pipe read errors are swallowed on purpose:
after a kill they would mask the real outcome; only sink failures propagate.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Run drains stdout and stderr on two goroutines that both call sink.Chunk, and
the non-streaming exit path calls it again on the main goroutine — three
call sites with no shared lock, so any Sink (including the brief's own test
recorder) raced on its internal state under -race. Task 7 makes
`go test -race ./...` load-bearing, and Task 6's real sink would inherit the
same race on its `failed` field.

Wrap the caller's Sink once in Run behind a new lockedSink so the runner,
which creates the concurrency, owns serializing it — callers no longer need
to make their own Sink implementation thread-safe. The test recorder is left
unlocked on purpose: it is the covering test for this fix under -race.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…s-timeout race

Three review findings on Task 2's exec.Runner, each with a covering test:

1. A pipe holder that escapes the process group (setsid) or outlives it
   (TimeoutS==0) wedged Run forever: WaitDelay only bounds Wait's own
   cleanup, not reads from *Pipe() readers, which Wait closes only after
   every read already finished (go.dev/issue/23019). Run now starts a
   drain watchdog that, drainGrace after runCtx ends, force-closes the
   stdout/stderr pipes itself so a wedged Read returns.

2. The non-streaming exit path emitted the whole buffered output (up to
   BufferCap, 8 MiB) as a single Chunk, breaking the 32 KiB ChunkSize
   frame cap and risking gRPC's 4 MiB default receive limit.
   streaming:false means no incremental delivery, not "exactly one
   frame": emitBuffered now slices buffered output into ChunkSize-capped
   Chunks at exit.

3. A command that exited 0 while a slow sink was still draining, with the
   deadline firing mid-drain, was misreported as ErrTimeout: runCtx spans
   the whole drain, not just the child's lifetime, and cmd.Wait's error
   was inspected after runCtx.Err() rather than before. Two fixes were
   required together: reorder the exit-code switch so a clean waitErr or
   any ExitCode()>=0 outranks ctx state, and make cmd.Cancel always
   report os.ErrProcessDone — per exec.Cmd.Cancel's documented contract,
   any other return value makes Wait synthesize a ctx/Cancel error over
   a child that already exited successfully by the time Cancel ran, which
   is exactly this race. A genuinely-killed child still exits with a
   non-success (signalled) status, a path Cancel's return value does not
   affect either way.

Covering tests: TestRunReturnsWhenPipeHolderEscapesGroup (skipped here,
no setsid on macOS), TestNonStreamingChunksAtExit,
TestNonStreamingSmallOutputIsOneChunkPerStream,
TestSlowSinkDoesNotTurnSuccessIntoTimeout.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
A real base64 -d round-trip proves writeFile's shape works, `cat` with no stdin
proves the unconditional close, and streaming=false proves exactly one Chunk per
stream — the only shape sandbox/v1 can express for "no incremental delivery",
since End has no stdout field.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Both tests guarded regressions whose failure mode was a hang: without a deadline
the base64 round-trip blocked until go test's 10-minute global timeout, and the
`cat` test asserted via t.Errorf from a goroutine that could outlive the test,
which panics the whole binary rather than failing one case. Each Run now gets a
bounded context, and the goroutine reports over a buffered channel.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
timeout_s SIGKILLs and returns ErrTimeout (~1s, not 30); a cancelled context
returns ErrAborted. The grandchild test is the one that fails without Setpgid:
a backgrounded subshell must stop appending to its sentinel after the abort,
which is what makes abort actually stop the work rather than orphan it.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Keyed on req_id per the wire contract, but guarded by a sha256 of command+stdin:
req_id is not unique per worker, since grpc-relay-transport.ts seeds its counter
at module scope while select-sandbox shares sandboxes across replicas. A genuine
redelivery is byte-identical and re-emits; a reused id with a different command
runs fresh instead of returning another exec's output.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ping

Serve owns one connection: Hello first, heartbeats, a fixed pool of
capacity_max goroutines draining a bounded queue, and exactly one terminal frame
per exec. Timeout maps to ExecError{"timeout:<n>"} to match every other harness
transport; abort maps to End{-1}. Only completed determinations are cached —
caching an abort would answer -1 for that req_id forever.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…minal frame

Task 6 code review found two blocking defects:

1. accept (recv goroutine) called a sendMu-guarded send that wraps a
   blocking st.Send, on the cache-hit, duplicate-in-flight, and
   queue-full paths. Under overload this could stall the recv
   goroutine behind its own refusal frame, so a following Abort (the
   only thing that frees a saturated pool) could never be read.

   Fixed by giving one dedicated sender goroutine exclusive ownership
   of st.Send. Hello is sent synchronously before any goroutine
   starts. All other frames go through an outbound channel: producers
   (heartbeat, pool workers) use a blocking enqueue for correct
   backpressure; the recv goroutine uses a non-blocking trySend that
   drops rather than stalls. The sender keeps draining outbound after
   a send failure instead of returning, so wg.Wait() still reaches
   zero. Teardown now cancels the connection and closes the exec
   queue before waiting on producers, then closes outbound and waits
   on the sender. frameSink.failed is gone: with a single owner of
   the stream, Chunk can no longer observe a send error.

2. A same-req_id resubmission while the original was still running
   sent an immediate ExecError refusal in addition to the original's
   own later terminal frame -- two terminal frames for one req_id.
   Fixed by coalescing silently (log only, no frame) instead.

Also renames TestAbortedRunBecomesSignalledEnd to
TestErrAbortedMapsToSignalledEnd: it tests the ErrAborted -> End{-1}
mapping, not real abort delivery. Real abort/queue-overflow/Serve-
return tests are deferred to the next task by design.

Verified: go test ./internal/session/ -count=1 (all pass), go test
-race ./internal/session/ -count=1, and go test -race ./... -count=1
all clean; gofmt -l . and go vet ./... silent.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Abort reaches a running exec and is a no-op for an unknown req_id. Overflow is
refused with "busy: queue full" and — the point of the test — the recv loop
stays alive afterward, since a blocking dispatch would deadlock against the
very Abort that frees the queue. Disconnect cancels in-flight execs so Serve
returns, and the dedup cache survives into the next connection.

The abort-while-queued test establishes abort-before-dequeue ordering
explicitly (pending() + a short sleep) rather than relying on close(r.block)
timing: releasing the pool immediately races the abort's delivery against the
worker's ctx.Err() check, and once both <-r.block and <-ctx.Done() are ready
inside the runner, select picks at random — a defect in test sequencing, not
in the session (an abort landing as an exec starts legitimately yields
End{-1} via ErrAborted either way). Confirmed fixed: 20/20 clean under
go test -race, targeted; full package clean at 15 repeats.

CI now runs go test -race for remote-worker.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
A reviewer found the sender-failure test could pass without ever exercising
the sender's failure path: st.close() reliably won a race against the
20ms heartbeat (25/25 observed), so fakeStream.Send was never called a
second time and `failed` was never set inside the sender goroutine. Even
when it was reached, nothing filled the 64-slot outbound buffer, so the
test could not tell "sender keeps draining after an error" apart from
"sender returns on its first error" — both produced the same fast pass.

Fix: scriptedRunner gains a chunks field that emits that many stdout
chunks via the sink (192, three times the queue cap) so a non-draining
sender wedges the producer; fakeStream gains sendAttempts() so the test
can gate st.close() on an observed second Send attempt instead of racing
a heartbeat; Heartbeat is set to time.Hour in this test so the chunks
drive the failure path, not a timer.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
relaytest parks an Attach stream in-process and can misbehave on purpose, which
the real relay cannot: it never redelivers a req_id (relay.ts:89-93), so the
dedup half of the battery has no other way to be driven. The first four
acceptance items run the real BashRunner over real gRPC: cat, base64 -d with
stdin, stdout/stderr split with exit 7, and a ~60 KiB grep proving the chunk cap.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Token() claimed to carry "the authorization metadata the worker sent" — false:
the bearer header is attached by the test's own dial code, not by the session,
which never touches auth. The comment now says plainly what the assertion
proves (grpc-go metadata propagation plus this test double's extraction) and
what it does not (nothing about the production relay's own extraction).

Adds an ExecError guard before the read/write/bash exit-code assertions: a
worker that emitted ExecError instead of End was silently no-oping through
GetEnd().GetExitCode() on a nil receiver, misdirecting a failure to "content
mismatch" instead of naming the ExecError. The grep test already had this
guard.

Also corrects the grep test's output-size accounting: the comment and the
total-bytes floor said ~60 KiB where the real payload is ~149 KiB.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…e interop

Completes the rossoctl#87 battery. The abort test proves the process group died, not just
that we stopped reading: a sentinel file must stop growing. The dedup test asserts
the marker file still has one line, since re-emitting the right frame is not the
same as not re-running. SH_LIVE_RELAY=1 runs read/write/bash against the real
TypeScript relay via SandboxExec.Exec, covering the one thing a self-authored fake
relay cannot vouch for.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…D stub

Wires env → session.Config → BashRunner and adds the reconnect loop the stub
lacked: it returned on the first recv error and exited, so a restart wiped the
dedup cache and "reconnect → dedup" was unreachable. One Session spans every
connection now, with 500ms→30s jittered backoff. Hello advertises probed
capabilities and the real capacity_max instead of ["hello-world"] and 1.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
The worker now runs `bash -c`, but Dockerfile shipped distroless/static — no
shell, no coreutils — so every exec would have failed with ENOENT. Both images
move to ubi-minimal with bash, base64, and file, and run as UID 1001 to match the
nonroot-v2 SCC. The binary stays CGO-free: bash is a dependency of the commands,
not of the worker, and in production it drops into a real sandbox image.

Probed the current bases directly (docker run against each): ubi9/ubi-micro has
bash and base64 but not file; ubi9/ubi-minimal has bash and base64 too but also
lacks file until installed. Neither satisfies all three out of the box, so both
Dockerfile and Dockerfile.runtime move to ubi-minimal + microdnf install bash
coreutils-single findutils file. Verified by building both images and running
`bash`, `base64 --version`, and `file --version` inside each — all present, and
the container runs as uid=1001.

DESIGN.md drops the fabricated HELLO WORLD output and documents the actual
behavior, including the honest limits: stdout/stderr interleaving, dedup covering
completed execs only, and the cross-replica req_id collision.

Also fixes remaining stub-era references outside DESIGN.md's four listed edits:
run-local.sh's "HELLO WORLD" comment, the design doc's `go run .` invocation
(main moved to cmd/worker), the ykt1 in-cluster verification anecdote that cited
a fabricated HELLO WORLD match, and worker-deployment.yaml/deploy-incluster.sh's
runAsUser comments so they match the image's now-declared USER 1001.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Both Dockerfiles intentionally track the current UBI 9 minor via
ubi9/ubi-minimal:latest and an unpinned microdnf install — a pinned
digest would go stale silently, and package-version pinning breaks on
minor bumps for the same reason .hadolint.yaml already ignores DL3018
for Alpine. Suppress the two warnings with per-instruction
`# hadolint ignore=` comments instead of weakening the shared
.hadolint.yaml (used by CI for the repo-root Dockerfile too).

Verified: hadolint v2.12.0 with the repo's .hadolint.yaml now exits 0
for both remote-worker/Dockerfile and remote-worker/Dockerfile.runtime.

Also reword the two DESIGN.md references to a nonexistent
README-worker.md so they no longer send readers to a file that isn't
in the repo.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
DESIGN.md:57 said non-streaming buffers and emits exactly one Chunk
per stream at exit. internal/exec/runner.go's emitBuffered deliberately
slices buffered output into ChunkSize (32 KiB)-capped pieces, so a
non-streaming exec producing more than 32 KiB emits several Chunk
frames per stream. streaming: false guarantees no incremental delivery
(nothing leaves before the process exits), not a single frame — the
32 KiB cap still applies regardless, since an 8 MiB frame would exceed
gRPC's default receive limit.

DESIGN.md:46's wire-contract table said the dedup cache stores
req_id -> End. internal/session/loop.go also caches the timeout
ExecError{"timeout:<n>"} frame via the same cacheable path as a normal
exit (see runOne's cacheable branch), so the row now says the cache
stores the terminal frame generally.

Both were defects carried forward from the task-11 brief's prose, not
introduced by the earlier rewrite. Re-read the full file after editing;
no other sentence implies "exactly one chunk" for non-streaming or
that only End frames are cached — the "Dedup covers completed execs
only" bullet in Known properties and limits already described the
real behavior correctly.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Record the four discrepancies found while implementing the ST4 reference
worker (req_id non-uniqueness, the non-streaming shape gap in sandbox/v1,
the shell-less runtime images, and a newly-found cache-hit-drops-output gap)
and a verified acceptance walk-through mapping the seven contract criteria
to their real test names, with honest caveats on the never-run live-relay
test and the macOS-skipped escaped-process-group test. Written to files
rather than posted to the issue, since posting is the user's call and
gh auth is unavailable here.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ry budget

Whole-branch review before PR. Nine fixes, no new dependencies (keepalive is
part of the grpc module already required; go.mod/go.sum unchanged).

session/loop.go — three defects in accept/runOne:

- accept now checks in-flight BEFORE the cache. runOne calls cache.Put before
  sending its terminal frame and the slot is only released afterwards, so a
  duplicate arriving in that window used to hit the cache and replay a terminal
  frame while the original's was still in flight — two terminal frames for one
  exec, against the invariant the file asserts. The window widens under
  backpressure, which is when duplicates are likeliest.
- The in-flight branch now consults a fingerprint carried on the slot. req_id is
  not unique per worker (harness counter is module-scoped, sandboxes are shared),
  so replica B's different command under replica A's still-running req_id was
  being coalesced silently: it never ran and no frame was ever emitted. Matching
  fingerprint still coalesces; a mismatch is refused with an ExecError, which is
  safe precisely because it is different work.
- A signalled exit (runner returns code -1 with err == nil: OOM-kill, external
  SIGKILL) is no longer cached. Caching it poisoned the req_id — every later
  redelivery answered -1 without re-running.

cmd/worker/main.go:

- gRPC client keepalive (30s/10s, PermitWithoutStream: false), bounding a
  half-open connection to ~40s instead of TCP retransmit exhaustion. Without it
  recvLoop blocks in Recv forever, Serve never returns, the reconnect loop never
  runs, and the pool parks in enqueue behind a Send that cannot complete. The
  relay configures no keepalive enforcement policy, so stream-only pings cannot
  trip GOAWAY ENHANCE_YOUR_CALM.
- Backoff resets on a session that lasted >30s, not on Attach returning a stream.
  With a wrong SANDBOX_TOKEN the stream opens and Recv then fails Unauthenticated,
  so the old reset pinned backoff at its ~500-750ms floor forever.
- RELAY_TLS is parsed with strconv.ParseBool and is fatal on garbage. "true",
  "yes", "1 " all used to select plaintext silently, sending the bearer token in
  cleartext.

Memory: the pod limit was 64Mi against a worst case of 2 streams x
MaxConcurrent 4 x BufferCap 8 MiB = 64 MiB plus bytes.Buffer doubling, and the
trigger (Exec.streaming = false, the proto3 default) is entirely relay-supplied.
Limit 256Mi / requests 64Mi, with the arithmetic spelled out on both sides.

Honesty fixes in comments and docs:

- trySend's dropped frame is TERMINAL, not "advisory" (a cache replay or a
  refusal), and the refusal is not cached so dropping it loses it outright. The
  comment says so and the log is now a warning naming the unanswered req_id.
  Restructuring frame egress is deliberately out of scope for this branch.
- Serve documents its ctx precondition: it must be the context the stream was
  created from, because recvLoop has no ctx select and unblocks only via
  stream teardown.
- Sink forbids Chunk after Run returns (frameSink writes to a channel Serve
  closes, so a late call panics rather than erroring).
- Fingerprint length-prefixes both fields; a bare NUL separator is not injective.
  Not exploitable today (a NUL-bearing command cannot reach cmd.Start), but this
  is the scheme other language ports will copy.
- .gitignore covers /worker, the binary go build ./... actually drops.
- DESIGN.md: the accept order, the signalled-exit exclusion, and the cache-replay
  gap (a hit re-emits no Chunks, so a redelivered `cat` answers 0 with empty
  content) are all recorded where a second implementer will look.

Tests: 48 -> 53 (51 pass, 2 deliberate skips). New coverage for the colliding
in-flight duplicate, the uncached signalled exit, streaming=false end to end
over the wire, Serve returning on stream-context cancellation, and RELAY_TLS
rejecting garbage. Each new test was mutation-checked against the pre-fix
behavior. The tautological capabilities() assertion (a literal that was never in
the probed list) is replaced with a real subset check.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
Every finding this branch's reviews raised and did not fix, in one place: three
recommended before merge, six residuals parked after the whole-branch review, and
33 deferred minors. None affects the acceptance battery or runtime correctness.

The implementation ledger that produced this list is git-ignored scratch and will
not survive the branch, so the list is committed where the PR can cite it.

Refs rossoctl#87

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>

@pdettori pdettori left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Assessment: APPROVE — no blocking findings. Submitted as COMMENT only because GitHub rejects APPROVE on a self-authored PR (422); treat this as an approving review with two suggestions.

The concurrency design holds up under reading, and the non-obvious parts are the ones that are right: sender-goroutine ownership of Send, trySend confined to the recv path, in-flight-checked-before-cache, cancelConn() before close(queue), and wg.Wait() before every Chunk-bearing return path. The cmd.Cancel returning os.ErrProcessDone unconditionally, and the drain watchdog compensating for WaitDelay's documented *Pipe() exclusion (go.dev/issue/23019), are both correct and the kind of thing that gets "cleaned up" later — the comments earn their length.

Verified rather than taken on trust:

  • go test -race ./... → 51 pass / 2 skip / 0 fail, matching the PR body exactly. Both skips are the documented ones.
  • TLS: MinVersion: tls.VersionTLS12, system roots, no InsecureSkipVerify. envBool failing loudly on unparseable RELAY_TLS is the right call for a flag that decides whether a bearer token crosses in cleartext.
  • No .claude/ or .vscode/ changes; 23 commits all signed off; no Co-authored-by trailers; all 10 CI checks green.

Two suggestions inline, both about triage accuracy rather than runtime behaviour — though the first is a real spurious-failure path currently filed as cosmetic. Neither blocks merge.

On the squash note: agreed on 8b87a41 and 0c5648b. Worth folding the deferred-doc corrections (comment 2) into the same pass, since that file is the artifact follow-up work will be planned from.


Areas reviewed: Go (exec runner, session loop, dedup cache, entrypoint), tests, Dockerfiles, K8s deployment, CI/Actions, docs
Agent/IDE config (.claude/.vscode): none

Assisted-By: Claude Code

Comment thread remote-worker/internal/session/cache.go Outdated
// can never be the source of a cached entry), but this scheme is the reference
// other language ports will copy, and a length prefix makes the encoding
// unambiguous for any input rather than only for the inputs bash accepts.
func Fingerprint(command string, stdin []byte) [32]byte {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

suggestion — Fingerprint covers command+stdin but not timeout_s, and deferred item 45 files the consequence as "the message then misstates what was asked." It is worse than a wrong message: the exec never runs.

Probed on this branch against the real session + fake relay:

delivery 1  req_id 5  "sleep 3"  timeout_s=1   -> Error{timeout:1}   [1.01s, ran]
delivery 2  req_id 5  "sleep 3"  timeout_s=30  -> Error{timeout:1}   [649us, NEVER RAN]

The second delivery had 10x the budget it needed and was failed in 649µs off the cache. That is not a cosmetic message defect — it is a spurious failure for work that would have succeeded.

What makes it worth promoting out of "deferred minor": the reachable path is precisely the cross-replica req_id collision described in finding #1 of the PR body — two harness replicas both counting from 1, same command, different budgets. That collision class is the entire reason the fingerprint guard exists, and on this axis the guard waves it through. The cache-hit branch in accept cannot help, because by construction it never re-runs.

The fix is small and the existing encoding extends naturally — the length-prefix scheme is already there:

binary.BigEndian.PutUint64(n[:], uint64(timeoutS))
h.Write(n[:])

A legitimate redelivery carries the same Exec message, so timeout_s is stable across it — including it costs nothing on the path dedup is actually for.

Same probe on streaming, for the same reason:

delivery 1  req_id 9  "echo hello"  streaming=false -> stdout "hello\n"
delivery 2  req_id 9  "echo hello"  streaming=true  -> stdout ""

That is the disclosed finding #4 root, but folding streaming into the hash closes the flag-flip half of it locally, without waiting on the contract change.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 3bbb2d3. Both fields are in the hash now, length-prefixed in the same style.

Your probe was the convincing part — I had this filed as a cosmetic wrong-message defect
and it isn't. A spurious failure for work that would have succeeded, on the one path the
guard exists to catch, is a different severity entirely.

Folded streaming in as well, for the reason you gave: it closes the flag-flip half of
finding #4 locally without waiting on the contract change. The remaining half stands — a
same-shape redelivery still re-emits the terminal frame with no chunks, because End has
nowhere to put output.

The behavior is pinned by a contract test rather than only a hash unit test, since the hash
being different is not the property that matters:

first    req_id 8  "sleep 3"  timeout_s=1   -> ExecError{"timeout:1"}
redeliver req_id 8  "sleep 3"  timeout_s=10  -> End{0}, ~3s elapsed

The elapsed-time assertion is what makes it non-vacuous. Mutation-checked by excluding
timeout_s from the hash: fails in 1.01s with timeout_s must be part of the fingerprint.

Comment thread docs/notes/st4-deferred-items.md Outdated

## Recommended before merge (3)

- Task 5: minor (deferred, RECOMMEND FIXING BEFORE MERGE): Fingerprint's 0x00 separator is not injective if `command` itself contains a NUL — Fingerprint("a\x00b", nil) and Fingerprint("a", []byte("b\x00")) collide. Low practical risk (proto3 strings may carry NUL but such a command could not exec), but a collision in the guard means a silent wrong answer, which is the exact failure class the guard exists to prevent. A length-prefix would close it (~3 lines).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

suggestion — three entries in this file describe defects the branch already fixes, including this one, which sits in the Recommended before merge (3) tier. Checked each against the shipped code at 546b21b:

This item (8) — "Fingerprint's 0x00 separator is not injective… A length-prefix would close it (~3 lines)." Shipped Fingerprint is length-prefixed (binary.BigEndian.PutUint64 before each field), its doc comment gives that exact rationale verbatim, and cache_test.go:70 asserts Fingerprint("a\x00b", nil) != Fingerprint("a", []byte("b\x00")). Done.

Item 46 (line 46) — "close(queue) precedes cancelConn(), leaving a window where a pool goroutine … spawns a real bash child that is killed immediately." Shipped order is the reverse, loop.go:235-236, with a comment stating why:

cancelConn() // stop heartbeats and kill in-flight/queued children
close(queue)

Fixed in ba795da — commit 11 of 23.

Item 44 (line 44) — "the comment should say so or the code should decline to cache code < 0." Shipped does both: cacheable = code >= 0 at loop.go:400, with the comment explaining that a signal is not a determination the worker would reproduce. Fixed in 8a5bd1e — commit 22.

This file is the final commit on the branch, so all three were stale on arrival rather than overtaken by later work. The cost is concrete: the merge checklist advertises 3 blockers when it is 2, and whoever picks up the deferred list would spend time re-fixing two closed items and re-verifying a third.

Worth a pass over the remaining 33 for the same class of drift before merge — items written per-task during implementation, then never reconciled against the post-review-wave code. (Item 45 is the inverse problem: still open, but under-rated — see the cache.go comment.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The file is gone as of 0976b02, and the audited list now lives in #173.

You undercounted it. I checked all three tiers against shipped code and every entry in
the "Recommended before merge (3)" section was already fixed
, not just the fingerprint one:

Listed as a blocker Shipped
Fingerprint NUL separator not injective length-prefixed, with that rationale in the doc comment
backoff resets on transport success time.Since(start) > 30*time.Second
nothing documents the attachCtx precondition documented on Serve

Plus items 44 and 46 as you found. So the checklist advertised three blockers where the
count was zero — and the three genuine residuals weren't in that tier at all.

Root cause is exactly the drift you diagnosed: I generated that file by grepping an
implementation ledger that recorded findings as they were raised, then never reconciled
it against the code after the final review wave. A mechanical extraction can't know which
of its inputs were subsequently closed. It was the last commit on the branch and stale on
arrival.

Rather than re-audit it in the repo, the write-ups moved to where they can be revised as
the code moves: findings on #87 and #89, the acceptance battery on #87 with the ST5
handover on #88, deferred items in #173. DESIGN.md and docs/specs/ still carry
everything a reader of the code needs.

I also took the three real residuals rather than shipping them as a checklist — the
non-streaming test that couldn't detect an ignored streaming: false (mutation-checked
now), Serve's half-over-broad failure-mode sentence, and the spec's collision-path drift.

…rprint

A redelivery differing only in timeout_s was answered from the cache without
running: req_id 5 "sleep 3" with timeout_s=1 fails as timeout:1, and the same
req_id with timeout_s=30 was failed off that entry in ~650us despite having ten
times the budget it needed. Same shape for streaming — a flag-flip returned empty
stdout. The reachable path is the cross-replica req_id collision the fingerprint
guard exists to catch, so on these two axes the guard was waving it through.

A genuine redelivery carries the same Exec message, so both fields are stable
across it and including them costs nothing on the path dedup is for.

The contract test asserts the redelivery actually RUNS (~3s, End{0}) rather than
merely returning a different frame; mutation-checked by excluding timeout_s from
the hash, which fails it in 1.01s with "timeout_s must be part of the fingerprint".

Refs rossoctl#87

Signed-off-by: Paolo Dettori <[email protected]>
accept() checks the in-flight map before the cache: a cross-replica
req_id collision is refused with ExecError while the original is still
running (two concurrent execs under one id would otherwise result), and
only runs fresh once the original has completed. The spec previously
described only the completed case. Also note that the in-flight check
ahead of the cache lookup is what stops a duplicate arriving between
cache.Put and slot release from being answered twice.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…ction

The comment claimed shutdown breaks if the identity between Serve's ctx
and the Attach stream's ctx is broken "in either direction." Only one
direction actually wedges: creating the stream from a context nothing
ever cancels hangs regardless of what ctx Serve is given. Handing Serve
an unrelated ctx is harmless as long as the stream's own context is the
one that gets cancelled.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…makes

TestContractNonStreamingBuffersThenChunksAtExit asserted chunk count,
per-frame cap, byte-exact completeness, and the terminal frame — all of
which hold for incremental streaming too, so the test could not detect a
worker that ignored streaming:false. Change the command to produce its
output immediately and then sleep before exiting, and assert the first
Chunk does not arrive until close to the sleep duration.

Verified by temporarily forcing Streaming=true in the runner (simulating
"ignore streaming:false"): the strengthened assertion fails, with the
first chunk landing in ~19ms instead of the ~700ms floor.

Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
These three files were review and handover artifacts, not documentation the repo
should carry: they duplicate what belongs on the tracker and go stale the moment
the code moves — st4-deferred-items.md was already advertising three blockers that
had been fixed one commit earlier.

Their content now lives where it is actionable and can be revised:
  - findings          -> rossoctl#87 and the epic rossoctl#89
  - acceptance battery -> rossoctl#87, with the ST5 handover on rossoctl#88
  - deferred items    -> rossoctl#173, audited against shipped code

DESIGN.md and docs/specs/ still carry everything a reader of the code needs.

Refs rossoctl#87

Signed-off-by: Paolo Dettori <[email protected]>
@pdettori
pdettori merged commit 84118c9 into rossoctl:main Aug 27, 2026
10 checks passed
@pdettori
pdettori deleted the feat/st4-go-worker branch August 27, 2026 14:59
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.

1 participant