Skip to content

fix(runtime): settle session work before fresh preparation - #522

Merged
steipete merged 1 commit into
mainfrom
fix/exact-session-retirement
Sep 16, 2026
Merged

steipete merged 1 commit into
mainfrom
fix/exact-session-retirement

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

Fresh-session preparation could acknowledge a reset while an earlier turn was still writing the same record. That late write could erase the reset or restore the old backend identity. A failed cleanup could also leave an unusable owner available for reuse, or be forgotten when preparation was retried.

The public prepareFreshSession({ handle }) API already landed in #596. This PR now focuses on completing its lifecycle guarantee:

  • Admit complete turns and preparation in order for each exact session record. Different records remain concurrent, and controls still reach the active turn.
  • Cancel and settle previously submitted turns before publishing fresh-session intent. A queued cancellation never starts its prompt or cancels its predecessor.
  • Unpublish owners before destructive cleanup, retain failed cleanup for retry, and coalesce concurrent cleanup attempts. Preparation rejects while the original owner still cannot be finalized.
  • Cancel queued work on ordinary close while preserving its existing early-return and resumable-session behavior. Remote discard retains its protocol requirement; fresh preparation does not require remote close or delete native history.

The original contribution's completion and strict-finalization work informed this repair. It preserves the accepted object-shaped API and uses the valid identical-launch restart control already on main, replacing the earlier process fixture that could pass solely because launch identity changed. Thanks @vincentkoc.

Reproductions

The regression cases failed before their fixes for the intended reasons:

active preparation: acknowledged before the active turn finalized
multiple submissions: only 1 of 2 turns finalized before preparation returned
failed idle cleanup: retry lost its session update
cleanup retry: preparation falsely succeeded while owner finalization still failed
ordinary close: a queued prompt still ran (2 prompts instead of 1)

Validation

  • Full pnpm run check and pnpm run check:docs passed on an isolated Linux runner.
  • All 117 focused runtime, manager, and session-context tests passed; regression cases include concurrent records, responsive active controls, queued cancellation, failed cleanup retries, and restart identity.
  • Independent structured review: no actionable P0–P2 findings (confidence 0.96).
  • Source-blind public-runtime proof passed against real stdio ACP subprocesses and file storage. Active plus queued preparation returned only after both turns were cancelled; queued text was suppressed; fresh identity remained stored. Ordinary close retained its permitted early return, both prior turns later cancelled, and the record remained closed.
  • Real Codex adapter smoke passed on the final build: preparation returned after cancelled/cancelled in 1,268 ms, then a runtime restart produced a different backend under the same acpx record and delivered fresh synthetic text. A separate real native-history control successfully resumed the retired backend and recalled its synthetic marker; that unchanged-history proof was reused in the final focused rerun.
  • All live tests used synthetic state. Owned runtimes and child processes were stopped; synthetic state was cleaned up.

This repair changes production by +70 net lines, tests by +210, and docs/changelog by +3. The added admission and retry state is confined to the existing runtime manager; the submitted tests are substantially smaller than the original PR's process harness.

@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 27, 2026
@clawsweeper

clawsweeper Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 16, 2026, 5:13 AM ET / 09:13 UTC (Revision 4).

ClawSweeper review

What this changes

Serializes runtime turns per session record and waits for cancellation and cleanup before recording fresh-session intent, with retry handling, regression tests, and updated documentation.

Merge readiness

✅ Ready for maintainer review

Keep open as a focused, still-needed lifecycle repair. The earlier API and restart-fixture blockers are resolved, and the reviewed diff introduces no blocking correctness finding.

Priority: P2
Reviewed head: 707a72b42a9d6e47ead09b93f45acfe31899f453

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with relevant regression coverage, reported production-path validation, and no remaining actionable finding.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The member-authored PR is exempt from the external-contributor proof gate. Its supplied real stdio/file-store and Codex observations nevertheless exercise the changed manager through public preparation, cancellation, and restart, reporting settled turns and preserved fresh identity.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The member-authored PR is exempt from the external-contributor proof gate. Its supplied real stdio/file-store and Codex observations nevertheless exercise the changed manager through public preparation, cancellation, and restart, reporting settled turns and preserved fresh identity.
Evidence reviewed 8 items Applicable repository policy: Read the complete root AGENTS.md, VISION.md, and CONTRIBUTING.md. No additional ancestor policy applies to the five changed paths, and no .agents/maintainer-notes directory exists. Applied the compatibility, lifecycle, documentation, and regression-evidence guidance.
Verified introduced scope: Read the complete local introduced diff, including patches truncated in the supplied context. Changes are confined to the runtime manager, two test files, session-control documentation, and changelog.
Current main still needs the lifecycle repair: Main delegates preparation directly to closeRuntimeSession, requests cancellation without awaiting complete turn finalization, and suppresses retained-owner cleanup errors. The branch adds per-record completion tracking and retryable cleanup at those production paths.
Findings None None.
Security None None.

How this fits together

The embedded acpx runtime manages ACP agent connections and persisted session records for host applications. Turn submission, cancellation, and fresh-session preparation pass through its session manager before reaching the adapter and session store.

flowchart TD
  A[Embedding host] --> B[Per-record task queue]
  B --> C[Run or cancel turn]
  C --> D[ACP agent connection]
  D --> E[Finalize session work]
  B --> F[Prepare fresh session]
  E --> F
  F --> G[Persist reset intent]
  G --> H[Next ensure creates fresh session]
Loading

Before merge

None.

Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test growth production +70 net lines; tests +210; docs/changelog +3 The added task admission and cleanup-retry state is confined to the existing manager and supported by focused lifecycle regressions.

Technical review

Best possible solution:

Preserve the accepted API while making fresh preparation acknowledge only settled session work and successful local cleanup, without discarding native history.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes the race: main can acknowledge preparation before an active turn finishes writing its record. The supplied before-fix failures and focused regressions support that path; this read-only review did not execute it.

Is this the best way to solve the issue?

Yes. The patch repairs the existing manager's completion and cleanup boundaries while preserving the accepted public API, ordinary-close behavior, and persisted reset format.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 420157a762a7.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The member-authored PR is exempt from the external-contributor proof gate. Its supplied real stdio/file-store and Codex observations nevertheless exercise the changed manager through public preparation, cancellation, and restart, reporting settled turns and preserved fresh identity.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 session-state: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This repairs a bounded embedded-runtime cancellation and reset-persistence race.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The member-authored PR is exempt from the external-contributor proof gate. Its supplied real stdio/file-store and Codex observations nevertheless exercise the changed manager through public preparation, cancellation, and restart, reporting settled turns and preserved fresh identity.

Evidence

What I checked:

  • Applicable repository policy: Read the complete root AGENTS.md, VISION.md, and CONTRIBUTING.md. No additional ancestor policy applies to the five changed paths, and no .agents/maintainer-notes directory exists. Applied the compatibility, lifecycle, documentation, and regression-evidence guidance. (AGENTS.md, 707a72b42a9d)
  • Verified introduced scope: Read the complete local introduced diff, including patches truncated in the supplied context. Changes are confined to the runtime manager, two test files, session-control documentation, and changelog. (src/runtime/engine/manager.ts:536, 707a72b42a9d)
  • Current main still needs the lifecycle repair: Main delegates preparation directly to closeRuntimeSession, requests cancellation without awaiting complete turn finalization, and suppresses retained-owner cleanup errors. The branch adds per-record completion tracking and retryable cleanup at those production paths. (src/runtime/engine/manager.ts:1890, 420157a762a7)
  • Prior API decision resolved: GitHub confirms feat: expose installed agents and fresh session preparation #596 merged on 2026-09-16. It established the existing object-shaped API; the September 16 maintainer update explicitly accepts this repair's lifecycle scope and supersedes the earlier API blocker. (src/runtime.ts:339, be3239fc80e9)
  • Restart control and cancellation coverage: The public-runtime test creates the seed through ensureSession, verifies ordinary restart retains its backend identity under identical launch settings, then checks preparation after zero, one, or two submitted turns before verifying fresh creation. Manager regressions cover independent records, active controls, queued cancellation, and repeated cleanup failure. (test/runtime.test.ts:1019, 707a72b42a9d)
  • Recorded production-path observations: The complete captured body reports real stdio ACP subprocess/file-store validation and a final-build Codex run: preparation returned after both turns cancelled in 1,268 ms, restart retained the acpx record while changing backend identity, and fresh synthetic text succeeded. A separate native-history control resumed the retired backend. The September 16 maintainer comment corroborates this evidence. These are supplied observations, not reviewer-executed tests; captured context sourceRevision is 78bb9cf1f2bfed003ff02c1de0ea54cc6b16aa220483a3e2a5fef4d83d95937b.

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-08-27T03:25:22.421Z sha 865a79e :: needs maintainer review before merge. :: none
  • reviewed 2026-09-02T15:11:29.080Z sha 865a79e :: found issues before merge. :: [P2] Create the seed through the same launch identity
  • reviewed 2026-09-14T12:57:37.121Z sha 865a79e :: blocked before merge. :: [P2] Create the seed through the same launch identity

@steipete

Copy link
Copy Markdown
Contributor

Maintainer triage: this remains a product/API decision because it introduces public prepareFreshSession(handle) semantics. There is also a concrete problem with the supplied restart proof.

test/runtime-retirement-process.ts seeds a record with agentCommand: "fixture" and no agentArgv, while the ensure process resolves fixture to [process.execPath, path.resolve(mockAgentPath)]. The existing reuse policy rejects a command/argv mismatch independently of retirement. Consequently, the three-process fixture can allocate a fresh backend even if the retirement phase is omitted; a changed backend UUID alone does not prove the new marker works.

The meaningful control is identical launch identity in every process: create the original record through real ensure, prove restart without retirement keeps the backend identity, then prove retirement changes that identity while preserving the intended record identity. This is a source-supported assessment, not a claim that I executed the retirement scenario.

Recommendation to the orchestrator: keep the decision with Peter until the retirement API, treatment of existing handles, and persistence guarantee are selected; the current proof should not be treated as satisfying that guarantee. No implementation or contributor changes are requested by this triage pass.

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 session-state 🚨 Merging this PR could lose, corrupt, stale, or mis-associate session or agent state. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 2, 2026
Serialize per-record turns and settle prior work before durable reset. Keep failed owner cleanup retryable, preserve ordinary close behavior, and cover real runtime cancellation, restart, and recovery.

Co-authored-by: Vincent Koc <[email protected]>
@steipete
steipete force-pushed the fix/exact-session-retirement branch from 865a79e to 707a72b Compare September 16, 2026 09:07
@steipete steipete self-assigned this Sep 16, 2026
@steipete steipete changed the title fix(runtime): retired sessions start fresh after restart fix(runtime): settle session work before fresh preparation Sep 16, 2026
@steipete
steipete marked this pull request as ready for review September 16, 2026 09:08
@steipete

Copy link
Copy Markdown
Contributor

Maintainer update: #596 already established the object-shaped fresh-session API. This rewrite keeps that accepted public contract and completes its cancellation, finalization, and cleanup-retry guarantees in the existing runtime manager. Same-record work is serialized; different records remain concurrent. Ordinary close retains its existing early-return/resume behavior.

The former API-absence blocker is superseded. The earlier false-positive restart fixture is replaced by the identical-launch control already on main, plus active/queued-turn and cleanup-failure regressions. The updated body includes observed failures before the fix, passing isolated Linux checks, independent review, and source-blind real Codex cancellation/restart/native-history evidence. Thanks @vincentkoc for the original retirement and finalization work.

@steipete
steipete requested a review from a team as a code owner September 16, 2026 09:08
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 Merging this PR could lose, corrupt, stale, or mis-associate session or agent state. labels Sep 16, 2026
@steipete
steipete merged commit 53177fc into main Sep 16, 2026
20 checks passed
@steipete
steipete deleted the fix/exact-session-retirement branch September 16, 2026 09:15
@steipete

Copy link
Copy Markdown
Contributor

Landed as 53177fc from reviewed head 707a72b.

Validation: 117 focused runtime/manager/session-context tests; full isolated Linux pnpm run check and pnpm run check:docs; independent review with no actionable findings; and green exact-head CI, including Node 22/24/26 and mutation tests. ClawSweeper's refreshed review also found no blockers.

Source-blind proof exercised real stdio/file-store cancellation, queued work, cleanup failure/retry, and restart. Real Codex preparation returned after explicit cancellation, and restart produced a new backend under the same acpx record with successful text output. Separate native-history proof reopened the retired backend and recalled its synthetic marker. All task-owned test processes and state were cleaned up; main is synchronized and clean.

Thanks @vincentkoc for the original contribution.

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

Labels

P2 Normal priority bug or improvement with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants