Skip to content

fix(api): hold follow-ups while waiting for the first VM - #2852

Merged
simple-agent-manager[bot] merged 9 commits into
mainfrom
sam/fix-2847-hold-follow-08fj1d
Nov 19, 2026
Merged

simple-agent-manager[bot] merged 9 commits into
mainfrom
sam/fix-2847-hold-follow-08fj1d

Conversation

@simple-agent-manager

@simple-agent-manager simple-agent-manager Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Draft-only hold lifted by Raphaël 2026-11-18.

Closes #2847

Summary

A second message sent while the initial task waits for a VM currently reaches sleep recovery, which reports sleeping_snapshot_missing and fails the conversation. Hold the follow-up in the existing durable inbox while its exact project/chat task is draft, ready, queued or delegated and has no retained sleep history. After startup it follows normal runtime readiness and busy-turn delivery.

Retained sleeping_at keeps genuine queued recovery tasks on the existing recovery path. In-progress/terminal tasks, allowWake=false, Instant handling and authority checks retain their diagnostic behavior. Readiness retries retain the original configurable TTL and cannot exhaust delivery attempts. Capacity waits beyond that TTL still expire (default one hour).

Adds one indexed existence query only when no workspace exists and waking is allowed; live runtime delivery adds no I/O. No new queue, schema, environment variable or public API.

Thanks to @leonceaklin for the report and prior approach in zebra-pig/simple-agent-manager#17, independently reviewed against upstream lifecycle writers.

SAM idea and findings · task record.

Validation

  • pnpm lint — 22 tasks passed; two existing web warnings.
  • pnpm typecheck — 36 tasks passed (www reports its known baseline Astro template issue).
  • pnpm build — 18 tasks passed.
  • pnpm test — 38/39 package tasks passed. API: 1,083 passed / 3 skipped / 2 failed files; all 3 failures were 5-second timeouts in unchanged archive-sharding/default-capacity-pools tests. Both files passed alone with unchanged timeouts: 230/230. No unrelated timeout changes.
  • Discriminating pre-fix real-D1/ProjectData run: 16 tests collected, 8 expected failures / 8 passing controls, no collection or fixture failures. Startup cases fail with wake_refused / sleeping_snapshot_missing on unchanged baseline resolver.
  • Final regression: 17/17 new real-D1/ProjectData tests passed; three adjacent sleep/wake Workers suites 50/50 passed. Initial test-fixture findings were corrected and revalidated. Sonar reported duplicated test-claim wiring; consolidated four copies into a shared helper, with specialist re-review PASS and all five affected Workers suites passing (49/49).
  • SonarCloud quality gate passed on 00b18a4: 0.0% new duplication after shared-harness cleanup. E2E Smoke (mock and worker) passed.
  • Full CI passed: all 3 API shards, all 7 Workers shards, CLI, build/typecheck, lint, code quality and other packages. Explicitly dispatched with ci.yml on the branch while PR remains draft: run 44060303730 on head 00b18a4df5439d9bf3d5551d5e2c395d85b3a5fa.

Full CI on the updated head passed: run 44124710948 on 365a5a82dd82c6b34f76bb761b52c2b57fc5c371, with all API/Workers shards and CLI checks successful. Quick draft CI, E2E smoke (mock and worker), and SonarCloud also passed on this head. Local build passed again (18 tasks, 297 docs pages); API typecheck, secret-readback policy check, and all five affected Workers suites passed (49/49 tests on the full migrated D1/DO setup).

Final head b9e3667d506fb4b3bad6490b3a07beb6f167b833 changes only the task evidence record. Runtime, tests, architecture docs and deployment source are byte-identical to the fully tested and staged 365a5a82d (verified with git diff --exit-code). Final record formatting, diff checks and PR preflight/specialist evidence checks passed. Final-head draft CI 44156217905, E2E 44156217920 and SonarCloud passed. The draft CI deliberately skips the full test matrix; the manually dispatched full suite passed on the identical code head above.

Staging Verification

  • Staging deployment green.
  • Live app verified via Playwright.
  • Existing dashboard/projects/settings workflows verified.
  • Queued follow-up → runtime/first-turn readiness → delivery verified.
  • Infrastructure: N/A, Worker service change only; no VM agent, cloud-init, DNS, TLS or deployment changes.
  • UI: N/A, no UI changes.

Staging Verification Evidence

Deployment safety prerequisite #2841 merged at 16:18:26 UTC. Updated this branch from main to 365a5a82dd82c6b34f76bb761b52c2b57fc5c371; runtime fix unchanged. Resolved main's architecture-document extraction by retaining the startup note in architecture/durable-objects.md. The local secret-readback gate passes with only main's immediately masked legacy read and pinned open removal task.

Deployment 44147093759 passed, including the actual standard smoke-test step, on 365a5a82dd82c6b34f76bb761b52c2b57fc5c371. Cloudflare independently reported API version bdcadf88-b09f-49c9-993d-ffdd7b62e867 at 100%, annotated with that commit. Workload-identity sign-in as the manually configured staging2-test-user succeeded. Authenticated dashboard, projects and infrastructure settings loaded in Chromium; screenshots inspected.

One fresh-VM trial used a disposable Artifacts project and the user's explicit Claude OAuth configuration through the existing compute pool. No shared settings changed. Project 01M7NDYAY28R2GZ73VYPVVHKKC, task 01M7NDYCTJ8EQYE9D781ZRK5TB, chat f8bfae1e-1a5f-4114-a36b-389c4308902d, delivery 01M7NDYK1P8SK8PQVMFQJ18976:

UTC Observed behavior
18:57:44 Task queued/node_selection, workspace NULL.
18:57:45 One follow-up accepted and queued; no resend.
18:58–19:02 Conversation active while task waits for first VM; D1 shows no error or sleep snapshot.
19:02:18–56 Same task gains workspace, progresses delegated → in_progress.
19:04:05.703 Initial assistant response received.
19:04:10.977–11.065 Original queued follow-up response received, exactly once and after the initial response.
19:05 Session active/idle; task awaiting_followup, error NULL, no retained sleep snapshot.

The transcript stores streaming chunks as separate assistant rows; the verification reader joins those chunks before asserting each complete marker appears once and in order. An early screenshot taken at DOM-ready showed the loading spinner; subsequent settled desktop/mobile screenshots were inspected and show the delivered responses. These were test-harness corrections, with no product changes or repeated trial submission.

Evidence retained in the SAM project library, directory /engineering/2847/: pending screenshot 01M7NE52TM2YP9G557HWK3N2CE, desktop 01M7NEFEDHX8HTBW3AWYTSAKSP, mobile 01M7NEFH5KJ88EHYJSRPXJYFNK, timeline 01M7NEFKR515CBD47GEA6RAYRD, response JSON 01M7NEFPV6W5Q82PNFZ9TB5TTP.

Cleanup completed at 19:08:46: normal session stop removed the workspace, strict VM deletion returned 200, then disposable project deletion returned 200. Independent D1 readback confirms the disposable project/task/workspace/node absent and the pre-existing node preserved. Cleanup evidence 01M7NEKMDN9TSPWK14XR60SXBH. Lease release 44155480622 succeeded. Queue readback at 19:11:03 UTC showed holder NULL and the next task in its turn; normal early-release handoff sent.

End-to-End Verification

Data flow: persistVmTaskSession creates the workspace-less chat and binds tasks.chat_session_id before runner startup → projectData.acceptPromptDelivery persists transcript/inbox → claimDuePromptDeliveries / runPromptDeliveryClaim → DefaultVmPromptDeliveryAdapter → resolveVmPromptDeliveryTarget / isVmPromptTargetStarting → retry in the same inbox → normal capability/receipt delivery after runtime readiness.

The regression runs this path using real migrated D1 and ProjectData SQLite; only the remote VM transport is simulated. It checks every startup status, a checkpoint versus retained sleep history, genuine queued recovery through real context/claim logic (placement discovery substituted), unchanged diagnostics, project/chat mismatch, allowWake=false, retries beyond the attempt cap, bounded expiry and busy first-turn delivery.

Writer inventory: web submit-vm-task-effects.ts:65–80, reserved submission reserved-task-submission-storage.ts:25–47, MCP dispatch-tool.ts:451–481,610–615, ProjectOrchestrator scheduling.ts:483–518; /sam dispatch/retry and triggers use reserved storage. TaskRunner workspace-steps.ts:79–86 writes queued→delegated; session-linking.ts binds task/workspace; in-progress-transition.ts:43–75 commits in_progress after runtime setup. Recovery nullers and sleeping_at clearers were inspected. Project creator and runner identities may legitimately differ; the task's exact project/chat binding is authoritative.

Untested Gaps

The live changed flow was verified with one fresh VM. The hour-long TTL, genuine-sleep/recovery and diagnostic/identity matrix were exercised locally through real migrated D1/ProjectData rather than repeated paid live VMs. Full CI passed on both the implementation head and the safe-main merge head; final bookkeeping changes only the task evidence record.

Post-Mortem

What broke

Follow-ups sent during initial capacity wait failed with a sleep-snapshot error despite the conversation never having slept.

Root cause

The no-workspace resolver branch unconditionally entered ensureSessionRecovery. Present at upstream baseline e5c5aa4; no specific introducing commit is attributed here. loadRecoveryContext correctly requires retained sleep history, so the resolver confused two lifecycle states and converted expected startup into a terminal wake refusal.

Class of bug

Lifecycle classification by absence of a runtime, without distinguishing initial startup from retained sleep recovery.

Why it wasn't caught

Existing delivery tests covered running targets and actual sleep/wake paths, without a primary submission writer creating a workspace-less task/chat and a follow-up flowing through the durable inbox.

Process fix included in this PR

apps/api/tests/workers/vm-prompt-delivery-task-starting.test.ts enforces the existing rule 58/74 distinction through real D1 and the durable inbox, with a proven pre-fix failure and recovery/diagnostic controls. No additional standing-rule text is needed.

Post-mortem file

tasks/archive/2026-11-17-hold-first-vm-follow-ups.md.

Specialist Review Evidence

  • All local reviewers completed and findings addressed.
Reviewer Status Outcome
cloudflare-specialist PASS Independently verified predicates, indexes, lifecycle writers/nullers, recovery authority and query cost; no correctness findings.
test-engineer ADDRESSED Corrected versioned busy-response fixture; specific expiry state/immutable TTL assertions retained. Re-review PASS.
task-completion-validator PASS Research/checklist/real vertical slice aligned; required final CI and live staging evidence recorded above.
constitution-validator PASS No new hardcoded tunables, URLs or identifiers; source-size limits satisfied.
doc-sync-validator ADDRESSED Added startup-hold behavior to existing architecture paragraph; state/writer inventory updated. Re-review PASS.
security-auditor (2026-11-19) PASS No CRITICAL/HIGH. Identity scoping (project + chat), steer path, fail-closed retry and logging verified. MEDIUM (a stuck pre-run task holds follow-ups until the 1h delivery TTL) deferred with reason: queued/delegated tasks are failed by the stuck-task sweep after 20/31 min (DEFAULT_TASK_STUCK_QUEUED_TIMEOUT_MS/..._DELEGATED_...), which ends the hold; the hold never misdelivers. LOW (add snapshot.project_id) declined: session_snapshots.project_id is nullable (ON DELETE SET NULL), so the predicate would misclassify real sleep history as starting (rule 63); chat session IDs are unique. LOW (no per-session cap) unchanged by this PR.

CodeRabbit Review Evidence

Requested at ready (2026-11-19 02:54 UTC) via the coderabbit-review label. CodeRabbit replied Review rate limited at 02:58 UTC, ending the wait; no review arrived. Recorded and skipped under rule 25.

Exceptions

  • None. The earlier draft-only hold was lifted by Raphaël 2026-11-18.

Resume Notes (2026-11-19)

  • Merged current origin/main (no conflicts) and archived the task file. Runtime and tests unchanged from the staged candidate; 41/41 affected Workers tests and API typecheck pass after the merge.
  • First ready CI failed only the direct-dependency-evidence check (main removed root lucide-react in chore(deps): remove unused root lucide-react dependency #2894 after the earlier merge). Merged main again (609a9eba0); the check passes, and ready full CI 44451626587 SUCCESS including required Durable Object Workers.
  • Prior real staging run (first VM, then exactly one queued follow-up, cleanup) applies to unchanged code (Raphaël 2026-11-18: reuse prior real-runtime evidence).

Agent Preflight (Required)

  • Preflight completed before code changes

Classification

  • external-api-change
  • cross-component-change
  • business-logic-change
  • public-surface-change
  • docs-sync-change
  • security-sensitive-change
  • ui-change
  • infra-change

External References

Issue #2847 and fork PR #17 treated as untrusted evidence, independently reviewed. No external library/API change.

Codebase Impact Analysis

apps/api/src/services/vm-prompt-delivery-target.ts and vm-prompt-delivery-startup.ts read D1 startup ownership and return existing retry results to packages/project-data/src/do/prompt-delivery-runner.ts. Live runtime, recovery implementation and queue architecture are unchanged. Searched existing-work SAM ideas/tasks and all open upstream PR titles before implementation; no overlapping initial-start fix found.

Documentation & Specs

Updated the durable prompt paragraph in apps/www/src/content/docs/docs/architecture/durable-objects.md (moved from overview by main). No API/env/schema/spec change. Detailed writer inventory and acceptance evidence in the active task record.

Constitution & Risk Check

Principles X/XI: smallest existing-path fix, no new components or tunables. Retained sleep history preserves recovery; exact project/chat predicates prevent unrelated queued work from masking loss. Existing finite TTL and capped attempt ordinal bound retry work. Real SQL regression and negative controls discriminate this change.

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@github-actions
github-actions Bot requested a deployment to staging November 17, 2026 09:20 Abandoned
Keep pre-workspace task follow-ups in the durable inbox until startup is ready. Retained sleep history still delegates to recovery, while existing readiness retry and TTL policy bound the wait.\n\nThanks to leonceaklin for the diagnosis and prior approach in zebra-pig#17.
@simple-agent-manager

Copy link
Copy Markdown
Contributor Author

Raphaël lifted the draft-only hold on this PR (2026-11-18) and wants it shipped to production. Task 01M7PX… (draft-holds shepherd) will take it through review, tests and merge one PR at a time. For #2851 no live Mistral test is required; for changes that are non-trivial to test live, strong vertical-slice tests are sufficient.

@simple-agent-manager
simple-agent-manager Bot marked this pull request as ready for review November 19, 2026 02:53
@simple-agent-manager simple-agent-manager Bot added the coderabbit-review Trigger CodeRabbit review for opt-in PRs label Nov 19, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-19T02:54:01.234187Z
We couldn’t complete this review. Comment @codex review to try again.
b10b29f Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@raphaeltm

Copy link
Copy Markdown
Owner

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Action not completed

Review rate limited.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sonarqubecloud

Copy link
Copy Markdown

@simple-agent-manager
simple-agent-manager Bot merged commit b87f398 into main Nov 19, 2026
35 checks passed
@simple-agent-manager
simple-agent-manager Bot deleted the sam/fix-2847-hold-follow-08fj1d branch November 19, 2026 04:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

coderabbit-review Trigger CodeRabbit review for opt-in PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A follow-up sent while a task waits for a VM fails the conversation

1 participant