Skip to content

perf(state): release cached Knowledge evidence buffers - #186100

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-storage-worker-heap-20261027
Oct 27, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-storage-worker-heap-20261027

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Knowledge storage workers retain artifact buffers and decoded text after a citation fails validation, because the cached Error's lazy V8 stack retains the request-scoped EvidenceInspector.

User Impact

Failed evidence verification no longer keeps the operation's artifact contents alive until cache invalidation. Citation errors, negative-cache hits, authority checks, and file-stamp invalidation keep their existing behavior. No schema, configuration, or API changes.

Why This Change Was Made

Materialize the original Error's stack once before retaining it. This preserves the existing Error and cheap negative-cache hit instead of allocating a new Error on each hit. Production delta is +2 lines (one statement and its lifetime comment); preserving negative-cache behavior requires the statement. The existing worker measurement script now supports synthetic failing evidence and aggregate heap evidence.

Evidence

The new regression fails on unchanged main under Node with cached verdict must not retain the request inspector, and passes with the fix. It keeps the verdict cache live across a GC, then verifies cached rejection and invalidation after a file rewrite. Bun does not exhibit the V8-specific retention, but passes the behavior test.

Real storage-worker protocol, Node 26.12.1, synthetic read-only vault with 32 distinct 1 MiB text artifacts and 32 records whose quotes do not match. Every tenth catalog request edits a record. Two counterbalanced A/B then B/A pairs, 2,000 measured requests per arm per pair (4,000 per revision), separate worker isolates; source mode includes equal loader overhead. Acceptance: release the completed inspector/artifact contents, preserve rejection/invalidation/authority behavior, and retain the existing cache-hit path without a material controlled regression. This is an owner retention result, not a whole-Gateway throughput claim.

Metric Pair 1 base → candidate Pair 2 base → candidate
Post-GC external memory 71.58 → 7.58 MiB 71.58 → 7.58 MiB
Post-GC V8 heap 38.47 → 38.87 MiB 38.75 → 35.06 MiB
Worker allocation, total 4,195.42 → 4,192.44 MiB 4,513.93 → 4,350.10 MiB
Worker CPU, total 18,391 → 19,091 ms 16,498 → 17,435 ms
Catalog RPC p50, n=2,000 each 7.69 → 7.95 ms 5.18 → 6.78 ms
Catalog RPC p99, n=2,000 each 114.50 → 123.59 ms 85.46 → 87.13 ms
Worker event-loop p99 8.06 → 6.34 ms (21,700/23,235 samples) 4.98 → 4.82 ms (18,655/20,159 samples)
Total GC 129.90 → 132.94 ms 109.92 → 137.84 ms
Maximum GC pause 6.56 → 8.43 ms 5.02 → 5.67 ms
Process RSS after GC (not worker RSS) 268.98 → 323.66 MiB 266.59 → 262.56 MiB
Host 1-minute load at arm end 43.44 → 42.20 36.16 → 38.20

The deterministic saving is 64 MiB external memory, comprising 32 MiB of buffers and 32 MiB of decoded text. Aggregate-only snapshot census: retained EvidenceInspector 1 → 0, Buffer objects 37 → 5, Buffer retained bytes 33,633,536 → 72,704. Main-thread CPU and sessions.list were not measured; the bounded retention fix uses the campaign's owner-proof fast path rather than a ten-minute Gateway stress run.

Timing/allocation differences are modest and noisy: paired-mean CPU +4.7%, allocation −1.9%, RPC p99 +5.0%; no speedup claimed. An identical-base A/A control varied CPU 13,981 → 15,471 ms (+10.7%), RPC p99 88.08 → 72.06 ms, and process RSS 270.28 → 319.31 MiB. RSS is inconclusive, not a worker-retention metric. GC rose by a paired mean 0.0077 ms/request, well below the campaign's 1 ms/request absolute threshold. Minor GC counts/time: 152/122.89 → 152/124.15 ms and 168/104.54 → 159/112.61 ms. Major counts were 1/1 and 1/7, so major pause statistics are context only. The discarded message-only-cache prototype allocated a new Error per negative hit and was replaced by this smaller fix.

Reproduce with the script header; the measured command is:

node --import ./scripts/tsx.mjs scripts/perf/knowledge-worker-heap-measure.mjs \
  --state-dir .local/knowledge-proof/state --output .local/knowledge-proof/result.json \
  --stores 1 --scan-pages 32 --evidence-mib 1 --iterations 2000 \
  --snapshot-dir .local/knowledge-proof/snapshots

For source overlays, add --baseline-dir <source-tree> --baseline-file extensions/knowledge/src/evidence-files.ts to both sides with their respective source bytes. Snapshots contain synthetic data and remain local; only aggregate counts are reported.

Validation: OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs extensions/knowledge/src/evidence-inspector.test.ts extensions/knowledge/src/storage-worker.test.ts extensions/knowledge/src/source-descriptor-integration.test.ts --maxWorkers=1 — 9 tests passed; final harness wall time 105.67 s (compilation/cleanup included), new regression about 0.34 s. Changed-file oxfmt/oxlint, script syntax, and git diff --check passed. The pre-rebase local test-line ratchet passed at 6,284,782 / 6,285,000. Exact-head CI later failed that gate on its merge tree at 6,285,692 / 6,285,000, with this PR adding 42 lines; the merge base was already 650 lines over. The ceiling is unchanged. This is an unresolved test-budget gate, not a passing/inherited-only CI claim. No new test file, production export, or module.

Review: independent subagent review (autoreview route unavailable), complete four-file diff through P2, no actionable findings. Autoreview refused provider/configuration mismatch before inference; no configuration was changed. The reviewed patch is unchanged after rebasing onto main; CI supplies broad exact-head validation. Merge is reserved for the coordinating maintainer.

Exact-head CI: run 40535170508 completed with only checks-fast-baseline-ratchets failing (test-lines), propagating to openclaw/ci-gate. All other substantive checks passed. No rerun was requested. A read-only audit found the nearby evidence tests protect distinct contracts; they were not deleted to offset this regression. A smaller in-process GC experiment passed but was discarded because the subprocess avoids shared-constructor and stack-formatter retention. Shared test-headroom cleanup is needed before this PR is green. Not merged.

Knowledge verification caches must retain verdicts without keeping request-scoped artifact buffers and decoded text alive through lazy V8 Error stacks. Materialize the stack once before caching the existing Error, preserving negative-cache identity and behavior.

Regression: a cached failure must allow its EvidenceInspector to be collected, while unchanged citations still reject and rewritten files invalidate the verdict. Independent subagent review (autoreview route unavailable) found no actionable P0-P2 findings.
@clawsweeper

clawsweeper Bot commented Oct 27, 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 scripts Repository scripts plugin: knowledge size: S labels Oct 27, 2026
@steipete
steipete marked this pull request as ready for review October 27, 2026 15:51
@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-27T15:51:49.336213Z da80532 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR materializes cached evidence-error stacks so completed Knowledge operations can release artifact buffers and decoded text.

Example: A Knowledge catalog scans 32 distinct 1 MiB text artifacts whose citation quotes do not match.

  • Before: The supplied worker measurements retain 71.58 MiB of external memory after GC.
  • After: The supplied measurements retain 7.58 MiB, while invalid citations remain rejected.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A minimal, correct lifetime repair with strong production-worker retention measurements and a targeted regression; the evidence supports the bounded memory claim rather than whole-Gateway performance.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Node 26.12.1 measurements exercise the actual Knowledge storage-worker entrypoint and catalog protocol with 32 failing 1 MiB citations, showing 64 MiB less retained external memory across both comparison pairs; the regression additionally covers collection, rejection, and rewrite invalidation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Knowledge workers keep artifact contents alive after failed citation verification has finished.
Reason: The change restores the documented operation lifetime with a minimal fix and measured memory benefit; the supplied maintainer-authored direction requires no additional product decision.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a concrete Knowledge memory-retention defect still present on current main, with no actionable introduced bugs found.

Priority: P2
Reviewed head: da805323673a373059045f248aefff65b6af6496

Before merge

None.

Findings

None.

Agent review details

How this fits together

Knowledge storage workers scan partition-local records and verify cited artifact files; operation-scoped inspectors read their contents, while the vault's longer-lived cache retains file-stamped verification verdicts.

flowchart TD
  A[Catalog request] --> B[Knowledge storage worker]
  B --> C[Vault scanner]
  C --> D[Evidence inspector]
  E[Artifact files] --> D
  D --> F[File stamped verdict cache]
  C --> G[Validated catalog and diagnostics]
Loading

Technical review

Best possible solution:

Materialize the existing Error stack at the verdict-cache owner, preserving negative-cache reuse and file-stamp invalidation.

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

The unchanged main cache retains Errors created through the request-scoped inspector; the supplied Node worker measurements and reported red-on-base regression establish a concrete reproduction path, which this read-only review did not execute.

Is this the best way to solve the issue?

This is the smallest complete repair: it removes the lazy-stack retention at the existing cache owner without replacing Errors, changing validation, or adding another lifetime mechanism.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Evidence verdict caching keeps the original intent (65ad180: Bundling Knowledge carried forward reusable file-stamped verdicts and operation-scoped artifact reads; the source explicitly excludes file contents from the retained cache.)
  • Worker measurement tooling keeps the original intent (f149999: Measure actual Knowledge worker entrypoints and protocols with synthetic state; the later catalog workload arrived through perf(plugins): release retired knowledge link parses #185368.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned production change: The introduced production hunk materializes the existing Error stack immediately before caching it; Error identity, deterministic-failure selection, cache keys, and invalidation remain intact. (extensions/knowledge/src/evidence-files.ts:242, da805323673a)
  • Current main still needs the fix: Fetched main still caches the unmaterialized Error. The verified test merge introduces only the four intended paths and preserves unrelated base changes. (extensions/knowledge/src/evidence-files.ts:241, c22d6a5c87ba)
  • Production-worker retention evidence: The PR body reports two counterbalanced worker-protocol comparisons on Node 26.12.1, each showing 64 MiB less post-GC external memory and an EvidenceInspector census of 1 to 0. Its A/A control and timing discussion explicitly limit the claim to retention; throughput and process RSS improvements are not claimed. (scripts/perf/knowledge-worker-heap-measure.mjs:277, da805323673a)
  • Distinct regression coverage: The new subprocess regression keeps the verdict map live while checking inspector collection, then checks cached rejection and successful invalidation after rewriting the artifact. The body reports the intended failure on base and success with the fix. (extensions/knowledge/src/evidence-inspector.test.ts:12, da805323673a)
  • Existing ownership and intent: The existing contract explicitly says cached verdicts must never hold file contents and inspectors must not outlive their operation. The repository imported this implementation through feat(knowledge): bundle the Knowledge memory plugin #180139; earlier standalone authorship is not established here. (extensions/knowledge/src/evidence-files.ts:175, c22d6a5c87ba)
  • Exact-head CI and merge state: GitHub reports the reviewed head as open, ready, and mergeable. The baseline-ratchet check remains in progress and the aggregate CI gate is pending; no diff-caused failure was identified. (da805323673a)

PR surface

Source +2, Tests +42, Docs +3, Other +58. Total +105 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 2 0 +2
Tests 1 43 1 +42
Docs 1 3 0 +3
Config 0 0 0 0
Generated 0 0 0 0
Other 1 64 6 +58
Total 4 112 7 +105

Review metrics

Metric Value Why it matters
Production versus regression growth Runtime production +2/-0 lines; regression test +43/-1 lines The runtime change is one statement and its lifetime comment; the subprocess test verifies collection and preserved cache behavior without adding a production seam.
Benchmark options 3 new measurement flags --baseline-file, --evidence-mib, and --snapshot-dir extend the existing performance script without changing Gateway configuration or defaults.

Labels

Label changes:

  • add P2: Failed Knowledge citations retain operation-scoped memory, with a demonstrated 64 MiB saving in the supplied bounded workload; no outage or message loss is established.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • 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.

Label justifications:

  • P2: Failed Knowledge citations retain operation-scoped memory, with a demonstrated 64 MiB saving in the supplied bounded workload; no outage or message loss is established.
  • 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.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 27, 2026, 12:08 PM ET / 16:08 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Landing at the pinned head da805323673a373059045f248aefff65b6af6496. The only red check is the repository test-line ceiling.

checks-fast-baseline-ratchets (and openclaw/ci-gate, which aggregates it) fails on the test-lines total: 692 lines over the ceiling. About 650 of those lines were already on main from earlier merges. This PR adds 42 lines, the Node retention regression for the cached Error stack. config/test-lines-baseline.txt is unchanged, and a separate shrink-only cleanup lane is restoring headroom. Every other check passed at this head. No CI reruns were used.

@steipete
steipete merged commit 5cf6a7f into main Oct 27, 2026
211 of 218 checks passed
@steipete
steipete deleted the steipete/perf-storage-worker-heap-20261027 branch October 27, 2026 16:27
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…186100)

Knowledge verification caches must retain verdicts without keeping request-scoped artifact buffers and decoded text alive through lazy V8 Error stacks. Materialize the stack once before caching the existing Error, preserving negative-cache identity and behavior.

Regression: a cached failure must allow its EvidenceInspector to be collected, while unchanged citations still reject and rewritten files invalidate the verdict. Independent subagent review (autoreview route unavailable) found no actionable P0-P2 findings.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. plugin: knowledge proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: S 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