Skip to content

feat(core): expose failover listener for model fallback observability - #3145

Merged
Buktal merged 1 commit into
agentscope-ai:mainfrom
Buktal:feat/failover-listener
Sep 14, 2026
Merged

Buktal merged 1 commit into
agentscope-ai:mainfrom
Buktal:feat/failover-listener

Conversation

@Buktal

@Buktal Buktal commented Sep 14, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #3142

问题

主备模型的 failover 对下游完全静默:主模型的错误在 ReActAgent#modelForCall 构建的包装器内部被 switchOnFirst 消费,只留一行 log.warn。该位置低于 onModelCall 中间件接缝、也低于 AgentEvent 转换层,ModelCallEndEvent 只携带 replyId + usage——进程内不存在任何观察面能拿到「哪个模型因什么错误被切换」。

下游(指标、限流冷却、告警)只能从副作用重建(比对包装器 getModelName() 的事后值),间接且有损:原始 Throwable 永远丢失,无法区分 429 与 5xx。

方案

新增 FailoverListener(io.agentscope.core.agent.config):

void onFailover(Model primary, Throwable error);
  • 在切换现场(switchOnFirst 内)同步回调,携带主模型实例与原始错误——事实出生点直报;
  • 契约:reactor 线程同步调用须快速非阻塞;单实例跨并发 run 共享须线程安全;实现抛出的异常仅记录日志,不影响切换与后续 fallback 调用;
  • 挂载完全沿用 fallbackModel 既有先例:ModelConfig 第三字段(@JsonIgnore,保留双参构造器兼容既有调用方)、ReActAgent.Builder.failoverListener(...)、fromAgent 拷贝、HarnessAgent.Builder 委托与 config 重建路径拷贝;
  • 默认 null,行为与现状逐位一致。

本 PR 刻意只做观察语义,不含跳过/降级策略——策略由下游基于本信号自持状态实现。

典型用法

ReActAgent.builder()
        .model("dashscope:qwen-plus")
        .fallbackModel("dashscope:qwen-max")
        .failoverListener((primary, error) ->
                metrics.recordFailover(primary.getModelName(), error))
        .build();

测试

  • 切换发生时回调收到主模型实例与原始错误(各断言一次);
  • 实现抛异常时切换与 fallback 服务不受影响;
  • 主模型成功、未配置 fallback 时均不回调;
  • fromAgent 拷贝 listener;ModelConfig JSON 序列化不含 listener。

文档:v2 zh/en building-blocks/agent.md(示例 + 契约说明)、middleware.md(说明切换为何观察不到、应使用 listener 而非 middleware)。

## 问题

主备模型的 failover 对下游完全静默:主模型的错误在 `ReActAgent#modelForCall`
构建的包装器内部被 `switchOnFirst` 消费,只留一行 `log.warn`。该位置低于
`onModelCall` 中间件接缝、也低于 `AgentEvent` 转换层,`ModelCallEndEvent`
只携带 `replyId + usage`——进程内不存在任何观察面能拿到「哪个模型因什么错误被切换」。

下游(指标、限流冷却、告警)只能从副作用重建(比对包装器 `getModelName()`
的事后值),间接且有损:原始 Throwable 永远丢失,无法区分 429 与 5xx。

## 方案

新增 `FailoverListener`(`io.agentscope.core.agent.config`):

```java
void onFailover(Model primary, Throwable error);
```

- 在切换现场(`switchOnFirst` 内)同步回调,携带主模型实例与原始错误——事实出生点直报;
- 契约:reactor 线程同步调用须快速非阻塞;单实例跨并发 run 共享须线程安全;
  实现抛出的异常仅记录日志,不影响切换与后续 fallback 调用;
- 挂载完全沿用 `fallbackModel` 既有先例:`ModelConfig` 第三字段(`@JsonIgnore`,
  保留双参构造器兼容既有调用方)、`ReActAgent.Builder.failoverListener(...)`、
  `fromAgent` 拷贝、`HarnessAgent.Builder` 委托与 config 重建路径拷贝;
- 默认 null,行为与现状逐位一致。

本 PR 刻意只做观察语义,不含跳过/降级策略——策略由下游基于本信号自持状态实现。

## 测试

- 切换发生时回调收到主模型实例与原始错误(各断言一次);
- 实现抛异常时切换与 fallback 服务不受影响;
- 主模型成功、未配置 fallback 时均不回调;
- `fromAgent` 拷贝 listener;`ModelConfig` JSON 序列化不含 listener。

文档:v2 zh/en `building-blocks/agent.md`(示例 + 契约说明)、`middleware.md`
(说明切换为何观察不到、应使用 listener 而非 middleware)。
@codecov

codecov Bot commented Sep 14, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Adds a FailoverListener observation seam for primary→fallback model switching: a new @JsonIgnore third component on ModelConfig, ReActAgent.Builder.failoverListener(...), HarnessAgent.Builder delegation plus both fromAgent copy paths, and a synchronous callback at the actual switch site inside switchOnFirst. Observability-only, default null keeps current behaviour. LGTM.

What I verified

  • Backward compatibility — the explicit ModelConfig(int, Model) convenience constructor keeps the old canonical signature, so existing callers and serialized snapshots are unaffected; defaults() and the two-arg path both leave the listener null (asserted in ModelConfigTest).
  • Failure isolation — notifyFailover null-guards the listener and contains Exception with a log.warn, so a broken listener cannot break the switch or the fallback call; the fallback stream is still returned. The payload is the primary model instance and the original Throwable, which is the right contract for downstream rate-limit/alerting use.
  • Credential handling — nothing new is logged beyond the existing primary/fallback name warn; the listener is excluded from JSON so callbacks can never leak into a state snapshot.
  • Copy paths — both ReActAgent.Builder.fromAgent and HarnessAgent.Builder.fromAgent propagate the listener, matching the fallbackModel precedent, and the javadoc table row was updated to rowspan="3".
  • Tests — four behavioural cases (notified exactly once with primary identity + original error, throwing listener still falls back, silent on primary success, silent without fallback) plus the fromAgent copy assertion; they assert outcomes rather than timing, so no obvious flakiness.

Non-blocking note: since ModelConfig is a record, equals/hashCode now fold in the listener instance, so two agents configured with structurally identical but distinct lambdas are no longer equal. Nothing in core/harness compares ModelConfig today, so this is only worth remembering if a future config-diff or caching path relies on that equality.

CI is green on this head (build ubuntu/windows, validate, module sync, license/cla) and merge state is BLOCKED only on review.


Automated review by github-manager-bot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: Surface fallback model switching to application code — the switch and its cause currently reach only the log

2 participants