Skip to content

perf: avoid extra transactions for pending input lookups - #182883

Merged
steipete merged 4 commits into
mainfrom
dbasync/dppragma
Oct 24, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/dppragma

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

chat.message.get opens an explicit read transaction when retrieving one retained pending input. The lookup is already one SELECT, including the current-session scalar and a byte-bounded payload, so BEGIN and COMMIT add two unnecessary SQL statements.

User Impact

Retrieve retained pending inputs with the same content, payload limits, current-session checks, missing-ID behavior and authorization, using one SQL statement instead of three. Count-and-page listings retain their snapshot. There is no schema, cache, write-transaction or worker-routing change.

Why This Change Was Made

Route ID lookups through the existing count-free page path and remove the now-redundant conditional around the listing count. Production diff: +5/−7 lines, net −2; the existing test is +60/−53 (net +7), and the reusable workload/protocol add 126/29 lines. The existing owner regression now covers both count-free context and ID lookup, including visibility of an input committed after an empty read; its SQL counter also captures native exec transaction envelopes. A committed synthetic WebSocket workload reproduces the public flow.

Evidence

Acceptance registered in this PR before the first run:

  • Flow: synthetic retained pending input retrieved over a real isolated Gateway WebSocket using chat.message.get; also check a missing ID.
  • Workload: one cold lookup and ten warm lookups per process, followed by a missing-ID lookup. Keep cold and warm results separate.
  • Metrics: executed SQL statements, worker requests and MAIN statements, including transaction envelopes. Expected native lookup cost 3 → 1 SQL statements, unchanged worker requests and MAIN. Preserve content and missing-input behavior.
  • Broad control: frozen observer v3.1.4, comparing baseline and candidate. Three alternating count pairs when host capacity qualifies; otherwise one pair or explicitly reported source attribution. Report median/p95/range and per-operation differences.
  • Latency/CPU comparisons require five interleaved samples per arm under the timing lock. Counts-only evidence makes no latency or CPU claim. All user-facing metrics must hold or improve; a 20% regression in any measured cell stops the change.

One committed baseline/candidate pair passed all 12 lookups per arm with zero SQL errors: baseline 8704e103e12, candidate df661e7d663. Counts use frozen observer v3.1.4; its 36 frozen files were verified. The observer's causal hook misses the current AsyncContext, so these are phase-file execution windows, not causal-turn attribution. Host 1-minute load was 75.09/86.43; 41/40 per-thread CPU profiles were captured for attribution only. No latency, CPU-speedup or memory claim.

Metric Baseline Candidate
Target SQL per cold / warm / missing lookup 3 / 3 / 3 1 / 1 / 1
Target worker requests per lookup 1 1
Runtime MAIN SQL per lookup 0 0
Ten warm windows: total SQL / requests / MAIN 36 / 12 / 0 10 / 10 / 0
Warm SQL median; p95; range 3; 7; 3–7 1; 1; 1–1
Warm requests median; p95; range 1; 2; 1–2 1; 1; 1–1
Target warm SQL median; p95; range 3; 3; 3–3 1; 1; 1–1
Cold window SQL / requests / MAIN 10 / 6 / 0 10 / 8 / 0
Missing window SQL / requests / MAIN 3 / 1 / 0 1 / 1 / 0
Whole run SQL / requests / MAIN 795 / 189 / 126 716 / 179 / 133

The two raw threshold crossings were inspected and accepted by the campaign coordinator: cold requests 6→8 comprise the same one lookup plus an extra background proactive-job request and execute; shutdown 16/4/6→23/4/13 comprises seven existing gateway-owner-lease.release startup-checkpoint admission reads. Those owners are byte-identical between arms. Boot MAIN is 120 on both, and runtime lookup MAIN remains zero. The saving attributed to this patch is exactly two SQL statements per lookup, with no worker-request saving claimed.

Rerun with a fresh synthetic --state-dir, the frozen observer in NODE_OPTIONS, SQLMEASURE_OUT pointing to a directory containing a phase file, and:

node --cpu-prof --cpu-prof-dir=<profiles> \
  --import ./scripts/lib/gateway-bench-cpu-profile.mjs \
  --import ./scripts/tsx.mjs scripts/perf/pending-input-read-measure.ts \
  --state-dir <fresh-synthetic-state>

Owner and real handler proof: 18 tests passed in session-pending-input-history.test.ts and chat-message-get-handler.test.ts. The ID regression is red on the original code (expected one statement, received three), while the existing context case passes. Two Codex autoreview rounds completed; final diff scoped-clean through P2. Formatting, basic and type-aware lint passed. PostgreSQL review approved the single-statement snapshot semantics. Knip matched baseline exactly: production 67/67, script 1,136/1,136 and full-tree 77/77 findings, with no new findings. CI initially found TS7022 in the benchmark response; final head 501ad566352 adds its explicit result type without changing production or runtime behavior. Local script typecheck stopped before source analysis at the mandated internal virtual-store containment guard; final-head CI passed script/test types, production types and all five core test-type shards. Core lint, source contracts and architecture also passed. Final-head CI run 40136190832 passed all type, lint, contract, architecture, ratchet and build checks. PostgreSQL shards 1/3 and 3/3 passed; shard 2/3 failed seven interactive-setup cases because the synthetic runtime lacks standalone-runtime-profile.mjs, which newer main code imports. That fixture and import are outside this diff. The campaign coordinator explicitly classified this as inherited red main from #182856 (4a38dbdb6b1), assigned the fix to REDMAIN14, and authorized unaffected lanes to land under RELAXED LANDING v4 while citing their failed run/job. This PR touches neither the fixture nor the import. PostgreSQL shard 2 remains failed; no passing claim or rerun is made.

Open-main overlap census covered 2,694 heads. Only #177351 at 4ba6e39ad497b1f2b838f084996fc886862ddf3d overlaps; comparing current main ad9f81409c251b03450a05465e44fd225b8b289c with the integrated candidate gives the same 18 conflict files / 27 hunks, zero added. Its kernel conflicts are in the separate recovery-filter section.

The inventory found no justified warm PRAGMA deletion: equal timeout assignments already skip, while maintenance transitions, pinned snapshots, integrity/recovery checks and nested write savepoints protect real behavior. Unreproduced handoff and transcript-identity candidates remain unchanged.

@clawsweeper

clawsweeper Bot commented Oct 24, 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 scripts Repository scripts size: XS labels Oct 24, 2026
@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. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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-repro Preliminary submission classification; full source review pending. labels Oct 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR documents acceptance criteria for removing redundant transaction statements from pending-input ID lookups.

Example: Retrieve a retained pending input through chat.message.get.

  • Before: The lookup uses BEGIN, SELECT, and COMMIT.
  • After: This document specifies a target of one SELECT; runtime behavior is unchanged.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A sound acceptance document for an unfinished optimization; the rating reflects its partial scope, not its draft status.
Proof confidence 🌊 off-meta tidepool Not applicable: The reviewed head is documentation-only and explicitly records future Gateway verification rather than claiming completed runtime proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Docs · Worth it: Yes · Fix scope: Partial
User problem: Retrieving a retained pending message performs transaction-control work that its single SELECT does not require.
Reason: The maintainer-authored draft follows the performance policy's preregistration requirement and identifies a concrete source-backed opportunity, but supplies only the acceptance plan.

Merge readiness

✅ Ready for maintainer review

Keep this maintainer-authored draft open: its acceptance plan matches current source, and the proposed optimization remains unimplemented; the document introduces no actionable defect.

Priority: P3
Reviewed head: f188e2699f065175e23cc9884e251c3a714bb04e

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway message retrieval delegates pending-input IDs to the session history owner, whose worker returns bounded stored messages and current-session facts.

flowchart LR
A[Gateway WebSocket request] --> B[Message get handler]
B --> C[Pending input history owner]
C --> D[History reader worker]
D --> E[Bounded database SELECT]
E --> F[Message response]
Loading

Technical review

Best possible solution:

Complete the optimization in the existing history kernel while preserving counted-list snapshots, payload bounds, and session checks.

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

Source confirms that ID lookups skip the count but retain the explicit snapshot wrapper; no runtime reproduction or measurement was performed.

Is this the best way to solve the issue?

The plan appropriately reuses the existing single-statement page owner and preserves multi-query listing snapshots; simplification steps 1–3 reveal no unnecessary machinery or test scaffolding.

AGENTS.md: found and applied where relevant.

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

Security

None.

Evidence

What I checked:

PR surface

Docs +29. Total +29 across 1 file. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 0 0 0 0
Tests 0 0 0 0
Docs 1 29 0 +29
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 1 29 0 +29

Labels

Label changes:

  • add P3: The reviewed patch only preregisters a bounded performance improvement and changes no user-facing runtime behavior.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool 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:

  • P3: The reviewed patch only preregisters a bounded performance improvement and changes no user-facing runtime behavior.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool 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 24, 2026, 5:14 PM ET / 21:14 UTC.

@steipete
steipete marked this pull request as ready for review October 24, 2026 21:27
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 24, 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-24T21:29:06.860066Z df661e7 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.

@steipete
steipete merged commit 0e6e231 into main Oct 24, 2026
143 of 148 checks passed
@steipete
steipete deleted the dbasync/dppragma branch October 24, 2026 22:24
steipete added a commit that referenced this pull request Oct 25, 2026
Reduce the durable submitted-input source lookup from five SQL statements to one snapshot-consistent autocommit SELECT on SQLite and PostgreSQL. Keep restart, expired-memory, and attachment duplicate-dispatch protection, with the original bounded recovery transaction unchanged.

The normal new-input path saves four statements without adding a worker request. The accepted rare recovery tradeoff is one additional statement for pending or committed input.

Verified with both-engine count regressions, 56 focused behavior/prompt-prefix tests, three synthetic Gateway baseline/candidate pairs, and PostgreSQL owner review. Exact-head CI passes all static gates; the inherited PostgreSQL shard 2 fixture failure was independently fixed in #182990.

Follow-up to #182334; single-statement precedent #182883.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…2883)

Retrieve retained pending inputs with one bounded SELECT instead of wrapping it in BEGIN/COMMIT. Keep the shared snapshot for count-and-page listings and preserve current-session checks, payload bounds, and authorization.

Synthetic Gateway WebSocket proof: every cold, warm, and missing-ID lookup uses 1 SQL statement instead of 3, with the same worker request and zero runtime main-thread SQL. Owner and handler regression tests cover the public flow.

No schema, cache, write-transaction, or worker-routing change.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…182971)

Reduce the durable submitted-input source lookup from five SQL statements to one snapshot-consistent autocommit SELECT on SQLite and PostgreSQL. Keep restart, expired-memory, and attachment duplicate-dispatch protection, with the original bounded recovery transaction unchanged.

The normal new-input path saves four statements without adding a worker request. The accepted rare recovery tradeoff is one additional statement for pending or committed input.

Verified with both-engine count regressions, 56 focused behavior/prompt-prefix tests, three synthetic Gateway baseline/candidate pairs, and PostgreSQL owner review. Exact-head CI passes all static gates; the inherited PostgreSQL shard 2 fixture failure was independently fixed in openclaw#182990.

Follow-up to openclaw#182334; single-statement precedent openclaw#182883.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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