Skip to content

perf(core): skip the per-chunk hook snapshot when no hook is registered - #3961

Merged
jujn merged 1 commit into
agentscope-ai:mainfrom
wahllllll:perf/issue-3929-skip-chunk-accumulation
Nov 11, 2026
Merged

jujn merged 1 commit into
agentscope-ai:mainfrom
wahllllll:perf/issue-3929-skip-chunk-accumulation

Conversation

@wahllllll

@wahllllll wahllllll commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Every streamed chunk crosses LegacyHookDispatcher.fireReasoningChunk, which snapshots the whole answer so far into a Msg before the dispatch loop runs:

if (content instanceof TextBlock) {
    accumulatedContent = TextBlock.builder().text(context.getAccumulatedText()).build();
}
...
return Flux.fromIterable(agent.getSortedHooks()).flatMap(hook -> hook.onEvent(event)).then();

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:

hookDispatcher.fireReasoningChunk(msg, context, name).contextWrite(...).subscribe();

which allocates a Mono, copies the Reactor context and starts a subscription per chunk, only for the result to be Mono.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 main the same guard measures −3.6 s, with the difference accounted for by main's own drift since that tag — see Independent measurement below.

Change

  • LegacyHookDispatcher gains hasHooks(), and fireReasoningChunk / fireSummaryChunk return immediately when nothing is registered — before the snapshot is built. fireActingChunk takes the same early return.
  • The reasoning and summary chunk stages in ReActAgent skip the per-chunk subscription entirely when no hook is registered.
  • The hooks list is now read once per chunk instead of once per event, and reused for the dispatch.

What does not change

With hooks registered, the same ReasoningChunkEvent carries the same accumulated Msg and the same incremental chunk, in the same order; the early return only replaces the Flux.fromIterable(empty).flatMap(...).then() that already produced Mono.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-check concatMap, is now its own PR: #4088.

Tests

LegacyHookDispatcherChunkTest:

Case Before After
reasoning chunk, no hooks getAccumulatedText() invoked never invoked
summary chunk, no hooks getAccumulatedText() invoked never invoked
reasoning chunk, hook registered hook receives snapshot "abc" and incremental "c" unchanged

The first two fail on main with Mockito's Never wanted here ... But invoked here for ReasoningContext.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 them DangerousPathBypassTest.symlinkTo{Ssh,DotEnv}IsDetected — a Windows symlink-privilege limitation that fails identically on unmodified main.
  • 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* and LegacyHookDispatcher differ, so head − parent isolates this guard on current main rather than comparing against a tag.

Per-token delivery:

build mean chain time
stock 2.0.4 151.2 s
parent (no guard) 142.8 s
head (this PR) 139.2 s

≈ −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.

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.
@realreus319

Copy link
Copy Markdown

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.

@wahllllll

Copy link
Copy Markdown
Contributor Author

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 d27f8230

Full ref, in case the checkout above drifts: wahllllll/agentscope-java:refs/heads/perf/issue-3929-skip-chunk-accumulation, head d27f8230, whose parent 4af86c518 is on main, so the tree merges cleanly onto today's main (33 commits behind, zero conflicts). It is one commit and it contains only the guard — no pipeline reshape, no transport change, no config change, so a difference in your numbers is attributable to the guard alone.

Three things I would want from the run:

  • whether the −5.7 s survives unchanged, since nothing else moved;
  • identical model-call / tool-call / token counts and 100% completion — the part I can only pin with a unit test, not with your load;
  • TTFT at 500 under burst delivery (your 3.23 s figure). The guard sits on the "is a hook registered" branch, not on delivery, so I expect it not to move, and not moving is the result I want to see.

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 — checkInterrupted() is only interruption.isInterrupted() ? error : empty wrapped in a Mono, so your §2 can become a synchronous handle that either passes the chunk through or terminates the stream, with order and backpressure preserved because handle is sequential. The thing I will not trade away is the stop landing mid-stream, and I will pin that in a test. I will post the branch here when it is done; the concatMapIterable reshape (§3) changes the shape of the chunk path and deserves its own PR and its own run after that.

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 maxAttempts(3) duplication you found while auditing is a separate defect from this one. Would you rather file it yourself with the request/prepared duplication angle, or should I open it so it does not get lost in this thread? Either is fine by me.

@wahllllll

Copy link
Copy Markdown
Contributor Author

The interruption change is done and up as a separate PR: #4088, branch perf/issue-3929-sync-interrupt-check, head 8d3a4385b.

git fetch wahl perf/issue-3929-sync-interrupt-check
git checkout wahl/perf/issue-3929-sync-interrupt-check

checkInterrupted() is now read in a handle step instead of a Mono behind concatMap, in both the reasoning stream and the summary stream.

One thing I did not expect to find while doing it: concatMap ran that check one chunk ahead of the consumer. The inner Mono for chunk N+1 was already subscribed while chunk N's events were being consumed, so an interrupt signalled during N still let N+1 through. With the read inline, the stream stops on N. On main the test reports expected: <alpha> but was: <alphabeta> — three runs, three times — and alpha with the branch. So your −5.1 s may come with an interruption-latency fix attached, which is worth having independently of the timing.

Nothing else moved: handle processes elements one at a time so ordering and backpressure are unchanged, checkInterrupted() is still used at the per-step call sites, and the whole of agentscope-core is 3026 tests with 0 failures (2 pre-existing Windows symlink errors, same on main).

If this one runs on your harness the same way, the pair would cover two of your three changes, and the concatMapIterable reshape waits until I see how these two land — it is the one that changes the shape of the chunk path, so I would rather not have two unsettled restructurings open at once.

@realreus319

Copy link
Copy Markdown

Head-to-head results, as requested. One methodological note first: your branch sits on current main, whose ReActAgent.java has drifted substantially since the 2.0.4 tag (the chunk path now enters through a ModelRequestPreparer layer), so we built three jars from full Maven builds of each tree, with the benchmark scaffold byte-identical across them: stock = 2.0.4 release, parent = your parent commit 4af86c51 (no guard), head = d27f8230. A class-level diff of the parent and head jars (18,489 classes each) shows only ReActAgent*.class and LegacyHookDispatcher.class differ, so head − parent isolates your guard on today's main. Same harness as #3929: chains of 10 streaming calls × 300 tokens + 9 tool calls, ~61 s unloaded (head calibration 60.88 / 60.94 s, exact counts), 500 concurrent chains, fresh JVM per group.

1. Does the −5.7 s survive? Partially — it is −3.6 s on current main.
Per-token (metronome) delivery, Go chain driver:

build mean chain time
stock 2.0.4 151.2 s
parent (no guard) 142.8 s (runs: 141.1 / 144.5)
head (guard) 139.2 s (runs: 137.5 / 140.9)

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.
All 10 groups (calibration + both delivery pairs): 100% completion, 0 errors, 0 timeouts, and exactly 10 model calls / 9 tool calls / 300 tokens per call in every group — identical to stock.

3. TTFT under burst delivery: unmoved, as you predicted.
100 ms burst delivery, Node chain client, 500 chains: head TTFT 3.78 s vs parent 3.80 s (−0.02 s, inside noise). Whole-chain means under burst were 114.2 s vs 112.6 s, also indistinguishable — the guard's win shows under per-token delivery; under bursts it neither helps nor hurts within what we can resolve. For reference, stock 2.0.4 in the same session measured 135.8 s / TTFT 4.19 s — please compare TTFT within this session only; absolute values shift between sessions (our earlier 3.23 s stock figure came from a different session), while the within-session deltas are the stable part.

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.

@wahllllll

Copy link
Copy Markdown
Contributor Author

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 head − parent attributable, and I would not have thought to do it. I am taking your correction as the record: ≈ −3.6 s per chain on main, with ~8.4 s of the head-vs-stock gap being main's own drift since 2.0.4 and not creditable to the guard. #3961 now carries that framing rather than the −5.7 s, attributed to you, because the 2.0.4 figure would overstate what this change does today.

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 8d3a4385b, parent 9ab7a4fab, which is today's main tip, so your parent/head pair is exactly main and main-plus-one-commit. It touches ReActAgent.java and one new test class, so your jar diff should show ReActAgent* alone.

Two things worth watching, one of which is behaviour rather than timing:

  • I expect the interruption change to shrink like the guard did, for the same reason main drifted. I would rather learn that from you than assume the −5.1 s.
  • The interrupt now lands on the chunk that is in flight instead of the next one. If your harness can drive a mid-stream interrupt, that is the scenario that moved: on main, interrupting while chunk N is being consumed still delivers N+1; on the branch it stops at N. Counting delivered chunks after an interrupt pins it, and it is a latency win independent of the throughput one.

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.

@wahllllll

Copy link
Copy Markdown
Contributor Author

@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 ReActAgent*), so the delta is attributable to the change rather than to main's drift.

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.

@jujn
jujn merged commit 76a1ff5 into agentscope-ai:main Nov 11, 2026
5 checks passed
@wahllllll

Copy link
Copy Markdown
Contributor Author

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.

jujn pushed a commit that referenced this pull request Nov 12, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 重要不紧急

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants