Skip to content

fix: memory indexing stops after embedding provider reload - #160048

Closed
NianJiuZst wants to merge 4 commits into
openclaw:mainfrom
NianJiuZst:codex/fix-159912-memory-background-reload
Closed

NianJiuZst wants to merge 4 commits into
openclaw:mainfrom
NianJiuZst:codex/fix-159912-memory-background-reload

Conversation

@NianJiuZst

@NianJiuZst NianJiuZst commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes #159912

What Problem This Solves

Fixes background memory indexing continuing to use a retired embedding plugin after a provider-only reload retains the existing Memory Core instance.

User Impact

Watcher, interval, startup catch-up, and session-update work can acquire the replacement provider without a foreground search or Gateway restart. Already admitted work keeps its original registry, and retiring memory instances reject new work. This PR requires no configuration or database migration.

Why This Change Was Made

A module-load async-context snapshot removes foreground turn state but also restores the registry from module load. Background work now combines turn detachment with fresh admission through its exact, retained Memory Core instance. Startup and session-update preparation await their inner synchronization.

The remaining file-watcher lifecycle calls are migrated too: startup captures its owning instance; cleanup uses detached context without requesting new admission from a retiring instance. Cleanup remains available during retirement, and a failed cleanup promise does not retain the closing caller's turn.

Current main was integrated at 7669e8bd04 to resolve two insertion conflicts. Both the background-task helper and main's watcher-health getter are retained; both the retirement regression and main's polling/health tests remain intact.

Related: #159921 handles registration-time context after an in-process restart and explicitly excludes this retained-instance provider-only reload case.

Evidence

Final validated head: 0a3bf14e68f7fc1c12bb8d26d4780ae6f8aa2a8e. Runtime: Node 24.19.0 and repository-pinned pnpm 12.5.1.

Actual Gateway provider-only reload, repeated after integration

Ran a real isolated Gateway on the clean final head with synthetic memory and a free deterministic embedding plugin. The Gateway, public plugin contracts, WebSocket plugins.reload method, filesystem watcher, and SQLite writes were real. The embedding implementation was a local fixture; this is not live llama-cpp or hosted-provider validation.

The persistent manager and watcher were created under provider A, before its lazy factory had run. Through a persistent Gateway connection, only the embedding plugin was reloaded. A was disposed without acquisition. A subsequent file write was embedded by B and observed directly in SQLite before any further foreground call. Only afterward did a public-SDK identity check confirm the exact manager object and Gateway process were retained.

Redacted final-head before/after reload trace:

candidate: 0a3bf14e68f7fc1c12bb8d26d4780ae6f8aa2a8e; clean=true
before: manager/watch ready; index rows=0; provider A registered; A factory calls=0
reload: pluginIds=[proof-embedding]; generation=3; restartRequired=false
retirement: A disposed; A factory calls still=0
write: synthetic MEMORY.md written after reload response
background: B factory + embedBatch; retired A not used
SQLite: new text present after 2783 ms; foreground calls since reload=0
identity (checked after SQLite): same manager=true; same Gateway process=true
status: files=1; chunks=1; dirty=false
watcher before/after: ready; mode=events; pollingFallback=false; pollIntervalMs=30000
shutdown: Gateway wrapper exited; B closed/disposed; SQLite clean-close receipt recorded

Indexed text: “Aster observatory replacement telescope calibration is verified after provider reload.”

No foreground search, manual registry adoption, callback delivery, fake timer, or scheduling override was used. The retained-manager case intentionally reloads before A is acquired; existing lifecycle policy retires a manager that already owns the outgoing adapter. This is final-code before/after reload evidence, not a negative runtime comparison against the original implementation. Native-event watching was observed; polling fallback and official live providers were not exercised.

Compatibility

The same existing SQLite database remained in use. Before and after reload/indexing: user_version=24, 196 schema objects, identical schema SHA-256 10ffa8c8aa8c11e15eed5b4c8d9a439f4cb6597ab97becc2924dda5df19bbd06. Relative to current main, the production diff changes admission/lifecycle handling, not persisted schema, vector metadata layout, configuration shape, or migration rules.

Additional populated-index run on the same final head:

seed: supported memory index CLI; existing document indexed; provider closed; CLI exit=0
reopen: real Gateway opens that same populated SQLite; original chunk row unchanged
reload: only proof-embedding; A still unacquired; same manager and Gateway process
background: B indexes a different document in 2550 ms; foreground calls since reload=0
preservation: every column in original memory_index_chunks row remains identical
final: files=2; chunks=2; dirty=false; schema/version unchanged
shutdown: provider B closed/disposed; SQLite clean-close receipt; Gateway exited cleanly (80 ms)

The original row's SHA-256 remained f52c16948973fe19be027fb563c7989f4992e45089b5001080feb418020f65a3 from the completed seed CLI through Gateway reopen and new-file indexing. Independent read-only SQL found both the preserved old content and new background-indexed content. This covers same-version hot-reload compatibility against an existing populated index. It is not a published-release migration/upgrade matrix; the provider and documents were isolated synthetic fixtures.

Final-head validation

  • 95 tests passed across 9 files after integration: provider adoption, admission, filesystem watchers, remote watch shutdown, startup catch-up, session races, and observation cleanup. This includes the retirement regression and main's seven polling/health cases. Total selected test command: 200.12 s.
  • Fresh canonical qaRuntime build passed in 92.9 s, including all 96 external plugin bundles, CLI bootstrap checks, native loading of 53 built modules/doctor closures, postbuild checks, and final-head stamps. Runtime bundling used --concurrency 1, OPENCLAW_TSDOWN_MAX_OLD_SPACE_MB=4352, and RAYON_NUM_THREADS=2 for this memory-limited host.
  • Focused watcher-test/dependency typecheck passed with the canonical extension-test compiler options. Formatting, focused syntax lint, and git diff --check passed. Independent review found no remaining P0–P2 findings in the watcher repair or conflict resolution.
  • pnpm test extensions/memory-core/src/memory/file-watcher.lifecycle.test.ts --maxWorkers=1: 20 cases passed, 43.19 s wall. Cold worker preparation accounted for 27.60 s; the new test body took 39 ms. It uses the existing watcher fixture to cover owning-instance capture and physical retirement, which the generic admission tests cannot observe. No real timer or Gateway boot was added to per-PR CI.

Earlier-head evidence and limits

  • Original head 692a05b8: all 12 existing watcher lifecycle tests failed with runInMemoryBackgroundContext is not a function.
  • Repair head 3591280: 88 selected tests and a complete build of its exact source tree passed, including all declaration batches, 96 plugin bundles, 53 native module loads, all 158 public SDK subpaths, and Control UI compilation. Initial attempts hit resource failures; the successful full build used serialized runtime bundling plus GOMEMLIMIT=2GiB and GOGC=50. It printed a non-failing UI gzip-budget advisory (217.2 KiB versus 215 KiB). Line-cap/max-lines and assertion-safety guards also passed on that repair.
  • That complete declaration/UI build is prior-head evidence. After integrating main, the final runtime build, focused typecheck, 95 tests, and real Gateway proof above were rerun. The complete declaration/UI and full repository check/release suites were not rerun on the final head. An extra monolithic extension-test typecheck on the earlier repair head exited137 and is not claimed as passed.

Hosted CI: inherited baseline blocker

Exact-head CI completed: 44 jobs passed and 23 were skipped. Six typecheck jobs failed, making the aggregate gate fail. Every failing typecheck reports the same TS2304: Cannot find name 'readMissingScopeError' at ui/src/components/session-group-defaults-dialog.ts:123 (job log). The core production and plugins-platform test-type graphs passed.

This is inherited from integrated main, not introduced by this PR: the UI file has identical blob f9000417936584d432760473b0a73e462dc69198 at main 7669e8bd04 and this head. Upstream commit 4293f49c54 adds the call without its import; the existing maintainer CI note independently records the same diagnosis. The unrelated UI file is unchanged by this PR.

The five additional failed jobs were inspected individually; each reports only the same missing readMissingScopeError name at the same UI file/line:

Final-head review accepted the runtime proof and found no actionable patch or security findings. Its readiness summary noted incomplete hosted-failure attribution; the individual logs above provide that attribution. The review still retains a generic data-model compatibility checklist item, while its technical assessment states that no stored-data contracts changed; the Compatibility section above now also records a supported-CLI-seeded populated-index run preserving the complete original chunk row while background indexing adds new content after reload. This evidence covers same-version hot reload, not a published-release upgrade matrix. CI is still red until the inherited UI error is addressed. No CI rerun or merge has been requested.

@clawsweeper

clawsweeper Bot commented Sep 28, 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 extensions: memory-core Extension: memory-core size: M labels Sep 28, 2026
@NianJiuZst
NianJiuZst marked this pull request as ready for review September 28, 2026 02:46
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 28, 2026
@clawsweeper

clawsweeper Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 1, 2026, 2:32 AM ET / 06:32 UTC (Revision 5).

ClawSweeper review

What this changes

Memory Core background indexing acquires the current embedding provider through its owning plugin instance and retains startup, session-update, and watcher work until completion.

Merge readiness

⛔ Blocked before merge - 1 item remains

This remains a useful fix: current main still retains the stale background snapshot. The earlier watcher defect is repaired, and the final-head evidence resolves the previous compatibility concern. No actionable patch finding remains.

Likely related people: steipete (high confidence) and jalehman (medium-confidence routing candidate).

Priority: P1
Reviewed head: 0a3bf14e68f7fc1c12bb8d26d4780ae6f8aa2a8e

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused lifecycle repair with convincing production-path proof and no remaining actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Exact-head terminal traces exercise the changed Memory Core owner through a real Gateway provider-only reload, native watcher, replacement embedding acquisition, and SQLite publication before foreground access. A populated-index run preserves existing rows. No stored-data contract changes, so the previous generic migration blocker does not apply; live-provider and polling coverage remain outside the demonstrated scenario.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): Exact-head terminal traces exercise the changed Memory Core owner through a real Gateway provider-only reload, native watcher, replacement embedding acquisition, and SQLite publication before foreground access. A populated-index run preserves existing rows. No stored-data contract changes, so the previous generic migration blocker does not apply; live-provider and polling coverage remain outside the demonstrated scenario.
Evidence reviewed 8 items Pinned introduced change: Reviewed the merge-base-to-head production and test hunks. The actual checkout is the original PR head; the supplied stale test merge was not used to infer removals from current main.
Still necessary on current main: Fetched main still exports the module-load AsyncLocalStorage snapshot, which can restore the predecessor registry when background callbacks execute after provider-only reload.
Latest release also retains the old helper: The latest supplied release contains the same module-load snapshot; this PR's repair is not established as shipped.
Findings None None.
Security None None.

How this fits together

Memory Core turns memory files and session transcripts into a searchable SQLite index using embedding-provider plugins. Background callbacks must follow provider reloads while preserving ownership of work already underway.

flowchart TD
  A[Memory files and transcripts] --> B[Watchers and background timers]
  B --> C[Detach foreground context]
  C --> D[Owning plugin admission]
  D --> E[Current embedding provider]
  D --> F[Reject retired owners]
  E --> G[Searchable SQLite index]
Loading

Before merge

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

Security

None.

PR surface

Source +68, Tests +429, Docs +6. Total +503 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 7 110 42 +68
Tests 6 430 1 +429
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 546 43 +503

Review metrics

Metric Value Why it matters
Production versus regression coverage production +68 net lines; tests and test support +429 net lines Production growth implements fresh owner admission; coverage protects registry adoption, asynchronous settlement, and watcher retirement at distinct boundaries.

Stored data model

Persistent data-model change detected: unknown-data-model-change: extensions/memory-core/src/memory/manager-session-sync-ops.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-watch-ops.ts, vector/embedding metadata: extensions/memory-core/src/memory/manager-watch-ops.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #159912
Summary: This PR directly targets the reported retained-instance background registry defect; the restart-focused PR covers a different lifecycle scenario.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep background indexing bound to Memory Core's live instance, preserving admitted registry generations and existing index contents through reload.

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

Yes: current-main source establishes the retained-snapshot mechanism, and the linked report supplies an interval/adoption regression path. This read-only review did not execute a failing current-main Gateway.

Is this the best way to solve the issue?

Yes: the patch reuses existing plugin-instance admission and migrates all former helper callers while awaiting actual synchronization; registration-time capture alone cannot cover retained-instance provider reloads.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: The linked production report describes hours of silently stalled memory indexing after reload despite healthy embedding services.
  • 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 (terminal): Exact-head terminal traces exercise the changed Memory Core owner through a real Gateway provider-only reload, native watcher, replacement embedding acquisition, and SQLite publication before foreground access. A populated-index run preserves existing rows. No stored-data contract changes, so the previous generic migration blocker does not apply; live-provider and polling coverage remain outside the demonstrated scenario.
  • proof: sufficient: Contributor real behavior proof is sufficient. Exact-head terminal traces exercise the changed Memory Core owner through a real Gateway provider-only reload, native watcher, replacement embedding acquisition, and SQLite publication before foreground access. A populated-index run preserves existing rows. No stored-data contract changes, so the previous generic migration blocker does not apply; live-provider and polling coverage remain outside the demonstrated scenario.

Evidence

What I checked:

  • Pinned introduced change: Reviewed the merge-base-to-head production and test hunks. The actual checkout is the original PR head; the supplied stale test merge was not used to infer removals from current main. (src/plugins/runtime/background-context.ts:13, 0a3bf14e68f7)
  • Still necessary on current main: Fetched main still exports the module-load AsyncLocalStorage snapshot, which can restore the predecessor registry when background callbacks execute after provider-only reload. (extensions/memory-core/src/memory/background-context.ts:6, e304e4ffc6d9)
  • Latest release also retains the old helper: The latest supplied release contains the same module-load snapshot; this PR's repair is not established as shipped. (extensions/memory-core/src/memory/background-context.ts:6, c074824a27c9)
  • Exact-owner admission and retirement: The helper clears the execution frame and retained-consumer context, carries only the Gateway resolver, and enters the exact owner's current registry. Existing runInRegistry checks accepting/revoked state before invoking new work; existing leases pin admitted work and disposal waits for its settlement. No concrete authority bypass was found. (src/plugins/runtime/background-context.ts:19, 0a3bf14e68f7)
  • Final-head real behavior proof: The captured PR body, sourceRevision eeb3146ef09c0bbc3e0496545376d4445476d8c29108520e076b8eea0efd68d1, records a real isolated Gateway, WebSocket plugins.reload, native watcher, and SQLite publication on the exact head. After provider A retired without acquisition, B embedded a new file in 2783 ms before any foreground call; manager and process identity remained unchanged. The deterministic embedding fixture limits provider-specific claims but does not replace the exercised production lifecycle. (extensions/memory-core/src/memory/manager-watch-ops.ts:101, 0a3bf14e68f7)
  • Compatibility and review continuity: The introduced production changes alter admission and completion handling, not schemas, serialization, vector metadata, configuration, or migration rules. Additional exact-head evidence reopens a CLI-seeded populated index, preserves every original chunk-row column, and adds background-indexed content after reload with unchanged schema/version. A published-release migration matrix is unnecessary for this unchanged storage contract. The earlier missing watcher export is fully migrated to owner-bound startup and detached cleanup. (extensions/memory-core/src/memory/file-watcher.ts:98, 0a3bf14e68f7)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • jalehman: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (4 earlier review cycles)
  • reviewed 2026-09-28T02:55:30.198Z sha fd95095cdc65a9c3a65556d14d256dbabc3c4751 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-01T00:40:35.917Z sha 692a05b :: needs real behavior proof before merge. :: [P1] Migrate the file watcher before removing its context export
  • reviewed 2026-10-01T05:50:09.975Z sha 3591280 :: blocked before merge. :: none
  • reviewed 2026-10-01T06:10:01.026Z sha 0a3bf14 :: blocked before merge. :: none

@jalehman
jalehman force-pushed the codex/fix-159912-memory-background-reload branch from fd95095 to 692a05b Compare October 1, 2026 00:32
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 1, 2026
@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. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 1, 2026
@jalehman

jalehman commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Exact-head CI note for 0a3bf14e68f7fc1c12bb8d26d4780ae6f8aa2a8e: check-prod-types fails with TS2304: Cannot find name 'readMissingScopeError' at ui/src/components/session-group-defaults-dialog.ts:123. The completed job log is available at https://github.com/openclaw/openclaw/actions/runs/36822259595/job/110240473303. Other checks and the new review are still running; this is not an all-green result.

This failure is inherited from integrated main 7669e8bd04b1d2cf6b324c7147243406e8a13497, not introduced by the memory repair: the file has identical Git blob f9000417936584d432760473b0a73e462dc69198 at that base and this head. Commit 4293f49c54c adds the call without its import. No CI rerun or branch update was requested for this inspection.

@ekinnee

ekinnee commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Related-work update: #167679 has merged the instance-bound background indexing repair, and #167724 has merged the separate Dreaming state ownership repair.

The latest review on #159912 identifies both merged fixes and notes that this PR remains an open closing candidate. Could the author or a maintainer check whether this PR retains any distinct fix or regression coverage worth carrying forward, and otherwise reconcile it as superseded?

The latest reporter evidence is still from 2026.9.9 without those fixes, so post-fix production validation remains separate from PR cleanup.

@clawsweeper

clawsweeper Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper status: review started.

I am starting a fresh review of this pull request: fix: memory indexing stops after embedding provider reload This is item 1/1 in the current shard. Shard 0/1.

This temporary status tracks the active review worker. The completed review will appear in the durable ClawSweeper review comment.

Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted.

@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Thanks for this work. The outage it targets is now fixed on main by two maintainer PRs. #167679 binds background memory sync to the plugin lifecycle owners. #167756 restarts memory indexing after a provider replacement. Both are on main and will ship in the next release.

We re-verified on current main with a real managed llama.cpp EmbeddingGemma provider. After both an in-process gateway restart --safe and a provider-only plugins.reload, background indexing kept working: new notes were indexed within about 2 s, with no "Plugin llama-cpp was reloaded or disabled" errors. Closing as superseded. The separate orphaned-llama-server problem after a SIGHUP restart is still tracked in #155769.

@steipete steipete closed this Oct 9, 2026
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 P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: L 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.

[Bug]: Memory background callbacks retain retired plugin registry after reload; indexing fails while health stays green

4 participants