Skip to content

improve: reduce Gateway allocation while draining SQLite receipts - #195129

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-owner-context-reentry-alloc-20260919
Nov 8, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-owner-context-reentry-alloc-20260919

Conversation

@steipete

@steipete steipete commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Queued SQLite worker receipts repeatedly restore the same owner context on the Gateway main thread.

User Impact

Less main-thread allocation and dispatch work during receipt bursts. Behavior, authority checks, schemas, and configuration remain unchanged; whole-Gateway latency is not measured here.

Why This Change Was Made

Enter the captured context once per nonempty synchronous drain. Keep callback context restoration and every per-message authority check, including after asynchronous preparation. Give relay creation callbacks their own restoration boundary, and skip context dispatch for an absent request observer.

The state-store and transcript-lifecycle audit found no redundant Gateway-scope copies or identical-current entries to remove. Their separate lifetime frames remain intact. Production code grows by 13 lines, including moving existing callback/authority types into the worker contract to keep the admission owner below its line cap.

Evidence

Five serial AB/BA samples per variant, plus two A/A controls, on Node 26 with 26 ambient stores and 4,096 synthetic session identities. CPU and allocation used separate uninstrumented passes; counts were measured separately.

Workload Snapshot restores Sampled host B/message Main CPU us/message Batch p95 us
single-admission 5 → 4 3773.37 → 3458.72 3.102 → 3.041 2.583 → 2.500
local-receipts 128 → 65 per 64 messages 1583.27 → 1336.65 0.948 → 0.875 65.375 → 62.125
worker-receipts 128 → 65 per 64 messages 1373.14 → 1123.66 1.022 → 0.916 74.000 → 69.000

A/A controls: single-admission: sampled host B/message 3721.006 → 3823.875, main CPU us/message 3.179 → 3.134; local-receipts: sampled host B/message 1576.293 → 1582.598, main CPU us/message 0.975 → 0.962; worker-receipts: sampled host B/message 1388.773 → 1376.810, main CPU us/message 1.002 → 1.004. The small single-admission CPU change overlaps sample spread; allocation gains are repeatable.

Run node --expose-gc --import ./scripts/tsx.mjs scripts/perf/sqlite-admission-context-measure.mjs --iterations 2000 --batch 64 --receipts --worker; omit --worker for local receipts or use --iterations 20000 --batch 1 for admission. Run unchanged on base/candidate, or pass --owner a baseline module with resolved imports. --cpu-profile <path> profiles the timing pass.

The sibling census (scripts/perf/sqlite-context-siblings-measure.mjs) uses real SQLite worker writes with 1,000 synthetic workspace rows and persisted readback. Per warm write: 2 snapshots created / 3 restored, unchanged across A/A arms. Lifecycle callbacks each enter one distinct owner. All measured owner flows make zero Gateway-scope copies. These are owner/transport measurements, not a large-database or full-Gateway throughput benchmark; sampled allocation excludes native and worker heap allocation.

Focused suites: 87 tests pass (admission 51, retention 6, lifecycle 4, Gateway scope 12, lint-suppressions 14; final five-shard run 26.57 s harness wall time). New tests refuse the second message after registry rotation or weak-target expiry and verify ambient callback isolation. Existing real-GC expiry, asynchronous revocation, and reentrant finish coverage remains passing. Added test budget: 99 lines for registry cases and a cursor-reset isolation regression. That error-path regression failed on the earlier batching candidate and passes after restoring the callback context. The baseline fails the performance count target; this is not a pre-existing authorization bug.

Rebased onto 306bf7730b0108e863a6ecfc549bc8289d9bddc7. Final head: 8ecfcfd7d8d7d1a1a9450baf941e627652087011.

The original CI run exposed a real failure introduced by this PR: its native-method capture suppressions increased the production suppression inventory from 213 to 215 entries. The same test failed locally before repair. All six new suppressions are removed, including the test-only capture, using structurally checked callable types with explicit receivers. Native function identity and exact restoration are preserved; the allowlist is unchanged.

Final local proof: all 87 focused tests, changed-source/script lint, and formatting pass. pnpm check:changed was rerun; its changelog-attribution gate fails on existing release records (exact-parent proof below). The two original CI infrastructure failures (check-lint-extensions-3 and check-additional-boundaries) could not stage the pinned Bun fork. Their local equivalents now pass: node --import ./scripts/tsx.mjs scripts/run-oxlint-shards.mts --only=extensions --extension-stripe=3/6 --threads=1 and node --import ./scripts/tsx.mjs scripts/run-additional-boundary-checks.mts. The same 20 attribution violations reproduce in a clean checkout of exact main parent 306bf7730b0108e863a6ecfc549bc8289d9bddc7 using node --import ./scripts/tsx.mjs scripts/check-changelog-attributions.mts. The forbidden-handle expansion in 266a7aa0fe69e2b5fe6445c4ceb1e15b5360c957 (#194364) introduced these rejections without repairing the existing records. This is a main regression needing follow-up; it is not a green changed-check run or a merge waiver.

The dead-export scan also fails on main-owned exports. Exact-parent reproduction uses node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts on the same main SHA. Introducing commits: c9e6370bb19157bb2dbadc6cb5ccd6fc95ea0e2e (#195099), scripts/plugin-npm-evidence-reuse.mjs:NPM_EVIDENCE_FILE; ce840d8a82902f0bff3eea5f1885f51c4ef16e01 (#195061), src/infra/path-containment.ts:canonicalizeForContainmentSync and UncanonicalReason; 754b41c65df0f72d3a6df1eb6abd810644b60190 (#195064), src/test-utils/retention.ts:expectCollected, expectLiveObjects, and forceFullGc. These are main gate regressions to repair, not ignored noise. All other changed checks pass.

After the capture repair, both measurement scripts passed smoke runs on Node 24.22.1: the real-worker 64-message batch still restores 65 snapshots with zero scope entries/copies; 1,000 synthetic SQLite workspace rows and both warm-write arms pass persisted readback. These smoke runs verify instrumentation behavior; the controlled performance figures above remain the original Node 26 AB/BA and A/A results.

Codex autoreview of the complete rebased candidate against 306bf7730b0108e863a6ecfc549bc8289d9bddc7: scoped-clean at P0–P2, no accepted/actionable findings. The reviewer verified exact native restoration, WeakRef receiver semantics, and preserved expiry and authority/lifecycle guards. Runtime production delta remains +13 lines; this repair adds no runtime production code.

Ready for review; intentionally left unmerged. New exact-head CI is pending.

@clawsweeper

clawsweeper Bot commented Nov 8, 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: L labels Nov 8, 2026
@steipete
steipete marked this pull request as ready for review November 8, 2026 08:38
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-08T09:48:48.675868Z
We couldn’t complete this review. Comment @codex review to try again.
8ecfcfd Manual request
ℹ️ 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.

@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR restores the captured owner context once per synchronous SQLite message drain while preserving callback isolation and per-message authority checks.

Example: Drain 64 queued SQLite commit receipts.

  • Before: The supplied benchmark reports 128 snapshot restorations.
  • After: The supplied benchmark reports 65 snapshot restorations.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful, narrowly scoped owner-level optimization with measured gains, harness-level evidence, and one confirmed CI regression.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; supplied measurements exercise the production admission owner with real MessagePorts, while focused tests cover context isolation and refusal boundaries.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Bursts of SQLite receipts allocate avoidable context-restoration work on the Gateway thread.
Reason: The maintainer-authored direction removes measured work at the existing owner without adding configuration, persistent state, or competing authority.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: the allocation reduction is useful and preserves the existing runtime checks, but its new lint suppressions cause a confirmed CI failure.

Priority: P3
Reviewed head: 3a11acb4ecc2ab37dd5ee35b85884235922816dd

Before merge

  • Register the new instrumentation suppressions in the explicit allowlist (P2) - These two directives, together with three in scripts/perf/sqlite-context-siblings-measure.mjs, introduce suppression entries absent from test/scripts/lint-suppressions.test.ts. The exact-head checks-node-compact-small-1 annotation shows that test failing with 215 entries instead of 213 and names both new script entries. Add the narrowly justified entries to the existing allowlist, or eliminate the directives while keeping lint clean, then run the suppression test.

Findings

  • [P2] Register the new instrumentation suppressions in the explicit allowlist — scripts/perf/sqlite-admission-context-measure.mjs:56-59

Tests

  • Missing end-to-end proof: The supplied owner and transport measurements do not establish whole-Gateway latency; no shipped Gateway benchmark is supplied.
Agent review details

How this fits together

The Gateway-side SQLite admission owner receives worker requests and committed receipts through MessagePorts, checks live database authority, and publishes grants or committed facts.

flowchart LR
  A[SQLite worker] --> B[MessagePort queue]
  B --> C[Gateway admission drain]
  C --> D[Captured owner context]
  D --> E[Live authority checks]
  E --> F[Native grant]
  D --> G[Committed fact observers]
Loading

Technical review

Best possible solution:

Keep the focused batching change and reconcile its five justified instrumentation suppressions with the existing explicit allowlist.

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

Current-main source restores context for every queued message, and the supplied measurements quantify that repeated work; the introduced CI failure is independently recorded in its test annotation.

Is this the best way to solve the issue?

Batching at the existing drain owner is the smallest complete optimization; callback restoration, live authority checks, retention cleanup, and the distinct regression cases remain justified.

Full review comments:

  • [P2] Register the new instrumentation suppressions in the explicit allowlist — scripts/perf/sqlite-admission-context-measure.mjs:56-59
    These two directives, together with three in scripts/perf/sqlite-context-siblings-measure.mjs, introduce suppression entries absent from test/scripts/lint-suppressions.test.ts. The exact-head checks-node-compact-small-1 annotation shows that test failing with 215 entries instead of 213 and names both new script entries. Add the narrowly justified entries to the existing allowlist, or eliminate the directives while keeping lint clean, then run the suppression test.
    Confidence: 1

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test test/scripts/lint-suppressions.test.ts --maxWorkers=1
  • pnpm check:changed
  • git diff --check

What I checked:

PR surface

Source +13, Tests +98, Other +446. Total +557 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 36 23 +13
Tests 1 98 0 +98
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 3 446 0 +446
Total 6 580 23 +557

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

  • add P3: This is a measured allocation optimization with no established user-facing runtime failure or urgent regression.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P3: This is a measured allocation optimization with no established user-facing runtime failure or urgent regression.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 November 8, 2026, 3:55 AM ET / 08:55 UTC.

Restore the captured owner once per synchronous drain while preserving live authority checks and callback isolation. Skip the empty request-observer dispatch. Keep registry expiry and generation checks effective between queued messages.
@steipete
steipete force-pushed the steipete/perf-micro-owner-context-reentry-alloc-20260919 branch from 3a11acb to 8ecfcfd Compare November 8, 2026 09:32
@auraecosystem

auraecosystem commented Nov 8, 2026 •

Copy link
Copy Markdown

@codex ^D review validate and execute

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@steipete

steipete commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

Landing note: ClawSweeper's P2 "register the new instrumentation suppressions" applied to the earlier head. At head 8ecfcfd all six unbound-method suppressions were removed by restructuring (no allowlist growth), and test/scripts/lint-suppressions.test.ts passes in exact-head CI. Merging at that head.

@steipete
steipete merged commit 4ff12d9 into main Nov 8, 2026
269 of 304 checks passed
@steipete
steipete deleted the steipete/perf-micro-owner-context-reentry-alloc-20260919 branch November 8, 2026 11:04
vincentkoc added a commit that referenced this pull request Nov 8, 2026
…tooling-lint-selection-20261108

* commit 'b0e90e6a4b359fff7756698067fdce4758b1907b': (38 commits)
  fix(android): Talk button demands a realtime provider on a native Talk setup (#191194)
  chore: trace first-run Gateway work and verify later replies (#195185)
  fix(knowledge): keep deleted messages out of reply previews (#195126)
  fix(agents): preserve streamed replies across Gateway restarts (#195164)
  perf(ci): reuse SDK transport path boundaries (#195180)
  fix(sandbox): avoid pauses for unchanged command checkpoints (#195120)
  fix(test): make retention checks portable across runtimes (#195091)
  fix(knowledge): clarify temporal kind filters (#194995)
  improve: reduce Gateway allocation while draining SQLite receipts (#195129)
  fix: reduce streaming CPU after reply and voice directives (#195145)
  fix: reduce Markdown reparsing during streamed tool-call checks (#195161)
  fix: restore the main dead-export gate (#195158)
  improve(ci): pack small UI selections into fewer jobs (#195107)
  fix(muse): quota and sign-in failures end with no reply (#195148)
  fix: allow first release push with shipped patch bytes (#195174)
  fix(ci): narrow single-config tooling selections (#195147)
  fix(packaging): reject incompatible prepublish plugin cohorts (#195152)
  fix(ci): prepare verified Bun before parity checks (#195155)
  fix: Incognito agent turns stall before execution (#195005)
  fix: credentialed search and speech providers work without picking a provider (#195169)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 9, 2026
…enclaw#195129)

* perf(sqlite): batch worker admission context restoration

Restore the captured owner once per synchronous drain while preserving live authority checks and callback isolation. Skip the empty request-observer dispatch. Keep registry expiry and generation checks effective between queued messages.

* fix(perf): preserve native receivers without lint suppressions
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: 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.

2 participants