Skip to content

perf(gateway): stream bounded link preview metadata - #166195

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-link-preview-off-main-thread-20260919
Oct 6, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-link-preview-off-main-thread-20260919

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Uncached Control UI link previews read and construct a DOM for up to 512 KiB of remote HTML on the Gateway main thread, even when the metadata ends near the top of the page. Large pages can delay other Gateway work.

User Impact

Browser-tab and ordinary external-link previews extract metadata without building a page DOM or reading the rest of the body. Reads stop at the head boundary or 64 KiB. Metadata beyond that limit is intentionally omitted; existing title/description bounds, public-network restrictions, anonymous requests, validated images, and the live disable switch remain in force.

Why This Change Was Made

Replace the DOM parser and buffered HTML-prefix path with a streaming htmlparser2 reader. Reuse the already-pinned dependency at runtime and the existing response deadline/cancellation owner. Preserve the existing bounded URL cache: concurrent requests coalesce, fragments share an entry, successful previews expire after one hour, and unavailable previews expire after five minutes. The existing cache remains the single owner of URL deduplication and TTLs.

Production TypeScript grows by 55 lines. The required streaming contract needs incremental parser state, response-reader cancellation, and idle/abort handling while preserving entity decoding, metadata precedence, and first-base URL resolution. The full DOM path is removed completely; no parallel implementation or compatibility fallback remains.

The session-continuity and streaming QA fixtures also use the existing prebuilt-Gateway route. They test real session/history and streaming behavior; installed-package bootstrap has separate coverage. This removes four mock-auth/repair CLI launches per fixture while preserving all assertions, deadlines, plugin isolation, and channel flags.

Evidence

Before/after measurements use identical HTML fixtures on a Linux rig with Node 26.8.1 through the actual loadControlUiLinkPreview entry point and public URL guard. HTML arrives through a synthetic 16 KiB-chunk transport; image requests return 404. Captured public GitHub and OpenClaw documentation pages retain identical title and description. Separate allocation sampling includes collected objects; timing excludes fixture construction and imports.

Fixture Mean main-thread CPU, before → after Sampled allocation, before → after HTML delivered, before → after
github-public 14.38 → 1.65 ms 5.184 → 0.363 MB 512 → 48 KiB
docs-public 24.12 → 1.11 ms 8.071 → 0.243 MB 300 → 16 KiB
large-2MiB 55.52 → 0.72 ms 18.936 → 0.113 MB 512 → 16 KiB
large-5MiB 57.80 → 0.59 ms 18.923 → 0.106 MB 512 → 16 KiB

100 uncached calls per fixture, plus two synthetic typical-page fixtures (600 total). Worst observed event-loop delay across all six fixtures: 558.55 → 10.57 ms. Cached repeats cause zero additional fetches. Timing uses one collection before each batch, with natural collection during the batch.

Validation used provider blacksmith-testbox, profile openclaw-check:

  • Lease tbx_01m48hd8hc6wvnke21bhdw9vr9: node scripts/check-changed.mjs --staged passed all typechecks and preceding guards, then stopped after 40m44s on inherited extensions/voice-call/src/types.ts: CallBrief. Restoring every lane file to the original base reproduced the same finding. The upstream fix in fix(voice-call): unblock unused-export checks #166147 was incorporated by rebasing, with no copied fix in this PR.
  • Lease tbx_01m48z8acra481jexb3damferk: frozen installation, final focused type-aware lint, all three Knip export scans, remaining extension lint, script/style lint, and pnpm check:import-cycles passed (zero runtime cycles). The interrupted lint run's completed core and first twelve extension groups were reused; the two mechanical lane lint corrections passed focused revalidation. The resumed command exited 0 in 12m48s. Both used leases are stopped.
  • node scripts/run-vitest.mjs src/gateway/control-ui-link-preview.test.ts --maxWorkers=1: the original parser fails exactly three new regressions (head/body early cancellation and byte cap). Final source passes all 21 tests on the rebased branch: 24.75s wrapper wall time, 22.42s Vitest duration, predominantly transformation. Cache expiry, URL fragments, metadata precedence, inert markup, anonymous requests, redirects, image safety, and disabling remain covered.
  • Independent Codex review of the final source passed with no actionable P0–P2 findings. Rebase preserved the exact preview source/test bytes.

Limits: this is isolated metadata-path proof, not a live Gateway deployment or end-to-end DNS, network, or image-decoding benchmark. The target is met for mean steady-state CPU, not every individual preview; forced collection before every request remains a slower cold-allocation diagnostic. On the original published head, the link-preview CI slice passed all 21 tests in 3.41s Vitest wall / 5.50s wrapper wall (107ms summed test time); its packed job took 264s. Final-head CI results are recorded below.

The initial CI run passed the link-preview slice but timed out in the session-continuity, session-streaming, and worker-launch runtime proofs. These scenarios disable Control UI. The first two unnecessarily ran four packaged mock-auth/repair CLI commands before Gateway startup; a retained streaming trace spent about 107 seconds before launch. Their fixtures now use the existing direct prebuilt-Gateway route. The unchanged worker-launch timeout did not reproduce and is not claimed fixed.

QA fixture proof used blacksmith-testbox leases tbx_01m4911bhdx9awwhqvg6qb6sqh and tbx_01m494qdxvbsvd2ma0sbnze8rg, Node 24.19.0, two-CPU affinity, CI serial admission, and the original deadlines:

  • node scripts/check-changed.mjs --staged: passed all selected checks; the combined initial serial pair and gate completed in 12m52.6s.
  • node scripts/run-vitest.mjs <each changed runtime file> --maxWorkers=1: 20/20 standalone runs per file passed. Continuity test-body median/range: 17.6s / 13.9–34.5s; streaming: 16.9s / 14.3–30.6s. Wrapper medians were 59.0s and 51.8s.
  • node --import ./scripts/tsx.mjs scripts/ci-run-node-test-shard.mts: three continuity-then-streaming serial shard runs passed. The final two took 108.2s and 92.5s. The unchanged worker-launch/package-contract sibling shard also passed its diagnostic replay.
  • Initial modified serial test bodies were 24.6s and 22.3s, versus 53.3s and 54.8s in the unchanged serial replay. Assertions and timeouts are unchanged; net test-only deletion is ten lines.
  • Independent review of the fixture change found no actionable P0–P2 findings. No test retry was used. A collector initially rejected duplicated Vitest summary output despite a passing test; its count was corrected and execution resumed at the next repetition. Both leases are stopped.

Current head 0a049c16a97a74a0d61f75ee97ba26cae68df1da: CI run 37509153592 completed with 157 successful jobs and 20 skipped jobs. Its only substantive failure is security-fast: newly reported MCP OAuth advisory GHSA-6qxp-vccf-f47h affects the unchanged SDK 1.30.1 and client 2.0.0 on both this branch and main. The aggregate gate fails only because of that audit. Node checks are 113 passed, one skipped; the previously failing runtime area is green. Two separate shared-kit report scans were still pending at this read.

Upstream repair #166217 already owns the MCP dependency update and reports a passing audit. This PR remains open pending that repair; incorporate it by rebasing after it lands, then run affected validation. No dependency fix was copied here and no failing gate was waived. The prior worker-launch timeout remains unreproduced; the passing new run is not claimed as a worker-launch repair.

Read only the bounded HTML head instead of building a full page DOM. Preserve anonymous URL caching, metadata precedence, public URL guards, and image validation.
@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 gateway Gateway runtime size: M labels Oct 6, 2026
@github-actions github-actions Bot added the dependencies-changed PR changes dependency-related files label Oct 6, 2026
@github-actions

github-actions Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Dependency graph changes

This maintainer PR changes the dependency graph.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 0a049c16a97a74a0d61f75ee97ba26cae68df1da
  • Maintainer: @steipete
  • Repository role: admin

These dependency graph changes were made:

  • pnpm-lock.yaml
  • package.json

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) October 6, 2026 16:21
@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 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, 2:39 PM ET / 18:39 UTC (Revision 4).

ClawSweeper review

What this changes

The PR streams bounded Control UI link metadata instead of building a page DOM and switches two session QA fixtures to the existing prebuilt Gateway startup route.

Merge readiness

✅ Ready for maintainer review

The performance improvement remains useful: fetched main still builds a DOM for preview metadata. No actionable introduced defect was found, and this maintainer-authored PR should remain open.

Priority: P2
Reviewed head: 0a049c16a97a74a0d61f75ee97ba26cae68df1da

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable optimization with meaningful scoped validation and no supported blocking findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-author exemption applies. Supplemental Linux measurements exercise loadControlUiLinkPreview with synthetic chunked transport and report lower CPU/allocation with retained metadata; repeated prebuilt-Gateway runs cover the QA fixture changes. No live Internet or browser proof is claimed, and 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 maintainer-author exemption applies. Supplemental Linux measurements exercise loadControlUiLinkPreview with synthetic chunked transport and report lower CPU/allocation with retained metadata; repeated prebuilt-Gateway runs cover the QA fixture changes. No live Internet or browser proof is claimed, and no stored-data contract changes.
Evidence reviewed 9 items Pinned introduction reviewed: Reviewed the complete introduced delta from the pinned merge base to the original PR head. The stale test merge was not used to infer removals or regressions of current-main behavior.
Current main still needs the optimization: Fetched main retains DOMParser, a 512 KiB HTML prefix, and buffered metadata extraction. The supplied merged related PR addresses voice-call exports; the open MCP repair addresses dependency auditing. Neither implements this optimization, and no fixed release is established.
Bounded reader preserves existing owners: The streaming reader uses the existing response deadline owner and cancels remaining body consumption. Metadata precedence, first-base resolution, guarded anonymous requests, image validation, cache TTLs, and live disabling remain with their existing owners. No persisted format or authority-bearing contract changes.
Findings None None.
Security None None.

How this fits together

Control UI sends public link URLs to the Gateway, which retrieves anonymous page metadata and validated images for browser cards and hover previews. A bounded cache shares requests and results.

flowchart TD
  A[Control UI link URL] --> B[Preview enabled and URL valid]
  B --> C[Bounded preview cache]
  C --> D[Guarded anonymous fetch]
  D --> E[Stream bounded HTML head]
  E --> F[Validate preview images]
  F --> G[Metadata and image data returned]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +55, Tests +81, Docs +6, Config 0, Other 0. Total +142 across 7 files.

View PR surface stats
Area Files Added Removed Net
Source 1 84 29 +55
Tests 3 101 20 +81
Docs 1 6 0 +6
Config 1 1 1 0
Generated 0 0 0 0
Other 1 3 3 0
Total 7 195 53 +142

Review metrics

Metric Value Why it matters
HTML parsing budget 512 KiB → 64 KiB maximum The reader reduces maximum parser input eightfold and stops earlier at the head boundary.
Production versus test growth production +55 lines, tests +81 lines The body explains production growth through incremental parsing and cancellation; QA fixture simplification offsets part of the regression coverage growth.

Technical review

Best possible solution:

Keep one streaming metadata reader with bounded consumption and the existing cache, cancellation, and public-network safeguards.

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

Yes, source establishes the uncached buffered DOM path on fetched main, and the supplied before/after measurements exercise the production loader. No runtime reproduction was executed during this read-only review.

Is this the best way to solve the issue?

Yes, replacing the buffered DOM path with one bounded streaming reader addresses the demonstrated cost while retaining existing lifecycle and security owners.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 69ccd1e6b7ba.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded Gateway responsiveness improvement with focused regression coverage.
  • 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 maintainer-author exemption applies. Supplemental Linux measurements exercise loadControlUiLinkPreview with synthetic chunked transport and report lower CPU/allocation with retained metadata; repeated prebuilt-Gateway runs cover the QA fixture changes. No live Internet or browser proof is claimed, and no stored-data contract changes.

Evidence

What I checked:

  • Pinned introduction reviewed: Reviewed the complete introduced delta from the pinned merge base to the original PR head. The stale test merge was not used to infer removals or regressions of current-main behavior. (0a049c16a97a)
  • Current main still needs the optimization: Fetched main retains DOMParser, a 512 KiB HTML prefix, and buffered metadata extraction. The supplied merged related PR addresses voice-call exports; the open MCP repair addresses dependency auditing. Neither implements this optimization, and no fixed release is established. (src/gateway/control-ui-link-preview.ts:48, 69ccd1e6b7ba)
  • Bounded reader preserves existing owners: The streaming reader uses the existing response deadline owner and cancels remaining body consumption. Metadata precedence, first-base resolution, guarded anonymous requests, image validation, cache TTLs, and live disabling remain with their existing owners. No persisted format or authority-bearing contract changes. (src/gateway/control-ui-link-preview.ts:48, 0a049c16a97a)
  • Intentional metadata bound: The maintainer-authored body explicitly accepts omission beyond the head boundary or 64 KiB; the changed public documentation records that same limitation. This acceptance covers the reviewed reader. Public docs: docs/web/control-ui/security-model.md. (docs/web/control-ui/security-model.md:31, 0a049c16a97a)
  • Parser dependency contract: The affirmative dependency signal is the new Parser import in the target preview module. Inspected the pinned version's HTML-mode defaults, incremental write/end methods, and pause behavior in htmlparser2 v12 source. The target moves the existing exact 12.0.0 pin from development to production dependencies without changing package resolution. (src/Parser.ts:750)
  • Regression and QA coverage: Read the complete preview suite and both session QA modules. New preview cases cover split head/body boundaries, inert markup, byte limits, and cache expiration. QA changes preserve assertions, deadlines, channel flags, and plugin isolation; the existing startup owner selects dist/index.js and stages isolated state when useRepoCli is false. (test/e2e/qa-lab/runtime/agent-session-scope-continuity.e2e.test.ts:298, 0a049c16a97a)

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 (3 earlier review cycles)
  • reviewed 2026-10-06T16:36:48.442Z sha 2e0d49d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T16:43:57.757Z sha 2e0d49d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T18:15:47.563Z sha 0a049c1 :: needs maintainer review before merge. :: none

@steipete
steipete merged commit cc7e664 into main Oct 6, 2026
254 of 259 checks passed
@steipete
steipete deleted the steipete/perf-micro-link-preview-off-main-thread-20260919 branch October 6, 2026 18:50
vincentkoc added a commit that referenced this pull request Oct 6, 2026
* commit 'c39d9b0692dbaafa5b1bfe02514c9f6411ab5546': (30 commits)
  fix(ci): clear MCP audit and service-worker test blockers (#166217)
  test(gateway): wait for steering admission in FIFO fixtures
  fix(llama-cpp): managed setup crashes and loops on macOS below 13.3 (#163358)
  perf(worktrees): avoid full session parsing during GC (#166072)
  fix(update): recover stopped legacy managed services (#166232)
  perf(gateway): stream bounded link preview metadata (#166195)
  perf(diagnostics): release completed Git operation state (#166214)
  chore(deps): update fs-safe to 0.24.1 and clone plugin source captures (#166189)
  feat(clients): adopt worker-local inference placement (#163647)
  test: serialize PowerShell completion process suites (#166229)
  test: stabilize release timing boundaries (#166218)
  refactor(sessions): persist run outcomes only; liveness comes from the run registry (#165733)
  test(gateway): prove mention refresh after config retargeting
  fix(team-reports): keep the missed closed day when catch-up runs after midnight (#165780)
  test(gateway): join WebChat queue admission and drain completion
  fix(logging): reject blank diagnostic stability query fields (#145532)
  fix(agents): report unparseable serialized edit arguments (#163577)
  improve(anthropic): log Claude Code version probe failures (#157697)
  fix(agents): clarify prompt-size provider failures (#159712)
  fix(memory): re-throw non-ENOENT/ENOTDIR errors in root memory file lookup (#107921)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
* perf(gateway): stream bounded link preview metadata

Read only the bounded HTML head instead of building a full page DOM. Preserve anonymous URL caching, metadata precedence, public URL guards, and image validation.

* test(qa): avoid package bootstrap in session runtime proofs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies-changed PR changes dependency-related files 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: M 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