Skip to content

fix: recover lease heartbeats after a PostgreSQL connection loss - #201858

Merged
VACInc merged 2 commits into
openclaw:mainfrom
VACInc:fix/postgres-heartbeat-reconnect
Nov 20, 2026
Merged

VACInc merged 2 commits into
openclaw:mainfrom
VACInc:fix/postgres-heartbeat-reconnect

Conversation

@VACInc

@VACInc VACInc commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

A dropped connection during a state-lease heartbeat can stop renewal permanently, including the Gateway owner's diagnostic heartbeat. Reopen the failed connection and retry the heartbeat once, while keeping the existing owner and expiry checks.

What Problem This Solves

Idle connections already reconnect. A connection lost during the renewal transaction instead leaves the shared heartbeat handle closed and causes every due lease to report loss. In-flight maintenance can abort, and the Gateway owner's heartbeat stays stopped until restart.

User Impact

A transient disconnect during renewal can recover without aborting healthy leased work. Replaced or expired leases still lose ownership. A failed reconnect or second failure still takes the existing loss path. No configuration, schema, or migration change is needed.

Root Cause

PostgresSyncConnection marks the handle closed after an in-flight connection failure. The heartbeat carrier retained that handle, and its scheduler captured the original connection permanently. Renewal errors therefore reached all due registrations as terminal errors.

The regression locks the disposable store's lease table, waits for the actual renewal backend to block, and terminates that backend. On base 3587df70a233dc639b733b9169797d3abd138301, the recovery assertion fails: the assertion that both persisted heartbeat timestamps advance fails.

Why This Change Was Made

Keep one shared connection owner and scheduler. Retire the failed connection, reopen through the existing physical-identity admission, and repeat only heartbeat reads or conditional renewals. The scheduler reads the current handle for each attempt. Completion runs after the first registration's database exchange ends, so a lost registration cannot strand a sibling behind its closed admission port.

Real behavior proof

RAN on Linux with a disposable PostgreSQL 18.7 UTF8 database over a Unix socket. The carrier uses real worker threads and database connections. With the database conformance preload pointed at that database:

pnpm test src/state/openclaw-state-lease-heartbeat.test.ts src/state/openclaw-state-lease-renewal.worker.test.ts --maxWorkers=1
Test Files  2 passed (2)
     Tests  21 passed (21)

After terminating the blocked renewal backend, both persisted heartbeat timestamps advance, no loss callback fires, and explicit verification and renewal succeed. A second case changes one owner and expires the other row during the disconnect. Both report the correct loss reason, preserve the changed rows, and shut down cleanly.

The two added cases used 1.36 seconds of test time. The two-file invocation used 56.66 seconds in Vitest and 114.45 seconds including worker preparation. The existing heartbeat suite includes real worker startup, contention, and blocked-parent lifetime cases, which account for its longer runtime.

A foreground Gateway also passed using separate HOME/state/config, claimed loopback ports, the repository's mock-model configuration helper, and a disposable database:

pnpm openclaw gateway run --allow-unconfigured --bind loopback --port <claimed-port>

After its first committed owner renewal, the owner was the only lease. The fixture locked that lease table, terminated the blocked renewal backend, then released the lock:

RAN foreground Gateway health: HTTP 200
RAN owner carrier initial renewal committed; owner is the only lease
RAN blocked owner-heartbeat backend terminated; heartbeat_at advanced; same foreground Gateway stays healthy; no owner-heartbeat-stopped warning

An initial foreground fixture failed setup: its temporary home was group-writable, and table locking began before cold carrier admission finished. The successful run used a private home and waited for the first committed renewal. Both disposable servers were stopped and their data directories removed.

The first CI head introduced an extra test file that exceeded the scheduled-main compact capacity: base planned 77 compact jobs, the first head planned 78. Keep the regression in the existing heartbeat suite and explicitly include that suite in database conformance selection. The unchanged capacity gate now passes all four cases locally. The conformance CLI lists the suite, and all ten conformance-planner tests pass. No capacity limit was raised. Hosted heartbeat cases reported 57.616 seconds in total; the two new cases used 2.199 seconds. Both ran successfully in database conformance CI.

Evidence

  • RAN: red-on-base recovery regression, then green through the real heartbeat carrier and database.
  • RAN: focused typecheck with the owning test shard's ambient declarations, targeted lint, format, and git diff --check.
  • RAN: simplification and a separate author readiness pass. The existing map owns reconnection; no new manager or lease policy. Production delta: +67/-39 lines. Test delta: +132/-2 lines, plus one conformance target and five documentation lines.
  • RAN: healthy explicit-renewal benchmark, same database and source runner, 20 warmups then three batches of 100 calls per version. Base batch medians: 1.42/1.03/1.28 ms; fixed: 1.53/1.10/1.16 ms. Base p95: 3.03/1.64/2.42 ms; fixed: 3.51/1.93/1.93 ms. These noisy local measurements do not establish zero overhead.
  • Local autoreview was attempted for the complete change, P0-P2. Its isolation preflight refused the configured CLI launcher before a reviewer started. No review result was produced. The required hosted fallback review subsequently completed on 3dd9b0e276082a7fb1417f96f95d5684b68d9c76 with no findings and a ready-for-maintainer-review result.

What was not tested

  • Real model turns or live channels. Foreground Gateway proof covers the owner-heartbeat diagnostic path with mock-model configuration. The runtime production files are unchanged by the later test-layout and CI-selection repair.
  • Paid model APIs were not called.
  • A prolonged server outage, repeated failure of the replacement connection, or loss of a COMMIT reply. The retry is limited to conditional heartbeat work; general operation replay and outcome-unknown policy are unchanged.
  • No stable-version upgrade test: this change does not change stored formats or migrations.

Verification

  • Recovery regression fails on the base for the intended behavior.
  • Real database recovery and ownership-loss controls pass.
  • Existing heartbeat and scheduler tests pass.
  • Focused types, lint, format, and whitespace checks pass.
  • Exact-head CI, security checks, and hosted independent review passed. All applicable checks passed; other checks were skipped by normal scope rules. No check was waived.

@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:46
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: M labels Nov 19, 2026
@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. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment 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

Reconnect a failed PostgreSQL lease-heartbeat connection and retry once while preserving ownership and expiry checks.

Example: PostgreSQL terminates the renewal backend for two active 30-second leases.

  • Before: Both leases report loss and stop renewing despite otherwise healthy ownership.
  • After: The shared carrier reconnects and advances both heartbeats; replaced or expired leases still report loss.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful repair with relevant production-path proof, distinct regression controls, and no identified correctness or security defect.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): Public terminal output records a foreground Linux Gateway recovering its owner heartbeat after termination of the blocked PostgreSQL backend; real worker/database regressions additionally verify sibling recovery and correct ownership loss, with production files unchanged by the latest test-layout repair.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A transient PostgreSQL disconnect can abort healthy leased work and leave the Gateway owner heartbeat stopped until restart.
Reason: The maintainer-authored direction restores recovery within the existing lease contract without new configuration or broader operation replay.

Merge readiness

✅ Ready for maintainer review

This PR fixes a current PostgreSQL heartbeat recovery defect. The earlier CI capacity blocker is resolved on the reviewed head, and no actionable code findings remain; other CI checks are still running.

Priority: P2
Reviewed head: 3dd9b0e276082a7fb1417f96f95d5684b68d9c76

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway ownership and maintenance leases register with a shared worker, which conditionally renews persisted lease rows and returns expiry or loss observations to their callers.

flowchart TD
  A[Gateway and maintenance callers] --> B[Shared heartbeat carrier]
  B --> C[Renewal scheduler]
  C --> D[Admitted PostgreSQL connection]
  D --> E[Persisted lease rows]
  D --> F[Reconnect and retry once]
  F --> E
  E --> B
Loading

Technical review

Best possible solution:

Keep reconnection in the existing shared heartbeat owner, refresh the scheduler’s connection, and preserve conditional owner-and-expiry renewal.

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

Current-main source retains a closed connection after an in-flight failure, and the author reports a matching red-on-base backend-termination reproduction; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch repairs the retained connection at its existing owner, updates all scheduler callers, and separates completion from the database exchange without introducing another manager or lease policy.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared heartbeat carrier and batched renewal keeps the original intent (6125c6b: Share native worker lifetime while retaining independent lease ownership, expiry, and cleanup; subsequent batching reduced idle wakeups.)
  • PostgreSQL heartbeat selection and admission keeps the original intent (6b36172: Carry the configured shared-state engine into lease workers without falling back to SQLite.)
  • Lazy PostgreSQL heartbeat loading keeps the original intent (c3b3d56: Reduce Gateway startup memory by keeping PostgreSQL implementation loading behind the selected-backend boundary.)
  • Connection-loss replay guidance changes intended behavior with a stated reason (90f0844: Reopen failed shared-state workers for subsequent operations without transparently replaying interrupted external effects.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit e0bb91e adds src/state/openclaw-state-lease-heartbeat.worker.ts:103 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e0bb91e15429; files: src/state/openclaw-state-lease-heartbeat.worker.ts)
  • Vincent Koc: Raw commit c3b3d56 adds src/state/openclaw-state-lease-heartbeat.worker.ts:496 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c3b3d56c37c9; files: src/state/openclaw-state-lease-heartbeat.worker.ts)

PR surface

Source +28, Tests +130, Docs +5, Other +1. Total +164 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 67 39 +28
Tests 2 132 2 +130
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 6 205 41 +164

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 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.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: A transient PostgreSQL connection failure can unnecessarily abort leased maintenance and permanently stop the Gateway owner’s diagnostic heartbeat.
  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-19T14:04:23.788Z sha 94c687a :: blocked before merge. :: none

Reviewed November 19, 2026, 9:13 AM ET / 14:13 UTC (Revision 2).

@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Nov 19, 2026
@VACInc

VACInc commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels Nov 19, 2026
@VACInc
VACInc merged commit cc849dd into openclaw:main Nov 20, 2026
154 of 155 checks passed
@VACInc

VACInc commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Merged via squash.

@VACInc
VACInc deleted the fix/postgres-heartbeat-reconnect branch November 20, 2026 16:27
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…nclaw#201858)

* fix: recover lease heartbeats after a PostgreSQL connection loss

* test: keep heartbeat recovery within existing CI capacity

---------

Co-authored-by: VACInc <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
…1858)

* fix: recover lease heartbeats after a PostgreSQL connection loss

* test: keep heartbeat recovery within existing CI capacity

---------

Co-authored-by: VACInc <[email protected]>
(cherry picked from commit cc849dd)

Gap-sweep intake (Dallin, 2026-11-24): ledger-high/P0-P1 fix not yet on 2026.11.10. Clean apply. Later main mentions of #201858: none.

Co-authored-by: RomneyDa <[email protected]>
maplel pushed a commit to maplel/openclaw that referenced this pull request Nov 24, 2026
…law#194384)

* docs: clarify PostgreSQL conformance coverage

* fix(cron): keep one-shot finalization working on PostgreSQL 16

* test(database): reuse cron conformance for JSON conversion regression

* test(postgres): accept fractional explain row counts

(cherry picked from commit 7ab0143)

Release adaptation: Only engine-owned jsonValue and retained cron enabled JSON replacement; preserve native boolean type with PG16 explicit ::json and SQLite json(). Omit unrelated PG docs/EXPLAIN test edits; retained one-shot enabled-transition caller present on baseline.

Follow-up dispositions: e029e18 docs: document isolated PostgreSQL restore drills (openclaw#202704); 49f0740 fix(database): report disabled memory after a port (openclaw#202630); a80b564 fix: keep database workers healthy after silent connection loss (openclaw#201856); 3d91af2 fix(config): reject reserved PostgreSQL schema prefixes (openclaw#202097); 835d722 fix: catch incompatible ownership before porting to SQLite (openclaw#202101); 67796a6 fix: keep scheduled Git backups current on PostgreSQL (openclaw#201870); cc849dd fix: recover lease heartbeats after a PostgreSQL connection loss (openclaw#201858); 6594caf fix: prepare macOS runtime pins without the PostgreSQL secret (openclaw#202102); 6ca56cd docs: clarify PostgreSQL storage and backup coverage (openclaw#202086); a079190 fix(postgres): chat history slows under concurrent reads (openclaw#190129); 2ff4256 feat(database): keep PostgreSQL rollback captures in PostgreSQL (openclaw#196236); 96c685b feat(backup): restore PostgreSQL stores into a staging database for restore drills (openclaw#194808); fb83d65 fix: reduce transcript allocation when preparing native context seeds; 71ec4d2 fix(config): keep Workboard PostgreSQL upgrades readable (openclaw#194648); b6ed907 perf(sessions): persist active transcript facts for hydration (openclaw#193682)

Validation: Baseline cron generated json(bound text) on PostgreSQL where json(text) is unavailable; helper and focused boolean regression retained. Exact PostgreSQL16 server proof unavailable; focused SQLite/helper tests queued. diff check passed.

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 38fdd9b52704d588d9ca24ef8e391d644961c985)
(cherry picked from commit fb935e6912388314851b05cb698ef038b83bbd07)
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: M 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