Skip to content

feat(database): hold Gateway state ownership in PostgreSQL on all-PostgreSQL installs - #196237

Merged
vincentkoc merged 13 commits into
openclaw:mainfrom
etzelm:feat/postgres-install-registry
Nov 13, 2026
Merged

vincentkoc merged 13 commits into
openclaw:mainfrom
etzelm:feat/postgres-install-registry

Conversation

@etzelm

@etzelm etzelm commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Part of #196156

Related: #196154, #196155, #196157

This is the ownership half of #196156 (item 2). Store identity (item 1) is not in this PR; see "Store identity: what blocks it" below.

What Problem This Solves

On an all-PostgreSQL install, Gateway state ownership is still a local lock file keyed by state/openclaw.sqlite. It only excludes processes that see the same state directory on the same host, and its refusals name a SQLite file that holds no application data.

User Impact

Operators can set database.postgres.ownership: "installation". It is opt-in and accepted only when database.engine is postgres and no family overrides to sqlite. The default, "state-directory", keeps today's local lock file. The setting only changes Gateway state ownership. Store anchors, client/credentials.sqlite, control/services.sqlite, the local lock files and the journals stay local.

  • A second Gateway, maintenance owner, or offline CLI owner (such as openclaw config set with no Gateway on its own state directory) with the same database and schema prefix is refused on any host. The refusal names the schema prefix and the holder's PID, host and PostgreSQL backend PID. A waiting Gateway logs the holder once.
  • If the owner's PostgreSQL session ends (crash, terminated backend, network loss) or a heartbeat fails, the running Gateway retires its state ownership at once. New and queued state work is refused, and the Gateway closes. PostgreSQL releases the lock, and the next Gateway can start.
  • On a silent network failure the Gateway finds out from the next heartbeat, within about 20 s (10 s interval plus 10 s query timeout). The docs ask operators to keep server-side dead-connection settings above that, so PostgreSQL cannot release the lock while the former Gateway still admits work.
  • A successor on another state directory starts on its own stores, because store identity is still the local anchor. It does not take over the former Gateway's data until store identity moves (see below).
  • Connection startup and every owner query time out after 10 s, so an unresponsive server cannot hang startup.
  • Nothing new is stored: no file, no schema, no table. The database and database.postgres.schemaPrefix name the installation, so the runtime role needs no new privilege.
  • The owner connection must be direct or go through a session-mode pooler. Session advisory locks do not work through PgBouncer in transaction mode.
  • The default and mixed installs behave exactly as before: no PostgreSQL lock, unchanged messages.
  • Downgrade: releases without this setting validate database.postgres strictly (2026.11.3 does), so remove ownership before rolling back to one. Installs that never set it are unaffected.

Why This Change Was Made

  • acquireGatewayLock also takes a session-level pg_try_advisory_lock on one dedicated pg connection outside the pool. The key is a hash of the schema prefix with its own namespace, so it never collides with the per-store writer locks. Advisory locks are per database, so the database and prefix together scope it.
  • CLI owners that resolve the configured engine only after taking the lock (runWithLocalStateOwner with databaseEngine: "configured", as openclaw config set does) take the PostgreSQL lock through the same handle once that selection is in scope, before the command reads or writes any state. Contention is refused like any other offline owner refusal. Its loss retires the same process owner. A cold config-only repair (databaseAccess: "none") skips this call and touches no database. Database port maintenance and recovery owners go through the same call; only the configured path has its own test.
  • Losing that session aborts a custody signal passed to acquireGatewayStateOwner. That retires the existing process owner, which is the one owner that admission (captureStateDatabaseAccess), queued workers and the server lifecycle (captureGatewayStateOwner(...).signal in server.ts) already observe. There is no parallel loss flag.
  • The PostgreSQL session lives exactly as long as the process owner's physical custody. When uncertain child cleanup keeps a borrowed lease after the lock is released (runWithLocalStateOwner on CommandProcessCleanupError), the session stays open until that lease ends, so no successor can start under live child work. The owner ends it through a release hook (onReleased in acquireGatewayStateOwner).
  • The holder is read from pg_locks and pg_stat_activity. The owner session sets application_name to openclaw-gateway-owner:<pid>:<host>, so there is no diagnostic row to go stale or to fail on release.
  • Release never rejects: it ends the session (bounded by the same 10 s), which releases the lock, so local custody is always released after it.
  • Contention reuses GatewayStateOwnerContentionError, so the existing wait and retry behavior applies unchanged.
  • The existing local file owner stays in place. It still provides in-process custody for SQLite handles; the PostgreSQL lock adds cross-host exclusion on top of it.
  • The setting lives under database.postgres and is named for what it changes (the scope of Gateway ownership), not for a later state with no local files. Earlier revisions of this PR called it database.localStores: "none"; that name was never released.

How this lock relates to the state_leases gateway-owner lease

Both exist with ownership: "installation", and they cover different scopes:

  • The advisory lock is per installation and is taken first, inside the ownership acquisition loop. A Gateway that cannot get it never reaches the lease.
  • The state_leases gateway-owner row lives in the state store's namespace, which is still per state directory because the state anchor is local. It carries the listener facts (port, mode, supervisor) used for restart and update handoff.

When PostgreSQL ends the owner session, the client is told at once and retires the owner. In the recorded run below that took about 0.1 s, before the successor acquired. On a silent network failure the client finds out within about 20 s, and PostgreSQL holds the lock until it ends the session itself. With server-side dead-connection settings above 20 s, the former Gateway stops before the lock is free.

From the code, offline lease recovery (gateway-lock-recovery.ts) and the Windows task probe (schtasks-process.ts) still take only the local owner; this is not separately tested. They act on one state directory after its holder is gone, and they never admit Gateway work.

Decision recorded

Maintainer acceptance recorded on 2026-11-13: after the recommended design and its limits were presented, continuation was authorized. Proceed with the ownership-only phase as opt-in database.postgres.ownership: "installation". The default remains "state-directory"; existing local custody and normal authentication remain enforced. The lock-loss shutdown and silent-network detection limits below remain part of the accepted design. Required review and validation still apply.

Options considered:

  1. Accepted recommendation: approve as is. Opt-in, default unchanged, no new persisted state or privilege, and cross-host exclusion works now for all-PostgreSQL installs.
  2. Approve with a different name or place, for example a top-level database.ownership. The rename is mechanical: schema, one runtime field, tests and the guide.
  3. Defer until store identity can move too, so all of [Feature]: Keep store identity and Gateway state ownership in PostgreSQL on all-PostgreSQL installs, as a first step to no local SQLite files #196156 lands at once. That work is blocked on a file-independent admission identity (below) and would not change this contract.

Accepted limits:

  • Installation identity. The database plus database.postgres.schemaPrefix. Nothing new is persisted. Two installations in one database must use different prefixes, as they already must for their store schemas.
  • Local custody. The local lock files and process owner stay and keep their current role.
  • Pooling. The owner connection must be direct or through a session-mode pooler.
  • Disconnect. Session loss stops the Gateway. A silent network is noticed within about 20 s, so server-side dead-connection settings must stay above that.
  • Offline recovery. Offline lease recovery keeps using only the local owner.

Later, separate question: should the state_leases gateway-owner lease merge into, or defer to, the lock once store identity moves?

Store identity: what blocks it

Moving the state store's identity into a PostgreSQL registry and opening the store on an in-memory anchor fails. The reason matters for the shape decision: the anchor file does more than record identity.

  • The process-wide admission cache (sqlite-database-admission.ts) keys every store's admission facts on the anchor's file identity. An in-memory anchor gets no admission (Missing PostgreSQL state admission).
  • The client credential receipt in client/credentials.sqlite binds to the state anchor's path, device and inode (readClientCredentialFileIdentity).
  • Agent-store callers treat "anchor file exists" as "store exists" in roughly ten places.

So removing anchors first needs a non-file admission identity, and the credential binding has to move with or before the state anchor. Proposed order:

  1. This PR: ownership.
  2. A file-independent admission identity.
  3. The registry for state and agent identity, offline anchor retirement, and registry writes from database port and backup restore.
  4. The fixed-local stores (fix(update): PostgreSQL update spends minutes validating the candidate before refusing a Gateway it cannot stop #196157).

Evidence

Maintainer correction and integration evidence

Reviewed signed candidate: f3ca42b3820e4865f92f04ac3ae31b72bb8b9e42, natively integrated onto landed capture baseline 2ff4256ae377bd54a7014a640336cc466ff4af6b. Publication and exact-head required checks/review remain separate gates. The original evidence below describes earlier candidates.

  • Fixed two independently reviewed P1 defects at the dedicated PostgreSQL session owner: all three queries use authoritative per-query timeouts despite a longer DSN query_timeout; recorded connection loss is rejected immediately before ownership handoff. Normal auth/TLS, release, retained custody and the accepted default/opt-in design remain enforced.
  • Real PostgreSQL 17.11 / Node 26.12.1: parent negative control failed all four expected assertions; corrected owner passed 4/4 focused real-driver cases (silent acquisition, holder lookup, heartbeat, and actual lock-success plus FATAL before acquisition settled). No mock query result or production injection seam. Isolated fixture closed.
  • Native integration preserves both recoveryCaptures and ownership schema/type/resolution contracts, current final-request forwarding, direct custody-loss shutdown and final retained-lease release. Combined config cases assert both flags and reject installation ownership with a SQLite family even with server captures enabled.
  • Published-candidate static checks exposed inline satisfies excess-property errors at the pg.query overloads and fixture typing/lint errors. The bounded correction uses explicitly typed query locals, preserves all query objects and lifecycle ordering, and repairs only fixture type/block/diagnostic contracts. Focused native owner semantics plus SDK-config declaration emission, focused owner/fixture test-config semantics and targeted type-aware lint all exited zero. The corrected fixture was then run against observed PostgreSQL 17.11 again: 4/4 passed, conformance command exit zero; the isolated container was stopped and its removal verified. Independent exact-correction review found no remaining source issue.
  • Both focused config/schema Vitest per-file caches record failed: false. The aggregate exit receipt was lost to output truncation; no aggregate exit-zero claim. Required exact-head CI remains authoritative.
  • Canonical config:docs:gen and config:docs:check, targeted formatting, git diff --check and native test-line ratchet exited zero. Exact net test growth: 634 lines, recorded in the existing allocation. Integration adds no production lines. Dedicated-owner corrections add 15 net production lines in total (latest type correction: net +2), required for the dependency timeout, custody handoff and typed query contracts.
  • Full feature/P1 review and bounded actual integration review found no remaining source finding. Exact-head ClawSweeper review is clean. Hosted CI run 43407736121 attempt 2 passed with no source change. Its one diagnostic replay of cancelled shard checks-node-changed-compact-large-40-1 executed the same merge 781d8c1f818cbcb64301dcb4345b83907c4bfd61 (head f3ca42b3820e4865f92f04ac3ae31b72bb8b9e42, base 4aa0168e1f2a17608fa6dbb8d7d07a406794fd96) and passed all 37 files / 351 tests. Attempt 1 had real Gateway RPC/test timeouts before the 60-minute job cancellation. Investigation compared the actual tested trees, complete shard selection, pinned runtime and available runner/resource observations; no causal source defect was established. Root cause remains unknown; the replay is diagnostic evidence, not an inherited-failure or repair claim. Source/test proof only; no deployment or live Team-service claim.

Original candidate evidence (historical)

All runs used PostgreSQL 17.11 on macOS (arm64), Node 24.22.2, and a build of this branch. The scratch database had unaccent, pg_trgm and vector installed, as the operator guide requires. Hosts, paths and anchor IDs are redacted; timestamps are as logged. Both Gateways ran on one machine with separate state directories and ports, which is what a second host sees: a different state directory and the same database.

Upgrade from the latest stable release (2026.11.3). Stable ran on default SQLite storage with agents.defaults.timeoutSeconds: 321, and a cron job was added through its CLI:

d1fa9142-05ff-4569-b27b-40f89d415c0e -   upgrade-proof   every 1d   in 1d   -   idle   main ...

After stable stopped, the branch followed the documented path: openclaw doctor --fix (exit 0, "Doctor complete."), then openclaw database port --to postgres, which ported the state and agent stores and set database.engine to postgres. Then ownership: "installation" was added and the branch Gateway started on the same state directory:

== config database section
{"engine": "postgres", "postgres": {"connection": {"source": "env", "provider": "default", "id": "OPENCLAW_DATABASE_DSN"}, "schemaPrefix": "proof196237", "ownership": "installation"}}
Config valid: <root>/a/openclaw.json
== branch ready
== cron job written by 2026.11.3
d1fa9142-05ff-4569-b27b-40f89d415c0e -   upgrade-proof   every 1d   in 1d   -   idle   main ...
== setting written for 2026.11.3
321
== owner lock
openclaw-gateway-owner:78133:<host> backend=78169
== schemas
proof196237_agent_<id>
proof196237_state_<id>

The job and the setting are unchanged. The only schemas are the two the port created; enabling the setting created none.

Validation. With engine: "sqlite", openclaw config validate refuses the setting and exits 1:

- openclaw.json:2 - database.postgres.ownership: database.postgres.ownership "installation" requires database.engine postgres and no family overrides to sqlite., got: "installation"

Authority chain after session loss. Gateway A (port 19631) held ownership. Gateway B used its own state directory and port 19632 on the same database and prefix. A's owner backend was then terminated with pg_terminate_backend while A kept running.

== 20:17:16.911 owner lock:
openclaw-gateway-owner:78482:<host> backend=78518
== B log while A holds:
20:17:26.291 [gateway] state ownership is held in PostgreSQL schema prefix proof196237: Gateway pid 78482 on host <host> holds it (PostgreSQL backend 78518).
20:17:26.292 [gateway] waiting for Gateway state ownership held by another OpenClaw process, up to 300 s
== 20:17:26.677 pg_terminate_backend(78518) (A's owner session)
== A log after termination:
20:17:26.775 [state] PostgreSQL Gateway ownership was lost (terminating connection due to administrator command); state work is refused and the Gateway stops. Check the PostgreSQL connection, then restart the Gateway.
20:17:26.778 [admission] closed: restart-signal fence
20:17:26.786 [admission] closed: restart (SIGUSR2: Error: PostgreSQL Gateway ownership was lost ...)
20:17:26.876 [audit/events] audit event persistence failed: PostgreSQL Gateway ownership was lost ...
== 20:17:31.376 A exited
== B log after termination:
20:17:27.263 [gateway] state ownership acquired after 1.0 s
20:17:31.182 [gateway] ready
== owner after:
openclaw-gateway-owner:78726:<host> backend=78816

A logged the loss and closed admission about 0.1 s after the terminate, and its in-flight audit write was refused. B acquired 0.59 s after the terminate, after A had closed admission. A had exited 4.7 s after the terminate (no supervisor ran, so it stayed down). B's state directory is separate, so it started on its own stores.

Cold CLI owner. Gateway A held ownership. A fresh openclaw config set agents.defaults.timeoutSeconds 321 then ran with its own state directory (<root>/b) and the same database and prefix. It resolves its engine only after taking its local lock.

== cold CLI on <root>/b while A holds
Cannot admit config set for agents.defaults.timeoutSeconds in state root <root>/b/state: OpenClaw state database is busy at PostgreSQL schema prefix proof196237. Gateway pid 78482 on host <host> holds it (PostgreSQL backend 78518). ... No local mutation was attempted. ...
exit 1
== b agents config after refusal:
None
== (A terminated and B stopped as above) owner after B stopped: []
== same cold CLI on <root>/b with the lock free
Updated agents.defaults.timeoutSeconds. Change will apply without restarting the gateway.
exit 0
{'defaults': {'timeoutSeconds': 321}}
== owner sessions in PostgreSQL connection log order:
openclaw-gateway-owner:78482:
openclaw-gateway-owner:78695:
openclaw-gateway-owner:78726:
openclaw-gateway-owner:78976:

While A held the lock, the CLI was refused, named A, and wrote nothing. With the lock free, it opened its own owner session (78976) and wrote the setting. 78695 is the refused attempt and 78726 is Gateway B. The refusal text after "holds it" is the existing contention guidance; part of it speaks of "the same state directory", which does not fit a holder on another state directory.

Tests, run with scripts/test-database-conformance.mjs against PostgreSQL 17.11, src/infra/gateway-postgres-owner.postgres.test.ts, 7/7:

  • A second Gateway (separate state and lock directory, same database) is refused. The error names the schema prefix and the holder's pid and host, and not openclaw.sqlite. Releasing twice is safe, and the next Gateway then acquires.
  • Session loss: after pg_terminate_backend, the former Gateway's owner signal aborts. A process-owner handle captured before the loss (as queued work holds one) fails assertCurrent. captureGatewayStateOwner and new captureStateDatabaseAccess(...).prepareAccess() are refused. A successor acquires, and exactly one backend holds the lock.
  • Silent network: a TCP proxy stops forwarding both ways without closing. The next heartbeat times out and reports the loss (2.1 s with a 100 ms interval and 2 s bound).
  • A server that accepts TCP but never answers fails acquisition with a timeout, and the attempt's socket is closed (241 ms with a 200 ms bound).
  • Cold CLI: with no engine selection installed, runWithLocalStateOwner for another state directory reads ownership: "installation" from its config and is refused while a Gateway holds the lock. runLocal never runs. After the Gateway stops, the same CLI holds exactly one owner session during runLocal and none after it returns. Without the new call in local-state-owner.ts, this test fails (promise resolved "'ran'" instead of rejecting).
  • Retained lease: a lease borrowed before the lock is released (as uncertain child cleanup does) keeps the PostgreSQL session open. A second host is refused until the lease ends, and then acquires. With the lock releasing the session directly, as in an earlier revision of this PR, this test fails.
  • Default mode: two Gateways with separate state directories both acquire, and no lock is taken.
  • Without connectionTimeoutMillis, the silent-server test hangs until the 120 s test timeout. Without the loss-to-owner wiring in gateway-lock.ts, the session-loss test fails (expected false to be true on the aborted signal). Both checks ran against the 4-test revision of this file.

src/config/zod-schema.database.test.ts covers the setting: it is accepted with all families on PostgreSQL, "state-directory" is accepted anywhere, and it is refused without engine: "postgres", with a family on sqlite, or with an unknown value. Against the previous head (with database.localStores), the three accept cases fail (Tests 3 failed | 26 passed (29)); on this head it passes 29/29.

Gates. The PR diff was checked merged onto main 277e32c668a. main 2cfd5ceab3d was merged later; it changes none of this PR's files except the generated config baseline. The first group below was then re-run on this head.

Check Result
config:docs:check OK (baseline hash regenerated)
oxfmt --check (changed files), oxlint (changed files), pnpm tsgo:core clean
gateway-lock.test.ts, zod-schema.database.test.ts, schema.base.generated.test.ts, doc-baseline.test.ts, server-database-engine.test.ts, server.state-owner.test.ts, local-state-owner.test.ts, config-cli.test.ts, plugin-local-state-owner.test.ts 146/146
gateway-postgres-owner.postgres.test.ts on PostgreSQL 17.11 7/7
check:max-lines-ratchet, check:line-cap-ratchet, check:assertion-safety, check:database-worker-ratchet, check:database-dialect-ratchet, check:test-timeout-race-ratchet, check:test-mock-exports OK (on 277e32c668a)
check:test-lines-ratchet config/test-lines-allocations/196156-postgres-gateway-owner.txt covers this PR's exact net growth (+311). The ratchet still reports over by: 7 because main 277e32c668a is already 7 over on its own (net delta: 0. Tree is over the ceiling; this change does not add test lines.).

…none

- Add database.localStores ("anchors" default, "none"); config validation
  accepts "none" only when database.engine is postgres and no family
  overrides to sqlite. In this stage "none" only moves Gateway ownership.
- With "none", engine selection carries an installation UUID read from or
  created once in <stateDir>/postgres-install.json (0600, link() publish).
- acquireGatewayLock also takes a session-level pg_try_advisory_lock keyed
  by the installation UUID on one dedicated connection outside the pool
  (TCP keepalive, 10 s query timeout), and writes
  <schemaPrefix>_install.gateway_owner (pid, host, boot id, heartbeat).
- Contention reuses GatewayStateOwnerContentionError, names the install
  schema and the holder's pid, host and boot id, and is logged once per
  holder while a Gateway waits.
- Session end, a failed heartbeat or a query timeout marks ownership lost
  and closes the session, releasing the lock; later ownership checks fail.
- Default mode and mixed installs take no PostgreSQL lock and create no
  install schema.
- Docs: "Gateway ownership in PostgreSQL" in database-engines.md, including
  the session-mode pooler requirement; regenerated config baseline hashes.
- Test-lines allocation for the new PostgreSQL and config coverage.

Part of openclaw#196156
@clawsweeper

clawsweeper Bot commented Nov 9, 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 size: M labels Nov 9, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 9, 2026
@clawsweeper

clawsweeper Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Adds opt-in installation-wide PostgreSQL locking for Gateway and offline-command state ownership.

Example: Two Gateways use separate state directories and ports 19631 and 19632 with PostgreSQL schema prefix proof196237.

  • Before: Their separate local locks allow both to acquire state ownership.
  • After: With ownership set to installation, the second Gateway waits and identifies the PostgreSQL lock holder.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong behavior evidence and no remaining source findings; this intentionally delivers only the ownership portion of the linked feature.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): Supplied real Gateway and CLI traces exercise contention, session-loss retirement, successor acquisition, and cold configured ownership; stable-upgrade traces preserve settings and a cron job, while the exact-head correction records passing real-driver timeout and handoff regressions.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Feature · Worth it: Yes · Fix scope: Partial
User problem: Separate state directories cannot currently coordinate installation-wide Gateway ownership through PostgreSQL.
Reason: A maintainer accepted the ownership-only phase and its limits; the PR correctly avoids claiming completion of the broader store-identity request.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR delivers a useful, maintainer-approved ownership phase. The exact-head correction preserves runtime behavior, and no actionable source defect remains; required CI is pending.

Priority: P2
Reviewed head: f3ca42b3820e4865f92f04ac3ae31b72bb8b9e42

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway startup and offline CLI commands acquire process custody before state access; the new dedicated PostgreSQL session adds installation-wide exclusion and forwards session loss into existing admission and shutdown handling.

flowchart TD
  A[Gateway or offline CLI] --> B[Existing process owner]
  B --> C[Dedicated PostgreSQL session]
  C --> D[Installation advisory lock]
  C --> E[Custody loss signal]
  E --> B
  B --> F[State admission and Gateway lifecycle]
Loading

Technical review

Best possible solution:

Land the accepted ownership-only phase through the existing process owner while leaving store-identity migration to the linked feature issue.

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

Current main keys custody to the local state path, establishing the cross-directory exclusion gap; supplied Gateway traces demonstrate the new behavior without executing target code during this review.

Is this the best way to solve the issue?

The dedicated PostgreSQL session extends existing custody and retirement machinery without new persisted identity or competing admission state, matching the accepted bounded design.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Process custody and retained leases keeps the original intent (8b16e53: Remove redundant SQLite coordination while preserving startup, schema, and offline-maintenance ownership.)
  • Owner loss and admission retirement keeps the original intent (99fccf4: Preserve ownership across separate Docker PID namespaces and retire admission through the existing custody-loss path.)
  • Database family selection keeps the original intent (995a9ae: One immutable engine-selection owner carries effective family choices and shared PostgreSQL connection input.)
  • Installation ownership scope changes intended behavior with a stated reason (fix(database): isolate PostgreSQL installations sharing one database #173745: Separate PostgreSQL installations use distinct prefixes and local anchors, with multiple Gateways per installation unsupported.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Exact correction preserves query semantics: The previous-head comparison changes inline query literals into explicitly typed locals while retaining query text, values, timeouts, loss checks, and lifecycle ordering. (src/infra/gateway-postgres-owner.ts:24, f3ca42b3820e)
  • Existing owner receives custody loss: PostgreSQL custody loss invokes the existing process-owner retirement path; retained leases defer final session release until physical custody ends. (src/infra/gateway-state-owner.ts:367, f3ca42b3820e)
  • Cold CLI acquisition: Configured offline commands acquire PostgreSQL custody after engine selection and before running their stateful operation. (src/cli/local-state-owner.ts:383, f3ca42b3820e)
  • Accepted product direction and operational limits: The maintainer confirms the recorded acceptance at feat(database): hold Gateway state ownership in PostgreSQL on all-PostgreSQL installs #196237 (comment), including opt-in ownership, unchanged local custody, session-mode pooling, disconnect shutdown, and silent-network detection limits.
  • Live behavior and upgrade evidence: The full PR body supplies real Gateway contention and session-termination traces, cold CLI refusal and success, and upgrade from 2026.11.3 preserving timeoutSeconds 321 and an existing cron job; the exact-head correction records four passing real PostgreSQL driver regressions. (f3ca42b3820e)
  • Current main still uses local ownership: Current main lacks this PostgreSQL custody integration; its existing process-owner lifecycle remains the foundation this PR extends. (src/infra/gateway-state-owner.ts:150, de02a1f5749a)

Likely related people:

  • Peter Steinberger: Raw commit 99fccf4 adds src/infra/gateway-state-owner.ts:158 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 99fccf43358c; files: src/infra/gateway-state-owner.ts)
  • Mitchell Etzel: Raw commit 2ff4256 adds src/infra/database-engine/config.ts:66 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 2ff4256ae377; files: src/infra/database-engine/config.ts)

PR surface

Source +309, Tests +634, Docs +59, Generated 0, Other +2. Total +1004 across 17 files. Added test files: 3.

View PR surface stats
Area Files Added Removed Net
Source 8 309 0 +309
Tests 5 634 0 +634
Docs 1 59 0 +59
Config 0 0 0 0
Generated 2 3 3 0
Other 1 2 0 +2
Total 17 1007 3 +1004

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.

Review metrics

Metric Value Why it matters
Production versus test growth Production +309; tests and support +634 Growth implements the dedicated session lifecycle and distinct real-transport contention, timeout, loss, CLI, and retained-custody regressions.
New configuration 1 optional setting; existing default preserved database.postgres.ownership selects installation-wide locking; omission retains state-directory ownership.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A bounded operator improvement for opt-in all-PostgreSQL installations.
  • merge-risk: 🚨 compatibility: The accepted setting requires direct or session-mode connections, and older releases require removing it before downgrade.
  • merge-risk: 🚨 availability: The accepted design stops the Gateway on ownership-session loss and requires server dead-connection settings above the documented detection window.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • 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 (7 earlier review cycles)
  • reviewed 2026-11-09T20:43:30.898Z sha fad722a :: needs real behavior proof before merge. :: [P1] Propagate PostgreSQL custody loss into the existing process owner | [P2] Bound connection establishment for the ownership session | [P2] Release local custody even when PostgreSQL cleanup fails | [P2] Use the existing persistence owner for installation identity
  • reviewed 2026-11-10T00:32:45.887Z sha 4004cce :: blocked before merge. :: [P2] Acquire PostgreSQL custody after cold CLI engine selection
  • reviewed 2026-11-10T02:14:50.183Z sha a956156 :: blocked before merge. :: [P2] Retain PostgreSQL custody while uncertain child work retains the owner
  • reviewed 2026-11-10T02:20:48.474Z sha a956156 :: blocked before merge. :: [P2] Retain PostgreSQL custody while uncertain child work retains the owner
  • reviewed 2026-11-10T04:41:30.072Z sha ea58cd8 :: blocked before merge. :: none
  • reviewed 2026-11-11T05:51:58.724Z sha 70d604f :: ready, awaiting a maintainer decision. :: none
  • reviewed 2026-11-13T10:01:25.354Z sha 15ab254 :: needs maintainer review before merge. :: none

Reviewed November 13, 2026, 5:22 AM ET / 10:22 UTC (Revision 8).

- Heartbeat failure callback takes `unknown` (use-unknown-in-catch-callback-variable)
  and keeps the original error as the cause.
- Tests go through acquireConfiguredGatewayPostgresOwner, so the
  test-only exports acquireGatewayPostgresOwner and gatewayOwnerLockKey are
  no longer exported (production unused-export scan).
- Test-lines allocation updated to the exact net growth (+181).

Part of openclaw#196156
- PostgreSQL session loss aborts a custody signal that retires the process
  state owner, so admission, queued work and the server lifecycle all stop.
- Bound connection startup with connectionTimeoutMillis and every session
  close with the same 10 s; release never rejects, so local custody is
  always released.
- Stop the heartbeat after loss; a silent network is reported by the next
  heartbeat within about 20 s.
- Drop postgres-install.json and the install schema; the lock key is the
  schema prefix within the database, and the holder is read from pg_locks
  and pg_stat_activity.
@etzelm

etzelm commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 10, 2026
- A cold CLI owner resolves its configured engine after taking the lock, so
  the lock saw no PostgreSQL selection and skipped installation custody.
- The lock handle now takes PostgreSQL custody once the selection is in
  scope; runWithLocalStateOwner calls it before stateful work. Config-only
  repair keeps its offline boundary.
- Custody loss still retires the same process owner; a sibling helper keeps
  gateway-lock.ts under its line cap.
@etzelm

etzelm commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 11, 2026
@roboclaw-bot roboclaw-bot added the clawtributors PR from a clawtributor label Nov 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Nov 13, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

Please review exact head 15ab2540f60ba4999609693ad98c86d7ce5ba480. The existing decision section records maintainer acceptance of the bounded ownership phase. The correction/integration evidence section records the two owner repairs, real-driver negative/positive proof, actual landed capture integration, independent review and remaining exact-head CI gates. Normal auth and the accepted default/retention limits remain enforced.

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Nov 13, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on maintainer Only explicit maintainer approvals or decisions remain; merge is still blocked. labels Nov 13, 2026
@vincentkoc

Copy link
Copy Markdown
Member

@clawsweeper re-review

Please review exact changed head f3ca42b3820e4865f92f04ac3ae31b72bb8b9e42. The prior exact review found no source finding; required CI exposed a pg overload/fresh-literal typing regression and static errors in the new real-driver fixtures. The bounded correction uses explicitly typed query locals and mechanical fixture type/lint fixes, preserving all query values/timeouts, lifecycle ordering and regression assertions. Focused native semantic/declaration and type-aware lint checks passed; corrected fixture passed all four real PostgreSQL 17.11 cases again. The PR evidence section records these receipts and the accepted default/auth/retention limits. Final exact-head CI remains required.

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@vincentkoc
vincentkoc merged commit c886f82 into openclaw:main Nov 13, 2026
287 of 289 checks passed
@vincentkoc

Copy link
Copy Markdown
Member

Merged via squash.

roboclaw-bot added a commit that referenced this pull request Nov 13, 2026
Register both Gateway PostgreSQL ownership suites introduced by #196237 in the existing conformance inventory. Preserve the completeness guard and the separate snapshot/cache registration repair in #198118.

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
…tgreSQL installs (openclaw#196237)

* feat(database): hold Gateway ownership in PostgreSQL for localStores none

- Add database.localStores ("anchors" default, "none"); config validation
  accepts "none" only when database.engine is postgres and no family
  overrides to sqlite. In this stage "none" only moves Gateway ownership.
- With "none", engine selection carries an installation UUID read from or
  created once in <stateDir>/postgres-install.json (0600, link() publish).
- acquireGatewayLock also takes a session-level pg_try_advisory_lock keyed
  by the installation UUID on one dedicated connection outside the pool
  (TCP keepalive, 10 s query timeout), and writes
  <schemaPrefix>_install.gateway_owner (pid, host, boot id, heartbeat).
- Contention reuses GatewayStateOwnerContentionError, names the install
  schema and the holder's pid, host and boot id, and is logged once per
  holder while a Gateway waits.
- Session end, a failed heartbeat or a query timeout marks ownership lost
  and closes the session, releasing the lock; later ownership checks fail.
- Default mode and mixed installs take no PostgreSQL lock and create no
  install schema.
- Docs: "Gateway ownership in PostgreSQL" in database-engines.md, including
  the session-mode pooler requirement; regenerated config baseline hashes.
- Test-lines allocation for the new PostgreSQL and config coverage.

Part of openclaw#196156

* fix(database): type the owner heartbeat catch as unknown

- Heartbeat failure callback takes `unknown` (use-unknown-in-catch-callback-variable)
  and keeps the original error as the cause.
- Tests go through acquireConfiguredGatewayPostgresOwner, so the
  test-only exports acquireGatewayPostgresOwner and gatewayOwnerLockKey are
  no longer exported (production unused-export scan).
- Test-lines allocation updated to the exact net growth (+181).

Part of openclaw#196156

* fix(database): retire the Gateway when PostgreSQL ownership is lost

- PostgreSQL session loss aborts a custody signal that retires the process
  state owner, so admission, queued work and the server lifecycle all stop.
- Bound connection startup with connectionTimeoutMillis and every session
  close with the same 10 s; release never rejects, so local custody is
  always released.
- Stop the heartbeat after loss; a silent network is reported by the next
  heartbeat within about 20 s.
- Drop postgres-install.json and the install schema; the lock key is the
  schema prefix within the database, and the holder is read from pg_locks
  and pg_stat_activity.

* fix(database): take PostgreSQL custody for cold CLI owners

- A cold CLI owner resolves its configured engine after taking the lock, so
  the lock saw no PostgreSQL selection and skipped installation custody.
- The lock handle now takes PostgreSQL custody once the selection is in
  scope; runWithLocalStateOwner calls it before stateful work. Config-only
  repair keeps its offline boundary.
- Custody loss still retires the same process owner; a sibling helper keeps
  gateway-lock.ts under its line cap.

* fix(database): keep PostgreSQL custody while retained leases hold the owner

- Uncertain child cleanup borrows the process owner before the lock is
  released; release used to end the PostgreSQL session anyway, so another
  host could take ownership while child work still ran.
- acquireGatewayStateOwner takes an onReleased hook that runs once physical
  custody ends, after the last retained lease; the lock ends its PostgreSQL
  session there.

* Merge remote-tracking branch 'origin/main' into feat/postgres-install-registry

* refactor(database): name the setting database.postgres.ownership

- database.localStores "none" becomes database.postgres.ownership "installation"; the default is "state-directory".
- The name now describes what this release changes (Gateway state ownership) instead of an end state where anchors are gone.
- Validation, runtime selection, tests and the operator guide follow the new key.

* Merge remote-tracking branch 'origin/main' into feat/postgres-install-registry

* Merge remote-tracking branch 'origin/main' into feat/postgres-install-registry

* fix(database): bound PostgreSQL ownership handoff

* fix: refresh the reviewed correction baseline

Baseline-Refresh: a62260acc6a7472995dadd2dd749b8ba579784cb

* test(database): cover capture and ownership config integration

* fix(database): type bounded owner queries and regression fixtures

Co-authored-by: Mitchell Etzel <[email protected]>
Co-authored-by: Mitchell Etzel <[email protected]>
Co-authored-by: Vincent Koc <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 14, 2026
…98325)

Register both Gateway PostgreSQL ownership suites introduced by openclaw#196237 in the existing conformance inventory. Preserve the completeness guard and the separate snapshot/cache registration repair in openclaw#198118.

Co-authored-by: obviyus <[email protected]>
Co-authored-by: steipete <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

clawtributors PR from a clawtributor cli CLI command changes docs Improvements or additions to documentation merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. size: L 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.

3 participants