Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

fix(cloud-agent): fence a busy workspace snapshot once per episode - #13849

Open
eshurakov wants to merge 3 commits into
mainfrom
eshurakov/workspace-busy-fence-once-per-episode
Open

eshurakov wants to merge 3 commits into
mainfrom
eshurakov/workspace-busy-fence-once-per-episode

Conversation

@eshurakov

@eshurakov eshurakov commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Why

The service that runs agent sessions fenced the workspace snapshot on every heartbeat while the workspace was busy. A workspace counts as busy for as long as any attached terminal has a running PTY, so a single open terminal kept the workspace busy for many minutes. Each heartbeat then wrote the workspace snapshot allocation row, increased its invalidation generation, and logged a fence diagnostic. One sandbox produced about 1 fence every 5 seconds for 28 minutes, which is a pointless Durable Object write and log noise on every sandbox with an open terminal.

A snapshot capture can only start while the disk's idle candidate is in place. This change fences the first busy heartbeat that sees that candidate and then does nothing for the rest of the same busy episode. That single fence clears the candidate, so no capture can start until an idle heartbeat restores it. When the idle heartbeat restores the candidate, it also restarts the snapshot idle wait, so a long busy period does not count toward the wait and a capture does not run the moment a terminal closes. Workspace snapshots stay unpublished for the whole busy period. The active and terminal fence reasons are unchanged.

Summary

  • services/cloud-agent-next/src/control-plane/sandbox/sandbox-do.ts: the heartbeat handler fences workspace_busy only when the allocation's workspace disk still carries an idle candidate (idleConnectionId). The fence clears the candidate, so later busy heartbeats in the episode are no-ops and the diagnostic is emitted once per busy episode.
  • The same handler restarts the snapshot idle wait (lastMutationAt) when an idle heartbeat restores the candidate. Scheduling (the alarm) and capture eligibility both read workspaceSnapshotIdleAt, so they now use the same idle clock. Repeated idle heartbeats keep the timestamp, and a wrapper reconnect refreshes the connection id without restarting the wait, so a pending capture is not delayed.
  • services/cloud-agent-next/test/integration/control-plane-workspace-snapshots.test.ts: one test drives three busy heartbeats and asserts one fence diagnostic, one generation increment, no capture during the episode, and a second fence after an idle heartbeat starts a new episode. Another test covers a busy episode longer than the idle wait: no capture during it or immediately after it, and a capture after one idle minute. A third test reconnects a wrapper while the workspace is idle and asserts the idle wait is kept and the pending capture is not delayed.
  • services/cloud-agent-next/test/integration/helpers/fake-wrapper.ts: the fake wrapper can request heartbeat acknowledgements, so the tests can order heartbeat processing deterministically.

Verification

No manual test ran. The change affects Worker heartbeat handling and snapshot scheduling in the Durable Object, with no user-facing UI or API surface, and the repository runs a separate manual QA phase after review. Automated checks are listed in Reviewer Notes.

Visual Changes

N/A

Reviewer Notes

Automated checks:

  • pnpm exec vitest run --config vitest.workers.config.ts test/integration/control-plane-workspace-snapshots.test.ts test/integration/workspace-snapshot-diagnostics.test.ts — 112 passed.
  • pnpm exec vitest run --config vitest.workers.config.ts test/integration/control-plane-session-v2.test.ts — 123 passed.
  • pnpm exec vitest run src/control-plane/sandbox/workspace-snapshot.test.ts src/control-plane/sandbox/allocation.test.ts — 46 passed.
  • The fence-once test fails on the original heartbeat code (expected 4 to be 2 for the generation after three busy heartbeats) and passes with the change.
  • The long-busy test fails when the idle heartbeat does not restart the idle wait (lastMutationAt stays about 90 seconds behind the idle heartbeat) and passes with the change.
  • The reconnect test fails when the idle heartbeat compares against the current connection id instead of a missing candidate (lastMutationAt changes across the reconnect) and passes with the change.
  • pnpm run typecheck, pnpm run lint, and oxfmt --check on the changed files pass.
  • pnpm exec vitest run (unit suite): 9717 passed, 1 failed in scripts/sentry-source-maps.test.ts. That test also fails on a clean checkout of the base commit in this environment, so it is pre-existing and unrelated.

Design choices and limitations:

  • No new persisted busy flag and no Durable Object migration. The existing idleConnectionId precondition already answers "could a capture have started since the last fence", and the busy fence clears it, so it is the dedupe marker. The idle heartbeat restores the candidate and restarts the idle wait only when no candidate was present; a reconnect keeps the candidate and does not restart it.
  • A busy episode that starts while the disk has no idle candidate (for example the first heartbeat after a new allocation, or just after another fence) logs no workspace_busy fence. No capture was possible in that state, so no fence is needed; every fence that is emitted remains countable.
  • The diagnostic no longer reports that a sandbox is still busy on each heartbeat. Monitoring a long busy episode must use the wrapper heartbeat rather than the fence event.
  • The tests measure allocation generation, diagnostics, capture attempts and the stored descriptor. They do not count database writes.

The sandbox control plane fenced the workspace snapshot on every wrapper
heartbeat that reported a busy workspace. A busy workspace stays busy for
as long as a terminal PTY runs, so an open terminal fenced the snapshot,
wrote the allocation row and logged one diagnostic every heartbeat.

A capture is only possible while the previous idle heartbeat left the
disk's idle candidate in place. Fence the first busy heartbeat that sees
that candidate, which clears it once. Later heartbeats of the same busy
episode change nothing, and no capture can start until an idle heartbeat
makes the disk eligible again. The active and terminal fences are
unchanged.
…ends

The busy fence records the mutation time that starts the snapshot idle
wait. After a busy episode longer than the wait, an idle heartbeat kept
that old timestamp, so scheduling and capture eligibility both saw an
expired wait and a capture could run as soon as the terminal closed.

The idle heartbeat that restores the disk's idle candidate now restarts
the wait with its own timestamp. Repeated idle heartbeats keep it, so the
wait does not restart while the workspace stays idle. Active heartbeats,
the terminal fence and the sandbox shutdown deadline are unchanged.

Add a regression test for a busy episode longer than the idle wait: no
capture during it or immediately after it, and a capture after one idle
minute.
@eshurakov

This comment has been minimized.

@eshurakov
eshurakov marked this pull request as ready for review December 4, 2026 05:04

@chrarnoldus chrarnoldus left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

bot: services/cloud-agent-next/src/control-plane/sandbox/sandbox-do.ts:8399 — The first idle heartbeat after a wrapper reconnect resets the snapshot timer even if the workspace stayed idle. This can delay a pending snapshot or schedule a redundant one. Refresh idleConnectionId on reconnect, but reset lastMutationAt only when there was no previous idle candidate.

The idle heartbeat restarted the snapshot idle wait whenever the disk's
idle candidate did not name the current connection. A reconnect changes
the connection id while the workspace stays idle, so the next idle
heartbeat pushed a pending capture a full wait away.

Every fence clears the idle candidate, so a missing candidate is the
only sign that the wait must restart. Refresh the candidate to the
current connection on every idle heartbeat, and reset the wait only
when the candidate was absent. A reconnect now keeps the wait.

Add a regression test: an idle candidate, a replacement wrapper with a
new connection id, and an idle heartbeat that keeps lastMutationAt and
does not delay the pending capture.
@eshurakov

Copy link
Copy Markdown
Contributor Author

bot: Fixed in 026bf04. The idle heartbeat now always refreshes idleConnectionId to the current connection and restarts the snapshot idle wait only when the previous candidate was absent. A reconnect keeps the candidate, so it no longer delays a pending capture or schedules a redundant one. Added a reconnect regression test; the snapshot and diagnostics integration suites pass.

@eshurakov

Copy link
Copy Markdown
Contributor Author

Manual QA — T-122

Untestable · tested 026bf043a8

  • Verified: the local stack runs this head (workspace-snapshot allocation written before preparation; one reason=active fence with generation 1 per attempt), and the deployed pre-fix worker still shows the defect: 844 reason=workspace_busy fences from one sandbox in about two hours, one every ~5 s, generation +1 each time.
  • Failed / still needs checking: no local session reaches a ready route. The wrapper's session restore (GET /api/session/<kiloSession>/export) is answered 503 because session-ingest never completes an STS runtime-secret read. With no terminal, no workspaceBusy heartbeat exists, so the fixed cadence can only be checked after deploy.
  • Key evidence: 03-workspace-setup-failed.png, 04-local-preparation-blocker.txt, 05-production-busy-fence-cadence.txt.
Test details and evidence

Scenarios

# Scenario Steps Expected Observed Evidence Result
1 One fence per busy episode Start a local Cloud Agent session, open a terminal for 75 s, count workspace_snapshot_fenced reason=workspace_busy in the worker log Exactly one fence and one generation increment for the episode Blocked before the terminal: preparation fails at the wrapper session restore (/api/session/<kiloSession>/export 503), the route never reaches ready, so no terminal and no busy heartbeat exist 03-workspace-setup-failed.png, 04-local-preparation-blocker.txt untestable
2 Second episode fences again Close the terminal, wait for an idle heartbeat, open a terminal again One more fence for the second episode only Blocked by the same preparation failure 04-local-preparation-blocker.txt untestable
3 Long busy period restarts the idle wait Keep a terminal busy longer than the idle wait (60 s), close it, watch workspace_snapshot_capture No capture during the episode or immediately after it; capture one idle minute later Blocked by the same preparation failure 04-local-preparation-blocker.txt untestable
4 active and terminal fences unchanged Inspect fences during preparation and on terminal open Same reasons and cadence as before the change reason=active still fires and increments generation 0→1 locally (four attempts). reason=terminal cannot be produced without a ready route 04-local-preparation-blocker.txt partial
5 Pre-fix baseline of the defect Query Axiom cloudflare-logpush, ScriptName cloud-agent-next, 20:06Z–06:06Z, group by reason One workspace_busy fence per heartbeat 844 workspace_busy fences, all from one sandbox, 01:49:57Z–03:46:37Z, about one every 5 s; sampled rows show generation +1 per fence 05-production-busy-fence-cadence.txt observed

UI after the wrapper session restore fails: preparation fails before any terminal can open

Problems found

None attributable to this change. The blocker is a local environment gap and happens before any heartbeat fence can be evaluated. It is recorded under "Not tested".

Not tested

  • Scenarios 1–3, and the terminal half of scenario 4: this worktree's local stack cannot complete wrapper session restore. The attempts, in order:
    1. Default stack: the wrapper's GET /api/session/<kiloSession>/export through the runtime credential proxy is answered 401 invalid_token, because session-ingest runs USER_BEARER_ACCEPT=uts-only while the worker mints legacy runtime handles (RUNTIME_HANDLE_ISSUER unset). UI shows Preparation failed · Workspace setup failed (03-workspace-setup-failed.png).
    2. RUNTIME_HANDLE_ISSUER=uts in the worker's local .dev.vars: the failure moves one step earlier, to runtime proxy grant minting (route_failed stage prepare_dispatch_failed), because the local UTS runtime delegation is not available for this web-origin session.
    3. USER_BEARER_ACCEPT=legacy-and-uts in session-ingest: the wrapper export returns 503.
    4. USER_BEARER_ACCEPT=legacy-only: the wrapper export still returns 503. session-ingest logged no successful STS runtime-secret read (session_ingest_secret_source_read count 0), so its runtime-attestation branch cannot verify the handle.
      All four probes are reverted; git status --untracked-files=no is empty.
  • The fixed cadence itself needs a deployed worker, so it is covered by post-deploy checks rather than by a local run.

Post-deploy checks

  1. In Axiom cloudflare-logpush (ScriptName == 'cloud-agent-next'), last 24 h: group workspace_snapshot_fenced by sandboxId and reason. For each sandbox with an open terminal, reason=workspace_busy must appear at most once per busy episode (no two within 4 minutes), and the total must be more than 90% below the pre-deploy baseline of 844 on one sandbox in about two hours.
  2. For one sandbox that keeps a terminal open for more than 10 minutes, confirm workspace_snapshot_captured does not appear during that period and that reason=active and reason=terminal keep their previous cadence.
  3. Close that terminal, reopen it, and confirm exactly one additional reason=workspace_busy fence for the new episode, with one generation increment.
  4. Reconnect check (new at this head): force one wrapper reconnect while the workspace is idle and confirm the pending workspace snapshot capture still runs on the original idle clock, with no extra workspace_busy fence for the idle period.

Verdict: untestable

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants