Repository navigation
fix: 🐛 Skip empty per-session scratch dir on writable workload runs - #613
Conversation
Assisted-By: Claude (Anthropic AI) <[email protected]> Signed-off-by: Evaline Ju <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Thanks for this. Avoiding the empty per-session directory is a good idea, but the condition and the tier assumption need tightening before this can merge:
- must-fix:
writesInMountis true for a read-only mounted run (mount: 'read-only', nowritable). That run is still told to use<WorkspaceRoot>/<sid>as scratch, and that directory now never gets created. UsecontextMode(env) !== 'read-only'. - must-fix: phase 1 workload runs (
contextWritable: true, no workload sandboxes) use the session's tier, so they can land on a microVM worker, andvmpoolrefuses an emptyworkspace_key. Gate the empty key on the record advertisingworkspace-subdir(container worker), or onworkloadbeing set. - suggestion: add a run-leaf test covering which context modes set the flag, plus a test that a no-capability record keeps the key.
- nit: rename
forWorkloadContextso it says what it does.
Commits are signed off (DCO passes) and all CI checks pass at 30d74a7.
| // that dir -- contextNote tells the agent to use it as scratch -- so keep the key then. | ||
| const writesInMount = | ||
| env.internalContext !== undefined && | ||
| (env.internalContext.writable === true || env.internalContext.mount !== undefined); |
There was a problem hiding this comment.
must-fix: a read-only mounted run loses its scratch dir. mount !== undefined is also true for mount: 'read-only' when writable is not set. That run's contextMode is 'read-only', and contextNote (line 666) still says "Use ${selected.config.podCwd} as writable scratch space". podCwd is still <WorkspaceRoot>/<sid>, because sessionPodCwd keys on the record's capability, not on the workspace key. With the key dropped, the worker never creates that directory. So the prompt points the agent at a path that doesn't exist. If the agent mkdirs it, the WorkspaceRunner doesn't track it (unseen key), so it is never swept. That's a permanent leak instead of a 30-minute one. This contradicts the comment above and the PR body ("read-only workload runs are unchanged").
The condition that matches the comment is the existing mode helper:
const writesInMount = env.internalContext !== undefined && contextMode(env) !== 'read-only';(copy = writable === true, on either an overlay or a read-only mount; persistent = mount === 'writable'.)
| // subdir on the worker would sit empty until the idle sweep. Workload-context runs are | ||
| // container-tier only, so the microVM "refuse empty workspace_key" rule does not apply. | ||
| { | ||
| workspaceKey: forWorkloadContext ? '' : sessionId, |
There was a problem hiding this comment.
must-fix: an empty key is refused on the microVM tier, and workload-context runs are not container-only. Only phase 2 workload sandboxes (workload/mount set) are container-only (sandbox_tier_unavailable in workloads.ts). A phase 1 workload run, with no sandboxes and only internalContext.writable: true (contextWritable), runs on the shared pool in the session's tier ("The sandbox tier is the session's, chosen as for any other run", docs/context-service.md §Runs). On a mixed stack with a microvm session, or a P4-only stack, selectPoolSandbox now sends workspaceKey: ''. vmpool.checkKey refuses that (RefuseEmptyKey, "the microVM path requires a non-empty workspace_key"). So the context overlay's first exec fails, and a run that works today now fails.
Suggested fix: drop the key only where an empty key is known to be safe. That means a record that advertises WORKSPACE_SUBDIR_CAPABILITY (only the container remote-worker does, cmd/worker/main.go:275; microvm-worker doesn't). For example, workspaceKey: forWorkloadContext && rec.capabilities.includes(WORKSPACE_SUBDIR_CAPABILITY) ? '' : sessionId. Alternatively, restrict it to workload !== undefined. Then fix the comment, and add a test that a record without the capability keeps sessionId.
| // the caller sets forWorkloadContext. Selection suppresses the per-session workspace_key so | ||
| // the worker does not create an unused <WorkspaceRoot>/<sessionId> dir that lives until the | ||
| // idle sweep. | ||
| it('sends an empty workspace key when forWorkloadContext is set', async () => { |
There was a problem hiding this comment.
suggestion: test the run-leaf decision, not only the plumbing. This test checks that the flag becomes '', but nothing checks which runs set the flag. That decision is where the read-only-mount bug above sits. A table test in run-leaf-context.test.ts would pin it: assert selectPoolSandboxMock's 4th arg .forWorkloadContext for an overlay read-only run (false), a mounted read-only run (false), an overlay copy run (true), a mounted read-only + writable run (true), and a mounted writable run (true). Also add a no-capability (microVM-style) record case here that keeps sessionId.
| * the per-session workspace_key, which would otherwise ask the worker to create an unused | ||
| * `<WorkspaceRoot>/<sessionId>` dir that lives for 30 min until the idle sweep. | ||
| */ | ||
| forWorkloadContext?: boolean; |
There was a problem hiding this comment.
nit: the name and doc don't match what the flag does. Read-only workload runs also "run with their cwd pointed at a workload-context mount", but they must not set this flag. A name that says what the flag does would avoid the mix-up above, for example omitWorkspaceKey or agentWritesInContext, with the doc saying "the agent's only writable dir is the context view".
cwiklik
left a comment
There was a problem hiding this comment.
Summary
Solid, well-motivated change with clear comments, but the predicate does not match the rule its own comment states: mount !== undefined also catches a read-only mount with no run-level writable, and for that shape contextNote still points the agent at <root>/<sessionId> as scratch -- a directory the worker no longer creates once the key is suppressed. contextMode(env) !== 'read-only' is the predicate the comment describes. Two suggestions follow, on the unenforced container-tier assumption and on where the new test sits.
Verified and not reporting: the relay's workspace_key authz (sandbox-caller.ts:260, e.workspaceKey !== claims.wsk -> PERMISSION_DENIED) is unreachable from this path. The harness presents the exec token, so execCaller returns kind: 'harness' and main.ts:299 routes through pumpExec, bypassing sandbox.exec entirely. An empty key is safe there.
Author: evaline-ju (MEMBER -- maintainer)
Areas reviewed: TypeScript (harness selection + leaf run), Tests
Agent/IDE config (.claude/.vscode): none
Commits: 1 commit, all signed-off: yes
CI status: passing (14/14)
| // that dir -- contextNote tells the agent to use it as scratch -- so keep the key then. | ||
| const writesInMount = | ||
| env.internalContext !== undefined && | ||
| (env.internalContext.writable === true || env.internalContext.mount !== undefined); |
There was a problem hiding this comment.
must-fix -- this predicate contradicts the rule the comment above it states.
The comment says a read-only workload run keeps the key. But mount !== undefined is true for mount: 'read-only' as well, and when writable is falsy that is exactly the read-only case: contextMode (line 715-718) returns 'read-only' for mount === 'read-only' without writable === true. So the key is dropped for the one shape the PR says is unchanged.
What follows from that: contextNote's read-only branch (line 737) tells the agent "Use ${scratch} as writable scratch space", and scratch is selected.config.podCwd (line 659), which sessionPodCwd sets to <root>/<sessionId>. That is unchanged by this PR. With the key suppressed, WorkspaceRunner passes straight through to Inner and never creates <root>/<sessionId> -- so the prompt names a directory that does not exist, and the agent's first write there fails.
The combination is reachable end to end, not hypothetical: resolveWorkloadRun (packages/knative-server/src/workloads.ts:775) spreads mount from the workload record, and server.ts:1045 sets writable: body.contextWritable === true. A POST /runs with no contextWritable, against a workload whose sandboxes.mount is 'read-only', produces { mount: 'read-only', writable: false }.
The fix is the rule the comment already describes:
const writesInMount = env.internalContext !== undefined && contextMode(env) !== 'read-only';That reuses the single source of truth for the three modes, so the predicate and the prompt can no longer drift apart -- which is how they drifted here.
| { workspaceKey: sessionId, ...(workload ? { workload } : {}) }, | ||
| // A workload-context run drops the key: its cwd is the workload mount, so a per-session | ||
| // subdir on the worker would sit empty until the idle sweep. Workload-context runs are | ||
| // container-tier only, so the microVM "refuse empty workspace_key" rule does not apply. |
There was a problem hiding this comment.
suggestion -- "Workload-context runs are container-tier only" is a deployment assumption, not something the code enforces, and the comment reads as though it were guaranteed.
run-leaf.ts never passes opts.tier, and line 695 resolves const tier = tiers ? opts.tier || tiers.default : ''. So the tier of a workload run is whatever the deployment declares as default (SH_SANDBOX_TIERS / SH_SANDBOX_DEFAULT_TIER). Nothing downstream restricts a workload run to the container tier.
If a deployment ever defaults to the microVM tier, vmpool.checkKey (remote-worker/internal/vmpool/workspace.go:19-24) refuses the empty key outright with empty-workspace-key: "the microVM path requires a non-empty workspace_key: there is no correct workspace to choose and nothing to fall back to". That is a hard Exec refusal, not a degraded path -- so the assumption carries the whole change.
Two options, either is fine: gate on the tier that was actually resolved (it is in scope right here), or soften the comment to say that today's workload deployments run on the container tier and this is why the microVM rule does not bite -- so the next reader knows it is a precondition to re-check, not an invariant.
| // the caller sets forWorkloadContext. Selection suppresses the per-session workspace_key so | ||
| // the worker does not create an unused <WorkspaceRoot>/<sessionId> dir that lives until the | ||
| // idle sweep. | ||
| it('sends an empty workspace key when forWorkloadContext is set', async () => { |
There was a problem hiding this comment.
suggestion -- this test pins the plumbing (forWorkloadContext: true -> workspaceKey: '') rather than the decision, so it passes regardless of which runs set the flag. The defect in run-leaf.ts is in the predicate, and this test cannot see it.
A case in harness/test/run-leaf-context.test.ts would close that gap, since it already builds exactly the right envelopes via mountedEnv('read-only') and mountedEnv('read-only', true). Worth noting the existing suite will not catch it as written either: those tests mock selectPoolSandbox wholesale (selectPoolSandboxMock), so the opts passed to it are never asserted. Asserting selectPoolSandboxMock.mock.calls[0][3].forWorkloadContext for the three modes -- 'read-only' keeps the key, 'read-only' + writable and 'writable' drop it -- would pin the rule itself.
Signed-off-by: Evaline Ju <[email protected]>
|
Thanks both — overlapping must-fixes and suggestions, all addressed in the latest push; also appreciate @cwiklik's relay authz trace confirmation.
|
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Thanks. All four items from our previous review are addressed in 84c5026:
- The predicate now uses
contextMode(env) !== 'read-only', so a read-only mounted run keeps its<root>/<sid>scratch dir, matchingcontextNote. - The empty key is gated on
WORKSPACE_SUBDIR_CAPABILITY, which matchessessionPodCwd. The microVM worker keeps the session key. - The run-leaf table test pins the decision for all five context shapes, and the no-capability record test pins the gate.
- The rename to
agentWritesInContextand the rewritten doc read well.
Commits are signed off, and all CI checks pass at 84c5026.
|
@cwiklik needs you re-review for clearing |
cwiklik
left a comment
There was a problem hiding this comment.
Summary
Re-review: all three items from my earlier CHANGES_REQUESTED are fixed, and the container-tier suggestion was addressed more robustly than I proposed -- a capability gate rather than a softened comment. One non-blocking coverage gap remains.
I verified the fixes by mutation testing rather than by reading the diff:
| Prior finding | Fix | Verified by |
|---|---|---|
must-fix: mount !== undefined also caught a read-only mount, dropping the key for the one shape the PR said was unchanged |
agentWritesInContext: env.internalContext !== undefined && contextMode(env) !== 'read-only' -- reusing contextMode as the single source of truth, so the predicate and contextNote's prompt can no longer drift apart |
M1: reverting to env.internalContext !== undefined fails the new 5-case test in 4ms |
| suggestion: unenforced container-tier assumption | Gates on rec.capabilities.includes(WORKSPACE_SUBDIR_CAPABILITY) |
M2: dropping the gate fails the new negative test |
| suggestion: the test pinned the plumbing, not the decision | The 5-case table in run-leaf-context.test.ts asserting selectPoolSandboxMock.mock.calls[0][3] across all three modes |
the M1 kill confirms it sees the predicate |
Worth recording why the capability gate is stronger than its own comment claims: it is structural, not conventional. The microVM worker's Capabilities come from man.Capabilities, which probe_capabilities (deploy/microvm/build-snapshot.sh:843) fills by probing for binaries inside the guest (bash rg base64 file python3 git node ripgrep curl). workspace-subdir cannot appear in that set, so vmpool.checkKey's empty-workspace-key refusal is unreachable from this path regardless of which tier a deployment defaults to -- the comment's "today's workload deployments default to the container tier" understates it, and the reader could keep the stronger fact.
Also re-confirmed on the new head and not reporting: the relay's workspace_key authz (sandbox-caller.ts:260, e.workspaceKey !== claims.wsk -> PERMISSION_DENIED) stays unreachable here. The harness presents the exec token, so execCaller returns kind: 'harness' and main.ts:299 routes through pumpExec, bypassing sandbox.exec. An empty key is safe there.
I also checked that the empty key cannot strand a path derived from podCwd: sessionPodCwd still returns <root>/<sessionId> on a capable record, but nothing cds there -- GrpcRelayTransport sends absolute commands, the context overlay is rooted at the absolute /workspace/.moca-context, and the promoted-config overlay at /workspace/.sh-config. So the unused directory is simply never created, which is the point of the change.
Verification: tsc --noEmit clean; both changed suites 58/58; full harness suite 697 pass / 18 fail, where all 18 are Redis-connection failures from having no local Redis (294 ECONNREFUSED/redis lines) and unrelated to this diff -- every suite in the changed area passes; prettier --check clean on all four files.
Author: evaline-ju (MEMBER -- maintainer)
Areas reviewed: TypeScript (harness selection + leaf run), Tests
Agent/IDE config (.claude/.vscode): none
Commits: 2 commits, all signed-off: yes
CI status: passing (15/15)
| listPods: async () => [], | ||
| lease, | ||
| affinity: noAffinity, | ||
| records: fakeRecords([{ ...grpcRec, capabilities: [WORKSPACE_SUBDIR_CAPABILITY] }]), |
There was a problem hiding this comment.
suggestion -- coverage gap: nothing pins the key being kept on a record that advertises the capability, which is the ordinary non-workload session. (Commenting here because the line that needs changing, the records: of keys the workspace by the session id even when the LEASE holder differs at line 251, is outside this diff.)
Hardcoding const agentWritesInContext = true (select-sandbox.ts:672, ignoring the opt entirely) passes all 58 tests in both changed suites. The cause is the fixture: grpcRec.capabilities is [] (line 139), so every existing non-empty-key assertion -- including this test and gives the leased transport the SESSION id as its workspace key -- runs against a record where the new gate short-circuits before agentWritesInContext is ever consulted.
The two new tests cover agentWritesInContext: true x {capable, incapable}. What is missing is false x capable: the combination where the flag is the only thing standing between a normal session and a dropped key.
A one-line change to that test's records: at line 251 closes it, since it already asserts workspaceKey === 'sess-1':
records: fakeRecords([{ ...grpcRec, capabilities: [WORKSPACE_SUBDIR_CAPABILITY] }]),I checked this both directions rather than just proposing it: with that change the agentWritesInContext = true mutation fails that test, and with the mutation reverted the suite is back to 39/39. Non-blocking -- the shipped behaviour is correct; this is about the suite noticing if it later stops being.
Signed-off-by: Evaline Ju <[email protected]>
ingpaolodettori-dev
left a comment
There was a problem hiding this comment.
Re-checked 963e731: this test-only change closes the coverage gap raised in review. The non-workload session test now uses a record that advertises WORKSPACE_SUBDIR_CAPABILITY, so the capability half of the key-drop gate is satisfied and the test pins that agentWritesInContext must also be set. Hardcoding the flag would now fail it. Production code is unchanged from 84c5026, which we already approved. Commits are signed off.
A worker deletes a session's workspace after SH_WORKSPACE_IDLE, and the next Exec for the key gets a fresh one. The placement code reports a reset only when the session moves to another sandbox, so a reclaim on the same sandbox was silent: the next turn started in an empty workspace and nobody was told. The harness now keeps a marker file, .moca-session, holding the workspace key at the root of the session's workspace, and records in the session's log (a `workspace_marker` custom entry, the latest winning) that it wrote it. At the start of every turn, before the agent runs, one Exec reads the marker and (re)writes it. If the log says it was written and it is missing or holds another key, the turn reports `workspace_reset` with the new reason `reclaimed`: in the placement (and so the result, the done frame and the runtime record), as the stream's first frame, and in a note before the model's prompt. Moved sessions keep their own reason, and their model now gets the note too. - No record means "never written", so no session from before this change is reported on its first turn after an upgrade. - The marker is written only into a workspace that holds something, at the turn's start or, failing that, at its end, so the container worker's early removal of empty session directories (#551) still applies. - The check never fails a turn: an Exec error is logged and gives no verdict. - It runs only when the Execs carry a workspace key, so a workload run that writes only in its context (#613) has no check. - `.moca-*` is already left out of a templated session's patch; the marker is also listed in a root repository's info/exclude. - Cost: one Exec per turn (two on a turn that starts in an empty workspace); the script uses only shell builtins once the workspace is marked. Docs: brain-and-hands (the limits: a session that deletes the marker is reported as reset; a turn right after a compaction checkpoint counts as a first turn; it needs a per-session workspace; it does not prevent the reset), sessions-and-turns, sandboxes-and-tiers, http-api, both OpenAPI documents (control plane 1.31.0, harness 1.7.0), the changelog and change-policy. mocactl prints the new reason. Part of #338 Assisted-By: Claude Code Signed-off-by: Rong Chang <[email protected]>
Summary
On a workload run whose leaf writes inside the workload mount, the sandbox worker was still creating an unused per-session subdir in the shared workspace that then lingered until the 30-minute idle sweep. This change teaches selection to omit the per-session key for those runs so no directory is created in the first place; read-only workload runs are unchanged because their prompt still names that subdir as writable scratch space.
Addresses part of #551, but eager cleanup for the read-only case would need a worker-side release signal on session end and would be a follow-up
Assisted-By: Claude (Anthropic AI) [email protected]
Checklist
git commit -s).make lintand the tests for the touched packages pass.docs/page, with the right maturity label (seedocs/CONTRIBUTING-DOCS.md). - N/Amake check-linkspasses if any Markdown changed. - N/Adocs/specs/README.mdordocs/adrs/README.md. - N/A