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

fix(cloud-agent): deliver transcript notifications inside a short grace - #13832

Open
eshurakov wants to merge 5 commits into
mainfrom
eshurakov/sandbox-notification-expiry-grace
Open

eshurakov wants to merge 5 commits into
mainfrom
eshurakov/sandbox-notification-expiry-grace

Conversation

@eshurakov

@eshurakov eshurakov commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor

Why

When the service that runs agent sessions forwards a batch of transcript events to the per-session
coordinator, it allows two seconds for the call. During a short stall in that coordinator the call
times out, and the batch is counted as lost and thrown away. The user then sees a transcript with
missing text or tool output until the next event refreshes it. The same two-second budget also
covers waiting for one of the four forwarding slots, so a busy sandbox can lose a batch that never
even started. Recovering those batches is visible to users as transcript text that would otherwise
be missing.

This change gives a transcript batch a bounded second chance. If its call or its queue wait expires
while the batch is younger than ten seconds, it is sent again with a fresh two-second attempt. The
delivery identity (one UUID and its expiry) is created once when the batch is admitted and reused,
so a resend after an ambiguous timeout is deduplicated by the per-session coordinator's existing
receipt and each transcript delta is stored once. Grace never delays critical notifications: a
retry is not started, or is aborted, when a route or outcome update is waiting for the same session,
and a retried batch never takes a forwarding slot ahead of another waiting session. Route and
outcome notifications keep their single attempt, their original deadlines, and the existing queue
limits and eviction order.

Summary

  • A transcript notification batch that expires in the queue or during a send is retried while its
    total age is below SANDBOX_NOTIFICATION_GRACE_MS (10 s). Each retry gets a fresh budgetMs
    (2 s) attempt deadline, capped by the remaining grace.
  • Grace yields to route and outcome notifications. A queued retry is dropped (yielded), an
    in-flight retry is aborted, no retry starts while a route or outcome waits for that session, route
    and outcome heads are served before regular and retried heads, and when retries occupy all four
    forwarding slots a new route or outcome aborts one retry to get a slot unless its own session is
    already sending. Critical deadlines are unchanged, route/outcome keep one attempt, and non-transcript
    notifications are never yielded.
  • The delivery identity ({ id, expiresAt }) is pinned when a batch is admitted, and its bytes are
    counted in the 1,000-entry / 8 MiB budget at admission, coalescing, send and retry. Fresh transcript
    events never coalesce into a batch that already started an attempt or entered grace, so they keep
    their own deadline and identity. A retry that yields releases its byte reservation before the
    critical notification is admitted.
  • NotificationLoss gains eventCount (transcript events), attempts (largest number of sends one
    dropped batch reached) and remote (ambiguous when the batch was sent at least once and may have
    reached the receiver, not_attempted when no send was attempted).
  • A recovered timeout is emitted as one Sandbox notification retry warning with the stable
    event: sandbox_notification_retry field, the expiry phase, the attempt number and queue/send
    durations. It is countable in Axiom and is not a loss.
  • docs/control-plane.md §Forwarding documents the grace, the yield rules, the pinned identity and
    the new loss and retry fields.

Verification

  • Automated checks only. The local harness simulates a stalled receiver inside the real Sandbox
    DO and Session DO path, which is the closest reproducible stall without the manual stack:
$ pnpm --filter cloud-agent-next exec vitest run src/control-plane/sandbox/notifications.test.ts
Tests  33 passed (33)
$ pnpm --filter cloud-agent-next exec vitest run --config vitest.workers.config.ts \
    test/integration/control-plane-session-v2-native-events.test.ts
Tests  15 passed (15)
$ pnpm --filter cloud-agent-next exec vitest run --config vitest.workers.config.ts \
    test/integration/sandbox-control-v2-routes.test.ts
Tests  106 passed (106)
  • Relevant tests: delivers a transcript batch after a held send in its own lane expires,
    yields a queued transcript retry to an outcome waiting in the same lane, does not let transcript retries take lanes ahead of another session outcome, frees a retry lane for an outcome that arrives after all four retries start, frees the slot for critical work ahead of an older transcript batch, does not free a retry lane when the critical session is already sending, does not coalesce fresh events into a batch already in grace, releases an aborted retry reservation before admitting critical traffic, reports a yield after an earlier send as ambiguous, applies a transcript delta once when a grace retry follows a lost response, and
    counts the pinned delivery identity at admission, send and retry.
  • Limit: a live end-to-end stall of a deployed Session DO needs the manual local stack and is left
    to the QA pass; this change was verified with the stalled-receiver harness above.

Visual Changes

N/A

Reviewer Notes

  • Grace size. Ten seconds lets one batch reach five sends, covers the observed 1.5–2 s stalls,
    and stays far inside the Session DO's five-minute receipt retention. A retried batch can hold its
    lane for up to ten seconds only when no route or outcome waits and no other session is ready; a
    newly arriving route or outcome aborts one retry if retries occupy every slot. The constant is one
    line.
  • Yield rule. A transcript retry that has already been queued is dropped and an in-flight retry
    is aborted when a route or outcome update arrives for the same session, and a new route or outcome
    aborts one retry when retries occupy all four slots, so critical work uses a lane immediately.
    Route and outcome deadlines and their single attempt are unchanged. The dropped batch is recorded
    once as yielded, with remote derived from whether it was sent before, not from where it was
    dropped.
  • Identity ownership. The delivery identity moved from notifySession into the dispatcher
    because the dispatcher owns retries; notifySession now forwards the pinned payload and no longer
    creates a new identity per attempt. The dispatcher is the only production caller.
  • Queue accounting on retry. A retry is re-inserted into the pending queue. The retained
    entry/byte count is unchanged by that re-insertion, so no capacity eviction is triggered by a
    retry; an entry at the byte boundary is accounted with its delivery metadata before admission.
  • Coalescing. Batches are coalesced only while the adjacent batch has no attempt yet, so a retry
    can never absorb a later batch under the same receipt.

An expired event batch was removed and counted at the two-second
notification deadline, so a short Session DO stall lost transcript text.
Retry transcript batches after expiry while their own age is below a
fixed ten-second cap, with a fresh two-second attempt each time. Route,
outcome and other notifications keep one attempt.

Pin one delivery identity and the same immutable payload on a batch at
its first send, so the Session DO receipt deduplicates a replay after an
ambiguous timeout. Add eventCount and attempts to the loss aggregate.

Update docs/control-plane.md Forwarding and cover queue expiry, send
deadline, identity stability and grace exhaustion in the dispatcher
unit and integration tests.
A retried transcript batch could hold a session lane past an outcome's
deadline, and across saturated lanes a retry could take the lane before
another session's critical notification. Grace now yields: a batch is not
retried while a route or outcome notification waits for the same session,
a queued retry is dropped and an in-flight retry is aborted when one
arrives, and a retried head never takes a lane ahead of another waiting
session. Critical deadlines and single attempts are unchanged.

Pin the delivery identity at admission and account its bytes in the byte
budget at admission and coalescing, so the 8 MiB cap holds through send
and retry. Only batches without an attempt coalesce, which keeps the
payload immutable.

Log each recovered timeout as a Sandbox notification retry warning with a
stable event field, and record whether an expiry or yield drop may have
reached the receiver, so a timeout is countable separately from a
terminal dispatcher drop. Update the forwarding docs.

Add tests for same-lane and saturated-lane yield, boundary byte
accounting across send and retry, and a real Session DO replay after a
lost response.
Four grace retries could hold every forwarding slot, so a route or outcome
arriving after they started waited for a whole attempt. When retries
occupy all four lanes, a new route or outcome now aborts one retry and
takes its lane. Critical deadlines and retained per-session order are
unchanged.

Derive the loss remote status from whether the batch was sent before,
not from the queue position at drop time, so a retried batch that later
yields or expires in the queue reports an ambiguous remote result. Test
critical arrival before and after all four slots enter grace and a yield
after an earlier send.

Wait for the replay's onEvents call to finish in the lost-response
integration test before flushing and reading the transcript, so a broken
replay cannot pass by reading before the duplicate write.
Freeing a retry lane did not decide who used it: an older transcript batch
could take the slot ahead of the critical notification. Lane selection now
serves route and outcome heads first, then regular heads, then grace
retries, so the freed slot goes to eligible critical work without changing
order inside a session. A critical session that is already sending cannot
use a freed lane, so it no longer costs an unrelated retry.

Yield only transcript batches: an expired route or outcome was recorded as
yielded when critical work was queued for the same session.

Signal replay completion from the second receiver call only, so a slow
first call cannot mark the replay applied before it finishes.
@eshurakov

This comment has been minimized.

@eshurakov
eshurakov marked this pull request as ready for review December 4, 2026 02:14

@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/notifications.ts:492: A batch that expired in the queue still has zero attempts, so fresh transcript events can merge into it and be dropped when an outcome makes the grace batch yield. Exclude grace batches from coalescing so fresh events keep their own delivery deadline.

bot: services/cloud-agent-next/src/control-plane/sandbox/notifications.ts:516: When an aborted grace retry would free enough bytes for a route or outcome, admission can still drop the critical notification because the retry holds its reservation until asynchronous cleanup. Recheck admission after the reservation is released while preserving the original deadline.

… reservation

A batch that expired in the queue and entered grace still had no attempt,
so fresh transcript events coalesced into it and inherited its old
deadline, delivery identity and grace cap. Coalescing now skips any batch
that started an attempt or entered grace, so fresh events keep their own
deadline and are delivered even when the grace batch yields to critical
traffic.

An aborted grace retry also kept its byte reservation until its
asynchronous cleanup, so admission could drop the route or outcome that
preempted it at the byte cap. Preemption now releases the reservation
synchronously, and the cleanup path does not subtract it twice.
@eshurakov

Copy link
Copy Markdown
Contributor Author

bot: Fixed both findings in 7c2f33f.

  1. Coalescing now skips an adjacent batch that started an attempt or entered grace, so fresh transcript events create their own entry with a new deadline and delivery identity. They are delivered even when the grace batch yields to critical traffic; the unit test does not coalesce fresh events into a batch already in grace covers it.

  2. Fixed with the small release: preemption subtracts the aborted retry's byte reservation synchronously and the asynchronous cleanup no longer subtracts it again, so the route or outcome is admitted against the freed capacity. Test: releases an aborted retry reservation before admitting critical traffic.

docs/control-plane.md §Forwarding and the PR description are updated. Dispatcher unit 33/33, native-events 15/15, routes 106/106, typecheck, oxlint and oxfmt pass.

@eshurakov

Copy link
Copy Markdown
Contributor Author

Manual QA — T-116

Untestable · tested 7c2f33f358

  • The shipped dispatcher passes all 7 harness scenarios (33/33 checks) with real wall-clock timers, including both acceptance cases and both review fixes: retry inside grace, one pinned delivery identity, exactly-once delta persistence, fresh events not merged into a grace batch, and a preempted retry releasing its bytes before a critical arrival.
  • The live end-to-end path is still blocked before any transcript: a fresh session fails workspace preparation at "Loading session history" because session-ingest returns 401 invalid_token for /api/session/:id/export; a Retry reproduces it. This is unchanged from QA 01 and outside the task diff.
  • The dispatcher behaviour is verified with artifacts; the live stall, the transcript recovery and the real retry log line remain untested, and two post-deploy checks cover them.
Test details and evidence

Scenarios

# Scenario Steps Expected Observed Evidence Result
1 Live: create a Cloud Agent session and read its transcript Fake login, New session, public repo octocat/Hello-World, model Fake Deterministic, prompt Reply with exactly qa-t116-cold, wait for preparation; then Retry Transcript shows the reply Preparation fails at "Loading session history" 0 s with "Workspace setup failed"; worker: upstreamStatus: 401, upstreamErrorExcerpt: invalid_token, proxyRoute: ingest, pathShape: /api/session/:kiloSessionId/export; the Retry fails the same way 01-cloud-start.png, 03-workspace-setup-failed.png, 04-loading-session-history-failed.png, 05-retry-failed.png, 07-worker-export-401.log, 08-session-ingest-export-401.log Blocked (environment)
2 Acceptance A: a held send, then a transcript batch behind it Route send for one session stalls to its 2 s deadline; a 2-delta transcript batch is enqueued 200 ms later The batch is delivered once with one pinned identity, both deltas stored once, no transcript expiry loss 2 sends total, 1 transcript send, s1-delta-1/s1-delta-2 once each, one id@expiresAt pinned at admission, no loss record with eventCount > 0; the held route expired once, as critical work keeps one attempt 10-acceptance-held-send.json, 06-harness-results.png Pass
3 Acceptance B: receiver slow past the 10 s grace 3-delta batch, receiver never answers, wait 13.5 s Five sends, one identity, one terminal expiry record with attempts and event count 5 sends, one identity, retry samples for attempts 1–4, one expired record: attempts=5, eventCount=3, remote=ambiguous, phase=send_deadline, maxQueueAgeMs=10002, retained/bytes 0 11-slow-past-grace.json Pass
4 Lost response after the batch was applied Receiver applies 2 deltas then stalls past the deadline; later attempts answer Retry reuses the identity; each delta is stored once 3 sends, 1 identity, s3-delta-1/s3-delta-2 persisted once each, no transcript loss 12-ambiguous-resend.json Pass
5 Review finding 1: fresh events against a batch already in grace 4 lanes stall, session batch retries into the queue, a fresh batch is enqueued, then an outcome arrives Fresh batch is a separate entry with its own identity and is not dropped with the grace batch Grace batch was queued after a retry; pending 1 → 2 after the fresh enqueue; the yielded aggregate is eventCount=2 (old event + one preempted lane event, not 3); fresh persisted under its own identity; outcome delivered 13-fresh-vs-grace.json Pass
6 Review finding 2: a yielded retry frees its reservation 4 retries hold large batches; a ~1 MB route arrives when 7,800,900 B of the 8,388,608 B cap is used The critical notification is admitted without a capacity loss; bytes stay under the cap Critical admitted and sent; no capacity loss; exactly one retry yielded and released 1,950,225 B; bytes after the enqueue 6,850,757 B, post-send 5,850,675 B 14-reservation-release.json Pass
7 Regression: critical outcome during an in-flight retry Transcript retry in flight, outcome for the same session arrives Retry aborts once as yielded, with remote state from prior sends; no further retry; outcome delivered One yielded record eventCount=1, attempts=2, remote=ambiguous; 3 sends (2 attempts + outcome); outcome delivered 15-critical-yield.json Pass
8 Regression: retirement during an in-flight retry Transcript retry in flight, retire(session), then sibling traffic One retired record, no further sends for the session, sibling unaffected One retired record eventCount=1, attempts=2; 2 transcript sends only; sibling delta delivered 16-retire-during-retry.json Pass
9 Live: transcript recovered after a Session DO stall Stall the Session DO past 2 s while a transcript batch is queued; read the transcript Every delta appears once; a retry line is countable Not reachable: workspace preparation fails before any transcript (scenario 1), so this worktree produces no real notification traffic — Untestable

Live: Cloud Agent composer with the fake account and a public repository

Live: the new session fails workspace preparation

Live: the failing preparation step is "Loading session history"

Live: the Retry action fails the same way

Harness results: 7 scenarios, all checks pass

Harness

~/Projects/_orchestrator/state/tasks/T-116/qa/02/private/harness.ts imports the shipped dispatcher and withDORetry (no copy) and runs each scenario in a fresh process with real timers. The receiver models the Session DO receipt in session-do.ts: key <padStart(expiresAt,16)>/<id>, value next event index, applied inside the row mutation. Sends use the same DEFAULT_DO_RETRY_CONFIG and { deadlineAt, signal } scope as SandboxControlV2.notifySession. The harness is not a real DO; it reproduces the dispatcher's decisions and the receipt dedupe, not the RPC transport.

Log evidence for the blocker

# dev/logs/cloud-agent-next.log (worker)
message: 'Runtime credential proxy request failed'  level: warn
  method: 'GET'  path: '/api/session/<redacted>/export'
  upstreamAttempted: true  upstreamStatus: 401
  upstreamContentType: 'application/json'
  upstreamErrorExcerpt: 'invalid_token'
  proxyRoute: 'ingest'  pathShape: '/api/session/:kiloSessionId/export'

# dev/logs/cloudflare-session-ingest.log
GET /api/session/<redacted>/export 401 Unauthorized (1ms)

The UI reports the same step: "Loading session history — Failed — Workspace setup failed". The local stack also logs session_ingest_active_sessions_auth_refusal reason=verification_unavailable for /api/sessions/active. The task diff touches only notifications.ts, sandbox-do.ts, docs/control-plane.md and three test files, so this blocker is outside the change.

Problems found

None owned by the task.

The local stack cannot verify local user tokens: session-ingest answers 401 invalid_token for the transcript export that workspace preparation calls, so every session fails at "Loading session history" before the wrapper starts Kilo. This reproduces on a fresh fake account and after Retry. It is an environment/credential problem in this worktree and is unchanged from QA 01.

Not tested

  • A live Session DO stall with real transcript traffic and the user-visible transcript recovery. Workspace preparation fails with 401 invalid_token before any transcript exists (scenario 1).
  • A real event: sandbox_notification_retry line in Axiom, and real Sandbox notification loss counters with eventCount/attempts. The callback is wired in sandbox-do.ts and the harness captures the same samples, but the local stack produced no notification traffic.
  • A rare edge in the dispatcher's deadline check. In one early run of scenario 6 one of the four large retries was recorded as failed (not expired) with attempts=1 and age 1999 ms, so no grace retry ran. It did not reproduce in 11 further runs: every deadline abort landed 0–3 ms after deadlineAt. The artifact from that run was overwritten; the cause is unproven. If a withDORetry timer ever fires 1 ms before the dispatcher's deadlineAt, now >= entry.deadlineAt is false and the batch is dropped as failed. The post-deploy check covers the live loss counts.

Post-deploy checks are recorded on T-116: the existing check for a live stall (no missing text, sandbox_notification_retry, expired with eventCount/attempts) and a second check for the two review fixes (same delivery id on retry, a later batch with its own id, and a yielded eventCount that covers only the yielded batch).

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