Skip to content

perf(memory-core): store embedding cache as Float32 BLOB instead of JSON TEXT [AI] - #95070

Closed
Nas01010101 wants to merge 1 commit into
openclaw:mainfrom
Nas01010101:perf/memory-core-embedding-cache-blob
Closed

Nas01010101 wants to merge 1 commit into
openclaw:mainfrom
Nas01010101:perf/memory-core-embedding-cache-blob

Conversation

@Nas01010101

@Nas01010101 Nas01010101 commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Consistency with the encoding you already use: the durable vec0 path already stores embeddings as packed Float32 BLOBs via the vectorToBlob helper. The one place still using JSON TEXT for a vector is memory_embedding_cache.embedding. This PR brings that cache in line with the encoding the durable index already uses.
  • Why it matters: for 1536-dim vectors, JSON.stringify is about 95% of the cache upsert CPU and roughly 3x the on-disk size of a packed Float32 buffer. Switching the cache to a BLOB measures at about 5x faster writes and 3x smaller payload (numbers below).
  • The change (the code): write the cache embedding as a Float32 BLOB via the existing vectorToBlob(), and read it back with a small decodeCachedEmbedding() that branches on the stored type: a Uint8Array becomes a zero-copy Float32 view and then number[]; a string falls back to the legacy parseEmbedding. About 20 lines of logic in manager-embedding-cache.ts plus a one-line export of vectorToBlob.
  • Backward-compatible, zero migration: the embedding cache is a rebuildable provider-response cache, not the durable index. Legacy JSON-TEXT rows keep decoding, new rows are BLOB, and a cold cache is safe since entries re-fetch on demand. No schema migration, no new config.
  • Deliberately the un-gated subset of Memory-plugin SQLite hot path: cache_size PRAGMA, FTS5+vec hybrid recall, redundant TEXT embedding column #77301: this does not touch the durable memory_index_chunks.embedding column, the cache_size PRAGMA, or the FTS/vec rerank. Those stay in the maintainer-sequenced work.

[AI] Prepared with AI assistance.

Linked context

Related #77301. This is the cache-only, un-gated first step that issue calls for. Proposed there before opening this PR.

Was this requested by a maintainer or owner? No. Opened per #77301's "land measured PRs in a deliberate sequence" guidance.

Real behavior proof (required for external PRs)

This proof drives the real upsertMemoryEmbeddingCache and loadMemoryEmbeddingCache (not a parallel bench) with real Ollama embeddings, and demonstrates the live upgrade path that mixes old JSON-TEXT rows and new BLOB rows in one table.

  • Behavior addressed: embedding cache writes and reads were JSON-serialized. They are now Float32 BLOB, returning the same vectors, matching the vec0 durable path. The review question was whether a table containing a mix of old TEXT rows and new BLOB rows works at runtime with no migration and no re-embed. It does.

  • Real environment tested: real node:sqlite (the driver memory-core uses), Node 26, real Ollama nomic-embed-text (768-dim) embeddings of four lines of repo text (not random vectors), driving the real upsertMemoryEmbeddingCache and loadMemoryEmbeddingCache from extensions/memory-core/src/memory/manager-embedding-cache.ts, against the real memory_embedding_cache schema. Branch perf/memory-core-embedding-cache-blob.

  • Exact steps or command run after the patch: a small vitest that imports the real cache functions and embeds via local Ollama, run with node scripts/run-vitest.mjs run --reporter=verbose extensions/memory-core/src/memory/_proof.real.test.ts. The temp test was run and then removed, so the branch diff is unchanged.

  • Evidence after fix: copied live output from the run:

    step 1 - legacy rows written as origin/main writes them (JSON.stringify, confirmed via git show origin/main):
      typeof(embedding) = text   (x4)
    step 2 - patched loadMemoryEmbeddingCache decodes those legacy TEXT rows:
      dims=768  max_abs_err=0   (x4, JSON round-trips doubles exactly)
    step 3 - patched upsertMemoryEmbeddingCache writes new rows:
      typeof(embedding) = blob   bytes_match_packed_float32 = true   (x4)
    step 4 - mixed table (2 legacy TEXT + 2 new BLOB, same provider/model/key), one load call:
      legacy TEXT -> max_abs_err = 0
      new BLOB    -> max_abs_err = 3.9e-9   (Float32 quantization, well under 1e-6)
    step 5 - payload per 768-dim row: BLOB 3072 bytes | TEXT 9486 bytes | 3.09x
    
    Test Files  1 passed (1)
    Tests  5 passed (5)
    

Terminal screenshot of the same run:

image
  • Observed result: legacy JSON-TEXT rows decode exactly (max_abs_err=0), new rows are stored as a packed Float32 BLOB, and a single loadMemoryEmbeddingCache over a mixed table returns every row correctly with no migration and no re-embed. Payload is 3.09x smaller per row.
  • What was not tested: cache eviction or LRU behaviour (not touched by this PR), very large caches (this run is 4 rows, the on-disk ratio converges toward the 3x payload ratio as the cache fills and SQLite page overhead is amortised), and Ollama connectivity across non-local environments.
  • Proof limitations: the model is nomic-embed-text (768-dim); the logic is model-agnostic but this is the model tested here. The full DB-file ratio at 4 rows (1.30x) is dominated by SQLite page overhead and tracks the 3.09x payload ratio as the cache fills. A separate scale bench at 25k and 100k rows showed about 5x faster writes and 3.75x smaller on disk.

Tests and validation

  • pnpm test:extension memory-core passes, including the cache tests: a Float32-BLOB round-trip (asserts the stored column is a BLOB and decodes Float32-exact), a legacy-JSON-TEXT row that still decodes with no migration, and a multi-row BLOB write/load round-trip.
  • oxfmt --check, oxlint, tsgo:extensions, and tsgo:extensions:test are clean.
  • Ran codex review --base origin/main locally before opening this PR and it passed with no actionable correctness issues, confirming the legacy JSON-row support, the shared vectorToBlob helper, and the Float32 cache precision.

Risk checklist

  • User-visible behavior change? No. Identical vectors are returned (legacy TEXT exact, new BLOB within 3.9e-9 Float32 quantization, which matches what the durable vec0 path already stores).
  • Config, env, or migration change? No migration and no new config. The storage format of one cache column changes, which is internal and backward-compatible, proven by the mixed-table run above.
  • Security, secrets, or network change? No.
  • Highest-risk area and the honest flaws:
    1. Driver-affinity dependency. Correctness relies on SQLite storing a BLOB in a TEXT-affinity column and the driver returning it as a Uint8Array. Confirmed for node:sqlite (current) and better-sqlite3 (fix(memory): replace node:sqlite with better-sqlite3 to enable sqlite-vec on macOS #90323). A future driver that coerced a BLOB to a string would break reads. The read detector falls back to parseEmbedding for strings, and this can move to an additive embedding_blob column with no behavior change if that ever happens.
    2. Float32 precision. Caching at Float32 instead of the provider's Float64. This matches what the durable vec0 path already stores, so it adds no new precision loss, and the cache feeds indexing rather than final scoring.
    3. Scope of the win. This is a serialization, storage, and reindex win, not a query-latency win. End-to-end reindex is still bounded by the embedding-provider call on cache misses.
  • Mitigation summary: a backward-compatible read path proven on a mixed table, reuse of the proven vectorToBlob, and tests covering both legacy and new rows.

Current review state

…SON TEXT

The provider-response embedding cache (memory_embedding_cache.embedding)
was serialized with JSON.stringify, which dominated upsert CPU for
high-dimensional vectors and roughly 5x-inflated on-disk size versus a
packed Float32 representation.

Store new rows as a packed Float32 BLOB (reusing the existing
vectorToBlob helper already used by the vec0 vector path) and decode on
read by value type: Uint8Array -> Float32 BLOB, string -> legacy JSON
TEXT via parseEmbedding. Because the column has TEXT affinity (a storage
preference, not a constraint) the BLOB round-trips as a BLOB under
node:sqlite, so this needs no schema change and no migration: pre-existing
TEXT rows keep reading, and this table is a rebuildable cache so even a
cold cache is safe.

Microbench (node:sqlite, 10k x 1536-dim): write 6.3x faster, read 2.3x
faster, stored bytes 5.0x smaller; Float32 round-trip exact vs the f32
reference. The durable index column (memory_index_chunks.embedding) is
left untouched; that change is gated on the maintainer decision in #77301.
@clawsweeper

clawsweeper Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 20, 2026, 6:07 PM ET / 22:07 UTC.

Summary
The PR changes memory-core embedding-cache writes from JSON text to packed Float32 BLOBs, keeps legacy JSON text reads, exports the existing vector BLOB helper, and adds cache round-trip tests.

PR surface: Source +41, Tests +83. Total +124 across 3 files.

Reproducibility: not applicable. as a bug reproduction; this is a performance/storage-format cleanup PR. Current main and v2026.6.8 source confirm the prior JSON cache behavior, and the PR proof demonstrates the after-fix mixed JSON/BLOB path.

Review metrics: 1 noteworthy metric.

  • Stored Cache Encoding: 1 encoding changed, 0 schema columns added. The PR changes how an existing persisted cache column is populated, so upgrade and driver behavior matter before merge.

Stored data model
Persistent data-model change detected: unknown-data-model-change: extensions/memory-core/src/memory/manager-embedding-cache.test.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-embedding-cache.ts, vector/embedding metadata: extensions/memory-core/src/memory/manager-embedding-cache.test.ts, vector/embedding metadata: extensions/memory-core/src/memory/manager-embedding-cache.ts, vector/embedding metadata: extensions/memory-core/src/memory/manager-vector-write.ts. Confirm migration or upgrade compatibility proof before merge.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster ✨ media proof bonus
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • none.

Risk before merge

  • [P1] The PR stores BLOB values in the existing TEXT-affinity cache column, so maintainers still need to accept the mixed JSON/BLOB upgrade boundary and SQLite-driver return-type assumption before merge.

Maintainer options:

  1. Accept Cache-Only Encoding (recommended)
    Land after exact-head checks if maintainers accept BLOB values in the existing cache column plus legacy JSON fallback as sufficient upgrade coverage.
  2. Require Explicit Storage Shape
    Ask for an additive BLOB column or migration if maintainers want a clearer durable type boundary before merge.
  3. Fold Into Broader Memory Work
    Pause this PR if maintainers prefer to sequence cache encoding with cache-size, durable embedding, and retrieval-ranking decisions in the broader memory issue.

Next step before merge

  • [P2] Manual review remains because accepting the in-place cache encoding change is a storage compatibility decision, not a narrow automation repair.

Security
Cleared: No concrete security or supply-chain concern was found; the diff does not change dependencies, workflows, secrets, networking, package metadata, or code-execution surfaces.

Review details

Best possible solution:

Land the cache-only encoding change if maintainers accept the in-place mixed JSON/BLOB cache boundary; otherwise require an explicit BLOB column or fold this into the broader memory storage sequence.

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

Not applicable as a bug reproduction; this is a performance/storage-format cleanup PR. Current main and v2026.6.8 source confirm the prior JSON cache behavior, and the PR proof demonstrates the after-fix mixed JSON/BLOB path.

Is this the best way to solve the issue?

Yes for the cache-only slice: it reuses the existing vector encoder, preserves legacy JSON reads, and avoids touching the durable index. The remaining question is whether maintainers prefer this in-place encoding change or an explicit new storage shape.

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P2: This is a bounded memory-core performance/storage improvement with limited blast radius, not an urgent outage or security issue.
  • merge-risk: 🚨 compatibility: The diff changes persisted cache row encoding and relies on mixed JSON/BLOB read compatibility across upgrades and SQLite drivers.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (screenshot): The PR body and inspected terminal screenshot show after-fix real behavior for patched cache upsert/load with real node:sqlite and Ollama embeddings, including legacy TEXT, new BLOB, and mixed-table reads.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body and inspected terminal screenshot show after-fix real behavior for patched cache upsert/load with real node:sqlite and Ollama embeddings, including legacy TEXT, new BLOB, and mixed-table reads.
  • proof: 📸 screenshot: Contributor real behavior proof includes screenshot evidence. The PR body and inspected terminal screenshot show after-fix real behavior for patched cache upsert/load with real node:sqlite and Ollama embeddings, including legacy TEXT, new BLOB, and mixed-table reads.
Evidence reviewed

PR surface:

Source +41, Tests +83. Total +124 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 45 4 +41
Tests 1 90 7 +83
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 135 11 +124

What I checked:

Likely related people:

  • vincentkoc: Recent GitHub path history shows schema and memory-cache-adjacent commits, including canonical agent database tables and schema helper compatibility. (role: recent area contributor; confidence: high; commits: 88bc08c124a5, 681e5a0f8c47, 6e6bd5633f1c; files: extensions/memory-core/src/memory/manager-embedding-cache.ts, packages/memory-host-sdk/src/host/memory-schema.ts)
  • steipete: History shows earlier extraction of memory embedding state and SQLite/vector write helpers that define the current helper boundary reused by this PR. (role: feature-history owner; confidence: high; commits: d806682f782e, 6b6c95b44378, 5b98f03c64d2; files: extensions/memory-core/src/memory/manager-embedding-cache.ts, extensions/memory-core/src/memory/manager-vector-write.ts, packages/memory-host-sdk/src/host/memory-schema.ts)
  • mushuiyu886: Recent merged work changed local default model identity migration behavior in the same cache helper area, so this person is adjacent to cache compatibility semantics. (role: adjacent cache identity contributor; confidence: medium; commits: 44e6caff5401; files: extensions/memory-core/src/memory/manager-embedding-cache.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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.

How this review workflow works
  • 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.

@clawsweeper clawsweeper Bot added 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. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jun 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. and removed proof: supplied External PR includes structured after-fix real behavior proof. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Jun 19, 2026
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Jun 19, 2026
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. proof: sufficient ClawSweeper judged the real behavior proof convincing. labels Jun 19, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. labels Jun 19, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jul 11, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing due to inactivity.
If you believe this PR should be revived, post in #clawtributors on Discord to talk to a maintainer.
That channel is the escape hatch for high-quality PRs that get auto-closed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: memory-core Extension: memory-core merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: 📸 screenshot Contributor real behavior proof includes screenshot evidence. proof: sufficient ClawSweeper judged the real behavior proof convincing. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S stale Marked as stale due to inactivity 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