Skip to content

fix(database): prevent PostgreSQL failures in ancillary stores - #183296

Merged
steipete merged 4 commits into
mainfrom
pgprep/pgportguard
Oct 25, 2026
Merged

steipete merged 4 commits into
mainfrom
pgprep/pgportguard

Conversation

@steipete

@steipete steipete commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Related: #183044, #183172

What Problem This Solves

Fixes PostgreSQL failures in skill usage, proxy capture, MCP OAuth prefix lookup, transcript search and deduplication, voice-session lookup, and legacy audit/debug-proxy migration when those paths emit SQLite-only SQL.

User Impact

These PostgreSQL paths preserve their existing SQLite results instead of failing during statement parsing or execution. This is PostgreSQL-readiness preparation: no SQLite runtime behavior, schema, configuration, dependency, admission, or transaction change.

Why This Change Was Made

One dialect owner now supplies numeric extrema, literal substring position, and NULL-safe equality. Voice lookup reuses the existing JSON dialect owner and retains the literal paths used by SQLite partial indexes. Existing inline node-settlement extrema and ACP accounting clamping also move to the shared owner.

All extrema operands here are non-NULL. The helper documents that SQLite scalar min/max propagate NULL while PostgreSQL least/greatest ignore NULL; nullable callers must coalesce explicitly. Skill upsert references are qualified to remove PostgreSQL's target/excluded ambiguity, and debug-proxy session aliases are quoted so reimport comparisons retain their field names.

This is phase 1 of the portability census. Protected session owners and the static guard are deliberately deferred to the final PR; cron repair is routed to its active owner. No allowlist of known defects is introduced.

Evidence

  • Registered owner-boundary regressions on real Homebrew PostgreSQL 17 and SQLite. Before: SQLite 10/10 passed; PostgreSQL failed the intended statements across all eight defective owners. Voice required documented search extensions before its valid RED (json_valid(text)); that setup failure is excluded from SQL proof.
  • Baseline PostgreSQL errors: missing instr and scalar min, non-NULL IS syntax, GLOB, json_valid, and ambiguous skill-upsert columns. Tests retain literal %/_ matching, out-of-order timestamps, nullable utterance deduplication, malformed JSON filtering, and repeated migration idempotence.
  • Post-fix focused proof: 6 files / 38 tests passed on both engines, including existing node-settlement and ACP retention conformance; Vitest 111.62 s. Production and infra-test typechecks, scoped lint, Kysely guardrails, formatter, and the existing dialect ratchet pass. All three full PostgreSQL conformance shards passed on final head 8faec4a3ab5ac2958c8acd1ab9a35a1179d65359 through Testbox: 180 files / 1,230 tests passed, with 3 files / 39 tests intentionally skipped (the SQL-probe SQLite arm and existing Workboard native-only checks). Shards took 445.39 s, 617.17 s, and 376.76 s; total remote command 24m21.686s. This proof was obtained while the PR was draft, using the canonical conformance runner directly with production and runner sources verified against that head. Subsequent changes are limited to wrapper inventory and the assertion-safety allowance.
  • pr-simplify completed. Production delta: +217/-75 lines; new owner regression tests and registration: +526 lines. Shared dialect spelling replaces leaf implementations; remaining growth is the four construct helpers and real two-engine regressions.
  • Independent isolated Codex autoreview: P0–P3 scoped-clean, repeated after the one-line lint repair; both complete passes exited 0.

Per-file test cost, each run as pnpm test <file> --maxWorkers=1 on the same Testbox (SQLite control; PG variants run separately above):

File under src/infra/database-engine/ Wall time
scalar-portability.conformance.test.ts 28.35 s
text-comparison.conformance.test.ts 25.35 s
migration-sql.conformance.test.ts 25.01 s
voice-lookup.conformance.test.ts 25.05 s

Full PostgreSQL proof command, each shard run sequentially against a disposable PostgreSQL 17.11 container on the same Blacksmith Testbox:

node scripts/test-database-conformance.mjs --engine postgres --connection postgresql://[email protected]:55432/postgres --shard 1/3 -- --maxWorkers=2
node scripts/test-database-conformance.mjs --engine postgres --connection postgresql://[email protected]:55432/postgres --shard 2/3 -- --maxWorkers=2
node scripts/test-database-conformance.mjs --engine postgres --connection postgresql://[email protected]:55432/postgres --shard 3/3 -- --maxWorkers=2

The initial full-shard source check failed before SQL because a synthetic capsule omitted the original commit object. Fetching the exact pushed SHA and comparing source bytes corrected that setup assumption; the successful run used unchanged production code. The local Homebrew PostgreSQL server and remote PostgreSQL container are stopped.

Final process inventory found and stopped one leftover esbuild process; the follow-up remote inventory was empty.
The single task-owned Testbox lease was stopped through the repository wrapper and independently verified completed, ready=false. Local worktree/runtime process checks and PostgreSQL port checks are empty. Coordinator review approved phase 1; the PR is ready for its exact-head CI and native landing gates. Phase 2 and the final static guard are not included.

Follow-up check repairs

Added the shared scalar helper to the wrapper extraction inventory and reduced the debug-proxy assertion allowance from 5 to 4 after replacing its unsafe assertion with a typed query. Production and conformance-test bytes remain identical to the coordinator-reviewed head.

The two previously failing wrapper extraction cases pass locally (2/2; 93.02 s wall). All baseline ratchets, line cap, coercion helpers, duplicate detection, generated metadata, dependency patches, import cycles, and formatter checks pass on the isolated candidate. No further baseline change was required.

The three local macOS deadcode commands (pnpm deadcode:dependencies, pnpm deadcode:unused-files, pnpm deadcode:exports) report unused declarations/files outside this PR. Running all three again on the exact original base with the same installed dependencies reproduces every path/symbol diagnostic; no changed SQL owner or new helper appears. These local results are recorded as inherited failures, not green checks. The preceding exact-head pull-request CI run completed with only the stale assertion allowance and aggregate gate failing; all three PostgreSQL conformance shards passed. Current-head CI and the additional attribution results are recorded below.

Current-head CI attribution

Pull-request CI run 40174638340, attempt 1, completed on db4d8cd0c2dd7d94a9dbd140c4778df637762e56. PostgreSQL shards 1 and 3 passed. The sole root failure was shard 2, job 121112880812: postgres interactive setup > setup saves interactive setup and releases ownership for a Gateway timed out waiting for PTY exit after authenticated readiness. The aggregate gate also failed.

An alternating three-base/three-candidate comparison used real Homebrew PostgreSQL 17.11 and the unchanged conformance runner, fixture, and deadlines. The base was CI's actual first parent 31d06089615d661c03ee35642626dfddfb234641; the candidate was its tested merge 83fd01d6cf0a2af5782dc241e0312998853e5426. Base: one complete pass and two authenticated-readiness timeouts. Candidate: two complete passes and one authenticated-readiness timeout; that failed candidate fixture also reported ENOTEMPTY during cleanup. None reproduced the CI shutdown timeout. Eight recent scheduled main PG2 runs were checked: seven passed and one failed a different idle-connection-reuse case.

Coordinator review accepts this as diagnosed flakiness in the Gateway PTY test family, not caused by the candidate: base failed 2/3 attempts, candidate failed 1/3, and this diff changes no Gateway lifecycle, PTY, or shutdown code. Readiness and shutdown signatures remain distinct; passing replays are not claimed as a repair. One explicitly authorized failed-job rerun was submitted for run 40174638340. Attempt 2 completed successfully on the same head: all 101 effective jobs completed, with no failures. PostgreSQL shard 2 and the aggregate CI gate passed. No manual workflow was dispatched.

Production and regression-test bytes remain identical to the reviewed head. The normal native merge command was invoked after green CI; it refused before submission because the task-owned clone has no PR review worktree. No admin merge or phase-2 work has been attempted. The five deferred guard files remain uncommitted. All local test processes and PostgreSQL services are stopped.

The initial native landing attempt was blocked on review initialization. From the ordinary checked-out task clone, scripts/pr merge-run 183296 --auto-merge exited 1 with Missing PR review worktree. Run: scripts/pr review-init 183296. The native helper confirmed its operation lock was released and all process-group/notification-pipe holders exited. The coordinator instruction forbids hand-running review-init and requires stopping on a new refusal, so no alternate initialization or merge route was attempted. Coordinator decision 7 subsequently authorized the documented review initialization sequence.

Landed

Merged as a6e32c0a0236472ca1f5b3644604170c4eebea55 at 2026-10-25T10:37:56Z. The native review initialization, checkout, artifact validation, preparation and normal merge sequence all passed on the unchanged approved head. No admin route or manual workflow dispatch was used. GitHub MERGED and main ancestry were independently verified; native cleanup completed successfully. The session-owner fixes and static guard continue in a separate phase-2 PR.

@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 agents Agent runtime and tooling size: L labels Oct 25, 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 Oct 25, 2026
@clawsweeper

clawsweeper Bot commented Oct 25, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR replaces SQLite-specific SQL in ancillary stores with shared dialect helpers while preserving existing store ownership and results.

Example: Skill usage receives timestamps 200, 100, 300, 150, and 300 on PostgreSQL.

  • Before: The conflict update fails on SQLite-style scalar extrema or ambiguous column references.
  • After: Usage records five events, first use at 100, and latest use at 300.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, focused implementation with substantive two-engine owner regressions and no definite introduced defect, but upgrade compatibility remains unproven.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Ancillary operations fail when their existing store queries execute on PostgreSQL.
Reason: The maintainer-authored direction repairs concrete backend failures without adding configuration, schemas, dependencies, or competing owners.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this useful maintainer-authored PR open; current main retains the PostgreSQL failures, and review found no definite introduced bug.

Priority: P2
Reviewed head: 8faec4a3ab5ac2958c8acd1ab9a35a1179d65359

Before merge

  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Supply a redacted latest-stable-to-head upgrade trace through shipped startup or Doctor showing existing capture and transcript data remain intact.
Agent review details

How this fits together

Ancillary store kernels receive usage events, OAuth prefixes, transcript queries, voice lookups, and legacy imports; they execute through existing database owners and return stored records or query results.

flowchart TD
  A[Feature operations] --> B[Existing store kernels]
  B --> C[Shared SQL dialect helpers]
  C --> D[Existing query executor]
  D --> E[SQLite]
  D --> F[PostgreSQL]
  E --> G[Records and results]
  F --> G
Loading

Technical review

Best possible solution:

Keep dialect spelling in the existing database-engine layer and retain each store's current predicates, write ownership, and persisted representation.

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

Current-main source emits the identified SQLite-only constructs, and the PR reports intended PostgreSQL failures before repair; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch follows the smallest complete repair: share dialect constructs, qualify conflicting references, reuse the JSON owner, and preserve existing operation boundaries.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Skill usage, including the former curator.kernel.ts path keeps the original intent (40b0584: Move usage SQL into the shared worker while preserving counts and timestamp ordering; the later Workshop rename retained that upsert.)
  • Proxy capture extrema keeps the original intent (5cc4537: Separate connection-bound capture operations from lifecycle management while retaining session and payload semantics.)
  • MCP OAuth prefix queries keeps the original intent (1b90b88: Move scoped credential and status reads into existing shared-state workers without changing authority or stored formats.)
  • Transcript search and exact retries keeps the original intent (improve: avoid loading transcript revisions for exact retries #146381: Select exact retries in SQL while retaining NULL distinctions, metadata bytes, session scope, and lone-surrogate handling; archive search separately requires literal substring matching.)
  • Voice lookup keeps the original intent (perf(talk): index open voice session lookups #165546: Use partial-index-compatible open-session predicates and exclude malformed or closed records before decoding.)
  • Legacy audit witness and debug-proxy import keeps the original intent (fix(backup): preserve audit capture across slow snapshots #130962: Detect cross-store backup drift; the debug-proxy migration separately preserves legacy data and repeated-import identity.)
  • ACP accounting and node settlement keeps the original intent (fix(database): make unbounded retention portable to PostgreSQL #183044: Preserve zero-clamped byte accounting; the separately merged node settlement repair preserves its timestamp clamp and native postimage.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 40b0584 adds src/skills/workshop/curator.kernel.ts:68 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 40b05842ee82; files: src/skills/workshop/curator.kernel.ts)

PR surface

Source +142, Tests +526. Total +668 across 16 files. Added test files: 4.

View PR surface stats
Area Files Added Removed Net
Source 11 218 76 +142
Tests 5 526 0 +526
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 744 76 +668

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +218/-76 lines; tests and registration +526/-0 lines. Production growth provides four shared SQL constructs and typed migration queries; regressions exercise distinct affected store contracts on both engines.

Labels

Label changes:

  • add P2: The repair addresses concrete SQL failures in several ancillary PostgreSQL paths while SQLite remains unchanged.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.

Label justifications:

  • P2: The repair addresses concrete SQL failures in several ancillary PostgreSQL paths while SQLite remains unchanged.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.

Rank-up moves

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

  • Demonstrate the latest-stable upgrade with existing capture and transcript data preserved.

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, 1:51 AM ET / 05:51 UTC.

@steipete
steipete marked this pull request as ready for review October 25, 2026 06:22
@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-25T06:24:25.020855Z 8faec4a 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.

@github-actions

github-actions Bot commented Oct 25, 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: db4d8cd0c2dd7d94a9dbd140c4778df637762e56
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/mcp-oauth-store.kernel.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.

@steipete
steipete merged commit a6e32c0 into main Oct 25, 2026
288 of 293 checks passed
@steipete
steipete deleted the pgprep/pgportguard branch October 25, 2026 10:37
@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 26, 2026
…law#183296)

* fix(database): make ancillary store queries portable to PostgreSQL

* refactor(database): use typed capture event counts

* fix: include scalar dialect helper in wrapper inventory

* chore: shrink assertion-safety baseline for typed debug-proxy query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts security-sensitive-changed size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant