Repository navigation
fix: recover lease heartbeats after a PostgreSQL connection loss - #201858
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesReconnect 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.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway 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
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +28, Tests +130, Docs +5, Other +1. Total +164 across 6 files. Added test files: 0. View PR surface stats
Preflight sourceSource unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified. LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (1 earlier review cycle)
Reviewed November 19, 2026, 9:13 AM ET / 14:13 UTC (Revision 2). |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…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]>
…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]>
…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)
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
PostgresSyncConnectionmarks 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=1After 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:
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:
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
git diff --check.3dd9b0e276082a7fb1417f96f95d5684b68d9c76with no findings and a ready-for-maintainer-review result.What was not tested
Verification