Skip to content

perf(memory): score fallback vector rows without decoding to number[] - #164773

Merged
steipete merged 2 commits into
openclaw:mainfrom
etzelm:perf/memory-vector-fallback-scorer
Oct 10, 2026
Merged

steipete merged 2 commits into
openclaw:mainfrom
etzelm:perf/memory-vector-fallback-scorer

Conversation

@etzelm

@etzelm etzelm commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Memory search without sqlite-vec decodes every stored embedding into a new numeric array and repeatedly normalizes the same query. Large indexes spend avoidable CPU and allocation work on each fallback scan.

User Impact

Fallback search uses less scoring work while preserving ranked results and exact scores. No configuration, schema, stored-format, migration, or operator action changes. Embedding-provider latency and the timeout reports in #128140 and #114913 remain outside this change.

Why This Change Was Made

Memory Core scores little-endian binary64 BLOBs directly and computes query-prefix norms once. It retains the existing bounded scan, bigint row cursor, cancellation, tie ordering, and contender payload snapshot. The former generic cosine implementation and its private-local export had no remaining production caller and were removed; the published legacy JSON parser and embedding codec remain intact.

Thanks @etzelm for the original optimization and numerical parity coverage. The contributor commits remain in the branch, with current main merged rather than rebased. Against main f18b305771d7e896d797945e4f4e6b0d22acc1b0: production +39/-24 (net +15), tests +105/-40, docs +3/-2. The remaining production growth provides direct byte scoring and reusable prefix norms; the original patch added 46 net production lines.

Evidence

Candidate 8965f2767c3c80f03a086fe18911de836934c6c5.

CI: The exact-head gate is red only for an inherited sidebar E2E expectation (run, failed UI job). CI tested merge 0303d0ba33ca against main aff6117e9351. Main's #168076 intentionally enabled child-session grouping, but the sidebar test still expected no “Move to group” item. The CI merge has no UI changes relative to that base. Main has already fixed this exact assertion in c355a4c109a8. The memory, core, type, lint, and ratchet jobs passed; the changed-plugin test job took 233 s and the boundary test job 79 s. This needs the native maintainer workflow's inherited-failure handling; no UI repair is included in this memory PR.

ClawSweeper reviewed this exact head: Ready for maintainer review, Findings: None, Before merge: None, proof/patch 5/6.

  • Focused fallback/native-KNN/codec suites on Node 26.10.0: 23 passed, 119.76 s wall, including worker preparation. The vector file's test bodies took about 2 s; its strengthened ranking case took 42 ms. Existing cancellation, signed-rowid, concurrent-write, snippet, malformed-vector, and dimension contracts remain covered.
  • Regression on unchanged main production: exact ranking passed, then repeated query normalization failed the work limit (1,520 square roots > 816). One expected failure, 16 unrelated cases skipped, 383.36 s wall including cold compilation. The test uses a deterministic operation ceiling, with no timing assertion or added timer.
  • All eight requested ratchets passed: max-lines, line-cap, assertion safety, database worker, test timeout race, mock exports, config docs, plugin inventory.
  • Independent Codex autoreview: scoped-clean through P2.
  • Core, plugin production, and plugin test typechecks passed (33.20/41.97/86.54 s). SDK surface check passed (16.88 s); scoped core/plugin lint passed (40.93/895.46 s, including 12,351 generated boundary declarations); formatting and diff checks passed.

Real local-model proof

The supported pnpm openclaw --profile memory-misc memory index/search commands use isolated state and direct Ollama bge-m3 through its OpenAI-compatible endpoint. Vector acceleration is disabled, and inspection confirms no sqlite-vec table. The real index contains 6,600 chunks, 1,024 dimensions, built from 33 synthetic memory entries repeated at distinct line numbers. The expansion reused all 33 cached model vectors without another document embedding request. Every indexed vector matches its seed cache bytes.

The candidate searches the same main-created index without reindexing. A task-only observer captures actual vector-worker requests and responses; it does not modify production code or results. CPU and heap sampling run separately. The supplemental warm benchmark replays the actual CLI model query through the real source owner against that same database, with 3 warmups and 12 measured scans.

Both sides ran on Node 26.11.1, V8 14.6.202.34-node.37, using the same preserved executable and unchanged index. All four live searches produced the same query vector, the same 200 ranked IDs and exact scores, and identical final CLI result objects. Every warm replay also matched.

Measurement Main Candidate Measured reduction
Actual worker thread CPU 535.324 ms 351.699 ms 34.3%
Warm source-owner median CPU, 12 scans 79.283 ms 57.1015 ms 28.0%
Sampled fallback allocations 203,333,032 B 13,879,760 B 93.2%
Decoder-attributed sampled allocations 189,978,776 B 0 B 100%

Warm CPU ranges were 65.776–91.306 ms on main and 51.206–60.683 ms on the candidate. A final read-only inspection confirmed unchanged chunk identity order and exact index/cache-vector pairing.

Commands used the real entry point, with task-owned configuration/state and store.vector.enabled: false:

OPENCLAW_STATE_DIR="$STATE" OPENCLAW_CONFIG_PATH="$CONFIG" pnpm openclaw --profile memory-misc memory index --force --verbose
OPENCLAW_STATE_DIR="$STATE" OPENCLAW_CONFIG_PATH="$CONFIG" pnpm openclaw --profile memory-misc memory search 'Where does Quartz project store the saffron tea?' --json

The full candidate build passed (3,382.33 s wall). An initial build was interrupted when host maintenance replaced the running Homebrew Node executable; the retry used a preserved copy of the installed runtime. Both performance arms were rerun on that same version. The build emits the same nonfatal UI startup-size warning as main; no UI files changed.

Allocation samples include objects collected by minor and major GC. They estimate V8 heap allocation, not retained heap, RSS, or SQLite/external-buffer memory. The host is shared; CLI startup, model latency, and heap-profiled CPU are excluded from speed comparisons. Native sqlite-vec performance is outside this optimization; its focused behavior tests pass.

The JS fallback scan in searchChunksByEmbedding decoded every stored
binary64 blob into a fresh number[] and recomputed the query norm per row.
Score the blob in place through a DataView and compute the query norm once.
Ranking and scores are bit-identical.
@clawsweeper

clawsweeper Bot commented Oct 4, 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.

@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 Oct 4, 2026
@clawsweeper

clawsweeper Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR scores stored memory vectors directly from binary64 bytes and computes query-prefix norms once per search.

Example: Search a 6,600-chunk, 1,024-dimension memory index with sqlite-vec disabled.

  • Before: Fallback scoring allocates a numeric array for every stored vector and repeatedly normalizes the query.
  • After: The supplied CLI runs return identical 200 ranked IDs, exact scores, and final results, with 34.3% less worker CPU.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused optimization with shipped-entry-point evidence, independent numerical coverage, verified no-migration compatibility, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): At the reviewed head, supplied supported-CLI runs exercise the actual fallback retrieval worker with real local-model embeddings, disabled sqlite-vec acceleration, and an unchanged main-created index; ranked IDs, exact scores, and final CLI objects match while worker CPU and sampled allocations decrease.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large memory searches without sqlite-vec spend avoidable CPU and heap allocations scoring stored vectors.
Reason: Comparable CLI runs demonstrate lower scoring cost with identical results and no additional operator burden.

Merge readiness

✅ Ready for maintainer review

Keep this PR: it provides a measured fallback-search optimization absent from current main, preserves numerical and storage contracts, and has no actionable patch findings.

Priority: P2
Reviewed head: 8965f2767c3c80f03a086fe18911de836934c6c5

Before merge

None.

Findings

None.

Agent review details

How this fits together

Memory Core sends query embeddings to a read-only retrieval worker, which scans SQLite embedding BLOBs and returns ranked chunks and snippets.

flowchart LR
A[Memory CLI or tool] --> B[Search orchestration]
B --> C[Read only retrieval worker]
D[SQLite embedding BLOBs] --> C
C --> E[Direct byte scorer]
E --> F[Ranked chunks and snippets]
Loading

Technical review

Best possible solution:

Land the focused private scorer while preserving the existing worker, storage, cancellation, and ranking contracts.

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

Current-main source shows per-row array allocation and repeated query normalization, and supplied paired CLI measurements demonstrate their cost; this review executed no target code.

Is this the best way to solve the issue?

Direct scoring at the existing fallback owner removes measured work without adding persistent state, configuration, or another public API.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Worker retrieval and generic cosine removal keeps the original intent (e14b3dd: Move retrieval into bounded workers without changing numerical behavior or storage ownership.)
  • Binary64 scoring and documentation keeps the original intent (c659113: Compact embeddings losslessly while preserving vector precision, ranking, and snapshot-safe contender payloads.)
  • Ranking test consolidation keeps the original intent (d1c5af3: Consolidate repeated fixtures while retaining stronger owner-boundary contracts.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +15, Tests +65, Docs +1. Total +81 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 39 24 +15
Tests 1 105 40 +65
Docs 1 3 2 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 147 66 +81

Review metrics

Metric Value Why it matters
Production versus test growth Production +39/-24; tests +105/-40 Production growth provides direct byte scoring and reusable prefix norms; test growth protects independent numerical parity and bounded normalization work.
Recorded worker CPU reduction 34.3% Supplied paired CLI runs use the same runtime and unchanged index; this measures fallback-worker CPU rather than total search or provider latency.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A focused performance improvement benefits large fallback memory searches without evidence of an urgent regression.
  • 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.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-04T05:00:55.566Z sha d17b499 :: blocked before merge. :: none
  • reviewed 2026-10-04T05:14:55.129Z sha d17b499 :: blocked before merge. :: none
  • reviewed 2026-10-04T15:43:19.715Z sha d17b499 :: blocked before merge. :: none
  • reviewed 2026-10-10T06:48:05.690Z sha 8965f27 :: needs maintainer review before merge. :: none

Reviewed October 10, 2026, 3:15 AM ET / 07:15 UTC (Revision 5).

Merge current main while preserving the contributor implementation. Cache query-prefix norms, retain exact binary64 ranking and malformed-vector behavior, and retire the unused private generic cosine path.
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M and removed size: S labels Oct 10, 2026
@steipete

Copy link
Copy Markdown
Contributor

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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 Oct 10, 2026
@steipete steipete self-assigned this Oct 10, 2026
@steipete
steipete merged commit 1cb9b5a into openclaw:main Oct 10, 2026
143 of 147 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

@etzelm

etzelm commented Oct 10, 2026

Copy link
Copy Markdown
Contributor Author

Thank you @steipete!

@etzelm
etzelm deleted the perf/memory-vector-fallback-scorer branch October 10, 2026 13:49
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…openclaw#164773)

The JS fallback scan in searchChunksByEmbedding decoded every stored
binary64 blob into a fresh number[] and recomputed the query norm per row.
Score the blob in place through a DataView and compute the query norm once.
Ranking and scores are bit-identical.
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 extensions: memory-core Extension: memory-core 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: 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.

2 participants