Skip to content

fix(k8s-sandbox): make the output cap a seam-wide guarantee + explicit truncation contract - #188

Merged
pdettori merged 17 commits into
rossoctl:mainfrom
pdettori:feat/st6-seam-output-cap-truncation
Aug 31, 2026
Merged

pdettori merged 17 commits into
rossoctl:mainfrom
pdettori:feat/st6-seam-output-cap-truncation

Conversation

@pdettori

@pdettori pdettori commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

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.

⚠️ Read before exercising this on a cluster

The pod-side head -c stage runs on every command through the persistent channel, not only over-cap ones. If head -c were absent or rejected -c in the sandbox image, { cat f; } | head -c N | base64 yields empty stdout with exit 0 — cat writes into the pipe buffer and exits cleanly, while the dead head stage leaves base64 with nothing to read. readFile would then return an empty buffer with a success code, and Pi's Edit tool writes back whatever readFile returns: the file would be truncated to zero.

✅ Now guarded in code, and verified on a live cluster. wrapCommand reports CAP_STAGE_FAILED when the cap or base64 stage fails, and persistentExecInPod latches on it, warns once, and routes every later op through the fallback transport — so a missing head -c is a loud degradation rather than a zero-length file (7dd511a). The shipped image is also fine, checked directly in sandbox-0:

  • head -c 1 /dev/null → exit 0
  • printf abcdefghij | head -c 4 → abcd (truncates correctly)
  • stat -c %s on a 12345-byte file → 12345

So 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:

kubectl exec -n <ns> <sandbox-pod> -- head -c 1 /dev/null; echo $?   # expect 0

Behaviour changes an operator needs to know

  • A bash whose stdout crosses 8 MiB now fails. It previously reported success: the transport SIGKILLed the child and resolved with exitCode: 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 reporting Command exited with code 137.
  • A file above 8 MiB is now unreadable through Read/Edit — not truncated, unreadable. pi-fork's read.ts reads the whole file before applying offset/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. readFile now throws naming the cap, the file size, and a bash+sed -n range read.

How the third transport is capped

persistentExecInPod multiplexes commands over one long-lived kubectl exec -- bash with nonce-bracketed, base64-encoded frames. The cap is applied in the pod, via a head -c <cap + 1> stage in wrapCommand's pipeline, rather than by counting bytes client-side:

  • It caps raw bytes before base64 inflation, so the trip point matches the per-call transports exactly. A client-side count would have capped content at cap × 3/4 — a weaker form of the same distinguishability persistentExecInPod is an uncapped third SandboxTransport, and it serves the file-reading tools #180 objects to.
  • 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.
  • It bounds FrameParser.push, which re-stringifies its buffer per chunk and so grows quadratically — a 20 MiB read allocated roughly 5.8 GB transiently.
  • The pod returns cap + 1 bytes so the client can distinguish "landed exactly on the cap" (complete) from "exceeded it".

A cap trip resolves with truncated: true rather than routing through the inflight fail() path — fail() retries via deps.fallback (the capped KubectlTransport), which would have re-run the command and flooded twice before failing anyway.

The battery now covers all three, and asserts mechanisms

producerStopped(): boolean becomes producerStop(): ProducerStop, a four-value mechanism each transport declares and the battery pins:

Transport Mechanism What it guarantees
GrpcRelayTransport remote-abort the worker kills the process group
KubectlTransport local-kill in-pod process stops on EPIPE, if at all
persistentExecInPod producer-side-cap raw output cannot exceed the cap at the source

The old boolean was set by each transport's own factory from its own local action, so all reported true and 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 assert false for both kubectl paths and so discard the coverage that child.kill is actually called. "none" is unclaimable, so deleting a stop fails loudly.

persistentExecInPod declares streams: 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. Note make typecheck covers four packages while CI typechecks six (it adds packages/sandbox-relay and packages/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).
  • Mutation-verified, not assumed. Deleting child.kill from exec.ts's cap branch fails the kubectl cap case with expected 'none' to be 'local-kill'; deleting client.abort from grpc-relay-transport.ts's fails the gRPC case with expected 'none' to be 'remote-abort'. Widening the persistent transport's trip threshold fails only the truncated assertion; widening its trim fails only the stdout assertion. Reverted in each case.
  • The pod-side pipeline is proved against a real bash, not only against the hermetic fake that simulates it: framing.test.ts pipes 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.
  • createPodGrepTool had no tests at all before this branch; it now has them.

One thing this PR does NOT establish

  1. The gated live smoke was not run. It has now been run: 7/7 passed on a live Kind cluster, most recently at 7dd511a (the current tip) — and re-run after every change that could affect it, including the #187 merge (fbc265a) and the wire-protocol change in 7dd511a. 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 only bash/coreutils).

    ✓ Claim 1  persistent process serves a burst of >=3 ops
    ✓ Claim 2  write/edit round-trips multi-line/special content
    ✓ Claim 3  env injection reaches the bash op
    ✓ Claim 4  glob honours ignore-list; gitignored dist/ pruned
    ✓ Claim 4b positive -g overrides a file-level gitignore
    ✓ Claim 5  close is non-throwing
    ✓ Claim 6  a file over the output cap fails the read loudly, with a usable message
    Test Files 1 passed (1) · Tests 7 passed (7)
    

    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 / the sed -n hint, asserts a 1 MiB file still reads cleanly, and asserts bash reports 137 rather than success — all against the real pod. So the pod-side head -c + base64 pipeline is now proven to compose end-to-end through kubectl exec, and stat -c %s is 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.ts
  2. Formatting was not applied, and could not be. make fmt runs pnpm exec prettier --write ., which fails with ERR_PNPM_RECURSIVE_EXEC_NO_PACKAGE — there is no root package.json. Had it run it would have been destructive rather than a no-op: .prettierrc sets singleQuote: true while the codebase is entirely double-quoted and .prettierignore does not exclude it, so it would rewrite hundreds of unrelated files. make lint separately aborts in pre-commit with InvalidConfigError: Type tag 'typescript' is not recognized on every commit including the baseline. .git/hooks/pre-commit is not installed in the working clone, and CI has no format check (ci.yml runs Typecheck, Test, buf lint, Go; security-scans.yml runs 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 in createPodFindOps.glob; both changes are kept, with truncated checked first, then the null exit code, then #187's !== 0 && !== 1 guard. Taking this branch's side of the conflict would have silently dropped #187's !== 1 tolerance 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 status head's, so a genuine rg exit 2 is masked as 0. This branch's truncation handling keys on truncated, never on the exit code, so it neither fixes nor hides that. #187's rc=${PIPESTATUS[0]}; … guard also composes with the outer head -c stage added here, because the guard sits inside wrapCommand's brace group and the outer PIPESTATUS[0] still resolves to that group as a whole.

Assisted-By: Claude (Anthropic AI) [email protected]

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]>
@pdettori

Copy link
Copy Markdown
Member Author

Follow-ups from this branch's review, filed rather than folded in — each is out of ST6's declared scope (docs/specs/2026-08-30-seam-output-cap-truncation-design.md §2):

@pdettori

Copy link
Copy Markdown
Member Author

Live gate now run — 7/7 on a Kind cluster

The PR body has been updated: the live smoke is no longer unexecuted.

Run at b074e80 (this PR's tip) with a clean working tree, so it exercised this branch's committed code — the harness side runs from TypeScript source under vitest, and the pod supplies only bash/coreutils, so no image rebuild is involved.

✓ Claim 1 · ✓ Claim 2 · ✓ Claim 3 · ✓ Claim 4 · ✓ Claim 4b · ✓ Claim 5 · ✓ Claim 6
Test Files 1 passed (1) · Tests 7 passed (7)

The deploy-blocking risk flagged earlier is closed for this image. The concern was that the head -c stage is unconditional on every persistent-channel command, so a missing head -c would make { cat f; } | head -c N | base64 return empty stdout with exit 0 — which readFile would hand back as a successful empty read, and Pi's Edit would write back, truncating the file to zero. Verified directly in sandbox-0:

  • head -c 1 /dev/null → exit 0
  • printf abcdefghij | head -c 4 → abcd
  • stat -c %s on a 12345-byte file → 12345

So both the empty-read path and the missing-stat degradation are unreachable here. The one-line check remains in the PR body for anyone building a different sandbox image.

Note for whoever runs this suite next

My 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 packages/k8s-sandbox/SMOKE.md §96-102 (a .gitignore plus seeded .ts files), which the tests do not create themselves. After a cluster restart that content is gone, and the symptoms are misleading — Read failed in pod (cat exited 1): /head/.gitignore and glob result: [], both of which look like regressions in the paths this PR touches. Seeding the documented fixtures and changing nothing else took it to 7/7.

Worth folding that seeding into the suite (or a beforeAll) so the next person does not spend the same time attributing it — I have not done so here, to keep this PR scoped.

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]>
@pdettori

Copy link
Copy Markdown
Member Author

Live-smoke fixtures now seeded by the suite (cdb5fc2)

Folded the manual SMOKE.md seeding step into a beforeAll, so the gated suite is self-contained.

Verified the way that actually proves it: deleted every fixture from the pod (/workspace left holding nothing but an unrelated stale dir), then ran the gate with no manual seeding — 7/7 passed. Still 7 skipped with M3_LIVE_SMOKE unset, so CI never runs it and never touches a cluster.

Why this was worth doing rather than leaving as a documented step: the failure mode of skipping it is misattributing. Claims 1/4/5 fail with Read failed in pod (cat exited 1): /head/.gitignore and glob result: [] — both of which look like regressions in the read and glob paths this PR changes. It cost real time to attribute during this branch's own live run (4/7 then 7/7, with no code change between), and a pod restart is enough to trigger it. Claims 2 and 4b were always fine because they build their own fixtures.

The seeding is idempotent by construction (mkdir -p, truncating redirects), so re-runs and a partly-seeded workspace both work, and it writes under /workspace because the pod runs as an arbitrary non-root UID and /tmp is not writable.

SMOKE.md's step 2 is marked no-longer-needed, keeping the commands as a record of what the suite seeds.

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]>
@pdettori

Copy link
Copy Markdown
Member Author

Rebased onto #187, which merged mid-review (fbc265a) — back to MERGEABLE

#187 landed on main while this was in review, touching the same createPodFindOps.glob. My earlier note said the two compose; they do, and both are kept.

The resolution matters, because the obvious one is wrong. Taking this branch's side of the conflict would have silently dropped #187's r.exitCode !== 1 tolerance and reintroduced the "no matches reads as an error" bug it exists to fix. Kept:

  • fix: propagate ripgrep failures from glob #187's shell guard verbatim — rc=${PIPESTATUS[0]}; [ "$rc" = 0 ] || [ "$rc" = 1 ] || [ "$rc" = 141 ] || exit "$rc" — so rg's status survives the pipe to head. That is about the search failing.
  • This branch's truncated check, first — a cap trip is a property of the seam and can occur while rg is perfectly happy, so reporting it as "rg exited N" blames the wrong component.

Order is truncated → exitCode === null → !== 0 && !== 1.

Verified the composition in the pod rather than on paper. glob runs over the persistent channel, so the merged command is #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 on the merged tree: 7/7, with Claim 4 returning ["top.ts","src/keep.ts"] — the exact result SMOKE.md documents.

make typecheck EXIT 0 · k8s-sandbox 129 passed / 11 skipped · harness 226 passed / 3 skipped.

@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.

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 exec site with unbounded output checks truncated: readFile (and so createPodEditOps.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.ts frames exit 42 as 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 keeps glob's inner exit "$rc" confined to a pipeline subshell, so the merged #187 guard cannot kill the session.
  • Transport wiring is consistent with the exit-137 rationale. bash and grep are on streamTransport (KubectlTransport), which does stream — so Pi's failure path genuinely has a tail to append. streams: false only affects the persistent channel, which serves Read/Write/Edit/Ls/Find.
  • The battery is not self-fulfilling. The producerStop enum, the exact-cap non-trip case, and the throwing fallback (reaching it means a cap trip was mistaken for a dead channel) each pin a distinct mechanism.
  • #187 is merged and integrated. fbc265a resolved the glob overlap correctly — the PIPESTATUS guard 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.

  1. The live-smoke section says the 7/7 run was at b074e80, "the tip of this PR." The tip is now fbc265a, two commits later, including an upstream merge that touched operations.ts:glob. The smoke has not been re-run against the merged code.
  2. The reproduce note tells the reader to seed fixtures per SMOKE.md §96-102 first, but cdb5fc2 made 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}`;

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 — 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.

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 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.

Comment thread packages/k8s-sandbox/src/operations.ts Outdated
// 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}.`,

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.

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.

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 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]>
@pdettori

Copy link
Copy Markdown
Member Author

Review addressed (7dd511a)

The silent failure is now guarded in code, not just documented — details in the framing.ts thread. Short version: reproduced both failure modes against real bash (head missing → stage status 127; head rejecting -c → 1; both yielding empty stdout with the command's own exit 0), then made wrapCommand report CAP_STAGE_FAILED when the cap or base64 stage fails. persistentExecInPod latches on it, warns once with the exact check to run, and routes every later op through the fallback transport — degraded but correct, rather than a zero-length file.

I used the stage-status check rather than the suggested spawn-time probe, and explained the tradeoff in the thread — the probe would shift the nonce sequence most of persistent-exec.test.ts asserts on and force the conformance fake to special-case it, while the stage check costs no extra exec, fires at the point of harm, and also covers a broken base64. Say the word if you'd prefer the probe.

readdir's cap error now offers a remedy, matching the other three.

The three body-accuracy points — all correct, all fixed

  1. The live-run section cited b074e80; it now cites 7dd511a and records that the gate was re-run after every change that could affect it, including the #187 merge and this protocol change. (Worth noting the smoke was re-run on the merged tree — 7/7 at fbc265a, in an earlier comment — the body just hadn't caught up. Your read of the body was right.)
  2. The reproduce note no longer points at SMOKE.md §96-102; the suite is self-seeding as of cdb5fc2.
  3. The conflict note now says fix: propagate ripgrep failures from glob #187 has merged and is integrated, with the resolution described.

Current state

make 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.

@pdettori
pdettori merged commit 25f6840 into rossoctl:main Aug 31, 2026
10 checks passed
@pdettori
pdettori deleted the feat/st6-seam-output-cap-truncation branch August 31, 2026 15:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant