Skip to content

fix(postgres): reopen shared-state workers after connection loss - #179128

Merged
steipete merged 2 commits into
mainfrom
pgprep/pgchaos-state-recovery
Oct 21, 2026
Merged

steipete merged 2 commits into
mainfrom
pgprep/pgchaos-state-recovery

Conversation

@steipete

@steipete steipete commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

After a PostgreSQL backend is terminated or the server restarts, a shared-state worker can retain a closed connection and reject later operations until the Gateway restarts. Both its primary native handle and its separately retained update-bookkeeping writer accepted a closed PostgreSQL connection during settlement, so the existing worker retirement and reopen path never ran.

Reject closed PostgreSQL handles in their settlement owners. The broker retires the failed actor, and a subsequent operation opens a fresh owner; the interrupted operation is never replayed. SQLite's intentional closed-wrapper behavior is preserved. The PostgreSQL troubleshooting guide describes the recovery behavior.

Evidence

  • The primary-handle regression is red on main base 76ce4df44eb8. The additional updater regression is red on the unchanged updater owner at the earlier PR head d313fc8f2f24, with Existing-state writer is closed. It uses the production async update API, terminates only the updater backend, verifies the other idle backends stay untouched and the previous value survives, then requires a fresh write to succeed.
  • The repaired candidate passes all 13 PostgreSQL state tests and 23 SQLite settlement/existing-writer tests, core and state-test typechecks, scoped type-aware lint, formatting, and whitespace checks. The PostgreSQL file takes 54.43 seconds including its existing migration/boot coverage; the two added fault cases take 0.991 and 1.153 seconds. The canonical PostgreSQL command, including setup/build work, takes 79.57 seconds. SQLite's two selected shards take 26.19 and 3.24 seconds.
  • Real Gateway + agent + model at C16: recovery turns after backend termination and fast restart improve from 0/3 to 3/3 without restarting the Gateway. After a 15-second immediate stop, two idle connections report their earlier loss on first use, then the third turn succeeds. This live comparison established the primary-handle repair; the updater participant is additionally covered by the production async API regression.
  • Final fault-replay teardown has zero application connections, advisory locks, or TEMP relations. A subsequent soak was interrupted by provider teardown at 48.9 minutes; it is not a two-hour pass and does not establish leak freedom.

Fresh isolated P0–P2 review is clean. Final-head CI39564974568 on c99e5e2ce5928cef1f4c42076bfeb9ed20b7d62f actually executed and passed all three PostgreSQL conformance shards. Security, lint, production types, source contracts, and the other test-type stripes passed.

The CI gate remains red solely for the inherited root-tooling errors in test/scripts/ci-changed-node-test-plan.test.ts:813,891: CompactNodeTestShard lacks configs required by ChangedNodeTestShard. The exact four diagnostic lines were independently reproduced on clean main 5e9c3fbfd6a2359f5980e75688c08c23a17af592 with node scripts/run-tsgo.mjs --noEmit -p test/tsconfig/tsconfig.test.root.tooling.json (exit2). This PR changes neither the planner nor those tests. Landing uses the authorized inherited-failure exception; the failed CI result is retained.

Pr-simplify retains the existing lifecycle owners and one table-driven real-PG regression covering the two retained participants. No SQL, transaction, advisory-lock, schema, or durability changes. Added healthy-path requests / wire trips / SQL: 0 / 0 / 0 by source inspection, with no throughput or latency optimization claim. Production +7/−1 lines, tests +114, documentation +5/−3.

@clawsweeper

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

@steipete
steipete marked this pull request as ready for review October 21, 2026 06:14
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: S labels Oct 21, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 21, 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-21T08:15:21.553655Z c99e5e2 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.

@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: d313fc8f2f

ℹ️ 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 +506 to +508
if (!nativeDatabase.db.isOpen && isPostgresSqlConnection(nativeDatabase.db)) {
throw new Error("Shared-state worker retained a closed PostgreSQL connection");
}

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 Retire actors when the update writer loses PostgreSQL

When a restart or backend termination is first observed by the retained updateRunWriter while the primary nativeDatabase has not yet issued another query, this check misses the closed connection: createExistingPostgresStateWriter.assertSettled() permits db.isOpen === false, and the new condition examines only nativeDatabase.db. The actor therefore remains available with the same closed update writer, so subsequent updateRuns.* operations immediately fail with Existing-state writer is closed until the actor is otherwise retired or the Gateway restarts, breaking the recovery behavior for update bookkeeping. Make the PostgreSQL update writer's settlement check trigger actor retirement too.

AGENTS.md reference: AGENTS.md:L76-L76

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 21, 2026
@clawsweeper

clawsweeper Bot commented Oct 21, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Reject closed primary PostgreSQL connections during worker settlement so subsequent requests can reopen shared state.

Example: Terminate the PostgreSQL backend after writing reconnect.fixture = "before".

  • Before: The interrupted write fails, and subsequent writes keep failing until the worker is retired.
  • After: The interrupted write fails without replay; a subsequent write stores "recovered" through a fresh connection.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-supported repair with meaningful real-database regression coverage; shipped-entry-point results are reported in prose rather than inspectable runtime artifacts.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the contributor proof gate; its body records real Gateway-agent-model recovery, while the inspected regression exercises the production worker with a real PostgreSQL backend.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: After PostgreSQL connection loss, shared-state operations remain unavailable even after the server returns.
Reason: The maintainer-authored direction restores useful recovery through existing lifecycle machinery with a narrow production change.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it provides a focused recovery fix that current main lacks, with no introduced correctness defect found.

Priority: P2
Reviewed head: d313fc8f2f244bbe06254260a8c4cc2ca4e3f23e

Before merge

None.

Findings

None.

Agent review details

How this fits together

Shared-state operations enter a broker-managed worker, which retains database connections and returns operation results; settlement tells the broker when a failed worker must retire.

flowchart LR
  A[Shared-state request] --> B[Worker broker]
  B --> C[Shared-state worker]
  C --> D[PostgreSQL connection]
  D --> E[Settlement check]
  E --> F[Retire failed worker]
  F --> B
Loading

Technical review

Best possible solution:

Keep closed-primary-handle rejection in the existing settlement owner, preserving failed-operation non-replay and SQLite settlement behavior.

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

Source establishes the stuck-handle path, and the added real-PostgreSQL test supplies a concrete backend-termination reproduction; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The three-line check is the smallest focused repair: it uses existing settlement and retirement owners without adding replay, state, or healthy-path database work.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Verified introduced change: The pinned introduction adds only a PostgreSQL closed-handle settlement check, one real-PostgreSQL regression, and recovery documentation. (src/state/openclaw-state.worker.ts:506, d313fc8f2f24)
  • Current main still accepts the failed handle: Current main checks retained transactions and readers but does not reject a closed primary PostgreSQL connection; assertTransactionUsable explicitly returns for PostgreSQL. (src/state/openclaw-state.worker.ts:502, aeae6d1d79a3)
  • Existing retirement owner: A thrown settlement check sets retire=true, preserving the existing broker-owned retirement mechanism rather than introducing retries or another lifecycle owner. (src/infra/sqlite-store.worker.ts:242, d313fc8f2f24)
  • Meaningful regression coverage: The added test terminates the actual PostgreSQL backend, checks that the interrupted write leaves the prior value intact, then verifies a fresh write succeeds through the production worker API. (src/state/openclaw-state-db.postgres.test.ts:137, d313fc8f2f24)
  • Existing review concern independently assessed: The concern at fix(postgres): reopen shared-state workers after connection loss #179128 (comment) identifies a real limitation of the separately retained update writer: its PostgreSQL settlement accepts closed handles. That behavior and its separate connection already exist on the base; this PR does not introduce the failure, so it is not reported as an introduced defect. (src/state/openclaw-state-db-existing-write.ts:364, d313fc8f2f24)
  • Reported behavior and current checks: The complete PR body reports base-red/head-green PostgreSQL recovery and real Gateway-agent-model recovery after backend termination and restart. Exact-head PostgreSQL conformance remains in progress; no failing check was observed in the returned check page. (d313fc8f2f24)

Likely related people:

  • Peter Steinberger: Raw commit 335d435 adds src/state/openclaw-state.worker.ts:305 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 335d435bded0; files: src/state/openclaw-state.worker.ts)
  • Galin Iliev: Raw commit 4269cd4 adds src/state/openclaw-state.worker.ts:644 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4269cd4e1afb; files: src/state/openclaw-state.worker.ts)
  • Vincent Koc: Raw commit 30717de adds src/state/openclaw-state.worker.ts:320 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: low; commits: 30717de979b7; files: src/state/openclaw-state.worker.ts)

PR surface

Source +3, Tests +56, Docs +2. Total +61 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 3 0 +3
Tests 1 56 0 +56
Docs 1 5 3 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 64 3 +61

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +3 lines; tests +56 lines The growth is justified by one real-backend regression covering recovery, retained data, and non-replay.

Labels

Label changes:

  • add P2: This restores recovery for PostgreSQL shared-state users after connection loss, with limited scope and no demonstrated urgent regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This restores recovery for PostgreSQL shared-state users after connection loss, with limited scope and no demonstrated urgent regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 21, 2026, 2:32 AM ET / 06:32 UTC.

@steipete
steipete merged commit 90f0844 into main Oct 21, 2026
125 of 128 checks passed
@steipete
steipete deleted the pgprep/pgchaos-state-recovery branch October 21, 2026 08:17
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 22, 2026
…nclaw#179128)

Reject closed PostgreSQL handles in the primary shared-state and update-bookkeeping settlement owners so the existing worker retirement path can reopen a connection for a later operation. Do not replay interrupted writes; preserve SQLite closed-wrapper behavior.

Real Gateway fault replay recovers fresh turns after backend termination and fast restart without restarting the Gateway. Regressions are red before each owner correction and pass after it: 13 PostgreSQL state tests and 23 SQLite tests. All three PostgreSQL conformance shards passed on the final head.

Final CI retains the inherited root-tooling TS2345 failures at ci-changed-node-test-plan.test.ts:813,891, independently reproduced on clean main 99969d3. Security, lint, and other typechecks passed; landed under the authorized inherited-failure exception.
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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant