Skip to content

fix: let large PostgreSQL maintenance operations finish - #201869

Merged
VACInc merged 5 commits into
openclaw:mainfrom
VACInc:fix/postgres-maintenance-budgets
Nov 21, 2026
Merged

VACInc merged 5 commits into
openclaw:mainfrom
VACInc:fix/postgres-maintenance-budgets

Conversation

@VACInc

@VACInc VACInc commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

High Level TLDR

Large database upgrades and search rebuilds can fail at the same timeout on every retry. Give these maintenance transactions a one-hour SQL budget and matching bridge headroom, while keeping ordinary requests on their existing limits.

  • Apply the scoped budget to schema admission/migration, including update generation fingerprints, first-use search extension builds, and explicit search rebuilds.
  • Keep the 60-second lock limit. Restore the caller's SQL limit after nested maintenance; transaction completion restores the session default.
  • Reuse the existing transaction owner and savepoints. No config, schema version, dependency, durability, or bridge wire-format change.
  • Composes with fix: keep database workers healthy after silent connection loss #201856: that PR sends each request's host deadline to the worker and retires a silent connection 20 seconds before it. Maintenance requests therefore get a client cutoff of one hour plus 10 seconds instead of the ordinary 100 seconds.

Root Cause

Runtime connections set a 90-second statement_timeout, and each synchronous bridge request has a separate 120-second deadline. Schema migrations and whole-store derived builds used these runtime limits too. A migration statement canceled at 90 seconds rolls back, so retrying cannot advance it. Generation fingerprinting can also exceed the bridge deadline across multiple statements.

On the base revision, a real openEngineStore migration with one retained row and an injected SELECT pg_sleep(91) failed after 90,028 ms with 57014: canceling statement due to statement timeout. The schema stayed at version 1 and the retained row was unchanged. This proves the deadline mechanism, not a production corpus-size threshold.

Real behavior proof

On a disposable, Unix-socket-only PostgreSQL 17.12 server:

  • The same 91-second migration passed after 91,119 ms. The row survived, its migrated value was present, and the schema advanced to version 2.
  • A 121-second migration also passed after 121,138 ms, crossing both former deadlines. SHOW statement_timeout returned 90s afterward in both runs.
  • An isolated foreground Gateway using the repository's mock OpenAI config returned OPENCLAW_E2E_OK_MAINTENANCE through agent --agent main --message 'Return marker OPENCLAW_E2E_OK_MAINTENANCE' --thinking off --json: exit 0, readiness true, marker true. No paid model calls.

Release compatibility from the current stable release: the official npm [email protected] package (schemas state 36 / agent 38) ran a real foreground Gateway on a disposable PostgreSQL 17 server with the repository's mock OpenAI config and completed a turn. The candidate, this PR combined with #201856 on the PR merge base, then ran doctor --fix --yes --non-interactive --no-workspace-suggestions: it saved pre-migration backups and upgraded the schemas to 40/43. All 8 transcript events kept identical payload hashes, a stored setting and selected config values survived, a new runtime connection reported statement_timeout 90s, and the candidate Gateway reopened the same session and returned the mock marker. Service repair was disabled; no paid model calls.

The same harness fails on current main without this PR (built at the main commit this branch merged): candidate Doctor exits 1 with This agent database scope still requires its existing native owner after maintenance finish. The PR merge base passes it, so the failure was introduced on main after the merge base and is independent of this PR's code; this branch's current head inherits it through the conflict-resolving merge of main. An earlier run with [email protected] on this PR alone also passed.

A third regression runs a real runTransaction(..., { maintenance: true }) with SELECT pg_sleep(12) on a connection whose runtime statement budget is 1 second. On the base it failed after 1112 ms (canceling statement due to statement timeout); with this PR it returns after 12015 ms and SHOW statement_timeout is 1s afterward. 12 seconds also exceeds the 11-second client cutoff that #201856 derives from that 1-second budget, so this test guards the combination. On a scratch merge of this PR's earlier head with #201856's earlier head (fixed client query_timeout), the same test failed after 11078 ms (PostgreSQL connection lost; transaction rolled back). On a scratch merge with #201856's current head it passes in 12024 ms, together with #201856's silent commit and idle regressions (11134 ms and 10066 ms, peers kept).

The two earlier committed regressions were red on the base: a delayed bridge reply was rejected at the runtime deadline, and maintenance retained the caller's runtime SQL limit. They now pass. The server regression also exercises migration admission and restoration after nested success and rollback, preserving committed rows.

Landing order

Land #201856 first, then merge main into this branch. The only code conflict is the request deadline line in src/infra/postgres-sync/connection.ts (and its policy import); docs merge cleanly. Verified resolution:

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

Either PR alone is safe: this PR alone has no client cutoff, and #201856 alone keeps the ordinary 100-second cutoff and 120-second deadline.

What was not tested

  • A production-sized corpus or corpus throughput benchmark. Injected SQL delays test the timeout boundary; they do not estimate migration speed. No production dataset was available to this test environment.
  • A current-stable Doctor upgrade on this branch's exact head: it inherits the main failure described above. The combined PR code passed the same upgrade on the merge base.
  • Managed-service package replacement through the updater. Release compatibility was tested through explicit Doctor with foreground Gateways and service repair disabled.
  • Local PostgreSQL 16/18, remote TLS, or paid model providers. CI also passed its PostgreSQL 16 smoke lane.
  • An hour-long timeout expiry. Maintenance still has a finite limit and can fail above it.

Verification

  • node scripts/test-database-conformance.mjs --engine postgres --connection "$TEST_POSTGRES_CONNECTION" -- src/infra/postgres-sync/connection.test.ts src/infra/database-engine/schema-admission.postgres.test.ts --maxWorkers=1: base 2 failed, 49 passed.
  • With the disposable-server conformance preload, node scripts/run-vitest.mjs src/infra/postgres-sync/connection.test.ts src/infra/database-engine/schema-admission.postgres.test.ts src/infra/database-engine/search-extension.postgres.test.ts src/infra/database-engine/postgres-search-admission.postgres.test.ts src/infra/database-engine/postgres-vector-search-schema.postgres.test.ts src/infra/database-engine/postgres-text-search-schema.postgres.test.ts src/infra/database-engine/adapters.test.ts src/infra/database-engine/open.test.ts --maxWorkers=1: 75 passed across eight files. Test shard durations: 1.02 s + 10.97 s; total wrapper wall time 52.74 s. Previous-head CI passed, including all four PostgreSQL conformance shards and the PostgreSQL 16 smoke lane.
  • Populated-search rebuild conformance: node scripts/run-vitest.mjs src/infra/database-engine/postgres-search.conformance.test.ts --maxWorkers=1 with the same disposable-server preload: 10 passed, including retained source rows, source deletion, rollback, and nonempty derived rebuilds. File duration 3.21 s, wrapper wall time 52.18 s. Total focused proof: 85 passed.
  • New regression durations: real-server migration/restoration 224 ms; injected-clock bridge deadline 3 ms.
  • Current head (main merged in to resolve a conflict in search-extension.ts: main's new owner-requested rebuild path now runs inside the maintenance transaction): node scripts/test-database-conformance.mjs --engine postgres --connection <disposable DSN> -- src/infra/postgres-sync src/infra/database-engine/schema-admission.postgres.test.ts src/infra/database-engine/search-extension.postgres.test.ts src/infra/database-engine/postgres-search.conformance.test.ts src/infra/database-engine/postgres-search-admission.postgres.test.ts extensions/memory-core/src/memory/manager-search-rebuild.postgres.test.ts on a disposable PostgreSQL 17 server: 45 + 132 + 2 passed. tsconfig.core.json and test-infra typecheck, oxlint, oxfmt and git diff --check: passed.
  • Exact-head CI on e0836463f29: SUCCESS, including all four PostgreSQL conformance shards and the PostgreSQL 16 smoke.
  • Combined with fix: keep database workers healthy after silent connection loss #201856's current head (scratch merge, not pushed), the same files plus port-command.integration.test.ts: 45 + 160 + 2 passed, including the maintenance composition test (12024 ms), fix: keep database workers healthy after silent connection loss #201856's silent commit/idle regressions (11134 ms, 10066 ms), and the lost-commit-reply port case.
  • node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental --tsBuildInfoFile .artifacts/tsgo-cache/core.tsbuildinfo: passed.
  • Focused node scripts/run-oxlint.mjs and node scripts/run-format.mts --check on changed files: passed. git diff --check: passed.
  • pnpm build: passed in 5m 1.2s, with nonblocking UI budget warnings.
  • Simplification pass: one existing transaction owner, no new persistent state or parallel maintenance connection. The added production code coordinates the SQL and bridge budgets; the tests protect timeout and restoration behavior.

Evidence

Local autoreview on the current head (branch mode, P0 to P2, base 3587df70a233dc639b733b9169797d3abd138301) is scoped-clean with no actionable findings. On the earlier head, local autoreview was attempted against base 3587df70a233dc639b733b9169797d3abd138301 and the complete local change, at P0–P2 coverage. Its CLI isolation preflight failed before a reviewer ran. Hosted review covered head a109443fa41cf70572e7365fa2cd847f9ce25e02 and reported no actionable code or security findings. It requested released-data compatibility proof; the real release-to-candidate Doctor upgrade above supplies that proof. Final maintainer review remains required.

@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: M labels Nov 19, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro 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 gives PostgreSQL migrations and search builds longer statement and bridge deadlines while preserving ordinary request limits.

Example: A PostgreSQL migration contains a statement that takes 121 seconds.

  • Before: The 90-second statement timeout cancels the migration, and retrying starts it over.
  • After: The migration completes within the maintenance budget, preserves existing rows, and restores the ordinary statement timeout afterward.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful repair with real PostgreSQL boundary evidence, meaningful regressions, green exact-head CI, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The public evidence exercises openEngineStore and the real PostgreSQL transport across both former deadlines, verifies restoration and retained rows, and demonstrates successful composition with the companion worker cutoff. Released-data compatibility is supported by the recorded v2026.11.6 Doctor upgrade; the exact-head Doctor limitation is explicitly attributed by a matching run without this PR. The generic Gateway marker is supporting smoke evidence, not the timeout proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Large PostgreSQL migrations and search builds can fail at the same deadline on every retry.
Reason: The maintainer-authored change repairs a demonstrated maintenance failure without adding user configuration or changing stored formats.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses a confirmed PostgreSQL timeout defect, and review found no actionable correctness or security findings.

Priority: P2
Reviewed head: e0836463f2937f90b71d1692aef03c7e6bce772b

Before merge

None.

Findings

None.

Agent review details

How this fits together

The database engine admits and migrates stores through a synchronous PostgreSQL connection backed by an I/O worker; transaction options now select maintenance budgets for SQL execution and bridge replies.

flowchart LR
  A[Store admission or search rebuild] --> B[Existing transaction owner]
  B --> C[Transaction-local SQL budget]
  B --> D[Synchronous bridge deadline]
  D --> E[PostgreSQL I/O worker]
  E --> F[PostgreSQL server]
  F --> B
Loading

Technical review

Best possible solution:

Keep maintenance budgets in the existing transaction and bridge owners, preserving savepoint rollback, caller timeout restoration, and ordinary request limits.

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

Current main applies runtime deadlines to maintenance, and the public reproduction records an injected 91-second migration failing with SQLSTATE 57014 while preserving its original schema and row; this review executed no target code.

Is this the best way to solve the issue?

The patch fixes the deadline owners directly, keeps the lock limit intact, and uses existing savepoints rather than introducing another connection or maintenance subsystem.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Runtime timeout policy and synchronous bridge deadline changes intended behavior with a stated reason (9dc6466: The shared adapter established connection-level timeouts below the existing bridge watchdog; this PR explicitly explains why maintenance needs a separate bounded budget.)
  • Transaction lifecycle and commit settlement keeps the original intent (5e78ec6: The existing transaction owner supplies savepoints and physical settlement; the patch retains those boundaries and adds transaction-local timeout handling.)
  • Search rebuild ownership keeps the original intent (bf46379: Search rebuilds belong inside the owning transaction with canonical source data authoritative; the added nested maintenance transaction preserves that contract.)
  • Owner-requested search extension rebuilds keeps the original intent (8832901: The merged repair allows tokenizer and vector-dimension rebuilds while preserving sealed text-column positions; the conflict resolution retains that logic inside the maintenance scope.)
  • PostgreSQL operator guidance changes intended behavior with a stated reason (876e77c: The guide distinguished runtime bridge limits from offline materialization; the patch updates that distinction for the newly scoped maintenance budget.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Introduced patch: The pinned introduced diff scopes maintenance to admission, search-extension installation, and explicit rebuilds; it adds no persistent format, schema version, dependency, or configuration change. (src/infra/database-engine/open.ts:274, e0836463f293)
  • Timeout restoration: Nested maintenance saves and restores the caller's statement timeout on success; the existing savepoint rollback restores it on failure, and transaction completion restores session settings. (src/infra/postgres-sync/transaction.ts:55, e0836463f293)
  • Bridge scope: The maintenance flag covers the complete existing transaction lifecycle, including beforeCommit fingerprinting, and is restored in finally; ordinary bridge requests retain their 120-second deadline. (src/infra/postgres-sync/connection.ts:113, e0836463f293)
  • Current main still needs the fix: Fetched main retains the fixed 120-second bridge deadline and has no maintenance statement-budget selection in its transaction owner. (src/infra/postgres-sync/transaction.ts:54, d874bf532f4c)
  • Public behavior and compatibility evidence: The updated body records real PostgreSQL migrations crossing the former SQL and bridge deadlines, retained rows, restored runtime limits, and an official v2026.11.6-to-candidate Doctor upgrade preserving transcript payload hashes and settings. It separately attributes the exact-head Doctor refusal to a matching failure without this PR. (e0836463f293)
  • Companion integration evidence: fix: keep database workers healthy after silent connection loss #201856 remains open and now derives its worker cutoff from each request's deadline; both PR bodies record successful combined maintenance and silent-connection regressions and explicitly specify its landing first. (src/infra/postgres-sync/connection.ts:200, e0836463f293)

PR surface

Source +46, Tests +101, Docs +9. Total +156 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 7 152 106 +46
Tests 3 102 1 +101
Docs 1 11 2 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 265 109 +156

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Maintenance on sufficiently large PostgreSQL stores can repeatedly roll back at runtime deadlines; the impact is limited to the opt-in PostgreSQL maintenance paths.
  • 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 (2 earlier review cycles)
  • reviewed 2026-11-19T14:14:46.089Z sha a109443 :: blocked before merge. :: none
  • reviewed 2026-11-20T18:38:33.930Z sha e083646 :: blocked before merge. :: none

Reviewed November 20, 2026, 2:08 PM ET / 19:08 UTC (Revision 3).

…nce-budgets-p13

# Conflicts:
#	src/infra/database-engine/search-extension.ts
@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:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 20, 2026
@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:

@clawsweeper clawsweeper Bot added 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 20, 2026
…nce-budgets-p13

# Conflicts:
#	src/infra/postgres-sync/connection.ts
@VACInc
VACInc merged commit c29f72b into openclaw:main Nov 21, 2026
123 checks passed
@VACInc

VACInc commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Merged via squash.

@VACInc
VACInc deleted the fix/postgres-maintenance-budgets branch November 21, 2026 03:34
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
)

* fix: let large PostgreSQL maintenance operations finish

* test: keep maintenance statements past runtime client bounds

---------

Co-authored-by: VACInc <[email protected]>
tideclaw-bot pushed a commit that referenced this pull request Nov 23, 2026
* fix: let large PostgreSQL maintenance operations finish

* test: keep maintenance statements past runtime client bounds

---------

Co-authored-by: VACInc <[email protected]>
(cherry picked from commit c29f72b)
Release adaptation: Preserve the baseline 120s runtime bridge deadline and existing search-extension semantics; apply only maintenance scopes. Do not import the separate client-cutoff protocol. Adjust live-test wording accordingly.:
Co-authored-by: RomneyDa <[email protected]>
(cherry picked from commit 624c457891f22803cb3dcd8c4437aeceb0197759)
(cherry picked from commit 4d18a2a6dde2cfa4c42c4ab1e57c371d57fc8cc1)
tideclaw-bot pushed a commit that referenced this pull request Nov 24, 2026
Baseline adaptation: Apply the one-hour statement and bridge budget only to Workboard schema bootstrap and migration. Keep the existing lock and transaction owners, and omit the newer search-extension paths.

(cherry picked from commit c29f72b)

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