Repository navigation
perf(core): skip the per-chunk hook snapshot when no hook is registered - #3961
Conversation
Every streamed chunk went through LegacyHookDispatcher.fireReasoningChunk, which snapshotted the whole answer so far into a Msg before asking whether anything wanted it, and the caller subscribed to that result from inside the chunk pipeline. With no hook registered the snapshot is built and discarded for every chunk, so a long stream copies its own prefix once per token. The dispatcher now reports whether any hook is registered, returns immediately when none is, and the reasoning and summary pipelines skip the subscription instead of creating a Mono, copying the context and subscribing for each chunk. The acting chunk callback takes the same early return. Behaviour with hooks is unchanged: the same accumulated Msg and the same incremental chunk reach the hook, in the same order. This is the first change listed in agentscope-ai#3929, measured there at -5.7s on a 500-stream run. The interrupt-check concatMap and the inner Flux per chunk from the same report are not included: they change pipeline shape rather than removing waste, and the report itself asks for a design review before those land.
|
Independent measurement supporting this change. In our fork A/B (same session, one change at a time; 500 concurrent chains of 10 streaming model calls × 300 tokens + 9 tool calls, ~61 s per chain unloaded), guarding the per-chunk hook snapshot — skipping the accumulated-message construction when no hook consumes it — was worth −5.7 s mean chain time under per-token delivery. The full three-change set (this guard, a synchronous interruption check, and synchronous event generation; changes #1–#3 in issue #3929) took stock 2.0.4 from 153.9 s → 113.4 s under per-token delivery and from 125.1 s → 87.6 s under 100 ms burst delivery, with 100% completion and exact model-call/tool-call/token counts in every run. Methodology and raw setup are in #3929; a self-contained repro is at https://github.com/realreus319/agentscope-streaming-repro. Happy to run this PR's branch head-to-head on the same harness if that helps the review. |
|
Thanks — that is the number I could not produce myself, and it is the one the review needs. Yes please, run this branch head-to-head on the same harness. Since the fork is a separate remote, the shortest path is: git remote add wahl https://github.com/wahllllll/agentscope-java.git
git fetch wahl perf/issue-3929-skip-chunk-accumulation
git checkout wahl/perf/issue-3929-skip-chunk-accumulation # head d27f8230Full ref, in case the checkout above drifts: Three things I would want from the run:
On going beyond it: agreed, and I would rather land the other two one at a time so each gets the same A/B treatment you gave the first. The interruption check is already in progress on my side — If you are willing to A/B the interruption change the same way, say so — your measurement would then be the evidence the review needs, and it is worth more coming from you than from me. One offer: the |
|
The interruption change is done and up as a separate PR: #4088, branch git fetch wahl perf/issue-3929-sync-interrupt-check
git checkout wahl/perf/issue-3929-sync-interrupt-check
One thing I did not expect to find while doing it: Nothing else moved: If this one runs on your harness the same way, the pair would cover two of your three changes, and the |
|
Head-to-head results, as requested. One methodological note first: your branch sits on current main, whose 1. Does the −5.7 s survive? Partially — it is −3.6 s on current main.
The two adjacent pairs differ by −3.62 s and −3.59 s, so the guard is worth a consistent ≈ −3.6 s per chain on main. The original −5.7 s was measured on 2.0.4; of the total head-vs-stock gap (−12.0 s), roughly −8.4 s is main's own drift since 2.0.4 and should not be credited to the guard. 2. Counts and completion: clean. 3. TTFT under burst delivery: unmoved, as you predicted. Happy to run #4088 the same way when you are ready — the interruption-latency find there (concatMap running the check one chunk ahead of the consumer) looks worth having independently of the timing. |
|
Thanks — and thank you for the method as much as the numbers. The class-level diff between the two jars is the right way to make TTFT unmoved is what the change was designed to do — the guard sits on the "is a hook registered" branch, so delivery timing should not see it — and your within-session-delta warning is worth repeating to whoever reads the PR: absolute numbers move between sessions, deltas do not. For #4088 the refs are head Two things worth watching, one of which is behaviour rather than timing:
Looking forward to your run on #4088 — please reply here (or on that PR) when the numbers are in, including the case where it does not reproduce; a flat result is a result, and I would rather have it than a guess. If the pair looks sound to you after that, a line saying "independent measurement, no objection" on #4088 with your numbers would be worth a great deal to a reviewer. Only if you think it is sound — I am not asking for a rubber stamp. |
|
@jujn — two of the three changes in #3929 are open (#3961, #4088), and the person who filed that issue independently measured both. Their method is worth one line: full builds of parent and head, then a class-level jar diff (19,056 files, 10 differ, all
Both are one commit, CI green, no conflicts. Anything you would want changed in either before they land? If the pair is too much at once, #3961 is the one with the measured win. |
|
Merged — thank you for the review. The sibling change, #4088, is the second of #3929's three (the interruption check that used to run one chunk ahead). It carries the same reporter's independent verification — the interrupt now stops on the in-flight chunk 5/5, timing flat, no regression — and the description states exactly how far that verification reaches. |
…4088) ## Background Second change of the three measured in #3929: *"Replace the interruption-check `concatMap` with a synchronous check (`handle`/`map`)"*. It was measured at −5.1 s mean chain time against 2.0.4, and it is one of the two we deliberately left out of #3961 so each one stays individually verifiable. `checkInterrupted()` was only ```java return Mono.defer(() -> interruption.isInterrupted() ? Mono.error(new InterruptedException("Agent execution interrupted")) : Mono.empty()); ``` — a field read wearing a `Mono` — and both streamed stages fed every chunk through `concatMap(chunk -> checkInterrupted().thenReturn(chunk))`. So a chunk crossed an asynchronous boundary to reach a field access. ## Change `CallExecution.untilInterrupted(Flux<T>)`, used by the reasoning stream and the summary stream: ```java private <T> Flux<T> untilInterrupted(Flux<T> upstream) { return upstream.handle((item, sink) -> { if (interruption.isInterrupted()) { sink.error(new InterruptedException("Agent execution interrupted")); return; } sink.next(item); }); } ``` Same flag, same error, same sequential processing — `handle` processes one element at a time, so ordering and backpressure are untouched. The per-chunk `Mono` allocation, its subscription and the handoff around it are gone. `checkInterrupted()` itself stays, and the per-step call sites are unchanged. Refs #3929
Problem
Every streamed chunk crosses
LegacyHookDispatcher.fireReasoningChunk, which snapshots the whole answer so far into aMsgbefore the dispatch loop runs:With no hook registered, that snapshot is built and discarded for every chunk — one full copy of the answer prefix per token, quadratic over a stream. The chunk pipeline makes it worse by subscribing from inside the per-chunk stage:
which allocates a
Mono, copies the Reactor context and starts a subscription per chunk, only for the result to beMono.empty().This is the first item in #3929. It was measured there at −5.7 s of chain time on a 500-stream run against 2.0.4; on today's
mainthe same guard measures −3.6 s, with the difference accounted for by main's own drift since that tag — see Independent measurement below.Change
LegacyHookDispatchergainshasHooks(), andfireReasoningChunk/fireSummaryChunkreturn immediately when nothing is registered — before the snapshot is built.fireActingChunktakes the same early return.ReActAgentskip the per-chunk subscription entirely when no hook is registered.What does not change
With hooks registered, the same
ReasoningChunkEventcarries the same accumulatedMsgand the same incremental chunk, in the same order; the early return only replaces theFlux.fromIterable(empty).flatMap(...).then()that already producedMono.empty().The third item from #3929 — flattening the per-chunk inner
Flux— is deliberately not included: it changes pipeline shape rather than removing waste, and the report asks for a design review before it lands. The second item, replacing the interrupt-checkconcatMap, is now its own PR: #4088.Tests
LegacyHookDispatcherChunkTest:getAccumulatedText()invokedgetAccumulatedText()invoked"abc"and incremental"c"The first two fail on
mainwith Mockito'sNever wanted here ... But invoked hereforReasoningContext.getAccumulatedText(), so the guard is not vacuous.Verification
mvn -B -pl agentscope-core "-Dtest=LegacyHookDispatcherChunkTest" test: 3/3 green.mvn -B -pl agentscope-core test: 2971 tests, 0 failures, 2 errors, both of themDangerousPathBypassTest.symlinkTo{Ssh,DotEnv}IsDetected— a Windows symlink-privilege limitation that fails identically on unmodifiedmain.spotless:check: BUILD SUCCESS.Independent measurement (2026-11-10, by @realreus319)
Built from three trees and run on the harness from #3929 — chains of 10 streaming calls × 300 tokens with 9 tool calls in between (~61 s per chain unloaded), 500 concurrent chains, fresh JVM per group. A class-level diff of the parent and head jars (18,489 classes each) shows only
ReActAgent*andLegacyHookDispatcherdiffer, sohead − parentisolates this guard on current main rather than comparing against a tag.Per-token delivery:
≈ −3.6 s per chain on current main, reproducible across the adjacent pairs (−3.62 s and −3.59 s). Of the 12.0 s head-vs-stock gap, roughly 8.4 s is main's own drift since 2.0.4 and is not credited to this change.
Counts and completion: 100% completion, 0 errors, 0 timeouts, exactly 10 model calls / 9 tool calls / 300 tokens per call in all 10 groups — identical to stock. TTFT under 100 ms burst delivery: head 3.78 s vs parent 3.80 s (−0.02 s, inside noise), whole-chain 114.2 s vs 112.6 s — the guard neither helps nor hurts there, which is what the design predicts, since it sits on the "is a hook registered" branch rather than on delivery. Absolute numbers shift between sessions; the within-session deltas are the stable part.
Addresses the first direction in #3929.