Skip to content

[Bug]: Synchronous model stream failures bypass the configured fallback #3148

Closed

Description

@pengmoubuaixuexi

Describe the bug

With fallbackModel configured, a failure before the primary emits its first response takes different paths depending on how Model.stream() reports it:

  • return Flux.error(failure) switches to the fallback and notifies FailoverListener.
  • throw failure before returning the Flux aborts the agent call; neither the fallback nor the listener runs.

ReActAgent.modelForCall() invokes model.stream(...) before installing switchOnFirst. A synchronous exception therefore escapes that fallback boundary. This matters for custom model adapters and provider-specific setup/formatting failures. ChatModelBase.stream() also delegates through Tracer.callModel() directly to the supplied implementation, so it does not generally normalize synchronous exceptions.

To Reproduce

In the repository's agentscope-core JUnit tests, the following uses the existing MockModel and TestUtils fixtures; no credentials or model endpoint are needed:

import static org.junit.jupiter.api.Assertions.assertEquals;
import io.agentscope.core.ReActAgent;
import io.agentscope.core.agent.test.MockModel;
import io.agentscope.core.agent.test.TestUtils;
import io.agentscope.core.message.Msg;
import io.agentscope.core.model.ChatResponse;
import io.agentscope.core.model.GenerateOptions;
import io.agentscope.core.model.Model;
import io.agentscope.core.model.ToolSchema;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;

class SynchronousFallbackTest {
    @Test
    void shouldUseConfiguredFallback() {
        Model primary = new Model() {
            @Override
            public Flux<ChatResponse> stream(
                    List<Msg> messages, List<ToolSchema> tools, GenerateOptions options) {
                throw new IllegalStateException("primary unavailable");
            }
            @Override
            public String getModelName() { return "primary"; }
        };
        MockModel fallback = new MockModel("fallback response");
        ReActAgent agent = ReActAgent.builder()
                .name("demo").model(primary).fallbackModel(fallback).build();
        Msg response = agent.call(TestUtils.createUserMessage("user", "hello"))
                .block(Duration.ofSeconds(5));
        assertEquals("fallback response", TestUtils.extractTextContent(response));
        assertEquals(1, fallback.getCallCount());
    }
}

Run mvn -pl agentscope-core -Dtest=SynchronousFallbackTest -Dspotless.skip=true test.
Replacing the throw with return Flux.error(new IllegalStateException("primary unavailable")); makes the same case succeed.

Expected behavior

A synchronous model invocation failure before any response should use the same configured fallback path as an initial reactive error, with the original error delivered to the listener. Errors after a response has already been emitted should continue to propagate without switching models.

Error messages

IllegalStateException: primary unavailable escapes the agent call. A parameterized local regression covering both error forms plus a mid-stream-error control reports Tests run: 3, Failures: 0, Errors: 1, Skipped: 0 on unmodified main; the synchronous case is the sole error.

Environment

  • AgentScope Java: 2.0.3-SNAPSHOT, main 60934595a7e9f6805bd0649a68d26766b158042e
  • Java: Temurin 17.0.15; Maven 3.9.12
  • OS: Windows

Additional context

The minimal fix I tested defers the primary invocation with Flux.defer(() -> model.stream(...)) before switchOnFirst. All three boundary cases then pass, as do the selected agent, builder, configuration and timeout/retry tests (57 tests total). It does not add retry or cooldown policy.

I checked #1851, #3145, #2864 and #2968: the listener addition and original single-fallback wiring retain the eager invocation; the optional multi-model chain leaves the legacy single-fallback path unchanged; empty-completion handling is a different case. I would like to contribute the small fix and regression tests.

AI assistance was used for source investigation and the patch; the reported local tests were executed and the diff reviewed. No live provider outage or HTTP response is claimed.

Activity

  1. oss-maintainer commented on Sep 15, 2026

    @oss-maintainer
    Collaborator

    Issue Evaluation

    Category: bug | Status: Confirmed

    Verified statically against main @ 60934595a7e9.

    Root Cause: ReActAgent.modelForCall() (agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java:4078) invokes model.stream(messages, tools, options) eagerly and only then installs the switchOnFirst fallback boundary on the returned publisher. A Model.stream() implementation that throws before returning a Flux therefore escapes the method, so neither the activeModel.set(fallbackModel) / notifyFailover(...) branch nor the fallback subscription runs. ChatModelBase.stream() does not normalize this either: it delegates doStream() through Tracer.callModel(), whose default implementation calls modelCall.get() directly (Tracer.java:46-53), and TracerRegistry defaults to NoopTracer.

    Impact: ReActAgent reasoning calls and max-iteration summary calls with a configured fallbackModel; FailoverListener observability is skipped for this failure class. Existing regression tests only cover the Flux.error(...) form (MockModel never throws synchronously), which is why the gap is invisible to CI.

    Severity: medium — defeats configured failover for pre-stream provider/setup failures; no data corruption or security boundary violation.

    On the proposed fix: Flux.defer(() -> model.stream(...)) before switchOnFirst is correct and minimal. Reactor turns an exception from the deferred supplier into an error signal, which reaches the existing first-signal branch unchanged; after a first onNext the callback returns flux, so a later onError still propagates without switching models. No retry/cooldown semantics change.

    Action: No automated fix proposal is generated here — PR #3149 (opened by the reporter against this issue) already implements exactly this change plus regression coverage. Please review and test there. Note that neither the PR nor this evaluation has had the new test executed in our CI-less check environment; build-level verification relies on the PR's CI run.


    Automated evaluation by github-manager-bot

  2. added
    bug
    area/core/agent
    on Sep 15, 2026
  3. added a commit that references this issue on Sep 15, 2026
    a51d176
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/core/agentbug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions