Repository navigation
perf(agents): remove per-token quadratic work from the streaming fanout - #118192
Conversation
|
Codex review: needs real behavior proof before merge. Reviewed August 2, 2026, 4:53 PM ET / 20:53 UTC. ClawSweeper reviewWhat this changesThis PR removes repeated per-token full-buffer parsing, projection, signature parsing, and queue copying from agent streaming and gateway fanout while preserving chat, abort, and session-note outputs. Merge readiness⛔ Blocked until real behavior proof from a real setup is added - 3 items remain Keep open. Current Priority: P3 Review scores
Verification
How this fits togetherProvider streaming deltas pass through embedded-agent handlers into live gateway buffers, session activity notes, and async stream consumers. Those buffers are sanitized and projected before broadcasts, abort snapshots, history recovery, and user-visible channel output. flowchart LR
Provider[Provider stream deltas] --> Agent[Embedded agent handler]
Agent --> Reasoning[Thinking-tag extraction]
Agent --> Notes[Session activity notes]
Agent --> Buffer[Gateway live buffer]
Buffer --> Projection[Sanitize and project]
Projection --> Fanout[Gateway chat fanout]
Fanout --> Clients[Chat and channel clients]
Agent --> Queue[Async event queue]
Queue --> Consumers[Stream consumers]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +136, Tests +279. Total +415 across 20 files. View PR surface stats
Review metricsNone. Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Keep the unified lazy Do we have a high-confidence way to reproduce the issue? Yes at source level: current main normalizes/projects the cumulative chat buffer before its 150 ms throttle and dequeues EventStream values with Is this the best way to solve the issue? Yes: centralizing lazy projection in AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against b35b8e286df0. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
|
ClawSweeper rank-up move handling: skipping the optional before/after concurrent-streaming benchmark in this PR. The benchmark harness and load measurement are owned by the named sibling For this PR, the accepted proof is the exact-head green CI plus focused byte-equivalence, sanitizer-call-count, flush/abort, signature-cache, and EventStream ordering/compaction regressions already listed in the body. The coordinator also ran the required Codex autoreview on this patch and it completed clean at 0.98. This consciously accepts unit/regression evidence for the no-behavior-change refactor; the sibling benchmark will provide the inspectable concurrent-load measurement. |
|
Merged via squash.
|
* origin/main: feat(gateway): track event-loop degradation persistence and add concurrency benchmark (#118193) fix(config): preserve secret ownership when configuration rows move (#118149) fix(cron): deliver failure alerts after persistence (#118200) chore(lint): clear 172 lint:all baseline violations in five batches (#118098) perf(gateway): remove streaming hot-path rescans (#118192) test(gateway): use in-memory task registry (#118191) test(macos): fix three races in the bounded process suites (#118196) refactor(migrate-hermes): consolidate test fixtures (#118182) test(android): share Wear transport fixtures (#118177) test(ui): deduplicate control UI e2e setup (#118180) fix(plugins): unblock prerelease validation (#118103) test(cli): reduce redundant process launches (#118141) test(gateway): compact terminal observer fixtures (#118179) fix(agents): make requested threads sidebar-visible (#118073) test(plugins): canonicalize native resolver fixtures (#118174) test: deduplicate agent runner fixtures (#118176) refactor(policy): consolidate doctor test fixtures (#118173) fix(plugins): remove disabled channel plugin configuration on uninstall (#118127) refactor(matrix): consolidate monitor test fixtures (#118175)
* origin/main: feat(gateway): track event-loop degradation persistence and add concurrency benchmark (openclaw#118193) fix(config): preserve secret ownership when configuration rows move (openclaw#118149) fix(cron): deliver failure alerts after persistence (openclaw#118200) chore(lint): clear 172 lint:all baseline violations in five batches (openclaw#118098) perf(gateway): remove streaming hot-path rescans (openclaw#118192) test(gateway): use in-memory task registry (openclaw#118191) test(macos): fix three races in the bounded process suites (openclaw#118196) refactor(migrate-hermes): consolidate test fixtures (openclaw#118182) test(android): share Wear transport fixtures (openclaw#118177) test(ui): deduplicate control UI e2e setup (openclaw#118180) fix(plugins): unblock prerelease validation (openclaw#118103) test(cli): reduce redundant process launches (openclaw#118141) test(gateway): compact terminal observer fixtures (openclaw#118179) fix(agents): make requested threads sidebar-visible (openclaw#118073) test(plugins): canonicalize native resolver fixtures (openclaw#118174) test: deduplicate agent runner fixtures (openclaw#118176) refactor(policy): consolidate doctor test fixtures (openclaw#118173) fix(plugins): remove disabled channel plugin configuration on uninstall (openclaw#118127) refactor(matrix): consolidate monitor test fixtures (openclaw#118175)
What Problem This Solves
Issue #118027: the gateway event loop saturates around 8 concurrent streaming turns (cpuCoreRatio ~1.0, Control UI shell 6.7 s, delayP99 2.6 s). Profiling-by-reading found the dominant cost is per-token work proportional to the full accumulated turn text — several independent O(n²) patterns in the stream fanout, none of them needed for correctness.
Why This Change Was Made
Each provider delta previously paid:
extractThinkingFromTaggedStreamre-runningmatchAllover the entire delta buffer per token → now an incremental scanner whose state shares the delta buffer's lifecycle; byte-identical outputs proven by randomized prefix-equivalence tests against the full-buffer reference.normalizeLiveAssistantBufferedText+ projection over the whole merged chat buffer (up to 500K chars) BEFORE the 150 ms broadcast throttle → projection is now computed lazily behindChatRunState.resolveBuffer, memoized on the raw buffer, and every reader (broadcast, flush, abort snapshot/partials) goes through the accessor. Sanitization still always operates on the complete merged buffer — ordering only.assembleAssistantBuffer(full, 4096)on the full cumulative text per token in session activity notes → full-snapshot assembly now throttled to 150 ms with forced exact sync at every consumer/flush; delta-only producers keep the historical bounded path.parseAssistantTextSignatureJSON.parsing the same blocks 3-5× per token → WeakMap cache keyed on block identity + signature text reference (streaming mutates blocks in place; a stale hit is impossible because the text reference is compared).content.toReversed()array copies per token → reverse index loops.EventStreamdequeue viasplice(0,1)(O(queue), quadratic exactly when the consumer lags) → cursor dequeue with bounded compaction.Not changed: channel partial sanitization (
normalizeStreamingText) also serves unthrottled CLI/QA/typing/tool-result callers; moving it behind the draft-loop throttle needs an explicit deferred-normalization contract and is deferred as a follow-up rather than forced into this no-behavior-change patch.User Impact
No behavior change: emitted payloads, persisted transcripts, and channel output are byte-identical (regression tests assert equivalence and sanitizer-call counts). Streaming turns stop costing O(turn-length) CPU per token on the gateway main loop, directly raising the concurrent-streaming ceiling from #118027.
Evidence
pnpm tsgo:coreandgit diff --checkclean.Part of #118027. Siblings: feat/event-loop-observability-118027 (adds the concurrency benchmark that measures this), perf/sessions-list-118027.