Skip to content

fix(core): check interruption synchronously between streamed chunks - #4088

Merged
jujn merged 1 commit into
agentscope-ai:mainfrom
wahllllll:perf/issue-3929-sync-interrupt-check
Nov 12, 2026
Merged

jujn merged 1 commit into
agentscope-ai:mainfrom
wahllllll:perf/issue-3929-sync-interrupt-check

Conversation

@wahllllll

@wahllllll wahllllll commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

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

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:

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.

The behavioural fix

An interrupt now lands on the chunk that is in flight. concatMap subscribed to the next chunk's Mono before the consumer had seen the current chunk's events, so a stop signalled while a chunk was being consumed let one more chunk through.

Pinned by ReActAgentSyncInterruptTest, on main:

interruptBetweenChunksStopsTheStreamAtTheChunkInFlight
  an interrupt must land before the next chunk, not after the whole response
  ==> expected: <alpha> but was: <alphabeta>

Three runs on main, three times alphabeta; with this change, alpha. The other two cases pin what must not move: chunks arrive in order when nothing interrupts, and interrupting after the last chunk changes nothing.

Who the extra chunk reaches (measured 2026-11-11)

A burst of 20 countable chunks, interrupt fired when the first text delta reaches the consumer — 5 runs per build:

build deltas delivered
parent 9ab7a4fab [0, 1] — 5/5 runs
head 8d3a4385b [0] — 5/5 runs

So the leak is real, and it is real for delta consumers: a streaming UI, a harness accumulating TextBlockDeltaEvents, or a log sees one chunk on main that this change stops.

The returned Msg is unaffected, and that is worth stating so nobody reads this as a data-corruption fix: on both builds the terminal message is the fixed interruption text with reason INTERRUPTED, byte-identical, and the partial text appears nowhere in it — the cancellation path discards the partial answer wholesale (verified through streamEvents, 5 runs, and call(), 3 runs).

Scope of that probe: it ran without a state store or memory configured, so it covers the returned-message path only. A caller that persists deltas as they arrive would persist the extra chunk on main; that path is untested here and is not claimed either way.

Tests

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0   (ReActAgentSyncInterruptTest)
Tests run: 3026, Failures: 0, Errors: 2, Skipped: 9   (whole agentscope-core)

The two errors are the pre-existing Windows symlink-privilege failures in DangerousPathBypassTest (symlinkToSshIsDetected, symlinkToDotEnvIsDetected); they fail the same way on main without this change.

Independent measurement (2026-11-10, by @realreus319)

Same method as the #3961 run: full Maven builds of parent (9ab7a4fab, current main tip) and head (8d3a4385b), byte-identical benchmark scaffold, and a class-level jar diff first — 19,056 files each, 10 differ, all ReActAgent*.class (the test class is not in the production jar).

Timing: below that harness's resolution, no regression. Per-token delivery, 500 concurrent chains, three parent/head pairs: −5.93 s, +2.07 s, +8.08 s; means 142.7 s vs 144.1 s. Same-jar repeats drifted ±8–9 s in that session, wider than the effect. Burst delivery: 116.8 s / TTFT 3.41 s (parent) vs 119.2 s / 3.61 s (head), also inside the drift band. The −5.1 s measured on 2.0.4 does not survive as a resolvable number on current main; what survives is "no regression". Reporting the first pair alone would have claimed a −5.9 s reproduction that the next two pairs contradict.

Interrupt latency: confirmed independently, at two levels. This PR's test, copied verbatim into the parent build, fails 3/3 with exactly expected: <alpha> but was: <alphabeta> and passes 3/3 on head. A separate stream-level probe (20 countable chunks, 5 runs per build, interrupt fired on the first chunk under burst arrival): the parent delivers exactly one extra chunk in 5/5 runs, the head stops exactly in 5/5.

Boundaries worth knowing: fired at the fifth chunk, neither build leaks; under 20 ms per-token spacing, neither build leaks. The run-ahead only shows itself when the source has already buffered ahead — bursty arrival, which is the production-like delivery shape.

Method note worth keeping: their first head build silently packaged a stale snapshot and diffed identical to parent. The class-level diff runs before any timing, which is what caught it.

Not in scope

The third change from #3929 (synchronous event generation, concatMapIterable instead of an inner Flux per chunk) is not included; it reshapes the chunk path and deserves its own PR and its own run.

Refs #3929

Every streamed chunk crossed a concatMap stage whose entire work was
checkInterrupted() — a read of the interruption flag wrapped in a Mono. The
read is a field access, so it can happen in the same step that passes the
element on: handle either continues with the chunk or ends the stream with the
same InterruptedException.

Ordering and backpressure are unchanged, because handle processes one element at
a time. Two things do change:

- the per-chunk Mono, its subscription and the asynchronous handoff around it
  are gone from both the reasoning and the summary stream;
- an interrupt now lands on the chunk that is in flight. concatMap subscribed
  to the next chunk's Mono before the consumer had seen the current chunk's
  events, so a stop signalled while a chunk was being consumed still let one
  more chunk through; with the check in place the stream stops where the flag
  was set.

Both are pinned by ReActAgentSyncInterruptTest: chunk order is preserved, an
interrupt between chunks stops before the next one, and interrupting after the
last chunk changes nothing. On main the middle case delivers "alphabeta" where
this branch delivers "alpha", deterministically.
@realreus319

Copy link
Copy Markdown

Results for #4088, same method as the #3961 run: full Maven builds of parent (9ab7a4fab, current main tip) and head (8d3a4385b), byte-identical benchmark scaffold, and a class-level jar diff first — 19,056 files each, only 10 differ, all ReActAgent*.class; your test class is not in the production jar, exactly as you said. (The gate earned its keep again: our first head build silently packaged a stale snapshot and diffed identical to parent; caught and rebuilt before any timing ran.) Calibration on head: 60.89 / 60.85 s, exact 10/9/300 counts. All 10 timing groups: 100% completion, zero errors/timeouts, exact counts.

Timing: not resolvable on this harness today — reporting it flat, as you asked.
Per-token delivery, 500 chains, three parent/head pairs (we ran extra pairs because the first two disagreed in sign): paired differences −5.93 s, +2.07 s, +8.08 s; means parent 142.7 s vs head 144.1 s. Same-jar repeats drifted ±8–9 s this session, far noisier than the #3961 session, so any effect of this change is smaller than our noise band. Reporting only the first pair would have claimed a −5.9 s "reproduction" that the next two pairs contradict. Under burst delivery: parent 116.8 s / TTFT 3.41 s vs head 119.2 s / TTFT 3.61 s — also inside the drift band. So this is consistent with your expectation that the 2.0.4 figure (−5.1 s, which was also measured stacked on top of the guard) would shrink on current main — but how far it shrank, we cannot honestly read. No regression is visible either; the differences are indistinguishable from session noise in both directions.

Interrupt behaviour: confirmed, in both layers — this is the solid result.
(a) Your test, copied verbatim into the parent build: fails 3/3 with exactly expected: <alpha> but was: <alphabeta>; on head it passes 3/3.
(b) An independent stream-level probe (same middleware trigger as your test, 20 countable chunks, 5 runs per build): when chunks arrive in a burst and the interrupt lands on the first chunk, parent delivers exactly one extra chunk in 5/5 runs; head stops exactly in 5/5 runs.
Two honest boundaries: triggered at the fifth chunk, neither build leaks; and under 20 ms per-token spacing, neither build leaks — the off-by-one shows itself under bursty arrival, which is the production-like delivery shape.

Summary from our side: independent measurement, no objection. The timing effect of this change is below what we can resolve and shows no regression; the interrupt-latency fix is real, independently reproduced at both unit and stream level, and in our view is worth having on its own. Together with the #3961 guard (verified −3.6 s on main, TTFT unmoved, counts clean), the pair looks sound to us.

@wahllllll

Copy link
Copy Markdown
Contributor Author

Reporting it flat is exactly what I wanted, and it is more useful than a number I would have had to defend: three pairs, two of them with the opposite sign, and a ±8–9 s session drift. #4088 will carry "below resolution on this harness, no regression visible" rather than leaving the −5.1 s sitting there unanswered.

The interrupt result is the one worth having, and your 5/5 stream-level probe with the burst-arrival boundary characterises it better than my single unit test: off-by-one under bursty delivery, not under 20 ms spacing, and not at the fifth chunk. That points straight at the run-ahead in concatMap — it only shows when the source has already buffered ahead — and I will record that boundary in the PR so nobody later reads the fix as "interrupts always landed late".

Thank you also for the stale-snapshot catch. A first head build that diffs identical to parent is exactly the failure that would have made the whole exercise meaningless; I would like to cite that as part of the method.

One question, since only your harness can answer it: under burst delivery, does the extra chunk that parent delivers actually reach the persisted answer, or does the cancel path drop it? If it persists, this is bigger than one chunk of latency and I would say so in the PR.

@wahllllll wahllllll changed the title perf(core): check interruption synchronously between streamed chunks fix(core): check interruption synchronously between streamed chunks Nov 10, 2026
@realreus319

Copy link
Copy Markdown

Follow-up on your question from last night — whether the extra chunk survives into the answer the framework returns or persists. We probed it on the same two jars (parent 9ab7a4fab / head 8d3a4385b): 20 countable chunks delivered in a burst, interrupt triggered by middleware when the first text delta reaches the consumer — your test's trigger.

It does not reach the returned message. On both builds, the terminal Msg — via streamEvents (5 runs each) and via call() (3 runs each) — is the fixed interruption text ("I noticed that you have interrupted me. What can I do for you?"), byte-identical between parent and head, with reason INTERRUPTED. The partial text (c0; — and on parent also c1;) appears nowhere in the returned message; the cancellation path discards the partial answer wholesale and substitutes the interruption notice. (Uninterrupted baseline on parent returns all 20 chunks, reason MODEL_STOP.)

But it does reach stream consumers. Parent delivered deltas [0, 1] in 5/5 runs; head delivered [0] in 5/5. So any caller that assembles the answer from TextBlockDeltaEvents itself — a streaming UI, a harness accumulating deltas, logging — sees one extra chunk on main that the branch stops. For those callers your "bigger than one chunk of latency" framing holds; for callers that only take the returned Msg, it does not — that path already throws the partial answer away cleanly.

One scope note: the probe ran without a state store or memory configured, so this covers the returned-Msg path only. A caller that persists deltas as they arrive would persist the extra chunk on main.

@wahllllll

Copy link
Copy Markdown
Contributor Author

Thank you — that is a sharper answer than my question deserved, and it splits my claim in two.

The accurate statement is: the extra chunk reaches delta consumers, not the answer. For anything assembling the text from TextBlockDeltaEvents — a streaming UI, a harness accumulating deltas, a log — main lets one chunk through that this branch stops. For callers that only read the returned Msg, both builds already discard the partial answer wholesale and substitute the interruption notice, byte-identical, reason INTERRUPTED. I was half a step away from calling this a corruption fix; your probe is what stops me writing that.

I have put exactly that in #4088, including your scope note verbatim in spirit: the probe ran without a state store, so a caller that persists deltas as they arrive would persist the extra chunk on main, and this run does not speak to that path. I would rather state the untested part as untested than let a reviewer infer I tested it.

No further rig on my account. If the persistence variant ever happens to be one flag away in your harness it is worth one line, but the delta-level result already decides how the change should be described, and nothing in this PR should be merged on the strength of my speculation about the store path.

Two things I owe you, since you have now measured both PRs independently: your numbers are the only performance evidence in either description, attributed to you, and both descriptions say so explicitly rather than borrowing your result as if it were ours. If either lands, the credit line stays.

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