Skip to content

perf(state): avoid async task context for synchronous reply decoding - #184831

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-main-thread-sqlite-task-wrapper-20261026
Oct 26, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-main-thread-sqlite-task-wrapper-20261026

Conversation

@steipete

Copy link
Copy Markdown
Contributor

Related: #184101

What Problem This Solves

SQLite worker reply decoding creates a fresh async task context for a wholly synchronous operation whenever Gateway stall monitoring is enabled.

User Impact

No user-visible behavior change. This removes a small allocation and CPU cost from each decoded reply while preserving the existing worker:sqlite:reply-decode stall label. Decoding, transport, admission, custody, ordering, transactions, and integrity checks are unchanged.

Why This Change Was Made

Use the task monitor's existing synchronous phase API: task worker:sqlite, phase reply-decode. That retains elapsed-time attribution without entering AsyncLocalStorage. Reply decoding and its transfer helpers are synchronous; continuation posting, settlement, and dispatch remain outside the phase.

This is residual work after #184101, which is already in the measured baseline. Most allocation under the decoder remains necessary V8 deserialization; this change only removes async-context setup. Runtime production delta is +1 line (2 added / 1 removed): the extra phase argument selects an existing API and deletes per-call work. No new owner, cache, helper, or compatibility path. The requested non-test/non-doc diff is net +5 lines including the benchmark update; tests add 24 lines.

Evidence

Acceptance declared before the paired comparison: reduce allocation in the monitored reply owner without consistently adverse CPU, preserve reply output and stall attribution, and eliminate async-context entry from synchronous decoding.

Five counterbalanced base/candidate pairs on Node 26.12.1, synthetic scalar/session-entry/64-row-page replies, 10,000 replies per pass. Each process runs five untraced timing passes and one separate allocation-sampling pass including collected objects. Fixtures/jobs are prepared before measurement. Each side therefore has 250,000 timed and 50,000 allocation-sampled replies per shape. Table reports mean sampled bytes/reply and mean of each process's median CPU/reply.

Reply shape Allocation B/reply, base → candidate Change CPU µs/reply, base → candidate Change
Scalar 960.37 → 274.13 −71.46% 0.541 → 0.362 −32.97%
Session entry 1,643.67 → 961.73 −41.49% 1.115 → 0.948 −14.98%
64-row page 40,808.13 → 40,171.81 −1.56% 37.428 → 37.061 −0.98%

Allocation and CPU improved in all five pairs for all shapes. Host 1-minute load ranged approximately 21.1–24.0. The page result is a small improvement, as expected when deserialization dominates. Baseline: c00af62f03e6ab9929234a998693f53341a4e126; comparison toggles only the two production hunks while running the same updated benchmark.

Reproduce on base and candidate with the updated benchmark:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/sqlite-worker-reply-measure.ts

The added regression fails on the baseline because decoding calls AsyncLocalStorage.run once. It passes with the change and also checks decoded output and the unchanged stall label.

  • Focused tests: node scripts/run-vitest.mjs src/infra/sqlite-worker-broker-reply.test.ts src/infra/main-thread-stall.test.ts --maxWorkers=1 — 16 passed, 33.08 seconds wrapper wall time (29.60 seconds Vitest, mostly transform).
  • Changed-file oxfmt, core/script oxlint, pnpm tsgo:core, and git diff --check — passed.
  • Independent subagent review (autoreview route unavailable): scoped clean through P2. The helper refused the provider/operator configuration mismatch before inference; configuration was unchanged.
  • Simplification pass completed: only the existing phase argument, regression, and monitored benchmark remain.

Measurement gap: no whole-Gateway load/stress run, GC/tail claim, or end-to-end speedup claim. This follows the task's explicit fast-path exception for deletion of redundant synchronous context setup. CI supplies broader proof; no remote validation lease was allocated.

@clawsweeper

clawsweeper Bot commented Oct 26, 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 26, 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-26T17:15:38.301698Z f53edae PR opened
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: XS labels Oct 26, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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. labels Oct 26, 2026
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Use the existing synchronous monitor phase API to avoid async-context allocation while decoding SQLite worker replies.

Example: A monitored SQLite reply decodes the value {"count":42}.

  • Before: Decoding enters AsyncLocalStorage and reports worker:sqlite:reply-decode.
  • After: Decoding returns the same value and stall label without entering AsyncLocalStorage.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A minimal, source-supported optimization with useful owner-level measurements; supplied evidence does not establish shipped Gateway behavior or system-wide gains.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary live-proof gate; its Node benchmark exercises the production reply owner and monitor with synthetic serialized replies, reports paired allocation and CPU improvements, and explicitly excludes whole-Gateway performance claims.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Monitored state replies perform avoidable allocation and CPU work on the Gateway main thread.
Reason: The maintainer-authored direction removes measured redundant work using an existing API while preserving decoding and diagnostic behavior.

Merge readiness

✅ Ready for maintainer review

This PR is a focused, maintainer-directed optimization with no actionable correctness or security findings; exact-head CI remains pending.

Priority: P3
Reviewed head: f53edae3ec8b441d37f2d76957c82d347383c060

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied owner benchmark does not exercise monitored reply decoding through a running Gateway.
Agent review details

How this fits together

The Gateway's SQLite broker receives serialized worker replies, decodes values or transfer frames, and passes completed results to the existing settlement owner.

flowchart LR
  A[SQLite worker] --> B[Broker reply receiver]
  B --> C[Synchronous monitored decode]
  C --> D[Transfer continuation]
  D --> A
  C --> E[Existing settlement owner]
  E --> F[Waiting caller]
Loading

Technical review

Best possible solution:

Retain this minimal use of the existing synchronous phase owner and complete the normal exact-head CI gates.

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

Current main enters AsyncLocalStorage for this synchronous decoder when monitoring is enabled; source inspection establishes the unnecessary entry, and the PR reports a baseline-failing regression.

Is this the best way to solve the issue?

The smallest complete change uses the monitor's existing phase argument, preserves the diagnostic label, and adds no competing owner or retained state.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • SQLite reply diagnostic scope keeps the original intent (10a3260: The earlier optimization inlined decoding into its existing diagnostic scope to remove completion envelopes while retaining attribution.)
  • Synchronous monitor phase semantics keeps the original intent (perf(infra): avoid async frames for synchronous stall phases #181147: Synchronous phases avoid copying async context while retaining task names and longest-segment accounting.)
  • Reply-owner measurement script keeps the original intent (10a3260: Measure actual reply-owner CPU and sampled allocation with prepared synthetic inputs; enabling monitoring exposes the cost this PR removes.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 10a3260 adds src/infra/sqlite-worker-broker-reply.ts:402 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 10a32601608a; files: src/infra/sqlite-worker-broker-reply.ts)

PR surface

Source +1, Tests +24, Other +4. Total +29 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 2 1 +1
Tests 1 24 0 +24
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 5 1 +4
Total 3 31 2 +29

Labels

Label changes:

  • add P3: A small measured allocation optimization preserves existing reply behavior and diagnostics.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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: A small measured allocation optimization preserves existing reply behavior and diagnostics.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp 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 26, 2026, 1:28 PM ET / 17:28 UTC.

@steipete
steipete merged commit a5a49c5 into main Oct 26, 2026
129 of 130 checks passed
@steipete
steipete deleted the steipete/perf-main-thread-sqlite-task-wrapper-20261026 branch October 26, 2026 17:48
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: XS 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