Repository navigation
fix(k8s-sandbox): make the output cap a seam-wide guarantee + explicit truncation contract - #188
Conversation
Design for closing rossoctl#180, rossoctl#181 and rossoctl#185 as one change: a required `truncated` flag on the SandboxTransport return type, the cap extended to `persistentExecInPod`, and declared-capability conformance covering all three implementations. Records three decisions with their rejected alternatives: - rossoctl#180: cap the persistent channel at the same 8 MiB, uniformly, rather than at a higher read-specific limit or not at all. Implemented pod-side via `head -c` in wrapCommand's pipeline, which gives exact byte parity before base64 inflation, keeps PIPESTATUS[0] indexing the command, and bounds a pre-existing O(n^2) in FrameParser.push. - rossoctl#181: createPodBashOps returns exit 137 on truncation, so Pi's existing path surfaces both the failure and the streamed output tail. A bare throw would lose the tail, since bash.ts appends output only for aborted/timeout. - rossoctl#185: producerStopped() becomes producerStoppedRemotely() and each transport declares its reach; the battery asserts the declared value instead of accepting true from everyone. Also records two findings that bound the work: createPodBashOps is the only call site that is actually wrong (the other five already fail closed, just with misleading messages), and capping the read path is costlier than rossoctl#180 states because pi-fork's read.ts reads whole files before applying offset/limit — so a capped file is unreachable, not merely truncated. Refs rossoctl#180, rossoctl#181, rossoctl#185. Epic rossoctl#89. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…e boolean Planning surfaced that the two-value reach from the approved draft would make the battery assert producerStoppedRemotely() === false for both kubectl paths, discarding the existing assertion that child.kill is actually called — coverage rossoctl#184's review found load-bearing, since with it removed deleting child.kill still passed. It also had no honest value for the persistent channel, which after §3.3 kills nothing client-side. Replace it with a four-value mechanism enum (remote-abort / local-kill / producer-side-cap / none) that each transport declares and the battery pins. Every transport now makes a positive claim about its own mechanism, and "none" turns a deleted stop into a failure instead of a silent true. Same decision as approved for rossoctl#185 — assert the declared mechanism rather than accept true from everyone — at the precision the battery actually needs. Refs rossoctl#185. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…sport seam exitCode === null was overloaded: it meant both 'our output cap tripped' and 'the process produced no exit status' (signalled; gRPC end.exitCode < 0; a stream that ended with no End frame). Callers could not tell those apart, which is the root of rossoctl#180, rossoctl#181 and rossoctl#185. Add a REQUIRED truncated: boolean to the seam's result. Required rather than optional so a future transport cannot omit it and read as 'not truncated' — that silent divergence is the defect, not an implementation detail. exitCode stays null on truncation, so every existing caller that checks !== 0 keeps failing closed and there is no flag day. Both per-call transports already tracked this internally and simply did not return it. persistentExecInPod carries false for now; its cap lands next. The battery asserts the invariant truncated ⇒ exitCode === null for every implementation. Refs rossoctl#180, rossoctl#181, rossoctl#185. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
createPodBashOps returned the seam's exitCode verbatim, and Pi's bash tool treats null as non-failing (pi-fork/.../tools/bash.ts:397). So a bash whose stdout crossed the 8 MiB cap was SIGKILLed mid-flight and presented to the model as having completed normally, with no signal its output was cut short. Return 137 (128+9, the conventional SIGKILL status) on truncation. It is not a fabricated code — the command was killed by signal 9 at the cap — and it routes through Pi's existing failure path, which appends the streamed output tail, so the model receives both the honest failure and the output. A bare throw would have lost the tail, since bash.ts appends output only for aborted/timeout messages. A null exit code that is NOT a cap trip still passes through untouched, so 'signalled, no status' is not relabelled as a cap kill. Closes rossoctl#181. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
persistentExecInPod was the third SandboxTransport and the only uncapped one, and extension.ts wires it to Read/Write/Edit/Ls/Find — so 'the cap is a seam guarantee' (spec §8) was false on every file-reading tool, and Pi could tell the backends apart on output volume: cat a 20 MiB file and 20 MiB came back, where either per-call transport returned 8 MiB plus the marker. Cap in the pod, via a head -c stage in wrapCommand's pipeline, rather than counting bytes client-side: - Exact byte parity. head -c bounds RAW stdout before base64 inflation, so the trip point matches the per-call transports. A client-side count would have capped content at cap × 3/4 — a weaker form of the same divergence. - PIPESTATUS[0] still indexes the command; appending a stage does not shift index 0. A trip makes it 141 (SIGPIPE), which is ignored: truncation is detected by length, so nothing depends on distinguishing that 141 from a command's own internal SIGPIPE. - It bounds FrameParser.push, which re-stringifies its buffer per chunk and so grows quadratically — a 20 MiB read allocated ~5.8 GB transiently. The pod returns cap+1 bytes so the client can tell 'landed exactly on the cap' (complete) from 'exceeded it'. A trip RESOLVES with truncated: true rather than calling the inflight fail() path, which retries through deps.fallback — the capped KubectlTransport — and would have re-run the command, flooding twice before failing anyway. Proved against a real bash in framing.test.ts, not only against the hermetic fake: 5000 bytes offered at cap 100 yields exactly 101, a failing command still frames exit 42, and the heredoc-stdin write path survives the added stage. Both client-side assertions were mutation-checked: widening the trip threshold by 1000 fails the cap test, and trimming to cap+1 fails the stdout assertion. Refs rossoctl#180. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…sh-ops tests
The BashOperations.exec method requires onData as a parameter, but the tests
omitted this required option, causing type errors in vitest that were masked
because the test runner doesn't typecheck (tsc does). All three new bash-ops
tests now pass { onData: () => {} } to satisfy the type requirement, while
maintaining the same test logic and assertions.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: Paolo Dettori <[email protected]>
…lared mechanisms producerStopped() reduced every stop mechanism to a boolean that each factory set from its own local action: the kubectl factory from 'child.kill was called', the gRPC factory from 'Abort was issued'. Both reported true, so the battery was satisfied and the asymmetry was invisible BY CONSTRUCTION (rossoctl#185) — in the battery that is the stated evidence for the epic's transport-swappability claim. Replace it with a declared mechanism each transport must claim and the battery pins: remote-abort (gRPC tells the far side and observes it), local-kill (kubectl kills its own client; in-pod death is by EPIPE, if at all), producer-side-cap (the persistent channel's pod-side head -c bounds output at the source, so there is nothing to kill). 'none' is unclaimable, so deleting a stop now fails loudly instead of reporting true. An enum rather than a 'was it remote?' boolean, which would have asserted false for both kubectl paths and so discarded the coverage that child.kill is actually called — load-bearing coverage, since with it removed deleting child.kill still passed. persistentExecInPod now runs the battery too, declaring streams: false because it is request/response over one multiplexed channel. Declared, not silently skipped: quietly omitting a case for one implementation is how rossoctl#185 survived. Its cap fake simulates the pod, so the pipeline itself is proved against a real bash in framing.test.ts; here the client half is held to the contract, and its fallback throws so a cap trip that re-ran the command would fail. Mutation-checked: removing child.kill from exec.ts's cap branch, and client.abort from grpc-relay-transport.ts's, each fail the cap case with 'none'. Closes rossoctl#180. Closes rossoctl#185. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Both already threw on exitCode === null, but the message blamed two causes at once — 'output cap tripped or cat signalled' — because that was all a null code could tell them. With truncated on the seam they can be specific. readFile now issues one stat -c %s on the truncation path to name the file size, and points at the only tool that can still reach the file: pi-fork's read.ts reads the WHOLE file before applying offset/limit, so a file over the cap is unreachable through Read/Edit entirely, not merely truncated. The extra exec is error-path only, and degrades to omitting the size if the stat also fails. A null exit code that is NOT a cap trip now says so, instead of sending the model chasing a size limit that is not the problem. Refs rossoctl#180, rossoctl#181. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
…n branch The glob counterpart of the readFile test fixed earlier had the same staleness: exitCode: null with no truncated set defaults to false, landing in the signalled branch, not the cap-trip branch its name and comment describe. It kept passing only because /glob (failed|truncated) in pod/ was loose enough to match either message. Set truncated: true so the fake represents an actual cap trip, and narrow the assertion to /output cap/ so it can only match the truncation message. Updated the comment to drop the now-split "cap tripped (or rg was signalled)" blended wording. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Three call sites already failed closed on exitCode === null, but blamed the wrong component: the pod grep tool surfaced our own output cap as "rg failed in pod (exit null)", and an over-cap workspace or swebench diff surfaced as "diff capture failed (exit null)" (or "swebench setup/diff capture failed") — each reading as a broken git/rg command rather than output too large for the seam. createPodGrepTool, convergeWorkspace, captureWorkspaceDiff, setupSwebenchWorkspace, and captureSwebenchDiff now check `truncated` before the existing exitCode guard and name the cap and the operation. packages/k8s-sandbox/test/grep-tool.test.ts did not exist; added it (modeled on operations.test.ts) with a fake ExecInPod covering the cap-trip, a genuine rg failure, and the no-matches path. harness/test/converge.test.ts and harness/test/swebench-setup.test.ts gained truncation-path tests; the existing converge.test.ts transport fakes were missing `truncated` (harness test files aren't included in tsconfig, so this compiled but was never exercising the truncated branch) — added `truncated: false` to match the seam's real shape. Refs rossoctl#180, rossoctl#181. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Spec §8 stated the cap as a seam property and then carried a 'Known exception' for the third transport plus two 'Accepted divergences' recording the false success and the unequal enforcement. All three are closed in code, so the prose becomes a statement rather than a caveat, with a table of the per-transport stop mechanisms the battery now pins. The rossoctl#182 default-deadline divergence stays: that is a separate open decision. ADR-0024 gains a Revisions entry per decision with its rejected alternatives, including the cost accepted for the Read path — a file above the cap is unreadable, not merely truncated, because pi-fork's read.ts reads whole files before applying offset/limit. Refs rossoctl#180, rossoctl#181, rossoctl#185. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
The pod-side cap is the one part of this change with no hermetic proxy: the conformance fake SIMULATES head -c, and framing.test.ts proves the pipeline under a local bash. Neither proves they compose through kubectl exec into the sandbox image's coreutils. Claim 6 writes a 9 MiB file in-pod, asserts the read fails with the size and the sed range hint, asserts a 1 MiB file still reads cleanly so the cap did not make the path fragile, and asserts bash reports 137 rather than success on the same real pod. Gated on M3_LIVE_SMOKE, so CI never runs it. This gate is committed UNEXECUTED: no live kind cluster was available in this session (sh-knative-control-plane had already exited), and reviving the cluster/Knative/Redis/sandbox stack was explicitly out of scope for this change. Confirmed only that the suite is skip-by-default with M3_LIVE_SMOKE unset (7 tests skipped, exit 0) and that it type-checks. No claim of a live pass is made here. To actually run it against the real local cluster: M3_LIVE_SMOKE=1 KAGENTI_SANDBOX_POD=sandbox-0 KAGENTI_SANDBOX_NAMESPACE=default \ KAGENTI_SANDBOX_CONTEXT=kind-sh-knative \ pnpm -C packages/k8s-sandbox exec vitest run test/m3-live-smoke.test.ts Refs rossoctl#180, rossoctl#181. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
exec.ts:72 cited spec §8 "Accepted divergences" for the SIGPIPE/EPIPE residual- risk fact. Task 7's own Step 2 deleted that divergence bullet — the fact now lives in §8's "Poisoned-output defense" bullet instead — so the citation moved because the divergence bullet it named was deleted. Point the comment there. Also tightens the 2026-08-30 ADR-0024 revision's readFile sentence: it now names the path (previously omitted) and states that the file size is included only when a truncation-path stat succeeds, rather than implying it is always present (operations.ts:34-35). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Applies the seven cross-cutting fixes from the whole-branch review of the 8 MiB output cap / truncation seam (closing rossoctl#180, rossoctl#181, rossoctl#185). Important: - operations.ts: drop the stale, duplicated comment above createPodFindOps.glob that still asserted the removed overloaded null-exit-code semantics. - run-leaf.test.ts: add the now-required `truncated: false` to two SandboxTransport fakes (harness/tsconfig.json excludes test/ from typecheck, so this compiled without it). - conformance.ts: add the missing at-the-cap boundary case ("does not flag output that lands exactly on the cap") to the shared battery, covering all three transports at once. Passed for KubectlTransport, GrpcRelayTransport, and persistentExecInPod on the first attempt; no factory changes needed. Minor: - persistent-exec.ts: fix an inaccurate comment claiming the trim matches the per-call transports "byte-for-byte" — only the `> cap` trip boundary matches, not the byte count. - conformance.ts: reword the ProducerStop `remote-abort` doc to not claim observability the code doesn't have (correlation by req_id only). - conformance.ts: fix two stale "two implementations" / "Both transports" counts now that the battery runs against three. - operations.ts: add the missing truncated-cap branch to createPodLsOps.readdir (ls -1A is unbounded), mirroring glob's split, with a paired test in operations.test.ts. make typecheck: exit 0 across all four packages. packages/k8s-sandbox test: 127 passed | 11 skipped (up from 123 passed). harness test: 226 passed | 3 skipped (unchanged). Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
|
Follow-ups from this branch's review, filed rather than folded in — each is out of ST6's declared scope (
|
Live gate now run — 7/7 on a Kind clusterThe PR body has been updated: the live smoke is no longer unexecuted. Run at The deploy-blocking risk flagged earlier is closed for this image. The concern was that the
So both the empty-read path and the missing- Note for whoever runs this suite nextMy first run was 4 passed / 3 failed, and the failures were not code-related: Claims 1, 4 and 5 require the fixture tree documented in Worth folding that seeding into the suite (or a |
Claims 1, 4 and 5 assert on a `.gitignore` and a tree of seeded `.ts` files that they do not create themselves; Claims 2 and 4b build their own, which is why they pass on a bare pod while the others do not. The seeding was a manual step in SMOKE.md, so a pod restart was enough to lose it. Skipping that step is actively misleading rather than merely inconvenient: the symptoms are `Read failed in pod (cat exited 1): /head/.gitignore` and `glob result: []`, which look exactly like regressions in the read and glob paths this branch changed. It cost real time to attribute during this branch's live run — 4 passed / 3 failed on the first attempt, 7/7 after seeding, with no code change between the two. Move the seeding into a `beforeAll` so the suite is self-contained. Idempotent by construction (`mkdir -p`, truncating redirects), so re-runs and a partly seeded workspace are both fine. It writes under `/workspace` because the pod runs as an arbitrary non-root UID and `/tmp` is not writable. Verified by deleting every fixture from the pod and running the gate with no manual seeding: 7/7 passed. Still skip-by-default (7 skipped) with M3_LIVE_SMOKE unset, so CI never runs it and never touches a cluster. SMOKE.md's manual step is marked no-longer-needed, retaining the commands as a record of what the suite seeds. Refs rossoctl#180, rossoctl#181. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Live-smoke fixtures now seeded by the suite (
|
rossoctl#187 (propagate ripgrep failures from glob) merged to main while this branch was in review, touching the same `createPodFindOps.glob`. The two changes are complementary and both are kept. rossoctl#187 adds a shell guard so `rg`'s own status survives the pipe to `head`, which would otherwise mask it: rc=${PIPESTATUS[0]}; [ "$rc" = 0 ] || [ "$rc" = 1 ] || [ "$rc" = 141 ] || exit "$rc" plus the matching `r.exitCode !== 1` tolerance, since rg exits 1 for "no matches". That is about the SEARCH failing. This branch splits truncation into its own `truncated` flag, because a cap trip is a property of the seam and can happen while rg is perfectly happy — reporting it as "rg exited N" blames the wrong component. Resolution keeps rossoctl#187's exec command verbatim and checks `truncated` first, then the null exit code, then rossoctl#187's `!== 0 && !== 1` guard. A naive resolution that took this branch's side would have silently dropped rossoctl#187's `!== 1` tolerance, reintroducing the "no matches reads as an error" bug it fixed. Verified the two compose in the pod, not just on paper: `glob` runs over the persistent channel, so the merged command is rossoctl#187's guard nested inside this branch's `{ … } | head -c <cap+1> | base64` wrapper. Inside the brace group `${PIPESTATUS[0]}` still resolves to the inner `rg | head -n` pipeline, and the group's own status becomes the outer `PIPESTATUS[0]`. Live gate 7/7 on the merged tree, with Claim 4 returning ["top.ts","src/keep.ts"] — the result SMOKE.md documents. make typecheck EXIT 0; k8s-sandbox 129 passed / 11 skipped; harness 226 passed / 3 skipped. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Rebased onto #187, which merged mid-review (
|
pdettori
left a comment
There was a problem hiding this comment.
Review
Author: pdettori (MEMBER — maintainer) · self-authored, so this is posted as a COMMENT review; approval needs a second maintainer.
Areas reviewed: TypeScript (k8s-sandbox seam + harness), tests, docs/specs/ADR
Agent/IDE config (.claude/, .vscode/): none
Commits: 16, all signed-off: yes
CI: all 10 checks passing
No must-fix issues. Two suggestions inline.
Verified rather than taken on trust
- Truncation coverage is complete at the consumer layer. Every
execsite with unbounded output checkstruncated:readFile(and socreatePodEditOps.readFile, which reuses it — the #180 data-loss path),bash,readdir,glob,grep, plus the four harness sites. The unchecked sites (access,mkdir,writeFile,exists,stat,detectImageMimeType) all produce bounded output, so a trip is unreachable there. - The
PIPESTATUS[0]claim holds against real bash.framing.test.tsframesexit 42as 42 through the added stage, returns exactly 101 bytes for 5000 offered at cap 100, and round-trips the heredoc-stdin write. The pre-existing{ …; } | …shape also keepsglob's innerexit "$rc"confined to a pipeline subshell, so the merged #187 guard cannot kill the session. - Transport wiring is consistent with the exit-137 rationale.
bashandgrepare onstreamTransport(KubectlTransport), which does stream — so Pi's failure path genuinely has a tail to append.streams: falseonly affects the persistent channel, which serves Read/Write/Edit/Ls/Find. - The battery is not self-fulfilling. The
producerStopenum, the exact-cap non-trip case, and the throwingfallback(reaching it means a cap trip was mistaken for a dead channel) each pin a distinct mechanism. - #187 is merged and integrated.
fbc265aresolved thegloboverlap correctly — thePIPESTATUSguard and the truncation check are both present, and in the right order.
Two body-accuracy points
Not code — flagging because the description is doing evidence duty here.
- The live-smoke section says the 7/7 run was at
b074e80, "the tip of this PR." The tip is nowfbc265a, two commits later, including an upstream merge that touchedoperations.ts:glob. The smoke has not been re-run against the merged code. - The reproduce note tells the reader to seed fixtures per
SMOKE.md§96-102 first, butcdb5fc2made the suite self-seeding and replaced that section. The Conflict note section likewise still describes #187 as OPEN and CONFLICTING.
Assisted-By: Claude Code
| ): string { | ||
| const begin = `printf '${SOH}B%s\\n' ${nonce}; `; | ||
| const end = `printf '${SOH}E%s %d\\n' ${nonce} "\${PIPESTATUS[0]}"\n`; | ||
| const cap = `head -c ${capBytes + 1}`; |
There was a problem hiding this comment.
suggestion — This stage is now unconditional on every persistent-channel command, but nothing in code or in non-live CI enforces that the image actually supports head -c.
The failure mode you documented is the worst kind: empty stdout with exit 0 → readFile returns an empty buffer with a success code → Edit writes it back → zero-length file. The PR body's manual kubectl exec … head -c 1 /dev/null check is the right check, but a PR description is not where an image bump will look.
A one-time capability probe when the session is first spawned in persistentExecInPod — probe, and on failure either throw or permanently route through deps.fallback — would turn a silent data-loss path into a loud startup error, at the cost of one exec per session. m3-live-smoke Claim 6 covers this today only under M3_LIVE_SMOKE=1, which CI does not run.
There was a problem hiding this comment.
Fixed in 7dd511a, though not with the startup probe — I took a different mechanism and want to be explicit about why, since you named one.
First, I reproduced the failure against real bash rather than reasoning about it:
head missing -> group=0, head=127, stdout EMPTY
head rejects -c -> group=0, head=1, stdout EMPTY
Both report the command's own exit 0 with no output, which is exactly the destructive shape you described. Note the second variant: detecting only "command not found" would have missed it.
wrapCommand now captures the whole PIPESTATUS array and reports CAP_STAGE_FAILED (-2) when the cap or base64 stage failed, instead of the command's status. persistentExecInPod latches on that code, warns once naming the pod and the exact kubectl exec … head -c 1 /dev/null check, and routes that op and every later one through deps.fallback — which caps client-side and needs no head -c, so file tools keep working in a degraded but correct mode rather than failing outright. Latched rather than retried because the pod's binaries will not change mid-session.
Why not the probe. It would occupy the first nonce on every channel, shifting the sequence that most of persistent-exec.test.ts asserts on (frameFor("n1", …)) and forcing the conformance fake to special-case a probe command — broad churn in the trickiest file, late in the branch. Checking the stage status instead costs no extra exec, catches the failure at the exact point of harm rather than only at spawn, and also covers a broken base64, which a head -c probe would not.
Evidence: both failure modes proved by shadowing head on PATH under real bash; an inverse test that a healthy pipeline still frames exit 42 as 42, so the check cannot swallow real exit codes; a client-side test that the latch degrades without a futile respawn. Mutation-verified — removing the latch fails that test, removing the stage check fails four framing tests. Live gate re-run 7/7 on a real pod with the changed protocol.
Happy to switch to the spawn-time probe if you'd rather have the check at startup; say so and I'll do it.
| // directory listing — it may even contain OUTPUT_TRUNCATED_MARKER as a bogus entry. | ||
| if (r.truncated) { | ||
| throw new Error( | ||
| `readdir exceeds the ${DEFAULT_OUTPUT_CAP} byte sandbox output cap: ${p}.`, |
There was a problem hiding this comment.
nit — This is the one cap error with no remedy. readFile points at sed -n, glob says "narrow the pattern or lower the limit", grep says "narrow the pattern or search a smaller path" — readdir just names the cap and the path. Something like List a subdirectory, or use bash with \ls -1A | head -n `.` would match the affordance the other three give.
There was a problem hiding this comment.
Fixed in 7dd511a. readdir's cap error now reads:
readdir exceeds the <cap> byte sandbox output cap: <path>. List a subdirectory, or use bash with \ls -1A | head -n `.`
which matches the affordance readFile, glob and grep already give.
Addresses the review on rossoctl#188. The `head -c` stage is unconditional on every persistent-channel command, and nothing enforced that the image supports it. Verified against real bash what happens when it does not: head missing -> group=0, head=127, stdout EMPTY head rejects -c -> group=0, head=1, stdout EMPTY Both report the COMMAND's own exit 0 with no output, so `readFile` returns an empty buffer with a success status and Pi's Edit tool writes that back — truncating the file to zero length. Silent data loss. `wrapCommand` now captures the whole PIPESTATUS array and reports CAP_STAGE_FAILED (-2) when the cap or base64 stage failed, rather than the command's status. `persistentExecInPod` latches on that code, warns once naming the pod and the check to run, and routes that op and every later one through deps.fallback — which caps client-side and needs no `head -c`, so file tools keep working in a degraded but correct mode rather than breaking outright. Chosen over the reviewer's suggested startup capability probe: a probe would occupy the first nonce, shifting the sequence that most of persistent-exec's tests assert on and forcing the conformance fake to special-case a probe command — broad churn late in the branch. Checking the stage status costs no extra exec, catches the failure at the exact point of harm rather than only at spawn, and also covers a broken `base64`. Both failure modes are proved by shadowing `head` on PATH under real bash, plus an inverse test that a healthy pipeline still frames `exit 42` as 42, plus a client-side test that the latch degrades without a futile respawn. Mutation- verified: removing the latch fails that test; removing the stage check fails four framing tests. Also addresses the review nit: `readdir`'s cap error now offers a remedy ("List a subdirectory, or use bash with `ls -1A | head -n <n>`"), matching what readFile, glob and grep already give. typecheck EXIT 0; k8s-sandbox 133 passed / 11 skipped; harness 226 passed / 3 skipped; live gate 7/7 on a real pod with the changed wire protocol. Refs rossoctl#180, rossoctl#181. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Paolo Dettori <[email protected]>
Review addressed (
|
What this does
Makes the 8 MiB output cap a true property of every
SandboxTransport, and gives truncation an explicit representation in the seam so a killed command can no longer be reported to the model as success.Closes #180. Closes #181. Closes #185.
Spec:
docs/specs/2026-08-30-seam-output-cap-truncation-design.md(ST6). Three decisions and their rejected alternatives are recorded in ADR-0024's Revisions section.The pod-side
head -cstage runs on every command through the persistent channel, not only over-cap ones. Ifhead -cwere absent or rejected-cin the sandbox image,{ cat f; } | head -c N | base64yields empty stdout with exit 0 —catwrites into the pipe buffer and exits cleanly, while the deadheadstage leavesbase64with nothing to read.readFilewould then return an empty buffer with a success code, and Pi's Edit tool writes back whateverreadFilereturns: the file would be truncated to zero.✅ Now guarded in code, and verified on a live cluster.
wrapCommandreportsCAP_STAGE_FAILEDwhen the cap orbase64stage fails, andpersistentExecInPodlatches on it, warns once, and routes every later op through the fallback transport — so a missinghead -cis a loud degradation rather than a zero-length file (7dd511a). The shipped image is also fine, checked directly insandbox-0:head -c 1 /dev/null→ exit 0printf abcdefghij | head -c 4→abcd(truncates correctly)stat -c %son a 12345-byte file →12345So neither path is reachable in this image — and if you build a different one, the code now tells you instead of corrupting files. The manual check remains useful as a fast pre-flight:
Behaviour changes an operator needs to know
bashwhose stdout crosses 8 MiB now fails. It previously reported success: the transport SIGKILLed the child and resolved withexitCode: null, and Pi's bash tool treats null as non-failing (bash.ts:397). It now returns 137 (128+9, the SIGKILL convention — accurate, since the command really was killed by signal 9), which routes through Pi's own failure path and so surfaces the failure with the streamed output tail attached. A verbose build or test run that crosses the cap will start reportingCommand exited with code 137.pi-fork'sread.tsreads the whole file before applyingoffset/limit, so the paging its own tool description advertises cannot reach past the cap either. Accepted deliberately: Pi clips Read output to 2000 lines / 50 KB regardless, so what is lost is a path returning bytes the model never saw, at the cost of harness memory and quadratic parse time.readFilenow throws naming the cap, the file size, and abash+sed -nrange read.How the third transport is capped
persistentExecInPodmultiplexes commands over one long-livedkubectl exec -- bashwith nonce-bracketed, base64-encoded frames. The cap is applied in the pod, via ahead -c <cap + 1>stage inwrapCommand's pipeline, rather than by counting bytes client-side:PIPESTATUS[0]still indexes the command; appending a stage does not shift index 0. A trip makes it 141 (SIGPIPE), which is ignored, because truncation is detected by length.FrameParser.push, which re-stringifies its buffer per chunk and so grows quadratically — a 20 MiB read allocated roughly 5.8 GB transiently.cap + 1bytes so the client can distinguish "landed exactly on the cap" (complete) from "exceeded it".A cap trip resolves with
truncated: truerather than routing through the inflightfail()path —fail()retries viadeps.fallback(the cappedKubectlTransport), which would have re-run the command and flooded twice before failing anyway.The battery now covers all three, and asserts mechanisms
producerStopped(): booleanbecomesproducerStop(): ProducerStop, a four-value mechanism each transport declares and the battery pins:GrpcRelayTransportremote-abortKubectlTransportlocal-killpersistentExecInPodproducer-side-capThe old boolean was set by each transport's own factory from its own local action, so all reported
trueand the asymmetry was invisible by construction — in the battery that is the stated evidence for the epic's transport-swappability claim. An enum rather than a "was it remote?" boolean, because a boolean would assertfalsefor both kubectl paths and so discard the coverage thatchild.killis actually called."none"is unclaimable, so deleting a stop fails loudly.persistentExecInPoddeclaresstreams: false(it is request/response over one multiplexed channel) and its streaming case is skipped, not silently omitted — quietly omitting a case for one implementation is how #185's asymmetry survived.Evidence
make typecheck— EXIT 0, 0 errors. Notemake typecheckcovers four packages while CI typechecks six (it addspackages/sandbox-relayandpackages/ibac-stub); both were run, both clean, and neither imports the seam.Makefile's narrower matrix is arguably its own bug, worth a separate issue.packages/k8s-sandbox— 123 passed / 10 skipped.harness— 226 passed / 3 skipped (needs Redis on 127.0.0.1:6379).child.killfromexec.ts's cap branch fails the kubectl cap case withexpected 'none' to be 'local-kill'; deletingclient.abortfromgrpc-relay-transport.ts's fails the gRPC case withexpected 'none' to be 'remote-abort'. Widening the persistent transport's trip threshold fails only thetruncatedassertion; widening its trim fails only thestdoutassertion. Reverted in each case.bash, not only against the hermetic fake that simulates it:framing.test.tspipes 5000 real bytes at cap 100 and asserts exactly 101 back, confirms a failing command still frames exit 42 through the added stage, and confirms the heredoc-stdin write path survives it.createPodGrepToolhad no tests at all before this branch; it now has them.One thing this PR does NOT establish
The gated live smoke was not run.It has now been run: 7/7 passed on a live Kind cluster, most recently at7dd511a(the current tip) — and re-run after every change that could affect it, including the#187merge (fbc265a) and the wire-protocol change in7dd511a. Working tree clean each time, so the runs exercised this branch's committed code — the harness side runs from TypeScript source under vitest, and the pod supplies onlybash/coreutils).Claim 6 is the one this PR adds: it writes a 9 MiB file in-pod, asserts the read fails naming the cap / the real
stat-measured size / thesed -nhint, asserts a 1 MiB file still reads cleanly, and assertsbashreports 137 rather than success — all against the real pod. So the pod-sidehead -c+ base64 pipeline is now proven to compose end-to-end throughkubectl exec, andstat -c %sis proven present.Reproduce with (the suite is self-seeding as of
cdb5fc2— no manual fixture step):M3_LIVE_SMOKE=1 KAGENTI_SANDBOX_POD=sandbox-0 KAGENTI_SANDBOX_NAMESPACE=default \ KAGENTI_SANDBOX_CONTEXT=kind-sh-knative \ pnpm -C packages/k8s-sandbox exec vitest run test/m3-live-smoke.test.tsFormatting was not applied, and could not be.
make fmtrunspnpm exec prettier --write ., which fails withERR_PNPM_RECURSIVE_EXEC_NO_PACKAGE— there is no rootpackage.json. Had it run it would have been destructive rather than a no-op:.prettierrcsetssingleQuote: truewhile the codebase is entirely double-quoted and.prettierignoredoes not exclude it, so it would rewrite hundreds of unrelated files.make lintseparately aborts inpre-commitwithInvalidConfigError: Type tag 'typescript' is not recognizedon every commit including the baseline..git/hooks/pre-commitis not installed in the working clone, and CI has no format check (ci.ymlruns Typecheck, Test,buf lint, Go;security-scans.ymlruns hadolint). Flagging it because a maintainer with hooks installed may see a large reformat on their next commit — that is pre-existing, not introduced here.Conflict note
PR #187 has merged and is integrated here (
fbc265a). It overlapped increatePodFindOps.glob; both changes are kept, withtruncatedchecked first, then the null exit code, then #187's!== 0 && !== 1guard. Taking this branch's side of the conflict would have silently dropped #187's!== 1tolerance and reintroduced the "no matches reads as an error" bug it fixed.The two compose, verified in the pod rather than on paper. #187 fixes a real defect this branch does not touch:
rg --files … | head -n <limit>makes the exec's statushead's, so a genuinergexit 2 is masked as 0. This branch's truncation handling keys ontruncated, never on the exit code, so it neither fixes nor hides that. #187'src=${PIPESTATUS[0]}; …guard also composes with the outerhead -cstage added here, because the guard sits insidewrapCommand's brace group and the outerPIPESTATUS[0]still resolves to that group as a whole.Assisted-By: Claude (Anthropic AI) [email protected]