Skip to content

fix(database): analyze PostgreSQL schemas after database port - #183447

Merged
steipete merged 1 commit into
mainfrom
upd/upd-l1906
Oct 25, 2026
Merged

steipete merged 1 commit into
mainfrom
upd/upd-l1906

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Fixes #183307. Thanks @etzelm for the detailed reproduction and planner observations.

Related: #183327.

What Problem This Solves

Porting a store to PostgreSQL leaves copied data, and the later agent memory rebuild, without planner statistics until autovacuum catches up. PostgreSQL backup restore uses the same bulk-copy path and has the same gap.

User Impact

Newly ported and restored stores have statistics before returning to their caller. Agent ports refresh them again after the memory manager finishes and closes. Statistics refresh failures produce warnings while preserving the verified data; autovacuum can finish the optimization later.

Why This Change Was Made

The shared bulk-copy owner now runs namespace-scoped ANALYZE after canonical verification and commit, in a separate transaction. Catalog discovery includes the destination's derived tables, identifiers are quoted, and unrelated namespaces are untouched. A 10-second statement timeout and 1-second lock timeout bound the work. Port reports expose success/table counts or a warning, including the post-rebuild result. PostgreSQL backup restore automatically uses the same helper through the materializer.

The existing worker owns SQL and the post-port offline owner retains custody through the memory refresh. No configuration, CLI options, dependencies, schemas, data verification, or steady-state autovacuum policy change. Simplification review retained one statistics helper for all bulk-copy callers; no parallel restore implementation was introduced.

Evidence

  • Regression with the original materializer behavior: a populated table returned reltuples = -1 instead of 1 with autovacuum disabled. After the fix, the state-port test checks statistics immediately after port and after both exact and sanitized restore.
  • Node command regression: real port custody, PostgreSQL writes, and worker transport, with a fixed memory-plugin service; statistics reflect the new memory chunk before the command returns. The selected regression passes in 16.6 seconds of test time (63.0 seconds wall, including source preparation).
  • PostgreSQL helper tests pass on Node: a quoted table name, a second namespace left unanalyzed, restored connection timeouts, and an actual conflicting lock that becomes a warning in about 1 second while committed rows remain readable.
  • Isolated live owner proof against local PostgreSQL 17, autovacuum disabled: doctorDatabasePort({ family: 'agent', to: 'postgres' }) ported 500 cache rows and ran the real bundled memory runtime, rebuilding one chunk in 22.7 seconds. Both phases reported analyzed for 47 tables. Immediately afterward, pg_class.reltuples was 500 for cache_entries and 1 for memory_index_chunks; pg_stat_user_tables.last_analyze was set for both.
  • Production and infra-test typechecks pass; touched-file Oxlint and oxfmt pass; line-cap ratchet passes for all 13 changed source files; Madge reports zero import cycles; git diff --check passes. Fresh isolated Codex review found no actionable P0–P2 findings.

Consumer validation ran all 34 runnable files selected by the owner-basename scan on Node 26.12.1 (the scan also matched a live-only subagent file through report.workers; it has no changed-owner import and the normal runner excludes it). The initial run reported 808 passed tests, 9 failed, and 4 skipped across those 34 files. Two bounded follow-ups are now green, leaving only the storage-permission limitations below:

  • Mixed-family round trips previously opened backup workers per operation: the first state round trip timed out at 124.2 seconds and left the shared test fixture mid-port for later cases. The suite now uses the existing pooled database-worker fixture, retaining real native worker protocol and SQL. Its first state round trip passes in 68.8 seconds; all five mixed-family cases pass with the original timeout and assertions. No retries or larger timeouts were added.
  • The refusal/resume consumer now distinguishes stable descriptor/data verification from the new per-attempt statistics report. Reusing a verified anchor performs no new copy or ANALYZE; all original canonical-data and anchor-byte assertions remain. This case passes in 6.6 seconds.
  • After those targeted repairs: 29 runnable files pass. Five files remain host-limited by the unchanged storage ancestor permission guard: agent-port.postgres.test.ts (one archive case), backup.test.ts, git-backup-secrets.postgres.test.ts (two cases), git-backup.postgres.test.ts (repository setup), and update-preflight.conformance.test.ts (baseline capture). The same ancestor is group-writable; no permission checks, baselines, or assertions were relaxed.

The PostgreSQL commands were OPENCLAW_VITEST_RUNTIME=node node scripts/test-database-conformance.mjs --engine postgres --connection <disposable-dsn> -- <selected test files> --maxWorkers=1. The final focused repair command selected port-command.mixed.integration.test.ts and port-command-refusals.postgres.test.ts: 2 files and 6 tests passed, 377.6 seconds wall including 65.8 seconds of shared worker compilation.

Existing slow consumer proof

The tooling pair passed 636 tests in 331.5 seconds (97% test time), dominated by its existing shell/Node fixture matrix. Whole-archive restore cases passed in 93.0, 42.8, and 48.7 seconds, including real store recovery and cold Gateway startup. Matrix account-root cases passed in 193.8, 174.8, and 69.8 seconds. The native port-command recovery cases range up to 114.4 seconds and deliberately exercise multiple full port/snapshot phases. Credential continuity cases reach 81.0 seconds; retained-agent update recovery took 81.1 seconds. These are existing broad compositions, not new planner-statistics work. The bounded mixed-suite worker-startup repair is described above; the dedicated one-shot custody proof remains intact.

Live-proof commands used isolated HOME, OPENCLAW_STATE_DIR, and OPENCLAW_CONFIG_PATH. The Node integration harness ran via node --import ./scripts/tsx.mjs .artifacts/port-live.mts; PostgreSQL was a disposable local pgvector/pgvector:pg17 container, with the same unaccent, pg_trgm, and vector prerequisites as CI. No remote lease or operator Gateway was used.

Limitations: pnpm openclaw database port --family agent --to postgres --json stopped before executing the port because the source launcher could not verify offline runtime-artifact publication. The live owner integration above succeeded instead; no service was stopped or guard bypassed. Existing archive and snapshot tests reject the group-writable storage-volume ancestor; filesystem permissions were left unchanged. Full check:changed SQLite inventory was skipped under the campaign's local gate budget; PR CI remains the broad proof.

Diff: production +146/-13 lines; tests +125/-3; docs +6/-0. No release changelog edit.

@clawsweeper

clawsweeper Bot commented Oct 25, 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 cli CLI command changes commands Command implementations size: M labels Oct 25, 2026
@steipete
steipete marked this pull request as ready for review October 25, 2026 08:39
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-25T08:41:09.745056Z 1c03007 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR refreshes PostgreSQL planner statistics after database port, backup restore, and post-port memory rebuilding.

Example: Port an agent store with 500 cache rows and rebuild one memory chunk.

  • Before: Copied and rebuilt tables can retain unknown row estimates until autovacuum runs.
  • After: The supplied owner replay reports row estimates of 500 cache entries and one memory chunk before returning.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, apparently correct repair with meaningful PostgreSQL coverage and supplied owner-level behavior evidence; shipped CLI execution is not demonstrated.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR. The body records an isolated PostgreSQL 17 production-owner replay with real memory rebuilding and immediate statistics for both phases, while disclosing the unsuccessful CLI launcher attempt. No canonical schema, backup format, persisted preference, or row identity changes; planner metadata is regenerable.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: First queries against newly ported PostgreSQL stores can plan from default estimates until autovacuum catches up.
Reason: The maintainer-directed change covers both reported write phases, preserves verified data on optimization failure, and introduces no configuration or steady-state maintenance policy.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-directed PR addresses both PostgreSQL statistics gaps still present on main, with no actionable correctness or security findings.

Priority: P2
Reviewed head: 1c0300725a08b8b259df55928a3f6c0fc1a567aa

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied live replay reaches doctorDatabasePort directly; the CLI launcher stopped before execution, so shipped CLI reporting remains unexercised.
Agent review details

How this fits together

The offline database workers consume verified private store images, materialize PostgreSQL namespaces, and return verified destinations for publication; the memory owner subsequently rebuilds agent indexes.

flowchart TD
 A[Database port command] --> B[Offline custody]
 B --> C[Shared bulk-copy worker]
 D[Backup restore] --> C
 C --> E[Verify and commit data]
 E --> F[Namespace statistics refresh]
 F --> G[Publish stores and rebuild memory]
 G --> H[Refresh statistics after memory closes]
Loading

Technical review

Best possible solution:

Keep statistics maintenance in one shared worker helper and refresh again after the existing memory owner closes.

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

Current-main source confirms both missing refresh paths, and the linked report supplies immediate PostgreSQL catalog observations; this read-only review executed no target code.

Is this the best way to solve the issue?

The defect is missing statistics after bulk writes, the invariant is refreshed destination estimates before return, and the smallest complete repair uses the existing materializer and memory lifecycle with one bounded shared helper.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit ddd9e83 adds src/infra/database-engine/port.worker.ts:587 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ddd9e838267e; files: src/infra/database-engine/port.worker.ts)
  • Dallin Romney: Raw commit 11d75e4 adds src/commands/doctor-database-port-context.ts:135 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 11d75e447e44; files: src/commands/doctor-database-port-context.ts)

PR surface

Source +133, Tests +122, Docs +6. Total +261 across 14 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 8 146 13 +133
Tests 5 125 3 +122
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 277 16 +261

Root-cause cluster

Relationship: same_root_cause
Canonical: #183307
Summary: The canonical report identifies bulk-copy and post-memory statistics gaps addressed by this PR and overlapping open implementations.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P2: Freshly ported PostgreSQL stores temporarily use inaccurate planner estimates; the report establishes neither data loss nor a measured availability or latency regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Freshly ported PostgreSQL stores temporarily use inaccurate planner estimates; the report establishes neither data loss nor a measured availability or latency regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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.

Reviewed October 25, 2026, 4:54 AM ET / 08:54 UTC.

@steipete
steipete merged commit 660b252 into main Oct 25, 2026
222 of 225 checks passed
@steipete
steipete deleted the upd/upd-l1906 branch October 25, 2026 09:01
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 26, 2026
…aw#183447)

openclaw database port --to postgres and backup restore into PostgreSQL handed back schemas without planner statistics, so first queries planned on default estimates. One shared helper now runs ANALYZE scoped to the destination namespace after the verified commit (and again after the memory rebuild); timeouts or errors are warnings and never undo verified data. Live PostgreSQL proof showed fresh statistics after port.

Fixes openclaw#183307. Thanks @etzelm for the report and @lonexreb (openclaw#183327) and @goutamadwant (openclaw#183392) for the earlier fixes.

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

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

[Bug]: database port --to postgres hands back PostgreSQL schemas with no planner statistics (no ANALYZE), so first queries plan on default estimates

1 participant