Skip to content

fix: keep PostgreSQL leases alive during lock contention - #201853

Merged
VACInc merged 1 commit into
openclaw:mainfrom
VACInc:fix/postgres-contention-errors
Nov 20, 2026
Merged

VACInc merged 1 commit into
openclaw:mainfrom
VACInc:fix/postgres-contention-errors

Conversation

@VACInc

@VACInc VACInc commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

A PostgreSQL lock timeout can stop a healthy lease heartbeat while its stored lease is still valid. Translate lock, deadlock, and serialization errors into the adapter's existing BUSY error shape so lease and transaction owners use their contention handling.

Root Cause

decodePostgresError translates constraint failures but leaves SQLSTATEs 55P03, 40P01, and 40001 unclassified. Existing contention handlers recognize SQLite BUSY/LOCKED result codes. Consequently, the heartbeat reports operation-error and loses ownership; lease cleanup does not schedule its retry.

The change is confined to the PostgreSQL decoder. It retains the server error and SQLSTATE in cause, consistent with constraint translation. Cancellation (57014), connection-loss handling, persisted expiry checks, and timeout settings are unchanged. This adds no retry loop or transaction replay inside the adapter.

Real behavior proof

RAN on Node 26.13.1 and a disposable PostgreSQL 18 server with a private Unix socket:

  • On the base, all three SQLSTATE regression cases fail. The real adapter plus lease cleanup owner also fails: after a lock timeout and lock release, the retained row remains instead of being deleted.
  • With this change, the cleanup retry deletes the retained row. The failed transaction has rolled back and its connection remains usable. This regression uses a 10 ms server lock timeout and advances only the cleanup timer.
  • A separate real withOpenClawStateLease run uses a worker heartbeat, a 210-second lease, and the default 60-second server lock timeout. Hold the store advisory lock before its first scheduled renewal, wait 132 seconds, then release it. Before: lease aborted after contention: true, with OPENCLAW_STATE_LEASE_LOST and SQLSTATE 55P03. After: lease aborted after contention: false; automatic renewal advances the persisted expiry after lock release, and ownership verification succeeds.

Focused command, with the repository database-conformance preload selecting the disposable connection:

node scripts/run-vitest.mjs src/infra/postgres-sync/protocol.test.ts src/infra/postgres-sync/contention.postgres.test.ts src/infra/postgres-sync/connection.test.ts src/state/openclaw-state-worker-error.test.ts --maxWorkers=1

Result: 121 tests passed across four files. New integration test body: 109 ms; protocol suite: 187 ms. Full invocation: 95.19 s, including 75.55 s of cold worker-artifact preparation.

A decoder/classifier benchmark used 1,000 warmup errors, then five samples of 10,000 errors each, on the same machine. Median lock-error handling was 1.34 microseconds before and 3.24 microseconds after. This measures the extra error wrapper, not healthy transaction throughput.

What was not tested

  • Actual two-writer deadlock or serialization-abort scenarios. Their SQLSTATEs are covered by the decoder regression table.
  • A full Gateway/channel flow, paid models, production state, or other operating systems. The runtime proof exercises the real lease and heartbeat worker directly.
  • Healthy transaction throughput. Existing 60-second lock waits and per-operation busy-timeout propagation are outside this change.
  • Independent maintainer review remains required before merge.

Verification

  • RAN: red-on-base and green-after-fix regressions; PostgreSQL rollback, connection reuse, and lease cleanup; real worker heartbeat before and after a 60-second lock timeout.
  • RAN: focused connection and worker-error transport suites; targeted TypeScript checking of the three touched files using the repository test-shard compiler options; targeted oxlint; oxfmt and git diff --check.
  • Simplification pass: eight production lines in the existing decoder; no new owner, state, retry mechanism, schema, or public option.

Evidence

RAN: local autoreview of the complete three-file change against 3587df70a233dc639b733b9169797d3abd138301, including the untracked regression before commit. P0-P2 coverage; scoped-clean, no actionable findings. The unchanged reviewed snapshot is committed as 7045cdfafdabd9b7248d45bf0ad40e790cc1d09a. Local ClawSweeper was unavailable. The hosted review completed on the same head with no findings: #201853 (comment)

Exact-head CI completed successfully, including all five PostgreSQL conformance jobs: https://github.com/openclaw/openclaw/actions/runs/44535887329

Final check snapshot: 68 passing checks, 67 skipped, none pending or failed; openclaw/ci-gate passed. Independent maintainer review is still required before merge. No merge or auto-merge was requested.

@clawsweeper

clawsweeper Bot commented Nov 19, 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.

@VACInc
VACInc marked this pull request as ready for review November 19, 2026 13:40
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 19, 2026
@clawsweeper

clawsweeper Bot commented Nov 19, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR classifies PostgreSQL lock, deadlock, and serialization failures as BUSY errors so existing contention handlers can recover.

Example: A 210-second PostgreSQL-backed lease encounters the default 60-second lock timeout during renewal.

  • Before: SQLSTATE 55P03 causes operation-error and aborts the lease despite its valid stored expiry.
  • After: The heartbeat checks the stored expiry, retries contention, and renews after the lock is released.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A small, correct owner-level repair supported by real PostgreSQL fault recovery and distinct regressions; supplied exact-head conformance checks remain pending.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied Node 26/PostgreSQL 18 evidence exercises the real lease heartbeat worker across an actual server lock timeout and reports continued ownership plus renewed persisted expiry after release; the real-adapter cleanup regression independently verifies rollback and recovery.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Healthy PostgreSQL-backed work can lose its lease after transient lock contention even though the stored lease remains valid.
Reason: The maintainer-authored direction restores existing contention behavior through the shared adapter without changing configuration, timeouts, or ownership rules.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR repairs a current PostgreSQL contention-classification bug with a focused change and meaningful regression coverage; no actionable patch defect was found.

Priority: P2
Reviewed head: 7045cdfafdabd9b7248d45bf0ad40e790cc1d09a

Before merge

None.

Findings

None.

Agent review details

How this fits together

The PostgreSQL adapter translates server errors into the shared SQL contract consumed by transaction, heartbeat, and cleanup owners.

flowchart TD
  A[Lease operation] --> B[PostgreSQL transaction owner]
  B --> C[PostgreSQL server]
  C --> D[Error decoder]
  D --> E[Shared BUSY classification]
  E --> F[Existing lease contention handling]
Loading

Technical review

Best possible solution:

Retain the narrow decoder mapping and let the existing transaction and lease owners handle rollback, expiry checks, and retries.

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

The decoder and heartbeat source establish the failure path, corroborated by the author's real PostgreSQL before-and-after worker run; this review executed no target code.

Is this the best way to solve the issue?

The patch fixes classification at its existing producer, preserves SQLSTATE diagnostics, and introduces no competing retry owner or transaction replay.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • PostgreSQL error translation keeps the original intent (5e78ec6: The original adapter translated PostgreSQL constraints into the shared SQLite-shaped contract while retaining server diagnostics as cause.)
  • Cancellation and connection-loss semantics keeps the original intent (697b23a: Preserve native cancellation provenance and uncertain-write handling without replaying operations.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5e78ec6 adds src/infra/postgres-sync/protocol.ts:165 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5e78ec6881c2; files: src/infra/postgres-sync/protocol.ts)

PR surface

Source +8, Tests +76. Total +84 across 3 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 1 8 0 +8
Tests 2 76 0 +76
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 84 0 +84

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P2: Transient contention can incorrectly abort PostgreSQL-backed lease work, with a limited blast radius confined to that database engine.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit 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: Transient contention can incorrectly abort PostgreSQL-backed lease work, with a limited blast radius confined to that database engine.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 November 19, 2026, 8:56 AM ET / 13:56 UTC.

@VACInc
VACInc merged commit db7d0db into openclaw:main Nov 20, 2026
225 checks passed
@VACInc

VACInc commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Merged via squash.

@VACInc
VACInc deleted the fix/postgres-contention-errors branch November 20, 2026 16:26
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
Co-authored-by: VACInc <[email protected]>
(cherry picked from commit db7d0db)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a5597470207a37e1c934f3a627988201824ec992)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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