Skip to content

fix(memory): avoid repeated database checks on cold searches - #138166

Merged
steipete merged 8 commits into
mainfrom
fix/memory-borrow-agent-connection
Sep 4, 2026
Merged

steipete merged 8 commits into
mainfrom
fix/memory-borrow-agent-connection

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

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):

Class Added Removed Net
Production 317 340 -23
Tests/test support 669 132 +537
Docs 15 9 +6

Crabbox proof built exact baseline 79930b846762b28f941b55f6568b1d66fa1e5961 and head 9306260da67345e2849317a4584b348b6cebfe99 before three alternating cold trials. Each revision used 623 one-chunk notes and 310 canonical sessions with 1 MiB prompts. Built-in FTS (provider: none, corpus memory) isolates database acquisition from embedding-provider latency. All 54 real Gateway HTTP searches passed, including unique-hit and explicit-empty outcomes.

Median of three cold requests Baseline Candidate
HTTP memory_search 782.4 ms 591.8 ms
Maximum Gateway event-loop delay 755.5 ms 665.3 ms
Manager acquisition 502 ms 403 ms

Sanitized transcript (Crabbox/Testbox workflow):

baseline: 79930b846762b28f941b55f6568b1d66fa1e5961
candidate: 9306260da67345e2849317a4584b348b6cebfe99
node scripts/run-node.mjs memory index --force --agent main
Memory index updated (main): 623 files indexed.
canonical sessions: 310; prompt bytes/session: 1048576
node scripts/run-node.mjs memory search 'vermilion lighthouse recovery' --agent main --max-results 6 --json
CLI unique hit: MEMORY.md
Gateway: random free loopback port; temporary synthetic HOME/state
POST /tools/invoke memory_search: 27/27 passed per revision
baseline cold physical opens / executed integrity scans: 2/2 in every trial
candidate cold physical opens / executed integrity scans: 0/0 in every trial
candidate transformed-loader/cache/catalog tests: 19 passed
sqlite-vec v0.1.9 on exact shared handle: pass
release preserves owner; native loading disabled; SQL loading blocked: pass
candidate-create / baseline-readwrite / candidate-reopen: all pass
unchanged agent schema version: 19
wrapper exitCode: 0; runStatus: succeeded

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.

@steipete steipete self-assigned this Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: memory-core Extension: memory-core size: L maintainer Maintainer-authored PR labels Sep 4, 2026
@steipete
steipete marked this pull request as ready for review September 4, 2026 10:05
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. 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 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 8:49 AM ET / 12:49 UTC.

ClawSweeper review

What this changes

The 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 src/infra/sqlite-transaction.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.

Regression provenance

Possible 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
Reviewed head: 9306260da67345e2849317a4584b348b6cebfe99

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A well-scoped owner-boundary repair with strong exact-head real-flow evidence and targeted lifecycle regressions.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied exact-head Testbox run exercises the changed production owner through real Gateway HTTP memory searches and observes the after-fix result: no duplicate cold physical opens or integrity scans, with successful vector lifecycle and compatibility reopen checks.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied exact-head Testbox run exercises the changed production owner through real Gateway HTTP memory searches and observes the after-fix result: no duplicate cold physical opens or integrity scans, with successful vector lifecycle and compatibility reopen checks.
Evidence reviewed 7 items Canonical owner and borrow boundary: The owner validates and caches physical opens; borrowing pins the exact handle, while explicit close remains able to revoke it.
Memory Core consumes the canonical handle: Non-status managers acquire the shared handle through the Plugin SDK and retain the returned release callback.
Startup handoff preserves cold owner lifetime: Startup maintenance hands the database to transcript reconciliation before its cold-handle cleanup branch runs.
Findings None None.
Security None None.

How this fits together

Gateway 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]
Loading

Before merge

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

Security

None.

PR surface

Source -18, Tests +532, Docs +6. Total +520 across 34 files.

View PR surface stats
Area Files Added Removed Net
Source 18 322 340 -18
Tests 14 664 132 +532
Docs 2 15 9 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 34 1001 481 +520

Review metrics

Metric Value Why it matters
Production versus test delta production −23; tests/test support +537; docs +6 The lifecycle repair is net-negative in production while adding targeted borrowing, eviction, startup-handoff, and module-identity coverage.

Stored data model

Persistent data-model change detected: migration/backfill/repair: extensions/memory-core/src/memory/manager-db.ts, migration/backfill/repair: src/config/sessions/startup-migration.ts, migration/backfill/repair: src/gateway/server-startup-session-migration.ts, unknown-data-model-change: extensions/memory-core/src/memory-forget.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager-db.ts, unknown-data-model-change: extensions/memory-core/src/memory/manager.ts, and 9 more. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #121985
Summary: This PR is the candidate repair for the canonical duplicate agent-database open issue; it also addresses one contributor to the broader cold memory-search report.

Members:

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

Technical review

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

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient. The supplied exact-head Testbox run exercises the changed production owner through real Gateway HTTP memory searches and observes the after-fix result: no duplicate cold physical opens or integrity scans, with successful vector lifecycle and compatibility reopen checks.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove merge-risk: 🚨 availability: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This repairs a bounded cold-path Gateway and Memory Core latency defect without evidence of data loss, security bypass, or an unusable runtime.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied exact-head Testbox run exercises the changed production owner through real Gateway HTTP memory searches and observes the after-fix result: no duplicate cold physical opens or integrity scans, with successful vector lifecycle and compatibility reopen checks.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied exact-head Testbox run exercises the changed production owner through real Gateway HTTP memory searches and observes the after-fix result: no duplicate cold physical opens or integrity scans, with successful vector lifecycle and compatibility reopen checks.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Heming Zeng: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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 (4 earlier review cycles)
  • reviewed 2026-09-04T10:18:33.967Z sha 1643c47 :: blocked before merge. :: [P2] Bound long-lived manager borrows
  • reviewed 2026-09-04T11:02:02.008Z sha b8245ef3a686be60d6d67612d0aa679ee4b13cc1 :: blocked before merge. :: [P3] Document the SQLite lifecycle control
  • reviewed 2026-09-04T11:22:26.495Z sha c6b64a57fb4e5daf2c4408655b6a30abc42a991c :: blocked before merge. :: [P3] Document the SQLite lifecycle control
  • reviewed 2026-09-04T12:09:40.943Z sha f6038e66d38014185d9a7343a93031624f8ea6ed :: blocked before merge. :: none

@steipete
steipete force-pushed the fix/memory-borrow-agent-connection branch from 6af3bb6 to c9f569c Compare September 4, 2026 10:49
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

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.

@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 4, 2026
@steipete
steipete force-pushed the fix/memory-borrow-agent-connection branch from b8245ef to c6b64a5 Compare September 4, 2026 11:13
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

The QA documentation-reference failure is resolved upstream by #138044. This branch has been refreshed onto that repair; git range-diff confirms the five memory commits are unchanged.

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.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 4, 2026
@steipete
steipete force-pushed the fix/memory-borrow-agent-connection branch from c6b64a5 to 111ac2e Compare September 4, 2026 11:53
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XL and removed size: L labels Sep 4, 2026
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The updated head 111ac2ec81a969ca320abb888abc97e24de30fd5 closes the supported transformed-SDK ownership gap: connection lifecycle, query-cache markers, commit observers, and hot-created-agent registry invalidation now share their process owner. The real-loader regression fails before the respective fixes and passes afterward. Native transaction state/savepoints replace duplicate nesting bookkeeping. A separate real SQLite trigger regression fixes eviction after physical close succeeds but lease release fails.

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.

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed the rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. label Sep 4, 2026
@clawsweeper clawsweeper Bot added the rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. label Sep 4, 2026
steipete and others added 7 commits September 4, 2026 05:17
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.
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Completed the requested native proof on f6038e66d38014185d9a7343a93031624f8ea6ed: Crabbox/Testbox run, wrapper exitCode=0, runStatus=succeeded. The lease is stopped; the Actions run is cancelled solely for lease cleanup.

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 79930b846762b28f941b55f6568b1d66fa1e5961 performed two cold physical opens and two integrity scans in every trial; candidate performed zero of either. Median cold HTTP time was 700.6 → 556.9 ms; median maximum event-loop delay was 683.1 → 569.4 ms. Earlier mixed timing results remain disclosed; the repeatable claim is removal of redundant database work.

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.

@steipete
steipete force-pushed the fix/memory-borrow-agent-connection branch from f6038e6 to 9306260 Compare September 4, 2026 12:22
@openclaw-barnacle openclaw-barnacle Bot removed the agents Agent runtime and tooling label Sep 4, 2026
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Final head 9306260da67345e2849317a4584b348b6cebfe99 passed Crabbox/Testbox proof: wrapper exitCode=0, runStatus=succeeded. The lease is verified completed; Actions cancellation is cleanup only.

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 sylvesterkaczmarek left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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.

@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Exact-head CI run 33872423001 completed successfully for 9306260da67345e2849317a4584b348b6cebfe99. All current PR checks have passed or intentionally skipped; none are pending or failed.

Native review artifacts are validated and recommend READY FOR /prepare-pr. Full changed-file checks and branch review passed. The final Crabbox proof and lifecycle/compatibility transcript are in the PR body and preceding comment. Production is +317/−340 (net −23); tests/test support +669/−132 (net +537); docs +15/−9 (net +6).

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.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Sep 4, 2026
@steipete
steipete merged commit 10afd71 into main Sep 4, 2026
192 checks passed
@steipete
steipete deleted the fix/memory-borrow-agent-connection branch September 4, 2026 12:51
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
…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]>
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 gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

2 participants