Repository navigation
perf(gateway): stream bounded link preview metadata - #166195
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
|
Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 2:39 PM ET / 18:39 UTC (Revision 4). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherControl 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +55, Tests +81, Docs +6, Config 0, Other 0. Total +142 across 7 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles) |
* 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) ...
* 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
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
htmlparser2reader. 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
loadControlUiLinkPreviewentry 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.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, profileopenclaw-check:tbx_01m48hd8hc6wvnke21bhdw9vr9:node scripts/check-changed.mjs --stagedpassed all typechecks and preceding guards, then stopped after 40m44s on inheritedextensions/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.tbx_01m48z8acra481jexb3damferk: frozen installation, final focused type-aware lint, all three Knip export scans, remaining extension lint, script/style lint, andpnpm check:import-cyclespassed (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.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-testboxleasestbx_01m4911bhdx9awwhqvg6qb6sqhandtbx_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.Current head
0a049c16a97a74a0d61f75ee97ba26cae68df1da: CI run 37509153592 completed with 157 successful jobs and 20 skipped jobs. Its only substantive failure issecurity-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.