Skip to content

fix(database): make shared-state queries portable to PostgreSQL - #170055

Merged
steipete merged 4 commits into
mainfrom
pgprep/p33-pr4a-portable-sql
Oct 12, 2026
Merged

steipete merged 4 commits into
mainfrom
pgprep/p33-pr4a-portable-sql

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Related: #169254 and #169933.

What Problem This Solves

Shared-state consumer queries fail on PostgreSQL because they still rely on SQLite-specific SQL and connection-global mutation bookkeeping.

User Impact

SQLite remains the default with the same retention, projections, publication, and update/rollback behavior. These changes remove SQL blockers for the experimental PostgreSQL backend; shared-state activation and end-to-end PostgreSQL validation remain held behind separate admission work.

Why This Change Was Made

The seven consumer paths now use portable owner-built statements and engine-owned JSON fragments. Large JSON projections stay in SQL before payload transfer, and PostgreSQL rejects NUL plugin keys with an explicit error.

Owner changes and scope left for follow-up
  • Cron retention uses a realizable upper bound instead of negative LIMIT.
  • Placement parent maps compare text values; plugin batch tuples use engine-owned JSON extraction.
  • Delivery receipt pruning uses bound Kysely statements, preserving count and age policies.
  • Plugin insert-if-absent names its composite conflict target; PostgreSQL rejects NUL keys explicitly.
  • Worker environment publications use their own affected-row/RETURNING results, including attachment-only writes and no-op suppression.
  • Transcript source, participants, and notes remain projected and bounded in SQL through engine-owned fragments.

No schema, retention, admission, or update migration changes. Existing SQLite data and rollback behavior are unchanged. PostgreSQL shared-state execution remains held behind the separate admission work; this PR does not claim end-to-end PostgreSQL readiness.

Scope left with its owner

  • Audit identity optional-table lookup needs engine-neutral admitted facts in overlap-owned state admission files; left unchanged.
  • Ten canonical GLOB checks already translate to case-sensitive PostgreSQL regex with C collation. Changing canonical CHECK text would cause existing SQLite schema drift. The remaining GLOB and one typeof occurrence are in the forbidden overlap migration.
  • Seven typeof occurrences belong to historical SQLite-source repair/backfill, not PostgreSQL runtime queries.
  • The subagent registry printf belongs to a larger bounded JSON projection with duplicate-envelope and malformed/overdepth fallback semantics; defer that complete projection conversion.
  • Rowid cursors and lazy DDL remain outside this PR.

Evidence

The external harness calls the actual owners against a capture-only PostgreSQL-branded connection, then PREPAREs and EXPLAINs their compiled SQL and bound parameters on PostgreSQL 17 against pnpm db:postgres:gen shared-state DDL. No SQL is rewritten by the harness. Worker mutation builders are unchanged; five representative shapes additionally pass the same proof.

Statement Owner PREPARE + EXPLAIN
1 1 cron retention / claim PASS
2 1 cron retention / claim PASS
3 2 placement parent map PASS
4 2 placement explicit parent PASS
5 3 delivery bounded global PASS
6 3 delivery bounded global PASS
7 3 delivery bounded prefix PASS
8 3 delivery age PASS
9 3 delivery age PASS
10 4 plugin insert absent PASS
11 4 plugin upsert PASS
12 5 plugin ordered batch PASS
13 6 worker mutation results PASS
14 6 worker mutation results PASS
15 6 worker mutation results PASS
16 6 worker mutation results PASS
17 6 worker mutation results PASS
18 7 transcript entry PASS
19 7 transcript latest PASS
20 7 transcript notes PASS

Scoped lint/format, madge (zero cycles), and git diff --check pass. Independent autoreview found no actionable P0–P2 issues. SQLite transcript proof: 3 files / 50 tests pass (426.62s Vitest duration; 683.14s total wrapper wall time including 213.34s cold bundle preparation). Cron proof: 3 files / 21 tests pass (414.77s Vitest duration). Placement grants: 14/14 pass. The new PostgreSQL-key guard test passes. Delivery/plugin-state infra proof covered 94 cases, with the observation-only correction and focused rerun described below.

Focused SQLite proof covers 256 unique cases across 19 files. Worker-environment proof covers 7 files / 76 passing cases: the 5 publication cases plus 71 cases across 6 supplemental owner files (1268.30s Vitest duration; 1300.48s wrapper wall time for the supplemental run).

Changed-test timing: pnpm test src/plugin-state/plugin-state-store.kernel.test.ts --maxWorkers=1 (run in the focused batch) took 32.74s in its one-file Vitest project, including 2.41s of test execution. pnpm test src/gateway/worker-environments/store-change-events.test.ts --maxWorkers=1 passed 5/5 cases: 437.31s Vitest duration, 62.66s test execution, 477.35s total wrapper wall time including cold build/setup. The existing public store/worker/session-projection composition is needed to prove commit publication, rollback, RETURNING-only changes, and no-op suppression; no sleeps or new timers were added. Cold worker bundle preparation took about 213–215s. CI seconds are pending the draft PR run.

Production: +258/-106 (net +152); tests: +63/-12 (net +51). No files in the async-DB overlap list were touched. The PostgreSQL cluster was stopped and removed after proof; the harness and per-statement plans remain outside the repository.

The shrink-only dialect ratchet compares source against Git, with no editable baseline file: mechanical 1 → 0; design 0 → 0; engine-maintenance 0 → 0 in the changed-file scope. JSON calls hidden in Kysely function builders are outside that lexical census and are covered by the statement proof above.

The initial delivery suite exposed an observation mismatch: its query-plan test only located uppercase WITH, while Kysely emits lowercase with. The observer now matches SQL keywords case-insensitively and retains the original index-plan, namespace, and retained-row assertions. The initial infra batch had 93 passing cases and this one failure; both affected count-limit cases passed after the correction (200.26s Vitest duration, 97% transform/setup; the other 20 cases were filtered because their valid initial results were retained). Production SQL and the PostgreSQL statement proof were unchanged.

The initial draft skipped broad CI. After prerequisite #170037 merged, main was merged into this branch and the PR was marked ready; final CI evidence is recorded below.

Ownership correction and refreshed proof

Head 661a90e2d661f3568ccc0520870e30a6b33e8ba5 removes the transcript-specific engine leaf. Generic jsonExtractText, jsonOrderedTextArray, and jsonRemoveKey live in database-engine/json-values.ts; the transcript owner supplies its field keys and ordering. All helper connection parameters use DatabaseSync | PostgresSqlConnection.

The notes consumer checks payload size and then calls JSON.parse(row.summary) rather than comparing serialized JSON bytes. The PostgreSQL key-removal branch documents that JSONB normalizes key order/whitespace and keeps the last duplicate key; parsed values agree, while serialized length/order may differ. SQLite aggregation continues to consume the transcript owner’s sorted input.

Before/after capture of the actual owners proves byte-identical compiled SQLite SQL and bindings for transcript entry, latest entry, notes, and plugin batch reads (4/4). The three refreshed transcript statements pass PostgreSQL 17 PREPARE + EXPLAIN against regenerated shared-state DDL. The throwaway unix-socket cluster on port 55438 was stopped and removed.

Focused rerun: pnpm test src/transcripts/library.test.ts src/transcripts/library.search.test.ts src/transcripts/library.query-budget.test.ts src/plugin-state/plugin-state-store.test.ts src/plugin-state/plugin-state-worker.test.ts src/plugin-state/plugin-state-store.kernel.test.ts --maxWorkers=1: 6 files / 70 cases passed, 614.76s wrapper wall time, including 122.47s cold worker preparation (unit 17.03s; infra 437.12s). This covers 27 transcript cases and 43 plugin-state cases.

pnpm test test/scripts/eager-import-closure.test.ts -t "PR wrapper inventory" --maxWorkers=1: 1 case passed, 37.39s wrapper wall time. Core oxlint, oxfmt, git diff --check, and madge (zero cycles) pass. The second autoreview round is clean. The ratchet remains mechanical 1 → 0, design 0 → 0, engine-maintenance 0 → 0. This revision adds nine net production lines, bringing the full PR to +152 net production lines.

Landing validation and CI exception

The single CI repair is cfa039480e516: operation-scoped database inventory classification, regenerated inventory documentation, and SQL allow-comments placed directly on their existing expressions. SQL and runtime behavior are unchanged. Kysely guardrails, the database worker ratchet (T1 481 → 481), formatting, line-cap ratchet, and independent Codex review pass.

Final CI run: 38298012289, exact head cfa039480e516c3db987fc23f5afb68fa15af5f4. The repaired guard jobs pass; no jobs were cancelled. The authorized native admin exception covers the following remaining failures; CI is not described as green:

Failed job Classification and evidence
checks-node-changed-compact-large-17 Inherited: four cron/delivery migration assertions also fail in main job 114956275108.
checks-node-changed-compact-large-2 Inherited: the media-retention assertions and revocation timeouts also fail in main job 114956275493.
checks-ui-e2e (6/7) Unrelated mocked UI request-shape assertions: session-list-row-events.e2e.test.ts expects compact rows and receives sidebar rows. The test installs a mock Gateway; the PR does not change its UI files or execute backend SQL in this flow.
checks-node-changed The session CLI fixture fails during unchanged runtime-config preparation, before Gateway startup or changed SQL. The repeated Slack progress-finalization timeout is in an unchanged fixture and direct Slack closure path; it has no demonstrated causal link to this PR. An exact-main E2E comparison is unavailable because the scheduled-main suite excludes this configuration.

The Slack timeout remains an attribution gap, not a passing test or an empirically proven inherited failure. Landing follows the delegated policy that only a proven causal-path product regression stops this campaign; none was demonstrated. The required aggregate gate fails downstream of the four jobs above.

Preserve SQLite retention and bounded JSON projections while using
engine-owned SQL fragments, explicit conflict targets, and owned mutation
results. Reject NUL plugin keys explicitly on PostgreSQL.

Refs #169254, #169933.
@openclaw-barnacle openclaw-barnacle Bot added gateway Gateway runtime size: M labels Oct 12, 2026
@clawsweeper clawsweeper Bot added 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. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces SQLite-specific shared-state queries and mutation bookkeeping with portable SQL and engine-owned JSON helpers.

Example: Cron retention selects terminal receipts after the newest 64 records on PostgreSQL.

  • Before: The query uses LIMIT -1, which PostgreSQL rejects.
  • After: The query uses LIMIT 9007199254740991, preserving practical retention behavior on both engines.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, coherent portability work with no actionable defect found; confidence rests on source inspection, owner integration coverage, and statement-level PostgreSQL validation.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored exemption applies; supplied evidence describes actual-owner SQL capture followed by PostgreSQL 17 PREPARE and EXPLAIN, plus SQLite owner integration runs, without claiming backend activation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Shared-state consumers contain SQL that cannot run on the experimental PostgreSQL adapter.
Reason: The maintainer-directed patch removes concrete consumer-query blockers while explicitly preserving the separate activation boundary.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it delivers useful, maintainer-directed PostgreSQL portability work that current main still needs, with no actionable introduced defect found.

Priority: P2
Reviewed head: cfa039480e516c3db987fc23f5afb68fa15af5f4

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence validates owner-generated PostgreSQL statements and SQLite integration behavior, but does not demonstrate full shared-state PostgreSQL execution, which remains outside this PR.
Agent review details

How this fits together

Shared-state owners compile and execute storage queries through the database adapter, returning bounded records and publishing committed mutation facts to Gateway consumers.

flowchart TD
A[Shared-state consumers] --> B[Domain storage owners]
B --> C[Kysely queries and JSON helpers]
C --> D[Database engine adapter]
D --> E[SQLite default]
D --> F[Experimental PostgreSQL]
B --> G[Committed change publications]
Loading

Technical review

Best possible solution:

Land the bounded portability changes through the recorded CI exception while keeping shared-state PostgreSQL activation with its admission owner.

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

Current-main source directly exposes PostgreSQL-incompatible LIMIT, JSON, and mutation-counter operations; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch uses existing domain and engine owners, preserves SQL-side payload bounds and retention predicates, and removes the replaced mutation-counter path without expanding backend activation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Cron receipt retention keeps the original intent (d3308e2: Durable cron receipts retain a bounded terminal history while fencing executions and recovery.)
  • Placement parent-map reads keeps the original intent (af18444: Worker-based grant preparation reads placement and durable parent decisions in one snapshot.)
  • Delivery receipt pruning keeps the original intent (ad6bc6d: Keep payload-free receipts for idempotency while enforcing existing count and age retention.)
  • Plugin state queries keeps the original intent (ad35243: Connection-owned query kernels preserve insert-if-absent behavior; later batched reads reuse compiled queries and positional results.)
  • Worker mutation publication keeps the original intent (5113445: Avoid invalidating resident session lists when a worker operation performs no writes.)
  • Transcript SQL projections keeps the original intent (3f12383: Provide bounded archive reads and exports without transferring unbounded stored payloads.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduction reviewed: Reviewed the merge-base-to-head hunks and relevant original blobs; the checkout matches the supplied original PR head and remains clean. (cfa039480e51)
  • Current main retains the portability blockers: Fetched main retains negative cron LIMIT, SQLite JSON functions, raw delivery-pruning SQL, and total_changes-based worker publication tracking. (src/gateway/worker-environments/store-write.ts:7, 04d4e9cd3fbf)
  • Operation-owned publication tracking: The replacement tracks affected-row counts and RETURNING rows within the existing synchronous worker operation; commit admission and deferred publication remain in their existing owner. (src/gateway/worker-environments/store-write.ts:14, cfa039480e51)
  • Bounded JSON projections remain in SQL: Consumers retain field selection and byte limits while the engine leaf supplies dialect-specific extraction, ordered aggregation, and key removal; PostgreSQL JSONB normalization is explicitly documented. (src/infra/database-engine/json-values.ts:35, cfa039480e51)
  • Accepted direction and bounded scope: The accepted design record supports engine-neutral queries; the PR explicitly leaves shared-state PostgreSQL activation and end-to-end conformance to separate admission work. Public docs: docs/reference/database-schemas/storage-changes.md. (docs/reference/database-schemas/storage-changes.md:59, cfa039480e51)
  • CI failure classification: Live annotations confirm matching cron-migration and media-retention failures on main. The UI failure uses a mock Gateway, the session CLI fails during runtime-config preparation, and the Slack timeout remains unattributed rather than proven inherited. The PR records its authorized CI exception. (cfa039480e51)

PR surface

Source +152, Tests +51, Docs +1, Other +10. Total +214 across 20 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 15 258 106 +152
Tests 3 63 12 +51
Docs 1 28 27 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 1 12 2 +10
Total 20 361 147 +214

Review metrics

Metric Value Why it matters
Production versus test LOC Production TypeScript +258/-106; tests +63/-12. Growth primarily replaces compact dialect-specific SQL with typed portable builders and shared JSON primitives; the added coverage exercises publication and invalid-key contracts.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Useful experimental-backend preparation with preserved SQLite defaults and no demonstrated urgent regression in supported user workflows.
  • 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.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-12T17:55:46.407Z sha 808cbe3 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T18:19:37.372Z sha 661a90e :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T18:58:32.789Z sha 0a21a9a :: needs changes before merge. :: [P2] Attach raw-SQL allowances to the tagged expressions
  • reviewed 2026-10-12T19:37:04.653Z sha cfa0394 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T20:05:05.920Z sha cfa0394 :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 4:15 PM ET / 20:15 UTC (Revision 6).

Replace transcript-specific engine helpers with generic JSON primitives.
Keep field keys in the transcript owner, use real connection types, and
document PostgreSQL JSONB normalization after verifying parsed consumption.

Preserve compiled SQLite statements and bindings.

Refs #169254, #169933.
@steipete
steipete marked this pull request as ready for review October 12, 2026 18:41
@clawsweeper

clawsweeper Bot commented Oct 12, 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.

@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts labels Oct 12, 2026
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@steipete
steipete merged commit ecffb99 into main Oct 12, 2026
146 of 152 checks passed
@steipete
steipete deleted the pgprep/p33-pr4a-portable-sql branch October 12, 2026 20:17
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…claw#170055)

Replace SQLite-specific shared-state consumer SQL with portable owner-built statements and engine-owned JSON fragments. Preserve SQLite retention, projections, publication, and update behavior.

Regenerate the database worker inventory and classify the portable SQL guard boundaries. PostgreSQL activation remains behind separate admission work.

Reviewed owner proof covers SQLite behavior and 20 PostgreSQL PREPARE/EXPLAIN statements. Required CI exceptions and the unverified Slack timeout comparison are documented in the PR body.
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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