Skip to content

perf(gateway): bound anchored history pages and message groups - #166263

Merged
steipete merged 5 commits into
mainfrom
steipete/perf-micro-history-anchored-page-byte-bound-20260919
Oct 7, 2026
Merged

steipete merged 5 commits into
mainfrom
steipete/perf-micro-history-anchored-page-byte-bound-20260919

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Related: #165897

What Problem This Solves

Anchored chat.history reads bypassed the normal page target, and an indivisible display group could grow to the 6 MiB ceiling. The original RPC regression returned 1,205,168 bytes.

User Impact

History pages and anchored continuations now share a 512 KiB message budget. Oversized source rows remain fetchable through chat.message.get, including complete 5 MB tool outputs in the Control UI. Stored transcript bytes remain unchanged. No configuration or database migration is required.

Why This Change Was Made

One response owner replaces oversized groups with existing message references and supplies pagination for both Gateway transports. This removes the oversized-group escape, partial-sibling replay, and duplicate embedded-adapter budgeting. Anchored cursors preserve physical-session and source identity, retain visibility/recovery context, and obey their own encoded-size limit. Full-message recovery restores visible fragments and supports retained sessions under the existing ownership checks.

Production/non-test delta: +213 lines (452 added, 239 removed; excludes tests, test support, and docs). The bidirectional source-bound cursor and retained-reference contracts require the growth. The embedded adapter alone loses 18 production lines.

Evidence

Page-assembly fixtures, measured as serialized UTF-8 bytes:

Fixture Before After
5 MB source group 5,008,356 374
Anchored page 1,301,315 500,598
Normal page 2,201 2,201

The normal page SHA-256 is unchanged: 41c297930d98612cf3b86c478de595db5fabc4c51bfff138d72c3f87cc228aea.

  • Real RPC regressions assert responses below 1 MB, lossless continuation, unchanged stored transcripts, exact 5 MB reference retrieval, and retained-session access boundaries.
  • A separate cursor-metadata regression reproduced a 2,667,067-byte response from a pathological stored ID. The encoder now enforces the decoder's existing limits; all 14 paging tests pass.
  • Testbox provider blacksmith-testbox, profile openclaw-check: leases tbx_01m48zph7zxzg9wh587kw2r05b and tbx_01m493nk56d954pa6yydm47ng9. The rebased RPC run passed 22 tests in 66.07 s; the final page-owner/embedded run passed 34 tests in 24.49 s; UI jsdom tests passed 61 tests in 6.66 s. Earlier ownership/recovery coverage also passed.
  • Full staged gate passed, exit 0, on the approved Linux rig fallback: node scripts/check-changed.mjs --staged, under nice -n 10 ionice -c3 with a worktree-owned TMPDIR. The run took approximately 45 minutes and verified candidate tree 671726c296fc3ee7012e737b84a82e3610204681 on base c10679395819.
  • Independent review is clean at P0–P2, including the final cursor-size and test cleanup changes.

The first Testbox completed before its remaining gate steps finished. Its replacement queued for more than 20 minutes, enabling the authorized rig fallback. Static validation found and resolved a fixture timestamp, an unnecessary test sort, and a test-only export. No checks were waived. The final rebase onto 4de57f22aa1d preserves every source/docs/test blob; only the baseline file incorporates unrelated upstream pruning. CI validates the published head.

Final staged-gate area Result
Core, 27 test typecheck shards, UI Passed
Changed-file lint 0 warnings, 0 errors; 28 files
Script lint 0 warnings, 0 errors; 1,331 files
Production, full-tree, script dead exports 0 entries
Runtime import cycles 0 cycles
Formatting, ratchets, dependency/plugin boundaries Passed
Native schema, legacy stores, media, sidecars, webhook/pairing guards Passed

CI follow-up bcaaf25c15d1 updates two stale test expectations without production changes. It passed independent review and focused proof on blacksmith-testbox lease tbx_01m49cn4e4mfwrmjkq21ycxh7k. The initial security-fast failure is the inherited MCP production-dependency advisory GHSA-6qxp-vccf-f47h, tracked by #166217; this PR changes no dependency versions or lockfile entries.

CI follow-up d4856a668b01 narrows the E2E request parameters through the shared record coercer, resolving the test-only TypeScript error. Independent review is clean. The exact candidate tree 5f5979b1c5cf6e52a768bb17f26a078ad3ee9981 passed node scripts/check-changed.mjs --staged on the authorized Linux rig fallback (openclaw-node-01, /srv/rig/wt-lane560-history-bound-20261006-1734), exit 0, about 10 minutes. The UI E2E type graph passed in 104.3 s; all three export scans reported zero entries; changed-file lint passed in 25.0 s with zero warnings/errors. Formatting, graph boundaries, i18n verification, dependency/patch guards, and test ratchets also passed. The pending Testbox lease tbx_01m49e5h4f1ajrf8gdte31d645 was stopped after rig verification. On head d4856a668b01, all selected Node test shards, typechecks, UI unit/E2E suites, UI performance, and build checks pass. In CI run 37528922395, the remaining reported failure is security-fast: the same inherited MCP advisory above. Android/native checks are still running at this handoff. Full CI is not green; this PR has not been merged.

The same CI run also failed the unchanged Android ChatComposerLayoutTest.progressCardRendersAdjacentBarsWithoutLeakingMarkup test: it could not find the Expand progress card node. Identical Android inputs passed on the previous head; the test supplies progressCard.get data directly and does not exercise the changed history APIs. The cause is unresolved, and no Android code or assertion has been changed.

Proof uses isolated synthetic state and jsdom components. No live deployment or browser automation was performed.

Focused commands and test cost
node scripts/run-vitest.mjs \
  src/agents/tools/embedded-gateway-stub.test.ts \
  src/gateway/server-methods/chat-history-request-budget.test.ts \
  src/gateway/server-methods/chat-history-page-cursor.test.ts \
  src/gateway/server-methods/chat-history-pages.test.ts \
  src/gateway/server-methods/chat-history-pages.recovery.test.ts \
  src/gateway/server-methods/chat-message-get-handler.test.ts \
  src/gateway/server-methods/chat-history-retained-sharing.test.ts --maxWorkers=1

node scripts/run-vitest.mjs run --config ui/vitest.config.ts --project unit \
  ui/src/pages/chat/components/chat-tool-output.test.ts \
  ui/src/pages/chat/components/chat-transcript-recovery.test.ts \
  ui/src/pages/chat/chat-pane-full-message-loader.test.ts

node scripts/check-changed.mjs --staged

Changed test execution totals in the initial single-worker Gateway run: request budget 19.05 s; source cursors 7.94 s; page recovery 15.36 s; page byte limits 0.02 s; full-message handler 23.79 s. UI totals: tool output 1.36 s; transcript recovery 1.66 s; full-message loader 0.04 s. RPC fixtures require the actual SQLite/worker/authorization boundary to catch dropped cursor fields and retained-source mistakes. Initial CI executed the worker test file in 13.44 s and found the stale tiny-budget assertion. The corrected file passed 5/5 on Testbox in 19.44 s (38.88 s wrapper), and both changed tests passed lint in 14.7 s. The browser fixture retains its full-output/copy/download assertions and now checks that the requested capacity covers the fixture, rather than pinning the old 2M implementation value.

@clawsweeper

clawsweeper Bot commented Oct 6, 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 app: web-ui App: web-ui gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 6, 2026
@steipete
steipete enabled auto-merge (squash) October 6, 2026 19:52
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

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

ClawSweeper review

What this changes

The PR bounds anchored chat-history pages and oversized message groups, adds directional continuation cursors, and extends full-message recovery for large outputs and retained sessions.

Merge readiness

✅ Ready for maintainer review

This PR still addresses gaps left by the earlier merged history-budget work. No blocking introduced defect was found, and the previous test findings are resolved.

Priority: P2
Reviewed head: 4322388b7ed7b0186a860fe52b6e2e887f4ad052

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful boundary regressions, shared ownership, and no remaining blocking correctness finding.
Proof confidence 🌊 off-meta tidepool Not applicable: Verified repository-admin authorship exempts this PR from ordinary contributor proof. The captured evidence exercises history and message-recovery handlers with real SQLite workers and serialization; UI recovery coverage uses jsdom, with no live-browser claim. 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 Not applicable Not applicable: Verified repository-admin authorship exempts this PR from ordinary contributor proof. The captured evidence exercises history and message-recovery handlers with real SQLite workers and serialization; UI recovery coverage uses jsdom, with no live-browser claim. No stored-data contract changes require migration proof.
Evidence reviewed 9 items Pinned introduction: Reviewed the introduced main-to-head delta at the supplied pinned revisions. Current main retains the hard-ceiling group escape and lacks the new anchored continuation implementation; the PR remains useful.
Current-main gap: Main still preserves indivisible projected groups under the 6 MiB hard ceiling. The earlier merged #165897 explicitly left anchored reads and oversized groups outside its smaller target, so it does not supersede this PR.
Shared response owner: Page assembly replaces oversized source groups with references before capping the page, and the embedded adapter consumes that same response owner instead of maintaining separate budgeting.
Findings None None.
Security None None.

How this fits together

Gateway chat history turns stored transcripts into bounded display pages for clients and embedded agent tools. The Control UI can retrieve referenced content separately without changing the stored transcript.

flowchart TD
  A[Client history request] --> B[Current session access]
  B --> C[Transcript worker]
  C --> D[Display projection]
  D --> E[Bounded page assembly]
  E --> F[Messages and continuation cursors]
  E --> G[Oversized message references]
  G --> H[Authorized full-message recovery]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +214, Tests +660, Docs 0, Other -1. Total +873 across 32 files.

View PR surface stats
Area Files Added Removed Net
Source 19 452 238 +214
Tests 11 816 156 +660
Docs 1 3 3 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 32 1271 398 +873

Review metrics

Metric Value Why it matters
Production versus test growth production +214 lines; tests +660 lines; test baseline -1 line The PR explains production growth through source-bound continuation and retained-reference recovery while removing duplicate adapter budgeting.
Full-message protocol 1 optional session selector; character ceiling 2,000,000 → 8,000,000 Recovery can target the displayed retained session and retrieve larger outputs while retaining the serialized transport limit.

Mantis proof suggestion

Optional browser proof would help confirm that a referenced large tool output recovers and remains usable in the chat interface. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis verify Control UI chat recovery of an oversized history reference, inspect the complete tool output and its copy/download actions, and return redacted screenshots and interaction results.

Technical review

Best possible solution:

Keep one bounded history-response owner, with lossless source-bound continuation and separately authorized recovery of complete referenced content.

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

Yes, source provides a high-confidence path: request an anchored page or an indivisible projected group exceeding the smaller page target on main. The supplied regressions exercise those cases, but this read-only review did not execute them.

Is this the best way to solve the issue?

Yes, the shared response owner and existing full-message recovery path provide a focused solution without rewriting stored transcripts or duplicating transport policy.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 0288eb1f3692.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded Gateway history performance and recovery repair with no demonstrated urgent outage.
  • 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: Verified repository-admin authorship exempts this PR from ordinary contributor proof. The captured evidence exercises history and message-recovery handlers with real SQLite workers and serialization; UI recovery coverage uses jsdom, with no live-browser claim. No stored-data contract changes require migration proof.

Evidence

What I checked:

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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-06T19:57:10.470Z sha 10b0448 :: needs changes before merge. :: [P2] Update the tiny-budget worker regression for reference pages | [P2] Align the browser output test with the larger recovery request
  • reviewed 2026-10-06T20:17:10.017Z sha bcaaf25 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T21:12:55.291Z sha d4856a6 :: needs maintainer review before merge. :: none

@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 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. labels Oct 6, 2026
@steipete
steipete merged commit e36feb2 into main Oct 7, 2026
130 checks passed
@steipete
steipete deleted the steipete/perf-micro-history-anchored-page-byte-bound-20260919 branch October 7, 2026 00:44
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
…law#166263)

* perf(gateway): bound anchored history pages and message groups

* fix(gateway): bound history continuation metadata

* test(gateway): align history budget and output recovery expectations

* test(ui): narrow history recovery request parameters
steipete added a commit that referenced this pull request Oct 7, 2026
#166263 made oversized message recovery request CHAT_MESSAGE_MAX_CHARS but left the chat-message-actions E2E expecting 500_000, turning checks-ui-e2e red on main.
steipete added a commit that referenced this pull request Oct 7, 2026
…66365)

## What Problem This Solves

`chat.send` could wait behind unrelated transcript-history reads while authorizing a request, admitting its run, or preparing durable input. An ordered metadata read could hold the database writer FIFO while waiting on the single history worker.

## User Impact

Hot-session input can be persisted and acknowledged while history dispatch is blocked. Exact session rows, target discovery, transcript identity selection, and bounded cold-archive metadata use the existing projection worker. Writer FIFO ordering, current permissions, source replacement checks, and durable input custody remain intact. There are no schema, configuration, retention, or update changes.

## Why This Change Was Made

Metadata discovery and payload reads selected different workers. Use the metadata worker consistently, remove the unused inventory lane parameter, and remove the discovery-only lane fallback. Transcript corpus/archive payloads and maintenance retain their existing owners.

Production LOC delta: **+14**. The generic reader also serves transcript payloads, so the metadata operations must select the existing projection lane explicitly; transcript target selection also retains its lazy worker/incognito boundary. Most added lines are argument/import formatting. No new pool, cache, wrapper, or configuration option is introduced.

## Evidence

Benchmarks and runtime tests ran with provider `blacksmith-testbox`, profile `openclaw-check`, on Linux x86_64 / Node 24.19.0. Paired measurements and the first full staged gate used lease **`tbx_01m499e9p8c3pwdkxrq7kqyt11`** on base `cc7e664dfe34`. The full staged gate also passed after rebase to `8f5c33c30d71` on the Linux rig fallback (`node scripts/check-changed.mjs --staged`, exit 0, approximately 50 minutes). Fresh-lease integration proof passed on **`tbx_01m49cshscnkd5rn7tva92rwrp`**: core production types and 63 tests covering exact reads, worktree-owner projection, managed owner policy, and durable ACK; total command 2m23s.

On **`tbx_01m49wfjav8vbwxmsdrw22nrad`**, base `0288eb1f3692`, core production types and 218 tests across 16 focused files passed in 6m51s. The three corrected race fixtures passed all 58 tests in 2m24s. Their staged gate and a full 227-case registry lifecycle replay passed in 6m14s. The final branch is rebased onto `98567acd6060`; SHA-256 verification confirms all 17 reviewed files are byte-for-byte unchanged. The earlier results are prior-base evidence; hosted CI checks the final integration. All four leases are stopped/expired.

The RPC router/handler and SQLite rig ran 64 sends at concurrency eight, alongside four continuous synthetic history readers and post-ACK preparation. Provider execution was mocked after ACK. Same baseline revision, synthetic data, and lease:

| Request latency | Before | After | Reduction |
|---|---:|---:|---:|
| p50 | 6,451 ms | 979 ms | 84.8% |
| p95 | 17,257 ms | 3,339 ms | 80.7% |
| p99 / max | 18,234 ms | 3,470 ms | 81.0% |
| mean | 7,548 ms | 1,273 ms | 83.1% |

Afterward, all 1,500 history-worker requests were background page reads; foreground metadata used the projection worker. Harness RSS after the run was 2.995 GB before and 3.193 GB after; these are whole test-process measurements, including worker heaps and retained synthetic turns.

A second paired run waited for warm startup, then measured 32 requests with one send outstanding and the same four background history readers:

| Warm request latency | Before | After |
|---|---:|---:|
| p50 | 2,250 ms | 188 ms |
| p95 | 3,036 ms | 323 ms |
| p99 / max | 16,280 ms | 2,246 ms |
| mean | 2,710 ms | 264 ms |

**Both workloads still exceed the 150 ms p50 / 500 ms p99 targets.** The warm median is below 300 ms. The remaining 2,245 ms warm tail records 2,094 ms in authority, 9 ms in admission, 77 ms in persistence, and 65 ms in run admission. Repeated authority preparation and production latency still need finer attribution; this change removes the proven history-queue dependency without relaxing authority or durability.

- The full router → durable transcript → ACK regression passes with history dispatch held. The original revision times out waiting for ACK under the same gate (the existing 120-second Vitest deadline), confirming the regression catches the old dependency.
- Broader owner/sibling coverage: 167 tests passed across 12 files. After the transcript-target and cold-metadata cutover, 71 relevant tests passed, including cold restore authority, physical replacement, first registration, run admission, and ACK-before-skill-preparation behavior.
- `pnpm test src/gateway/server-methods/chat-send-preparation-ack.test.ts --maxWorkers=1`: 5 passed; 38.85 s runner wall time including worker compilation; 10.93 s test time. The new case took 3.67 s. Real router authorization and SQLite custody are required to prove a durable ACK; helper-only tests would miss the persistence dependencies. Added Linux test execution cost: approximately 3.7 seconds per run, measured on Testbox; hosted per-case timing was not collected.
- `node scripts/check-changed.mjs --staged`: passed on the paired measurement base in 27m53s, including all 27 core test type graphs, lint, dead-export, cycle, and storage guards. Every reviewed file matched its recorded SHA-256.
- Independent Codex reviews of the production scope and final three test corrections: scoped-clean, no actionable P0/P1 findings.
- Three additional test fixtures now inject metadata races/errors through the projection worker: native model ownership, diff-baseline generation, and SDK transcript-target locking. All 58 tests in those files passed on the fresh lease in 2m24s; their assertions are unchanged. The scoped staged gate selected and passed the `agents-other`, `other`, and `plugin-sdk` type graphs, lint, and dead-export checks.

<details>
<summary>24-hour slow-send attribution</summary>

The journal query covered 2026-10-05 19:00:50Z through 2026-10-06 19:00:50Z and yielded 77 request and 99 startup records. These are **conditional slow-stage distributions**: the logger excludes stages below 1,000 ms. Timers include awaited/scheduling time and can overlap; they are not exclusive CPU measurements. Missing fields are absent samples. Nearest-rank p99 equals max for these sample counts.

| Stage / phase | Samples | p50 ms | p95 ms | p99 / max ms |
|---|---:|---:|---:|---:|
| Request total | 77 | 3,418 | 5,611 | 6,951 |
| Authority | 77 | 1,429 | 2,267 | 2,748 |
| Admission | 77 | 273 | 469 | 685 |
| Attachments | 77 | 0 | 11 | 285 |
| Persistence | 77 | 566 | 1,234 | 2,815 |
| Preparation | 77 | 0 | 1 | 8 |
| Reply context | 77 | 0 | 83 | 116 |
| Run admission | 77 | 1,135 | 2,314 | 2,402 |
| Effects | 77 | 0 | 0 | 0 |
| Response | 77 | 1 | 1 | 2 |
| Startup total | 99 | 5,674 | 102,321 | 3,288,574 |
| Startup ACK (repeated request duration) | 99 | 3,158 | 4,851 | 6,951 |
| Startup authoring | 95 | 1 | 6 | 9 |
| Startup preparation | 95 | 3,532 | 5,951 | 3,046,035 |
| Startup reply initialization | 95 | 1,612 | 80,753 | 356,488 |
| Startup reply context | 99 | 0 | 0 | 129 |
| Startup worktree | 13 | 3,575 | 5,131 | 5,131 |
| Startup dispatch | 99 | 15 | 544 | 8,757 |

The 54.8-minute startup record had already ACKed in 250 ms and began after that process started. It does not establish pre-ACK blocking or unfinished work from the earlier restart. Source tracing and the blocked-history regression establish the metadata-worker dependency fixed here; they do not attribute every production tail.

</details>

Related: #165608.

<details>
<summary>Hosted CI investigation and remaining upstream failures</summary>

Final-head [CI run 37556779529](https://github.com/openclaw/openclaw/actions/runs/37556779529), head `3292922b0e82`, completed with 79 successful jobs, 24 skipped jobs, two failed test jobs, and the failed aggregate gate. The stale metadata-race fixtures are corrected. No CI rerun was requested.

- **MCP fixture routing:** all ten `mcp-http.session-controls.test.ts` cases fail during tool/auth preparation before the session action. On unchanged base `0288eb1f3692`, `pnpm exec vitest run --config test/vitest/vitest.gateway-core.config.ts src/gateway/mcp-http.session-controls.test.ts --maxWorkers=1 -t 'MCP dispatch preserves archive final-effect authority: allowed'` fails with the identical `Shared-state admission requires the host broker`; adding `--pool=forks` passes. Upstream #166199 moved the sibling question-authority fixture into the fork-backed database-worker lane but omitted this fixture. This branch does not change its routing.
- **History expectation after the new base:** `chat.history advances past a replay boundary that cannot fit all projected siblings` still expects only sequence 2 on page one. Upstream #166263 now compresses an oversized source group into a fetchable placeholder before capping, allowing the older sequence-1 message to fit on the same page. The fixture and paging owner are byte-identical between base `98567acd6060` and this branch. The exact filtered case also fails on unchanged base `98567acd6060` on `blacksmith-testbox` lease `tbx_01m49zrpad1bfnzpwb9wp7t3tz`: a diagnostic print before the unchanged assertion captured `sequences: [1, 2]` and `hasMore: false`. The test exited 1 as expected; the probe command completed in 1m35s, restored the test, removed its temporary worktree, and the lease is stopped. No history behavior is changed here.

The initial CI run also reported one remaining fake timer in `subagent-registry-lifecycle.test.ts`, case `preserves cleanup exhaustion when another run settles (related=true)`. The complete 227-case file passed separately on unchanged base and candidate, and the corrected head's CI no longer reports it. The original failure remains unexplained; passing replays are not claimed as a fix, and no assertion was weakened.

</details>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 8, 2026
openclaw#166263 made oversized message recovery request CHAT_MESSAGE_MAX_CHARS but left the chat-message-actions E2E expecting 500_000, turning checks-ui-e2e red on main.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 8, 2026
…enclaw#166365)

## What Problem This Solves

`chat.send` could wait behind unrelated transcript-history reads while authorizing a request, admitting its run, or preparing durable input. An ordered metadata read could hold the database writer FIFO while waiting on the single history worker.

## User Impact

Hot-session input can be persisted and acknowledged while history dispatch is blocked. Exact session rows, target discovery, transcript identity selection, and bounded cold-archive metadata use the existing projection worker. Writer FIFO ordering, current permissions, source replacement checks, and durable input custody remain intact. There are no schema, configuration, retention, or update changes.

## Why This Change Was Made

Metadata discovery and payload reads selected different workers. Use the metadata worker consistently, remove the unused inventory lane parameter, and remove the discovery-only lane fallback. Transcript corpus/archive payloads and maintenance retain their existing owners.

Production LOC delta: **+14**. The generic reader also serves transcript payloads, so the metadata operations must select the existing projection lane explicitly; transcript target selection also retains its lazy worker/incognito boundary. Most added lines are argument/import formatting. No new pool, cache, wrapper, or configuration option is introduced.

## Evidence

Benchmarks and runtime tests ran with provider `blacksmith-testbox`, profile `openclaw-check`, on Linux x86_64 / Node 24.19.0. Paired measurements and the first full staged gate used lease **`tbx_01m499e9p8c3pwdkxrq7kqyt11`** on base `4a96fff224ff`. The full staged gate also passed after rebase to `66cf8a4c0732` on the Linux rig fallback (`node scripts/check-changed.mjs --staged`, exit 0, approximately 50 minutes). Fresh-lease integration proof passed on **`tbx_01m49cshscnkd5rn7tva92rwrp`**: core production types and 63 tests covering exact reads, worktree-owner projection, managed owner policy, and durable ACK; total command 2m23s.

On **`tbx_01m49wfjav8vbwxmsdrw22nrad`**, base `fd7d42fa5176`, core production types and 218 tests across 16 focused files passed in 6m51s. The three corrected race fixtures passed all 58 tests in 2m24s. Their staged gate and a full 227-case registry lifecycle replay passed in 6m14s. The final branch is rebased onto `772d281b298f`; SHA-256 verification confirms all 17 reviewed files are byte-for-byte unchanged. The earlier results are prior-base evidence; hosted CI checks the final integration. All four leases are stopped/expired.

The RPC router/handler and SQLite rig ran 64 sends at concurrency eight, alongside four continuous synthetic history readers and post-ACK preparation. Provider execution was mocked after ACK. Same baseline revision, synthetic data, and lease:

| Request latency | Before | After | Reduction |
|---|---:|---:|---:|
| p50 | 6,451 ms | 979 ms | 84.8% |
| p95 | 17,257 ms | 3,339 ms | 80.7% |
| p99 / max | 18,234 ms | 3,470 ms | 81.0% |
| mean | 7,548 ms | 1,273 ms | 83.1% |

Afterward, all 1,500 history-worker requests were background page reads; foreground metadata used the projection worker. Harness RSS after the run was 2.995 GB before and 3.193 GB after; these are whole test-process measurements, including worker heaps and retained synthetic turns.

A second paired run waited for warm startup, then measured 32 requests with one send outstanding and the same four background history readers:

| Warm request latency | Before | After |
|---|---:|---:|
| p50 | 2,250 ms | 188 ms |
| p95 | 3,036 ms | 323 ms |
| p99 / max | 16,280 ms | 2,246 ms |
| mean | 2,710 ms | 264 ms |

**Both workloads still exceed the 150 ms p50 / 500 ms p99 targets.** The warm median is below 300 ms. The remaining 2,245 ms warm tail records 2,094 ms in authority, 9 ms in admission, 77 ms in persistence, and 65 ms in run admission. Repeated authority preparation and production latency still need finer attribution; this change removes the proven history-queue dependency without relaxing authority or durability.

- The full router → durable transcript → ACK regression passes with history dispatch held. The original revision times out waiting for ACK under the same gate (the existing 120-second Vitest deadline), confirming the regression catches the old dependency.
- Broader owner/sibling coverage: 167 tests passed across 12 files. After the transcript-target and cold-metadata cutover, 71 relevant tests passed, including cold restore authority, physical replacement, first registration, run admission, and ACK-before-skill-preparation behavior.
- `pnpm test src/gateway/server-methods/chat-send-preparation-ack.test.ts --maxWorkers=1`: 5 passed; 38.85 s runner wall time including worker compilation; 10.93 s test time. The new case took 3.67 s. Real router authorization and SQLite custody are required to prove a durable ACK; helper-only tests would miss the persistence dependencies. Added Linux test execution cost: approximately 3.7 seconds per run, measured on Testbox; hosted per-case timing was not collected.
- `node scripts/check-changed.mjs --staged`: passed on the paired measurement base in 27m53s, including all 27 core test type graphs, lint, dead-export, cycle, and storage guards. Every reviewed file matched its recorded SHA-256.
- Independent Codex reviews of the production scope and final three test corrections: scoped-clean, no actionable P0/P1 findings.
- Three additional test fixtures now inject metadata races/errors through the projection worker: native model ownership, diff-baseline generation, and SDK transcript-target locking. All 58 tests in those files passed on the fresh lease in 2m24s; their assertions are unchanged. The scoped staged gate selected and passed the `agents-other`, `other`, and `plugin-sdk` type graphs, lint, and dead-export checks.

<details>
<summary>24-hour slow-send attribution</summary>

The journal query covered 2026-10-05 19:00:50Z through 2026-10-06 19:00:50Z and yielded 77 request and 99 startup records. These are **conditional slow-stage distributions**: the logger excludes stages below 1,000 ms. Timers include awaited/scheduling time and can overlap; they are not exclusive CPU measurements. Missing fields are absent samples. Nearest-rank p99 equals max for these sample counts.

| Stage / phase | Samples | p50 ms | p95 ms | p99 / max ms |
|---|---:|---:|---:|---:|
| Request total | 77 | 3,418 | 5,611 | 6,951 |
| Authority | 77 | 1,429 | 2,267 | 2,748 |
| Admission | 77 | 273 | 469 | 685 |
| Attachments | 77 | 0 | 11 | 285 |
| Persistence | 77 | 566 | 1,234 | 2,815 |
| Preparation | 77 | 0 | 1 | 8 |
| Reply context | 77 | 0 | 83 | 116 |
| Run admission | 77 | 1,135 | 2,314 | 2,402 |
| Effects | 77 | 0 | 0 | 0 |
| Response | 77 | 1 | 1 | 2 |
| Startup total | 99 | 5,674 | 102,321 | 3,288,574 |
| Startup ACK (repeated request duration) | 99 | 3,158 | 4,851 | 6,951 |
| Startup authoring | 95 | 1 | 6 | 9 |
| Startup preparation | 95 | 3,532 | 5,951 | 3,046,035 |
| Startup reply initialization | 95 | 1,612 | 80,753 | 356,488 |
| Startup reply context | 99 | 0 | 0 | 129 |
| Startup worktree | 13 | 3,575 | 5,131 | 5,131 |
| Startup dispatch | 99 | 15 | 544 | 8,757 |

The 54.8-minute startup record had already ACKed in 250 ms and began after that process started. It does not establish pre-ACK blocking or unfinished work from the earlier restart. Source tracing and the blocked-history regression establish the metadata-worker dependency fixed here; they do not attribute every production tail.

</details>

Related: openclaw#165608.

<details>
<summary>Hosted CI investigation and remaining upstream failures</summary>

Final-head [CI run 37556779529](https://github.com/openclaw/openclaw/actions/runs/37556779529), head `3292922b0e82`, completed with 79 successful jobs, 24 skipped jobs, two failed test jobs, and the failed aggregate gate. The stale metadata-race fixtures are corrected. No CI rerun was requested.

- **MCP fixture routing:** all ten `mcp-http.session-controls.test.ts` cases fail during tool/auth preparation before the session action. On unchanged base `fd7d42fa5176`, `pnpm exec vitest run --config test/vitest/vitest.gateway-core.config.ts src/gateway/mcp-http.session-controls.test.ts --maxWorkers=1 -t 'MCP dispatch preserves archive final-effect authority: allowed'` fails with the identical `Shared-state admission requires the host broker`; adding `--pool=forks` passes. Upstream openclaw#166199 moved the sibling question-authority fixture into the fork-backed database-worker lane but omitted this fixture. This branch does not change its routing.
- **History expectation after the new base:** `chat.history advances past a replay boundary that cannot fit all projected siblings` still expects only sequence 2 on page one. Upstream openclaw#166263 now compresses an oversized source group into a fetchable placeholder before capping, allowing the older sequence-1 message to fit on the same page. The fixture and paging owner are byte-identical between base `772d281b298f` and this branch. The exact filtered case also fails on unchanged base `772d281b298f` on `blacksmith-testbox` lease `tbx_01m49zrpad1bfnzpwb9wp7t3tz`: a diagnostic print before the unchanged assertion captured `sequences: [1, 2]` and `hasMore: false`. The test exited 1 as expected; the probe command completed in 1m35s, restored the test, removed its temporary worktree, and the lease is stopped. No history behavior is changed here.

The initial CI run also reported one remaining fake timer in `subagent-registry-lifecycle.test.ts`, case `preserves cleanup exhaustion when another run settles (related=true)`. The complete 227-case file passed separately on unchanged base and candidate, and the corrected head's CI no longer reports it. The original failure remains unexplained; passing replays are not claimed as a fix, and no assertion was weakened.

</details>
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