Skip to content

improve(memory): reduce vector replacement overhead - #148201

Merged
vincentkoc merged 2 commits into
mainfrom
perf/memory-vector-statements-tranche4
Sep 15, 2026
Merged

vincentkoc merged 2 commits into
mainfrom
perf/memory-vector-statements-tranche4

Conversation

@vincentkoc

@vincentkoc vincentkoc commented Sep 14, 2026 •

Copy link
Copy Markdown
Member

Related: #134575

What Problem This Solves

Replacing multiple memory vectors repeatedly prepares the same SQL statements, adding avoidable CPU work to indexing.

User Impact

This is an internal indexing optimization. Search results, storage format, transaction boundaries, and failure behavior remain unchanged; no migration or configuration change is required. It does not establish an overall indexing, Gateway responsiveness, allocation, or RSS improvement.

Why This Change Was Made

Reuse independently lazy DELETE and INSERT statements within one replacement, creating the writer only when an eligible vector is encountered. Statements are not retained across replacements. DELETE failures remain caught, INSERT failures still propagate, and vector encoding and operation order stay unchanged.

This does not change source-clearing SQL or take over #140102.

Evidence

Source-bound retained results from the remote Testbox lifecycle run, based on 87891ce2b5c8e7c72f4a8a722d73669f2e221004:

  • 7 focused SQLite/vector tests passed, including repeated and distinct IDs, independent Float32 byte checks, DELETE/INSERT failure behavior, multirow rollback/retry, sibling retention, and tombstones.
  • 6 doctor-contract tests run by the changed-check command passed. Both selected type lanes, preceding guards, and dead-code checks passed.
  • 1 separate private benchmark test passed on Node v24.19.0 / SQLite 3.53.3 / Linux x64. Each arm used real vec0 writes in immediate transactions, with five alternating pairs of eight replacements per timed leg and independent row/byte checks outside timing.
  • For 64 vectors of 768 dimensions, median per-replacement wall time was 1.2773 ms before and 0.9338 ms after. The median of the five paired reductions was 27.847% wall / 31.061% CPU, with 5/5 positive directions in both. These are paired reductions, not ratios of separate arm medians.
  • Untimed preparation-call counts fell from 128 to 2 per 64-vector replacement; SQL execution counts stayed at 128. Preparation calls are not allocations. The single-row control was noisy; no single-row gain is claimed.
  • At the previously published head 24ead1f90a5b0c7e06e9a6110c57906d8e67da21, all four committed files matched the remotely tested formatted bytes.

Original validation gap: the original aggregate remains FAILED/UNQUALIFIED. Extension lint reached its fixed command deadline during normal boundary-artifact preparation; no source diagnostic was observed, but lint did not pass. Four following guards were not reached: check:database-first-legacy-stores, check:media-download-helpers, check:runtime-sidecar-loaders, and check:import-cycles. That campaign's owned commands joined, source was restored, and lease cleanup completed. Its linked lifecycle workflow is CANCELLED, not successful required-CI evidence.

Fresh scoped P2 autoreview completed with no actionable findings. Exact-head CI and its required gate are SUCCESS for 24ead1f90a5b0c7e06e9a6110c57906d8e67da21, completed September 14, 2026 at 12:28:51 UTC. Its selected successful jobs cover normal extension lint/artifact preparation, architecture including the database-first guard, and import cycles.

Residual proof completed for the previous head: On September 15, 2026, both pnpm check:media-download-helpers and pnpm check:runtime-sidecar-loaders passed with exit 0 on direct AWS Crabbox after one frozen workspace install at 24ead1f90a5b0c7e06e9a6110c57906d8e67da21. Node 24.19.0, pnpm 12.3.4 and the pinned dependency versions were verified, together with the exact committed head/tree and all 43 source pins before and after. Full command captures were retained; all owned processes joined and that lease was confirmed released. This supplements the historical failed aggregate without rewriting it as a pass.

Current-head refresh: 189592520aa7b35522c319e9c2b9aa3543ec60e1 reconciles the same four-file change with main 33aee1b2f7872f2701f283ad26fb854dfb5bdf00. It preserves main's void-returning kernel contract and removal of the kernel-owned tombstone case, while keeping all row, byte, source-metadata, sibling, rollback and retry assertions. The vector writer and its tests are byte-identical to the previously tested versions. Fresh scoped P2 autoreview found no actionable issue.

Current CI proof: CI run 34932049788 and its required gate passed for PR head 189592520aa7b35522c319e9c2b9aa3543ec60e1, completing September 15, 2026 at 05:37:25 UTC. This is PR merge-integration proof, not a standalone head checkout: CI checked out c54a52ee1406a55c98f3857eb6bd70807b599f94, merging that PR head into a62da047dc26b22829a46e1eb443d692eded6ef8. All four changed file blobs exactly match the PR head. On Node 24.19.0, job 104262311640 passed the two current kernel tests and four vector-writer tests, including stored-byte, repeated-binding, sibling-retention and rollback/retry coverage.

Formatting job 104262312184 also passed: its log records FORMAT_CHECK: true and the actual oxfmt --check invocation at 05:19:15 UTC, not merely a successful lint label.

Proportional follow-up: The prepared supplemental standalone AWS campaign remains UNRUN and is retired, not counted as a pass. The two additional residual guards are not materially affected by this refresh: the changed production files contain no media remote-read/save roundtrips; runtime-sidecar loaders and tsdown entries are untouched. Their broad extension-path selection does not establish new affected behavior. The previous-head residual passes remain historical, while the qualified current CI integration and six focused tests cover the reconciled change. No benchmark replay or new performance claim is implied. Native preparation and merge still own final admission.

Operational follow-up: Two earlier Testbox dispatch failures returned no unambiguous lease/run identity; their resource disposition and cleanup remain unknown. Four preceding AWS setup attempts also remain recorded failures, with no guard passes claimed from them; their identified leases were released. The successful residual proof does not resolve the two unknown Testbox allocations.

Stored-data compatibility: This changes prepared-statement lifetime only, not a persisted data model. The schema, table and columns, DELETE/INSERT SQL, vector codec, operation order, and transaction boundary are unchanged. The retained real SQLite/vec0 tests and the six passing current CI tests cover independent stored-byte checks, repeated bindings, and rollback/retry; no migration or upgrade behavior is introduced. The generic data-model classification is not applicable to this source change. This addresses the review's compatibility request without claiming an unrun upgrade test or removing any historical validation gap above.

@vincentkoc vincentkoc self-assigned this Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 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.

@vincentkoc
vincentkoc marked this pull request as ready for review September 14, 2026 11:13
@openclaw-barnacle openclaw-barnacle Bot added extensions: memory-core Extension: memory-core size: M maintainer Maintainer-authored PR labels Sep 14, 2026
@vincentkoc vincentkoc closed this Sep 14, 2026
@vincentkoc vincentkoc reopened this Sep 14, 2026
@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 Sep 14, 2026
@clawsweeper

clawsweeper Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 15, 2026, 1:53 AM ET / 05:53 UTC (Revision 6).

ClawSweeper review

What this changes

Memory Core reuses vector-write statements within each source replacement and strengthens checks for stored bytes, repeated bindings, rollback, and recovery.

Merge readiness

⛔ Blocked before merge - 1 item remains

This remains a useful, focused optimization with no actionable correctness finding. The previous migration-proof blocker does not apply: prepared-statement reuse changes neither the persisted data model nor upgrade behavior.

Priority: P2
Reviewed head: 189592520aa7b35522c319e9c2b9aa3543ec60e1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, maintainable optimization with meaningful storage coverage and appropriately bounded performance evidence.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The ordinary external-contributor proof gate does not apply to this MEMBER-authored internal optimization. Retained native vec0 measurements address statement preparation, and current integration CI supports kernel behavior; neither establishes whole-Gateway responsiveness.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The ordinary external-contributor proof gate does not apply to this MEMBER-authored internal optimization. Retained native vec0 measurements address statement preparation, and current integration CI supports kernel behavior; neither establishes whole-Gateway responsiveness.
Evidence reviewed 10 items Bounded statement lifetime: The writer is created lazily inside replace(), used only for eligible embeddings, and discarded after that replacement. DELETE preparation and execution remain caught; INSERT failures propagate. The SQL and vectorToBlob codec are unchanged.
Existing transaction and authority owners retained: The normal indexing caller checks current database ownership immediately before source replacement inside its admitted transaction. The shadow writer calls the same synchronous kernel on its admitted connection. Neither caller is changed by this PR.
Still needed on current main: Fetched main still calls replaceMemoryVectorRow for each eligible vector, preparing DELETE and INSERT separately for every row. The proposed reuse is absent.
Findings None None.
Security None None.

How this fits together

Memory Core indexes prepared document and session chunks for later search. Its source-index kernel writes chunks, vectors, and search metadata inside a transaction admitted by the existing database owner.

flowchart TD
  A[Prepared chunks and embeddings] --> B[Database write admission]
  B --> C[Source replacement]
  C --> D{Eligible vector?}
  D -->|Yes| E[Reuse local DELETE and INSERT statements]
  E --> F[Commit searchable index]
  D -->|No| F
  E -->|Write failure| G[Transaction rollback]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source -2, Tests +129. Total +127 across 4 files.

View PR surface stats
Area Files Added Removed Net
Source 2 18 20 -2
Tests 2 169 40 +129
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 4 187 60 +127

Review metrics

Metric Value Why it matters
Production versus test growth Production −2 net lines; tests +129 net lines The optimization reduces production code while expanding byte-integrity and failure-recovery coverage.
Preparation work 128 → 2 preparations for 64 eligible vectors The bounded reuse removes repeated preparation while retaining 128 SQL executions.

Stored data model

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

Technical review

Best possible solution:

Keep statement reuse scoped to each replacement while preserving the existing SQL, encoding, failure handling, and transaction owner.

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

Not applicable as a correctness bug reproduction; repeated statement preparation is directly visible in current main, and the PR reports a bounded native benchmark.

Is this the best way to solve the issue?

Yes. Replacement-local reuse follows the existing chunk-writer pattern without adding persistent caches, changing SQL strategy, or expanding public APIs.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded indexing performance improvement without a demonstrated urgent user-facing regression.
  • 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. Not applicable: The ordinary external-contributor proof gate does not apply to this MEMBER-authored internal optimization. Retained native vec0 measurements address statement preparation, and current integration CI supports kernel behavior; neither establishes whole-Gateway responsiveness.

Evidence

What I checked:

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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 (5 earlier review cycles)
  • reviewed 2026-09-14T11:32:19.442Z sha 24ead1f :: blocked before merge. :: none
  • reviewed 2026-09-14T11:58:44.704Z sha 24ead1f :: blocked before merge. :: none
  • reviewed 2026-09-15T04:55:38.765Z sha 24ead1f :: blocked before merge. :: none
  • reviewed 2026-09-15T05:01:30.460Z sha 24ead1f :: blocked before merge. :: none
  • reviewed 2026-09-15T05:23:47.904Z sha 1895925 :: blocked before merge. :: none

@vincentkoc

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

Please review unchanged head 24ead1f90a5b0c7e06e9a6110c57906d8e67da21. Native landing requires a fresh completed review; exact-head CI and both residual guards now pass. The PR body retains the historical failed attempts and unresolved Testbox resource follow-ups.

@clawsweeper

clawsweeper Bot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@vincentkoc
vincentkoc merged commit a8be1cf into main Sep 15, 2026
100 checks passed
@vincentkoc
vincentkoc deleted the perf/memory-vector-statements-tranche4 branch September 15, 2026 07:44
vincentkoc added a commit that referenced this pull request Sep 15, 2026
* commit '0945dabbe487213e95e84a72ad1aae3659e0e000': (115 commits)
  fix: omit automation service aliases from squash coauthors (#148883)
  test: restore services typecheck shard headroom (#148885)
  perf(trajectory): avoid native probes for truncation records (#148870)
  improve(gateway): load cron only when reload requests it (#143500)
  fix: resolve issue #146088 — [Bug]: The most recent Linux AppImage does not ship with the correct versions of libs needed to run (#148174)
  refactor(theme): share nonvirtual ANSI color lookup (#148717)
  perf(gateway): scope exact session row topology reads (#148836)
  improve(memory): reduce vector replacement overhead (#148201)
  fix(i18n): keep HTTP headers out of native translations (#147119)
  refactor(plugins): share source-root display formatting (#148646)
  fix(cron): reject blank script paths before mutations (#148787)
  refactor(config): share audit positional scanning (#148643)
  fix(test): restore infrastructure typecheck shard headroom (#148861)
  fix(release): harden package validation fallbacks (#148729)
  refactor(config): share leaf and descendant unset pruning (#148216)
  test: reuse prepared runtime for pristine preflight (#148858)
  fix(ui): settle global model drafts across agent switches (#148843)
  fix(queue): avoid repeated scans when cancelling backlogs (#148754)
  fix(logging): orphaned \\\\?\\ path markers corrupt redacted Windows diagnostics (#147542)
  refactor(hooks): share optional reply metadata projection (#148641)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 16, 2026
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 maintainer Maintainer-authored PR 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