Skip to content

refactor(sessions): keep pending history reads off the Gateway thread - #163582

Merged
steipete merged 1 commit into
mainfrom
dbasync/pendinghist
Oct 2, 2026
Merged

steipete merged 1 commit into
mainfrom
dbasync/pendinghist

Conversation

@steipete

@steipete steipete commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Pending-input pages in chat.history/chat.startup and exact pending-message lookup in chat.message.get still executed SQLite on the Gateway thread. Their read helper also synchronously wrote inferred interruptions for inputs without live custody.

Why This Change Was Made

Move durable bounded reads through the existing history reader and stale-disposition reconciliation through the existing agent writer. Capture the physical store before yielding, reread authoritative candidates in a synchronous transaction, and ask the live host custody registry at transaction and commit admission without host SQL. An aborted registered owner keeps its right to finish cancelled. Acknowledged commit receipts update the page even if ordinary result delivery fails; accepted work settles before releasing custody, and uncertain writes are never replayed.

Both runtime callers now await the operations. Remove the old synchronous read implementation and migrate its test callers. The reader factory gets one minimal registration; reply validation is unchanged.

User Impact

No schema, durability, retention, configuration, or update changes. Preserve 20-item and byte limits, ordering, consumed filtering, and exact-message isolation. Process-held incognito retains its existing owner pending its separate actor cutover. Stage/finish/append custody, submitted-input recovery, pending-input repair, and S10 entry patching remain outside this change.

Production LOC: +606 / −153 / net +453 (759 changed lines). Selected durable-flow host SQL exposure: 8 → 0. Conservative full inventory T1: 1,518 → 1,518; the shared kernels remain counted because incognito still uses them, and staging retains its native custody query. No mixed file was relabeled worker-only.

Overlap: draft #157240 has a different reply-validation refactor. Coordinator explicitly approved minimal reader-factory additions here; that PR must rebase after subsequent merged factory changes. #162473 touches shared pending-input files in separate append/consumption functions; these hunks preserve that scope.

Evidence

Base pinned to 9b6e3c4bdb5ca52dc1ef4bd5c1f79acb5f841d35, which contains the requested base and merged #163264.

All focused invocations use pnpm test <file> --maxWorkers=1. Wall times include compiler preparation and cleanup on a loaded macOS host.

File Tests Wall time
src/config/sessions/session-pending-input-history.test.ts 4 51.68 s
src/config/sessions/session-accessor.pending-inputs.test.ts 37 87.33 s
src/config/sessions/session-accessor.pending-inputs-consumed.test.ts 47 46.66 s
src/gateway/server-methods/chat-pending-inputs.test.ts 6 72.38 s
src/gateway/server-methods/chat-message-get-handler.test.ts 7 95.22 s
src/gateway/server-methods/chat-send-pending-inputs.test.ts 33 99.42 s
src/gateway/server-methods/chat-send-pending-input-withdrawal.test.ts 13 61.15 s
src/gateway/server-methods/sessions-suggestions.custody.test.ts 4 42.13 s
src/state/openclaw-agent-pending-inputs-schema.test.ts 7 24.80 s

The zero-caller-SQL regression failed on the original implementation (39.56 s wall), then passed with real reader/writer workers. It also proves transaction/commit custody rechecks, atomic rollback of multiple candidates, and acknowledged commit recovery after ordinary reply loss. Existing suites cover bounds, stable cursors, consumption, cancellation, reset, and Gateway presentation.

An initial schema-fixture run also exposed an unjoined asynchronous database close before raw reopen; it now joins worker cleanup and passes all seven cases. Five UI E2E callsites were migrated to awaited reads and retained async polling.

An initial accessor run failed because its injected SQL trigger was rejected by canonical worker schema admission. The rollback assertion now uses commit-grant refusal in the boundary suite; the production schema check remains intact.

  • Codex autoreview through P2 against the pinned base: scoped-clean, no actionable findings.
  • Database-worker ratchet: passed against the pinned base.
  • Madge: 0 cycles.
  • node scripts/check-changed.mjs: reaches the inherited env-name budget failure (477 vs 476); the max-lines suppression check reports it. The standalone env-count script confirms the same failure, and this diff adds 0 OPENCLAW_* names. Budget unchanged. Remaining planned checks executed separately: passed after fixing lint, except the inherited test type error below. Final focused lint, formatting, UI i18n checks, and the resumed typecheck shards passed.
  • Broad tsgo:core:test also reports inherited TS2339 at src/gateway/worker-environments/worker-turn-launcher.claim-recovery.test.ts:346: openSessionManager().appendMessage(...) calls an instance method on a Promise. The pinned base already has this exact call; its unchanged helper at worker-turn-launcher.test-support.ts:287 explicitly returns Promise<SessionManager>. Both files and session-manager.ts are unchanged by this PR. Remaining typecheck shards were run separately so this inherited failure does not hide checks for this change.
  • git diff --check: passed.

Hosted CI seconds are not yet available. This PR is ready for review; it has not been merged.

Released SDK surface check

Compared the changed signatures against release tag v2026.9.7 and inspected the SDK exports, documented subpaths, and api.runtime implementation. listSessionPendingInputs and readSessionPendingInput were synchronous internal helpers in that release; neither is reachable from a released plugin contract. The internal session-accessor barrel is not wildcard-exported by an SDK entrypoint. No released signature changes, compatibility record, or compatibility type test are needed.

Landing preflight reran the standalone env-count check against the pinned base: the inherited count remains 477 against budget 476. The PR adds zero OPENCLAW_* names and does not change the budget.

Move durable pending history and exact-message reads through the history worker and stale interruption through the agent writer. Preserve bounded pages, consumed filtering and live cancelled disposition custody with SQL-free transaction and commit grants; settle acknowledged writes without replay. Keep incognito and unrelated custody operations with their existing owners.
@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 2, 2026
@steipete

steipete commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority 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 Oct 2, 2026
@clawsweeper

clawsweeper Bot commented Oct 2, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 2, 2026, 10:52 AM ET / 14:52 UTC.

ClawSweeper review

What this changes

Move durable pending-message history reads and stale-input reconciliation into existing database workers, and update callers to await their results.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: current main and the latest release still perform pending-history SQL synchronously. No actionable correctness or security defect was found in the introduced changes.

Likely related people: steipete (medium confidence, recent session-storage work).

Priority: P2
Reviewed head: 131b7205726eef28430510d5a03b0319e6188580

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent worker cutover with meaningful boundary coverage and no identified blocking defect.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied repository state identifies a member-authored internal refactor, so ordinary external-contributor proof is exempt. Inspected worker-boundary coverage supports custody and reply-loss handling; no unresolved authority case requires an additional proof gate. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies a member-authored internal refactor, so ordinary external-contributor proof is exempt. Inspected worker-boundary coverage supports custody and reply-loss handling; no unresolved authority case requires an additional proof gate. No stored-data contract changes.
Evidence reviewed 8 items Pinned introduction and clean checkout: Reviewed the pinned merge-base-to-head introduction, rather than endpoint drift. Initial and final status showed a clean detached checkout at the supplied PR head; diff whitespace validation passed.
Still needed on current main: Fetched main retains the synchronous readPendingInputRows implementation, including direct pending-row queries and inferred-interruption writes.
Latest release also retains synchronous helpers: The v2026.9.7 source exposes synchronous listSessionPendingInputs and readSessionPendingInput implementations; the requested worker cutover is not already supplied by that release.
Findings None None.
Security None None.

How this fits together

Pending-input history supplies accepted messages that have not entered the conversation transcript to chat history, startup, and exact-message lookup. Its storage owner also records interrupted inputs when their live execution custody has ended.

flowchart TD
  A[Chat history and message lookup] --> B[Capture database identity]
  B --> C[History read worker]
  C --> D{Live input custody?}
  D -->|Yes| F[Return bounded pending messages]
  D -->|No| E[Agent writer rechecks and reconciles]
  E --> F
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +453, Tests +309, Docs +9. Total +771 across 48 files.

View PR surface stats
Area Files Added Removed Net
Source 14 606 153 +453
Tests 33 543 234 +309
Docs 1 14 5 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 48 1163 392 +771

Review metrics

Metric Value Why it matters
Production versus test growth production +606 / −153; tests and support +543 / −234 Production growth is explained by physical-store capture, worker custody admission, and acknowledged-write settlement.

Technical review

Best possible solution:

Keep pending-history reads and reconciliation with the existing reader and writer owners while preserving bounded pages, live custody, and confirmed-write settlement.

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

Yes for the stated caller-thread SQL mechanism: current-main source directly performs those queries and writes. Runtime performance was not reproduced during this read-only review.

Is this the best way to solve the issue?

Yes: the patch extends existing database owners, removes the synchronous durable implementation, and preserves the separate incognito owner without adding a competing storage path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 553c6bde778c.

Labels

Label changes:

  • add P2: This is a bounded database-worker improvement to chat history, with no demonstrated urgent user-facing regression.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool 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 supplied repository state identifies a member-authored internal refactor, so ordinary external-contributor proof is exempt. Inspected worker-boundary coverage supports custody and reply-loss handling; no unresolved authority case requires an additional proof gate. No stored-data contract changes.

Label justifications:

  • P2: This is a bounded database-worker improvement to chat history, with no demonstrated urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool 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 supplied repository state identifies a member-authored internal refactor, so ordinary external-contributor proof is exempt. Inspected worker-boundary coverage supports custody and reply-loss handling; no unresolved authority case requires an additional proof gate. No stored-data contract changes.

Evidence

What I checked:

  • Pinned introduction and clean checkout: Reviewed the pinned merge-base-to-head introduction, rather than endpoint drift. Initial and final status showed a clean detached checkout at the supplied PR head; diff whitespace validation passed. (131b7205726e)
  • Still needed on current main: Fetched main retains the synchronous readPendingInputRows implementation, including direct pending-row queries and inferred-interruption writes. (src/config/sessions/session-accessor.pending-inputs.ts:453, 553c6bde778c)
  • Latest release also retains synchronous helpers: The v2026.9.7 source exposes synchronous listSessionPendingInputs and readSessionPendingInput implementations; the requested worker cutover is not already supplied by that release. (src/config/sessions/session-accessor.pending-inputs.ts, c074824a27c9)
  • Custody and settlement boundary: The new host owner captures physical database identity, checks registered input custody without SQL at transaction and commit admission, and consumes confirmed native receipts after settlement without replaying uncertain writes. The writer rereads queued, unconsumed candidates in its synchronous transaction. (src/config/sessions/session-pending-input-history.ts:199, 131b7205726e)
  • Focused regression coverage: The added boundary suite exercises real reader/writer workers, aborted-but-registered custody, ownership acquired at transaction or commit admission, atomic rollback, and acknowledged interruption after ordinary reply loss. The body reports baseline failure and after-fix passes; this read-only review inspected the suite but did not execute it. (src/config/sessions/session-pending-input-history.test.ts:23, 131b7205726e)
  • Caller authorization and internal API boundary: Both production callers await the migrated helpers. Exact-message lookup rechecks current session identity and sharing after the new await; history publication retains its existing current-sharing check. Searches found no export of either helper through plugin SDK entrypoints. (src/gateway/server-methods/chat-message-get-handler.ts:160, 131b7205726e)

Likely related people:

  • steipete: 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.

@steipete
steipete merged commit 84af472 into main Oct 2, 2026
151 of 155 checks passed
@steipete
steipete deleted the dbasync/pendinghist branch October 2, 2026 14:56
@steipete

steipete commented Oct 2, 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 3, 2026
…63582)

Move durable pending history and exact-message reads through the history worker and stale interruption through the agent writer. Preserve bounded pages, consumed filtering and live cancelled disposition custody with SQL-free transaction and commit grants; settle acknowledged writes without replay. Keep incognito and unrelated custody operations with their existing owners.
amittell added a commit to amittell/openclaw that referenced this pull request Oct 11, 2026
…nventory

Run A (all --changed shards at a25baa1) failed 16 tests, all in
fork-pinned areas. Each is TEST-DRIFT: the fork behaviour holds on 10.1
and only the test setup changed upstream. Each fix has a revert control
that fails for the right reason.

- attempt-prompt-context (Telegram current-message carrier, v3/v4):
  openclaw#163471 replaced the BEGIN/END internal-context wrapper with an
  "OpenClaw runtime context:" label applied at model send. The fork's
  carrierText still states the body. Control: without carrierText the v3
  case fails on a bare "openclaw#19452:".
- session-context (runtime carriers at compaction boundaries, 3, an
  upstream test): openclaw#161281 pins the summary exactly, and the fork's
  checkpoint line collides with that. The cut point is unchanged from
  9.9. Controls: no checkpoint line -> 14/21; a cut between the carrier
  and its user -> 19/21.
- pending-inputs.redrive: openclaw#163582 made listSessionPendingInputs async.
  Control: without the fork's terminal block, 10.1 admits a fresh turn
  for a committed source turn ("expected true to be false").
- agent-runner-failure-reply (3) and assistant-failure (1): the 10.1 copy
  from openclaw#163381, under this carry's precedent (the fork keeps its
  classification and takes 10.1's copy). The transport cases now also
  assert "not took too long"; without that, the old negatives passed with
  the fork code removed. assistant-failure asserts the FailoverError
  fields (provider, model) in place of the old text. The 9.9 build did
  not rotate profiles on this path either (probe at 9eea409).
- owner-only-tool-stubs (4) and attempt.owner-only-tool-stubs (2): openclaw#154239
  makes non-owner turns use the real `sessions` tool, limited to
  assign_owner, rather than denying it. Alex, 2026-10-11: take upstream's
  rule. The tests therefore expect every owner-only tool except
  `sessions` to be stubbed. openclaw#164296 makes the tool-surface bridge add the
  Tool Search controls itself, so the attempt test covers Tool Search
  off, on, and Code Mode. Controls: with the fork's stub shaping off,
  5/8; with the refusal line removed, 0/4.

Also adds src/agents/owner-only-tool-stub-marker.ts to
scripts/pr-lib/wrapper-components.txt. tool-policy.ts has imported it since
the 9.9 carry and it was never listed, which failed eager-import-closure.
With the line, eager-import-closure is 18/18 and pr-wrappers 217/217.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL 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