Skip to content

fix(gateway): settle terminal runs before session mutations - #166784

Merged
steipete merged 2 commits into
mainfrom
codex/stab-post-terminal-active-run
Oct 8, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/stab-post-terminal-active-run

Conversation

@steipete

@steipete steipete commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Running /compact from the Control UI right after a reply finishes fails with "has an active run; retry after it finishes". The UI calls sessions.compact directly. On main 9aa7455 the call is refused for 2.2–4.9 s after the chat final and the lifecycle end, on both the built-in OpenClaw runtime and the Codex runtime, with and without tools. A user who types /compact as soon as the answer appears sees an error for work that is already finished.

The same window applies to fork, rewind, and branch switching from a message, which share the active-run gate.

User Impact

  • /compact, fork, rewind, and branch switching right after a reply now succeed on the first attempt instead of erroring.
  • A genuinely active turn or accepted queued work is still refused, exactly as before.
  • Automatic session titles still apply after the first reply; they no longer block anything while the naming model call runs.

Why This Change Was Made

The window was background session-title generation. After the foreground reply released, the title job acquired a session work admission and held it for the whole naming model call, and compaction counted that admission as an active run. Naming only patches metadata through the title writer, which already checks the exact session identity and existing name before writing, so it does not need a turn admission. Title generation now holds no session lease. It still waits for turn.released before starting and keeps the Gateway shutdown custody that runWithGatewayIndependentRootWorkContinuation provides. This also subsumes #162689: rollover can no longer drain a title lease because none exists, and that PR's rollover regression still passes unchanged.

Terminal publication can also legitimately precede the last transcript writes and owner cleanup of a finished run. A small shared helper, waitForTerminalSessionRunSettlement, handles this. It captures only the owners that have already published a terminal outcome: chat runs with an observed terminal, plus committed reply operations, including retained failed replies that still own cleanup. It awaits their existing settlement promises within the existing 15 s session-admission budget, outside the lifecycle locks. Any competing admission or nonterminal owner is refused immediately, so a live turn is never waited on. The caller's own in-band execution is excluded by exact identity while other terminal writers are still awaited. Compaction, fork, rewind, and branch switching call it. The ownership, active-run, worker-inference, and queued-work checks that follow are unchanged. Reset, delete, and archive keep their existing drains.

Known residual: the chat final event is published a few milliseconds before the run's terminal bookkeeping is recorded. A client that calls sessions.compact within about 70 ms of the final can still get one "active run" refusal; a retry about 100 ms later succeeds. That ordering is tracked as a follow-up, not hidden here.

This is complementary to #166163, which changed the in-band /compact chat command's handling of a truly active turn.

Evidence

Live (dev Gateway built from this head, fresh state, real OpenAI provider; sessions.compact polled every 100 ms from the chat final):

                 main 905a74d1 / 9aa74552                 this head
main  plain      refused for ~2.8 s (6 attempts)           one refusal at 63 ms, accepted on retry
main  tool       refused for ~2.2 s                        one refusal, accepted on retry
codex plain      refused for ~4.1 s (8 attempts)           one refusal at 68 ms, accepted on retry
codex tool       refused for ~4.9 s                        one refusal, accepted on retry
compact during a live turn (sleep 12)                      refused in 77 ms (built-in) / 41 ms (Codex), turn keeps running

Tests (--maxWorkers=1, isolated TMPDIR):

session-run-settlement.test.ts                      10 passed   26.5 s
sessions-compact.settlement.test.ts (+rewind)       4 passed    21.3 s
chat-send-title-preparation.test.ts                 5 passed    47.2 s
server.chat-dashboard-title-rollover.test.ts (#162689)  1 passed  22.8 s
compaction/rewind/admission/title sibling set       188 passed, 9 files, 175.4 s

With only the production files restored to base, the regressions fail (8 failed / 6 passed, 49.4 s). That includes both review findings: the live-turn wait and the skipped terminal writer during an in-band command. Types, scoped lint, format, docs, and the import-cycle check (0) pass. Autoreview is clean through P2. The earlier CI failure in subagent-control.test.ts was a main fixture issue fixed separately by #166807.

Production +129/-53, tests +496/-20, docs +2 (docs/concepts/compaction.md).

Let manual compaction and history edits join existing terminal writers with a bounded wait outside lifecycle locks. Stop retaining session execution admission for metadata-only chat title generation. Preserve active and queued work exclusion and revalidate session ownership after settlement.
@clawsweeper

clawsweeper Bot commented Oct 7, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Oct 7, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 7, 2026, 8:30 PM ET / October 8, 2026, 00:30 UTC (Revision 2).

ClawSweeper review

What this changes

The PR lets compaction, fork, rewind, and branch switching wait for completed reply cleanup while removing background session naming from the active-turn gate.

Merge readiness

✅ Ready for maintainer review

This remains a useful fix: current main still lets background title generation block session mutations. No actionable introduced defect was found, and the recorded live evidence supports the changed behavior.

Priority: P2
Reviewed head: 186481a249257fa558b2b5f8228d8b961a3bf8a6

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused lifecycle repair with relevant live observations, discriminating regressions, and no blocking correctness finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The recorded real-provider Gateway run exercises sessions.compact after chat final and shows the multi-second admission window removed while a live turn is promptly refused. Source and regression inspection support captured cleanup and unchanged title persistence guards; no stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The recorded real-provider Gateway run exercises sessions.compact after chat final and shows the multi-second admission window removed while a live turn is promptly refused. Source and regression inspection support captured cleanup and unchanged title persistence guards; no stored-data contract changes require migration proof.
Evidence reviewed 9 items Verified introduced scope: Reviewed the merge-base-to-head patch and corresponding current modules at the pinned original PR head; base-branch drift was not attributed to this PR.
Current main still needs the fix: Fetched main still acquires session admission around chat title generation and enters compaction's lifecycle gate without the new terminal-owner settlement step. The merged rollover repair does not resolve this remaining post-reply window.
Captured settlement preserves live-work exclusion: The helper immediately rejects competing admission and nonterminal owners, filters by session and agent, excludes the exact in-band execution, and waits on existing captured cleanup promises within the existing 15-second budget. This is an OpenClaw lifecycle contract; its correctness does not depend on Codex harness internals.
Findings None None.
Security None None.

How this fits together

Gateway session methods receive requests to compact or edit conversation history. They coordinate with reply writers and session lifecycle ownership before changing transcripts, while automatic naming updates session metadata separately.

flowchart TD
  A[Session mutation request] --> B[Check competing live work]
  B -->|Live work| C[Refuse with retry guidance]
  B -->|Completed writers| D[Wait for captured cleanup]
  D --> E[Recheck ownership under lifecycle lock]
  E --> F[Compact or edit history]
  G[Background title generation] --> H[Guarded metadata update]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +76, Tests +476, Docs +2. Total +554 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 4 129 53 +76
Tests 3 496 20 +476
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 627 73 +554

Review metrics

Metric Value Why it matters
Production versus regression growth production net +76 lines; tests net +476 lines Production growth has a stated purpose: one shared bounded settlement path for four session mutation methods, backed by lifecycle regressions.

Technical review

Best possible solution:

Keep terminal cleanup with its existing owners and allow history mutations only after settlement and fresh lifecycle checks, with metadata-only naming independent of turn admission.

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

Yes: request sessions.compact immediately after a first reply while background naming is pending; current-main source establishes the conflicting admission, and the body records real before/after runs. This reviewer did not execute the reproduction.

Is this the best way to solve the issue?

Yes: removing metadata-only admission and joining captured terminal owners uses existing lifecycle contracts without adding a parallel owner or changing live-turn policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4f4d61a73b5e.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The fix removes a short post-reply refusal window for session operations while preserving active-turn exclusion.
  • 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. Sufficient (live_output): The recorded real-provider Gateway run exercises sessions.compact after chat final and shows the multi-second admission window removed while a live turn is promptly refused. Source and regression inspection support captured cleanup and unchanged title persistence guards; no stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The recorded real-provider Gateway run exercises sessions.compact after chat final and shows the multi-second admission window removed while a live turn is promptly refused. Source and regression inspection support captured cleanup and unchanged title persistence guards; no stored-data contract changes require migration proof.

Evidence

What I checked:

  • Verified introduced scope: Reviewed the merge-base-to-head patch and corresponding current modules at the pinned original PR head; base-branch drift was not attributed to this PR. (186481a24925)
  • Current main still needs the fix: Fetched main still acquires session admission around chat title generation and enters compaction's lifecycle gate without the new terminal-owner settlement step. The merged rollover repair does not resolve this remaining post-reply window. (src/gateway/server-methods/chat-send-background.ts, 4f4d61a73b5e)
  • Captured settlement preserves live-work exclusion: The helper immediately rejects competing admission and nonterminal owners, filters by session and agent, excludes the exact in-band execution, and waits on existing captured cleanup promises within the existing 15-second budget. This is an OpenClaw lifecycle contract; its correctness does not depend on Codex harness internals. (src/gateway/server-methods/session-run-settlement.ts:28, 186481a24925)
  • Mutation guards remain after the wait: Compaction rechecks request authority, session identity, lifecycle revision, active owners, worker inference, and queued work under lifecycle custody. The shared history-edit handler likewise rechecks session identity and commit authority before delegating writes. (src/gateway/server-methods/sessions-compact.ts:197, 186481a24925)
  • Title writer retains its independent guard: Background naming retains Gateway shutdown custody and turn-release ordering. The unchanged title writer patches only a matching session identity without an explicit name; the patch introduces no stored schema, serialized-format, config, or migration change. (src/gateway/dashboard-session-title.ts:333, 186481a24925)
  • Recorded production-path proof: The complete supplied PR body records a fresh-state dev Gateway using a real OpenAI provider and sessions.compact requests following chat final. Main refused for 2.2–4.9 seconds; the candidate accepted on the next 100-ms retry after one early refusal. During a live turn, refusal returned in 77 ms for the built-in runtime and 41 ms for Codex while the turn continued. The maintainer-authored scope explicitly retains the roughly 70-ms final-publication ordering window as follow-up work. (186481a24925)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • ericcaiwx-star: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (1 earlier review cycle)
  • reviewed 2026-10-07T22:53:30.340Z sha f2bddda :: needs maintainer review before merge. :: none

@steipete
steipete merged commit eacaa1b into main Oct 8, 2026
119 of 120 checks passed
@steipete
steipete deleted the codex/stab-post-terminal-active-run branch October 8, 2026 00:42
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 8, 2026
…#166784)

* fix(gateway): settle terminal runs before session mutations

Let manual compaction and history edits join existing terminal writers with a bounded wait outside lifecycle locks. Stop retaining session execution admission for metadata-only chat title generation. Preserve active and queued work exclusion and revalidate session ownership after settlement.

* fix(gateway): scope terminal settlement to captured owners
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

1 participant