Skip to content

perf(gateway): acknowledge chat sends before skill preparation - #165608

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-chat-send-latency-20260919
Oct 6, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-chat-send-latency-20260919

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

chat.send waits for skill selection and authoring before acknowledging an admitted message, and slow-send logs cannot distinguish acknowledgement work from reply startup.

User Impact

Durably admitted messages can be acknowledged before skill preparation finishes. The admitted run owns preparation, cancellation, and error publication. Receipt fields, input bytes, idempotency, and message order remain unchanged.

The median-ACK performance target remains unmet. The prior 100-send comparison measured ACK p50 130.98 → 144.50 ms and p99 431.96 → 299.47 ms, versus requested limits of 50/200 ms. First assistant delta p50/p99 improved 1488.70/4757.73 → 1416.39/2567.24 ms. These are historical measurements, not measurements of the rebased head. The change provides post-ACK preparation and diagnostics; it does not establish a median improvement or explain the reported production three-second tail. No obvious source-level cause for the 13.52 ms median regression was established during the conflict repair.

Why This Change Was Made

Move selection and authoring into existing detached dispatch. Reserve the existing reply-admission ticket before ACK and retain it across preparation and pre-execution retries, so later inputs cannot overtake stalled or retrying inputs. Current input authority is revalidated before startup and retries; accepted injection keeps its existing backing-run outcome.

The timing owner emits slow chat send <N>ms request/startup records at one second and openclaw_chat_send_phase_seconds{phase,stage} with bounded labels. Initial session-row reads remain in replyInitialization, ordinary sandbox readiness remains in preparation, and worktree covers pending workspace creation. The optional transcript-start reader has a nested snapshot observation. Inclusive, overlapping phases must not be summed.

Rebased onto 876dd7520f7b4eb9a30933fbee90b173386ce540. The sole textual conflict was the session-prepared callback: main's replyDispatch.notePreparedSession(binding) handoff remains alongside the phase mark. Timing accepts narrow input facts without importing the admission/request/session owners, removing the type-import cycle. The two stale tests now use the synchronous preparation result and wait for existing dispatch settlement before counting dispatches.

Production LOC is +422 / −172, net +250, excluding tests, test support, and docs. The repair itself removes three net lines. Growth in the overall feature is required for the new diagnostic lifecycle/histogram and FIFO ownership across deferred preparation and retries. Eager preparation paths and superseded timing helpers are removed. No new configuration, cache, protocol field, compatibility shim, or schema change is introduced. Release-note context is this description; the changelog is release-owned.

Evidence

Final repair head fcc8409858e1b755b19ddb35508513f91f1172d3 has tested tree d1a61d996db2ff523309a25f8b80bf2a3f5f903b. Two detached independent reviews through the direct API route completed scoped-clean with no actionable P0–P2 findings and a 3600-second engine budget. All four remaining commits are patch-identical to the reviewed stack (git range-diff reports four = mappings). The remote source was reconstructed from the pinned base and reviewed patch; full Git-tree equality and a clean worktree were verified before and after validation.

The original three failures in run 37351765214 were corrected:

  • Madge's type-import cycle: timing no longer imports request/session/admission owners.
  • Core lint's stale await: the identity test consumes the synchronous preparation result.
  • Concurrent retry test: its dispatch-count assertion follows the existing session-work settlement signal, preserving all admission and receipt assertions.

After that repair passed remote proof, run 37391070288 passed those checks but exposed an inherited main test mismatch. Main's #165788 intentionally moved source-only command reservations directly into the follow-up queue, retaining the source operation as a drain barrier. The media-path test still expected the former parked fallback. The unchanged base reproduced that exact failure. While the repair was being validated, main landed 50b3573d11ea with the same fixture correction and a stronger exact-argument assertion. The latest rebase keeps that upstream fix and drops our redundant test-only commit; no unrelated upstream fix was copied or cherry-picked. Main’s new steering-rejection logging also remains intact.

Remote proof uses the authorized Hetzner fallback, Node 24.19.0 and repository-pinned pnpm 12.5.1, after Blacksmith failed to admit a lease within the authorized two-hour window. Neither queued Testbox lease ran tests. No local suites, builds, or typechecks ran. Both Hetzner leases below are released.

Latest-base integration proof: provider Hetzner, lease cbx_828dab055085, run run_129c145727fd30b552ce5e9fc1301a3c. One normally synchronized crabbox run --provider hetzner --no-hydrate --timing-json -- bash -c "$SCRIPT" invocation completed with exit 0 in 659.054 s; the payload verified the final Git tree and ran:

Latest-head proof Result Wall time
node --import ./scripts/tsx.mjs scripts/ci-run-node-test-shard.mts with the exact failed group 23 files / 372 tests passed 175 s
node scripts/run-vitest.mjs on ordering, preparation ACK, session binding, and steering custody, --maxWorkers=1 4 files / 38 tests passed 154 s
pnpm format:check on the 26 changed files Passed 1 s
pnpm tsgo:core Passed 61 s
node scripts/run-oxlint.mjs --tsconfig config/tsconfig/oxlint.core.json on changed core files 0 warnings/errors 21 s
node scripts/run-oxlint.mjs --tsconfig extensions/tsconfig.json on changed extension files 0 warnings/errors 180 s
node --import ./scripts/tsx.mjs scripts/check-madge-import-cycles.ts 0 cycles 20 s

The immediately preceding full gate ran on base 14ac5158149676d6d56c89713b49da03238ab6c4, candidate tree 17b15ed2334f13e3b2b8b60aea8e9036d723f916: provider Hetzner, lease cbx_c6d76f40adc6, run run_d1a8b343d45554fd9f434667590fe541, exit 0 in 3907.454 s. This is prior-base full-gate evidence; the table above checks the changed integration after the mechanical rebase.

Prior-base full proof Result Wall time
Untouched main: exact CI shard selection and two-worker override Reproduced exactly 1 failed / 371 passed; same stale assertion 159.10 s Vitest duration
Repaired candidate: identical shard selection 23 files / 372 tests passed 162 s
pnpm test src/auto-reply/reply/agent-runner.media-paths.test.ts --maxWorkers=1 20 passed 53 s
Existing source-completion barrier E2E case 1 selected case passed; 223 filtered out 1025 s, including normal cold E2E build
ACK/preparation/FIFO/session-binding/steering-custody tests 4 files / 38 tests passed 144 s
node scripts/check-changed.mjs --staged Passed, exit 0 2336 s

The first rebased tree also passed all 75 chat-server tests (202 s), 23 identity tests (20 s), the full 14-file chat/reply/custody/timing batch (373 s), four Prometheus tests (12 s), extension lint (zero warnings/errors, 176 s), and Madge (zero cycles, 35 s) on Hetzner cbx_f202e86c2b2a. Its initial rig staged gate stopped when SDK declaration setup exceeded the existing 300000 ms timeout; the exact failed step and trailing guards subsequently passed unchanged. That earlier aggregate remains a recorded setup failure, not an inherited-code claim or a passing invocation.

The replay preserves the failed auto-reply-reply-agent-runner group, its scoped config, 24 include patterns, and two-worker override; 23 files execute because that config excludes the E2E file. The source-barrier case was run separately through the normal E2E config.

No test cases, sleeps, or fixture boots were added by the check repairs. The existing slower files exercise Gateway/runner admission, SQLite custody, media, cancellation, and history; reported standalone times include compiler startup. Exact-head CI run 37400628388 completed: 46 jobs passed, 25 skipped, and two failed (security-fast and its aggregate openclaw/ci-gate). All selected tests, guards, lint, and typechecks passed. Its security-fast audit failed on existing production dependency source-map-js (GHSA-68fv-2mgg-jv7q, affected range >=1.0.0 <1.2.2). This is independently reproduced by the untouched CI base 381b1e05d7f0fa572fdf085e7714d4f90864d4b5: main run 37399800174, job 112064212410 failed with the identical advisory and exit 1. This PR changes neither dependencies nor audit policy. The PR remains ready, MERGEABLE, and squash auto-merge armed, but unmerged because this inherited audit is blocking. No guard or dependency policy was weakened, no merge command was run, and no rerun was requested merely for green.

Prior feature proof (before this rebase)

Blacksmith Testbox tbx_01m46g6171vtxpfvzjkwbwb2ej validated the tree published as 6af0005d88a6: 210 focused chat/reply/custody tests, four Prometheus tests, and 41 Control UI sending tests passed. The same source-bound synthetic socket rig ran three-send smoke and 100 sends per variant. It used 25 authenticated clients, a real worktree and Docker sandbox, 5,000 historical messages, eight synthetic private skills, and a deterministic loopback streaming provider. Both variants preserved history bytes and ordered new-user-content digests.

Prior 100-send measurement Before After
ACK p50 130.98 ms 144.50 ms
ACK p99 431.96 ms 299.47 ms
First assistant delta p50 1488.70 ms 1416.39 ms
First assistant delta p99 4757.73 ms 2567.24 ms

Prior candidate phase medians were authority 39.16 ms, persistence 31.68 ms, and run admission 24.94 ms. Preparation 1021.39 ms, reply initialization 47.60 ms, and authoring 0.79 ms occurred after ACK. These inclusive observations are not additive.

Earlier Testbox tbx_01m45wgswedwvn4jf15ta9dtae established negative controls: original code failed all four stalled-preparation ACK cases; unconditional ticket release produced A, B, A-retry, while retained ownership preserved A, A-retry, B.

No deployment or production mutation was performed. Production tail attribution still needs slow-send phase records after a separately authorized deployment. Native clients were source-audited, not device-tested. Historical rig measurements do not cover the optional fallback transcript-start reader; its observer lifecycle has focused coverage.

First repair batch commands and prior test cost
node scripts/run-vitest.mjs src/gateway/server-methods/chat-send-ordering.test.ts src/gateway/server-methods/chat-send-preparation-ack.test.ts src/gateway/server-methods/chat-send-session-binding.test.ts src/gateway/server-methods/chat-send-diagnostics.test.ts src/gateway/server-methods/chat-send-user-turn.test.ts src/gateway/server-methods/chat-send-pending-inputs.test.ts src/gateway/server-methods/chat-send-reply-dispatch.test.ts src/gateway/server-methods/chat-send-steering-custody.test.ts src/gateway/server-methods/chat-send-dispatch-errors.test.ts src/gateway/server-methods/chat-send-retry.test.ts src/gateway/server-methods/chat-send-pending-input-withdrawal.test.ts src/auto-reply/reply/agent-runner-execution-timing.test.ts src/auto-reply/reply/get-reply.maintenance-conflict.test.ts src/auto-reply/dispatch.question-input.test.ts --maxWorkers=1
node scripts/run-vitest.mjs extensions/diagnostics-prometheus/src/service.chat-send-stages.test.ts extensions/diagnostics-prometheus/src/service.catalog-stages.test.ts extensions/diagnostics-prometheus/src/service.worktree.test.ts --maxWorkers=1
node scripts/run-oxlint.mjs --tsconfig extensions/tsconfig.json extensions/diagnostics-prometheus/src/service-operation-timing.ts extensions/diagnostics-prometheus/src/service.chat-send-stages.test.ts

Prior-base standalone cost for the feature's new tests, measured with pnpm test <file> --maxWorkers=1 on Testbox: ordering 44.240 s (2 tests), preparation ACK 23.138 s (4 tests), diagnostics 3.013 s (4 tests), Prometheus stages 7.860 s (1 test). These include compiler/startup time. The slower ordering/preparation tests protect real admission, persistence, retries, and cancellation through existing fixtures; no added sleeps, serial configuration, or per-case Gateway process boot. These costs are historical; the current grouped timings above are separate evidence.

@clawsweeper

clawsweeper Bot commented Oct 5, 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 extensions: diagnostics-prometheus size: L labels Oct 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 5, 2026, 9:53 PM ET / October 6, 2026, 01:53 UTC (Revision 10).

ClawSweeper review

What this changes

The PR moves skill selection and authoring after chat acknowledgement, preserves send ordering through retries, and adds startup timing logs and metrics.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep open: current main still performs skill preparation before ACK, and this maintainer-authored PR remains useful. No actionable patch defect was found; the previously identified latency tradeoff still needs explicit acceptance.

Priority: P2
Reviewed head: fcc8409858e1b755b19ddb35508513f91f1172d3
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, well-supported implementation with no concrete correctness finding; performance acceptance remains a separate landing decision.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The recorded source-bound WebSocket rig exercises Gateway admission and detached dispatch with real workspace, sandbox, and transport boundaries, showing post-ACK preparation and preserved transcript/order results. Latest-tree integration checks supplement that proof; historical latency results do not prove current-head target attainment. No stored-data contract changes require migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The recorded source-bound WebSocket rig exercises Gateway admission and detached dispatch with real workspace, sandbox, and transport boundaries, showing post-ACK preparation and preserved transcript/order results. Latest-tree integration checks supplement that proof; historical latency results do not prove current-head target attainment. No stored-data contract changes require migration.
Evidence reviewed 8 items Pinned introduction: Reviewed the merge-base-to-head introduced patch, rather than endpoint drift. The introduced changes retain existing persistence and authorization machinery and add no dependency, configuration, protocol-field, or schema changes.
ACK and FIFO ownership: The handler revalidates input authority, reserves the existing reply-admission ticket, sends the ACK, and hands the ticket to detached dispatch. Dispatch retains it across retries and releases it at terminal settlement; the existing agent runner also releases it at queue handoff.
Deferred preparation and authority: Skill preparation now runs inside admitted dispatch. Existing authoring capabilities continue to check caller, delegated-run, revocation, and receipt authority at use; the prepared-session callback retains main's reply-dispatch handoff. No concrete introduced authority bypass was established.
Findings None None.
Security None None.

How this fits together

The Gateway receives chat messages from connected clients, admits their input, and starts agent replies. This change separates acknowledgement from skill preparation while retaining the existing cancellation, persistence, and reply-ordering owners.

flowchart TD
  A[Connected chat client] --> B[Authorize and admit input]
  B --> C[Reserve reply order]
  C --> D[Acknowledge message]
  D --> E[Prepare skills and workspace]
  E --> F[Dispatch agent reply]
  B --> G[Request and startup diagnostics]
  E --> G
Loading

Decision needed

Question Recommendation
May this PR land for deferred preparation and diagnostics despite the historical median ACK regression and unmet 50/200 ms targets? Accept the scoped improvement: Explicitly accept the published latency tradeoff and land this as deferred preparation and diagnostics without claiming the original targets are met.

Why: The implementation and behavior proof support its scoped benefits, but only the requirement owner can relax the requested latency limits.

Before merge

  • Resolve merge risk (P1) - The historical comparison worsened median ACK latency by 13.52 ms and missed both requested limits; no current-head measurement or explicit maintainer acceptance resolves that performance tradeoff.
  • Complete next step (P2) - Explicitly accept the published latency tradeoff or retain the original targets as a before-merge requirement.
  • Resolve maintainer decision - Resolve the maintainer decision shown above before merge.
Agent review details

Security

None.

PR surface

Source +250, Tests +478, Docs +24. Total +752 across 26 files.

View PR surface stats
Area Files Added Removed Net
Source 13 422 172 +250
Tests 10 502 24 +478
Docs 3 24 0 +24
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 26 948 196 +752

Review metrics

Metric Value Why it matters
Production and test growth production +422/−172, net +250; tests +502/−24, net +478 The body justifies production growth with diagnostic lifecycle and FIFO ownership across deferred preparation and retries.
Historical ACK comparison p50 +13.52 ms; p99 −132.49 ms The measured median and tail move in opposite directions, requiring explicit performance acceptance.

Merge-risk options

Maintainer options:

  1. Accept the measured tradeoff (recommended)
    Record explicit acceptance of the historical median regression and unmet targets for this scoped delivery.
  2. Keep the original targets
    Pause landing until a current-head comparison meets the retained latency requirement.

Technical review

Best possible solution:

Retain the single admitted-dispatch owner and bounded diagnostics, with an explicitly agreed performance acceptance criterion.

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

Not applicable as a functional bug report: source and recorded rig results establish deferred preparation, but the rebased head has no new latency measurement.

Is this the best way to solve the issue?

Yes for moving preparation into the existing admitted owner and preserving FIFO order; it does not yet establish the requested ACK performance improvement.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded chat acknowledgement and diagnostics improvement without an established urgent production regression.
  • merge-risk: 🚨 other: Green correctness checks do not resolve the measured median latency regression or acceptance of unmet performance targets.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The recorded source-bound WebSocket rig exercises Gateway admission and detached dispatch with real workspace, sandbox, and transport boundaries, showing post-ACK preparation and preserved transcript/order results. Latest-tree integration checks supplement that proof; historical latency results do not prove current-head target attainment. No stored-data contract changes require migration.
  • proof: sufficient: Contributor real behavior proof is sufficient. The recorded source-bound WebSocket rig exercises Gateway admission and detached dispatch with real workspace, sandbox, and transport boundaries, showing post-ACK preparation and preserved transcript/order results. Latest-tree integration checks supplement that proof; historical latency results do not prove current-head target attainment. No stored-data contract changes require migration.

Evidence

What I checked:

  • Pinned introduction: Reviewed the merge-base-to-head introduced patch, rather than endpoint drift. The introduced changes retain existing persistence and authorization machinery and add no dependency, configuration, protocol-field, or schema changes. (fcc8409858e1)
  • ACK and FIFO ownership: The handler revalidates input authority, reserves the existing reply-admission ticket, sends the ACK, and hands the ticket to detached dispatch. Dispatch retains it across retries and releases it at terminal settlement; the existing agent runner also releases it at queue handoff. (src/gateway/server-methods/chat-send-handler.ts:579, fcc8409858e1)
  • Deferred preparation and authority: Skill preparation now runs inside admitted dispatch. Existing authoring capabilities continue to check caller, delegated-run, revocation, and receipt authority at use; the prepared-session callback retains main's reply-dispatch handoff. No concrete introduced authority bypass was established. (src/gateway/server-methods/chat-send-agent-dispatch.ts:302, fcc8409858e1)
  • Still necessary on current main: Fetched main still awaits user-turn skill selection and authoring before responding. The merged related PR fix(auto-reply): wait for source operations before draining followups #165788 repairs a separate follow-up drain barrier and does not implement this ACK change. (src/gateway/server-methods/chat-send-handler.ts, 50f38c6ceb80)
  • Complete captured body inspected: GitHub's full body matched captured SHA-256 b58e10b52ccaaf4c71c4780e72e164477d302f67064fb80c32a4f4e5a824e7f4. The omitted range records an inherited dependency-audit failure and pending CI, not additional latency acceptance. Live non-ClawSweeper discussion contains only the informational security guard; there are no submitted reviews. (fcc8409858e1)
  • Positive behavior proof with bounded claims: The captured body reports a source-bound Testbox WebSocket rig with 25 authenticated clients, a real worktree and Docker sandbox, historical messages, private skills, and a loopback streaming provider. It observed preparation after ACK, preserved transcript bytes and input order, and included stalled-preparation and retry-order negative controls. Latest-tree remote integration checks supplement this historical feature proof; they are not current-head latency measurements. (6af0005d88a6)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

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

  • Record explicit acceptance or retention of the original ACK latency requirement using the published historical comparison.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (9 earlier review cycles; latest 8 shown)
  • reviewed 2026-10-05T14:56:46.765Z sha 484989c :: blocked before merge. :: none
  • reviewed 2026-10-05T15:16:00.721Z sha 88a6c726ab839562300cce19325133f49c3d46a1 :: blocked before merge. :: none
  • reviewed 2026-10-05T15:51:47.942Z sha 5eb2265 :: blocked before merge. :: none
  • reviewed 2026-10-05T16:21:03.278Z sha bec13ef :: blocked before merge. :: none
  • reviewed 2026-10-05T17:03:07.550Z sha bec13ef :: blocked before merge. :: none
  • reviewed 2026-10-05T17:59:01.414Z sha 6af0005 :: blocked before merge. :: none
  • reviewed 2026-10-06T00:07:25.061Z sha 621c5694625a07f7c7b32e51b9adbbbb78690f1f :: blocked before merge. :: none
  • reviewed 2026-10-06T01:28:04.571Z sha 35ffbaccc98fc97be1484756d26603f80d51324c :: blocked before merge. :: none

@steipete
steipete force-pushed the steipete/perf-micro-chat-send-latency-20260919 branch 2 times, most recently from 5eb2265 to bec13ef Compare October 5, 2026 16:05
@steipete
steipete marked this pull request as ready for review October 5, 2026 17:53
@github-actions

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

These security sensitive changes were made:

  • src/gateway/server-methods.ts: Controls Gateway authentication, pairing, or caller permissions. Check identity validation, scope checks, and revocation.

Carefully review these changes before merging.

@steipete
steipete enabled auto-merge (squash) October 5, 2026 17:54
@clawsweeper clawsweeper Bot added the merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. label Oct 5, 2026
@steipete
steipete force-pushed the steipete/perf-micro-chat-send-latency-20260919 branch 2 times, most recently from 621c569 to 35ffbac Compare October 6, 2026 01:20
Move skill selection and authoring into the admitted dispatch owner after
input custody and ACK. Retain reply-admission order through preparation and
pre-execution retries, and preserve existing receipt and cancellation behavior.

Add bounded request/startup phase metrics and plain-text slow-send logs,
including independent transcript-start reader observations. Consolidate timing
state in its existing owners and keep observer failures isolated from execution.

The synthetic sandbox rig improves ACK p50/p99 from 166/407 to 84/228 ms;
the requested 50/200 ms limits remain unmet. Production attribution is pending
an authorized deployment. This change is being published for draft review.
Keep the timing emitter callable without a receiver, bind the original
admission wait in the ordering test, and use the standard disposal binding.
Remove obsolete test awaits after user-turn preparation became synchronous.

Focused Testbox validation passes 33 tests. Affected lint and typechecks
pass, and independent review found no actionable issues. The broader
changed-code gate retains two reproduced baseline unused-export failures.
Keep the timing helper independent of request, session, and admission owners
so its consumers do not introduce a type-import cycle. Remove the stale
await of synchronous user-turn preparation and assert concurrent retry
dispatch after the existing session-work settlement signal.

The rebased feature preserves main's prepared-session handoff alongside the
phase mark. All focused chat/reply/custody and Prometheus suites pass on the
reviewed tree, including 75 chat-server and 23 identity tests. Core lint and
all typechecks pass; extension lint and Madge pass on the Hetzner fallback.
The rig's full staged gate stopped at an SDK preparation timeout; its exact
remaining guards passed separately without source or guard changes.
Independent review found no actionable P0-P2 findings.
@steipete
steipete force-pushed the steipete/perf-micro-chat-send-latency-20260919 branch from 35ffbac to fcc8409 Compare October 6, 2026 01:42
@steipete
steipete merged commit e532b82 into main Oct 6, 2026
145 of 149 checks passed
@steipete
steipete deleted the steipete/perf-micro-chat-send-latency-20260919 branch October 6, 2026 01:56
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
…law#165608)

* perf(gateway): acknowledge chat sends before skill preparation

Move skill selection and authoring into the admitted dispatch owner after
input custody and ACK. Retain reply-admission order through preparation and
pre-execution retries, and preserve existing receipt and cancellation behavior.

Add bounded request/startup phase metrics and plain-text slow-send logs,
including independent transcript-start reader observations. Consolidate timing
state in its existing owners and keep observer failures isolated from execution.

The synthetic sandbox rig improves ACK p50/p99 from 166/407 to 84/228 ms;
the requested 50/200 ms limits remain unmet. Production attribution is pending
an authorized deployment. This change is being published for draft review.

* fix(gateway): resolve chat send lint failures

Keep the timing emitter callable without a receiver, bind the original
admission wait in the ordering test, and use the standard disposal binding.
Remove obsolete test awaits after user-turn preparation became synchronous.

Focused Testbox validation passes 33 tests. Affected lint and typechecks
pass, and independent review found no actionable issues. The broader
changed-code gate retains two reproduced baseline unused-export failures.

* perf(gateway): consolidate chat send timing ownership

* fix(gateway): repair chat send preparation checks

Keep the timing helper independent of request, session, and admission owners
so its consumers do not introduce a type-import cycle. Remove the stale
await of synchronous user-turn preparation and assert concurrent retry
dispatch after the existing session-work settlement signal.

The rebased feature preserves main's prepared-session handoff alongside the
phase mark. All focused chat/reply/custody and Prometheus suites pass on the
reviewed tree, including 75 chat-server and 23 identity tests. Core lint and
all typechecks pass; extension lint and Madge pass on the Hetzner fallback.
The rig's full staged gate stopped at an SDK preparation timeout; its exact
remaining guards passed separately without source or guard changes.
Independent review found no actionable P0-P2 findings.
steipete added a commit that referenced this pull request Oct 7, 2026
…66365)

## What Problem This Solves

`chat.send` could wait behind unrelated transcript-history reads while authorizing a request, admitting its run, or preparing durable input. An ordered metadata read could hold the database writer FIFO while waiting on the single history worker.

## User Impact

Hot-session input can be persisted and acknowledged while history dispatch is blocked. Exact session rows, target discovery, transcript identity selection, and bounded cold-archive metadata use the existing projection worker. Writer FIFO ordering, current permissions, source replacement checks, and durable input custody remain intact. There are no schema, configuration, retention, or update changes.

## Why This Change Was Made

Metadata discovery and payload reads selected different workers. Use the metadata worker consistently, remove the unused inventory lane parameter, and remove the discovery-only lane fallback. Transcript corpus/archive payloads and maintenance retain their existing owners.

Production LOC delta: **+14**. The generic reader also serves transcript payloads, so the metadata operations must select the existing projection lane explicitly; transcript target selection also retains its lazy worker/incognito boundary. Most added lines are argument/import formatting. No new pool, cache, wrapper, or configuration option is introduced.

## Evidence

Benchmarks and runtime tests ran with provider `blacksmith-testbox`, profile `openclaw-check`, on Linux x86_64 / Node 24.19.0. Paired measurements and the first full staged gate used lease **`tbx_01m499e9p8c3pwdkxrq7kqyt11`** on base `cc7e664dfe34`. The full staged gate also passed after rebase to `8f5c33c30d71` on the Linux rig fallback (`node scripts/check-changed.mjs --staged`, exit 0, approximately 50 minutes). Fresh-lease integration proof passed on **`tbx_01m49cshscnkd5rn7tva92rwrp`**: core production types and 63 tests covering exact reads, worktree-owner projection, managed owner policy, and durable ACK; total command 2m23s.

On **`tbx_01m49wfjav8vbwxmsdrw22nrad`**, base `0288eb1f3692`, core production types and 218 tests across 16 focused files passed in 6m51s. The three corrected race fixtures passed all 58 tests in 2m24s. Their staged gate and a full 227-case registry lifecycle replay passed in 6m14s. The final branch is rebased onto `98567acd6060`; SHA-256 verification confirms all 17 reviewed files are byte-for-byte unchanged. The earlier results are prior-base evidence; hosted CI checks the final integration. All four leases are stopped/expired.

The RPC router/handler and SQLite rig ran 64 sends at concurrency eight, alongside four continuous synthetic history readers and post-ACK preparation. Provider execution was mocked after ACK. Same baseline revision, synthetic data, and lease:

| Request latency | Before | After | Reduction |
|---|---:|---:|---:|
| p50 | 6,451 ms | 979 ms | 84.8% |
| p95 | 17,257 ms | 3,339 ms | 80.7% |
| p99 / max | 18,234 ms | 3,470 ms | 81.0% |
| mean | 7,548 ms | 1,273 ms | 83.1% |

Afterward, all 1,500 history-worker requests were background page reads; foreground metadata used the projection worker. Harness RSS after the run was 2.995 GB before and 3.193 GB after; these are whole test-process measurements, including worker heaps and retained synthetic turns.

A second paired run waited for warm startup, then measured 32 requests with one send outstanding and the same four background history readers:

| Warm request latency | Before | After |
|---|---:|---:|
| p50 | 2,250 ms | 188 ms |
| p95 | 3,036 ms | 323 ms |
| p99 / max | 16,280 ms | 2,246 ms |
| mean | 2,710 ms | 264 ms |

**Both workloads still exceed the 150 ms p50 / 500 ms p99 targets.** The warm median is below 300 ms. The remaining 2,245 ms warm tail records 2,094 ms in authority, 9 ms in admission, 77 ms in persistence, and 65 ms in run admission. Repeated authority preparation and production latency still need finer attribution; this change removes the proven history-queue dependency without relaxing authority or durability.

- The full router → durable transcript → ACK regression passes with history dispatch held. The original revision times out waiting for ACK under the same gate (the existing 120-second Vitest deadline), confirming the regression catches the old dependency.
- Broader owner/sibling coverage: 167 tests passed across 12 files. After the transcript-target and cold-metadata cutover, 71 relevant tests passed, including cold restore authority, physical replacement, first registration, run admission, and ACK-before-skill-preparation behavior.
- `pnpm test src/gateway/server-methods/chat-send-preparation-ack.test.ts --maxWorkers=1`: 5 passed; 38.85 s runner wall time including worker compilation; 10.93 s test time. The new case took 3.67 s. Real router authorization and SQLite custody are required to prove a durable ACK; helper-only tests would miss the persistence dependencies. Added Linux test execution cost: approximately 3.7 seconds per run, measured on Testbox; hosted per-case timing was not collected.
- `node scripts/check-changed.mjs --staged`: passed on the paired measurement base in 27m53s, including all 27 core test type graphs, lint, dead-export, cycle, and storage guards. Every reviewed file matched its recorded SHA-256.
- Independent Codex reviews of the production scope and final three test corrections: scoped-clean, no actionable P0/P1 findings.
- Three additional test fixtures now inject metadata races/errors through the projection worker: native model ownership, diff-baseline generation, and SDK transcript-target locking. All 58 tests in those files passed on the fresh lease in 2m24s; their assertions are unchanged. The scoped staged gate selected and passed the `agents-other`, `other`, and `plugin-sdk` type graphs, lint, and dead-export checks.

<details>
<summary>24-hour slow-send attribution</summary>

The journal query covered 2026-10-05 19:00:50Z through 2026-10-06 19:00:50Z and yielded 77 request and 99 startup records. These are **conditional slow-stage distributions**: the logger excludes stages below 1,000 ms. Timers include awaited/scheduling time and can overlap; they are not exclusive CPU measurements. Missing fields are absent samples. Nearest-rank p99 equals max for these sample counts.

| Stage / phase | Samples | p50 ms | p95 ms | p99 / max ms |
|---|---:|---:|---:|---:|
| Request total | 77 | 3,418 | 5,611 | 6,951 |
| Authority | 77 | 1,429 | 2,267 | 2,748 |
| Admission | 77 | 273 | 469 | 685 |
| Attachments | 77 | 0 | 11 | 285 |
| Persistence | 77 | 566 | 1,234 | 2,815 |
| Preparation | 77 | 0 | 1 | 8 |
| Reply context | 77 | 0 | 83 | 116 |
| Run admission | 77 | 1,135 | 2,314 | 2,402 |
| Effects | 77 | 0 | 0 | 0 |
| Response | 77 | 1 | 1 | 2 |
| Startup total | 99 | 5,674 | 102,321 | 3,288,574 |
| Startup ACK (repeated request duration) | 99 | 3,158 | 4,851 | 6,951 |
| Startup authoring | 95 | 1 | 6 | 9 |
| Startup preparation | 95 | 3,532 | 5,951 | 3,046,035 |
| Startup reply initialization | 95 | 1,612 | 80,753 | 356,488 |
| Startup reply context | 99 | 0 | 0 | 129 |
| Startup worktree | 13 | 3,575 | 5,131 | 5,131 |
| Startup dispatch | 99 | 15 | 544 | 8,757 |

The 54.8-minute startup record had already ACKed in 250 ms and began after that process started. It does not establish pre-ACK blocking or unfinished work from the earlier restart. Source tracing and the blocked-history regression establish the metadata-worker dependency fixed here; they do not attribute every production tail.

</details>

Related: #165608.

<details>
<summary>Hosted CI investigation and remaining upstream failures</summary>

Final-head [CI run 37556779529](https://github.com/openclaw/openclaw/actions/runs/37556779529), head `3292922b0e82`, completed with 79 successful jobs, 24 skipped jobs, two failed test jobs, and the failed aggregate gate. The stale metadata-race fixtures are corrected. No CI rerun was requested.

- **MCP fixture routing:** all ten `mcp-http.session-controls.test.ts` cases fail during tool/auth preparation before the session action. On unchanged base `0288eb1f3692`, `pnpm exec vitest run --config test/vitest/vitest.gateway-core.config.ts src/gateway/mcp-http.session-controls.test.ts --maxWorkers=1 -t 'MCP dispatch preserves archive final-effect authority: allowed'` fails with the identical `Shared-state admission requires the host broker`; adding `--pool=forks` passes. Upstream #166199 moved the sibling question-authority fixture into the fork-backed database-worker lane but omitted this fixture. This branch does not change its routing.
- **History expectation after the new base:** `chat.history advances past a replay boundary that cannot fit all projected siblings` still expects only sequence 2 on page one. Upstream #166263 now compresses an oversized source group into a fetchable placeholder before capping, allowing the older sequence-1 message to fit on the same page. The fixture and paging owner are byte-identical between base `98567acd6060` and this branch. The exact filtered case also fails on unchanged base `98567acd6060` on `blacksmith-testbox` lease `tbx_01m49zrpad1bfnzpwb9wp7t3tz`: a diagnostic print before the unchanged assertion captured `sequences: [1, 2]` and `hasMore: false`. The test exited 1 as expected; the probe command completed in 1m35s, restored the test, removed its temporary worktree, and the lease is stopped. No history behavior is changed here.

The initial CI run also reported one remaining fake timer in `subagent-registry-lifecycle.test.ts`, case `preserves cleanup exhaustion when another run settles (related=true)`. The complete 227-case file passed separately on unchanged base and candidate, and the corrected head's CI no longer reports it. The original failure remains unexplained; passing replays are not claimed as a fix, and no assertion was weakened.

</details>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 8, 2026
…enclaw#166365)

## What Problem This Solves

`chat.send` could wait behind unrelated transcript-history reads while authorizing a request, admitting its run, or preparing durable input. An ordered metadata read could hold the database writer FIFO while waiting on the single history worker.

## User Impact

Hot-session input can be persisted and acknowledged while history dispatch is blocked. Exact session rows, target discovery, transcript identity selection, and bounded cold-archive metadata use the existing projection worker. Writer FIFO ordering, current permissions, source replacement checks, and durable input custody remain intact. There are no schema, configuration, retention, or update changes.

## Why This Change Was Made

Metadata discovery and payload reads selected different workers. Use the metadata worker consistently, remove the unused inventory lane parameter, and remove the discovery-only lane fallback. Transcript corpus/archive payloads and maintenance retain their existing owners.

Production LOC delta: **+14**. The generic reader also serves transcript payloads, so the metadata operations must select the existing projection lane explicitly; transcript target selection also retains its lazy worker/incognito boundary. Most added lines are argument/import formatting. No new pool, cache, wrapper, or configuration option is introduced.

## Evidence

Benchmarks and runtime tests ran with provider `blacksmith-testbox`, profile `openclaw-check`, on Linux x86_64 / Node 24.19.0. Paired measurements and the first full staged gate used lease **`tbx_01m499e9p8c3pwdkxrq7kqyt11`** on base `4a96fff224ff`. The full staged gate also passed after rebase to `66cf8a4c0732` on the Linux rig fallback (`node scripts/check-changed.mjs --staged`, exit 0, approximately 50 minutes). Fresh-lease integration proof passed on **`tbx_01m49cshscnkd5rn7tva92rwrp`**: core production types and 63 tests covering exact reads, worktree-owner projection, managed owner policy, and durable ACK; total command 2m23s.

On **`tbx_01m49wfjav8vbwxmsdrw22nrad`**, base `fd7d42fa5176`, core production types and 218 tests across 16 focused files passed in 6m51s. The three corrected race fixtures passed all 58 tests in 2m24s. Their staged gate and a full 227-case registry lifecycle replay passed in 6m14s. The final branch is rebased onto `772d281b298f`; SHA-256 verification confirms all 17 reviewed files are byte-for-byte unchanged. The earlier results are prior-base evidence; hosted CI checks the final integration. All four leases are stopped/expired.

The RPC router/handler and SQLite rig ran 64 sends at concurrency eight, alongside four continuous synthetic history readers and post-ACK preparation. Provider execution was mocked after ACK. Same baseline revision, synthetic data, and lease:

| Request latency | Before | After | Reduction |
|---|---:|---:|---:|
| p50 | 6,451 ms | 979 ms | 84.8% |
| p95 | 17,257 ms | 3,339 ms | 80.7% |
| p99 / max | 18,234 ms | 3,470 ms | 81.0% |
| mean | 7,548 ms | 1,273 ms | 83.1% |

Afterward, all 1,500 history-worker requests were background page reads; foreground metadata used the projection worker. Harness RSS after the run was 2.995 GB before and 3.193 GB after; these are whole test-process measurements, including worker heaps and retained synthetic turns.

A second paired run waited for warm startup, then measured 32 requests with one send outstanding and the same four background history readers:

| Warm request latency | Before | After |
|---|---:|---:|
| p50 | 2,250 ms | 188 ms |
| p95 | 3,036 ms | 323 ms |
| p99 / max | 16,280 ms | 2,246 ms |
| mean | 2,710 ms | 264 ms |

**Both workloads still exceed the 150 ms p50 / 500 ms p99 targets.** The warm median is below 300 ms. The remaining 2,245 ms warm tail records 2,094 ms in authority, 9 ms in admission, 77 ms in persistence, and 65 ms in run admission. Repeated authority preparation and production latency still need finer attribution; this change removes the proven history-queue dependency without relaxing authority or durability.

- The full router → durable transcript → ACK regression passes with history dispatch held. The original revision times out waiting for ACK under the same gate (the existing 120-second Vitest deadline), confirming the regression catches the old dependency.
- Broader owner/sibling coverage: 167 tests passed across 12 files. After the transcript-target and cold-metadata cutover, 71 relevant tests passed, including cold restore authority, physical replacement, first registration, run admission, and ACK-before-skill-preparation behavior.
- `pnpm test src/gateway/server-methods/chat-send-preparation-ack.test.ts --maxWorkers=1`: 5 passed; 38.85 s runner wall time including worker compilation; 10.93 s test time. The new case took 3.67 s. Real router authorization and SQLite custody are required to prove a durable ACK; helper-only tests would miss the persistence dependencies. Added Linux test execution cost: approximately 3.7 seconds per run, measured on Testbox; hosted per-case timing was not collected.
- `node scripts/check-changed.mjs --staged`: passed on the paired measurement base in 27m53s, including all 27 core test type graphs, lint, dead-export, cycle, and storage guards. Every reviewed file matched its recorded SHA-256.
- Independent Codex reviews of the production scope and final three test corrections: scoped-clean, no actionable P0/P1 findings.
- Three additional test fixtures now inject metadata races/errors through the projection worker: native model ownership, diff-baseline generation, and SDK transcript-target locking. All 58 tests in those files passed on the fresh lease in 2m24s; their assertions are unchanged. The scoped staged gate selected and passed the `agents-other`, `other`, and `plugin-sdk` type graphs, lint, and dead-export checks.

<details>
<summary>24-hour slow-send attribution</summary>

The journal query covered 2026-10-05 19:00:50Z through 2026-10-06 19:00:50Z and yielded 77 request and 99 startup records. These are **conditional slow-stage distributions**: the logger excludes stages below 1,000 ms. Timers include awaited/scheduling time and can overlap; they are not exclusive CPU measurements. Missing fields are absent samples. Nearest-rank p99 equals max for these sample counts.

| Stage / phase | Samples | p50 ms | p95 ms | p99 / max ms |
|---|---:|---:|---:|---:|
| Request total | 77 | 3,418 | 5,611 | 6,951 |
| Authority | 77 | 1,429 | 2,267 | 2,748 |
| Admission | 77 | 273 | 469 | 685 |
| Attachments | 77 | 0 | 11 | 285 |
| Persistence | 77 | 566 | 1,234 | 2,815 |
| Preparation | 77 | 0 | 1 | 8 |
| Reply context | 77 | 0 | 83 | 116 |
| Run admission | 77 | 1,135 | 2,314 | 2,402 |
| Effects | 77 | 0 | 0 | 0 |
| Response | 77 | 1 | 1 | 2 |
| Startup total | 99 | 5,674 | 102,321 | 3,288,574 |
| Startup ACK (repeated request duration) | 99 | 3,158 | 4,851 | 6,951 |
| Startup authoring | 95 | 1 | 6 | 9 |
| Startup preparation | 95 | 3,532 | 5,951 | 3,046,035 |
| Startup reply initialization | 95 | 1,612 | 80,753 | 356,488 |
| Startup reply context | 99 | 0 | 0 | 129 |
| Startup worktree | 13 | 3,575 | 5,131 | 5,131 |
| Startup dispatch | 99 | 15 | 544 | 8,757 |

The 54.8-minute startup record had already ACKed in 250 ms and began after that process started. It does not establish pre-ACK blocking or unfinished work from the earlier restart. Source tracing and the blocked-history regression establish the metadata-worker dependency fixed here; they do not attribute every production tail.

</details>

Related: openclaw#165608.

<details>
<summary>Hosted CI investigation and remaining upstream failures</summary>

Final-head [CI run 37556779529](https://github.com/openclaw/openclaw/actions/runs/37556779529), head `3292922b0e82`, completed with 79 successful jobs, 24 skipped jobs, two failed test jobs, and the failed aggregate gate. The stale metadata-race fixtures are corrected. No CI rerun was requested.

- **MCP fixture routing:** all ten `mcp-http.session-controls.test.ts` cases fail during tool/auth preparation before the session action. On unchanged base `fd7d42fa5176`, `pnpm exec vitest run --config test/vitest/vitest.gateway-core.config.ts src/gateway/mcp-http.session-controls.test.ts --maxWorkers=1 -t 'MCP dispatch preserves archive final-effect authority: allowed'` fails with the identical `Shared-state admission requires the host broker`; adding `--pool=forks` passes. Upstream openclaw#166199 moved the sibling question-authority fixture into the fork-backed database-worker lane but omitted this fixture. This branch does not change its routing.
- **History expectation after the new base:** `chat.history advances past a replay boundary that cannot fit all projected siblings` still expects only sequence 2 on page one. Upstream openclaw#166263 now compresses an oversized source group into a fetchable placeholder before capping, allowing the older sequence-1 message to fit on the same page. The fixture and paging owner are byte-identical between base `772d281b298f` and this branch. The exact filtered case also fails on unchanged base `772d281b298f` on `blacksmith-testbox` lease `tbx_01m49zrpad1bfnzpwb9wp7t3tz`: a diagnostic print before the unchanged assertion captured `sequences: [1, 2]` and `hasMore: false`. The test exited 1 as expected; the probe command completed in 1m35s, restored the test, removed its temporary worktree, and the lease is stopped. No history behavior is changed here.

The initial CI run also reported one remaining fake timer in `subagent-registry-lifecycle.test.ts`, case `preserves cleanup exhaustion when another run settles (related=true)`. The complete 227-case file passed separately on unchanged base and candidate, and the corrected head's CI no longer reports it. The original failure remains unexplained; passing replays are not claimed as a fix, and no assertion was weakened.

</details>
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 extensions: diagnostics-prometheus gateway Gateway runtime merge-risk: 🚨 other 🚨 Merging this PR has meaningful risk outside the owned taxonomy. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: XL 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