Skip to content

fix: avoid repeated agent database checks at gateway startup - #122005

Closed
Grynn wants to merge 1 commit into
openclaw:mainfrom
Grynn:fix/gateway-agent-db-double-open
Closed

Grynn wants to merge 1 commit into
openclaw:mainfrom
Grynn:fix/gateway-agent-db-double-open

Conversation

@Grynn

@Grynn Grynn commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Closes #121985

What Problem This Solves

Fixes an issue where operators starting the Gateway with an existing SQLite agent database would pay for a full physical database open and integrity check twice during startup. The duplicate work is especially visible on large agent databases.

Why This Change Was Made

The session startup migration now leaves its agent database handle in the existing bounded cache so transcript reconciliation can reuse it. The per-physical-open integrity policy is unchanged, and a lifecycle regression test verifies that the handle remains warm across the migration-to-reconciliation boundary.

User Impact

Gateway startup avoids one redundant database open and integrity check per affected agent within the existing cache capacity. Database validation and repair behavior are otherwise unchanged.

Evidence

  • node scripts/run-vitest.mjs src/gateway/server-startup-session-migration.test-support.ts — 28 tests passed.
  • node scripts/check-changed.mjs --dry-run -- src/config/sessions/startup-migration.ts src/gateway/server-startup-session-migration.test-support.ts — classified as focused core production + core test changes.
  • node_modules/oxfmt/bin/oxfmt --check src/config/sessions/startup-migration.ts src/gateway/server-startup-session-migration.test-support.ts — both files formatted.
  • git diff --check origin/main...fix/gateway-agent-db-double-open — clean.
  • Live diagnosis on an approximately 765 MiB agent database measured a full integrity check at about 1.0 second, making the redundant physical open directly observable.

AI-assisted: yes. I reviewed and understand the lifecycle change and its test coverage.

Real behavior proof (added 2026-08-17)

After-fix gateway startup runtime trace demonstrating removal of the second physical open, on a real dataset: a 1.5 GiB agents/main/agent/openclaw-agent.sqlite plus its real agents/main/sessions store (operator state copies), isolated OPENCLAW_STATE_DIR, dist-backed node dist/index.js gateway, cold process, run to [gateway] ready. Physical opens were observed two independent ways: the product's own [state/agent-db] slow OpenClaw agent database open warning (fires per physical open slower than 1s; this database's integrity check takes ~2s) and strace -f -e trace=openat filtered to the exact database path.

Before — current main without this fix (baseline c98ae0f99cb, the fix's rebase parent):

[state/agent-db] slow OpenClaw agent database open   (17:54:26)
[state/agent-db] slow OpenClaw agent database open   (17:54:37)
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDONLY|...)          # owner probe
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDONLY|...)          # integrity read
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDONLY|...)          # integrity read
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDWR|O_CREAT|...)    # t+6.0s  migration open
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDWR|O_CREAT|...)    # t+16.1s reopen for reconciliation

After — exact PR head b79d9047e68:

[state/agent-db] slow OpenClaw agent database open   (17:56:01)   # exactly one
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDONLY|...)
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDONLY|...)
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDONLY|...)
openat(... "agents/main/agent/openclaw-agent.sqlite", O_RDWR|O_CREAT|...)    # single physical open, kept warm through reconciliation

The three read-only probe/verification opens are identical across both runs; the delta is exactly the redundant close→reopen pair between canonical-key migration and transcript reconciliation described in #121985 (which also predicted the two slow-open warnings — reproduced verbatim in the baseline run).

@clawsweeper

clawsweeper Bot commented Aug 11, 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 gateway Gateway runtime size: XS labels Aug 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 11, 2026
@clawsweeper

clawsweeper Bot commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 2, 2026, 9:51 PM ET / September 3, 2026, 01:51 UTC.

ClawSweeper review

What this changes

The PR keeps agent SQLite handles warm after session-startup maintenance so Gateway transcript reconciliation can reuse them instead of reopening and integrity-checking the same database.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open: the duplicate-open path remains on current main and in stable v2026.8.2, but this branch globally removes a close from a shared routine and regresses Local TUI handle lifecycle.

Priority: P2
Reviewed head: d3a7cdb7f048328272f2a932d6376435d9775caf

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong real Gateway proof supports the performance premise, but the shared lifecycle change remains unsafe for Local TUI and no longer fits current main's startup boundary.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body provides a real cold Gateway, dist-backed before/after trace on a 1.5 GiB agent database, with product slow-open logs and exact-path strace output showing two physical opens before and one after; the proof supports the intended Gateway optimization but not the unresolved Local TUI lifecycle defect.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body provides a real cold Gateway, dist-backed before/after trace on a 1.5 GiB agent database, with product slow-open logs and exact-path strace output showing two physical opens before and one after; the proof supports the intended Gateway optimization but not the unresolved Local TUI lifecycle defect.
Evidence reviewed 6 items Introduced lifecycle change: The PR removes the shared routine's cold-handle close after opening an agent database for canonical-key or registry maintenance.
Non-Gateway caller: Embedded Local TUI directly awaits the shared startup migration and has no following transcript-reconciliation handoff.
Current-main behavior: Current main still opens a cold database for maintenance, closes it in finally, then Gateway passes the same database options into reconciliation; reconciliation's write path opens through the agent database owner again.
Findings 1 actionable finding [P2] Scope warm-handle retention to the Gateway handoff
Security None None.

How this fits together

Gateway startup performs session-store maintenance before reconciling transcript indexes, both of which use the process-owned agent SQLite cache. The Local TUI also calls the maintenance routine but does not enter reconciliation.

flowchart TD
  A[Gateway startup] --> B[Session-store maintenance]
  B --> C[Agent database cache]
  C --> D[Transcript reconciliation]
  D --> E[Gateway serves history]
  F[Local TUI startup] --> B
Loading

Before merge

  • Scope warm-handle retention to the Gateway handoff (P2) - The deleted close applies to every caller of this shared migration, but EmbeddedTuiBackend calls it directly and never reconciles transcripts. A cold Local TUI startup can therefore retain each opened database until cache eviction or process exit. The added test exercises only the Gateway wrapper, so preserve the default close for Local TUI or make its lifecycle explicit. This re-raises the still-unfixed prior review finding.
  • Resolve merge risk (P1) - Merging the introduced global close removal would leave databases opened by Local TUI startup cached until LRU eviction or process exit, despite no Local TUI reconciliation handoff or lifecycle coverage.
  • Resolve merge risk (P1) - The branch is dirty against main, whose startup owner and test layout were substantially rewritten; its old two-file patch cannot be merged safely as-is.
  • Complete next step (P2) - Rebase or replace the branch against current main, retain handles only across the Gateway migration-to-reconciliation handoff, and add Local TUI lifecycle coverage.

Findings

  • [P2] Scope warm-handle retention to the Gateway handoff — src/config/sessions/startup-migration.ts:151-161
Agent review details

Security

None.

PR surface

Source -8, Tests +34. Total +26 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 1 9 -8
Tests 1 34 0 +34
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 35 9 +26

Review metrics

Metric Value Why it matters
Production vs test delta production -8, test support +34 The production simplification is net-negative, but the added coverage proves only the Gateway handoff and omits the shared Local TUI caller.

Merge-risk options

Maintainer options:

  1. Rebase with a Gateway-only handoff (recommended)
    Retain a cold handle only for Gateway's immediate reconciliation path and add Local TUI/default-close lifecycle coverage before merge.
  2. Pause this branch
    Leave the performance issue tracked by [Bug]: Gateway startup opens and integrity-checks existing agent SQLite databases twice #121985 until the current startup boundary can be repaired without changing Local TUI lifecycle semantics.

Technical review

Best possible solution:

Rebase or replace this branch with a Gateway-owned migration-to-reconciliation handoff that retains only the needed handles, while preserving the shared routine's default close for Local TUI and other non-handoff callers.

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

Yes — the supplied cold-Gateway trace shows the two-open baseline, and current main still has the source sequence that opens, closes, then reconciles through the same database owner.

Is this the best way to solve the issue?

No — retaining every handle in the shared routine fixes Gateway's path but changes Local TUI behavior; the cache handoff belongs at the Gateway boundary.

Full review comments:

  • [P2] Scope warm-handle retention to the Gateway handoff — src/config/sessions/startup-migration.ts:151-161
    The deleted close applies to every caller of this shared migration, but EmbeddedTuiBackend calls it directly and never reconciles transcripts. A cold Local TUI startup can therefore retain each opened database until cache eviction or process exit. The added test exercises only the Gateway wrapper, so preserve the default close for Local TUI or make its lifecycle explicit. This re-raises the still-unfixed prior review finding.
    Confidence: 0.98

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 63974421ae54.

Labels

Label justifications:

  • P2: This is a reproducible startup-latency defect for affected Gateway databases, with bounded user impact and no data-loss or availability evidence.
  • merge-risk: 🚨 compatibility: The patch changes the established cache-release lifecycle of a shared startup routine used by Local TUI.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR body provides a real cold Gateway, dist-backed before/after trace on a 1.5 GiB agent database, with product slow-open logs and exact-path strace output showing two physical opens before and one after; the proof supports the intended Gateway optimization but not the unresolved Local TUI lifecycle defect.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body provides a real cold Gateway, dist-backed before/after trace on a 1.5 GiB agent database, with product slow-open logs and exact-path strace output showing two physical opens before and one after; the proof supports the intended Gateway optimization but not the unresolved Local TUI lifecycle defect.

Evidence

Acceptance criteria:

  • [P1] node scripts/run-vitest.mjs src/gateway/session-startup-migration.test.ts.
  • [P1] OPENCLAW_TUI_PTY_INCLUDE_LOCAL=1 node scripts/run-vitest.mjs run --config test/vitest/vitest.tui-pty.config.ts.
  • [P1] node scripts/run-vitest.mjs src/config/sessions/startup-migration.registry-recovery.test.ts.

What I checked:

  • Introduced lifecycle change: The PR removes the shared routine's cold-handle close after opening an agent database for canonical-key or registry maintenance. (src/config/sessions/startup-migration.ts:151, d3a7cdb7f048)
  • Non-Gateway caller: Embedded Local TUI directly awaits the shared startup migration and has no following transcript-reconciliation handoff. (src/tui/embedded-backend.ts:416, d3a7cdb7f048)
  • Current-main behavior: Current main still opens a cold database for maintenance, closes it in finally, then Gateway passes the same database options into reconciliation; reconciliation's write path opens through the agent database owner again. (src/config/sessions/startup-migration.ts:117, 63974421ae54)
  • Reconciliation owner: The transcript preflight calls the writer transaction, whose owner opens or reuses the cached agent database; after the preceding cold-handle close this is a new physical open. (src/config/sessions/session-transcript-reconcile.ts:88, 63974421ae54)
  • Shipped and feature history: The current-shape owner retains the conditional close in commit a7466da; the release containment check reports v2026.8.2, so the central performance bug is not already shipped as fixed. (src/config/sessions/startup-migration.ts:117, a7466da1c061)
  • Real Gateway behavior proof: The PR body contains a redacted cold dist-Gateway before/after trace on a real 1.5 GiB agent database: the prior head reports two slow physical opens and the fixed head reports one, corroborated by an exact-path strace excerpt. (b79d9047e687)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Shakker: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Rebase onto current main and make cache retention a Gateway-owned migration-to-reconciliation handoff.
  • Add a Local TUI lifecycle regression proving cold migration-opened databases retain the default close behavior.
  • After the revised implementation, provide a redacted exact-head Gateway trace showing one physical open.

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 (6 earlier review cycles)
  • reviewed 2026-08-11T11:12:33.626Z sha b79d9047e687115fda4fda42c3e8744da8d59ade :: needs real behavior proof before merge. :: none
  • reviewed 2026-08-17T13:08:28.384Z sha b79d9047e687115fda4fda42c3e8744da8d59ade :: needs maintainer review before merge. :: none
  • reviewed 2026-08-20T09:06:19.250Z sha b79d9047e687115fda4fda42c3e8744da8d59ade :: needs changes before merge. :: none
  • reviewed 2026-08-26T10:16:06.415Z sha b79d9047e687115fda4fda42c3e8744da8d59ade :: needs changes before merge. :: none
  • reviewed 2026-08-26T10:31:48.342Z sha b79d9047e687115fda4fda42c3e8744da8d59ade :: needs changes before merge. :: [P2] Scope cache retention to the Gateway handoff
  • reviewed 2026-08-27T15:20:15.726Z sha d3a7cdb :: needs changes before merge. :: [P2] Scope cache retention to the Gateway handoff

@clawsweeper

clawsweeper Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

@Grynn

Grynn commented Aug 17, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Real behavior proof added to the PR body: cold-start gateway runs against a real 1.5 GiB agent database, before/after. Baseline (main without the fix) reproduces the two slow OpenClaw agent database open warnings and two O_RDWR physical opens from #121985; the exact PR head shows exactly one of each, with identical read-only probe opens — the removed second open is the migration→reconciliation close/reopen pair.

@clawsweeper

clawsweeper Bot commented Aug 17, 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 added proof: sufficient ClawSweeper judged the real behavior proof convincing. 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Aug 17, 2026
@clawsweeper clawsweeper Bot added 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. and removed 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. labels Aug 26, 2026
@Grynn
Grynn force-pushed the fix/gateway-agent-db-double-open branch from b79d904 to c71c7b3 Compare August 27, 2026 14:56
@Grynn

Grynn commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (8012723c729) as the review asked, rather than merging the obsolete file shape.

The defect is still reachable on current main

c43166a9208 (#128513) reduced how often the migration loop rescans stores, but the open/close churn is independent of that and survives it. src/config/sessions/startup-migration.ts on 8012723c729 still does:

const alreadyOpen = isOpenClawAgentDatabaseOpen(path);
const isRegistered = registeredDatabases.has(`${target.agentId}\0${path}`);
if (!isRegistered || !isCanonicalSqliteSessionMainKeyCurrent(...)) {
  const database = openOpenClawAgentDatabase({ agentId: target.agentId, env, path });
  setCanonicalSqliteSessionMainKey(database, params.cfg.session?.mainKey);
}
...
if (!alreadyOpen && isOpenClawAgentDatabaseOpen(path)) {
  closeOpenClawAgentDatabaseByPath(path);
}

Transcript reconciliation reopens that same file moments later, so a cold database that needs registration or canonical-key work is opened and integrity-checked twice per gateway start. On a multi-gigabyte agent store that is the dominant cost of an otherwise idle startup.

The change

Startup leaves the handle it opened in place and lets reconciliation reuse it, which is what the rest of startup already assumes. The alreadyOpen bookkeeping and the conditional close are removed rather than made smarter, so there is exactly one open per database per start.

Production delta is net -8 (1 added, 9 removed); the +34 is the regression test.

A correction to the regression test

The previous head's test passed vacuously. The suite's stub is:

sessionSqliteDatabaseExists: vi.fn().mockImplementation((params) => params.path === undefined)

A test that supplies a real resolved store path therefore makes databaseExists false, the migration loop hits continue, and no database is ever opened — so the "is it still open?" assertion saw a closed handle for a reason unrelated to the bug. The rebased test forces that stub true so it exercises the real open path.

Validation on this head

  • src/gateway/server-startup-secret-owner-isolation.test.ts (which loads server-startup-session-migration.test-support.ts) — 32 passed
  • Discrimination check on this exact base: with startup-migration.ts reverted to 8012723c729's version the new test fails expected false to be true (1 failed / 31 passed); with the fix applied, 32 passed
  • check:changed over both changed files

New head: c71c7b3acbf.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Aug 27, 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.

Startup migration opened each existing agent database to refresh its canonical
session main key, then closed it again whenever it had not already been open.
Transcript reconciliation reopens the very same file moments later, so every
gateway start paid a second open plus a second SQLite integrity check of a file
it had just finished checking. On a multi-gigabyte agent store that is the
dominant cost of an otherwise idle startup.

Startup now leaves the handle it opened in place and lets reconciliation reuse
it, which is what the rest of startup already assumes. The `alreadyOpen`
bookkeeping and the conditional close go away rather than being made smarter,
so there is one open per database per start.

Main's openclaw#128513 reduced how often the migration loop rescans stores, but the
open/close churn was independent of that and is still reachable for cold
databases that need registration or canonical-key work.

Regression coverage asserts the handle is still open while reconciliation runs.
Note the suite's `sessionSqliteDatabaseExists` stub answers
`params.path === undefined`, so a test that supplies a real resolved path skips
the migration branch entirely and would pass without ever opening anything; the
new test forces that stub true so it exercises the real open path. It fails on
unfixed code with `expected false to be true`.

Refs openclaw#121985
@Grynn
Grynn force-pushed the fix/gateway-agent-db-double-open branch from c71c7b3 to d3a7cdb Compare August 27, 2026 15:13
@Grynn

Grynn commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

CI note on the previous head (c71c7b3acbf): 206 checks passed, one real failure — build-artifacts, and I do not believe it is attributable to this change.

The failing verifier was startup-memory:

plugins list --json median max RSS 401.7 MB exceeded effective ceiling 401 MB
(base limit 400 MB; RSS tolerance 1 MB; samples: 328.8, 401.7, 402.5 MB)

That is a 0.7 MB overshoot — 0.17% — decided by a median of three samples whose spread is 74 MB.

This branch cannot plausibly move that number:

  • The measured command is openclaw.mjs plugins list --json. The only module this PR touches in production is src/config/sessions/startup-migration.ts, whose sole importers are src/gateway/server-startup-session-migration.ts (gateway boot) and a dynamic await import() in src/tui/embedded-backend.ts. Neither is on the plugins list path.
  • The production diff is -8 lines and two removed imports. Removing imports can only shrink the module graph, never grow it.
  • The retained SQLite handle this PR introduces is only retained inside runSessionStartupMigration, which plugins list never calls.

The reading I would offer instead is that plugins list --json on main has drifted up to the ceiling: a 400 MB base limit with a 1 MB tolerance, against samples ranging 328.8 to 402.5 MB, will fail intermittently for any PR that happens to land on an unlucky median. That is a main-owned budget decision (raise the ceiling, or find and fix the drift), not something this PR should absorb, so I have not touched it here.

I do not have rerun rights on this repository, so I refreshed the head to re-fire CI. d3a7cdb7f04 has a byte-identical tree to c71c7b3acbf (7d6b116870ec006ee2a62a748184ab1673d17f1f in both) — no behavior change, purely a CI re-trigger.

If the re-run reproduces the same overshoot, that is stronger evidence for the drift reading than for a regression here, and I am happy to open a separate issue for the startup-memory budget.

@Grynn

Grynn commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

CI is green on d3a7cdb7f04, including build-artifacts.

That settles the earlier startup-memory failure: c71c7b3acbf and d3a7cdb7f04 have the same tree (7d6b116870ec006ee2a62a748184ab1673d17f1f), and the identical bytes failed once and passed once. The gate is nondeterministic at that threshold, not sensitive to anything in this change.

For whoever owns that budget, the failing sample set was:

plugins list --json median max RSS 401.7 MB exceeded effective ceiling 401 MB
(base limit 400 MB; RSS tolerance 1 MB; samples: 328.8, 401.7, 402.5 MB)

A 1 MB tolerance over samples spanning 328.8-402.5 MB will keep flipping for unrelated PRs. Happy to open a separate issue for it if that is useful — it is out of scope for this change, so I have left it alone here.

steipete added a commit that referenced this pull request Sep 4, 2026
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]>
steipete added a commit that referenced this pull request Sep 4, 2026
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 #137750
Closes #121985
Supersedes #122005

Thanks to Hampert for reporting the cold-search stall and @Grynn for identifying the startup duplicate checks.

Co-authored-by: Grynn <[email protected]>
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Thanks, @Grynn. Your duplicate-startup-check intent is now absorbed in #138166, merged as 10afd71a79e6, with Co-authored-by: Grynn <[email protected]> retained in the landed commit.

The landed repair reuses the already-verified canonical connection throughout Gateway startup and memory-manager acquisition, removing the redundant writable open and initialization. It also preserves temporary TUI maintenance cleanup, isolated rebuild writers, validation before exposure, and borrowed-handle shutdown. Native/transformed SDK identity and transaction semantics are covered.

Exact-head CI and Crabbox CLI/Gateway/vector/older-reader compatibility proof passed. Closing this PR as superseded by that complete owner-lifecycle repair; no remaining implementation from this PR is needed separately.

@steipete steipete closed this Sep 4, 2026
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

gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Gateway startup opens and integrity-checks existing agent SQLite databases twice

2 participants