Skip to content

perf(gateway): reduce redundant approval and placement queries - #168995

Merged
steipete merged 4 commits into
mainfrom
dbasync/t1gateway
Oct 11, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/t1gateway

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Approval transitions and placement moves read rows again after their owner already has the authoritative state. Placement move lookups also retain a synchronous Gateway path despite an existing worker operation. Group-catalog snapshots issue separate queries for order and defaults.

User Impact and Design

Use INSERT/UPDATE RETURNING for approval insert, resolution, denial, consumption, and expiry, and for placement completion/draining. Keep the approval decision and mutation in the same transaction, with the security check intact. Route placement move reads through the existing worker, delete the superseded synchronous readers, and remove redundant internal source/move and membership rereads. Load group order and defaults together. No schema, stored-format, permission, public SDK, update, or lifecycle change.

The lane's source inventory is 43 → 40 T1 expressions on the paired base, and 44 → 41 against the final integrated main parent (which reclassified one retained restart-clear compatibility primitive as T1), excluding the separately owned GitHub publication family. The original 92-call assignment included that family. This is a bounded cutover, not a claim that Gateway T1 has reached zero. Remaining calls need an owner or compatibility redesign: released synchronous placement/standing-grant SDK methods, native approval commit callbacks that must remain atomic, workspace-reservation authority at an external effect, process-held incognito databases, and deprecated synchronous Mention Inbox operations. Their contracts and retirement paths are recorded in worker-access.md; no new compatibility path is added.

SQL Measurement

Three alternating pairs, M/C/M/C/M/C, on one otherwise idle AWS c7a.8xlarge using the shared workload unchanged. Base 18941faa9629ce0a9fa318f979351fd385878850; candidate b60c2bb48c6ba4cafab351b662571bd6d2c7c626. Final head b6df4ae33403643a5e1cddd0658d29493e827bf3 includes two main integrations. Only the generated inventory conflicted; it was regenerated. Upstream placement recovery and SDK deprecation-warning changes merged cleanly. The PR-owned SQL edits remain unchanged, so the paired proof is reused under the campaign integration rule.

Metric per warmed turn Base median [min–max] Candidate median [min–max]
All-thread statements 456.0 [455.2–456.5] 451.0 [450.8–456.5]
Worker requests 90.8 [90.4–91.0] 90.4 [90.4–90.9]
Main-thread statements 4.1 [4.1–4.1] 4.1 [4.1–4.1]
Phase Base statements median Candidate statements median Delta
01.boot 2079 2078 -1
01.connect 944 948 +4
02.first-turn 1315 1307 -8
04.second-session 1808 1808 +0
05.control-plane 104 104 +0
06.cron 674 673 -1
07.compaction 201 201 +0
08.shutdown 100 106 +6

The measured base is already below the 500 warmed-statement aim. The raw warmed median falls by 5.0 statements and 0.4 requests, but that difference comes from unchanged session-owner work (database.prepareWrite, session.turn.commit, exact-entry/row-fact reads). It is not attributed to this PR. The repeatable shared-harness saving is sessionGroups.snapshot: 5 → 4 statements, one request in both versions, during boot. Warmed paths touched by this PR do not add work.

The largest candidate/base phase-duration median ratio is 1.057; warmed duration is 15.780 → 15.796 seconds. First-turn and warmed medians do not rise. Connect +4 and shutdown +6 are within the campaign's absolute non-turn tolerance: unchanged session prewarm/registry timing, audit-prune busy-timeout statements, and agent clean-close bookkeeping account for those deltas. No extra pair was needed.

A separate synthetic probe invokes the public asynchronous approval owner after warming the database, using the same all-thread statement observer. Both revisions produce the expected outcomes:

Operation Base statements Candidate statements Worker requests, both Main-thread statements, both
Insert approval 8 7 1 0
Resolve approval 7 6 1 0
Consume allow-once 7 6 1 0
Force denial 7 6 1 0
Expire one approval 6 5 1 0

Removed Checks and Accepted Edges

  • Approval post-write rereads and duplicate mutation predicates: the initial decision and mutation share one synchronous write transaction, so another writer cannot intervene there.
  • Group membership rereads around admission/commit: the owner serializes membership and mutation; no supported outside writer participates.
  • Placement preparation/recovery source and move rereads: unexpected out-of-band same-session cancellation can allow recoverable preparation before exact worker completion rejects it. Normal moves remain coordinator-serialized. Actual environment/session/policy authority checks at external effects and exact completion predicates remain.

Evidence

  • 329 focused tests across 21 files passed, including placement recovery, current environment authority, approval first-answer/allow-once behavior, write-receipt visibility, group mutation, and destination-authority E2E. The remote node scripts/run-vitest.mjs <21 files> --maxWorkers=1 wall time was 1034.23s, including cold worker compilation/cleanup; Vitest reported 690.58s for the 20-file shard and 77.07s for the E2E shard. No new CI test job was added.
  • SDK compatibility and approval settlement/web-push suites passed; the additional fixture-lifecycle mock test passed on the merged head (4.76s wall time).
  • check:changed passed on the measured candidate, including types, Knip, type-aware lint, source contracts, T1 and dialect ratchets. Madge and export collisions passed. On the merged head, type-aware lint, export collisions, the generated inventory check, Madge, and T1/dialect ratchets passed.
  • Final-head Knip reports only the inherited production unused export src/infra/agent-run-terminal-writes.ts: captureAgentRunTerminalWriteContext; the full-tree and scripts scans pass. The merged-head check:changed stops at the inherited max-lines suppression in src/web-search/runtime.test.ts. Both exact findings were reproduced on main e7e3b949ae134060cc8c2a7cd8d224ad27edcd91 with its frozen dependencies installed; neither affected file nor the relevant baselines/configs are changed by this PR. These are the only static exceptions. Required changed-file static checks were run separately after that stop; no PR-caused static finding remains.
  • Two Codex autoreview rounds completed with no remaining P0/P1 findings. The subsequent correction preserves the existing in-process environment authority check before opening a tunnel and removes no security check.
  • Required CI and security gates passed on the final integrated head b6df4ae33403643a5e1cddd0658d29493e827bf3: CI run 38129718475. Earlier CI failures in the changed code were fixed; the earlier session-files failure also failed in scheduled main run 38122045725 and disappeared after integrating main.
  • Published-driver × candidate update cell is not applicable: no update, Doctor, schema/migration, plugin loading, or service lifecycle changes. No SDK API surface change.

LOC against the integrated main parent: production +137 / −277, tests +128 / −174, docs/tooling +11 / −34, generated inventory +12 / −15; 32 files total.

@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts size: L labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge.

What this changes

This PR reduces repeated approval, placement, and group-catalog queries using returned write rows and existing worker readers.

Example: Resolve approval approval-1 with allow-once, then retry with deny.

  • Before: The transaction validates and updates the approval, then selects its resulting row again.
  • After: The update returns the resulting row directly while the first decision remains authoritative.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) Useful simplification with one unresolved P2 defect and insufficient final-effect authority evidence; inspection verifies no schema or persisted-format migration.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Approval and placement operations perform avoidable database work, including synchronous Gateway reads.
Reason: Recorded owner direction supports this bounded simplification and explicitly accepts recoverable preparation before exact completion rejection.

Merge readiness

⛔ Blocked before merge - 4 items remain

Keep this useful performance PR open; the previously reported selected-database regression remains unresolved.

Priority: P2
Reviewed head: b6df4ae33403643a5e1cddd0658d29493e827bf3

Before merge

  • Add real behavior proof - Authority-chain proof required: the full body and discussion report SQL measurements and passing suites but provide no after-change trace showing allowed node dispatch and rejection before send after parent approval revocation or placement reassignment; provide redacted logs or terminal evidence excluding IPs, API keys, phone numbers, and non-public endpoints. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • Preserve the explicitly selected database in synchronous grant reads (P2) - With databaseOptions: { database: selectedDatabase }, asynchronous binding preparation and retention use selectedDatabase.path, but this reader resolves only path or env and can read the default database instead. A valid retained grant then becomes placement-missing and is deleted during validate or consume, rejecting the launch. Set path from databaseOptions.database.path before falling back to databaseOptions.path, matching readApprovalStore, and cover asynchronous preparation followed by synchronous consumption with a different default store. This previously reported finding remains unresolved.
  • Resolve security review attention item - No privilege bypass was established, but the changed final grant-read boundary requires authority validation.
  • Resolve merge risk - The replacement of the transactional grant reader remains an unverified security boundary change for final node dispatch after parent revocation or placement reassignment.

Findings

  • [P2] Preserve the explicitly selected database in synchronous grant reads — src/gateway/operator-approval-placement-grants.ts:183-185

Tests

  • Missing end-to-end proof: Show allowed node dispatch and rejection before send after parent revocation or placement reassignment, including an explicitly selected database distinct from the default store.
Agent review details

How this fits together

Gateway approval and placement owners process operator decisions and session moves through SQLite workers; their records feed lifecycle recovery and authorization immediately before node transport.

flowchart LR
A[Operator requests] --> B[Gateway owners]
B --> C[SQLite workers]
C --> D[Shared database]
C --> E[Committed publications]
E --> B
D --> F[Final authority read]
B --> F
F --> G[Node transport]
Loading

Technical review

Best possible solution:

Keep the query reductions while preserving the selected physical database and immediate final transport authorization.

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

Source establishes that asynchronous preparation honors databaseOptions.database.path while synchronous consumption can read the default store and invalidate a valid grant; no runtime reproduction was executed.

Is this the best way to solve the issue?

RETURNING and transaction-local fact reuse fit the existing owners, but the synchronous grant reader must retain the same database selection as asynchronous preparation.

Full review comments:

  • [P2] Preserve the explicitly selected database in synchronous grant reads — src/gateway/operator-approval-placement-grants.ts:183-185
    With databaseOptions: { database: selectedDatabase }, asynchronous binding preparation and retention use selectedDatabase.path, but this reader resolves only path or env and can read the default database instead. A valid retained grant then becomes placement-missing and is deleted during validate or consume, rejecting the launch. Set path from databaseOptions.database.path before falling back to databaseOptions.path, matching readApprovalStore, and cover asynchronous preparation followed by synchronous consumption with a different default store. This previously reported finding remains unresolved.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

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

Merge-risk options

Maintainer options:

  1. Hold for authority validation (recommended)
    Keep this PR open until final node-send authority is established for allowed use, parent revocation, and placement reassignment.
  2. Retain the existing transactional grant reader
    Restore the standing-grant read boundary and retain the other approval, placement, and group-catalog query reductions.

Provenance checked

Testing

Proof path: in-process harness.

Security

Needs attention: No privilege bypass was established, but the changed final grant-read boundary requires authority validation.

Evidence

What I checked:

Likely related people:

  • Josh Lehman: Raw commit 28164d0 adds src/gateway/operator-approval-placement-grants.ts:175 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 28164d093498; files: src/gateway/operator-approval-placement-grants.ts)

PR surface

Source -140, Tests -46, Docs +7, Other -33. Total -212 across 32 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 15 137 277 -140
Tests 14 128 174 -46
Docs 2 22 15 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 34 -33
Total 32 288 500 -212

Review metrics

Metric Value Why it matters
Production versus tests Production +137/-277; tests +128/-174 The introduced diff removes redundant reads and obsolete synchronous paths, with net reductions in both production and test code.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This bounded performance improvement has a concrete regression affecting standing grants prepared against an explicitly selected database.
  • merge-risk: 🚨 security-boundary: The changed synchronous reader supplies durable approval and exact placement authority immediately before node transport.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

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

  • Add final-effect proof showing allowed node dispatch and rejection before transport after parent revocation or placement reassignment.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-11T08:04:39.063Z sha adb53cd :: needs real behavior proof before merge. :: [P2] Preserve the explicitly supplied database in synchronous grant reads | [P2] Align the recovery test with the accepted preparation behavior
  • reviewed 2026-10-11T08:34:24.928Z sha b60c2bb :: needs real behavior proof before merge. :: [P2] Preserve the explicitly selected database in synchronous grant reads
  • reviewed 2026-10-11T09:16:30.665Z sha 5ae6f21 :: needs real behavior proof before merge. :: [P2] Preserve the explicitly selected database in synchronous grant reads

Reviewed October 11, 2026, 5:56 AM ET / 09:56 UTC (Revision 4).

@steipete
steipete merged commit ac8a432 into main Oct 11, 2026
142 checks passed
@steipete
steipete deleted the dbasync/t1gateway branch October 11, 2026 09:58
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…law#168995)

Use mutation RETURNING rows for approval transitions and placement completion, route move lookups through the existing worker, and fetch group ordering/defaults together. Remove redundant internal rereads while retaining current authority checks at real effects.

The final Gateway lane inventory falls from 44 to 41 T1 expressions; released synchronous SDK and incognito-owner constraints remain documented. Direct approval probes save one statement per insert, resolve, consume, deny, and expiry operation, with one worker request and no main-thread SQL. Three alternating workload pairs record 456.0 to 451.0 median warmed statements and 90.8 to 90.4 requests; the warm difference is unchanged session-owner timing, not claimed as this change's saving.

Accept recoverable preparation after out-of-band same-session cancellation; exact completion still rejects it. No schema, format, retention, or permission change.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 18, 2026
First-parent upstream fd0fc62..f4f4868 (8 commits: openclaw#169033
collaboration/workshop SQLite bookkeeping, 952c102, openclaw#155464 active
turns during worker dispatch, openclaw#168995 approval/placement queries,
openclaw#154286 telegram polling workers, 194a08e, openclaw#169045 code-mode catalog
bytes, openclaw#159697 talk voice permissions).

Conflicts:
- session-sharing-store.native.ts: upstream folded the member lookup and
  delete into one DELETE ... RETURNING with a no-row early return; our
  recipient-authority advance now follows that return, so only an actual
  removal revokes access (same order as before the merge).
- worker-access inventory: took upstream, regenerated (632 files, 2442
  calls).

sharing-store receipt/worker auto-merged: upstream's category plan
(keys only) is disjoint from our authority.capture command.

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant