Repository navigation
fix(memory): avoid repeated database checks on cold searches - #138166
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. |
|
Codex review: blocked before merge. Reviewed September 4, 2026, 8:49 AM ET / 12:49 UTC. ClawSweeper reviewWhat this changesThe PR makes Memory Core and Gateway startup borrow the canonical per-agent SQLite handle so cold work avoids redundant database opens and integrity checks. Warning SQLite table change This PR modifies persisted SQLite tables in Regression provenancePossible regression — probable (reproduction; reviewed change). No predecessor PR is attributed. Merge readiness⛔ Blocked before merge - 1 item remains Keep this maintainer-owned PR open: its duplicate-open repair is not on current main or the latest release, and no introduced correctness defect was found in the final head. Priority: P2 Review scores
Verification
How this fits togetherGateway startup and Memory Core both use each agent’s SQLite database. The change routes both through the process-owned owner, retaining a borrow across work while preserving explicit disposal and quarantine. flowchart LR
A[Gateway startup] --> B[Agent database owner]
C[Memory search] --> D[Borrow shared handle]
B --> D
D --> E[Validated SQLite connection]
E --> F[Session reconciliation]
E --> G[Memory search results]
Before merge
Agent review detailsSecurityNone. PR surfaceSource -18, Tests +532, Docs +6. Total +520 across 34 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Land only the canonical shared-handle lifecycle, retaining the borrower pin, explicit owner disposal, and the documented private-local SDK boundary. Do we have a high-confidence way to reproduce the issue? Yes: the old close-then-reopen boundary is source-traceable, and the supplied exact-head real Gateway comparison directly records the changed physical-open and integrity-scan counts. Is this the best way to solve the issue? Yes: moving retention to the process-owned database lifecycle removes the duplicate open without creating a competing Memory Core connection owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 6b25e1840775. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (4 earlier review cycles)
|
6af3bb6 to
c9f569c
Compare
|
ClawSweeper follow-through: the 65-manager experiment counts both physical connection owners, rather than only entries in the canonical cache. With one canonical access and one retained default manager per agent, the base held 129 live SQLite connections (64 canonical plus 65 independent memory connections); the candidate holds 65 shared connections. The identical new regression fails on the base and passes on the candidate. These are measured SQLite connection counts, not inferred OS file-descriptor counts. The requested multi-manager coverage is added. The requested hard 64-manager retirement/admission policy is not applied: the default-manager registry was already unbounded, and forcibly evicting a retained connection would invalidate its prepared statements and vector state. The fixed-budget comment is corrected to describe the actual cache target. This rejects the finding's introduced-resource-regression premise while making the limitation explicit: live borrowers, transactions, and incognito state may exceed the target. Manager shutdown releases ownership tokens and leaves 65 reusable handles in this test; the next new connection trims the idle cache back to 64. A new active-manager limit would be a separate product/lifecycle change. The data-model flag is addressed by the accepted database review checkpoint and unchanged canonical SQL/schema versions, stored shapes, and migration code. The refreshed Crabbox proof will additionally exercise candidate-created state with the baseline reader/writer, then reopen it with the candidate to verify code-only rollback and return; that result is still pending. CI follow-through: the first full run passed 136 checks. The memory shard's three schema-0 fixture failures were reproduced locally and corrected by seeding canonical databases and removing independent connection swaps; the behavior assertions remain. The corrected fixtures, shared-manager lifecycle, and publication tests passed (24 cases), followed by the final lifecycle suite (14 cases, including the 65-manager regression). The other failure was the npm advisory endpoint exhausting all four timeout attempts, with credential scans passing. Fresh exact-head CI is required before landing. The main refresh preserves #138145's shadow-context ownership, recording the vector-table fact before the writer closes and consuming it during publication. All 42 focused acquisition/publication/recovery/fixture tests passed after that integration. The PR body will be updated with final exact-head CI and refreshed Crabbox evidence before landing. |
b8245ef to
c6b64a5
Compare
|
The QA documentation-reference failure is resolved upstream by #138044. This branch has been refreshed onto that repair; The refreshed real-flow comparison completed successfully for all nine searches per revision, native sqlite-vec loading, and candidate-create → baseline-readwrite → candidate-reopen compatibility at unchanged schema version 19. However, this paired timing reversed the earlier result: baseline cold HTTP 764.6 ms / max loop delay 741.9 ms; candidate 3610.4 ms / 3818.9 ms. That slower result is preserved and is not being treated as a performance win. Before landing, a fresh Crabbox run will build both revisions first, alternate three fresh Gateway runs per revision, and trace physical SQLite opens, integrity queries, CPU, and page faults around each request. This will distinguish the repaired ownership path from other cold-start work or contention. Final performance evidence and exact-head CI remain pending. |
c6b64a5 to
111ac2e
Compare
|
@clawsweeper re-review The updated head The 65-manager resource proof and hard-cap rationale from the earlier review remain in the body. Production is net −23 lines. The final 23-case cleanup/incognito/module/manager suite and both full changed-file gates pass; independent review of the new owner correction is clean through P2. Four test-only lines also restore production error classification in the unrelated compact-runtime fixture, preserving every denial assertion. Final exact-head CI, full branch review, and fresh Crabbox before/after proof are running. The body now distinguishes prior measured evidence from this pending final-head run, including the mixed/negative timing results; no general latency improvement is claimed. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
Borrow verified per-agent connections across manager work and release them without closing the shared owner. Pin exact handles against cache eviction, retain explicit disposal, and keep shadow publication synchronous. Hand startup maintenance directly to Gateway reconciliation while preserving temporary maintenance cleanup. Use the same connection for vector deletion and guard native extension loading against post-import revocation. Fixes #137750 Fixes #121985 Supersedes #122005 Co-authored-by: Grynn <[email protected]>
Seed canonical agent databases for cleanup and missing-identity scenarios, removing independent fixture connections and handcrafted schema copies. Cover 65 retained managers across canonical and memory access, including shared-handle retention on release and LRU convergence on the next open. Clarify the cache target without changing active manager lifetimes.
Preserve the newly landed shadow-context lifecycle after the main refresh. Carry the vector-table fact out before closure and use the shared idempotent release callback for cleanup.
Keep connection lifecycle, registry invalidation, query caches and commit observers under one process owner. Use native transaction state and savepoints instead of duplicate depth tracking, and recover closed cached handles after lease-release failures.
|
Completed the requested native proof on Both revisions were built before three alternating cold trials over 623 one-chunk notes and 310 canonical 1 MiB sessions. All 54 real Gateway HTTP searches passed. Baseline The built SDK loaded packaged sqlite-vec v0.1.9 on the exact shared handle, preserved it on borrow release, disabled native loading afterward, and blocked SQL loading. Candidate-created state was read and updated by baseline, then reopened by candidate, with unchanged agent schema version 19. All 19 candidate loader/cache/catalog tests passed; the baseline catalog fixture reproduced its three expected failures. This addresses the latest ClawSweeper requests for physical-open tracing, packaged native loading, and older-reader compatibility. The SQLite SDK subpath documentation is corrected. Landing remains pending: hosted CI exposed a Gateway test-fixture cleanup leak, and main independently landed the catalog fixture fix. I am resolving that overlap and proving the fixture cleanup in the original test order before the final push. |
f6038e6 to
9306260
Compare
|
Final head All 54 real Gateway searches passed over the specified 623-note/310-session corpus. Three alternating cold trials measured baseline 2 physical opens / 2 executed integrity scans each, candidate 0 / 0 each. Median cold HTTP time was 782.4 → 591.8 ms; median maximum loop delay was 755.5 → 665.3 ms. Timing limitations and the earlier negative sample remain in the PR body. All 19 native loader/cache/catalog tests passed. Packaged sqlite-vec loaded on the exact shared handle, release preserved its owner, native loading was disabled afterward, and SQL loading stayed blocked. Candidate-created schema-19 state passed baseline read/write and candidate reopen. The original CI failure order now passes all 55 tests, and all seven Gateway/fixture suites pass 81 tests. Full changed-file gates, P0–P2 branch review, and exact-head native review-artifact validation passed. This completes the ClawSweeper physical-open, native dependency, compatibility, documentation, and description follow-through. CI run 33872423001 remains the final landing gate; no new runtime changes followed the proven owner repair. |
sylvesterkaczmarek
left a comment
There was a problem hiding this comment.
The borrow/release ownership model is cleaner than reopening the same agent DB in memory consumers. The key invariant is preserved: borrowers prevent idle eviction but cannot close the shared handle; quarantine and explicit disposal remain authoritative.
|
Exact-head CI run 33872423001 completed successfully for Native review artifacts are validated and recommend Proceeding through native prepare/merge. The earlier schema-0 and incognito fixture failures were reproduced and repaired at their fixture owners; the catalog fixture correction is now inherited from main #138238. No runtime changes followed the final proof. Contributor credit from #122005 is retained. |
|
Merged via squash.
|
…w#138166) Memory managers reopened and synchronously rechecked per-agent databases that Gateway startup had already verified. Borrow the exact canonical connection and retain its complete owner lifecycle across native and transformed SDK modules, including query caches, registry invalidation, and commit observers. Manager cleanup releases only its borrow; explicit owner disposal remains authoritative. Preserve read-only diagnostics, isolated shadow rebuilds, synchronous publication, native vector-loading boundaries, and temporary startup-maintenance cleanup. Remove duplicate initialization and transaction bookkeeping. Production delta: -23 lines. Regression proof covers physical-open/integrity counts, corruption before exposure, settings replacement, maintenance isolation, shutdown, cross-module rollback and discovery, and failed lease-release recovery. Real Crabbox CLI/Gateway searches, packaged sqlite-vec loading, and candidate/baseline/candidate database compatibility pass. Repair fixture-owned database cleanup exposed by the process-shared lifecycle without changing production incognito lifetime. Closes openclaw#137750 Closes openclaw#121985 Supersedes openclaw#122005 Thanks to Hampert for reporting the cold-search stall and @Grynn for identifying the startup duplicate checks. Co-authored-by: Grynn <[email protected]>
Closes #137750
Closes #121985
Supersedes #122005
What Problem This Solves
The first memory search could stall the Gateway while reopening and rechecking an agent database that startup had already verified. Memory managers now borrow that canonical connection at the exact configured path. This repairs the duplicate-open residual; session decoding was fixed separately in #138051.
Why This Change Was Made
The canonical per-agent owner validates the physical open before exposing a handle. Borrowers retain it against idle-cache eviction and release only their own token; manager cleanup cannot close the shared connection. Explicit disposal and quarantine remain authoritative. Gateway startup hands its maintenance handle directly to transcript reconciliation, preserving temporary TUI maintenance cleanup.
Native and transformed SDK modules share the complete owner lifecycle, registry invalidation, query-cache markers, and commit observers. SQLite savepoints replace duplicate module-local transaction depth/counter bookkeeping, preserving nested rollback across module graphs. Long rebuilds keep their isolated shadow writer; vector loading finishes before synchronous attach/publication/detach. Native loading is disabled afterward, and SQL loading remains blocked. Read-only status/forget previews remain noncreating; vector deletion borrows the canonical handle.
Database review checkpoint: Peter approved this lifecycle change on 2026-09-04, decision 11 (accepted rationale). No schema, version, stored representation, migration, configuration, environment, or protocol changes. Physical-open integrity/index, owner, lease, and registration checks still precede exposure. Rollback is code-only; candidate-create → baseline-read/write → candidate-reopen is proven below. Late borrow releases cannot close replacements.
This absorbs @Grynn's #122005 intent while preserving its temporary maintenance lifetime. The commit retains
Co-authored-by: Grynn <[email protected]>. Thanks to Hampert for the original report and @Grynn for identifying duplicate startup checks.User Impact
Cold search reuses the verified connection. Hot-created agents still validate their first open; corrupt stores fail before manager exposure. Settings replacement and manager shutdown preserve the shared owner's handle. The second writable open, duplicate initialization, hidden read-only map, independent deletion connection, and duplicate transaction bookkeeping are removed.
Evidence
Pre-fix regressions failed for duplicate physical opens/integrity scans, deletion bypassing the canonical connection's TEMP trigger, deferred native loading after revocation, split transformed-SDK query caches, stale hot-agent discovery, and a closed cache entry after real lease-release failure. Coverage includes exact-path identity, settings replacement, maintenance, isolated rebuild publication/failure, nested rollback, observer ordering, explicit disposal, and shutdown.
Local proof passed 165 owner/transaction tests and 199 broader lifecycle/memory tests (each with 4 existing skips), plus the final 23 cleanup/incognito/module-identity/manager cases. Earlier focused startup, deletion, publication and recovery suites also passed. Full changed-file checks and independent P0–P2 branch review passed; exact-head CI remains enforced by the native landing workflow.
CI exposed a fixture lifetime leak: a failed placement-retirement test intentionally retained an incognito session, then deleted its temporary HOME without closing the handle. The original worker-placement → list-store → placement-projection order reproduced 3 failures/52 passes. Root-scoped fixture cleanup now passes all 55 in that order and 81 across seven Gateway suites. The existing cleanup-error regression also failed pre-fix with both durable/incognito handles open and now verifies both close. Live suite-server handles remain retained. Main #138238 independently absorbed the catalog result-classification fixture fix, so its duplicate commit was dropped during rebase; all 17 changed production modules remained byte-identical.
git diff --numstat, classified (fixture helpers count as test support):Crabbox proof built exact baseline
79930b846762b28f941b55f6568b1d66fa1e5961and head9306260da67345e2849317a4584b348b6cebfe99before three alternating cold trials. Each revision used 623 one-chunk notes and 310 canonical sessions with 1 MiB prompts. Built-in FTS (provider: none, corpusmemory) isolates database acquisition from embedding-provider latency. All 54 real Gateway HTTP searches passed, including unique-hit and explicit-empty outcomes.Sanitized transcript (Crabbox/Testbox workflow):
Risks and Review Follow-through
The repeatable result is removal of redundant database work, not a universal latency guarantee. Earlier timing pairs were mixed: one regressed 764.6 → 3610.4 ms HTTP and 741.9 → 3818.9 ms maximum loop delay; that result remains public in the PR comments. The original provider-specific 62-second report was not reproduced. Remaining cold latency includes plugin/module setup and search work.
ClawSweeper's packaged native-loading, physical-open trace, compatibility, and SDK lifecycle-documentation requests are addressed. The 65-manager regression measures 129 old connections versus 65 shared connections; these are connection counts, not file descriptors. The requested hard 64-active-manager cap is intentionally skipped: the manager registry was already unbounded, and forced eviction would invalidate retained statements/vector state. The documented 64 limit is an idle-cache target; live borrowers, transactions and incognito state remain retained. A new admission policy is separate product scope.
NO-FOLLOW-UP PR: the useful connection-owner refactor is included here. Named preexisting follow-ups are “Drain memory-manager registry during Gateway close/restart” and “Fence QA repository-path resolution to the owning checkout.” The latter's unrelated stale-document CI failure was repaired upstream in #138044; its outer-checkout resolution issue remains recorded. Earlier CI also exposed schema-0 fixtures (repaired at their producer) and an npm advisory endpoint timeout after four attempts, with no vulnerability finding.