Skip to content

perf(memory): move admission off the Gateway thread and reuse clean receipts - #171322

Merged
steipete merged 3 commits into
mainfrom
dbasync/memadmit
Oct 13, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/memadmit

Conversation

@steipete

@steipete steipete commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Memory manager creation opened a native reader on the Gateway thread after its worker had already admitted the database. This repeated nine admission statements on the first turn and after reconnect. Initial reindexing also invalidated the memory schema receipt by replacing its FTS/vector tables, causing the next clean restart to repeat schema setup.

User Impact

Memory admission and bundled status reads use the memory workers. Clean restart can reuse the schema receipt after a successful reindex; unclean shutdown still requires integrity verification. Stored data, schema versions, configuration, and retention are unchanged.

The released MemorySearchManager.status() API remains deprecated synchronous compatibility. Built-in callers use statusAsync() through readMemorySearchManagerStatus; a worker failure never falls back to the native reader. Third-party managers that implement only the released synchronous API retain their existing behavior.

Why This Change Was Made

The publication worker returns admitted schema version, physical identity, table/index presence, and index facts. The manager keeps that worker and consumes its receipt instead of opening a second native connection. Retrieval workers admit read-only managers and provide status snapshots. Search retains the metadata it already received so a pre-existing manager observes a repair by another manager without another read or write. Owner-controlled derived-table replacement republishes the existing memory schema receipt only after commit, alongside existing transaction staging.

Removed duplicate checks and accepted edges:

  • The host's second quarantine/schema/canonical-definition admission is removed; the worker's physical database admission is authoritative until its owner retires it.
  • Read-only index/FTS existence uses worker-admitted schema facts; callers do not independently rediscover tables.
  • Full reindex reuses the FTS definition read for presence rather than querying presence separately; absent FTS remains unavailable and repairs through ordinary admission.
  • Native-handle liveness probes become owner-lifetime checks. Explicit synchronous compatibility alone opens that handle.
  • Internal read completion no longer rechecks the caller after receiving a worker snapshot; a concurrent change may leave that completed snapshot older than a later write. Existing effect and publication authority checks remain.

Static T1 in this scope: 0 → 0. The five-primitive inventory does not count these native reader/admission executions, so nine MAIN statements are not nine static T1 sites. The remaining synchronous status contract is explicitly retained compatibility debt.

Evidence

  • Regression coverage: first admission, async status after in-process writes, read-only reopen, FTS/vector replacement, clean receipt reuse, unclean integrity/schema verification, and concurrent repair observed by an already-open manager.
  • Focused CI-failure diagnosis: vector/non-vector admission and deadline fallback (3 cases), real fresh-process restart (2 cases), and concurrent Gateway repair (1 case) pass with successful wrapper exits. The lifecycle suites also pass in final-head CI.
  • Local: changed-file oxfmt, oxlint, and git diff --check pass.
  • Independent Codex review: both rounds scoped-clean, with no actionable P0/P1 findings. The second round covers the CI fixes and retained search metadata.
  • Final-head CI passed all 61 executed jobs, including all selected behavioral bundles, SDK packaging, production/test types, lint, source contracts, Knip, Madge, and the worker/T1/dialect ratchets. The aggregate CI gate is green. Initial CI exposed the repaired fixture and shared-status issues plus a now-pruned assertion baseline; its SDK declaration timeout did not recur on the final head.
  • Published-driver × candidate update cell: passed for final candidate 9ac15b453c421f92bc984d712bbd9541c4559f10. The package/image preparation and published-driver update job both passed.
  • One post-merge shared-harness parent/candidate pair passed: base 1798288f352286af4471a26a98b0d7feb3848a97, merge 05848c1714bd6987caf2a69392a30f861d1e5512. Both ran all 13 turns, control-plane/cron/compaction work, and two clean restarts; all fixture children exited. Node 26.11.1 / SQLite 3.53.4 on both sides. Counts only; no latency claim on the loaded host.
Runtime metric Base Candidate
Initial connection memory MAIN statements 9 0
First clean reconnect memory MAIN statements 9 0
Second clean reconnect memory MAIN statements 2 0
First clean restart memory schema-setup statements 125 4
Second clean restart memory schema-setup statements 4 4
Warmed causal statements, median [min–max] 137 [137–137] 137 [137–137]
Warmed causal requests, median [min–max] 37 [37–38] 37 [37–38]
Warmed causal MAIN statements 0 0
Whole extended workload statements / requests / MAIN 6,604 / 1,316 / 738 6,337 / 1,315 / 718

The first-start memory admission occurs in the connection window before the first turn. The remaining four restart statements are existing provenance/FTS data repair, not repeated schema validation. Memory-matched SQL across the extended workload fell 696 → 572. Original-workload totals rose 5,136 → 5,200 statements (+1.25%) and 1,006 → 1,008 requests (+0.20%): 31 extra memory-tagged cold worker-admission/session-projection statements and 33 other background statements. This uses the authorized ≤2% cold worker-move allowance; all warmed causal owner/family counts are unchanged. Initial schema setup shifted from connection to first turn, with the combined 250 setup statements unchanged.

Raw warmed-window medians remain 147 statements / 41 requests. Candidate has four background plugin-lease MAIN reads in its first warmed window; the same four occur during baseline's first turn (13 total lease reads on each side). There is no new MAIN work: total MAIN drops by exactly the 20 removed memory-reader executions. Full phase and per-operation counts are in the post-merge evidence comment.

Attribution of the prior nine: quarantine version + decision (2), agent schema metadata (1), expected canonical schema construction (5), expected-definition read (1). Caller: manager registry → manager creation → MemoryIndexDatabase.openPublished → openMemoryDatabaseReadOnlyAtPath → canonical read-only admission.

LOC: production +474/−197 (net +277); tests +252/−35 (net +217); docs +29/−3 (net +26); tooling +4/−1 (net +3).

Follow-ups from automated review

Two P2 lifecycle findings are deferred under the requested two-round/P0–P1 review limit: propagate worker-owner revocation into manager-registry liveness (otherwise a manager retained across database replacement can require restart), and close the retained publication worker when manager construction throws. Existing worker publication authority remains enforced; neither finding demonstrates a stale write, data loss, or a security bypass. These are recovery/resource-cleanup follow-ups, not additional admission checks.

@clawsweeper

clawsweeper Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Contributor

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T20:23:45.966007Z 9ac15b4 New commits
ℹ️ About Codex in GitHub

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

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

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime extensions: memory-core Extension: memory-core commands Command implementations plugin: file-transfer size: L labels Oct 13, 2026

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bc869cf26b

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +243 to +244
get isOpen(): boolean {
return !this.closed && (this.nativeDb?.isOpen ?? true);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Tie isOpen to the worker owner's revocation

When bundled callers use the new asynchronous status path, nativeDb remains unset, so this getter stays true even after the agent-database lifecycle revokes the retained publication worker. MemoryIndexManager.get() consequently reuses the stale manager; if Doctor or recovery replaced the database file, its captured admission identity no longer matches and subsequent publications fail until the manager or process is explicitly restarted. Preserve a worker-owner liveness signal so lifecycle revocation invalidates the registry entry without requiring the deprecated synchronous reader to have been opened.

AGENTS.md reference: AGENTS.md:L70-L70

Useful? React with 👍 / 👎.

Comment on lines +116 to +120
if (initialized) {
database.publicationWorker = Promise.resolve({
store: initialized.worker,
busyTimeoutMs: 5_000,
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Close the retained worker when manager construction fails

When MemoryIndexManager construction throws after openPublished() returns—for example, a missing or throwing runInBackgroundContext during default-manager setup—this worker has already transferred into database, but the constructor catch calls only release() and the outer creation catch has no assigned manager to close. Because release() does not close publicationWorker, the failed acquisition leaks its worker and database execution ownership, potentially retaining resources or preventing clean shutdown; the ownership-transfer failure path needs to close the worker as well.

AGENTS.md reference: AGENTS.md:L50-L52

Useful? React with 👍 / 👎.

@steipete steipete changed the title improve(memory): move admission off the Gateway thread and reuse clean receipts perf(memory): move admission off the Gateway thread and reuse clean receipts Oct 13, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 13, 2026
@steipete
steipete merged commit 05848c1 into main Oct 13, 2026
162 of 164 checks passed
@steipete
steipete deleted the dbasync/memadmit branch October 13, 2026 21:27
@steipete

Copy link
Copy Markdown
Contributor Author

Post-merge measurement completed on the exact squash merge and its parent, after green CI and the published-driver update cell. One pair only; the shared harness was copied solely to append two same-device clean restart cycles. Both 13-turn workloads, child/cron/compaction/RPC checks, restarts, and process cleanup passed.

Base 1798288f352286af4471a26a98b0d7feb3848a97; merge 05848c1714bd6987caf2a69392a30f861d1e5512. Node 26.11.1 / SQLite 3.53.4 for both. Local 32-core host load was 20.1–30.3; these are execution counts, with no latency claim.

Memory-owned MAIN is 9 → 0 at initial connection, 9 → 0 at first clean reconnect, and 2 → 0 at second clean reconnect. Static scoped T1 remains 0 → 0 because the inventory does not count these native/transitive admissions. The baseline call chain is manager registry → manager creation → MemoryIndexDatabase.openPublished → openMemoryDatabaseReadOnlyAtPath → canonical read-only admission. Its nine statements are readQuarantineSchemaVersion (1), readQuarantineDecision (1), readExistingAgentSchemaMeta (1), expectedDefinitions (5), and readDefinitions (1).

Warmed all-thread metric Base median [min–max] Candidate median [min–max]
Turn-caused statements 137 [137–137] 137 [137–137]
Turn-caused requests 37 [37–38] 37 [37–38]
Turn-caused MAIN 0 [0–0] 0 [0–0]
Raw-window statements 147 [147–150] 147 [147–170]
Raw-window requests 41 [41–43] 41 [41–45]
Raw-window MAIN 0 [0–0] 0 [0–4]

The four candidate raw-window MAIN reads are background readOpenClawStateLeaseExpiry calls from plugin registry startup. Baseline executes all 13 such lease reads in the first-turn window; candidate executes 9 there and 4 in the first warmed window. Total is 13 on both sides, with no turn causality. This is a phase shift, not new MAIN work. Exact-entry facts stay 20 statements / 20 containing requests across the ten warmed turns; actor hydration, entry-cache snapshots, session-row facts, and transcript watermarks stay zero. Causal coverage is complete, with no duplicate request records.

Phase Base statements / requests / MAIN Candidate statements / requests / MAIN
Initial boot 680 / 90 / 448 704 / 93 / 448
Initial connection 815 / 42 / 9 528 / 13 / 0
First turn 803 / 130 / 40 1,097 / 158 / 36
First restart boot 502 / 104 / 94 389 / 107 / 94
First restart connect 263 / 34 / 13 123 / 37 / 4
First restart shutdown 122 / 21 / 9 64 / 11 / 9
Second restart boot 397 / 104 / 94 376 / 103 / 94
Second restart connect 99 / 34 / 6 65 / 30 / 4
Second restart shutdown 85 / 13 / 9 120 / 19 / 9
Original workload, before appended restarts 5,136 / 1,006 / 513 5,200 / 1,008 / 504
Whole extended workload 6,604 / 1,316 / 738 6,337 / 1,315 / 718

First clean restart memory schema setup drops 125 → 4, and the second stays 4 → 4. Those remaining statements are two provenance backfill statements, FTS row-count reconciliation, and path-FTS backfill; they preserve data repair. Initial memory setup is 250 statements on both sides, shifted from connection + first turn into first turn. Across the extended workload, memory-matched statements fall 696 → 572.

The original workload increases by 64 statements (1.25%) and two requests (0.20%), within the authorized cold worker-move allowance. Memory-tagged cold admission/session projections account for +31 statements and memory-origin requests for +2; the remaining +33 statements are other background work. The extended workload saves 267 statements and one request. No warmed causal owner or shared-family increase occurs.

Memory operation, extended workload Base requests / directly attributed statements Candidate requests / directly attributed statements
Shadow open + initialization 2 / 15 2 / 15
Reindex publication commands 7 / 172 7 / 172
runMemoryIndexRead 13 / 22 12 / 27
runMemoryOriginRead 4 / 7 5 / 16
Transcript stats worker 1 / 6 1 / 9
Memory index preparation 2 / 0 2 / 0
Search prewarm 1 / 0 1 / 0
Publication-worker close 1 / 1 1 / 1
Memory-triggered transcript runtime 3 / 25 4 / 34
Memory-triggered transcript resource reads 3 / 0 3 / 0
Memory-triggered transcript read runtime 1 / 5 1 / 5
Memory-triggered execution-owner reads 1 / 8 2 / 16

These request rows exclude nested requests from the parent's SQL count. Memory-origin request totals are 28 → 30 before restarts and 39 → 41 overall. Reindex and shadow operations are unchanged; async reads and background session synchronization account for the cold differences. The successful-statement census excludes one baseline and two candidate failed BEGIN IMMEDIATE attempts in the existing audit-prune shutdown worker (database is locked); both complete workloads and cleanup passed.

Final CI passed all 61 executed jobs, including static gates and owner regressions; update validation passed. The two documented P2 lifecycle follow-ups remain deferred under the requested review limit. The released synchronous status compatibility contract remains deprecated; bundled flows use worker status without a synchronous fallback.

steipete added a commit that referenced this pull request Oct 13, 2026
Return Workboard cards and worker context from one owner read, and skip empty related-card snapshots. Let memory search use published status facts without unused diagnostic count queries while preserving full diagnostic status and visibility checks.

Add real-store regressions for a committed Workboard edit and refreshed memory contents. Preserve the async memory status owner introduced by #171322. No schema, retention, or configuration changes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…eceipts (openclaw#171322)

Keep memory admission and bundled status reads in the memory workers, publishing admitted facts to the manager instead of opening a second native reader on the Gateway thread. Republish memory schema receipts after committed FTS/vector replacement so clean restarts reuse them while unclean shutdowns still trigger integrity checks.

Retain and deprecate the released synchronous status API; bundled callers use async status. Preserve already-returned worker metadata across shared index repairs without adding database reads.

Validation: focused admission, clean/unclean restart, and concurrent repair regressions; final PR CI and published-driver update validation. Runtime statement evidence follows in the PR after merge.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…#171387)

Return Workboard cards and worker context from one owner read, and skip empty related-card snapshots. Let memory search use published status facts without unused diagnostic count queries while preserving full diagnostic status and visibility checks.

Add real-store regressions for a committed Workboard edit and refreshed memory contents. Preserve the async memory status owner introduced by openclaw#171322. No schema, retention, or configuration changes.
Grynn added a commit to Grynn/openclaw that referenced this pull request Oct 21, 2026
Retain the remaining raw-byte behavior from local8039fc5195d on upstreamf91bca9546f5. The host fs-safe append option recognizes leadingLF only; a proposed delta beginning withCR orCRLF must not receive an extraLF. Apply the same separator decision in sandbox writes and provenance contentAfter without changing replay rejection, source authority or path guards.

Do not replay the old aggregate maintenance/routing patch: upstream#168123 owns duplicate-note rejection,openclaw#138786 reindex backoff,openclaw#168471 and8fc0987fb08 Gateway CLI recall routing,openclaw#168860/openclaw#171322 worker-owned memory publication and admission. Raw proposed Markdown remains verbatim; no prefix stripping or normalized-offset mapping is retained.

Proof: four actual host/sandbox wrapper cases fail before the repair, then24tests pass including replay rejection, authority revocation and exact provenance/disk bytes forCRLF,CR,indentation,hard-break spaces and non-BMP text. Targeted agents-root types,scoped lint,format andline-cap pass; fresh independentP0-P2 review scoped-clean. Full candidate build,Doctor andactivation remain separate gates. Related:openclaw#125309.

Local-Feature: memory-append-raw-separators
Semantic-Source: 39a740d
Upstream-Tracking: openclaw#125309
Drop-When: Upstream host/sandbox append and provenance preserve leading CR and CRLF bytes.
Rebase-Base: ed9d493
Grynn added a commit to Grynn/openclaw that referenced this pull request Oct 21, 2026
Retain the remaining raw-byte behavior from local8039fc5195d on upstreamf91bca9546f5. The host fs-safe append option recognizes leadingLF only; a proposed delta beginning withCR orCRLF must not receive an extraLF. Apply the same separator decision in sandbox writes and provenance contentAfter without changing replay rejection, source authority or path guards.

Do not replay the old aggregate maintenance/routing patch: upstream#168123 owns duplicate-note rejection,openclaw#138786 reindex backoff,openclaw#168471 and8fc0987fb08 Gateway CLI recall routing,openclaw#168860/openclaw#171322 worker-owned memory publication and admission. Raw proposed Markdown remains verbatim; no prefix stripping or normalized-offset mapping is retained.

Proof: four actual host/sandbox wrapper cases fail before the repair, then24tests pass including replay rejection, authority revocation and exact provenance/disk bytes forCRLF,CR,indentation,hard-break spaces and non-BMP text. Targeted agents-root types,scoped lint,format andline-cap pass; fresh independentP0-P2 review scoped-clean. Full candidate build,Doctor andactivation remain separate gates. Related:openclaw#125309.

Local-Feature: memory-append-raw-separators
Semantic-Source: 39a740d
Upstream-Tracking: openclaw#125309
Drop-When: Upstream host/sandbox append and provenance preserve leading CR and CRLF bytes.
Rebase-Base: ed9d493
Grynn added a commit to Grynn/openclaw that referenced this pull request Nov 13, 2026
Retain the remaining raw-byte behavior from local8039fc5195d on upstreamf91bca9546f5. The host fs-safe append option recognizes leadingLF only; a proposed delta beginning withCR orCRLF must not receive an extraLF. Apply the same separator decision in sandbox writes and provenance contentAfter without changing replay rejection, source authority or path guards.

Do not replay the old aggregate maintenance/routing patch: upstream#168123 owns duplicate-note rejection,openclaw#138786 reindex backoff,openclaw#168471 and8fc0987fb08 Gateway CLI recall routing,openclaw#168860/openclaw#171322 worker-owned memory publication and admission. Raw proposed Markdown remains verbatim; no prefix stripping or normalized-offset mapping is retained.

Proof: four actual host/sandbox wrapper cases fail before the repair, then24tests pass including replay rejection, authority revocation and exact provenance/disk bytes forCRLF,CR,indentation,hard-break spaces and non-BMP text. Targeted agents-root types,scoped lint,format andline-cap pass; fresh independentP0-P2 review scoped-clean. Full candidate build,Doctor andactivation remain separate gates. Related:openclaw#125309.

Local-Feature: memory-append-raw-separators
Semantic-Source: 39a740d
Upstream-Tracking: none (no upstream issue or PR tracks CR-led append separators); related openclaw#125309 (closed completed 2026-10-24, memory-maintenance scope)
Drop-When: Upstream host/sandbox append and provenance preserve leading CR and CRLF bytes.
Rebase-Base: 0220489
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations docs Improvements or additions to documentation extensions: memory-core Extension: memory-core gateway Gateway runtime plugin: file-transfer scripts Repository scripts size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant