Skip to content

perf(gateway): keep artifact downloads off the main thread - #158583

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

steipete merged 10 commits into
mainfrom
perf/l06-artifact-download-worker

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Downloading a large inline artifact can pause the Gateway thread while it hashes and decodes the entire payload, even for HEAD or a tiny byte range.

User Impact

HTTP artifact downloads keep the same URLs, response semantics, and access checks while leaving the Gateway thread available for other conversations. There are no protocol, configuration, or database schema changes.

Why This Change Was Made

The existing history worker now prepares both grants and fresh HTTP responses. Grant creation returns only summary metadata and a digest; each delivery rereads the transcript and verifies that digest before returning any bytes. HEAD, 304, and 416 return no payload, and range reads decode and transfer only the requested bytes in an independently owned buffer. The Gateway retains current connection, ticket, request, and original session-generation authority, including rechecks after the worker read.

The artifact reader parent (#158450) is merged. This branch merges main and reuses its artifact selection operations; the remaining diff is only the download unit. Managed media keeps its canonical streaming owner, and internal callers without a live connection retain the inline fallback. Process-held incognito transcripts retain their existing in-process reader exception.

Evidence

Synthetic 12 MiB artifact, actual registered RPC grant and HTTP delivery handlers, five warmed sequential requests per operation, macOS arm64 / Node 26.9.0. Before uses the parent PR's source handlers; after uses this branch. The shared host was heavily loaded, so these are directional measurements, not deployed latency guarantees.

Operation Median request, before → after Max sampled main-thread gap, before → after
Grant 77.1 → 80.3 ms 22.9 → 7.4 ms
HEAD 89.8 → 80.6 ms 18.0 → 6.8 ms
1 KiB range 83.8 → 78.4 ms 33.4 → 7.1 ms
Full GET 140.1 → 103.3 ms 41.7 → 6.6 ms

HEAD returns no body; the 1 KiB range returns exactly 1 KiB. Regression coverage verifies the registered worker transfer hook, range alignment and backing-buffer size, actual length despite incorrect declared size, fresh digest rejection for HEAD/range/conditional GET, and authority revocation while a read is pending.

Validation on merged candidate 07862b230d7192d052f2a0246d3626643c540e04:

  • Seven focused local suites passed: 85 tests, 377.76 s total harness wall, using node scripts/run-vitest.mjs <files> --maxWorkers=1. These cover byte projection, HTTP authority, registered artifact lookup and request authority, transcript images, transcript readers, and worker schema freshness/transfer behavior.
  • The existing registered request-authority regression now requests HTTP transport while the transcript read is pending. On the unfixed code it failed with Artifact download connection is no longer available (109.38 s focused command wall). After the repair, reconnection returns the expected inline bytes, while cancellation and authority revocation still refuse disclosure. No new test cases, timers, fixtures, or production test seams were added.
  • Independent Codex review of the merged candidate and repair is scoped-clean through P2. The earlier artifact-selection concern was rejected after inspecting the complete collector: it excludes nonmatching IDs before appending results, so the selected first result is the requested artifact.
  • node scripts/check-changed.mjs --base origin/main passed through the repository Crabbox wrapper on one Blacksmith Testbox, with exact source/tree verification; command wall 27m35.857s, exit 0. Production and test types, lint, dead-export scans, and boundary guards passed. Lease tbx_01m3eb6qp2tmj053rxcqwegwt2 is stopped/completed. Changed-gate run. A post-success portal-status sync warning did not affect the recorded check result. The first wrapper invocation rejected a raw SHA base before allocation; the corrected invocation used its required remote-tracking ref.
  • Prior authenticated WSS/HTTPS delivery proof passed on Blacksmith Testbox: 1 test, 19.004 s test time, 625.28 s command wall including build/setup. Behavior run. This remains prior-head evidence; the landing gate is reported separately below.

The reconnect repair rechecks grant eligibility after the worker await and reuses the existing inline reader if the connection can no longer receive a ticket. Request and session authority remain required. The merge preserves main's reset/archive transcript fallback exactly. No schema, protocol, configuration, retention, or update behavior changes.

CI follow-up on 1eedd8b39d28bd31817dd0336bc0e1c5d0a1f52b:

Exact-head CI run 36229562054 failed eight existing assertions in artifacts.test.ts: the extracted reader supplied an unnecessary empty options object for canonical scoped keys. That failing job cancelled 79 siblings. The same eight failures reproduced locally (53 tests, 81.85 s command wall). The reader now preserves the existing no-options call for scoped keys; bare/global keys retain their explicit owner. No assertions were weakened or changed.

After repair, the complete artifact, request-authority, and transcript-image suites passed 94 tests in 114.82 s command wall (node scripts/run-vitest.mjs <three files> --maxWorkers=1); scoped lint and independent Codex review through P2 passed. The earlier Testbox check applies to the merged candidate before this behavior-equivalent lookup correction; current-head CI validates the final correction. No failed run was rerun solely to obtain green.

@clawsweeper

clawsweeper Bot commented Sep 26, 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 gateway Gateway runtime size: L labels Sep 26, 2026
@steipete
steipete marked this pull request as ready for review September 26, 2026 02:30
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels 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, 4:48 AM ET / 08:48 UTC (Revision 3).

ClawSweeper review

What this changes

Moves transcript-backed artifact download preparation and HTTP response bytes into the history worker while the Gateway retains download tickets and delivery.

Merge readiness

✅ Ready for maintainer review

Current main still hashes and decodes inline artifact downloads on the Gateway thread. This PR addresses that distinct work, and the current head repairs the connection-loss case identified in the previous review.

Priority: P2
Reviewed head: 1eedd8b39d28bd31817dd0336bc0e1c5d0a1f52b

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The focused implementation has credible registered-handler proof and relevant authority coverage, with no confirmed blocking defect.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The PR reports a 12 MiB artifact exercised through the registered RPC and HTTP handlers on macOS arm64, with lower sampled Gateway-thread gaps and correct HEAD and range output. The authenticated HTTPS run is prior-head evidence; focused final-head checks cover the later lookup correction. 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 PR reports a 12 MiB artifact exercised through the registered RPC and HTTP handlers on macOS arm64, with lower sampled Gateway-thread gaps and correct HEAD and range output. The authenticated HTTPS run is prior-head evidence; focused final-head checks cover the later lookup correction. No stored-data contract changes.
Evidence reviewed 7 items Current main still decodes downloads on the Gateway thread: After rereading the artifact, the HTTP handler hashes its data and decodes the complete base64 payload before planning even a HEAD or range response.
Introduced worker preparation: The branch hashes the selected artifact and prepares HEAD, conditional, range, and full responses in the artifact projection; range responses allocate only the requested output bytes.
Final HTTP authority check: The ticket handler checks the live connection, expiry, ticket identity, and captured session authority before and after awaiting the worker, then sends the prepared response.
Findings None None.
Security None None.

How this fits together

The Gateway receives an artifact download request, selects an artifact from session history, and issues a connection-bound URL. An HTTP request for that URL reads the artifact and returns its headers and bytes.

flowchart LR
  A[Artifact download request] --> B[Session authorization]
  B --> C[History worker]
  C --> D[Prepared digest and summary]
  D --> E[Connection-bound ticket]
  E --> F[HTTP request]
  F --> G[Worker-prepared response]
  G --> H[Gateway delivery]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +199, Tests +294. Total +493 across 15 files.

View PR surface stats
Area Files Added Removed Net
Source 9 426 227 +199
Tests 6 305 11 +294
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 731 238 +493

Review metrics

Metric Value Why it matters
Production and test growth production net +199 lines; tests net +294 lines The production growth implements worker preparation and response projection; the tests cover byte transfer and authority boundaries.

Technical review

Best possible solution:

Keep artifact preparation in the existing history worker while preserving live ticket and session checks, byte-range semantics, and the inline fallback for a lost connection.

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

Yes, from source: current main hashes and decodes the full inline payload in the HTTP handler, including for HEAD and small ranges. The PR reports registered-handler before-and-after measurements; I did not execute the path in this read-only review.

Is this the best way to solve the issue?

Yes. The patch uses the existing history worker and retains the Gateway's ticket and authorization owners, with a tested inline fallback when a connection disappears.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports a 12 MiB artifact exercised through the registered RPC and HTTP handlers on macOS arm64, with lower sampled Gateway-thread gaps and correct HEAD and range output. The authenticated HTTPS run is prior-head evidence; focused final-head checks cover the later lookup correction. No stored-data contract changes.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Large downloads can pause the Gateway thread, but the change is a bounded performance improvement rather than an urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR reports a 12 MiB artifact exercised through the registered RPC and HTTP handlers on macOS arm64, with lower sampled Gateway-thread gaps and correct HEAD and range output. The authenticated HTTPS run is prior-head evidence; focused final-head checks cover the later lookup correction. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR reports a 12 MiB artifact exercised through the registered RPC and HTTP handlers on macOS arm64, with lower sampled Gateway-thread gaps and correct HEAD and range output. The authenticated HTTPS run is prior-head evidence; focused final-head checks cover the later lookup correction. No stored-data contract changes.

Evidence

What I checked:

  • Current main still decodes downloads on the Gateway thread: After rereading the artifact, the HTTP handler hashes its data and decodes the complete base64 payload before planning even a HEAD or range response. (src/gateway/artifact-downloads.ts:134, a2792b9a40bb)
  • Introduced worker preparation: The branch hashes the selected artifact and prepares HEAD, conditional, range, and full responses in the artifact projection; range responses allocate only the requested output bytes. (src/gateway/artifact-download-projection.ts:45, 1eedd8b39d28)
  • Final HTTP authority check: The ticket handler checks the live connection, expiry, ticket identity, and captured session authority before and after awaiting the worker, then sends the prepared response. (src/gateway/artifact-downloads.ts:103, 1eedd8b39d28)
  • Prior finding addressed: The RPC now rereads the artifact for inline delivery if the connection loses ticket eligibility while worker preparation is pending. The registered-handler regression checks that reconnect case. (src/gateway/server-methods/artifacts.ts:409, 1eedd8b39d28)
  • Boundary and behavior proof: The captured PR body reports a 12 MiB synthetic artifact exercised through registered RPC and HTTP handlers, with reduced sampled main-thread gaps and exact HEAD and range results. Its authenticated WSS/HTTPS run is identified as prior-head evidence; final-head focused suites cover the lookup correction. (1eedd8b39d28)
  • Related merged reader work: The merged artifact-reader PR perf(gateway): keep artifact reads off the main thread #158450 introduced the shared selection worker, while current main still retains synchronous HTTP download decoding. (src/gateway/session-artifact-read.ts:280, 4ed4df0e9b3f)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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 September 25, 2026, 10:51 PM ET / September 26, 2026, 02:51 UTC sha unknown :: needs maintainer review before merge. :: none
  • reviewed 2026-09-26T05:19:10.237Z sha 8567e1e :: blocked before merge. :: [P2] Preserve inline delivery when grant preparation loses its connection

@clawsweeper clawsweeper Bot added 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. and removed 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 Sep 26, 2026
Base automatically changed from perf/l06-artifact-worker-reads to main September 26, 2026 05:09
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: XL and removed size: L labels Sep 26, 2026
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 26, 2026
Merge current main after the stacked artifact reader parent landed. Preserve main transcript fallback handling and keep only the artifact download worker unit in the PR diff. Recheck HTTP grant eligibility after preparation so authorized reconnected requests retain inline delivery; the registered-handler regression fails before this repair.
@openclaw-barnacle openclaw-barnacle Bot removed docs Improvements or additions to documentation size: XL labels Sep 26, 2026
Keep canonical scoped-key reads on the existing no-options lookup path and pass an explicit owner only for unscoped keys. This removes an unnecessary empty options object introduced by extraction. CI and local reproduction exposed eight existing artifact scope assertions; all 94 artifact, authority, and transcript-image tests pass after correction.
@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: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 26, 2026
@steipete
steipete merged commit 5f3781d into main Sep 26, 2026
208 checks passed
@steipete
steipete deleted the perf/l06-artifact-download-worker branch September 26, 2026 09:16
@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
…158583)

* 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

* perf(gateway): prepare artifact downloads in the history worker

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

* fix(gateway): allow absent artifact response headers

* fix(gateway): preserve default artifact session lookup

Keep canonical scoped-key reads on the existing no-options lookup path and pass an explicit owner only for unscoped keys. This removes an unnecessary empty options object introduced by extraction. CI and local reproduction exposed eight existing artifact scope assertions; all 94 artifact, authority, and transcript-image tests pass after correction.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant