Repository navigation
feat(database): hold Gateway state ownership in PostgreSQL on all-PostgreSQL installs - #196237
Conversation
…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
|
🦞👀 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 changesAdds 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.
Review scores
ProductKind: Feature · Worth it: Yes · Fix scope: Partial 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherGateway 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +309, Tests +634, Docs +59, Generated 0, Other +2. Total +1004 across 17 files. Added test files: 3. 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. Review metrics
LabelsLabel changes: No label 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 (7 earlier review cycles)
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.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
- 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.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Baseline-Refresh: a62260acc6a7472995dadd2dd749b8ba579784cb
|
@clawsweeper re-review Please review exact head |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review Please review exact changed head |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
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]>
…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]>
…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]>
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 whendatabase.engineispostgresand no family overrides tosqlite. 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.openclaw config setwith 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.database.postgres.schemaPrefixname the installation, so the runtime role needs no new privilege.database.postgresstrictly (2026.11.3 does), so removeownershipbefore rolling back to one. Installs that never set it are unaffected.Why This Change Was Made
acquireGatewayLockalso takes a session-levelpg_try_advisory_lockon one dedicatedpgconnection 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.runWithLocalStateOwnerwithdatabaseEngine: "configured", asopenclaw config setdoes) 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 theconfiguredpath has its own test.acquireGatewayStateOwner. That retires the existing process owner, which is the one owner that admission (captureStateDatabaseAccess), queued workers and the server lifecycle (captureGatewayStateOwner(...).signalinserver.ts) already observe. There is no parallel loss flag.runWithLocalStateOwneronCommandProcessCleanupError), 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 (onReleasedinacquireGatewayStateOwner).pg_locksandpg_stat_activity. The owner session setsapplication_nametoopenclaw-gateway-owner:<pid>:<host>, so there is no diagnostic row to go stale or to fail on release.GatewayStateOwnerContentionError, so the existing wait and retry behavior applies unchanged.database.postgresand 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 itdatabase.localStores: "none"; that name was never released.How this lock relates to the
state_leasesgateway-owner leaseBoth exist with
ownership: "installation", and they cover different scopes:state_leasesgateway-ownerrow 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:
database.ownership. The rename is mechanical: schema, one runtime field, tests and the guide.Accepted limits:
database.postgres.schemaPrefix. Nothing new is persisted. Two installations in one database must use different prefixes, as they already must for their store schemas.Later, separate question: should the
state_leasesgateway-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.
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).client/credentials.sqlitebinds to the state anchor's path, device and inode (readClientCredentialFileIdentity).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:
database portandbackup restore.Evidence
Maintainer correction and integration evidence
Reviewed signed candidate:
f3ca42b3820e4865f92f04ac3ae31b72bb8b9e42, natively integrated onto landed capture baseline2ff4256ae377bd54a7014a640336cc466ff4af6b. Publication and exact-head required checks/review remain separate gates. The original evidence below describes earlier candidates.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.recoveryCapturesandownershipschema/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.satisfiesexcess-property errors at thepg.queryoverloads 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.failed: false. The aggregate exit receipt was lost to output truncation; no aggregate exit-zero claim. Required exact-head CI remains authoritative.config:docs:genandconfig:docs:check, targeted formatting,git diff --checkand 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.43407736121attempt 2 passed with no source change. Its one diagnostic replay of cancelled shardchecks-node-changed-compact-large-40-1executed the same merge781d8c1f818cbcb64301dcb4345b83907c4bfd61(headf3ca42b3820e4865f92f04ac3ae31b72bb8b9e42, base4aa0168e1f2a17608fa6dbb8d7d07a406794fd96) 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_trgmandvectorinstalled, 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:After stable stopped, the branch followed the documented path:
openclaw doctor --fix(exit 0, "Doctor complete."), thenopenclaw database port --to postgres, which ported the state and agent stores and setdatabase.enginetopostgres. Thenownership: "installation"was added and the branch Gateway started on the same state directory: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 validaterefuses the setting and exits 1: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_backendwhile A kept running.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 321then ran with its own state directory (<root>/b) and the same database and prefix. It resolves its engine only after taking its local lock.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.mjsagainst PostgreSQL 17.11,src/infra/gateway-postgres-owner.postgres.test.ts, 7/7:openclaw.sqlite. Releasing twice is safe, and the next Gateway then acquires.pg_terminate_backend, the former Gateway's owner signal aborts. A process-owner handle captured before the loss (as queued work holds one) failsassertCurrent.captureGatewayStateOwnerand newcaptureStateDatabaseAccess(...).prepareAccess()are refused. A successor acquires, and exactly one backend holds the lock.runWithLocalStateOwnerfor another state directory readsownership: "installation"from its config and is refused while a Gateway holds the lock.runLocalnever runs. After the Gateway stops, the same CLI holds exactly one owner session duringrunLocaland none after it returns. Without the new call inlocal-state-owner.ts, this test fails (promise resolved "'ran'" instead of rejecting).connectionTimeoutMillis, the silent-server test hangs until the 120 s test timeout. Without the loss-to-owner wiring ingateway-lock.ts, the session-loss test fails (expected false to be trueon the aborted signal). Both checks ran against the 4-test revision of this file.src/config/zod-schema.database.test.tscovers the setting: it is accepted with all families on PostgreSQL,"state-directory"is accepted anywhere, and it is refused withoutengine: "postgres", with a family onsqlite, or with an unknown value. Against the previous head (withdatabase.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. main2cfd5ceab3dwas 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.config:docs:checkoxfmt --check(changed files),oxlint(changed files),pnpm tsgo:coregateway-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.tsgateway-postgres-owner.postgres.test.tson PostgreSQL 17.11check: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-exports277e32c668a)check:test-lines-ratchetconfig/test-lines-allocations/196156-postgres-gateway-owner.txtcovers this PR's exact net growth (+311). The ratchet still reportsover by: 7because main277e32c668ais already 7 over on its own (net delta: 0. Tree is over the ceiling; this change does not add test lines.).