Skip to content

fix(agents): keep durable turns committing when other sessions are stale - #160153

Merged
obviyus merged 2 commits into
openclaw:mainfrom
ericcaiwx-star:codex/fix-156425-context-engine-finalize-drain
Sep 29, 2026
Merged

obviyus merged 2 commits into
openclaw:mainfrom
ericcaiwx-star:codex/fix-156425-context-engine-finalize-drain

Conversation

@ericcaiwx-star

@ericcaiwx-star ericcaiwx-star commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Related: #156425

What Problem This Solves

Fixes: a successfully accepted durable context-engine turn can remain uncommitted when unrelated sessions already fill the global outbox drain window.

User Impact

The accepted turn now commits in the same turn and can start post-turn maintenance even when other sessions have stale admitted rows. Ready turns from idle sessions still receive a bounded retry opportunity; this does not change the broader orphan-recovery policy tracked in #135628.

Why This Change Was Made

Accepted-turn finalization previously used one global drain. Sixteen older unrelated sessions could consume its full budget before the newly accepted row was considered.

Finalization now drains the accepted session first. It then offers one bounded retry to each of up to 16 other pending sessions, preserving the existing cross-session recovery opportunity without immediately retrying a failed row from the accepted session. Maintenance remains coalesced once per committed session after draining finishes.

Evidence

  • Current-main pre-fail at c0196aec9eb22dde60d1d36616d9d8e6d41fcbd4: with 16 unrelated admitted sessions ahead of one accepted ready turn, the accepted session's commitTurn was called 0 times (expected 1).
  • Exact-head regression at d8f58c0df5533ea39fb06c57d45ba8df37f539c4: the combined case commits the accepted session first and then commits a ready turn from another session while 15 unrelated admitted sessions are also queued.
  • Owner and sibling tests: node scripts/run-vitest.mjs src/agents/harness/context-engine-turn-attempt.test.ts src/agents/harness/context-engine-turn-outbox.test.ts passed 37/37 tests in 39.02 seconds.
  • Existing failure semantics remain intact: the sibling suite still verifies a failed current-session commit stays queued with one attempt before the next run.
  • Real Gateway proof: a temporary on-disk context-engine plugin with durable transcript semantics and foreground maintenance ran through chat.send and agent.wait; the redacted verdict was {"terminalStatus":"ok","lifecycle":["maintain","commit","maintain"]}. The accepted turn reached plugin commitTurn, then post-turn maintain, with no production credentials or external targets.
  • Changed-file checks passed against upstream/main, including formatting, core and test type checks, lint, database guards, import-cycle checks, and repository ratchets.
  • Test-audit authoring gate: the regression owns the observable finalization-order and cross-session-retry contract, fails for the original starvation mechanism, is not duplicated by existing coverage, and adds no test-only production seam.
  • Independent AutoReview found no P0-P2 issue in the final working-tree repair; its only P1 was explicitly index-only and identified the superseded staged version that lacked the bounded retry loop.
  • Local focused-test wall time: 39.02 seconds on macOS arm64 with Node 26.7.0 and pnpm 12.5.1. Exact-head CI time is pending.

Isolated Gateway proof on an Anthropic route

A real Gateway (openclaw --profile <isolated> gateway run, task-owned home/state/config, loopback port) served openclaw agent --session-key ... --json turns. The default model was an anthropic-messages provider with id anthropic pointed at a local mock server (synthetic key, no real credentials), with contextPruning.mode: "cache-ttl" so each successful turn also writes the openclaw.cache-ttl marker. The context engine was an on-disk plugin declaring atomic-idempotent-v1 and recording every commitTurn in its own JSONL store. To reproduce the reported outbox state, 16 unrelated sessions were started on turns the mock never answered, and the Gateway was SIGKILLed mid-turn. That left 16 admitted outbox rows. The Gateway was then restarted and one new Anthropic turn was sent. Baseline: this branch with only context-engine-turn-attempt.ts reverted to origin/main (which already contains the #156611 anchor fix). Candidate: d4912a099927.

Scenario Baseline Candidate
Clean state, Anthropic route committed committed
Clean state, OpenAI chat-completions route (control) committed committed
Clean state, provider returns HTTP 400 (control) not committed, no outbox row not committed, no outbox row
16 stale admitted sessions, new Anthropic turn ok reply, not committed; its row stays ready, attempt_count 0 ok reply, committed (user,assistant); row removed
16 stale sessions, provider returns HTTP 400 (control) not committed, no outbox row not committed, no outbox row

In both runs the 16 stale rows stayed admitted/0, and the agent database user_version was unchanged (23). The clean-state rows show this is not a duplicate of #156611: on current main the anchor fix already commits Anthropic turns, and the remaining failure is the unscoped finalize drain.

After merging current origin/main, the owner and sibling tests passed again: context-engine-turn-attempt.test.ts and context-engine-turn-outbox.test.ts, 37/37.

No overlap with Pash/Sarah changes: neither has commits on the changed files.

Thanks to @ericcaiwx-star for the fix and to @Kaspnov for the detailed report and outbox analysis.

Not tested: a third-party production context-engine deployment or real user data. The Gateway proof used a local loopback provider, an ephemeral plugin, synthetic transcript data, and no credentials.

@clawsweeper

clawsweeper Bot commented Sep 28, 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 P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 28, 2026, 10:36 PM ET / September 29, 2026, 02:36 UTC (Revision 3).

ClawSweeper review

What this changes

The PR changes durable context-engine turn finalization to commit the accepted session first, then offer bounded retries to other pending sessions before maintenance runs.

Merge readiness

✅ Ready for maintainer review

Current main still has the reported starvation path. The branch has a focused regression test and credible Gateway before-and-after proof; I found no blocking patch defect.

Priority: P1
Reviewed head: d4912a099927e24dd567d005c452617b19ea018d

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A narrow owner-level repair has credible Gateway before-and-after proof and regression coverage, with no blocking finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The changed finalization owner was exercised through a real isolated Gateway with an on-disk durable context-engine plugin: after 16 stale sessions blocked the baseline, the candidate committed the new turn and removed its ready row. Cross-session retry is covered by the focused regression; no stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The changed finalization owner was exercised through a real isolated Gateway with an on-disk durable context-engine plugin: after 16 stale sessions blocked the baseline, the candidate committed the new turn and removed its ready row. Cross-session retry is covered by the focused regression; no stored-data contract changes.
Evidence reviewed 7 items Introduced finalization order: The introduced patch scopes the first drain to the accepted session, then lists up to 16 other pending sessions and gives each one bounded attempt.
Current main remains affected: Current main still makes one unscoped finalization drain. The outbox selects the oldest pending sessions with a limit of 16, so older admitted rows can consume the window before a newly ready session.
Outbox selection contract: Pending sessions are ordered by oldest enqueue sequence; the drain charges its budget before asking whether a row can commit, while admitted rows cannot commit.
Findings None None.
Security None None.

How this fits together

The agent harness records accepted turns in a per-agent SQLite outbox. Finalization sends ready turns to the selected context-engine plugin and schedules maintenance after acknowledged commits.

flowchart LR
  A[Accepted agent turn] --> B[Durable outbox]
  B --> C[Drain accepted session]
  C --> D[Retry other sessions]
  D --> E[Context engine commit]
  E --> F[Post-turn maintenance]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +24, Tests +65. Total +89 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 39 15 +24
Tests 1 66 1 +65
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 105 16 +89

Review metrics

Metric Value Why it matters
Production and test growth production +39/−15 lines; tests +66/−1 lines The added production flow preserves cross-session retries after prioritizing the accepted session.

Technical review

Best possible solution:

Land the session-scoped finalization behavior with its regression coverage; keep global orphan recovery tracked separately in #135628.

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

Yes. The PR records a current-main Gateway baseline with 16 stale admitted sessions and a new ready turn that remains uncommitted; current source supports that mechanism.

Is this the best way to solve the issue?

Yes. The repair stays with the existing finalization and outbox owners, prioritizes the accepted turn, and retains a bounded opportunity for other sessions.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 4187710037fc.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: On current main, stale sessions can prevent accepted durable agent turns from committing during their own finalization.
  • merge-risk: 🚨 session-state: The patch changes durable-turn commit ordering across sessions, where an ordering error could leave accepted context state queued.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The changed finalization owner was exercised through a real isolated Gateway with an on-disk durable context-engine plugin: after 16 stale sessions blocked the baseline, the candidate committed the new turn and removed its ready row. Cross-session retry is covered by the focused regression; no stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The changed finalization owner was exercised through a real isolated Gateway with an on-disk durable context-engine plugin: after 16 stale sessions blocked the baseline, the candidate committed the new turn and removed its ready row. Cross-session retry is covered by the focused regression; no stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • Josh Lehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • WhatsSkiLL: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: 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 (2 earlier review cycles)
  • reviewed 2026-09-28T05:30:22.362Z sha 63b1db898160183475355bdc2a6e81d4999c1509 :: needs real behavior proof before merge. :: [P1] Preserve retries for ready turns in other sessions
  • reviewed 2026-09-28T06:12:09.367Z sha d8f58c0 :: needs maintainer review before merge. :: none

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Sep 28, 2026
@ericcaiwx-star
ericcaiwx-star force-pushed the codex/fix-156425-context-engine-finalize-drain branch from 63b1db8 to d8f58c0 Compare September 28, 2026 06:03
@ericcaiwx-star
ericcaiwx-star marked this pull request as ready for review September 28, 2026 06:04
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 28, 2026
@obviyus
obviyus merged commit 5360b70 into openclaw:main Sep 29, 2026
248 checks passed
@obviyus

obviyus commented Sep 29, 2026

Copy link
Copy Markdown
Collaborator

Landed in 5360b70. Thanks @ericcaiwx-star for the fix, and @Kaspnov for the detailed report and outbox analysis that pinned down the unscoped finalize drain.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 29, 2026
…ale (openclaw#160153)

Related: openclaw#156425

## What Problem This Solves

Fixes: a successfully accepted durable context-engine turn can remain uncommitted when unrelated sessions already fill the global outbox drain window.

## User Impact

The accepted turn now commits in the same turn and can start post-turn maintenance even when other sessions have stale admitted rows. Ready turns from idle sessions still receive a bounded retry opportunity; this does not change the broader orphan-recovery policy tracked in openclaw#135628.

## Why This Change Was Made

Accepted-turn finalization previously used one global drain. Sixteen older unrelated sessions could consume its full budget before the newly accepted row was considered.

Finalization now drains the accepted session first. It then offers one bounded retry to each of up to 16 other pending sessions, preserving the existing cross-session recovery opportunity without immediately retrying a failed row from the accepted session. Maintenance remains coalesced once per committed session after draining finishes.

## Evidence

- Current-main pre-fail at `a709790e7808e5d833fc75a73c6614ab364f943e`: with 16 unrelated admitted sessions ahead of one accepted ready turn, the accepted session's `commitTurn` was called 0 times (expected 1).
- Exact-head regression at `d8f58c0df5533ea39fb06c57d45ba8df37f539c4`: the combined case commits the accepted session first and then commits a ready turn from another session while 15 unrelated admitted sessions are also queued.
- Owner and sibling tests: `node scripts/run-vitest.mjs src/agents/harness/context-engine-turn-attempt.test.ts src/agents/harness/context-engine-turn-outbox.test.ts` passed 37/37 tests in 39.02 seconds.
- Existing failure semantics remain intact: the sibling suite still verifies a failed current-session commit stays queued with one attempt before the next run.
- Real Gateway proof: a temporary on-disk context-engine plugin with durable transcript semantics and foreground maintenance ran through `chat.send` and `agent.wait`; the redacted verdict was `{"terminalStatus":"ok","lifecycle":["maintain","commit","maintain"]}`. The accepted turn reached plugin `commitTurn`, then post-turn `maintain`, with no production credentials or external targets.
- Changed-file checks passed against `upstream/main`, including formatting, core and test type checks, lint, database guards, import-cycle checks, and repository ratchets.
- Test-audit authoring gate: the regression owns the observable finalization-order and cross-session-retry contract, fails for the original starvation mechanism, is not duplicated by existing coverage, and adds no test-only production seam.
- Independent AutoReview found no P0-P2 issue in the final working-tree repair; its only P1 was explicitly index-only and identified the superseded staged version that lacked the bounded retry loop.
- Local focused-test wall time: 39.02 seconds on macOS arm64 with Node 26.7.0 and pnpm 12.5.1. Exact-head CI time is pending.

### Isolated Gateway proof on an Anthropic route

A real Gateway (`openclaw --profile <isolated> gateway run`, task-owned home/state/config, loopback port) served `openclaw agent --session-key ... --json` turns. The default model was an `anthropic-messages` provider with id `anthropic` pointed at a local mock server (synthetic key, no real credentials), with `contextPruning.mode: "cache-ttl"` so each successful turn also writes the `openclaw.cache-ttl` marker. The context engine was an on-disk plugin declaring `atomic-idempotent-v1` and recording every `commitTurn` in its own JSONL store. To reproduce the reported outbox state, 16 unrelated sessions were started on turns the mock never answered, and the Gateway was SIGKILLed mid-turn. That left 16 `admitted` outbox rows. The Gateway was then restarted and one new Anthropic turn was sent. Baseline: this branch with only `context-engine-turn-attempt.ts` reverted to `origin/main` (which already contains the openclaw#156611 anchor fix). Candidate: `d4912a099927`.

| Scenario | Baseline | Candidate |
| --- | --- | --- |
| Clean state, Anthropic route | committed | committed |
| Clean state, OpenAI chat-completions route (control) | committed | committed |
| Clean state, provider returns HTTP 400 (control) | not committed, no outbox row | not committed, no outbox row |
| 16 stale `admitted` sessions, new Anthropic turn | `ok` reply, **not committed**; its row stays `ready`, `attempt_count 0` | `ok` reply, **committed** (`user,assistant`); row removed |
| 16 stale sessions, provider returns HTTP 400 (control) | not committed, no outbox row | not committed, no outbox row |

In both runs the 16 stale rows stayed `admitted`/`0`, and the agent database `user_version` was unchanged (23). The clean-state rows show this is not a duplicate of openclaw#156611: on current main the anchor fix already commits Anthropic turns, and the remaining failure is the unscoped finalize drain.

After merging current `origin/main`, the owner and sibling tests passed again: `context-engine-turn-attempt.test.ts` and `context-engine-turn-outbox.test.ts`, 37/37.

No overlap with Pash/Sarah changes: neither has commits on the changed files.

Thanks to @ericcaiwx-star for the fix and to @Kaspnov for the detailed report and outbox analysis.

Not tested: a third-party production context-engine deployment or real user data. The Gateway proof used a local loopback provider, an ephemeral plugin, synthetic transcript data, and no credentials.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S 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