Skip to content

fix(memory): resume background reindex after foreground turns - #178979

Merged
steipete merged 4 commits into
mainfrom
dbasync/memresume
Oct 21, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/memresume

Conversation

@steipete

@steipete steipete commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes background memory rebuilds repeatedly discarding completed indexing work when a foreground agent turn starts. A large rebuild could restart for each turn and fail to publish until activity stopped.

User Impact

SQLite memory rebuilds now keep their private shadow index across foreground turns and resume on the next sync, including a bootstrap search. Searches continue to use the published index until the replacement is complete. The existing foreground yield points are unchanged.

Owner close, shadow errors, provider or published-identity changes, and an explicit full rebuild discard the retained work. Process restart still starts over. PostgreSQL retains its existing discard-on-yield behavior; resumption there needs a stage-backed spool rather than holding a pooled connection between syncs.

Why This Change Was Made

The background sync returns when it yields, releasing the existing sync promise and reindex lock. The memory owner retains the shadow and completed-source cursor; it does not leave an awaited stack paused. This lets a foreground bootstrap resume the same work without a dependency cycle.

Completed session sources are skipped, and the shadow's existing memory-file hashes preserve completed memory work. Source-change notifications and targeted sync requests invalidate the affected completed entries before publication. The final publication and Forget/revision boundary remain unchanged. One backend capability preserves PostgreSQL's current lifetime contract.

Removed the discard-and-full-retry path for SQLite foreground yields and the duplicate shadow-close wrapper. The rebuild operation moves into its own owner layer so shadow lifetime is explicit. No schema, cursor table, new lock, freshness probe, or keyword-search change. Net change: production +200 lines, tests +315, docs +4; the growth is retained progress/lifecycle handling and regressions, with existing rebuild code extracted rather than duplicated.

Evidence

  • Two planned Codex reviews plus a coordinator-authorized review of the watcher-admission correction completed with no actionable P0–P2 findings. PostgreSQL review approved production head d121309e77400b1360d261b7aca02950244eab1a; its unchanged stage-discard and connection-lifetime behavior were verified. Final head 41a4b0cee824498dcecfc5020e546e0e4f7d24c1 changes two test files only; all measured/reviewed production blobs are identical. The coordinator approved the exact final head by test-only extension; all three PostgreSQL conformance shards also passed on the identical production head.
  • Focused owner and consumer proof covers 156 distinct passing tests in 18 files. The watcher correction passed all 16 tests in four files, extension production/test types, type-aware lint, and formatting. The two CI-replay files also passed all 36 tests on the base.
  • Regressions cover no repeated completed groups, bootstrap resume with a timeout guard, changed memory/session sources at first publication, normalized targeted archive requests, close during suspension, unsupported-backend discard, and provider fallback after suspension. The original resume/close behavior regressions fail on the base.
  • Production types, type-aware lint, Madge, export collisions, and Knip passed (zero unused exports). T1 calls 171 → 171; deprecated-only compatibility calls 15 → 15; dialect constructs 0 → 0. check:changed reports three max-lines suppressions in untouched UI files; the same rule and files fail on exact base beb97b5b7dc3 (chat-message.test.tsx, config-page-state.ts, sessions-page-state.ts). No new static findings remain.
  • Initial large synthetic diagnosis: quiet 1 shadow / 0 discards / 1,251 groups / 344.801 seconds to publish; foreground turns every 60 seconds caused 8 shadows / 7 discards / 442 discarded groups / 771.371 seconds to publish. These diagnosis numbers establish the defect and are not candidate savings.

The large synthetic comparison uses current main at start, beb97b5b7dc368d8cafa507c781a32e9299a024d, against production head d121309e77400b1360d261b7aca02950244eab1a. One observation per arm/scenario: no additional turns, or real synthetic Gateway turns every 60 seconds until first publication (maximum ten minutes, then quiet recovery). These are not repeated-run medians; timing includes observer overhead and shared-host load. Host load was lower on the candidate: one-minute load before/after was 10.87/16.70 (base quiet), 15.17/14.10 (base cadence), 7.78/6.82 (head quiet), and 6.60/4.42 (head cadence), on 32 cores. Timings are observations, not isolated causal speedups; the removed-work counts are direct.

Scenario / version SQL Requests MAIN Shadows opened / discarded Groups written / discarded First open → publish
Quiet base 406,523 45,698 135 1 / 0 1,251 / 0 301.828 s
Quiet head 406,741 45,719 135 1 / 0 1,251 / 0 277.879 s
60-second cadence base 1,344,975 200,028 135 8 / 7 2,431 / 1,180 767.727 s
60-second cadence head 407,770 46,113 135 1 / 0 1,251 / 0 352.515 s

The candidate recorded five foreground yield → owner return → same-shadow resume intervals, preserving prefixes of 336, 336, 336, 697, and 1,048 groups. No groups completed while suspended. It published during the cadence after five successful turns; the baseline needed ten turns and quiet recovery. Whole-run savings therefore also include the shorter run and fewer turns, not only avoided rebuilding. Candidate turn durations were 6.197–6.492 s (median 6.212 s).

Direct discarded-shadow cost fell from 851,050 SQL / 36,262 requests-with-SQL to zero; these exclude preparation on other stores and zero-SQL requests. Group replacements fell from 386,019 SQL / 2,431 requests to 198,740 / 1,251; session preparation fell from 19,465 requests to 10,004. Core quiet rebuild/cache counts match exactly, and background preparation width remains eight. Quiet whole-run +218 SQL / +21 requests includes transcript-index maintenance +209 / +19 and two extra initial vector-setup requests (+18 SQL), before any session group or suspension, through byte-identical vector setup. All increases are retained in the attribution.

Frozen-v3.1 standard pair: whole workload 3,004 SQL / 790 requests / 98 MAIN → 3,031 / 799 / 98. Ten warm causal turns have median [range] 46 [46–50] SQL → 46 [46–50], 11 [11–12] requests → 11 [11–13], and 0 MAIN → 0. Means are 46.7 / 11.2 / 0 → 46.7 / 11.3 / 0. All memory read, preparation, group-replacement and cache families are unchanged. The single additional warm request is the net of unchanged auth-profile reads (−4 SQL / −1 request), commit patch (+3 / +1) and plugin catalog (+1 / +1). Whole-run +27 SQL / +9 requests is entirely other maintenance/usage/deletion, model/plugin, commit, quarantine and metadata operations. Native errors are zero and duration coverage is complete in every accepted arm. Frozen harness hashes are unchanged.

Final test-only repair passed all 18 tests in the workspace-watcher and resume files (43.3 seconds command wall time), extension test types, type-aware lint, mock-export ratchet, formatting and diff checks. Watcher tests now await the existing owner-idle boundary and assert published rows before a search can repair them; bounded-drain and close assertions remain. Earlier CI repairs also retained pathname-custody protection and awaited cleanup while clearing successfully closed shadow state.

CI run 39544365556 identified four inherited type errors: ui/src/components/overlay-registry.ts:32, TS2339, openClawModalLayers absent from Document. They match current-main run 39544978413 at 5be2b73ebf46, jobs 119041151110, 119041151122, 119041151443, and 119041151192; these UI files are untouched. The two in-scope failures (obsolete watcher synchronization and the mock annotation) are fixed in the final test-only commit. Final-head CI 39547065636 passed all 42 executed jobs (25 skipped), including all three PostgreSQL conformance shards. The required openclaw/ci-gate is green (publisher 39548862776). CI tested merge commit da733ab558545d520f319f9060a0413eb5a42794, whose main parent fbc99b8c03f5 includes UI type fix 20d2826d7c6. No branch integration was needed; the actual merge commit, rather than the stale API base field, was verified.

Large-fixture validation caught an earlier candidate losing the background flag at watcher/automatic-recall admission; its measurements are excluded. The final watcher-boundary regression fails on that candidate (three groups instead of one after foreground activity starts), and passes with preserved background admission, no writes during suspension, and one final publication. The accepted candidate restores eight-source preparation and removes the rejected candidate’s +1,670 SQL / +391 cache-request anomaly.

@clawsweeper

clawsweeper Bot commented Oct 21, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-21T05:04:04.098377Z 41a4b0c New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: memory-core Extension: memory-core size: XL labels Oct 21, 2026
@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. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed 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. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR retains unfinished SQLite memory rebuilds across foreground turns and resumes them on the next sync.

Example: A foreground turn interrupts a rebuild after 8 of 17 session sources finish.

  • Before: The shadow is discarded, so the next rebuild repeats those 8 sources.
  • After: The next sync reuses the shadow and processes the remaining sources, revisiting completed sources when notified of changes.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-scoped repair with focused regression evidence, but recovery defects and a confirmed consumer-test failure block readiness.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied evidence exercises real memory owners in an in-process harness, while candidate Gateway measurements remain pending.
Patch quality 🦪 silver shellfish (2/6) 3 actionable review findings remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Foreground turns repeatedly erase completed rebuild work, delaying publication of a large memory index.
Reason: The maintainer-authored direction preserves foreground priority and published-index availability without adding configuration, schemas, or another scheduler.

Merge readiness

⛔ Needs changes before merge - 4 items remain

Keep open: this PR addresses a current rebuild problem, but two recovery regressions and a diff-caused CI assertion need repair.

Priority: P2
Reviewed head: 8792a87aa647ab57e0dd6f690022bac9f3e97d33

Before merge

  • Restore the sessions-only full-rebuild marker reset (P2) - For a sessions-only index, vector recovery calls markConfiguredSourcesForFullReindex(), which deliberately sets memoryFullRetryDirty even though the memory source is disabled. The previous rebuild cleared that marker with clearMemoryRetryState() when no memory files were being rebuilt. The extracted path omits that reset, and executeSourceSync cannot clear it because shouldSyncMemory is false. After a successful repair, subsequent syncs therefore keep selecting another full shadow rebuild. Restore the no-memory reset after source completion, while retaining it across suspension and restoring it on failure.
  • Release terminal shadow state when file cleanup loses custody (P2) - If a closed shadow pathname has been replaced, assertShadowPath() throws before reindexState is cleared. The rebuild catches and logs that cleanup failure, but every later sync enters resumeReindex(), sees the closed shadow, and calls the same failing discard again; close() also keeps rejecting through retryFailedClose(). The existing replaced-shadow regression exercises this case, and exact-head CI reports the error through discardReindex. Preserve the replacement file and the identity guard, but retire the terminal rebuild state once its resources have closed; retain retry ownership only for resources that still need release.
  • Update the consumer assertion for incremental shadow filling (P2) - The new rebuild intentionally calls executeSourceSync with needsFullReindex:false so retained shadow hashes can skip completed memory files. The existing search-maintenance test still requires syncMemoryFiles to receive true, causing checks-node-changed-extensions-bundle-3 to fail at line 508. Remove or update this internal call-shape assertion while preserving the test's published-search and eventual-content assertions.
  • Explain or restore the original intent of Sessions-only rebuild retry reset - 4ab6862: fix(memory): recover from same-file legacy index divergence #110216 makes migrated derived indexes converge; its patch replaces the no-memory dirty reset with clearMemoryRetryState, clearing the full-rebuild marker too.

Findings

  • [P2] Restore the sessions-only full-rebuild marker reset — extensions/memory-core/src/memory/manager-reindex-ops.ts:174-178
  • [P2] Release terminal shadow state when file cleanup loses custody — extensions/memory-core/src/memory/manager-reindex-ops.ts:63-68
  • [P2] Update the consumer assertion for incremental shadow filling — extensions/memory-core/src/memory/manager-search-orchestration.test.ts:508-510

Provenance

Tests

  • Missing end-to-end proof: The candidate Gateway workload results for quiet and recurring foreground activity remain pending; the body reports base-red/head-green evidence for the original resume and close regressions.
Agent review details

How this fits together

Memory Core converts memory files and session transcripts into a private replacement index, then atomically publishes it while searches continue reading the existing index.

flowchart TD
  A[Memory files and transcripts] --> B[Memory sync owner]
  C[Foreground activity] --> B
  B --> D[Retained SQLite shadow]
  D --> E[Publication worker]
  E --> F[Published index]
  F --> G[Memory search]
Loading

Technical review

Best possible solution:

Retain the existing shadow under the memory owner while restoring sessions-only retry cleanup and releasing terminal shadow state safely.

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

Current main directly exposes the discard-on-interruption path, and the supplied baseline diagnosis records repeated shadows and discarded groups; no target code was executed during this review.

Is this the best way to solve the issue?

Keeping progress with the existing memory owner is a focused solution, and the extraction removes the superseded rebuild implementation, but recovery markers and terminal cleanup must preserve their previous contracts.

Full review comments:

  • [P2] Restore the sessions-only full-rebuild marker reset — extensions/memory-core/src/memory/manager-reindex-ops.ts:174-178
    For a sessions-only index, vector recovery calls markConfiguredSourcesForFullReindex(), which deliberately sets memoryFullRetryDirty even though the memory source is disabled. The previous rebuild cleared that marker with clearMemoryRetryState() when no memory files were being rebuilt. The extracted path omits that reset, and executeSourceSync cannot clear it because shouldSyncMemory is false. After a successful repair, subsequent syncs therefore keep selecting another full shadow rebuild. Restore the no-memory reset after source completion, while retaining it across suspension and restoring it on failure.
    Confidence: 0.98
  • [P2] Release terminal shadow state when file cleanup loses custody — extensions/memory-core/src/memory/manager-reindex-ops.ts:63-68
    If a closed shadow pathname has been replaced, assertShadowPath() throws before reindexState is cleared. The rebuild catches and logs that cleanup failure, but every later sync enters resumeReindex(), sees the closed shadow, and calls the same failing discard again; close() also keeps rejecting through retryFailedClose(). The existing replaced-shadow regression exercises this case, and exact-head CI reports the error through discardReindex. Preserve the replacement file and the identity guard, but retire the terminal rebuild state once its resources have closed; retain retry ownership only for resources that still need release.
    Confidence: 0.99
  • [P2] Update the consumer assertion for incremental shadow filling — extensions/memory-core/src/memory/manager-search-orchestration.test.ts:508-510
    The new rebuild intentionally calls executeSourceSync with needsFullReindex:false so retained shadow hashes can skip completed memory files. The existing search-maintenance test still requires syncMemoryFiles to receive true, causing checks-node-changed-extensions-bundle-3 to fail at line 508. Remove or update this internal call-shape assertion while preserving the test's published-search and eventual-content assertions.
    Confidence: 1

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 c622b70b2b4c.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test extensions/memory-core/src/memory/manager-reindex-resume.test.ts extensions/memory-core/src/memory/manager.reindex-recovery.test.ts extensions/memory-core/src/memory/manager.borrowed-connection.test.ts extensions/memory-core/src/memory/manager-search-orchestration.test.ts
  • Prove a sessions-only vector-recovery rebuild clears its full-rebuild marker and a subsequent unchanged sync creates no new shadow.
  • Prove replacement shadow files survive rejected cleanup while subsequent sync and manager close can finish.
  • Run affected extension test types and type-aware lint, then verify the exact-head extension CI results.

What I checked:

PR surface

Source +188, Tests +299, Docs +4. Total +491 across 15 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 10 518 330 +188
Tests 4 301 2 +299
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 15 823 332 +491

Review metrics

Metric Value Why it matters
Production versus test growth production +188 lines; tests and test support +299 lines The production increase retains rebuild progress and lifecycle state; the test increase covers distinct interruption, invalidation, shutdown, bootstrap, backend, and fallback failures.

Labels

Label changes:

  • add P2: Repeated background rebuild work and the introduced recovery defects affect memory indexing, while the published index remains available.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Repeated background rebuild work and the introduced recovery defects affect memory indexing, while the published index remains available.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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.

Reviewed October 20, 2026, 11:30 PM ET / October 21, 2026, 03:30 UTC.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 680bdd955c

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +343 to +344
if (this.syncing || this.reindexProgress) {
return await this.syncAdmitted(params);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve background mode when resuming search maintenance

When a suspended reindex exists and a search starts detached maintenance (for example, because a memory-file change left dirty set), this path resumes it through syncAdmitted without { background: true }. Consequently syncIsBackground becomes false, so shouldYieldSessionIndexing() ignores an active foreground agent turn and the resumed rebuild can process the entire remaining session corpus in 128-file groups instead of yielding. Pass the background option when this nominally background path reuses the serving manager.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 6387f3a into main Oct 21, 2026
130 of 132 checks passed
@steipete
steipete deleted the dbasync/memresume branch October 21, 2026 05:20
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
…aw#178979)

Keep the SQLite shadow and completed-source cursor in the memory owner when background indexing yields. Return from sync so the existing lock is released, resume on the next sync, and reconcile changed sources before atomic publication.

Discard on close, shadow failure, provider/identity changes, and explicit full rebuild. Process restart still starts over. PostgreSQL retains discard-on-yield until its stage-backed spool supports suspension without pinning a pooled connection.

Prove same-shadow resume, changed-source reconciliation, close cleanup, bootstrap without deadlock, unsupported-backend discard, and watcher admission. The large synthetic 60-second cadence lost zero groups versus 1,180 on base; warm memory work counts are unchanged.
fuller-stack-dev added a commit that referenced this pull request Oct 22, 2026
#178979 moved watch notifications, session startup catch-up and session
deltas from Memory Core's public sync() to its background sync owner so
indexing can yield to foreground turns and resume. Memory Core's own tests
were updated, but src/plugins/memory-background-reload.test.ts still waited
for sync() calls that no longer happen, so three cases timed out after 120 s.

Observe the background sync owner instead, keeping every outcome assertion.

The reload-deadline case also passed only when an earlier case had already
marked the main agent's index live in this process. A cold service start
leaves untouched indexes closed, so open the index before waiting for its
first watcher.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 23, 2026
…180826)

openclaw#178979 moved watch notifications, session startup catch-up and session
deltas from Memory Core's public sync() to its background sync owner so
indexing can yield to foreground turns and resume. Memory Core's own tests
were updated, but src/plugins/memory-background-reload.test.ts still waited
for sync() calls that no longer happen, so three cases timed out after 120 s.

Observe the background sync owner instead, keeping every outcome assertion.

The reload-deadline case also passed only when an earlier case had already
marked the main agent's index live in this process. A cold service start
leaves untouched indexes closed, so open the index before waiting for its
first watcher.
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 P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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