Skip to content

fix(doctor): PostgreSQL maintenance custody - #173683

Merged
steipete merged 1 commit into
mainfrom
pgprep/r14a-pg-custody
Oct 16, 2026
Merged

steipete merged 1 commit into
mainfrom
pgprep/r14a-pg-custody

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Doctor cannot acquire maintenance custody on PostgreSQL shared state because lease inspection takes a SQLite repair snapshot and rejects the PostgreSQL reader. Populated PostgreSQL leases also lose their camel-case column aliases, preventing owner identity decoding.

User Impact

Doctor can acquire and release offline PostgreSQL custody and run data-only legacy state migrations. A live Gateway still blocks maintenance, including through another anchor for the same PostgreSQL store.

Schema migrations remain blocked with an actionable error until their state-family backup path is available. The remaining work is tracked separately: the PG schema-migration end-to-end proof follows R13 (state family registration).

Why This Change Was Made

Reuse the admitted PostgreSQL state reader and existing owner-lease checks, with typed PostgreSQL lease selection. Keep SQLite's private snapshot and damaged-index-safe query byte-for-byte. Writes retain the existing PostgreSQL advisory transaction lock; no new lock protocol or shared-admission revision changes.

The schema runner is unchanged. Its backup dependency now reports the missing PostgreSQL state-family support and directs the operator to keep the database and retry with a supporting version.

Evidence

  • PostgreSQL 17 conformance: all four cases pass, using one in-process suite fixture. The actual config-machine-state no-op step runs through the migration runner, followed by a synthetic committed state write. Custody releases/reacquires; a real Gateway lease blocks a second anchor; schema backup refusal names the next step.
  • SQLite maintenance inspection: the original implementation and patched implementation both pass the same eleven ordered raw-statement expectation, including writable-schema admission and the NOT INDEXED lease scan.
  • Production delta: +27 net lines, below the 400-line limit.
  • Existing SQLite custody/lock tests: 47 passed. SQLite migration-backup tests: 17 passed.
  • Format, targeted lint, and all 29 core test-typecheck shards plus the final core production typecheck passed. Madge reports zero cycles. Worker ratchet: 222 → 222 live calls. Assertion, dialect, timeout, mock-export, and line-cap ratchets passed. One isolated Codex autoreview completed with no actionable P0–P2 findings.
  • Inherited local gate failures at the base commit: max-lines still lists ui/src/pages/chat/components/chat-message.test.ts while the unchanged file is now .tsx; Knip reports the unchanged, unused ui/src/components/loading-skeleton.ts. No UI files or baseline exceptions are changed here.

Conformance timing: 25.79 seconds in Vitest (about 2 seconds executing the four cases); 128 seconds for the wrapper including cold worker compilation. The initial live-lease test exposed PostgreSQL alias folding and passed after the typed-query fix. A first SQLite backup test attempt was rejected because source changed during worker compilation; the final frozen-source rerun passed.

Draft CI observation for 90c825a832ac5117536859cd217e971987198269: all 12 checks that ran passed (including TypeScript contracts, Rust workspace, actionlint, PR context/evidence, and Socket). Full CI and openclaw/ci-gate were skipped while the PR was draft; this is not full-CI proof.

Landing validation

Final-head CI: run 38843454803, attempt 1, head 90c825a832ac5117536859cd217e971987198269. PostgreSQL conformance passed, including all four maintenance-custody cases; all typechecks, baseline ratchets, and the other selected test jobs passed. No failed/cancelled-job rerun or fix push was needed.

The native admin exception is limited to this unrelated failure and its downstream aggregate:

Failure Classification and evidence
checks-node-changed-compact-large-18-2: src/state/openclaw-agent-db.test.ts / serializes concurrent ownership claims for one unowned database Unrelated SQLite ownership race: both child openers returned success. The failing test and its owner, src/state/openclaw-agent-db-schema.ts, are unchanged; the case invokes ensureOpenClawAgentDatabaseSchema on SQLite and does not call the changed PostgreSQL maintenance-custody path. The failed job's executed test-file set is disjoint from this PR's changed files.
openclaw/ci-gate Aggregate failure caused by the single test job above; security-fast passed independently.

The earlier local UI gate failures are also present on main and remain outside this PR: Knip reports unused ui/src/components/loading-skeleton.ts in scheduled main run 38841437948; main 6ce4fb7f39ca751db358b0da9f50f7552b0e8ef3 retains ui/src/pages/chat/components/chat-message.test.ts in config/max-lines-baseline.txt while the actual file is .tsx. Neither UI file nor the baseline is changed here. The final-head CI baseline-ratchet job passed.

Inspect PostgreSQL Gateway leases through admitted state readers and preserve
case-sensitive lease aliases. Keep SQLite maintenance snapshots and statements
unchanged. Data-only migrations retain existing writer advisory transactions;
schema migrations report the missing PostgreSQL state-family backup support.
@clawsweeper

clawsweeper Bot commented Oct 16, 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation commands Command implementations size: M labels Oct 16, 2026
@steipete
steipete marked this pull request as ready for review October 16, 2026 03:01
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 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-16T03:05:40.191982Z 90c825a Draft marked ready
ℹ️ 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.

@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: 90c825a832

ℹ️ 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".

try {
authority.assertCurrent();
if (schemaMaintenance) {
if (schemaMaintenance && !isStatePostgres()) {

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.

P1 Badge Hold PostgreSQL maintenance custody across the workflow

When Doctor uses anchor A and a Gateway starts afterward through anchor B for the same PostgreSQL store, this branch has performed only a point-in-time lease inspection and publishes no PostgreSQL-visible maintenance ownership. The Gateway can therefore acquire its own lease while Doctor remains active; the per-transaction advisory lock only serializes individual writes, allowing the Gateway to observe or interleave intermediate migration state. The new conformance test covers only Gateway-before-Doctor, so PostgreSQL custody needs to remain visible until maintenance releases it.

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

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR enables PostgreSQL maintenance lease inspection, preserves lease aliases, and explicitly refuses unsupported schema backups.

Example: Doctor inspects a PostgreSQL store containing a Gateway lease on port 19483.

  • Before: SQLite-specific inspection rejects PostgreSQL, and unquoted aliases prevent lease decoding.
  • After: Doctor decodes the lease and refuses maintenance while that Gateway is active.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful engine-specific repair with meaningful integration coverage, blocked by nonexclusive maintenance custody; latest-stable upgrade preservation evidence is also absent.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🧂 unranked krab (1/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Doctor cannot obtain maintenance custody for configured PostgreSQL shared state.
Reason: The maintainer-authored direction restores an existing maintenance responsibility without adding configuration, schemas, or public APIs.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep open: this maintainer-authored PR addresses a real PostgreSQL limitation, but maintenance custody does not exclude a later Gateway using another anchor.

Priority: P2
Reviewed head: 90c825a832ac5117536859cd217e971987198269

Before merge

  • Add real behavior proof - Authority-chain proof required: the supplied PostgreSQL 17 in-process conformance exercises acquisition, a synthetic committed write, release, and Gateway-before-Doctor refusal, but does not prove a later second-anchor Gateway is rejected before PostgreSQL lease publication or writes, or that released custody cannot authorize further maintenance effects. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Hold PostgreSQL maintenance custody across the entire workflow (P1) - Removing the PostgreSQL maintenance refusal permits Doctor to proceed after a point-in-time Gateway lease read, but its retained ownership is only anchor-local. With two anchors for the same store, acquire Doctor custody through A and then start a Gateway through B: B has a different file lock, finds no Gateway lease, and can publish its own lease. Maintenance never publishes PostgreSQL-visible exclusion, and pg_advisory_xact_lock ends at each commit, so the Gateway can observe or interleave intermediate migration state. Extend the existing custody lifecycle to exclude other anchors until release, or retain the PostgreSQL maintenance refusal. The added test covers only Gateway-before-Doctor.
  • Complete next step - Classify the failed agent ownership CI assertion against the pinned base before treating it as inherited or requiring an author repair.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P1] Hold PostgreSQL maintenance custody across the entire workflow — src/infra/gateway-owner-lease.worker.ts:42-44

Tests

  • Missing end-to-end proof: Missing production-boundary proof starts Doctor first, rejects a second-anchor Gateway before lease publication or writes, and permits acquisition only after release; the PostgreSQL regression's base failure is also unshown.
Agent review details

How this fits together

Doctor acquires lifecycle custody before migrations; worker lease inspection reads the selected state engine and determines whether maintenance may proceed.

flowchart TD
Doctor[Doctor migrations] --> Custody[Lifecycle custody owner]
Custody --> Anchor[Anchor-local ownership lock]
Custody --> Reader[State lease read worker]
Reader --> Postgres[PostgreSQL shared state]
Gateway[Gateway through another anchor] --> Postgres
Doctor --> Writer[State write transactions]
Writer --> Postgres
Loading

Technical review

Best possible solution:

Extend the existing custody owner to exclude all anchors for the PostgreSQL store throughout maintenance while retaining SQLite behavior and unsupported-backup refusal.

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

Source establishes the failure sequence: Doctor acquires anchor A, then a Gateway using anchor B sees no maintenance lease and can acquire the same PostgreSQL store; no target code was executed.

Is this the best way to solve the issue?

The admitted-reader and typed-alias changes fit the existing owners, but enabling maintenance requires store-wide exclusion beyond individual write transactions.

Full review comments:

  • [P1] Hold PostgreSQL maintenance custody across the entire workflow — src/infra/gateway-owner-lease.worker.ts:42-44
    Removing the PostgreSQL maintenance refusal permits Doctor to proceed after a point-in-time Gateway lease read, but its retained ownership is only anchor-local. With two anchors for the same store, acquire Doctor custody through A and then start a Gateway through B: B has a different file lock, finds no Gateway lease, and can publish its own lease. Maintenance never publishes PostgreSQL-visible exclusion, and pg_advisory_xact_lock ends at each commit, so the Gateway can observe or interleave intermediate migration state. Extend the existing custody lifecycle to exclude other anchors until release, or retain the PostgreSQL maintenance refusal. The added test covers only Gateway-before-Doctor.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • node scripts/test-database-conformance.mjs --engine postgres --connection "$REVIEW_POSTGRES_DSN" -- src/infra/database-engine/maintenance-custody.conformance.test.ts --maxWorkers=1
  • pnpm test src/infra/gateway-owner-lease.test.ts src/infra/gateway-lock.test.ts src/infra/gateway-state-owner.test.ts src/commands/doctor-migration-backup.scoped.test.ts --maxWorkers=1
  • pnpm check:changed
  • git diff --check

What I checked:

  • Pinned introduction and current-main comparison: The introduced patch removes PostgreSQL maintenance refusal and preserves the SQLite scan; fetched main still contains the refusal and unquoted PostgreSQL aliases. (src/infra/gateway-owner-lease.worker.ts:42, 90c825a832ac)
  • Maintenance ownership remains local: Lifecycle ownership uses the local database path, and only the Gateway role publishes a PostgreSQL-visible Gateway lease; maintenance publishes no equivalent exclusion. (src/infra/gateway-lock.ts:662, 90c825a832ac)
  • Transaction locks do not cover the workflow: PostgreSQL writes acquire pg_advisory_xact_lock and release it at transaction completion, leaving gaps between migration steps. (src/infra/postgres-sync/transaction.ts:36, 90c825a832ac)
  • Existing discussion independently verified: The recorded Codex connector review identifies the same Doctor-first, second-anchor custody defect; source inspection supports that concern. (src/infra/gateway-owner-lease.ts:151, 90c825a832ac)
  • Accepted scope: The maintainer-authored body deliberately leaves schema migrations blocked pending state-family backups; that existing limitation is documented rather than silently bypassed. (src/commands/doctor-migration-backup.ts:192, 90c825a832ac)
  • CI failure remains unattributed: The failed shard reports two successful concurrent agent ownership claims where one is expected at openclaw-agent-db.test.ts:2349; no matching base failure was established, and downloading its detailed logs was blocked by the artifact host allowlist. (src/state/openclaw-agent-db.test.ts:2349, 90c825a832ac)

Likely related people:

  • Peter Steinberger: Raw commit 7c2aa57 adds src/infra/gateway-owner-lease.ts:147 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7c2aa571ea03; files: src/infra/gateway-owner-lease.ts)

PR surface

Source +27, Tests +264, Docs +8. Total +299 across 8 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 44 17 +27
Tests 2 264 0 +264
Docs 2 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 317 18 +299

Review metrics

Metric Value Why it matters
Production versus test change Production +44/-17 lines; tests +263 lines The focused production growth is reasonable, but the integration coverage omits the reverse acquisition order that exposes the custody defect.

Labels

Label changes:

  • add P2: This affects optional experimental PostgreSQL maintenance, with a focused integrity repair needed before merge.
  • add merge-risk: 🚨 session-state: A Gateway using another anchor can read or mutate shared state between Doctor migration transactions.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦐 gold shrimp and patch quality is 🧂 unranked krab.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: This affects optional experimental PostgreSQL maintenance, with a focused integrity repair needed before merge.
  • merge-risk: 🚨 session-state: A Gateway using another anchor can read or mutate shared state between Doctor migration transactions.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🦐 gold shrimp and patch quality is 🧂 unranked krab.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

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, 11:18 PM ET / October 16, 2026, 03:18 UTC.

@steipete
steipete merged commit 3154917 into main Oct 16, 2026
284 of 288 checks passed
@steipete
steipete deleted the pgprep/r14a-pg-custody branch October 16, 2026 03:42
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
Inspect PostgreSQL Gateway leases through admitted state readers and preserve
case-sensitive lease aliases. Keep SQLite maintenance snapshots and statements
unchanged. Data-only migrations retain existing writer advisory transactions;
schema migrations report the missing PostgreSQL state-family backup support.
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 merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant