Skip to content

perf(database): PostgreSQL replica reuse parity — scoped commit revisions and read snapshots - #175498

Merged
steipete merged 6 commits into
mainfrom
pgprep/pg-reuse
Oct 17, 2026
Merged

steipete merged 6 commits into
mainfrom
pgprep/pg-reuse

Conversation

@steipete

@steipete steipete commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

PostgreSQL invalidates session replicas after unrelated or empty transactions, repeating database work on warm Gateway turns.

User Impact

Warm PostgreSQL turns can reuse unaffected replicas. Pure worker reads use read-only snapshots; transactions that may write still take the eager store advisory lock before reading. No configuration, schema, durability, or SQLite token-format change.

Why This Change Was Made

Reuse the existing scoped receipt owner at PostgreSQL mutation and settlement boundaries instead of publishing a broad revision for every COMMIT. Transactions with no mutation publish no revision. Uncertified raw writes and schema work retain broad invalidation. Modifying CTE DML can borrow certified owner scopes; SELECT INTO remains broad. Attempted writes retain SQLite’s monotonic cache witness across rollback, and unknown outcomes retain conservative invalidation. Per-connection pending-write ownership prevents an idle read handle from settling another handle's write on a shared anchor.

The PostgreSQL bridge retains mutation evidence across SQL batches, including a trailing SELECT. It also returns the existing backend transaction status after each successful query, so a batch ending in COMMIT settles immediately and a transaction opened later in a batch stays pending. No extra SQL is issued; error and unknown-outcome handling are retained. The existing placeholder lexer distinguishes scoped modifying CTE DML from schema-changing SELECT INTO, including mixed batches. Qualified keyword columns stay pure reads; quoted identifiers and numeric literals are consumed as tokens so they cannot hide a following SELECT INTO. Pending scoped tokens now predict the same receipt that COMMIT publishes, using the existing SQLite composition unchanged.

Switch 21 clearly pure read callsites to the existing snapshot owner. Keep repairing/callback-uncertain deferred paths and maintenance metadata settlement callbacks intact; empty metadata transactions no longer invalidate replicas.

Evidence

Matched synthetic Gateway census on PostgreSQL 17 with pgvector; same frozen provider fixture and one-second settle as the earlier campaign. Traced request values are per warm turn, separate from full windows that include detached/background work. The matched baseline c7640b58060 and measured head 02db95bb276 each have three warm windows. The subsequent read-snapshot mutation guard is at 035edd3749b; its final SQLite warm replay passed, and prior PostgreSQL performance results retain their measured revision. Earlier candidate replays remain separate prior-head evidence and are not pooled with the final head. Both use Node 24.22.0. The traced path improves, but SQLite request parity is not reached, and full-window database work increases. The completed coordinator review authorizes landing this scoped change; the remaining work is separate follow-up.

Engine / source Worker requests Client round trips SQL MAIN SQL
PostgreSQL historical campaign 49.4 193.4 214.4 0
PostgreSQL matched main (c7640b58060) 44.00 174.67 193.67 0
PostgreSQL measured (02db95bb276) 36.33 154.67 173.67 0
SQLite matched main 16.33 — 61.33 0
SQLite measured (02db95bb276) 16.33 — 61.33 0

Traced requests decrease 17.4%, round trips 11.5%, and SQL 10.3%. Full-window values below include detached/background work and overlap the traced values; they are not additive.

PostgreSQL full warm window Worker requests Client round trips SQL MAIN SQL
Matched main 61.00 231.33 258.33 0
Final (02db95bb276) 67.00 257.67 283.67 0

A separately labelled diagnostic run observed scoped session writes and confined broad raw-write publications to the state database; it found no broad agent-store settlement in those warm windows. Remaining PG-only work includes transcript anchors/hydration, activity summaries, ACP metadata, history, and detached row/membership/shared-fact refreshes. This PR does not establish their remaining invalidation cause or claim end-to-end work parity.

PostgreSQL C=64, five turns per session Successful / requested Failed / unattempted Turns/s p95 ms Read-invalidated errors
Matched main 312 / 320 2 / 6 0.793 94,224.2 1 confirmed log occurrence
Final (02db95bb276) 320 / 320 0 / 0 3.171 24,079.8 0

No timeouts occurred in either C=64 run. The final candidate completed in 100.928 seconds. p95 is end-to-end latency among successful turns; throughput is successful turns divided by stage wall time. Final throughput is 4.00× the observed baseline, with 74.4% lower p95. These are shared-host observations: initial one-minute host load was 18.29 for the final candidate versus 50.28 for baseline, so the timing difference is not an isolated causal speedup. Both the invalidation class name and message fragment were checked; the baseline has one confirmed occurrence and the final candidate has none. All 320 final turns invoked session_status successfully, and every result named the final build. The earlier 96e11490d7e replay also completed 320/320 turns, at 2.821 turns/s and 27,715.1 ms p95; that result remains separate prior-head evidence.

Focused proof: 45 final-head SQLite receipt/scoped-token/commit-receipt/transaction tests, plus an earlier 92-test mixed-engine receipt/transaction/worker run; 53 PostgreSQL lexer/connection/reuse/locking tests plus 38 earlier decoder/connection checks after narrowing the decoder contract; three affected Workboard rollback/terminated-session cases. The concurrent deferred increment regression holds the eager lock before the first read and commits both updates without deadlock. Empty commits preserve unrelated scoped replicas. Live tests cover raw and scoped modifying CTEs, SELECT INTO, pending-to-committed tokens, shared-anchor read-handle close, completed/open transaction batches, and connection loss. SQLite exact transaction statement captures passed. The final-head SQLite Gateway repeats the baseline windows exactly: 62 SQL / 17 requests / 0 MAIN, then 61 / 16 / 0 twice; every normalized native SQL statement and count matches per phase. Core and infra test typechecks and targeted lint pass on the corrected source. Autoreview is scoped-clean through P2 after the final correction.

Initial CI exposed two Workboard assertions that expected rollback to preserve cache revisions. They now require SQLite’s existing monotonic attempted-write invalidation while preserving exact committed-row and known-versus-unknown outcome checks. The three affected cases pass locally. Hosted review also caught transaction-batch settlement and qualified-keyword false mutation hints; both have base-failing/live-head-passing regressions. Independent review caught quoted-name and numeric-literal SELECT INTO boundaries during the lexer repair; both were reproduced live and fixed before committing. A later infra CI run exposed the analogous old PG-only rollback expectation in the session-actor suite; the affected case now passes on both SQLite and PG, preserving durable data, authority-refusal, reopened state and transcript assertions. Final-head CI follows. No failed CI run was blindly rerun.

Footprint: 31 files, +459/-122, net +337 lines (production +82, tests +248, docs +7).

The changed-file test-type selector encountered main's existing root-budget limits (gateway-root 721; infra 733; limit 720). No test roots were added. The narrow core and infra compiler graphs pass; CI remains the broad proof.

SELECT-only caller audit (candidate line numbers)
File Lines
src/agents/auth-profiles/inline-usage.worker.ts 48
src/config/sessions/session-accessor.sqlite-branches.worker.ts 19
src/config/sessions/session-accessor.sqlite-maintenance-transaction.ts 72
src/config/sessions/session-accessor.sqlite-transcript-reports.worker.ts 105
src/config/sessions/session-accessor.transcript-range.worker.ts 158
src/config/sessions/session-entry-cohort.worker.ts 79, 231
src/config/sessions/session-entry-list.worker.ts 187
src/config/sessions/session-entry-read.worker.ts 628
src/config/sessions/session-history-read-operation.worker.ts 174
src/config/sessions/session-memory-entry.worker.ts 59
src/config/sessions/session-pending-input-history.kernel.ts 38
src/config/sessions/session-pending-input-source.kernel.ts 22
src/config/sessions/session-transcript-maintenance-read.ts 50, 92
src/config/sessions/session-transcript.worker.ts 190, 452
src/infra/restart-sentinel.read.worker.ts 15, 28
src/sessions/session-state-events.read.worker.ts 98
src/state/openclaw-state-read-session-rows.worker.ts 41

Routing-only follow-ups: session-lifecycle-projection.worker.ts:202 can repair canonical entries. session-accessor.sqlite-projection-read.ts:503, session-transcript-anchor-read.kernel.ts:356, session-accessor.sqlite-read.ts:202,352,385,417, and session-canonical-key.ts:162,338 retain callback/admission composition needing owner review.

Receipts review follow-up

The receipts owner gave REVIEW-OK through the coordinator. A follow-up prevents a read snapshot from publishing a sibling writer's pending receipt when raw SELECT SQL trips the mutation lexer (for example, an unquoted merge column). The connection tracks its read-only transaction and rejects any classified mutation before write bookkeeping. The live regression fails before the fix and passes afterward; it checks that the writer's pending token remains private and the real COMMIT publishes it. The SELECT-call write-function classification requirement is documented; the current inventory contains no such function.

The follow-up passes 54 targeted PostgreSQL tests, 45 SQLite receipt/token/transaction tests plus 18 mixed transaction/statement-capture tests, core/infra type checks, targeted lint/format, and independent autoreview through P3. Its exact-head Node 24.22.0 SQLite Gateway warm replay is 62 SQL / 17 requests / 0 MAIN, then 61 / 16 / 0 twice, identical to baseline. Every normalized statement/count map matches per phase; artifact hashes identify 035edd3749b.

Shard-14 attribution

The earlier local baseline c7640b58060 was not the base that CI executed. Run 39036252400 checked out merge 8fc7cf12666a61ae08b70c4de6e560fda29d3bc6, whose main parent is 9c26ee3d6f581bf473dbe21a2a29b7dcf8e7aef1 and PR parent is 02db95bb27630f2e32ff269b61ca078707c6a1ad.

With isolated frozen installs and the same pinned Bun four-worker archive group, both exact merge and exact main parent fail the archived-list assertion at line 79 with materializedCount expected 3 / actual 0; each finishes 27/28 tests. That signature is inherited. The exact Node diagnostics replay also fails both assertions on both refs: each finishes 5/7 tests and reports materializedRowCount expected 0 / actual 1 and reusedRowCount expected 1 / actual 0. All three original shard-14 signatures are therefore inherited from the main parent; no passing replay is used for that attribution.

Original failure Exact CI merge 8fc7cf12666 Exact main parent 9c26ee3d6f5
Archived list warm count FAIL: expected 3 / actual 0 FAIL: expected 3 / actual 0
Diagnostics slow warning FAIL: materialized/reused 1/0 instead of 0/1 Same failure
Diagnostics concurrent traces FAIL: materialized/reused 1/0 instead of 0/1 Same failure

Archive replay: pinned Bun, vitest.gateway-methods.config.ts, four workers, the CI three-file group (chat.abort-errors, sessions-list-archived, sessions-sharing.identities). Diagnostics replay: Node 24.22.0, vitest.gateway-database-workers.config.ts, two workers, only sessions-read-diagnostics.test.ts. Both worktrees use isolated frozen-lockfile installs and remain source-clean. Linux Testbox capacity queued and was stopped; the exact-ref reproductions above ran on macOS. The archived and diagnostic assertion bytes match the Linux CI failures.

Source inspection finds no loss of the named SQLite publication scopes: top-level read snapshots call the same deferred transaction helper, and the explicit surrounding post-commit scopes remain. No assertion was weakened or read-owner conversion reverted on the basis of a passing replay.

Final-head CI

Head 035edd3749bbd8afc8f32d4367117ee3116f5774 is READY and unmerged. CI run 39038871417, after one failed-job recovery, has 59 successful jobs, 24 skipped, and no failures. Its exact merge is 0a8aa289d6597e3b8133d01ce5797e04384b0728, main parent d23cd5d48f80a960d1851dceb05ac94f9d015f71.

Final-head check Final result
PostgreSQL conformance: infra PASS: 436 tests, 72 files; attempt 2
PostgreSQL conformance: integrations PASS: 408 passed / 37 skipped; 49 passed files / 4 skipped; executed in attempt 1
Original archived/diagnostics files, now in changed shard 18 PASS: archived 4/4 and diagnostics 7/7
Changed shard 14 PASS; regrouped, does not contain the original two files
Types, lint, build, docs, security, other executed test shards and gates PASS
Aggregate CI gate PASS

The first infra attempt passed 434 tests and failed two in Git backup: its long case exceeded the fixed 120-second deadline, then the next case hit state-owner contention. That case took 109.885 seconds in the preceding successful PG CI run. The backup implementation, test and key ownership fixtures are byte-identical between the original and final CI main parents; indirect main changes are not established as causal. Both cases share suite state, so an overlapping timed-out operation makes the subsequent contention plausible.

The unchanged final-head file passes focused PG17 replays under pinned Bun (16.722s and 4.220s; 46.32s total) and Node 24.22.0 (54.723s and 7.622s; 99.96s total). Those are macOS observations, not identical Linux reproduction or a code fix. Based on the fixed-deadline failure, prior near-deadline CI pass and complete focused replays, only failed CI jobs were rerun once as timing-flake recovery. The same head passed: the two Git-backup cases took 96.241s and 15.060s, and all 436 infra tests passed. No source, timeout, assertion or baseline was changed for the recovery; the original failure remains recorded.

Hosted review also identified connection loss after an embedded COMMIT in a SELECT-leading raw batch. The original baseline and exact CI main parent already use the same outcome classification and skip invalidation in the reported lost-reply case. That separate inherited gap is recorded for follow-up; no runtime reproduction or repair is claimed. The existing standalone-COMMIT safeguards remain intact.

A fresh hosted review was requested for this head; independent autoreview is already clean. The disposable local PG17 cluster was stopped, verified inactive, and only its exact data directory removed. All worktrees and proof artifacts remain for the coordinator. The completed coordinator review authorizes landing this scoped change; the remaining work is separate follow-up.

Landing decision

The coordinator gate is complete for 035edd3749bbd8afc8f32d4367117ee3116f5774: scoped receipts and read-snapshot mutation refusal are accepted; the eager writer lock stays. The receipts review is REVIEW-OK, shard-14 attribution is satisfied by matching failures on the exact CI merge and its main parent, and independent autoreview is clean. Final-head CI run 39038871417 attempt 2 is successful, including both PostgreSQL shards and openclaw/ci-gate. No current CI exception is needed. The prior Git-backup timing-flake recovery and inherited shard-14 evidence remain recorded above.

Publish only mutation-backed PostgreSQL receipts, reuse pure read snapshots, and keep raw-write and unknown-outcome invalidation. Preserve eager deferred writer locking and prove scoped, empty-commit, shared-anchor and concurrent read-then-write behavior.
@clawsweeper

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 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-17T14:04:34.334191Z 035edd3 New commits
ℹ️ 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.

@github-actions

github-actions Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 035edd3749bbd8afc8f32d4367117ee3116f5774
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/inline-usage.worker.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: M labels Oct 17, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 70413815ed

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/infra/postgres-sync/connection.ts Outdated
Comment on lines 247 to 248
if (/^\s*(?:COMMIT|ROLLBACK)\s*;?\s*$/i.test(sql)) {
this.isTransaction = false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Settle writes when a batch ends its transaction

When a caller submits a complete batch such as BEGIN; INSERT ...; COMMIT, PostgreSQL commits it, but this standalone-only check leaves isTransaction true. The detected mutation therefore remains pending instead of publishing its cache-invalidating receipt, and the next managed transaction tries SAVEPOINT against an idle backend and fails. Use the returned trailing command/transaction status to recognize transaction-ending batches and settle the write immediately.

AGENTS.md reference: AGENTS.md:L70-L70

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR gives PostgreSQL scoped replica invalidation and moves pure worker reads to read-only snapshots.

Example: A transaction updates session scope second while scope first has a cached replica.

  • Before: The PostgreSQL commit invalidates both scopes, including after an empty transaction.
  • After: Only second advances after its write; first and empty-transaction revisions remain unchanged.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful final-head runtime evidence supports scoped reuse, but the aggregate performance benefit remains unresolved.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The final-head body records the changed PostgreSQL owners exercised through an isolated Gateway on PostgreSQL 17: matched warm turns, 320/320 concurrent turns with successful session_status calls, no observed actor-invalidated errors, and identical SQLite statement captures; live PostgreSQL regressions cover scoped receipts, read snapshots, rollback, locking, and connection loss.
Patch quality 🦐 gold shrimp (3/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Warm PostgreSQL turns repeat database work because empty or unrelated transactions invalidate reusable session replicas.
Reason: The maintainer-authorized direction restores scoped reuse through existing owners, with broader parity explicitly left unfinished.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: this useful maintainer-owned optimization resolves the earlier findings, while the explicit merge pause remains warranted.

Priority: P2
Reviewed head: 02db95bb27630f2e32ff269b61ca078707c6a1ad

Before merge

  • Resolve merge risk - Explain or eliminate the matched full-window increase from 61 to 67 worker requests and 258.33 to 283.67 SQL statements before lifting the existing merge hold.
  • Complete next step - Investigate the three failures in changed-test shard 14 under its Linux configuration and establish whether they are caused by this diff before selecting a repair or inherited-failure disposition.

Findings

None.

Agent review details

How this fits together

Database workers execute session and state operations through the PostgreSQL bridge, then publish anchor receipts that determine whether cached replicas remain reusable.

flowchart TD
  A[Gateway operations] --> B[Database workers]
  B --> C[Read snapshot or write transaction]
  C --> D[PostgreSQL bridge]
  D --> E[PostgreSQL store]
  D --> F[Scoped anchor receipts]
  F --> G[Session replicas]
Loading

Technical review

Best possible solution:

Retain the scoped receipt implementation while resolving the aggregate-work increase and the failed Linux check before advancing this PR.

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

Current main publishes a broad anchor revision for every successful COMMIT, directly explaining invalidation after empty or unrelated transactions; this review did not execute target code.

Is this the best way to solve the issue?

Reusing the existing scoped receipt and snapshot owners addresses the observed invalidation without a competing cache mechanism, although the measurements do not establish overall work parity.

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Resolve the aggregate-work increase (recommended)
    Trace the additional detached refresh work and reduce it or establish why the measured increase is unrelated to this change.
  2. Keep the optimization paused
    Preserve the useful scoped changes while the broader PostgreSQL work reduction remains unfinished.

Provenance checked

  • PostgreSQL commit receipts changes intended behavior with a stated reason (9dc6466: The shared experimental engine adapter published anchor receipts so PostgreSQL transaction outcomes invalidated existing caches.)
  • Attempted-write mutation witnesses keeps the original intent (1e2d50c: Agent engine selection added PostgreSQL mutation witnesses matching SQLite's monotonic invalidation across rollback.)
  • Consistent multi-read session snapshots keeps the original intent (89a3add: Multi-statement transcript, authorization, and session cohorts retained consistent snapshots while live effect owners retained authority checks.)
  • Exclusive PostgreSQL transport reuse keeps the original intent (9a35d1a: Idle transport reuse avoided repeated connection establishment while active transactions retained exclusive connections and were discarded on close.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source +74, Tests +217, Docs +6. Total +297 across 31 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 22 166 92 +74
Tests 8 247 30 +217
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 31 419 122 +297

Review metrics

Metric Value Why it matters
Production versus test growth Production net +74 lines; tests and support net +217 lines. Growth primarily covers scoped settlement, SQL classification, and real PostgreSQL transaction and locking regressions.
Matched PostgreSQL work Traced SQL 193.67 → 173.67; full-window SQL 258.33 → 283.67. Foreground savings do not establish an aggregate database-work improvement.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.

Label justifications:

  • P2: This improves an experimental PostgreSQL performance path without evidence of an urgent released-user regression.
  • merge-risk: 🚨 other: Aggregate PostgreSQL database work increases in the matched measurements despite lower traced foreground work.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Identify the source of the additional full-window database work and demonstrate the intended overall benefit.

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-10-17T12:21:33.222Z sha 7041381 :: needs changes before merge. :: [P2] Settle pending invalidations when a SQL batch commits | [P2] Align Workboard assertions with conservative rollback invalidation
  • reviewed 2026-10-17T13:02:10.168Z sha a32b7b2 :: blocked before merge. :: [P3] Exclude qualified identifiers from mutation hints

Reviewed October 17, 2026, 9:52 AM ET / 13:52 UTC (Revision 3).

Keep modifying CTE DML inside its certified owner scope while SELECT INTO and uncertified raw writes retain broad invalidation. Align Workboard rollback assertions with SQLite’s monotonic mutation witness, retaining row persistence and known-versus-unknown outcome checks.

Validation: 47 focused PostgreSQL tests, three affected Workboard cases, targeted typecheck and lint, and scoped-clean autoreview through P2.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 96e11490d7

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/infra/postgres-sync/protocol.ts Outdated
Comment on lines +101 to +103
mutation === undefined &&
/^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(keyword) &&
!(keyword === "UPDATE" && (previousKeyword === "FOR" || previousKeyword === "KEY"))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Invalidate writes performed through SELECT functions

When writable raw SQL invokes a side-effecting PostgreSQL function—such as SELECT mutate_rows()—the server reports SELECT, and this keyword allowlist also produces no mutation hint. A later standalone COMMIT therefore finds no pending write, publishes no receipt, and leaves cached snapshots stale even though the function changed rows. Such unclassifiable statements need conservative invalidation or must be rejected in writable transactions.

AGENTS.md reference: AGENTS.md:L70-L70

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a32b7b2f0e

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +102 to +106
mutation === undefined &&
/^(?:INSERT|UPDATE|DELETE|MERGE)$/.test(keyword) &&
!(keyword === "UPDATE" && (previousKeyword === "FOR" || previousKeyword === "KEY"))
) {
mutation = "scoped";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict DML hints to actual write clauses

Because this lexer classifies every unquoted INSERT, UPDATE, DELETE, or MERGE token, a read that uses one as an identifier—such as SELECT t.update FROM status AS t—is reported as a scoped mutation. execute() consequently advances mutationRevision and publishes a writer receipt when the read-only transaction rolls back, invalidating otherwise reusable replicas despite no write occurring. Parse these keywords only in statement/CTE command positions rather than treating arbitrary words as mutation evidence.

AGENTS.md reference: AGENTS.md:L70-L70

Useful? React with 👍 / 👎.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Both prior findings are addressed. Workboard rollback assertions retain committed-row and outcome checks while matching monotonic attempted-write cache invalidation. The batch settlement regression now reproduces the stale transaction-state defect before the fix and passes with the bridge returning PostgreSQL's existing backend transaction status after successful queries.

Final head: a32b7b2. Focused PG, type, lint, independent review, exact SQLite statement comparison, warm census, and C=64 proof are complete; the PR body has the final-head tables and remaining parity limitation. Both PostgreSQL CI shards are running. Do not merge.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Oct 17, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 02db95bb27

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const autocommitWrite = !wasTransaction && mutated;
if (result.command === "COMMIT" || autocommitWrite) {
// All confirmed commits advance the anchor, including callers using raw SQL.
if (!this.isTransaction && (mutated || wasTransaction)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Settle committed prefixes before retaining a later transaction

When a compound query commits a mutation and then opens another transaction, such as BEGIN; INSERT ...; COMMIT; BEGIN, result.inTransaction is true, so this condition leaves pendingWrite unsettled even though the insert is already durable. Other handles can consequently reuse stale scoped snapshots for the lifetime of the new transaction; track and settle the committed prefix rather than gating every mutation on only the trailing server status.

AGENTS.md reference: AGENTS.md:L70-L70

Useful? React with 👍 / 👎.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Final head: 02db95b. The qualified-keyword read classification finding is fixed, with live regressions for qualified columns and quoted/numeric SELECT INTO boundaries. The session-actor rollback assertion now matches SQLite's monotonic attempted-write invalidation; durable data and authority checks remain exact.

The body now contains the completed final-head warm census and C=64 replay: 320/320 successful turns, no actor invalidation, and unchanged SQLite statement captures. It also preserves the full-window work increase and explicitly makes no parity or isolated timing-speedup claim. PostgreSQL CI shards are running; the three session projection count failures in changed-test shard 14 remain under investigation. No merge is requested.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 17, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 035edd3749

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines 245 to 246
{ operation: "query", sql, parameters },
!wasTransaction || /^\s*COMMIT\b/i.test(sql),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat embedded commits as outcome-unknown

When the connection is already in a transaction and a compound request contains a later commit—for example, SELECT 1; INSERT INTO entries VALUES (1); COMMIT—this passes false because the SQL does not start with COMMIT. If the connection drops after PostgreSQL commits but before returning the response, the inserted mutation has not yet set pendingWrite, so loseConnection() publishes no receipt and cached snapshots can remain stale; batches capable of committing need the same unknown-outcome handling as standalone commits.

AGENTS.md reference: AGENTS.md:L70-L70

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a real pre-existing raw-batch outcome gap, rather than an introduced regression. I compared the original baseline c7640b5 and the exact main parent of the original failed CI run, 9c26ee3. Both already pass !wasTransaction || /^\s*COMMIT\b/i.test(sql) to request, and both only invalidate on connection loss when that flag is true. For a transaction whose first write is in the reported SELECT-leading compound request, the lost reply already bypasses the baseline's confirmed-COMMIT publication. This PR preserves that classification and its standalone-COMMIT safeguards. I am recording embedded-COMMIT loss classification as a separate follow-up; no runtime reproduction or fix is claimed here. The PR remains explicitly unmerged.

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Head: 035edd3. The receipts owner confirmed REVIEW-OK through the coordinator. The new read-snapshot mutation guard preserves a sibling writer's pending receipt until real COMMIT, with a live regression that fails before the guard and passes afterward. SELECT-called write-function classification is documented.

All three original shard-14 assertion signatures reproduce on exact CI merge 8fc7cf12666a61ae08b70c4de6e560fda29d3bc6 and its main parent 9c26ee3. The two original files now pass 11/11 in final-head shard 18. SQLite statement maps and steady warm counts remain unchanged. Independent review is clean.

Final-head PG integrations passed. Infra hit a fixed 120-second Git-backup timeout followed by contention; unchanged focused Bun and Node 24 replays pass, and one failed-only timing recovery is running. The body preserves that failure and the increased full-window PG work. No parity claim or merge is requested.

@clawsweeper

clawsweeper Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete
steipete merged commit 271f240 into main Oct 17, 2026
269 of 272 checks passed
@steipete
steipete deleted the pgprep/pg-reuse branch October 17, 2026 14:49
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 18, 2026
…ions and read snapshots (openclaw#175498)

* perf(database): restore PostgreSQL scoped replica reuse

Publish only mutation-backed PostgreSQL receipts, reuse pure read snapshots, and keep raw-write and unknown-outcome invalidation. Preserve eager deferred writer locking and prove scoped, empty-commit, shared-anchor and concurrent read-then-write behavior.

* fix(database): retain certified PostgreSQL CTE write scopes

Keep modifying CTE DML inside its certified owner scope while SELECT INTO and uncertified raw writes retain broad invalidation. Align Workboard rollback assertions with SQLite’s monotonic mutation witness, retaining row persistence and known-versus-unknown outcome checks.

Validation: 47 focused PostgreSQL tests, three affected Workboard cases, targeted typecheck and lint, and scoped-clean autoreview through P2.

* fix(database): settle PostgreSQL transaction batches from server state

* fix(database): distinguish PostgreSQL names from mutation keywords

* test(database): align actor rollback witnesses across engines

* fix(database): reject mutations in PostgreSQL read snapshots
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. plugin: workboard proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. security-sensitive-changed size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant