Repository navigation
feat: per-turn artifacts, a bounded status read, and seven-day retention (#390) - #840
Conversation
…ion-delete walk Five findings from the review of rossoctl#840, each with a case: 1. `deleteSessionTurns` spent 3-4 sequential Redis round trips per turn across the WHOLE retention window -- ~20k calls for a session that ran 5k turns in a week, seconds of a single-threaded server inside one HTTP request, where before the index the walk was bounded by the 50-turn open quota. Two passes now: the owner set stays per-turn (its members span every session of the subject, and an open turn holds a quota slot and an idempotency claim only its own record can release, so the record must be read), and the indexed remainder -- this session's by construction, already terminal, so `toTerminal` freed both -- is a bulk `del` of 500 keys per call with no per-turn read at all. 2. The same method's comment promised "a retried DELETE re-walks whatever the first attempt did not reach". It cannot: `deleteSession` tombstones the session through `cascadeDelete` BEFORE calling this, so a second DELETE stops in `assertOwner` with `session_not_found`. Said plainly instead, with what a cut walk actually leaves (the index's own TTL), which is also why 1 is worth doing. 3. The projection called `verdict` and `gate` "bounded by construction". They are not: `verdict.reason` and the gate's `summary`/`proposed_action` are model-written and capped nowhere (`validateVerdict` checks the shape, not the length), so a `done` turn's body was as unbounded as the patch this projection exists to remove -- on every poll. Clipped to the same `MOCA_TURN_SUMMARY_BYTES`; clipped rather than moved out, because unlike the patch there is no artifact route to fetch them from. 4. `MOCA_TURN_SUMMARY_BYTES=0` is documented as "no summary at all" and produced `summary: "…[truncated]"`. The key is now omitted. 5. The artifact route hashed the body on every fetch -- up to 8 MiB of sha256 on the event loop per request -- although the capture's digest already covers exactly those bytes in all three branches, and the status read advertises it as `artifacts[].sha256`. Reused, so the ETag and that field cannot disagree; still hashed for a record that recorded no digest. Tests: the 251-turn sweep crosses the DEL-chunk boundary (one full chunk plus a remainder) against both the fake and real Redis; the projection's verdict/gate clip asserts the full strings appear nowhere in the body, and that a null verdict stays null; the ETag test asserts one digest across the two routes. packages/control-plane 1901 passed, packages/server 582 passed, `make typecheck` and `SKIP=hadolint-docker make lint` clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Summary
This PR does three things:
- Async results are kept for 7 days by default.
- A session delete now also removes its finished turns, through a new per-session index walked in chunks of 500.
- The async status read returns a bounded projection (
summary,artifacts[]), and the patch moves to the newGET …/turns/{turnId}/artifacts/{kind}.
The contract bump is control plane 1.25.0 / harness 1.4.0. The artifact route is owner- and session-checked (assertOwner, then turnOnSession) before any read, and kind is matched literally. ROUTES, openapi, CHANGELOG and change-policy agree. The deploy-scripts failure at 749dfbb (smoke.test.sh's mock still served result.text after smoke.sh moved to .result.summary) is fixed by eb760ad. I have five suggestions and two nits; none block.
Author: cwiklik (MEMBER, maintainer)
Areas reviewed: TypeScript (control-plane, harness, mocactl), Shell (k8s smoke + tests), API docs, Tests
Agent/IDE config (.claude/.vscode): none
Commits: 8 commits, all signed-off: yes
CI status: red deploy-scripts/deploy-scripts-bash32 at 749dfbb, which eb760ad fixes; checks at eb760ad were still pending when I drafted this
| // of them `lost` before the reaper's record write, or a crash between the two) cannot leave an | ||
| // immortal key behind; `toTerminal` re-arms it from the same sum. | ||
| await this.guard(() => | ||
| this.redis.zAdd(this.sessionKey(rec.sessionId), { score: rec.createdAt, value: rec.turnId }), |
There was a problem hiding this comment.
suggestion: The per-session index only grows. create ZADDs every turn, and both create and toTerminal (:432) push the key's EXPIRE out again. Nothing trims members whose records have already expired, so a long-lived, busy session's key never expires and keeps one id per turn indefinitely. deleteSessionTurns then zRanges all of it and DELs 2×N mostly-gone keys, which undoes the point of the 500-chunking. The score is createdAt, so a ZREMRANGEBYSCORE key -inf (now - (resultTtl+margin)*1000) here or in toTerminal would bound the set to the retention window. That's the same pattern as bundle-budget.ts:117. An open turn older than the window is still reached by the owner-set pass, so trimming it from this index is safe.
There was a problem hiding this comment.
Fixed in 1cdea85 — with the second half your suggestion needs to be safe.
create now trims by score (ZREMRANGEBYSCORE <key> -inf <createdAt − (resultTtl+margin)*1000>), the bundle-budget.ts:117 pattern. But trimming on createdAt alone would delete a live turn: one submitted two windows ago and finished a minute ago has its record and result TTLs starting at the terminal transition, not at submission. So toTerminal now re-scores the member to now first. "Past the window" then means "its keys are already gone", which is what makes the sweep a no-op on anything reachable. And as you say, an open turn older than the window is still reached by the owner-set pass, which never consults this index.
Contract test covers both halves together (fake + real Redis, via a new indexedTurns hook): it fails if either the trim or the re-score is missing.
| // PROJECTED, not the stored record (#390): the patch and the assistant text are fetched as | ||
| // artifacts, so polling this route costs the same whether the leaf produced four lines or | ||
| // four megabytes. | ||
| ...(result ? { result: projectLeafResult(result, deps.config.turnSummaryBytes) } : {}), |
There was a problem hiding this comment.
suggestion: The projection bounds the response, but every poll still GETs the full leaf:result:<sid>:<turnId> record and JSON.parses it (readLeafResult). That means a 4-8 MiB patch is still read and parsed on the single event loop on each poll. The claim that "polling costs the same whether the leaf produced four lines or four megabytes" (here and in the PR body) overstates what this does. Either soften it or note it as a known limit in §4.4. Storing the descriptor separately would be a follow-up.
There was a problem hiding this comment.
You are right, and the claim is now gone. The comment says the response is bounded and the read is not: readLeafResult still GETs the whole value and JSON.parses it, so the bytes still move from Redis and parse on the event loop once per poll — the projection only keeps them off the wire.
Recorded in spec §4.4 as a known limit rather than left implied, including what closing it costs (the writer splits the record into a small status value beside the bytes — a stored-format change plus a migration for every result written before it) and the trigger to do it: a poll rate where that parse shows up in the control plane's event-loop lag, not a patch size.
|
|
||
| The body is the diff exactly as the leaf produced it -- never truncated, and byte-exact for a | ||
| diff that is not valid UTF-8 (the worker stores such a capture base64 and this route decodes | ||
| it). `ETag` is a sha256 of the bytes served, so a client can skip a re-fetch; it is the |
There was a problem hiding this comment.
suggestion: This says the ETag lets a client skip a re-fetch, but getTurnArtifact (turn-handlers.ts:~252) never reads If-None-Match and always returns 200 with the full body. Either answer 304 on a match or drop the sentence. The ETag also comes in two formats: "sha256:<hex>" from the capture's digest, and a bare "<hex>" when the handler hashes the bytes itself. Prefixing the fallback with sha256: would make it uniform for clients comparing against artifacts[].sha256.
There was a problem hiding this comment.
Both halves taken, the second as the fix and the first as the honest answer.
The format is now uniform: the fallback is "sha256:<hex>" too, so a client comparing a stored ETag against artifacts[].sha256 matches whether or not the record carried a capture digest. Previously the two grammars could never compare equal, which made the fallback ETag useless for exactly the case it existed for.
The re-fetch sentence is dropped rather than implemented. 304 is not a one-liner here: RequestCtx (handlers.ts:310) exposes no request headers at all, so honouring If-None-Match means plumbing a header surface through the router for one route. openapi, the changelog and the response header description now say the ETag is for comparison and that the route always serves the full body.
| return [ | ||
| `set -eu`, | ||
| `LEAF=${sq(LEAF)}`, | ||
| `git -C "$LEAF" rev-parse HEAD`, |
There was a problem hiding this comment.
suggestion: rev-parse HEAD runs after the agent's turn, so it is the converge commit only if the model never ran git commit in the leaf worktree. If it did, workspace.baseline becomes a sandbox-local commit no caller has, and diff --cached leaves out the committed changes. The same applies to buildSwebenchDiffScript (swebench-setup.ts:56). Consider recording the pinned commit at converge time (COMMIT=$(git rev-parse FETCH_HEAD) in buildConvergeScript) and diffing against it, as buildPatchCaptureScript does with SEED_BASELINE. At minimum, document the assumption.
There was a problem hiding this comment.
Fixed properly, not documented away — this one is a silent wrong answer, not just a bad baseline. An agent that ran git commit moved HEAD, so diff --cached HEAD dropped the committed work and named a sandbox-local sha as the baseline.
buildConvergeScript writes the commit it pinned to <leaf>.base (a sibling of the worktree, so it cannot be staged), and buildDiffCaptureScript reads BASE=$(cat "$LEAF.base" 2>/dev/null || git -C "$LEAF" rev-parse HEAD) and diffs against that. buildCleanupScript removes the file with the worktree, so nothing leaks onto the pooled sandbox. buildSwebenchDiffScript now takes the dataset's base_commit — it was already in scope, so no file is needed there.
Proven end to end over a real file:// repo in converge.test.ts: commit in the leaf, assert HEAD moved, then assert the captured baseline is still the pinned commit and the patch contains the committed change.
| patch?: string; | ||
| text?: string; | ||
| summary?: string; | ||
| artifacts?: { kind: string; bytes: number; sha256?: string }[]; |
There was a problem hiding this comment.
suggestion: TurnStatus.result now advertises artifacts, but mocactl has no client call for GET …/artifacts/{kind}, so a CLI user can no longer reach an async turn's patch or text. Also, packages/mocactl/test/control-plane.test.ts:290/294 still uses { status: 'solved', patch: 'd' }, a shape the server no longer returns. Please move that fixture to the summary/artifacts shape, and add a getTurnArtifact client method here or as a follow-up.
There was a problem hiding this comment.
Fixture fixed; the client method is a deliberate follow-up, with a reason.
control-plane.test.ts now uses the bounded body the server actually sends (status, summary, artifacts: [{kind, bytes, sha256}], workspace). You are right that the old one was worse than stale: asserting pass-through of {patch: 'd'} proved the client copied a field nothing returns, so it would have stayed green through this narrowing.
On getTurnArtifact: getTurn itself has no caller anywhere in packages/mocactl/src — it is client surface from #387 with no command behind it yet — so no CLI path regressed here, and a second never-called method adds surface without adding reach. It belongs with whatever command first displays an async turn, which is where the question of how to present a patch (write it to a file? pipe it to git apply?) actually gets answered. Happy to file that as the follow-up issue alongside the frame-level transcript one if you'd rather have it tracked now.
| export function clip(text: string, maxBytes: number): string { | ||
| const buf = Buffer.from(text, 'utf8'); | ||
| if (buf.byteLength <= maxBytes) return text; | ||
| return buf.subarray(0, maxBytes).toString('utf8') + '…[truncated]'; |
There was a problem hiding this comment.
nit: clip returns maxBytes of content plus '…[truncated]' (14 more bytes), so the output isn't actually "clipped to MOCA_TURN_SUMMARY_BYTES" as configuration.md, the CHANGELOG and openapi say. At a cap of 0, verdict.reason and the gate fields become just the marker. Either subtract the marker from the budget or reword the docs to "content capped at N bytes, plus a marker".
There was a problem hiding this comment.
Both parts fixed, each the way it should be.
The docs were wrong, so they are reworded rather than the budget shrunk: the cap bounds the content, and a clipped string is MOCA_TURN_SUMMARY_BYTES plus the 14-byte marker. Said that way in configuration.md, the API changelog, openapi (result and summary) and spec §4.4. Subtracting the marker from the budget would make the knob mean "N minus 14 of your content", which is harder to reason about and would silently change what an operator who set 2048 gets.
The cap-0 case was a real bug, not a wording problem: 0 is how an operator asks for no model prose, and reason: '…[truncated]' obeyed the cap in bytes while ignoring the request. clipFields now drops those fields at 0, exactly as summary was already omitted. The shaped siblings stay (item_id, verdict, gateId) — a client branches on verdict, and the knob must not change the contract. Test asserts verdict is {item_id, verdict}, gate is {gateId}, and the whole serialized body contains no truncated at all.
| return sessionTurnsKey(this.tag(sessionId)); | ||
| } | ||
|
|
||
| /** A terminal record's lifetime, and the session index's: one sum, one place (§5.1). */ |
There was a problem hiding this comment.
nit: The TurnStoreOptions.resultTtlSeconds doc comment at :18 still says (86400 default). It should be 604800, to match resultTtlSeconds().
There was a problem hiding this comment.
Fixed in 1cdea85 — the comment now names LEAF_RESULT_TTL_SECONDS and 604800, matching the default C1 raised it to.
clawgenti
left a comment
There was a problem hiding this comment.
Review: per-turn artifacts, bounded status read, seven-day retention (#390)
Reviewed across the control-plane turn store/result projection, the harness patch-capture path, the new artifact route, and the deploy/OpenAPI/doc updates. The design holds together well: the read-time-only projection (no second writer, no migration), the session index armed off the same TTL sum as the record it must outlive, and the bulk-DEL rewrite of the session-delete walk each show the failure modes were thought through, and the test coverage (turn-store contract against both fakes, ETag cross-route assertion, 251-turn DEL-chunk sweep) matches the claims in the PR body.
Must fix
deploy-scriptsanddeploy-scripts-bash32are failing on this head (run 43992010010, "Run deploy shell tests" step) — both passed on the previous commit04f0b096and pass on currentmain, and the only deploy change since isdeploy/k8s/smoke.sh. I could not pull the CI logs from my environment (egress to the Actions log receiver times out) and my localmake test-deployrun failsresearch-smoke.test.shandjanitor.test.shon both this head andmain, so it cannot discriminate. Worth a look at the failing suite names in the logs before merge.
The rest are suggestions/nits
- The
patchSizemeasurement on a solve leaf (Buffer.byteLength(raw.patch)) is O(patch size) on every status poll. It only applies to records without a descriptor, so it's minor — but a polled route scanning 4 MiB per call is worth remembering if solve leaves ever carry large patches withoutworkspace. smoke.shkeeps thejq … 2>/dev/null || trueswallow (pre-existing style, retained in the edited line) — a malformed status body degrades to the grep-failure message rather than a clear parse error.
Author: cwiklik (CONTRIBUTOR — returning external, elevated scrutiny)
Areas reviewed: TypeScript (control-plane, harness), Shell (deploy), YAML (OpenAPI), Docs
Agent/IDE config (.claude/.vscode): none
Commits: 8, all signed off: yes
CI status: failing (deploy-scripts, deploy-scripts-bash32); all other checks pass
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| jq -r '.result.summary // empty' 2>/dev/null || true)" | ||
| grep -q async-leaf-ok <<<"$text" || | ||
| bad="$bad (${async_tids[0]} returned no tool output: '${text:0:200}')" | ||
| fi |
There was a problem hiding this comment.
must-fix — deploy-scripts and deploy-scripts-bash32 both fail on this head (passed on 04f0b096, pass on main; the only deploy delta between those commits is this file's .result.text → .result.summary change). I couldn't fetch the CI logs (egress blocked from my environment) and deploy/k8s/tests/smoke.test.sh passes locally on this head, so I can't name the failing suite. Suggested fix: check the "Run deploy shell tests" step output in run 43992010010 — if it's the two suites that are environmentally flaky, a re-run may clear it; otherwise this blocks merge.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
There was a problem hiding this comment.
resolved by eb760ad3 — the follow-up commit "fix(k8s): the smoke's own mock still served the removed field" landed while this review was being drafted, and both deploy-scripts and deploy-scripts-bash32 are green on that head (17/17 checks passing). No action needed; leaving this thread for the record since the failure was real on 749dfbbb.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
| const stat = obj(ws?.diffstat); | ||
| if (stat) { | ||
| const n = (v: unknown) => (typeof v === 'number' ? v : 0); | ||
| return `${n(stat.files)} files, +${n(stat.insertions)} -${n(stat.deletions)}`; |
There was a problem hiding this comment.
suggestion — for a solve leaf with a bare patch string, patchSize calls Buffer.byteLength(text) on every status poll, which scans the whole multi-megabyte diff per call. The descriptor path avoids it; only descriptor-less records pay. If solve leaves always carry workspace post-1.4.0 this is moot, but a defensive patchBytes in the descriptor for the solve path too would make the poll O(1) in all cases.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
clawgenti
left a comment
There was a problem hiding this comment.
Correction to my review above (it was drafted against 749dfbbb and submitted just as eb760ad3 landed): the deploy-scripts / deploy-scripts-bash32 failure I flagged as must-fix is resolved by eb760ad3 ("the smoke's own mock still served the removed field") — both jobs are green on that head, 17/17 checks passing. The failure was real on 749dfbbb and its cause is confirmed by the fix commit: the smoke's own mock still served the removed .result.text field. Everything else in the review stands; no open must-fix items.
Generated by RepoMan github-pr-review@235a7f7 (https://github.com/rossoctl/agent-skills/blob/235a7f7620139ee3e4ab0872b8439591fe52e8c1/skills/github-pr-review/SKILL.md).
Seven review comments on rossoctl#840, each with the smallest change that closes it. 1. The per-session turn index only grew (turn-store.ts). Every `create` re-armed the key's expiry, so a session submitting turns for a year held a year of ids -- all but the last week naming keys Redis had already expired -- and `deleteSessionTurns` enumerated and DEL'd every one, undoing the point of the 500-chunking. `create` now trims by score (`ZREMRANGEBYSCORE -inf <createdAt - window>`), the sweep `bundle-budget.ts` already uses. What makes that safe is a second change: `toTerminal` re-scores the member to the moment the turn finished, which is when the record's and result's own TTLs start -- so "past the window" means "its keys are gone", not "it was submitted long ago". A turn that outlived the window while still open is reached by the owner-set pass, which never consults this index. `CpRedisLike` gains the one command. 2. The projection bounds the RESPONSE, not the read: `readLeafResult` still GETs and JSON.parses the whole stored record per poll. The comment that claimed otherwise is corrected, and spec section 4.4 records it as a known limit with the trigger for closing it (event-loop lag, not patch size) rather than pretending it is closed. 3. The artifact ETag came in two grammars -- `sha256:<hex>` from the capture and bare hex when the handler hashed the bytes itself -- so a client comparing against `artifacts[].sha256` could never match the fallback. Now always `sha256:<hex>`. The openapi sentence claiming the ETag saves a re-fetch is dropped: the route does not read `If-None-Match`. Answering 304 is not a one-liner here -- `RequestCtx` exposes no request headers at all. 4. `rev-parse HEAD` ran AFTER the agent's turn, so an agent that ran `git commit` in its leaf worktree made `workspace.baseline` a sandbox-local sha no caller has, and `diff --cached` against it silently dropped the committed work. `buildConvergeScript` now writes the commit it pinned to `<leaf>.base`, and the capture diffs against that file with HEAD only as a fallback (cleaned up with the worktree). `buildSwebenchDiffScript` takes the dataset's `base_commit`, which it already had. Proven end to end over a real file:// repo: an agent commit no longer corrupts baseline or patch. 5. `packages/mocactl/test/control-plane.test.ts` asserted pass-through of `{status:'solved', patch:'d'}`, a shape the server stopped returning in this PR -- so the fixture proved the client copied a field nothing sends. Moved to the bounded `summary`/`artifacts` shape. A `getTurnArtifact` client method is deliberately left as a follow-up: `getTurn` itself has no caller in mocactl's source, so nothing regressed and a second never-called method is not worth the surface. 6. `clip`'s cap bounds the CONTENT; the marker is 14 bytes on top of it. configuration.md, the API changelog, openapi and the spec now say so instead of promising a total length. And at a cap of 0 -- how an operator asks for no model prose -- `verdict.reason` and the gate's two lines are now DROPPED rather than replaced by a bare marker, which obeyed the cap in bytes while ignoring what was asked for. The shaped fields (`item_id`, `verdict`, `gateId`) stay, so the knob cannot change what a client branches on. 7. `TurnStoreOptions.resultTtlSeconds`'s doc comment still said 86400. Tests: a turn-store contract case for the trim and the re-score together (both halves bite -- it fails without either), against the fake and real Redis via a new `indexedTurns` hook; the cap-0 case for the verdict and gate strings; the converge end-to-end case above; the swebench script and capture assertions for the new signature; and the two ETag assertions for the uniform format. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
B5 (rossoctl#390) asks that "a result from 72 hours ago is still readable with the default settings", and the default was 86400 -- so the acceptance criterion failed by three days. An async turn is submitted precisely because nobody is waiting for it, so a day is the wrong unit: a Friday afternoon turn has to be readable on Monday. LEAF_RESULT_TTL_SECONDS now defaults to 604800. The strict parse is unchanged (the value goes straight to Redis as EX, so a typo must stop the boot, not every write), and this stays the ONE retention knob the design asked for (spec 5.1, ADR-0047): the terminal turn record's TTL is still this plus the one-hour margin, so record and result move together. Two intended side effects, since the same variable is read elsewhere: - sync /runs run markers (harness/src/run-lease.ts) and paused-gate records now live seven days too. For a paused gate that is the point -- a human gate waiting over a weekend no longer expires underneath its approver. - Redis holds roughly 7x the result bytes at steady state. Deployments that cannot afford that set the knob down; the configuration reference names it. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…on delete
`DELETE /v1/sessions/{id}` could not reach a FINISHED async turn. The result key
carries a turn id (`leaf:result:<sid>:<turnId>`), so only an enumeration of the
session's turns reaches it, and the one enumeration there was walked the owner's
OPEN-turn set -- which `toTerminal` removes from, to free the quota slot. So a
finished turn's record (envelope included) and its stored result outlived the
session that produced them and expired on their own clock. The async fan-out spec
§9.2 recorded this and left it to M2; rossoctl#390 raising the default to seven days makes
a week of a deleted session's bytes a different proposition from a day of them.
Fixes it with the index §9.2 prescribes: `sh:cp:session:<sid>:turns`, scored by
`createdAt`, written by `TurnStore.create`, walked by `deleteSessionTurns` and
UNIONED with the owner-set pass rather than replacing it -- a record written
before the index has no entry in it, and an open record carries no TTL at all, so
the owner set is the only thing that reaches one. A `SCAN MATCH` is ruled out
there: SCAN costs the whole keyspace per session delete, not the matches.
The index is armed at `resultTtlSeconds + ttlMarginSeconds` -- the terminal
record's own sum, §5.1's rule reused rather than a second retention number -- at
`create`, so a session whose turns all go `lost` leaves no immortal key, and
re-armed LAST at every terminal transition, so it never expires before a record it
would have to reach. It is deliberately not a `dataKeys` entry in `ownership.ts`:
`deleteSession` cascades before it calls `deleteSessionTurns`, so the index would
be gone before the walk could read it, with every test still green.
A record found only through the owner set and already absent is skipped unless the
index names it: the owner set spans a subject's sessions, so a missing record
there says nothing about whose turn it was.
The fake Redis `del` did not remove string keys, where a leaf result lives, so
every fake-backed assertion that a session delete removed a result would have
passed without the code deleting anything.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
…octl#390) A solve leaf returned a bare diff: no commit to apply it against and no sense of its size. Prompt-leaf turns already carried that descriptor (TurnWorkspace with baseline/patchSha256/patchBytes), so this brings the solve path up to it and adds a diffstat to both. - diffstat(patch) counts only in-hunk +/- lines, so +++/--- headers, "\ No newline at end of file" and a GIT binary patch payload never reach a counter; a binary-only diff reports its file count with zero lines. - captureTurnPatch puts diffstat in facts, so the refused-too-large branch carries it too - the case where it is the only description a caller gets. - buildDiffCaptureScript and buildSwebenchDiffScript print rev-parse HEAD before staging (not env.ref, which can be a branch a patch will not reapply against); splitBaseline takes the baseline off line 1 and the patch off the rest, restoring the trailing newline. - runSolveLeaf attaches a DESCRIPTOR only, and only when a baseline was captured: the patch bytes stay in result.patch, so the synchronous /runs and /runs/status bodies keep their shape and their size. Two intended, additive widenings in harness-openapi.yaml: diffstat on TurnWorkspace and workspace on LeafResult's solved branch (POST /runs echoes the whole result). RunStatus's solved branch is unchanged. Refs rossoctl#390 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
…an artifact (rossoctl#390) GET /v1/sessions/{id}/turns/{turnId} handed back the stored leaf result verbatim, so a 4 MiB patch rode every poll - the opposite of B5's "a large patch is fetched as an artifact, not inline". The status read now answers a PROJECTION: the turn's output (a solve leaf's patch, a prompt leaf's text) leaves the body, `summary` carries one clipped line about it (MOCA_TURN_SUMMARY_BYTES, default 2048 - bytes, like every other bound in this repo), `workspace` keeps the patch's descriptor (baseline, sha256, size, diffstat) and `artifacts` names what can be fetched. Everything else the leaf recorded passes through unchanged. GET /v1/sessions/{id}/turns/{turnId}/artifacts/{kind} serves those bytes whole, with `text/x-diff` and an ETag of the bytes served. One kind in M1, `patch`; a base64 capture (a diff that is not valid UTF-8) comes back byte-exact. Every absence is 404 with a message naming which - unknown kind, turn still running, no stored result, a capture refused for size - and `turn_not_found` is NOT reused, it belongs to the dequeue exchange. Projection is READ-TIME only: nothing new is stored, so there is no second writer, no migration, and a record written by an older worker projects the same way as a new one. assertOwner and the session check run before the kind is even read, which is what the authz enumeration sweep requires. server.ts gains a Buffer branch beside the string one; without it the router would JSON-encode the diff as {"type":"Buffer","data":[...]}. Refs rossoctl#390 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
B5 changed two documented contracts, so the version markers and the records
that explain them move together.
Control plane 1.26.0: the async turn status read is now a bounded projection
(summary, artifacts, workspace-without-bytes) and the output has its own route,
GET /v1/sessions/{id}/turns/{turnId}/artifacts/{kind}. Harness 1.4.0: TurnWorkspace
gained diffstat and LeafResult's solved branch gained workspace, both additive.
result.patch and result.text leaving the status body is a NARROWING of a response.
It is permitted because /v1 is Preview (docs/reference/maturity-and-lifecycle.md),
and Preview requires it be listed, which is what the 1.26.0 changelog section does.
The synchronous /v1/runs and /runs/status bodies are deliberately untouched —
nothing polls them, so nothing there needed narrowing.
ADR-0047 and the fan-out spec carry the amendment rather than being rewritten: the
ADR's status-read bullet says the read is bounded and why the projection is
read-time only (no second writer, no migration, an older worker's record projects
identically), and the spec's §4.4 response block shows the current shape beside the
artifact route. §9.2's retention note and §12's owed list already record what rossoctl#390
closed; §12 also names what is still owed - a frame-level transcript for an async
leaf, which needs plumbing ADR-0040's frame log does not have for run-leaf.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
…ion-delete walk Five findings from the review of rossoctl#840, each with a case: 1. `deleteSessionTurns` spent 3-4 sequential Redis round trips per turn across the WHOLE retention window -- ~20k calls for a session that ran 5k turns in a week, seconds of a single-threaded server inside one HTTP request, where before the index the walk was bounded by the 50-turn open quota. Two passes now: the owner set stays per-turn (its members span every session of the subject, and an open turn holds a quota slot and an idempotency claim only its own record can release, so the record must be read), and the indexed remainder -- this session's by construction, already terminal, so `toTerminal` freed both -- is a bulk `del` of 500 keys per call with no per-turn read at all. 2. The same method's comment promised "a retried DELETE re-walks whatever the first attempt did not reach". It cannot: `deleteSession` tombstones the session through `cascadeDelete` BEFORE calling this, so a second DELETE stops in `assertOwner` with `session_not_found`. Said plainly instead, with what a cut walk actually leaves (the index's own TTL), which is also why 1 is worth doing. 3. The projection called `verdict` and `gate` "bounded by construction". They are not: `verdict.reason` and the gate's `summary`/`proposed_action` are model-written and capped nowhere (`validateVerdict` checks the shape, not the length), so a `done` turn's body was as unbounded as the patch this projection exists to remove -- on every poll. Clipped to the same `MOCA_TURN_SUMMARY_BYTES`; clipped rather than moved out, because unlike the patch there is no artifact route to fetch them from. 4. `MOCA_TURN_SUMMARY_BYTES=0` is documented as "no summary at all" and produced `summary: "…[truncated]"`. The key is now omitted. 5. The artifact route hashed the body on every fetch -- up to 8 MiB of sha256 on the event loop per request -- although the capture's digest already covers exactly those bytes in all three branches, and the status read advertises it as `artifacts[].sha256`. Reused, so the ETag and that field cannot disagree; still hashed for a record that recorded no digest. Tests: the 251-turn sweep crosses the DEL-chunk boundary (one full chunk plus a remainder) against both the fake and real Redis; the projection's verdict/gate clip asserts the full strings appear nowhere in the body, and that a null verdict stays null; the ETag test asserts one digest across the two routes. packages/control-plane 1901 passed, packages/server 582 passed, `make typecheck` and `SKIP=hadolint-docker make lint` clean. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
`k8s-kind-e2e` failed on both heads of this branch, at the "Live smoke" step. Claim 13
("five async leaves ... all reach a result") read `.result.text` from
`GET /v1/sessions/{id}/turns/{turnId}` to prove the leaf's tool actually ran -- and C4
took `text` out of that body on purpose (spec §4.4, api CHANGELOG 1.25.0). So the read
answered empty, the `async-leaf-ok` grep missed, and the claim failed on a stack that was
working.
Reads `.result.summary` now, which for a prompt leaf IS that text, clipped at
`MOCA_TURN_SUMMARY_BYTES` (2048 by default) -- long enough for the one-line echo this
claim greps for.
The only consumer of the dropped fields outside the tests: `grep -rn 'result\.text\|result\.patch'`
over deploy/, scripts/, docs/ and packages/mocactl/src finds nothing else that reads them
(the remaining hits are the docs that record the removal). The smoke has no DELETE claim
and no TTL assertion, so C1 and C2 are not involved.
Not run locally: the kind e2e needs Docker, which is not up here. `shellcheck
deploy/k8s/smoke.sh` reports the same five pre-existing infos as before the edit.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
`deploy-scripts` and `deploy-scripts-bash32` went red on the previous commit: the curl mock
in `deploy/k8s/tests/smoke.test.sh` answers a turn read with `{result: {text: ...}}`, the
shape the status route stopped returning in 1.25.0 (rossoctl#390), so claim 13 read `.result.summary`
against a body that had none and the suite's "every leaf responded" case failed.
The mock now serves `summary`, which is what a real stack returns for a prompt leaf -- and
keeps the suite honest in the other direction too: a smoke.sh that went back to reading
`text` would fail here rather than in a cluster.
`bash deploy/k8s/tests/smoke.test.sh` green (the claim 13 cases, MOCK_ASYNC_TEXT included);
`k8s-kind-e2e` passed on the previous commit, so the live smoke's own read is confirmed.
Assisted-By: Claude (Anthropic AI) <[email protected]>
Signed-off-by: cwiklik <[email protected]>
Seven review comments on rossoctl#840, each with the smallest change that closes it. 1. The per-session turn index only grew (turn-store.ts). Every `create` re-armed the key's expiry, so a session submitting turns for a year held a year of ids -- all but the last week naming keys Redis had already expired -- and `deleteSessionTurns` enumerated and DEL'd every one, undoing the point of the 500-chunking. `create` now trims by score (`ZREMRANGEBYSCORE -inf <createdAt - window>`), the sweep `bundle-budget.ts` already uses. What makes that safe is a second change: `toTerminal` re-scores the member to the moment the turn finished, which is when the record's and result's own TTLs start -- so "past the window" means "its keys are gone", not "it was submitted long ago". A turn that outlived the window while still open is reached by the owner-set pass, which never consults this index. `CpRedisLike` gains the one command. 2. The projection bounds the RESPONSE, not the read: `readLeafResult` still GETs and JSON.parses the whole stored record per poll. The comment that claimed otherwise is corrected, and spec section 4.4 records it as a known limit with the trigger for closing it (event-loop lag, not patch size) rather than pretending it is closed. 3. The artifact ETag came in two grammars -- `sha256:<hex>` from the capture and bare hex when the handler hashed the bytes itself -- so a client comparing against `artifacts[].sha256` could never match the fallback. Now always `sha256:<hex>`. The openapi sentence claiming the ETag saves a re-fetch is dropped: the route does not read `If-None-Match`. Answering 304 is not a one-liner here -- `RequestCtx` exposes no request headers at all. 4. `rev-parse HEAD` ran AFTER the agent's turn, so an agent that ran `git commit` in its leaf worktree made `workspace.baseline` a sandbox-local sha no caller has, and `diff --cached` against it silently dropped the committed work. `buildConvergeScript` now writes the commit it pinned to `<leaf>.base`, and the capture diffs against that file with HEAD only as a fallback (cleaned up with the worktree). `buildSwebenchDiffScript` takes the dataset's `base_commit`, which it already had. Proven end to end over a real file:// repo: an agent commit no longer corrupts baseline or patch. 5. `packages/mocactl/test/control-plane.test.ts` asserted pass-through of `{status:'solved', patch:'d'}`, a shape the server stopped returning in this PR -- so the fixture proved the client copied a field nothing sends. Moved to the bounded `summary`/`artifacts` shape. A `getTurnArtifact` client method is deliberately left as a follow-up: `getTurn` itself has no caller in mocactl's source, so nothing regressed and a second never-called method is not worth the surface. 6. `clip`'s cap bounds the CONTENT; the marker is 14 bytes on top of it. configuration.md, the API changelog, openapi and the spec now say so instead of promising a total length. And at a cap of 0 -- how an operator asks for no model prose -- `verdict.reason` and the gate's two lines are now DROPPED rather than replaced by a bare marker, which obeyed the cap in bytes while ignoring what was asked for. The shaped fields (`item_id`, `verdict`, `gateId`) stay, so the knob cannot change what a client branches on. 7. `TurnStoreOptions.resultTtlSeconds`'s doc comment still said 86400. Tests: a turn-store contract case for the trim and the re-score together (both halves bite -- it fails without either), against the fake and real Redis via a new `indexedTurns` hook; the cap-0 case for the verdict and gate strings; the converge end-to-end case above; the swebench script and capture assertions for the new signature; and the two ETag assertions for the uniform format. Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
1cdea85 to
fd0a5aa
Compare
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Follow-up at fd0a5aa: the rebase onto main 1aa8dd6 resolves the version collision. The control plane is now 1.26.0 above main's 1.25.0 (idle lifetimes) in openapi.yaml, CHANGELOG.md, change-policy.md (which keeps the idle-lifetime entry) and the p6 spec. Harness 1.4.0 is unchanged. Range-diff shows the rest of the slice unchanged, so the earlier items stay closed. One leftover 1.25.0 reference is noted inline.
| # / MOCK_ASYNC_ATTEMPTS (claim 14) set that final state, its result text and the delivery it finished | ||
| # on. Everything else is a refused connection. | ||
| # / MOCK_ASYNC_ATTEMPTS (claim 14) set that final state, its result summary and the delivery it | ||
| # finished on. `summary`, not `text`: the status read stopped inlining the output in 1.25.0 (#390), |
`mocactl follow-up SESSIONID "prompt"` is #381's last unbuilt command: a second turn on a finished subagent's session, which keeps the first turn's context, so `get` the result, read it, and ask for the next thing without paying for the first turn again. The result is copied out before the turn is dispatched. The sync path keeps one result record per session and overwrites it unconditionally, so the copy has to precede the dispatch or it races it; `cmdGet`'s write block is now a shared `writeResultFiles` and both commands produce the same three files. An async row is copied nothing: each of its turns keeps its own artifacts for seven days (#840). A record that aged out of its 24 hours is not a refusal, but a result that could not be *read* is, so a transport fault never costs the result it promised to preserve. The dispatch mirrors the row's backend, as a gate decision does: a row with a `turnId` submits another turn, a row without one forks the same detached worker `spawn` uses. The turn is always a prompt, including on a `solve` row -- the session holds the repository workspace already (#461) -- and it inherits the subagent's bundle and workload. The ledger row is replaced by a fresh `record` line rather than updated: `foldLines` keeps the later one, and an update line cannot carry an envelope. That is what makes a gate on the follow-up answerable, since `approve` re-sends the row's envelope and it has to hold the follow-up's text, not the first turn's. Tag and label carry over -- one subagent, one turn on. Refused while the subagent is `running` (wait with `get --wait`) or parked at a gate: a follow-up prompt is not an answer to a gate, and dispatching one would leave it pending for good. Tests: 14 new (12 on the command, 2 on the CLI surface). 189 green across the 7 suites this touches; `make typecheck` and `make check-links` clean. Refs #381 Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: cwiklik <[email protected]>
Closes #390 (B5 of epic #378).
Two of B5's five scope items already held when this started —
TURN_STATEScarriesrunningandlost(#387), and results are keyed per turn (#388) — so this branch is the other three, each acommit of its own.
What changed
Seven-day result retention (
0c0bf4b1→LEAF_RESULT_TTL_SECONDSdefault86400→604800).B5's own acceptance criterion is "a 72 h-old result is readable with the default settings", which a
24 h default cannot satisfy. It is deliberately the ONE knob: the terminal turn record's TTL derives
from it (
+ TURN_RECORD_TTL_MARGIN_SECONDS), as spec §5.1 and ADR-0047 both say it should. Twointended side effects, stated in the commit: sync run markers and paused-gate records also live
seven days, and Redis holds ~7× the result bytes at steady state.
A session delete now reaches a finished turn's bytes (
cb885030). A 7-day window on a deletedsession's results is a different proposition from a 1-day one, so this closes the limit spec §9.2
recorded and deferred:
deleteSessionTurnswalked the owner's open-turn set only, so a finishedturn's record and result survived
DELETE /v1/sessions/{id}and expired on the clock. Newper-session index
sh:cp:session:<sid>:turns, unioned with the owner-set pass rather thanreplacing it (a record written before the index has no entry in it, and an open record carries no
TTL at all). The index is armed off the same sum as the terminal record and re-armed last at
every terminal transition, so it can never expire before a record it has to reach. It is
deliberately NOT an
ownership.tsdataKeysentry:deleteSessioncascades before it callsdeleteSessionTurns, so the index would be gone before the walk could read it.A base commit and a diffstat on every captured patch (
d1065dcf). A solve leaf's patch was abare string: no baseline, so a caller could not apply it safely once the leaf's workspace was gone.
captureWorkspaceDiffnow printsrev-parse HEADfirst (the conventionbuildPatchCaptureScriptalready used) —
rev-parse, not the envelope'sref, which can be a branch name that moves. Thepatch bytes stay in
result.patch, so the synchronous/runsand/runs/statusbodies keep theirshape; only a descriptor is attached.
diffstatcounts in-hunk lines only, so a binary-only diffreports its file count with no changed lines, and it is computed before the refused-too-large
branch — the case where it is the only description of the patch a caller gets.
A bounded status read and a
GET …/turns/{turnId}/artifacts/{kind}route (6e460da0). Thestatus read passed the stored record through verbatim, so a 4 MiB patch rode every poll of the
one route designed to be polled — the opposite of "a large patch is fetched as an artifact, not
inline". The body now carries a projection:
summary(one clipped line — assistant text, else agate's summary, else the diffstat, else the failure reason),
artifacts: [{kind, bytes, sha256?}],and
workspaceas the patch's descriptor minus its bytes. Measured on a 1 MiB patch against liveRedis: 1048596 B → a 200 B status body. The artifact route serves the bytes whole, byte-exact
for a diff that is not valid UTF-8, with an
ETagof what was actually served. The projection isread-time only: nothing extra is stored, so there is no second writer, no migration, and a
record written by an older worker projects identically (asserted).
Contract bump (
8e7f3608): control plane 1.25.0, harness 1.4.0, with the ADR and spec amendedrather than rewritten.
The one narrowing, called out
result.patchandresult.textleave the turn status body. That is a narrowing of a response,not an addition. It is permitted because
/v1is Preview(
docs/reference/maturity-and-lifecycle.md), and Preview requires it be listed, which the 1.25.0changelog section does. The synchronous
/v1/runsand/runs/statusbodies are deliberatelyuntouched — nothing polls them, so nothing there needed narrowing.
Deliberately omitted
A frame-level transcript for an async leaf. B5's scope item 5 asks for a "bounded
transcript-summary read", which lands here as the bounded
summary. A frame-level transcript is notreachable without new plumbing: ADR-0040's frame log is wired to
/v1/turnstreaming only andrunLeafemits no frames at all, and none of B5's four acceptance criteria ask for one. Follow-upissue rather than scope creep;
docs/specs/…p6-async-fan-out-design.md§12 records it as owed.Bounds are in bytes, not the issue's "N tokens": every bound in this repo is bytes (
clip,patchRefused,SH_TURN_STREAM_TOOL_RESULT_PREVIEW_BYTES), and the only token counter in the treeis an estimate.
New knob
MOCA_TURN_SUMMARY_BYTES, default2048(mirrors the worker's preview-bytes knob), strict parse,0means no summary. Indocs/reference/configuration.md.Verification
packages/control-plane1894 passed,packages/server577 passed,packages/sandbox-relay297passed,
packages/work-queue20 passed, harness 881 passed.make typecheckandSKIP=hadolint-docker make lint(Docker down locally) both clean.turn's record and its result against both the fake and real Redis, and that the index's TTL is
never shorter than the last record it points at;
getTurnArtifacthas a table of all fourabsences (unknown kind, non-terminal turn, no result,
patchRefused) plus an authz-order test, andthe base64 case goes through the real HTTP server, which is the only thing that exercises the new
Bufferresponse branch.ttlon the result604800, on the record608400, on the index608400; two sibling results coexist and both vanish with the session, noleftover keys. Against real bash and real git: the captured baseline equals
HEADandgit apply --checkaccepts the patch at it.upstream/mainwithout thesecommits:
harness/test/promote.test.ts > projectRootandharness/test/context-overlay.test.ts(a macOSmvinto a read-only staged dir), pluspackages/provisioner's seed tests (same macOS cause) and mocactl's Ink tests timing out at the5 s default under load (they pass at
--testTimeout=30000).Assisted-By: Claude Code