Skip to content

fix(memory): stop livelocked full-reindex retries launched by every search - #135800

Closed
LiuwqGit wants to merge 2 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-135754-reindex-backoff
Closed

LiuwqGit wants to merge 2 commits into
openclaw:mainfrom
LiuwqGit:feat/issue-135754-reindex-backoff

Conversation

@LiuwqGit

@LiuwqGit LiuwqGit commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Under sustained concurrent writes to a single agent's memory index, a full reindex reliably loses its publish race ("Memory index changed while full reindex was building ... retry the full reindex"). The failed detached maintenance restores the dirty generation on the serving manager, and because search-triggered sync is enabled by default with no cooldown or single-flight guard, the very next memory search immediately launches another detached full rebuild — repeating forever with no backoff. Each attempt writes a fresh multi-hundred-MB shadow database, climbing gateway memory and degrading responsiveness (issue reports memory pressure: level=warning, slow SQLite transaction hold, and WebSocket probe timeouts).

Fixes #135754

Why This Change Was Made

  • The livelock lives at the serving maintenance owner: syncPublishedIndexInBackground handed the dirty generation to a new detached maintenance manager on every search, with no record of a recent failure and no coalescing of concurrent triggers.
  • The revision-conflict rejection itself is correct (it protects the newer live index), so the repair defers and coalesces retries instead of weakening publication: a MemorySearchMaintenanceRetryGate single-flights concurrent search-triggered attempts into the in-flight one, and after a failure defers the next detached attempt behind an escalating cooldown (30 s doubling, capped at 15 min).
  • An attempt that resolves but returns an incomplete reason (its maintenance manager stayed dirty and the generation was restored) counts as a failure for the cooldown exactly like a thrown error, so a resolved-but-still-dirty outcome cannot relaunch rebuilds on every subsequent search either; the escalation resets only after an attempt fully clears the handed-off generation.
  • Dirty state stays owned by the serving manager, so a later search retries and recovers once write volume settles — no schema or public configuration change, matching the deliberately unexposed sync.* knobs.
  • Out of scope (documented/intentional per review): rememberAcrossConversations adding a sessions source on top of sources: ["memory"], and deleted-archive indexing policy.

User Impact

  • Busy agents with concurrent sessions no longer continuously rebuild full shadow indexes after a lost publish race; gateway memory, disk usage, and UI responsiveness stop degrading.
  • Memory recall itself is unchanged: the published index keeps serving reads, and the deferred retry still lands once the index stays still long enough.
  • Explicit sync paths (CLI openclaw memory index --force, watcher, interval, targeted session syncs) are untouched — only search-triggered detached maintenance is gated.

Evidence

Real environment tested: yes (local repo worktree; the suite exercises real SQLite databases through the extension harness, including an end-to-end case with no maintenance-manager stub that drives the public search() API through a real detached maintenance generation)

Exact steps or commands run after this patch:

# RED: failing regression captured before editing
node scripts/run-vitest.mjs run extensions/memory-core/src/memory/manager-search-maintenance.test.ts \
  -t "incomplete maintenance outcome"
# GREEN: format + lint + same-directory tests + type check
skills/fix-pr/scripts/validate.sh extensions/memory-core/src/memory/manager.ts \
  extensions/memory-core/src/memory/manager-search-maintenance.ts \
  extensions/memory-core/src/memory/manager-search-maintenance.test.ts

Evidence after fix: five regressions pass, covering coalescing, failure cooldown, incomplete-outcome cooldown, real end-to-end publish, and search-driven cooldown recovery.

 RED (before the incomplete-outcome fix):
 × memory search maintenance retry gating > defers retries after an incomplete maintenance outcome that leaves the index dirty
   → expected "vi.fn()" to be called 1 times, but got 2 times

 GREEN (after):
 ✓ memory search maintenance retry gating > coalesces concurrent search-triggered maintenance into a single detached attempt
 ✓ memory search maintenance retry gating > defers search-triggered maintenance retries after a failed attempt and recovers later
 ✓ memory search maintenance retry gating > defers retries after an incomplete maintenance outcome that leaves the index dirty
 ✓ memory search maintenance retry gating > publishes new memory content through a search-triggered maintenance generation
 ✓ memory search maintenance retry gating > stops later searches from relaunching maintenance while a failed attempt cools down

 Test Files  2 passed (2)
      Tests  26 passed (26)
[validate] 全部通过 ✅   (oxfmt + oxlint + same-directory tests + tsgo:core)

Observed result after fix: single-flight coalescing, failure and incomplete-outcome cooldowns, and later recovery all verified through the public search() path.

  • Owner-boundary sequence through search(): a dirty serving manager's first search hands the generation to a detached maintenance manager; a failed attempt restores dirty state and the immediately following search acquires no new maintenance manager; after the cooldown a later search retries and clears dirty state plus the last sync error. The end-to-end case with no stubs shows the real detached generation publishing new content that becomes searchable.
  • Escalating cooldown: 30 s base, doubling per consecutive failure or incomplete outcome, capped at 15 minutes, reset only on a fully cleared generation.

What was not tested: sustained multi-GB concurrent-write load was not reproduced locally; the retry scheduling behavior at the serving owner was verified from source. Full CI lanes (pnpm test:extension memory-core, pnpm check:test-types) run on GitHub Actions.

…earch

A failed detached search-triggered maintenance run (for example a
publish revision conflict while a full reindex was building under
concurrent writes) restores the dirty generation on the serving
manager. Because search-triggered sync is enabled by default with no
cooldown or single-flight guard, the very next memory search could
immediately launch another detached full rebuild that loses the same
revision race, repeating forever. Each attempt rebuilds a multi-GB
shadow database, spiking gateway memory usage and degrading
responsiveness.

Defer and coalesce these retries at the serving maintenance owner: a
new gate single-flights concurrent search-triggered attempts into the
in-flight one and defers retries behind an escalating cooldown
(30s doubling up to 15 minutes) after a failure, resetting after a
successful run. Dirty state stays owned by the serving manager so a
later search still recovers once writes settle.

Fixes openclaw#135754
@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 clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 2, 2026
@clawsweeper

clawsweeper Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed September 2, 2026, 12:04 AM ET / 04:04 UTC.

ClawSweeper review

What this changes

The branch adds a per-manager single-flight and exponential-cooldown gate for detached search-triggered Memory Core index maintenance, with regression coverage for failed, incomplete, and recovered maintenance.

Regression provenance

Possible regression — probable (reviewed change; failure trace). No predecessor PR is attributed.

Merge readiness

⛔ Blocked until real behavior proof from a real setup is added - 6 items remain

Keep open: the retry gate addresses the reported relaunch path and fixes the prior resolved-but-dirty gap, but the PR would auto-close a broader issue it explicitly leaves partially unresolved and still lacks real behavior proof.

Priority: P1
Reviewed head: ca2e0aa53ea47bd5bb4809657a5b9bd08b4cb74f

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The implementation appears focused and resolves the prior functional finding, but the issue-linking defect and missing real behavior proof block merge readiness.
Proof confidence 🦪 silver shellfish (2/6) Needs real behavior proof before merge: The changed production owner is the serving manager’s detached search-maintenance handoff. The PR body supplies passing Vitest and validation output, including a SQLite fixture and public search coverage, but not independent real-environment evidence of a concurrent-write conflict, cooldown suppression, and recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Needs proof Needs real behavior proof before merge: The changed production owner is the serving manager’s detached search-maintenance handoff. The PR body supplies passing Vitest and validation output, including a SQLite fixture and public search coverage, but not independent real-environment evidence of a concurrent-write conflict, cooldown suppression, and recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed 7 items Current-main search trigger: Current main starts detached maintenance whenever enabled search sees dirty state, and only tracks the resulting promise for teardown.
Current-main conflict behavior: Full-reindex publication rejects when the live revision changed during the rebuild, providing the failure that restores retry state.
Introduced owner-boundary repair: The PR places the gate on the serving manager around detached maintenance, preserving the existing handoff and restoration owner.
Findings 1 actionable finding [P1] Avoid auto-closing the broader linked issue
Security None None.

How this fits together

Memory Core serves agent memory searches from a SQLite-backed index. Searches can request detached maintenance to refresh a dirty index; this change decides whether a retry may start or must wait.

flowchart LR
  Search[Memory search] --> Serving[Serving index manager]
  Serving --> Gate[Retry and single-flight gate]
  Gate --> Maintenance[Detached maintenance manager]
  Maintenance --> Publish[Publish refreshed index]
  Maintenance --> Restore[Restore dirty generation]
  Restore --> Gate
Loading

Before merge

  • Add real behavior proof - Needs real behavior proof before merge: The changed production owner is the serving manager’s detached search-maintenance handoff. The PR body supplies passing Vitest and validation output, including a SQLite fixture and public search coverage, but not independent real-environment evidence of a concurrent-write conflict, cooldown suppression, and recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Avoid auto-closing the broader linked issue (P1) - This change fixes the search-maintenance retry path, but the PR body uses closing syntax for Full memory reindex retries forever under concurrent writes (no backoff); rememberAcrossConversations indexes session transcripts despite sources: ["memory"] #135754 while explicitly leaving its source-filtering and deleted-archive concerns out of scope. Use a non-closing reference so merging does not hide remaining work.
  • Resolve merge risk (P1) - The PR body uses closing syntax for Full memory reindex retries forever under concurrent writes (no backoff); rememberAcrossConversations indexes session transcripts despite sources: ["memory"] #135754 even though it explicitly leaves that report’s source-filtering and deleted-archive concerns out of scope; merging would close remaining tracked work.
  • Resolve merge risk (P1) - The submitted terminal output is a Vitest and validation transcript, not a redacted real-runtime trace of a concurrent-write publish conflict, suppressed immediate retriggers, and later recovery.
  • Resolve merge risk (P1) - The bug fix adds 67 net production lines; the state is owner-specific and appears justified, but the added retry owner should remain the only new production surface.
  • Complete next step (P2) - The remaining work is a contributor body correction and real-behavior proof, neither of which is suitable for automated repair.

Findings

  • [P1] Avoid auto-closing the broader linked issue — extensions/memory-core/src/memory/manager.ts:304-327
Agent review details

Security

None.

PR surface

Source +67, Tests +229. Total +296 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 2 74 7 +67
Tests 1 229 0 +229
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 303 7 +296

Review metrics

Metric Value Why it matters
Production versus test delta production +67 net (74 added, 7 removed); tests +229 The new per-manager retry state is limited to the maintenance owner and is accompanied by targeted regression coverage.

Stored data model

Persistent data-model change detected: unknown-data-model-change: extensions/memory-core/src/memory/manager-search-maintenance.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #135754
Summary: This PR is a candidate repair for the search-triggered reindex-retry portion of the linked report.

Members:

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

Merge-risk options

Maintainer options:

  1. Correct linkage and prove the runtime sequence (recommended)
    Replace the broad closing reference with a non-closing link and add redacted after-fix evidence of search-triggered retry suppression followed by recovery.
  2. Pause for narrower issue ownership
    Keep the PR unmerged if the linked report must remain the canonical tracker for its source-filtering and archive-indexing work.

Technical review

Best possible solution:

Retain the serving-manager retry gate, change the broad issue reference to non-closing linkage, and attach a redacted post-fix runtime trace that shows conflict, suppression during cooldown, and later recovery.

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

Yes, from source: a revision-conflict rebuild restores dirty retry state while each subsequent dirty search schedules detached maintenance. The review did not execute the external contributor’s branch.

Is this the best way to solve the issue?

Yes for the retry defect: the serving manager owns both the search trigger and retry state, while the existing publication conflict protection remains intact. The issue linkage and real-runtime proof still need correction.

Full review comments:

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 4e36c68976a9.

Labels

Label changes:

  • add merge-risk: 🚨 other: The PR’s closing syntax would automatically resolve a broader issue despite explicitly unimplemented portions.

Label justifications:

  • P1: Repeated full-index rebuilds under concurrent writes can materially degrade a busy gateway.
  • merge-risk: 🚨 availability: The change intentionally delays search-triggered index-maintenance retries that affect gateway resource pressure and recovery timing.
  • merge-risk: 🚨 other: The PR’s closing syntax would automatically resolve a broader issue despite explicitly unimplemented portions.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The changed production owner is the serving manager’s detached search-maintenance handoff. The PR body supplies passing Vitest and validation output, including a SQLite fixture and public search coverage, but not independent real-environment evidence of a concurrent-write conflict, cooldown suppression, and recovery. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Evidence

What I checked:

Likely related people:

  • Hoi Hin Adrian Ip: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

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 (2 earlier review cycles)
  • reviewed 2026-09-02T02:17:20.652Z sha 86fb4b3 :: needs real behavior proof before merge. :: [P1] Cool resolved-but-dirty maintenance outcomes
  • reviewed 2026-09-02T02:49:18.877Z sha 86fb4b3 :: needs real behavior proof before merge. :: [P1] Cool resolved-but-dirty maintenance outcomes

A detached search maintenance can resolve while its manager stays
dirty (for example a keyword-only provider fallback): the generation
is restored to the serving manager and an incomplete reason is
reported instead of throwing. The retry gate treated that as a
success and reset its cooldown, so the next search could immediately
relaunch a full rebuild. Count an incomplete outcome as a failure for
the escalating cooldown, and reset the escalation only after an
attempt fully clears the handed-off generation.

Move the retry-gate regressions into a dedicated test file and add
coverage driving the public search() path, including an end-to-end
case where the real detached maintenance generation publishes new
content without any maintenance-manager stub.

Addresses review feedback for openclaw#135754
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Sep 2, 2026
@obviyus

obviyus commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Thanks @LiuwqGit — I rechecked the reported write → search → detached full-reindex order on current main at 4e36c68976a9474e6c7bf6dc55e2aedb4321d54d.

Current main is not red. #135653 moved the existing reindex lease to the concrete sync-generation owner in 9e45fd9db719, so ordinary memory-file and session index writes cannot advance the published revision while a shadow rebuild owns that lease.

Exact-main proof used real SQLite state and the public search() path:

node scripts/run-vitest.mjs extensions/memory-core/src/memory/manager-search-concurrency.proof.test.ts

concurrentWrite: blocked by shared reindex lease
firstSearchReindex: published without revision conflict
laterSearch: published queued file once
maintenanceAttempts: 2
livelock: false
Test Files 1 passed (1)
Tests 1 passed (1)

The anti-cheat check also passed: the existing privacy-purge race test still makes a stale full reindex fail when memory forget intentionally changes the live revision. That proves the harness reaches the revision fence. The ordinary concurrent writer instead hits the shared reindex lease and cannot create the reported retry loop.

The proposed cooldown is also local to one manager, while command-line and Gateway memory searches use fresh transient managers. Its added tests do not cover that cross-manager surface or reproduce a real concurrent-write revision conflict.

Closing this PR as superseded by the current-main coordination fix. #135754 stays open for its separate source-selection and deleted-archive concerns.

@obviyus obviyus closed this Sep 2, 2026
@LiuwqGit
LiuwqGit deleted the feat/issue-135754-reindex-backoff branch September 22, 2026 14:47
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: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

2 participants