Skip to content

fix(memory): bind background sync to plugin lifecycle owners - #167679

Merged
steipete merged 3 commits into
mainfrom
codex/stab-memory-sync-reload
Oct 9, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/stab-memory-sync-reload

Conversation

@steipete

@steipete steipete commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

After any hot plugin reload, Memory Core's background sync fails on every trigger until the Gateway restarts. Reloads are common: editing plugins.load/installs, transcripts, agents.defaults.decisionModel, or a plugin entry. The failures are log-only, so memory indexing silently stops:

[memory] sync failed (session update): Error: Plugin openai was reloaded or disabled; use its current tools.
[memory] sync failed (session-startup-catchup): Error: Memory sync aborted: embedding provider "openai" is configured but unavailable. Refusing to run sync in fts-only fallback mode ...
[memory] sync failed (watch): ...same...

Reproduced on main (dev Gateway, real OpenAI provider, openai embeddings): after a plugins.load hot reload, in-flight turns finish fine, but every later memory sync fails. 7 of 7 failures in the log came after the reload. The nightly dreaming sweep failed the same way ("Plugin memory-core runtime is no longer active").

User Impact

  • Memory keeps indexing across plugin reloads, both provider-only reloads that keep Memory Core and reloads that replace it, for session updates, file watching, intervals, and startup catch-up.
  • Background memory work never keeps the request context of the turn that opened a manager.

Why This Change Was Made

extensions/memory-core/src/memory/background-context.ts took one module-level AsyncLocalStorage.snapshot() at import and ran all background work inside it. That snapshot permanently captured the first plugin registry. Reload correctly retired the memory managers, but their replacements reused the stale snapshot and resolved the retired openai plugin instance.

A plugin-local per-registration snapshot was evaluated and ruled out. Provider-only reloads keep Memory Core's registration (the loader skips re-registering retained instances), and registration is not guaranteed to run outside a turn.

The maintainer approved one additive SDK capability on the existing instance-bound lifecycle facade:

api.lifecycle.runInBackgroundContext<T>(run: () => T): T

It is owned by the plugin-instance lifecycle (src/plugins/plugin-instance-background.ts). It detaches the caller's turn and request context, selects that exact instance's currently adopted registry, preserves host resource bindings, and honors admission, drain, and cleanup authority. Retired managers keep their old owner and never adopt a replacement. No SDK subpaths or package exports were added. Memory Core's session-sync, watcher, interval, startup catch-up, and cleanup paths now use it, and the module-level snapshot and its import side effect are deleted. The remote memory-files worker keeps its own worker-lifetime context.

Evidence

Live (dev Gateway from this change, real OpenAI provider, openai embeddings): four turns on both runtimes were in flight when plugins.load was edited. All four finished correctly. There were 0 [memory] sync failed lines before or after the reload; on main every later trigger fails. The memory index kept growing after the reload: memory_index_chunks rows were written 15–37 s afterwards, all with real text-embedding-3-small embeddings.

Tests:

  • Original-production negative control: both reload regressions (retained and replaced instance, all four triggers) fail on the retired embedding provider.
  • With the fix, both pass (103.6 s wall); the replaced-instance case completes in about 9 s.
  • 100-file memory, plugin, Gateway, and SDK suite: 1,121 passed; the 4 initial failures were one fixture that now uses the owner-aware tool helper. Remote watcher and scheduling harness pass.
  • Full build, types, lint, format, the import-cycle check (0), SDK surface and documentation guards pass. Autoreview is clean through P2.

Production +190/-87, tests/support +1030/-112, docs +19/-0.

Main integration verification

ClawSweeper revision 2 requested integration with main's publication-generation lifetime change in manager.ts. Commit 0c1d63993774b835ba843d1cac8cfc642b3d0cf8 merges main 3b3cd5939993f16017b6747cbcf80a83b49006ef without conflicts and preserves that lifetime change. The PR remains +1242/-200 across 56 files relative to the integrated main. Independent review of the combined candidate found no actionable findings through P2.

Focused proof on the combined candidate: 32 tests passed across five files in 162.63 s wall. This includes retained/replaced Memory Core reloads, detached context, exact-owner retirement, cleanup draining, and publication settlement:

pnpm test src/plugins/memory-background-reload.test.ts src/plugins/api-facades.background.test.ts src/plugins/memory-runtime.owners.test.ts extensions/memory-core/src/memory/manager-close-observation-lifecycle.test.ts extensions/memory-core/src/memory/manager-publication-settlement.test.ts --maxWorkers=1

Prior-head CI run 37899879030 passed at fa781eb3ac9d4cba619621abb90845a137bd82ed (70 successful jobs, 23 skipped). The new head remains subject to its own review and required CI gates.

Replace the module-level async-context snapshot with the approved instance lifecycle background runner. Each callback uses its exact instance and current adopted registry while preserving host resources and independent completion through disposal cleanup.

Carry the runner through runtime, tools, CLI, watchers, manager reuse, and maintenance acquisition. Cover retained and replaced Memory Core reloads through startup, session updates, watch notifications, and intervals. Preserve sync observation throughout the fixture, retain cleanup failures, and share the owner-aware test runner across direct tools and scheduling harnesses.
@clawsweeper

clawsweeper Bot commented Oct 9, 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 gateway Gateway runtime extensions: memory-core Extension: memory-core agents Agent runtime and tooling plugin: file-transfer size: XL labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Memory Core, the plugin that indexes notes and conversations for recall, binds background indexing to its owning plugin instance so indexing continues after plugin reloads.

Example: The operator changes plugins.load while using openai embeddings.

  • Before: Later memory syncs fail with “Plugin openai was reloaded or disabled; use its current tools.”
  • After: Background indexing continues with text-embedding-3-small embeddings after the reload.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A valuable owner-level repair with live Gateway evidence, meaningful retirement regressions, successful reviewed-head CI, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR reports a real development Gateway with OpenAI embeddings exercising plugin reload while turns were active, followed by successful background embedding writes and no sync failures. Retained/replaced-owner controls cover the remaining lifecycle branches, and combined-head checks cover publication settlement. Historical Activity media is unrelated supplemental context; no stored-data contract changes require migration.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: After plugin reloads, new notes and conversation content stop entering memory search until recovery or restart.
Reason: This restores established background-indexing behavior. The existing area's owner authored the repair and recorded the additive lifecycle direction, so no new product decision remains.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary and has no actionable findings. The previous integration requirement is resolved, and the reviewed head has successful CI. Its maintainer-authored lifecycle repair merits landing.

Priority: P1
Reviewed head: 0c1d63993774b835ba843d1cac8cfc642b3d0cf8

Before merge

None.

Findings

None.

Agent review details

How this fits together

Memory Core turns workspace notes and saved conversations into a searchable SQLite index using embedding providers. The plugin lifecycle controls which provider registry background work can use and when that work must finish during reload or shutdown.

flowchart TD
  A[Notes and conversation updates] --> B[Memory background triggers]
  B --> C[Owning plugin lifecycle]
  C --> D{Admission still open?}
  D -->|Yes| E[Current adopted provider registry]
  E --> F[Embedding and indexing]
  F --> G[Searchable SQLite memory index]
  D -->|No| H[Reject new work and drain cleanup]
Loading

Technical review

Best possible solution:

Keep background execution in the existing plugin lifecycle owner and land the coherent Memory Core cutover.

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

Yes: current main still restores the import-time registry snapshot, and the PR supplies a real Gateway reload reproduction plus failing original-production controls. This read-only review verified the mechanism without running target code.

Is this the best way to solve the issue?

Yes: the existing plugin instance already owns registry adoption, admission, and cleanup, so placing detachment there removes the stale snapshot without creating a competing lifecycle owner.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • extensions/memory-core/src/memory/background-context.ts and manager.ts keeps the original intent (98ebcc4: Give background resources their own context so they do not retain completed requests and saved prompts.)
  • extensions/memory-core/src/memory/file-watcher.ts keeps the original intent (52992fb: Consolidate filesystem observation through fs-safe while preserving consumer recovery and teardown.)
  • extensions/memory-core/src/memory/manager-session-sync-ops.ts and manager-watch-ops.ts keeps the original intent (c077e80: Separate synchronization responsibilities while preserving watcher ordering, publication, and session cancellation behavior.)
  • extensions/memory-core/index.ts, runtime-api.ts, and src/runtime-provider.ts keeps the original intent (fix(memory): isolate local embedding services across runtimes #104741: Inject host-scoped local-service acquisition so embedding managers cannot reuse another runtime's lifecycle owner.)
  • src/plugins/plugin-instance.ts registry invocation keeps the original intent (de3010b: Keep ordinary non-joining calls distinct from cleanup authority and prevent disposal from waiting on itself.)
  • extensions/memory-core/src/remote/memory-files-worker.ts keeps the original intent (14cf168: Serve remote workspace memory files through the existing provider contract and packaged worker while keeping indexing on Gateway.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +103, Tests +918, Docs +19, Other +2. Total +1042 across 56 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 21 190 87 +103
Tests 32 1030 112 +918
Docs 1 19 0 +19
Config 0 0 0 0
Generated 0 0 0 0
Other 2 3 1 +2
Total 56 1242 200 +1042

Review metrics

Metric Value Why it matters
Production versus test growth Production +190/-87; tests/support +1030/-112 Production growth provides the approved lifecycle capability and migrates existing triggers; most growth supplies ownership and reload regression coverage.
Plugin lifecycle capability 1 additive capability; 0 new SDK subpaths The public addition stays on the existing lifecycle facade and has an explicit documented contract.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #159912
Summary: This PR repairs the stale background-registry mechanism documented by the canonical issue; other open PRs propose alternative fixes.

Members:

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

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster. Replaced prior rating: 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Plugin reloads can silently stop indexing new notes and conversations while Gateway health remains healthy.
  • merge-risk: 🚨 compatibility: The PR adds a documented plugin lifecycle capability and changes background admission; the area owner's recorded direction covers this additive contract.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster. Replaced prior rating: 🐚 platinum hermit.
  • 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 (2 earlier review cycles)
  • reviewed 2026-10-09T07:23:49.046Z sha 44b54a8 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-09T07:43:10.227Z sha fa781eb :: needs changes before merge. :: none

Reviewed October 9, 2026, 4:07 AM ET / 08:07 UTC (Revision 3).

The PR wrapper extracts only its inventory; the new plugin-instance background
runner and its two imports were missing, breaking wrapper provisioning and the
eager-import closure check. Also prune the now-obsolete Memory Core mock baseline
entry.
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 9, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The revision-2 requirement is addressed at head 0c1d63993774b835ba843d1cac8cfc642b3d0cf8: main 3b3cd5939993f16017b6747cbcf80a83b49006ef was merged without conflicts, preserving the publication-generation lifetime in manager.ts. The combined candidate passed 32 focused reload, ownership, cleanup, and publication-settlement tests in 162.63 seconds; independent review is clean through P2. Exact-head CI run 37901419378 is successful (70 jobs passed, 23 skipped). The PR body includes the exact focused test command.

@clawsweeper

clawsweeper Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit ee5dea9 into main Oct 9, 2026
151 of 152 checks passed
@steipete
steipete deleted the codex/stab-memory-sync-reload branch October 9, 2026 08:13
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

RomneyDa pushed a commit that referenced this pull request Oct 9, 2026
Backport #167724 together with its required #167679 lifecycle background-context owner. Preserve the release branch database admission implementation and its existing detached context owner.

(cherry picked from commit ee5dea9)

(cherry picked from commit 226b033)
(cherry picked from commit 474bbab335a6cf7b1157097612b81d2d6098e260)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 10, 2026
…w#167679)

* fix(memory): bind background sync to lifecycle owners

Replace the module-level async-context snapshot with the approved instance lifecycle background runner. Each callback uses its exact instance and current adopted registry while preserving host resources and independent completion through disposal cleanup.

Carry the runner through runtime, tools, CLI, watchers, manager reuse, and maintenance acquisition. Cover retained and replaced Memory Core reloads through startup, session updates, watch notifications, and intervals. Preserve sync observation throughout the fixture, retain cleanup failures, and share the owner-aware test runner across direct tools and scheduling harnesses.

* fix(memory): list lifecycle runner modules in the PR wrapper inventory

The PR wrapper extracts only its inventory; the new plugin-instance background
runner and its two imports were missing, breaking wrapper provisioning and the
eager-import closure check. Also prune the now-obsolete Memory Core mock baseline
entry.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant