Skip to content

perf(gateway): keep artifact reads off the main thread - #158450

Merged
steipete merged 8 commits into
mainfrom
perf/l06-artifact-worker-reads
Sep 26, 2026
Merged

steipete merged 8 commits into
mainfrom
perf/l06-artifact-worker-reads

Conversation

@steipete

@steipete steipete commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Artifact browsing can pause Gateway chat streams because listing artifacts, paging images, and reading referenced images execute transcript SQLite queries and payload decoding on the Gateway thread.

User Impact

Artifact lists, image retrieval, public-share history, and anchored message visibility reads use the existing history worker while preserving IDs, ordering, pagination, filters, and access checks. No Gateway protocol, configuration, SQLite schema, retention, or update change is required. Process-held incognito data and existing native callback visitors retain their current owners.

Why This Change Was Made

The existing async transcript facade contained synchronous read callbacks. This moves artifact selection into its admitted worker, returns selected results, and keeps connection cursors, request authority, and post-await authorization in the Gateway. The shared pagination facade now dispatches durable reads through that owner. Read-only image discovery still refuses cold restoration. The artifact selector and managed-ID parser have one implementation each; history dispatch moves into a focused sibling to keep the worker within its line cap.

Evidence

  • Synthetic registered-handler benchmark: 20 sequential artifact lists over 512 × 16 KiB transcript messages plus one file. On a shared macOS arm64/Node 26.9.0 campaign host, caller-thread transcript SQL fell from 40 to 0, maximum sampled event-loop gap from 4347.3 ms to 9.6 ms, and total request time from 4346.3 ms to 1088.4 ms. The before measurement uses the provided reference build; the after measurement uses source workers. These are loaded-host synthetic measurements, not live-Gateway latency or release-build throughput claims.
  • Existing artifact filtering, first-match payload access, download coalescing, cancellation, managed-media ownership, and request-authority tests: 146 passed, 1 existing skipped, five files, 365.27 s command wall with one worker.
  • node scripts/run-vitest.mjs src/gateway/server-methods/artifacts.images.test.ts --maxWorkers=1: 5 passed, 250.67 s command wall, including cold worker preparation. Existing cases now assert no caller-thread transcript payload SQL for full and image-only lists.
  • node scripts/run-vitest.mjs src/gateway/server-methods/artifacts.transcript-images.test.ts --maxWorkers=1: 6 passed, 131.91 s command wall. Covers exact bytes, legacy duplicate IDs, replacement incarnations, post-await revocation, and no caller-thread transcript payload SQL.
  • Reader sibling checks: 38 passed in the Gateway shard. The facade shard exposed an archive-only regression when SQLite was absent; the shared reader now preserves reset-archive fallback without considering obsolete active JSONL. The corrected node scripts/run-vitest.mjs src/gateway/session-transcript-readers.test.ts --maxWorkers=1 passed 16 tests in 140.87 s command wall, including extended recent/page coverage. The original mixed run took 579.15 s and failed only that corrected case.
  • node scripts/check-changed.mjs passed, including production and all 25 core-test typecheck graphs, formatting, lint, dead-export, import-cycle, storage, and authentication guards. The initial run caught parameter-reassignment/shadowing lint issues; those were fixed before the passing final run.
  • Deslop completed; independent Codex review of the final branch is scoped-clean through P2, with no accepted/actionable findings.
  • Current line delta: production net +405; tests/support net +72; docs +9. Growth is the typed worker operations, captured requests, and facade dispatch needed to preserve existing readers and lifecycle rules. Extraction replaces the old artifact-selection code instead of keeping a second implementation; unrelated code was not deleted to offset the worker boundary.
  • The initial baseline test attempt was stopped after lengthy cold preparation; three transcript-image cases had passed. Completed post-change runs above supply the correctness evidence. No live Gateway or full test suite was run.

Landing CI repair

The original head's CI run 36204316844 failed check-additional-runtime-topology-architecture: the all-import graph found a cycle through the new history request types, reader implementation, and session-accessor barrel. Other jobs were cancelled after that failure. The follow-up moves the message-by-ID result type alongside the reader's existing result contracts and points three type-only imports at their existing contract owners (six files, +13/-13; no runtime logic change).

The full pnpm check:architecture suite passed, including zero runtime and all-import cycles. Core production types, targeted lint, formatting, and independent Codex review through P2 passed. Compiling each of the six repaired files with the installed TypeScript transform produced byte-identical JavaScript before and after the repair. The existing architecture gate covers the regression; no duplicative source-inspection test was added.

The additional focused local test attempt was stopped during module loading on the heavily loaded host after a 742-second cold worker build; it returned exit 143 without test results. It is not counted as passing evidence. The earlier focused behavior proof above remains applicable to this type-only repair, and fresh CI is running on the new commit. An accidentally selected broad TypeScript config reported out-of-lane test errors; the correct tsconfig.core.json production lane passed.

The next exact-head CI run, 36208663918, reached the source-contract guard and found that the selector and async facade both exported readSessionArtifacts. The internal selector is now selectSessionArtifacts, with its worker, incognito, and fixture callers updated together; the facade contract stays unchanged. check-export-name-collisions.mts, core production types, and targeted lint passed after the rename. The run's source-contract failure cancelled remaining jobs; no unchanged CI rerun was requested.

Final selector-rename proof: node scripts/run-vitest.mjs src/gateway/server-methods/artifacts.test.ts --maxWorkers=1 passed 53 tests, 545.19 s command wall on the loaded local host (468.96 s Vitest duration; worker preparation 347.96 s). This updates only the existing fixture's selector reference; no tests or assertions were added. Independent Codex review of the rename was scoped-clean through P2.

ClawSweeper's missing-storage finding was reproduced through the real reader facade: with fallback disabled, paging resolved an empty history instead of rejecting (290.37 s command wall for the failing regression). The reader now suppresses missing SQLite for scoped history reads only when reset-archive fallback is explicitly enabled, preserving storage errors for public-share paging. Existing count and exact-ID missing-store behavior remains unchanged. The existing archive fixture now checks fallback false and omitted before its fallback-enabled reads; no additional test fixture or Gateway boot was introduced.

After that fix, the complete reader-facade and public-share suites passed 22 tests in 713.18 s command wall (reader shard 94.13 s, public-share shard 193.72 s, cold worker preparation 368.38 s). The extended missing-store/archive case itself took 2.626 s. This uses real reader-worker admission and preserves the existing fixtures; most command time was cold preparation and transforms on the loaded host. Independent Codex review with the reader owner and public-share caller supplied as context was scoped-clean through P2.

CI run 36211910596 then exposed one invalid cached-context fixture: it supplied a session ID without creating SQLite and relied on the former main-thread reader opening an empty database. Replaying the same 16-file shard reproduced that one failure (220 passed, 1 failed). The test now uses its existing transcript fixture; its cached-token assertions and production behavior are unchanged. The same shard then passed 221 tests in 159.84 s Vitest duration (the repaired case took 866 ms), versus 522.04 s for the failing local replay and 22.62 s for the original CI shard. Targeted lint and an independent review through P2 passed. No unchanged CI rerun was requested.

The full changed-file check passed after the storage-error repair, including production types, all 25 core-test type graphs, formatting, lint, unused-export scans, and storage/auth guards. The subsequent fixture-only change also passed its messaging type graph and targeted lint.

CI run 36214029659 reported a session-store discovery change during the second history read in the nested Code Mode lifecycle fixture. Its initial 187-file single-worker replay passed 3,350 tests (22 existing skips) in 512.92 s, so the exact interfering registry writer was not reproduced or identified. Source inspection found that the fixture isolated only its transcript directory while sharing the process state registry and scheduling entry maintenance. It now uses the existing owned-state helper, a canonical store inside that state root, and the established maintenance-skipping seed pattern. All production discovery/authority checks and behavior assertions remain unchanged. The fixture's type graph, targeted lint, line-cap guard, and independent review through P2 passed.

Lifecycle-fixture verification completed 20 standalone file runs: 28 tests per run, 560 successful executions, zero failures (wrapper median 86.23 s, range 34.11–192.99 s on the loaded host). The first full 187-file replay at CI's eight-worker concurrency passed 3,350 tests with 22 existing skips in 198.66 s command wall. The second replay passed the lifecycle case but failed three unrelated real-time MCP polling/catalog-timeout tests in two unchanged files; both MCP files then passed all 153 tests in isolation. Those failures remain recorded and are not treated as fixed by the isolated pass. No production guard, assertion, baseline, timeout, or CI retry was weakened.

The third planned eight-worker shard replay passed all 3,350 tests (22 existing skips) in 82.54 s command wall. Thus the three replay outcomes were pass / unrelated MCP timing failures / pass; the failed middle replay is retained as a known local validation limitation, not replaced by additional attempts. Exact-head GitHub gates remain required for landing.

Final exact-head CI passed on 5bab1b983d41ebf62ef9f13c30e770e8c51c7a0c: run 36218607343. Aggregate test-job wall times were 439 s for checks-node-changed-compact-large-9 and 378 s for checks-node-changed-compact-large-13, both successful.

@clawsweeper

clawsweeper Bot commented Sep 25, 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: XL labels Sep 25, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 12:50 AM ET / 04:50 UTC (Revision 7).

ClawSweeper review

What this changes

Moves transcript artifact selection, image paging, and general history reads into the existing session-history worker while keeping artifact access checks in the Gateway.

Merge readiness

✅ Ready for maintainer review

Current main still performs artifact scans on the Gateway thread, so this PR remains useful. The earlier missing-storage finding is repaired and covered by a focused test; this review found no new blocking defect.

Priority: P2
Reviewed head: 5bab1b983d41ebf62ef9f13c30e770e8c51c7a0c

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Direct handler-level performance evidence, focused boundary checks, and repairs to earlier review findings support an above-average assessment.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR reports before-and-after measurements through the registered artifact handler with real transcript workers and a synthetic SQLite workload: caller-thread SQL fell from 40 to 0 and the sampled scheduling gap from 4347.3 ms to 9.6 ms. Focused reader and authority tests supplement that result; no stored-data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR reports before-and-after measurements through the registered artifact handler with real transcript workers and a synthetic SQLite workload: caller-thread SQL fell from 40 to 0 and the sampled scheduling gap from 4347.3 ms to 9.6 ms. Focused reader and authority tests supplement that result; no stored-data contract changes.
Evidence reviewed 8 items Current main still scans on the Gateway thread: The current-main artifact handler calls the synchronous transcript visitor during artifact collection.
Introduced worker dispatch: The PR adds typed artifact and history requests to the existing worker path; the artifact selector runs inside the worker's admitted database lifetime.
Disclosure authority remains in the Gateway: The artifact handler rechecks the selected session and lifecycle after the worker read, before returning artifacts.
Findings None None.
Security None None.

How this fits together

Gateway artifact requests read media references from session transcripts. The history worker selects transcript data, then the Gateway checks current access before returning results to the client.

flowchart LR
A[Artifact request] --> B[Session access check]
B --> C[History worker read]
C --> D[Artifact selection]
D --> E[Current access recheck]
E --> F[Client response]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +405, Tests +72, Docs +9. Total +486 across 28 files.

View PR surface stats
Area Files Added Removed Net
Source 17 907 502 +405
Tests 10 272 200 +72
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 28 1188 702 +486

Review metrics

Metric Value Why it matters
Code growth by purpose production net +405; tests and support net +72; docs +9 The PR attributes production growth to typed worker operations and dispatch while replacing the former on-thread selector.

Technical review

Best possible solution:

Use the existing history worker as the single durable transcript-read owner, with connection cursors and final disclosure checks retained in the Gateway.

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

Yes, at the source level: current main's artifact handler visits transcript messages on the Gateway thread, and the PR reports a before-and-after registered-handler benchmark. This read-only review did not rerun it.

Is this the best way to solve the issue?

Yes. The branch moves durable reads to the existing history worker and retains Gateway-owned authorization and cursors.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against dac6274dae58.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Artifact browsing can stall chat streams, but the affected workflow is bounded and the proposed repair has direct handler-level evidence.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR reports before-and-after measurements through the registered artifact handler with real transcript workers and a synthetic SQLite workload: caller-thread SQL fell from 40 to 0 and the sampled scheduling gap from 4347.3 ms to 9.6 ms. Focused reader and authority tests supplement that result; no stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports before-and-after measurements through the registered artifact handler with real transcript workers and a synthetic SQLite workload: caller-thread SQL fell from 40 to 0 and the sampled scheduling gap from 4347.3 ms to 9.6 ms. Focused reader and authority tests supplement that result; no stored-data contract changes.

Evidence

What I checked:

  • Current main still scans on the Gateway thread: The current-main artifact handler calls the synchronous transcript visitor during artifact collection. (src/gateway/server-methods/artifacts.ts:409, dac6274dae58)
  • Introduced worker dispatch: The PR adds typed artifact and history requests to the existing worker path; the artifact selector runs inside the worker's admitted database lifetime. (src/gateway/session-history-worker-reader.ts:19, 5bab1b983d41)
  • Disclosure authority remains in the Gateway: The artifact handler rechecks the selected session and lifecycle after the worker read, before returning artifacts. (src/gateway/server-methods/artifacts.ts:113, 5bab1b983d41)
  • Earlier finding repaired: Missing SQLite storage is suppressed for history reads only when reset-archive fallback is enabled; the changed facade test checks rejection with fallback disabled or omitted. (src/gateway/session-transcript-read-kernel.ts:175, 5bab1b983d41)
  • After-fix behavior evidence: The PR body reports a registered-handler benchmark using real transcript workers: caller-thread transcript SQL fell from 40 to 0 and the maximum sampled event-loop gap from 4347.3 ms to 9.6 ms. It identifies this as a synthetic loaded-host measurement, not deployed Gateway latency.
  • Main and release check: The new selector file is absent from fetched current main and from the supplied latest release commit; current main's existing handler confirms the central optimization has not landed. (src/gateway/session-artifact-read.ts, dac6274dae58)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Vincent Koc: 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 (6 earlier review cycles)
  • reviewed 2026-09-25T23:58:43.178Z sha 7f9c1e9 :: blocked before merge. :: [P2] Preserve missing-store errors without archive fallback
  • reviewed 2026-09-26T00:24:32.070Z sha 7f9c1e9 :: blocked before merge. :: [P2] Preserve missing-store errors without archive fallback
  • reviewed 2026-09-26T01:40:11.474Z sha 14eb4ba :: needs changes before merge. :: [P2] Preserve missing-storage errors without archive fallback
  • reviewed 2026-09-26T02:05:19.042Z sha 8ba1345 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T02:38:01.642Z sha 4f2539d :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T03:19:52.234Z sha e792822 :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review September 26, 2026 00:17
@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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 26, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 26, 2026
@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Sep 26, 2026
@steipete
steipete merged commit 4ed4df0 into main Sep 26, 2026
218 checks passed
@steipete
steipete deleted the perf/l06-artifact-worker-reads branch September 26, 2026 05:09
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
* perf(gateway): move artifact reads off the main thread

* fix(gateway): preserve archive-only transcript reads

* style(gateway): clarify captured worker reader inputs

* fix(gateway): break artifact history type import cycles

* fix(gateway): distinguish artifact selector from read facade

* fix(gateway): preserve missing history storage errors

* test(gateway): provide stored transcript for cached context report

* test(agents): isolate nested tool history state
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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: 🦞 diamond lobster Very strong PR readiness with only minor 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