Skip to content

[Bug]: HarnessAgent.streamEvents() does not recover from context overflow while call() does #3171

Open

Description

@KANLON

Describe the bug
HarnessAgent.call() already detects model context-overflow errors and triggers emergency compaction plus one retry via recoverFromOverflow().

However, HarnessAgent.streamEvents() does not have the same recovery. When the model rejects a streaming request with a context-overflow error, the raw provider 400 is propagated to the subscriber without compaction or retry.

This is especially visible in streaming/SSE deployments, where the user only sees an error message like:

HTTP transport error during streaming: HTTP request failed with status 400 | {"error":{"code":400,"message":"input token limit is 1048576","type":"invalid_request_error"}}

To Reproduce
Steps to reproduce the behavior:

call code

        HarnessAgent agent = cached.agent;
            java.util.function.Supplier<Msg> streamCall = () -> {
                if (activeRun.cancelRequested.get()) {
                    return null;
                }
                return agent.streamEvents(buildUserMessage(req), rc)
                        .takeUntilOther(activeRun.cancelSignal.asMono())
                        .doOnNext(evt -> {
.....
.....

            Msg finalMsg;
            try {
                finalMsg = streamCall.get();
            } catch (Exception first) {
.....
.....

ask

Image

generate_random_string method

Image

Expected behavior

streamEvents() should behave consistently with call():

  • Detect context-overflow errors.
  • Run emergency compaction with triggerMessages=1.
  • Persist the compacted AgentState before retrying.
  • Replay the event stream once.
  • Errors from the replay should not re-enter the overflow handler, so there is no retry loop.

Error messages
Detailed error messages.

Image

Environment (please complete the following information):

  • AgentScope-Java Version: [2.0.2]
  • Java Version: [17]
  • OS: [windows]

Activity

  1. added
    bug
    on Sep 16, 2026
  2. oss-maintainer commented on Sep 16, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Area: area/harness | Status: Confirmed | Severity: medium

    Verified against current main (6c8ccc5c6, 2.0.3-SNAPSHOT). The asymmetry described in the report is real.

    Evidence

    Claim Result Location
    call() detects overflow and retries once after emergency compaction confirmed HarnessAgent.java:961-964 — base.onErrorResume(... isContextOverflowError(e) → recoverFromOverflow(msgs, effective))
    Overflow recovery helpers exist confirmed recoverFromOverflow :1048-1053, forceCompactAndRetry :1060, detector isContextOverflowError :1105
    streamEvents() has no equivalent recovery confirmed all overloads (:863, :871, :883, :891, :903, :922) funnel into wrappedStreamEvents (:993), which has no onErrorResume, no isContextOverflowError check and no recoverFromOverflow call — the provider error is propagated raw to the subscriber
    The streaming error text would have matched the detector confirmed the detector is a case-insensitive substring match including token limit, so HTTP transport error during streaming … "input token limit is 1048576" matches; it simply is never consulted on the streaming path
    Zero test coverage for the recovery path confirmed no test in the repo exercises HarnessAgent overflow recovery on either path (HarnessAgentTest never references isContextOverflowError / recoverFromOverflow; CompactionMiddlewareTest covers compaction fallback only)

    Not provider-specific — because detection is text-based, every model provider whose overflow reply contains one of the seven matched substrings hits this, so the gap is on the harness streaming path, not in an extension.

    We are not opening our own PR here. #3170 (open, non-draft, @KANLON, agentscope-harness only, +59/−15) already adds recoverFromOverflowStream() and registers the resume inside the sandbox scope. That PR is the carrier; a second PR would collide on the same lines. Review continues in the PR patrol.

    Four hazards the streaming fix has to answer explicitly (worth confirming on #3170 rather than re-reporting here):

    1. Partially emitted events. delegate.streamEvents(...) can emit events before the overflow surfaces, so a replay that restarts the delegate stream may re-emit an earlier prefix. The contract must be one of: suppress duplicates, emit an explicit retry marker, or document that the stream restarts from scratch — consumers doing incremental rendering will otherwise show duplicated text.
    2. Sandbox resource scope. wrappedStreamEvents runs inside Flux.using with acquireForCall / releaseForCall; the recovery must stay inside that scope and release exactly once on terminal signal, which is what fix(harness): recover from context overflow on the streaming path #3170's description claims to do.
    3. State mutation under concurrency. forceCompactAndRetry mutates state.contextMutable() (:1092-1093). On the reactive path this happens while other calls on the same (userId, sessionId) slot may be in flight — needs the same per-session isolation guarantee call() relies on.
    4. No second-failure guard. call() retries exactly once with no backoff; if emergency compaction itself fails or does not shrink the context enough, the streaming variant inherits the same single-shot behavior. Please keep the replay non-reentrant (an error from the replay must not re-enter the handler, as the report requests).

    Suggest adding regression coverage for both paths as part of the fix: a stub model that throws a token limit error on the first attempt and succeeds after compaction, asserted once for call() and once for streamEvents(), including a case where events were already emitted before the failure.


    Automated evaluation by github-manager-bot

  3. added
    area/harness
    on Sep 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/harnessbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions