Skip to content

fix: keep database workers healthy after silent connection loss - #201856

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

VACInc merged 2 commits into
openclaw:mainfrom
VACInc:fix/postgres-silent-connections

Conversation

@VACInc

@VACInc VACInc commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

A silent database connection could block a worker for two minutes and then reset healthy connections on the same I/O service. Enable TCP keepalive and retire the silent connection before the host watchdog fires, so ordinary transport loss fails only the affected connection. The worker's cutoff now follows the deadline the host sends with each request, so longer maintenance requests from #201869 are not cut at the ordinary 100 seconds. Idle validation can reconnect before caller SQL; a lost commit reply remains uncertain and is never replayed.

  • Bridge data clients enable TCP keepalive (10-second initial delay).
  • Each bridge request carries deadlineMs, the time left before the host resets the I/O service. For query and recovery-generation requests, the worker ends that request's client 20 seconds before the deadline. With runtime defaults: deadline 120 s, cutoff 100 s, server statement timeout 90 s (unchanged).
  • Connection setup and idle validation queries keep separate 10-second client bounds.
  • One internal worker-message field. No public API, config, schema, stored-data, or dependency change.

Root Cause

The data bridge configured a connection timeout and server statement timeout, but no client query timeout or TCP keepalive. A server timeout cannot deliver an error through a black-holed return path. The host's 120-second watchdog therefore became the first effective bound and retired the entire assigned service.

The regression reaches the real synchronous connection through a socket proxy. It forwards a transaction's COMMIT to a disposable server and discards the reply. On the base, the call took 120001 ms, failing the under-20-second assertion.

The first revision of this PR fixed that with a fixed client query_timeout of statement timeout + 10 s. That bound is set once per connection and cannot see a longer request budget. #201869 gives maintenance transactions (migrations, search rebuilds, search-extension admission) a one-hour transaction-local statement timeout and a one-hour-plus-30-second host deadline. Combined with the fixed client bound, every maintenance statement over the ordinary cutoff would be killed on the client. On a scratch merge of the two earlier heads, a maintenance pg_sleep(12) on a connection with a 1-second runtime statement budget failed after 11078 ms with PostgreSQL connection lost; transaction rolled back.

This revision makes the host the single owner of the request budget. The host deadline is now the connection's statement timeout plus 30 seconds (still 120 s in production, where the statement timeout is always 90 s), it is sent with each request, and the worker's per-request timer ends the client 20 seconds early. Ending the client fails the pending query without an SQLSTATE, which the host already classifies as connection loss with the existing outcome-unknown rules.

Real behavior proof

RAN on Linux against a disposable PostgreSQL 17 server (loopback and Unix socket only), through node scripts/test-database-conformance.mjs --engine postgres --connection <disposable DSN> -- <files>.

This PR alone at the exact pushed head, src/infra/postgres-sync (all 11 files):

isolates a silent commit connection without replaying writes            11231ms
isolates a silent idle connection without replaying writes              10085ms
keeps a statement running until shortly before a longer request deadline 12034ms
Tests 42 passed (42) + 92 passed (92)
  • Silent commit and idle cases use a 1-second statement budget, so the host deadline is 31 s and the worker cutoff 11 s. The commit is outcome-unknown, written exactly once, and four peer connections keep their backend IDs (no service reset).
  • The new long-deadline case sends a 45-second request deadline and runs SELECT pg_sleep(12) under SET LOCAL statement_timeout = '1h'. With the previous worker it failed after 11067 ms (PostgreSQL connection lost; transaction rolled back); with this worker it returns after 12 s.

Combined with #201869 (local scratch merge, not pushed; the only conflict is the deadline line in connection.ts, resolved as below), src/infra/postgres-sync plus src/infra/database-engine:

lets maintenance statements outlive the runtime statement limit and client cutoff 12024ms
keeps a statement running until shortly before a longer request deadline          12019ms
isolates a silent commit connection without replaying writes                      11134ms
isolates a silent idle connection without replaying writes                        10066ms
restores runtime statement limits after maintenance commits and nested rollbacks    156ms

A second scratch merge against #201869's current head (which merged main for an unrelated conflict) passed src/infra/postgres-sync, the schema-admission, search-extension, search-conformance, search-admission and port-command PostgreSQL suites, and the memory search-rebuild suite: 45 + 160 + 2 passed, including the lost-commit-reply port case. The numbers above are from that run except the 156 ms admission case (first run).

The maintenance case is a real runTransaction(..., { maintenance: true }) on a connection with a 1-second runtime budget; it ran past the old 11-second cutoff, and SHOW statement_timeout returned 1s afterward. The combined database-engine run had 15 local failures, all environmental and rechecked: 14 from this host's group-writable temp directories (passed after rerunning with umask 022) and 1 lost-reply proxy case that needs a TCP listener (failed the same way on the base revision; passed on the combined branch once the disposable server listened on loopback).

Combined resolution of the deadline line:

const deadlineMs =
  (this.maintenance
    ? POSTGRES_MAINTENANCE_STATEMENT_TIMEOUT_MS
    : (this.bridgeParameters.statementTimeoutMs ?? POSTGRES_STATEMENT_TIMEOUT_MS)) + 30_000;

Landing order

Land this PR first. #201869 then needs main merged with the resolution above (code conflict only in that line and its import; docs merge cleanly). Either PR alone is safe: this one alone keeps production at 100 s / 120 s, and #201869 alone has no client cutoff.

What was not tested

  • Full Gateway/channel flows or paid model calls.
  • Real hardware suspension, kernel TCP keepalive timing, or a production failover.
  • The full default 100-second cutoff or a one-hour maintenance budget in wall time; the real-I/O regressions use the same calculation with a 1-second statement budget.
  • The accepted edge case where the cutoff fires during the brief window in which an idle reconnect has closed the old client but not yet created the new one; the reconnect happens at request start and the cutoff at least 10 s later, so the window is not reachable in practice. The host watchdog still covers it.
  • General throughput, full package/release builds, or upgrade migrations. No schema or stored-data changes.

Verification

  • Red-on-previous-head regression for the long deadline (11067 ms connection lost), then green; silent commit/idle regressions still green.
  • node scripts/run-tsgo.mjs -p tsconfig.core.json and -p test/tsconfig/tsconfig.core.test.infra.json: passed.
  • node scripts/run-oxlint.mjs on changed files, oxfmt --check, git diff --check: passed.
  • Unit suites connection.test.ts, protocol.test.ts, bridge-prestart.test.ts: passed (message expectations now include deadlineMs).
  • pr-simplify pass: no further reduction; the fixed client timeout was replaced, not layered. Production delta against the merge base: 43 added / 15 removed lines (this revision: 20 added / 5 removed).
  • Local autoreview (branch mode, P0 to P2) against base 3587df70a23: scoped-clean, no actionable findings.
  • Exact-head CI on 8430fc80d91: SUCCESS, including all four PostgreSQL conformance shards and the PostgreSQL 16 smoke.

@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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: S labels Nov 19, 2026
@VACInc
VACInc marked this pull request as ready for review November 19, 2026 13:45
@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 adds TCP keepalive and request-budget-aware connection cutoffs so silent PostgreSQL transport loss does not reset healthy peer connections.

Example: A proxy forwards COMMIT but silently discards its reply.

  • Before: The host waits 120 seconds, then resets the shared I/O service and its healthy connections.
  • After: With production defaults, the affected connection closes after 100 seconds; COMMIT remains outcome-unknown and is never replayed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Focused transport repair with relevant real-I/O fault proof, successful exact-head gates, and no actionable findings; full Gateway and production failover coverage are expressly unclaimed.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): Supplied terminal results exercise the production synchronous connection, real node-postgres transport, disposable PostgreSQL 17, and injected lost replies; they demonstrate isolated failure, no write replay, idle recovery, and longer-deadline success.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: One silent PostgreSQL connection can stall a database worker and cause healthy connections on its shared I/O service to fail.
Reason: The maintainer-authored direction addresses demonstrated transport failure with a focused change and preserves uncertain-write safety.

Merge readiness

✅ Ready for maintainer review

This PR addresses a real PostgreSQL failure boundary that remains on current main; the reviewed changes preserve uncertain-write handling, and no actionable correctness or security findings remain.

Priority: P2
Reviewed head: 8430fc80d91758c048cb3040b77aadf0bdd67fd2

Before merge

None.

Findings

None.

Agent review details

How this fits together

The synchronous PostgreSQL adapter sends database operations over message ports to four shared I/O workers, which execute them through node-postgres and return results or transport failures.

flowchart LR
  A[Database store owner] --> B[Synchronous connection]
  B --> C[Request with deadline]
  C --> D[Shared I O worker]
  D --> E[PostgreSQL client]
  E --> F[PostgreSQL server]
  D --> G[Connection result or failure]
  G --> B
Loading

Technical review

Best possible solution:

Land the connection-local cutoff through the existing bridge owner, then integrate the documented maintenance-budget resolution in #201869.

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

Source shows that a lost reply can reach the service-wide watchdog; supplied base-red and head-green transport traces corroborate the path, without reviewer execution.

Is this the best way to solve the issue?

The patch places the cutoff in the existing transport owner, derives its budget from the host, and preserves reconnect-before-SQL and no-replay boundaries without adding another recovery layer.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Shared-service watchdog and request deadline changes intended behavior with a stated reason (b378654: Sharing PostgreSQL I/O across four workers reduced resource use while retaining a bounded service-wide reset for wedged services.)
  • Idle validation and reconnect-before-caller-SQL keeps the original intent (d107cb8: Restore long-idle validation after a terminated-backend regression while preserving burst reuse and transaction exclusivity.)
  • Retained-idle recovery and uncertain writes keeps the original intent (ba9faf8: Recover the first operation after suspension only before caller SQL; transactions and uncertain writes must never be replayed.)
  • Connection setup and read-only initialization keeps the original intent (cf50d4a: Separate read-only standby connections and enforce read-only behavior without changing writer semantics.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main boundary: The pinned introduced diff adds connection-local cutoffs and bounded setup validation; current main retains the unbounded validation queries and service-wide host watchdog. (src/infra/postgres-sync/bridge.worker.ts:267, 8430fc80d917)
  • Supplied real transport proof: The PR body records Linux/PostgreSQL 17 runs through the production synchronous connection and real socket proxy: lost COMMIT replies remain outcome-unknown, writes occur once, four peers retain backend IDs, idle validation reconnects, and a longer request deadline permits a 12-second statement. (src/infra/postgres-sync/blackhole.postgres.test.ts:14, 8430fc80d917)
  • Exact-head merge gates: GitHub reports the reviewed head mergeable and clean; dependency review, security-sensitive review, and the effective CI gate are successful. (8430fc80d917)
  • Related maintenance work: fix: let large PostgreSQL maintenance operations finish #201869 owns longer maintenance budgets; both PR bodies document successful combined transport runs and the deadline-line resolution, with this PR landing first. (src/infra/postgres-sync/connection.ts:189, 8430fc80d917)
  • Pinned transport dependency contract: The bridge imports pg 8.23.1, making its shutdown contract relevant: Client.end destroys the socket when a non-pipelined query remains active, while query_timeout rejects bounded validation requests. (packages/pg/lib/client.js:799, 0980cefebe0a)
  • Policy and history review: Read root and applicable docs instructions, applied the simplification and test-value guidance, and found no maintainer-notes directory; feature history covers the original bridge, shared pool, idle validation, and retained-idle recovery, with traversal beyond creation limited by an unavailable historical object. (AGENTS.md:1, 8430fc80d917)

Likely related people:

  • Peter Steinberger: Raw commit f3009a5 adds src/infra/postgres-sync/bridge.worker.ts:164 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f3009a56907e; files: src/infra/postgres-sync/bridge.worker.ts)
  • Mitchell Etzel: Raw commit f7d9d71 adds src/infra/postgres-sync/bridge.worker.ts:99 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: f7d9d711f86d; files: src/infra/postgres-sync/bridge.worker.ts)

PR surface

Source +28, Tests +172, Docs +9. Total +209 across 7 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 43 15 +28
Tests 3 173 1 +172
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 225 16 +209

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:

No label changes.

Label justifications:

  • P2: Silent PostgreSQL transport loss can disrupt healthy connections sharing an I/O service, with impact limited to affected PostgreSQL deployments.
  • 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:10:06.626Z sha 303dccb :: needs maintainer review before merge. :: none

Reviewed November 20, 2026, 1:17 PM ET / 18:17 UTC (Revision 2).

@VACInc

VACInc commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@VACInc
VACInc merged commit a80b564 into openclaw:main Nov 20, 2026
156 checks passed
@VACInc

VACInc commented Nov 20, 2026

Copy link
Copy Markdown
Member Author

Merged via squash.

@VACInc
VACInc deleted the fix/postgres-silent-connections branch November 20, 2026 19:42
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…claw#201856)

* fix: keep database workers healthy after silent connection loss

* fix: bound silent PostgreSQL requests by the host deadline

---------

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

Baseline adaptation: Keep one worker per connection; bound startup and transport failure without adding shared services, idle borrowing, or write replay. Preserve existing outcome-unknown classification.

(cherry picked from commit a80b564)

Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit a9832c21d032063a55ff697d959448233683f3b3)
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. 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