Skip to content

fix(sessions): await agent schema preparation before discovery - #173196

Merged
steipete merged 4 commits into
mainfrom
dbasync/firstbirth
Oct 15, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/firstbirth

Conversation

@steipete

@steipete steipete commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Fresh installations can accept a signed Gateway connection and then reject the first explicit-key sessions.create with SessionStoreUnavailableError (schema-missing). The agent owner has admitted the empty SQLite catalog, but its canonical schema creation is still pending. Session discovery treated that catalog admission as completed preparation.

This makes session target discovery join active first preparation through the existing per-agent execution owner before reading the catalog. Preparation settles before caller operations run, so discovery cannot wait on its own operation. Cancellation stops an individual discovery wait without canceling schema creation. Concurrent cold callers retain their own preparation completion until each settles. No retries, timeout increases, new schema, or second admission owner are added. Gateway readiness continues to permit lazy agent stores.

Reproduction and behavior proof

Fresh-state sample Attempts Target failures Sampling rule
Baseline, immediate after connect 18 0 Attempt 19 stopped before RPC and excluded
Baseline, one second after connect (authcold timing) 5 1 Stopped at first failure; not an unbiased rate estimate
Candidate, same one-second timing 50 0 Fixed 50-boot sample completed

Baseline build: a46ecb4350fc3230331ec5ac7c1def9ea9ba383a. Initial candidate base: 45d8782918d5b458b0dead5820e6efde87687bf0. Integrated main 93e4b56350e (including shared-state engine selection) into measured candidate 703a6331a89259cb35536701daf42bebb31c4a27 without conflicts; the fix and regression test are unchanged. The intervening change in this path adds cancellation forwarding; it leaves the catalog/schema ordering unchanged.

Baseline live fixture state was on external storage. Candidate live fixture state is on internal storage following host storage-fault guidance; the before/after samples are not a controlled failure-rate estimate. The deterministic regression isolates the ordering change.

The natural failing boot returned schema-missing 71 ms before schema DDL began and 523 ms before schema transaction commit. Teardown began after the client received the error. The deterministic RPC regression pauses initialization between catalog admission and canonical schema birth, covering both a new database and an interrupted empty file, plus cancellation of a concurrent preparer. It fails with the original ordering and checks the resulting persisted session after release.

SQL and thread scope

Metric Before After
Added statements / worker requests 0 0
Gateway T1 calls in changed execution/discovery modules 0 0
Warmed all-thread and MAIN totals Not measured for this reliability fix Not measured for this reliability fix

There is no warmed SQL reduction claim. The new warm-path lookup is an in-process owner lookup. No SQL implementation, schema, boot/service lifecycle, Doctor, update, plugin loading, or public SDK surface changes; no update cell applies.

No paranoid checks are removed in this reliability lane. Accepted edges: a preparation failure remains with its initiating caller and discovery reports normal availability afterward; failed creation is not retried. A genuinely empty database without active preparation retains existing availability handling. P2 follow-ups retained after the two review rounds: preparation starting on an earlier candidate while discovery awaits another can still report temporary unavailability. If an active cold preparation fails or is canceled after catalog admission, discovery can also finish before an independent queued preparer enters the native generation. These recoverable failed/canceled or multi-candidate edges are not the reproduced fresh-boot path; no repeated rescans or broader queue coordination are added.

Validation

Passed: deterministic Gateway RPC regression (both cases, including concurrent cancellation), plus six idle-owner tests; changed-file formatting, type-aware lint, and diff whitespace check; independent Codex review of the fix with no actionable P0–P2 findings, plus a clean P0/P1 review of the test-only CI correction. Runtime build at 703a6331a89 passed, including 97 plugins and the CLI import-boundary guard.

CI before the static-repair integration passed: 44 successful jobs, 25 skipped. The initial PR run exposed a test-only union-Promise inference error; the correction discards an unused fixture return value without changing completion or error propagation. Integrated-head attempt 1 passed all five test-type graphs, then hit the job deadline in the root-test partition. Rerunning only that cancelled job and its dependent gate passed without a code change.

The fixed 50-boot candidate sample completed with no failures at 703a6331a89. Integrated main's static repair through 486f5b5181fb into final head 3a88eacd54c0236ddf17267d17aee6452173a39e without changing any firstbirth production or regression file. Final-head CI passed with 46 successful jobs and 25 skipped, including the aggregate gate, types, lint, source contracts, worker/dialect ratchets, PostgreSQL conformance, and Madge (zero cycles).

Canonical production/full-tree/script Knip scans completed on Blacksmith Testbox, lease tbx_01m50eejz48avq4ebknvvzf1hq, after verifying the selected source hashes. Command: node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts. Exit 1 contains only these five inherited findings, exactly matching scheduled main at the incorporated base:

  • Production: src/gateway/operator-approval-store.ts: expireDueOperatorApprovals; ui/src/components/scroll-state.ts: scrollState.
  • Full tree: src/skills/lifecycle/clawhub.test-support.ts: expectInvalidSlug; ui/src/e2e/login-gate-e2e.test-support.ts: mountLoginGate.
  • Scripts: scripts/watch-pr-ci.mts: classifyAttachedCiRun.

No changed file is flagged. The Testbox was granted immediately (requested 16-class, observed four CPUs). Local canonical scans had hit their unchanged 600-second limits; those timeouts are not counted as passes. Node compile cache was disabled for all SSD builds and tests. Host load makes these reliability counts, not latency claims. The separate reported pre-readiness 300-second timeout remains unproven and is not claimed fixed.

LOC: +319 / −45 overall; production net +49, tests net +219, documentation +6. Most of the native-owner diff moves existing preparation into a try/finally that publishes completion before operation dispatch.

@clawsweeper

clawsweeper Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-15T18:40:59.807183Z 3a88eac 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 size: M labels Oct 15, 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: bd8d8c2e4b

ℹ️ 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 +547 to +550
for (const physicalPath of admissionPaths) {
const preparation = getPendingOpenClawAgentDatabasePreparation(physicalPath);
if (preparation) {
await racePromiseWithAbortSignal(preparation, signal, (aborted) => aborted.reason);

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 Recheck all candidates after preparation waits

When discovery has multiple exact candidates, this loop checks and awaits them sequentially. If candidate A has no preparation when checked, candidate B causes an await, and A's cold preparation admits its empty catalog during that wait, A is never checked again; the subsequent admission turn can then skip A because it appears admitted and dispatch discovery before A's schema DDL commits, reproducing the schema-missing failure. Multi-candidate batches are produced for shared/fixed stores by captureSessionStoreCandidateInventory, so the preparation snapshots should be collected together and all paths rescanned after any await before dispatch.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 15, 2026
@clawsweeper

clawsweeper Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

Session discovery waits for active agent database schema preparation before inspecting the catalog.

Example: Create agent:firstbirth-new:dashboard:first-birth while its empty database is initializing.

  • Before: sessions.create can fail with SessionStoreUnavailableError and schema-missing.
  • After: Discovery waits for schema preparation, then creates and persists the session.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The repair has clear value and meaningful boundary coverage, but a federated ordering defect remains and after-fix shipped behavior has not been supplied; no persisted format changes require migration.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A fresh Gateway can accept a connection and then reject its first explicit session creation because the agent schema is still being created.
Reason: The reported failure violates the existing session-creation contract, and the maintainer-authored direction repairs it through the established owner without new configuration or storage formats.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: it addresses a current first-session failure through the correct owner, but federated discovery can still bypass pending preparation after awaiting another store.

Priority: P1
Reviewed head: bd8d8c2e4b7457782728748ac1fe5cecc06faabc

Before merge

  • Recheck all exact candidates after preparation waits (P2) - Federated inventories can contain separate exact paths for agents main and work without a sibling-family reservation. If main has no pending preparation when checked, discovery awaits work, and main begins cold preparation during that await, main is never checked again. Once work settles, main's already-admitted empty catalog causes runWithSqliteDatabaseAdmissionTurn to skip its outstanding writer turn, allowing discovery to report schema-missing before main's schema commits. Collect pending preparations across all exact paths and rescan after waiting before dispatch; extend the boundary regression to this two-agent case.

Findings

  • [P2] Recheck all exact candidates after preparation waits — src/config/sessions/session-transcript-worker-resources.ts:547-550

Tests

  • Missing end-to-end proof: Supply completed candidate fresh-state Gateway sessions.create output and cover two per-agent candidates where the earlier store begins preparation during the later store's wait.
Agent review details

How this fits together

Gateway session requests resolve physical stores through discovery workers; the agent execution owner prepares their SQLite schemas and publishes readiness before readers consume them.

flowchart TD
  A[Gateway session request] --> B[Capture store candidates]
  B --> C[Observe agent preparation]
  C --> D[Agent execution owner]
  D --> E[SQLite schema preparation]
  C --> F[Discovery worker]
  F --> G[Resolved session store]
Loading

Technical review

Best possible solution:

Join preparation across all captured exact candidates and rescan after waits before discovery dispatch, retaining cancellation and existing unavailable-store handling.

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

The reported baseline boot trace and deterministic RPC regression establish the catalog-before-schema failure path; source inspection confirms current main retains it, but this review executed no target code.

Is this the best way to solve the issue?

Using the existing execution owner is the right repair and preserves lazy stores, but sequential observation must account for preparation that starts on an earlier candidate during another candidate's wait.

Full review comments:

  • [P2] Recheck all exact candidates after preparation waits — src/config/sessions/session-transcript-worker-resources.ts:547-550
    Federated inventories can contain separate exact paths for agents main and work without a sibling-family reservation. If main has no pending preparation when checked, discovery awaits work, and main begins cold preparation during that await, main is never checked again. Once work settles, main's already-admitted empty catalog causes runWithSqliteDatabaseAdmissionTurn to skip its outstanding writer turn, allowing discovery to report schema-missing before main's schema commits. Collect pending preparations across all exact paths and rescan after waiting before dispatch; extend the boundary regression to this two-agent case.
    Confidence: 0.88

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 824fde2bfab6.

Provenance checked

  • Retained native preparation keeps the original intent (8b7917c: Reuse settled native preparation rather than repeat schema admission on warm operations; the later retained-writer optimization preserves that contract.)
  • Discovery admission and worker ownership keeps the original intent (56e0b78: Cold discovery must join physical writer admission while stores remain lazy, with genuine schema absence still reported.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 31c35d5 adds src/state/openclaw-agent-execution-owner.ts:315 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 31c35d5f5b09; files: src/state/openclaw-agent-execution-owner.ts)

PR surface

Source +49, Tests +217, Docs +6. Total +272 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 5 94 45 +49
Tests 2 217 0 +217
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 317 45 +272

Labels

Label changes:

  • add P1: The reported current-main failure rejects the first explicit session creation after a fresh Gateway accepts a connection.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P1: The reported current-main failure rejects the first explicit session creation after a fresh Gateway accepts a connection.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 15, 2026, 10:39 AM ET / 14:39 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Follow-up from automated review: in multi-candidate discovery, a new cold preparation can start on an already-inspected path while another candidate is awaited. The accepted recoverable outcome is temporary store unavailability for that discovery. This fix joins already-active preparation through its owner; repeated cross-candidate readiness rescans are deferred. The deterministic first-birth regression covers the reported single-agent flow and cancellation of an overlapping preparer.

@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: 3a88eacd54

ℹ️ 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 +361 to +362
getPendingPreparation() {
return generation?.getPendingPreparation();

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 Track preparation before writer-queue admission

When two cold prepare() calls for the same store originate from independent async contexts, runOpenClawAgentWorkerWrite serializes them in the writer queue, but this getter exposes only the native generation's set, which is populated after a caller reaches current.run. If the active attempt aborts or fails after catalog admission, its deferred resolves before the outer queue admits the next live preparer; a discovery already awaiting that deferred can therefore observe no pending preparation and dispatch against the still-empty catalog, reproducing schema-missing even for a single candidate. Track pending preparation at the file-owner/admission level so queued attempts remain visible.

AGENTS.md reference: AGENTS.md:L7-L8

Useful? React with 👍 / 👎.

@steipete
steipete merged commit 55d9dab into main Oct 15, 2026
136 of 139 checks passed
@steipete
steipete deleted the dbasync/firstbirth branch October 15, 2026 19:11
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…law#173196)

Fresh installations could accept a Gateway connection and reject the first explicit-key sessions.create with schema-missing while the agent owner was still creating its schema. Join active first preparation through the existing agent execution owner before inspecting its admitted catalog. Settle preparation before caller dispatch and let discovery cancellation end only its own wait.

The deterministic RPC regression fails with the original ordering and passes for both new and interrupted-empty stores. The live authcold-timed baseline failed on boot 5; all 50 candidate boots passed. Baseline and candidate fixture storage differed, so those samples are not a controlled failure-rate estimate. Warm-path SQL and worker requests are unchanged; changed-module T1 remains zero. The separate 300-second startup timeout is not claimed fixed.

Final-head CI passed. Detailed proof, inherited static findings, and accepted P2 follow-ups are recorded in the PR.
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 gateway Gateway runtime P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M 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.

1 participant