Skip to content

fix(memory): prevent search contention and reindex leaks - #136482

Closed
jason-oc-agents wants to merge 2 commits into
openclaw:mainfrom
jason-oc-agents:fix/memory-search-contention
Closed

jason-oc-agents wants to merge 2 commits into
openclaw:mainfrom
jason-oc-agents:fix/memory-search-contention

Conversation

@jason-oc-agents

Copy link
Copy Markdown

Summary

  • move canonical memory-index publication into a bounded worker so gateway SQLite handles do not retain long publication transactions
  • publish embedding cache in small revision-checked batches and preserve source-change safety
  • deterministically clean shadow DB/WAL/SHM/journal artifacts, including cancellation and partial cleanup failures
  • add regression coverage for concurrent search/publication, worker teardown, lock recovery, source races, and orphan cleanup

Validation

  • source and focused regression tests were added and reviewed against isolated temporary databases only
  • full local test execution was blocked because the worktree dependency install is incomplete and offline pnpm metadata for @anthropic-ai/vertex-sdk is unavailable
  • production memory DB/state was not mutated

Safety

  • draft only; do not merge until CI and maintainer review complete

@clawsweeper

clawsweeper Bot commented Sep 2, 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. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR offloads memory-index publication, retries searches across index revisions, batches cache replacement, and expands shadow-database cleanup.

Example: A full memory reindex publishes while a semantic search is running.

  • Before: Publication waits for the search generation to finish.
  • After: Publication proceeds and the search retries if its captured revision changed.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful cleanup work remains, but the unchanged head retains three verified defects and lacks changed-behavior and populated-state upgrade proof.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Memory maintenance can stall searches and leave large temporary databases after interrupted rebuilds.
Reason: The cleanup problem has concrete operator value; preserve its distinct contribution while reusing publication work already merged on main.

Merge readiness

⛔ Blocked before merge - 8 items remain

Keep open: current main covers publication offloading, but distinct cleanup work remains and three previously reported defects still block this PR.

Priority: P2
Reviewed head: 1ee7bcea7209610e3d594a8f10b18bfa9ebd3d38

Before merge

  • Add real behavior proof - The full PR body and discussion supply no executed after-fix trace for this head’s publisher, revision-retried search, cache replacement, or cleanup; added tests are unexecuted evidence, and the expired recordings belong to the different merged publication PR. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Fence stale queries before vector preparation can alter the index (P1) - Removing the read-generation lease allows another process to publish a different embedding dimension while this query awaits its embedding. Retrieval then calls ensureVectorReady with the old dimensions; manager-sync-base.ts reads the new metadata and drops/recreates the published vector table to fit the stale query. The revision comparison here runs only afterward and cannot restore the deleted vectors. Keep retrieval read-only and protect the captured generation before entering vector preparation.
  • Reuse the query embedding across a revision retry (P2) - When publication changes the revision during an otherwise successful search, this loop reruns searchCandidatesAtRevision, including provider.embed for the same query and unchanged provider generation. The new concurrency test explicitly expects two query calls. This adds another provider request and its latency or quota cost merely to reread updated index rows. Retain the successful embedding within its captured provider generation and retry retrieval alone.
  • Keep orphan cleanup failures from blocking ordinary indexing (P2) - Every sync now awaits cleanupMemoryReindexTempFiles before runSync. A recognized orphan whose WAL remains undeletable with EACCES, EBUSY, or EIO makes the helper throw, so even incremental indexing of unrelated changed notes never runs; later attempts encounter the same orphan and fail again. Report cleanup failures while allowing ordinary sync to proceed, preserving strict failure only where a failed operation actually prevents safe publication.
  • Complete next step - Resolve the reported merge conflict against current main, preserving its shared publication and retrieval owners while separating the remaining cleanup changes.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.
  • Explain or restore the original intent of Published-index generation isolation - a7766f1: fix(memory-core): keep memory search usable during dirty sync #112214 introduced cross-process generation isolation so searches read a stable published index while maintenance builds its replacement.
  • Explain or restore the original intent of Best-effort orphan cleanup - a42bda5: The earlier cleanup implementation deliberately suppressed cleanup failures so they could not prevent indexing; this patch propagates them before every sync without explaining that availability change.

Findings

  • [P1] Fence stale queries before vector preparation can alter the index — extensions/memory-core/src/memory/manager-search-orchestration.ts:83-86
  • [P2] Reuse the query embedding across a revision retry — extensions/memory-core/src/memory/manager-search-orchestration.ts:82-84
  • [P2] Keep orphan cleanup failures from blocking ordinary indexing — extensions/memory-core/src/memory/manager.ts:399-401

Provenance

  • Published-index generation isolation changes intended behavior without addressing why it exists (a7766f1: fix(memory-core): keep memory search usable during dirty sync #112214 introduced cross-process generation isolation so searches read a stable published index while maintenance builds its replacement.)
  • Best-effort orphan cleanup changes intended behavior without addressing why it exists (a42bda5: The earlier cleanup implementation deliberately suppressed cleanup failures so they could not prevent indexing; this patch propagates them before every sync without explaining that availability change.)

Tests

  • Missing end-to-end proof: Provide redacted source and packaged-runtime observations covering publication during search, dimension-changing publication, cleanup failure recovery, and upgrade from the latest stable release with populated settings and data preserved.
Agent review details

How this fits together

Memory Core serves agent and CLI searches from the published index while maintenance builds shadow databases and publishes memory-owned tables into the shared agent database.

flowchart LR
  A[Memory search tool or CLI] --> B[Memory manager]
  B --> C[Published index retrieval]
  B --> D[Shadow index build]
  D --> E[Publication worker]
  E --> F[Agent SQLite database]
  C --> F
  D --> G[Shadow file cleanup]
Loading

Technical review

Best possible solution:

Keep current main’s shared publication and generation owners, and narrow the remaining repair to safe shadow cleanup that cannot block ordinary indexing.

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

Source establishes all three introduced failure paths, including an added test expecting duplicate embedding calls; no target code was executed during this read-only review.

Is this the best way to solve the issue?

This is no longer the best complete fix: current main already shares publication across incremental and full-index writes, while this branch adds a separate publisher and weakens retrieval isolation.

Full review comments:

  • [P1] Fence stale queries before vector preparation can alter the index — extensions/memory-core/src/memory/manager-search-orchestration.ts:83-86
    Removing the read-generation lease allows another process to publish a different embedding dimension while this query awaits its embedding. Retrieval then calls ensureVectorReady with the old dimensions; manager-sync-base.ts reads the new metadata and drops/recreates the published vector table to fit the stale query. The revision comparison here runs only afterward and cannot restore the deleted vectors. Keep retrieval read-only and protect the captured generation before entering vector preparation.
    Confidence: 0.98
  • [P2] Reuse the query embedding across a revision retry — extensions/memory-core/src/memory/manager-search-orchestration.ts:82-84
    When publication changes the revision during an otherwise successful search, this loop reruns searchCandidatesAtRevision, including provider.embed for the same query and unchanged provider generation. The new concurrency test explicitly expects two query calls. This adds another provider request and its latency or quota cost merely to reread updated index rows. Retain the successful embedding within its captured provider generation and retry retrieval alone.
    Confidence: 0.99
  • [P2] Keep orphan cleanup failures from blocking ordinary indexing — extensions/memory-core/src/memory/manager.ts:399-401
    Every sync now awaits cleanupMemoryReindexTempFiles before runSync. A recognized orphan whose WAL remains undeletable with EACCES, EBUSY, or EIO makes the helper throw, so even incremental indexing of unrelated changed notes never runs; later attempts encounter the same orphan and fail again. Report cleanup failures while allowing ordinary sync to proceed, preserving strict failure only where a failed operation actually prevents safe publication.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Bounded embedding-cache transactions keeps the original intent (30ae21f: fix: prevent SQLite lock stalls and schema drift #108663 materialized cache pages and committed before asynchronous yields to avoid holding SQLite transactions across awaits.)
  • Shadow discovery and deletion safeguards changes intended behavior with a stated reason (a7fada4: History retains age and primary-presence safeguards inherited from earlier safe-swap cleanup; this patch instead documents exclusive reindex-lease ownership as its deletion boundary.)

Testing

Proof path: none.

Security

None.

Evidence

What I checked:

PR surface

Source +40, Tests +328, Other +4. Total +372 across 26 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 11 936 896 +40
Tests 12 764 436 +328
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 5 1 +4
Total 26 1705 1333 +372

Review metrics

Metric Value Why it matters
Production versus tests and support Production/tooling +941/-897, net +44; tests/support +764/-436, net +328. The pinned introduced diff includes substantial relocation and reindentation; worker isolation explains the original capability growth, but current main now provides that owner and allows a smaller remaining repair.

Labels

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review merge-risk labels are merge-risk: 🚨 session-state, merge-risk: 🚨 availability.

Label justifications:

  • P2: Useful memory-maintenance work remains, but this conflicted draft overlaps a merged publication repair and is not an urgent landing candidate.
  • merge-risk: 🚨 session-state: A stale query can drop the newly published vector index before the outer revision check detects the generation change.
  • merge-risk: 🚨 availability: A permanent orphan-file removal failure prevents every subsequent ordinary sync from reaching indexing.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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.

History

Review history (4 earlier review cycles)
  • reviewed 2026-09-02T17:40:49.515Z sha 1ee7bce :: needs real behavior proof before merge. :: none
  • reviewed 2026-09-02T18:53:29.661Z sha 1ee7bce :: needs real behavior proof before merge. :: [P2] Reuse the query embedding across a revision retry
  • reviewed 2026-10-07T19:36:18.458Z sha 1ee7bce :: needs real behavior proof before merge. :: [P1] Fence stale queries before vector preparation can alter the index | [P2] Reuse the query embedding across a revision retry
  • reviewed 2026-10-07T19:56:47.840Z sha 1ee7bce :: needs real behavior proof before merge. :: [P1] Fence stale queries before vector preparation can alter the index | [P2] Reuse the query embedding across a revision retry | [P2] Keep orphan cleanup failures from blocking ordinary indexing

Reviewed October 18, 2026, 7:40 AM ET / 11:40 UTC (Revision 5).

@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 Sep 17, 2026
@clawsweeper clawsweeper Bot removed the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label Sep 23, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Sep 24, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 7, 2026
@ekinnee

ekinnee commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

I noticed #136327 while checking this cleanup path. Both PRs touch manager-db.ts and manager-sync-ops.ts, but they cover different cases: this PR handles current .memory-reindex-<uuid> shadows during runtime under the reindex lease, while #136327 adds Doctor cleanup for aged legacy .tmp-<uuid> families in archived-primary upgrades. Could we coordinate the shared helper and cleanup owner while preserving those separate safety rules? The existing review findings are also distinct: this PR needs cleanup failures not to block ordinary indexing; #136327 needs to preserve unresolved legacy files until retirement is established. A shared async primitive may help, but I don't think either PR as currently written substitutes for the other.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 18, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 18, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@taishu-oc

Copy link
Copy Markdown

I ran the memory-core suite in this PR against both the PR head and its branch point, to get a before/after on the behaviours this PR targets.

Environment: same clone, same lockfile (no lockfile changes between the two refs), Node v26.12.1, pnpm 12.1.0 as pinned by the repo, one vitest run per file (the extension-memory project).

  • PR head: 1ee7bcea7
  • branch point: 925a31d98
  • the same three test files were copied onto the branch point, so both arms execute identical tests

Results, extensions/memory-core/src/memory/<file>:

test file branch point PR head
manager.reindex-recovery.test.ts (20) 3 failed / 17 passed 1 failed / 19 passed
manager-sync-yield.test.ts (4) 2 failed / 2 passed 4 passed
manager-publish-subprocess.test.ts (2) cannot run (module added by this PR) 2 passed
total 5 failed 1 failed

Failures on the branch point — i.e. exactly the behaviours this PR claims to fix:

  1. rebuilds automatic maintenance after a concurrent promotion changes memory sources
  2. keeps search available while a published reindex converges its cache
  3. recovers after a build-lock timeout without losing data or leaving shadows
  4. replaces the published cache in committed pages between event-loop yields
  5. stops cache publication when the canonical index revision changes

The single remaining failure on the PR head looks test-side rather than behavioural, and it is deterministic (3/3 reruns, identical diff each time):

- Expected { text: "Searchable alpha memory refreshed after the shadow build." }
+ Received { text: "Searchable alpha memory refreshed after the shadow build.\n" }

In manager.reindex-recovery.test.ts the fixture is written with a trailing newline (await fs.writeFile(sourcePath, \${refreshedSource}\n`), around L202) while the assertion compares against the value **without** it ().toMatchObject({ text: refreshedSource });, around L232). Asserting `` ${refreshedSource}\n`` — or using a trimmed /toContain` comparison — should clear it; as written this suite cannot go green regardless of the implementation.

Caveats, to keep the claim scoped: this is unit-level memory-core only. I did not measure end-to-end gateway behaviour, fd/handle growth over time, or search latency percentiles under sustained concurrency, and I did not rebase onto current main. If a long-running fd/latency soak would help the needs proof review, say what shape you want and I will run it.

@ekinnee

ekinnee commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

Is any of the behavior covered by this draft still reproducible on current main? I was looking through the related PRs and found several merged changes that seem relevant:

#149901 moved canonical index publication into the SQLite worker/writer queue.
#112214 added published-generation isolation for searches.
#108663 addressed cache-copy transactions held across await.
Thanks for the before/after testing, @taishu-oc. The comparison against the original branch point is helpful; as you noted, it does not include current main, so I don’t think we can tell from those results how much remains uncovered after the merged changes.

One distinction from the earlier cleanup discussion may also be useful to anyone investigating: #136327 is still unmerged and concerns legacy .tmp-UUID families, while this draft concerns current-format .memory-reindex-UUID runtime shadows. That leaves me unsure whether the cleanup/recovery cases here are already covered upstream or remain a separate gap.

Sharing these links in case they help someone compare the regression cases with current main. I haven’t run that comparison myself.

@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Oct 30, 2026
@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale after 7 days without qualifying human activity.
Without new human activity, Barnacle may close it as not planned 7 days after this message was posted. This is administrative inactivity cleanup, not a claim that the problem is fixed.
A human update restarts the inactivity clock; a new PR head also restarts it. A maintainer can add no-stale for a durable hold, or bad-barnacle to suppress Barnacle. Remove the hold when work can resume.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Nov 5, 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: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: XL stale Marked as stale due to inactivity status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants