Skip to content

improve(memory): keep large-note searches responsive - #146168

Merged
steipete merged 12 commits into
mainfrom
codex/worker-memory-a0c2
Sep 12, 2026
Merged

steipete merged 12 commits into
mainfrom
codex/worker-memory-a0c2

Conversation

@steipete

@steipete steipete commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Uses the merged admission owner from #146067. Related: #146166, #127866.

What Problem This Solves

Resolves a problem where searching or indexing large memory collections can stall the Gateway event loop. Lexical fallback scans, cosine fallback, and preparation of large Markdown notes currently compete with request handling on the same thread.

Why This Change Was Made

Memory Core submits retrieval and immutable chunk preparation to separate bounded workers using the shared compute admission contract. The current database owners retain publication, generation leases, source-hash checks, and tombstones. Search results are checked against existing chunks after worker completion so a concurrent forget cannot return a deleted hit.

The worker SDK facades load the existing pure chunking and read-only database primitives directly. This removes unrelated provider/configuration initialization from their import graphs without duplicating algorithms or changing schema, configuration, or dependencies.

User Impact

Large memory searches leave the main event loop available to other work. Background chunk preparation has a separate worker from foreground retrieval. Index publication still uses the existing synchronous database writer, so this does not remove every indexing pause.

Evidence

  • Earlier source proof passes 198 tests across ten Memory Core files, covering real worker retrieval, cancellation/generation behavior, keyword and hybrid ranking, provenance, reset boundaries, stale source publication, and tombstones.
  • Earlier focused proof passed 63 tests across five files, covering admission, cancellation, provider fallback/leases, worker URL layouts, tombstones and SQLite writer locks. Final follow-up passes 58 tests across orchestration, real search workers and optional-provider flows. Saturation now covers first-search bootstrap, missing-index-identity repair, lexical, hybrid and actual vector retrieval, with positive recovery after drain. The bootstrap and identity cases fail the original handlers by resolving an empty result; removing the vector overload guard fails by returning partial lexical results. The earlier vector case used a retired configuration field and duplicated hybrid coverage; it is replaced by a nonzero embedding and admission saturation at the existing embedding hook. Both keyword cancellation regressions also fail the original code. Typed overload remains an unsuccessful search, and keyword admission cannot retire a healthy fallback embedding provider.
  • The new real-worker/forget regression fails before the authoritative chunk-existence filter and passes afterward. Real worker reads preserve a parent SQLite writer lock against an independent writer on both Windows and Linux.
  • Native Linux validation passes 154 database tests plus all three real-worker regressions, including forget/admission recovery and POSIX writer-lock preservation. Six filesystem-specific alias cases are skipped by the existing platform conditions.
  • Existing host chunk-budget and embedding-limit tests pass. An AST comparison confirms that all thirteen relocated chunking, vector, query, and read-only database function bodies are unchanged.
  • SDK export synchronization and the plugin-SDK subpath export check pass. Fresh independent review of the final cancellation, overload, package-layout and isolation repairs is scoped-clean through P2.
  • Compiled worker import graphs shrink from 606 modules/6.68 MB to 110 modules/647 KB for retrieval and from 604 modules/6.66 MB to 76 modules/506 KB for preparation. Byte totals count local static imports, not external dependencies.
  • The final pnpm build qaRuntime passes with physical Linux dependencies, including all 92 plugin builds, bootstrap checks and 52 native control-plane load checks. Final exact-head CI 34711809099 and the required openclaw/ci-gate passed before native landing.
  • Core, extension and script TypeScript lanes pass. Kysely, assertion-safety, full dead-code scans, formatting, diff checks and targeted core/extension lint pass. The original Knip configuration recognizes both workers through their package manifest entries; no extra inventory override remains. One local declaration-preparation attempt stopped after dependency hardlink metadata changed; a normal retry in a quiet dependency window passed without bypassing the guard.
  • Standalone proof builds both workers into a renamed package directory. Its actual index worker returns valid chunks and a content hash, and its public manager retrieves a positive lexical hit from a database indexed by the bundled manager. Complete standalone manager sync is not claimed: its existing trusted keyed-state binding is outside this fixture, and was not bypassed. Root-bundled full indexing/search is exercised by the public-entrypoint benchmark below.
  • The read-only schema functions were relocated without changing the schema, version, migrations or persisted rows. Their original function bodies were verified by AST comparison; the CI follow-up only removes an unnecessary type assertion and uses the existing cache-state leaf to preserve KNN dependency isolation.
  • The broader Windows database suite reported two platform-specific symlink/mode failures and one failed-open fixture failure. The exact failed-open test reproduces on the unchanged original database source. All three cases pass on Linux; no database policy was changed to accommodate the Windows failures.

The shipped-build comparison uses Node 26.8.2, four-CPU affinity, the built public memory-host-search facade, two prewritten 40,000-line workspaces, and 12,000 additional synthetic chunks (15,073 total). One paired baseline/candidate process run measured cold operations and six warmed searches; no source loader or worker substitution was used. Empty-query and positive-hit assertions passed in both processes.

Operation Baseline wall time Candidate wall time Baseline maximum event-loop delay Candidate maximum event-loop delay
Cold indexing 2,087 ms 1,172 ms 1,034 ms 468 ms
Warm indexing, distinct workspace 1,579 ms 1,141 ms 897 ms 610 ms
Cold lexical search 250 ms 474 ms 252 ms 5.0 ms
Warm lexical searches 154–234 ms 78–116 ms 155–234 ms 3.0–3.8 ms

The cold search pays about 224 ms of worker startup, and final process RSS increases from 464 to 566 MiB. Indexing retains a synchronous writer pause. These are measured tradeoffs, not a guarantee for every workload or host. Manager-open timing varied with host/cache state and is not claimed as an algorithmic improvement.

A later final-build confirmation uses the same public entrypoint, fixtures and four-CPU affinity while other host validation runs. All positive-hit and chunk assertions pass. Warm searches take 108–164 ms with maximum event-loop delays of 3.4–7.4 ms; cold search takes 570 ms with a 12.2 ms maximum delay, and final RSS is 565 MiB. Cold/warm indexing pauses are 781/738 ms. This additional run confirms responsiveness while showing host variability; it is not a second paired throughput comparison.

Final integration with current main preserves its canonical metadata reader and keeps that schema-admission read free of the query-builder runtime. The newer ownership-header snapshot behavior is retained. Combined KNN, PDF, memory search and memory indexing registrations pass 51 targeted tests: source/compiled worker generation, build configuration, database ownership and read-only admission, full preflight artifacts, native header lifecycle, and real KNN WAL visibility/dependency isolation. Another 202 cases were deliberately outside these focused filters. Independent review of the final six-file integration found no actionable P0-P2 issues. No schema, version, transaction or persistence-policy change is introduced.

Final overload repair preserves typed capacity errors in all three mandatory synchronization catches: first-search bootstrap, its embedding fallback, and required index-identity repair. The background refresh retains its existing behavior of serving published results. The unsupported test-only hybrid configuration is removed rather than restoring retired product configuration. Fresh independent P2 review of the two-file repair has no findings. Production extension types, extension-test types, formatting and diff checks pass. Final targeted lint passes with zero warnings/errors in a separate physical checkout after normal SDK declaration preparation emitted 9,269 files. The original nested checkout preparation refused an ancestor dependency path; its failure is retained and no guard was bypassed. The previous hosted test-type failure was caused by that retired test configuration; final exact-head hosted CI 34711809099 and its required gate passed.

@clawsweeper

clawsweeper Bot commented Sep 12, 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 scripts Repository scripts agents Agent runtime and tooling extensions: xai size: XL maintainer Maintainer-authored PR labels Sep 12, 2026
@steipete
steipete marked this pull request as ready for review September 12, 2026 16:17
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 12, 2026
@clawsweeper

clawsweeper Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 12, 2026, 2:49 PM ET / 18:49 UTC (Revision 6).

ClawSweeper review

What this changes

Moves Memory Core’s lexical searches, vector fallback scans, and Markdown preparation into bounded workers while preserving existing indexing and database ownership.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/state/openclaw-agent-db-schema-helpers.ts, src/state/openclaw-agent-db-schema-read.ts. Prefer a design that avoids changing persisted SQLite tables. If the change is necessary, verify migration and upgrade compatibility against an existing database before merge.

Merge readiness

⛔ Blocked before merge - 1 item remains

This remains useful work: current main still performs the affected memory work inline. The previous overload blocker is resolved, the supplied runtime evidence supports the responsiveness improvement, and no blocking introduced defect remains.

Priority: P2
Reviewed head: 77661607fdb12b7ef213adfe1cb7c57802a31d69

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent worker cutover with strong runtime measurements and the previous overload blocker resolved.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied built-public-entrypoint benchmark exercises actual indexing and worker-backed searches on large fixtures, verifies positive hits, and records substantially lower event-loop delay; final-build observations corroborate responsiveness, with startup, RSS, and remaining writer pauses disclosed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied built-public-entrypoint benchmark exercises actual indexing and worker-backed searches on large fixtures, verifies positive hits, and records substantially lower event-loop delay; final-build observations corroborate responsiveness, with startup, RSS, and remaining writer pauses disclosed.
Evidence reviewed 8 items Previous blocker resolved: The exact head commit adds overload propagation to bootstrap, bootstrap fallback, and required index-identity repair. Its regression table adds empty-index and missing-identity scenarios, rejects typed overload, and verifies positive search results after capacity drains.
Current main still needs this work: Fetched main directly invokes keyword queries with the manager’s database and performs Markdown chunk preparation inline. The merged admission prerequisite, #146067, supplies shared capacity but does not implement this memory cutover.
Latest release comparison: The supplied latest-release commit for v2026.9.4 also executes keyword retrieval directly against the manager connection; this worker implementation is not already shipped there.
Findings None None.
Security None None.

How this fits together

Memory Core turns workspace notes and session content into searchable chunks. Its search manager combines lexical and vector matches for agent recall, while database owners control publication and deletion.

flowchart TD
  A[Notes and session content] --> B[Shared compute admission]
  C[Memory search request] --> B
  B --> D[Chunk preparation worker]
  B --> E[Retrieval worker]
  D --> F[Existing publication owner]
  F --> G[Agent memory database]
  G --> E
  E --> H[Current chunk checks and ranked results]
Loading

Before merge

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

Security

None.

PR surface

Source +337, Tests +205, Docs +15, Config +13, Other +8. Total +578 across 48 files.

View PR surface stats
Area Files Added Removed Net
Source 28 991 654 +337
Tests 9 244 39 +205
Docs 2 16 1 +15
Config 3 14 1 +13
Generated 0 0 0 0
Other 6 9 1 +8
Total 48 1274 696 +578

Review metrics

Metric Value Why it matters
Measured responsiveness tradeoff Warm loop delay 155–234 ms → 3.0–3.8 ms; final RSS 464 → 566 MiB The supplied paired benchmark quantifies the responsiveness gain and its memory cost.
Production and regression coverage Production net +334 lines; tests net +205; tooling net +9 Production growth provides bounded worker dispatch and isolated imports, with regression coverage for cancellation, overload recovery, forgetting, and writer locks.

Stored data model

Persistent data-model change detected: database schema: src/state/openclaw-agent-db-metadata.ts, database schema: src/state/openclaw-agent-db-schema-helpers.ts, database schema: src/state/openclaw-agent-db-schema-read.ts, migration/backfill/repair: src/state/openclaw-agent-db-schema-helpers.ts, migration/backfill/repair: src/state/openclaw-agent-db-schema-read.ts, serialized state: packages/memory-host-sdk/src/host/embedding-vector.ts, and 25 more. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep CPU admission centralized while preserving existing generation leases, provider health, publication checks, and explicit overload failures.

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

Yes: current main’s inline retrieval and chunk preparation match the supplied large-note benchmark showing substantial event-loop delays. This review inspected source and recorded evidence without executing the workload.

Is this the best way to solve the issue?

Yes: reusing shared worker admission and existing algorithms avoids a competing scheduler or storage owner, and the final repair preserves overload failures through mandatory indexing.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied built-public-entrypoint benchmark exercises actual indexing and worker-backed searches on large fixtures, verifies positive hits, and records substantially lower event-loop delay; final-build observations corroborate responsiveness, with startup, RSS, and remaining writer pauses disclosed.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, 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:

  • P2: This addresses measured memory-workload responsiveness problems with a bounded scope and no demonstrated emergency.
  • 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 (live_output): The supplied built-public-entrypoint benchmark exercises actual indexing and worker-backed searches on large fixtures, verifies positive hits, and records substantially lower event-loop delay; final-build observations corroborate responsiveness, with startup, RSS, and remaining writer pauses disclosed.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied built-public-entrypoint benchmark exercises actual indexing and worker-backed searches on large fixtures, verifies positive hits, and records substantially lower event-loop delay; final-build observations corroborate responsiveness, with startup, RSS, and remaining writer pauses disclosed.

Evidence

What I checked:

  • Previous blocker resolved: The exact head commit adds overload propagation to bootstrap, bootstrap fallback, and required index-identity repair. Its regression table adds empty-index and missing-identity scenarios, rejects typed overload, and verifies positive search results after capacity drains. (extensions/memory-core/src/memory/manager-search-orchestration.ts:106, 77661607fdb1)
  • Current main still needs this work: Fetched main directly invokes keyword queries with the manager’s database and performs Markdown chunk preparation inline. The merged admission prerequisite, fix: bound concurrent compute work and pending worker inputs #146067, supplies shared capacity but does not implement this memory cutover. (extensions/memory-core/src/memory/manager-keyword-retrieval.ts:262, 7d6eeb9cdae7)
  • Latest release comparison: The supplied latest-release commit for v2026.9.4 also executes keyword retrieval directly against the manager connection; this worker implementation is not already shipped there. (extensions/memory-core/src/memory/manager-keyword-retrieval.ts:262, 3a9d69db306c)
  • Production behavior evidence: The complete supplied PR body, captured under sourceRevision d8cfca926c20750bb2202d06ddc4d612a58fffb48c7d2a56a45a80d4dd93e8f4, describes built public memory-host-search runs on Node 26.8.2 with four-CPU affinity and 15,073 chunks. Positive-hit assertions passed. Paired warm-search maximum event-loop delay fell from 155–234 ms to 3.0–3.8 ms; a final-build confirmation reported 3.4–7.4 ms. It explicitly records worker startup cost, increased RSS, remaining indexing pauses, and limited standalone-sync coverage.
  • Reader lifetime and forgotten hits: Retrieval uses the canonical read-only opener and closes its reader before replying. Keyword expansion settles all admitted probes before releasing its generation. Metadata enrichment removes missing chunks, and the real-worker regression delays a returned hit until after forgetting it, then expects only the surviving note. (extensions/memory-core/src/memory/manager-search-worker.test.ts:16, 77661607fdb1)
  • Storage and SDK compatibility: The introduced diff relocates existing chunking and read-only ownership/version checks, preserves their existing exports, and leaves chunking version and persisted schema unchanged. Worker facades are documented as private bundled contracts; package exports and worker registrations accompany the new entrypoints. (src/state/openclaw-agent-db-readonly-open.ts:35, 77661607fdb1)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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 (5 earlier review cycles)
  • reviewed 2026-09-12T16:16:12.411Z sha 7ba2edb :: blocked before merge. :: [P2] [P2] Preserve overload errors at the memory search boundary
  • reviewed 2026-09-12T16:27:23.167Z sha 7ba2edb :: blocked before merge. :: [P2] [P2] Preserve overload errors at the memory search boundary
  • reviewed 2026-09-12T17:40:32.928Z sha be86fbc :: blocked before merge. :: [P2] Propagate chunk-preparation overload through first-search bootstrap
  • reviewed 2026-09-12T18:14:49.836Z sha 5c4c593 :: blocked before merge. :: [P2] Propagate chunk-preparation overload through first-search bootstrap
  • reviewed 2026-09-12T18:20:57.532Z sha 5c4c593 :: blocked before merge. :: [P2] Propagate chunk-preparation overload through first-search bootstrap

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Sep 12, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 12, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the agents Agent runtime and tooling label Sep 12, 2026
@steipete
steipete marked this pull request as draft September 12, 2026 17:59
@steipete
steipete marked this pull request as ready for review September 12, 2026 18:07
@steipete
steipete marked this pull request as draft September 12, 2026 18:12
@steipete
steipete marked this pull request as ready for review September 12, 2026 18:38
@clawsweeper clawsweeper Bot added 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 12, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The remaining data-model checkbox is a path-based false positive on 77661607fdb12b7ef213adfe1cb7c57802a31d69. I checked the final delta against its current main base: this PR does not change DDL, schema versions, migrations, stored columns, transaction boundaries, retention, or database ownership policy.

The existing version/owner assertions move unchanged from openclaw-agent-db-schema-helpers.ts into the lightweight schema reader. The canonical metadata reader reads the same three columns with the same primary-row predicate and decoding; its native SELECT keeps schema admission independent of the query-builder runtime. Current main's ownership-header snapshot behavior is retained.

Compatibility proof includes the 154 passing database cases (six existing platform skips), real worker reads preserving parent SQLite writer locks, and 51 final integration cases covering source/compiled worker registration, read-only admission, ownership/header lifecycle and KNN WAL visibility/dependency isolation. The final 58-case memory suite and both extension type lanes pass; lint passes on the exact published tree. No new schema or migration is being accepted through this PR.

The fresh review's actual overload finding is fixed and reproduced: first-search bootstrap and required identity repair now reject saturation instead of reporting no matches, and recover after capacity drains. Its latest exact-head review reports no actionable code or security findings. Required hosted CI remains the landing gate.

@steipete
steipete merged commit e14b3dd into main Sep 12, 2026
269 checks passed
@steipete
steipete deleted the codex/worker-memory-a0c2 branch September 12, 2026 18:59
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 13, 2026
* fix: bound concurrent compute work and pending worker inputs

* fix: supply the host response budget in worker checkpoint tests

* fix: preserve prepared catalog ownership under admission pressure

* improve(memory): keep large-note searches responsive

* fix(memory): preserve worker errors and package boundaries

* docs: separate worker entrypoint guidance

* chore: align metadata extraction with main

* chore: align worker registration for main refresh

* fix(memory): unify metadata reads and worker registration

* fix(memory): preserve overload during index bootstrap and repair
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 extensions: xai maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. 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: 👀 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.

1 participant