Skip to content

feat(core): add multi-level model fallback chain (fallbackModels) - #2864

Open
Letter2025 wants to merge 9 commits into
agentscope-ai:mainfrom
Letter2025:feat/fallback-chain
Open

Letter2025 wants to merge 9 commits into
agentscope-ai:mainfrom
Letter2025:feat/fallback-chain

Conversation

@Letter2025

Copy link
Copy Markdown
Contributor

Summary

Adds multi-level model fallback as a pluggable, opt-in Model wrapper plus a builder switch:

  • FallbackChainModel (io.agentscope.core.model): tries an ordered chain [primary, fb1, fb2, ...]. On a failure that switching can recover from (429 / 5xx / timeout / network / 401 / 403) it moves to the next candidate; on a request-side failure (400/422 and other 4xx) it fails fast without consuming the chain.
  • Per-candidate cooldown (default 30s, configurable): a failed candidate is skipped for the window, then becomes eligible again — lazy recovery verified by real traffic, no scheduler/threads, fully in-memory.
  • Mid-stream failures are not retried on a fallback (avoids duplicating delivered content), but still apply cooldown.
  • Capability delegation: getModelName() / supportsNativeStructuredOutput() / getContextWindowSize() report the currently active candidate, so callers can observe which model actually served the turn.
  • ReActAgent.Builder.fallbackModels(Model...): opt-in switch — when no chain is configured, the existing single-fallback path is byte-for-byte unchanged (zero default behaviour change, backward compatible). Users can also wire the wrapper directly via model(new FallbackChainModel(primary, fallbacks)).
  • Agent-scoped shared cooldown table: every modelForCall() creates a fresh wrapper, but all wrappers share the agent's cooldown table — cooldown survives reasoning rounds and successive requests; the active-model reference stays per-call (concurrency-safe).

Example

ReActAgent.builder()
        .model("dashscope:qwen-plus")
        .fallbackModels(
                List.of(
                        ModelRegistry.resolve("dashscope:qwen-max"),
                        ModelRegistry.resolve("openai:gpt-4o-mini")))
        .build();

Compatibility

  • fallbackModel(Model/String), maxRetries(int), ModelConfig record: all untouched.
  • No new dependencies, no threads, no external state.

Tests

  • FallbackChainModelTest (12): primary success; switch on 503; full-chain exhaustion propagates last error; 401/403 switch; timeout/network switch; 400 fail-fast; mid-stream no-switch + cooldown; cooldown skip + lazy recovery; cooldown persistence across wrapper instances (shared table); null/empty handling; null primary rejected; capability delegation.
  • ReActAgentFallbackChainTest (4 integration): agent falls back on 503; primary-only default unchanged; fail-fast does not consume chain; direct wrapper wiring via .model(...).
  • Full agentscope-core model+agent package regression: 327 tests, 0 failures.

Closes #2863

@Letter2025
Letter2025 force-pushed the feat/fallback-chain branch from 28dc6c6 to cb6ac0b Compare August 27, 2026 09:51
@codecov

codecov Bot commented Aug 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.17021% with 26 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...a/io/agentscope/core/model/FallbackChainModel.java 88.80% 7 Missing and 7 partials ⚠️
...e/src/main/java/io/agentscope/core/ReActAgent.java 80.95% 5 Missing and 7 partials ⚠️

📢 Thoughts on this report? Let us know!

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR has conflicts with the main branch and cannot be merged. Please rebase or merge main into your branch and resolve the conflicts:

git fetch origin
git checkout feat/fallback-chain
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Feel free to @mention me for a review once the conflicts are resolved.


Automated notification by github-manager-bot

@oss-maintainer

Copy link
Copy Markdown
Collaborator

⚠️ Merge conflict detected

This PR currently conflicts with main and cannot be merged. Please rebase (or merge main in) and resolve the conflicts:

git fetch origin
git checkout feat/fallback-chain
git rebase origin/main
# resolve conflicts, then:
git push --force-with-lease

This is a one-time reminder. Ping me after the conflicts are resolved and I will re-review.


Automated notification by github-manager-bot

@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 an opt-in multi-level model failover wrapper (FallbackChainModel) plus a ReActAgent.Builder.fallbackModels(...) switch, with per-candidate cooldown and failure classification. Well-structured, genuinely useful feature and the test suite is thorough — the concern is that the new chain path silently drops the FailoverListener observability that #3145 just added, and that a few pieces of shared state (activeModel, the name-keyed cooldown map) are riskier than the docs assume under the concurrent, long-lived agents this framework targets.

Top items:

  • [Warning] notifyFailover(...) is never invoked on the chain path — failover becomes invisible for fallbackModels(...) users.
  • [Warning] activeModel is mutated at assembly time on a wrapper shared by concurrent calls, so getModelName()/getContextWindowSize()/supportsNativeStructuredOutput() can report the wrong candidate.
  • [Warning] cooldown keyed by model name only + never evicted.
  • [Warning] last-candidate log line reads like a successful switch, then the chain errors.

Findings

9 inline comments — see the diff. None of them are blocking design objections; the missing failover notification and the per-call model binding are the two I would fix before merge.

Notes

  • CLA is signed; I have not re-notified about the merge conflict since a reminder was already posted on this HEAD.
  • Not approving in this round because of the items above — push updates and @mention me for a re-review.

Automated review by github-manager-bot

// and per-candidate cooldown live in FallbackChainModel. Cooldown state is shared at
// agent scope (survives across reasoning rounds and successive requests), while the
// active-model reference stays per-call so concurrent calls do not interfere.
if (!fallbackModels.isEmpty()) {

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.

[Warning] This early return bypasses the FailoverListener plumbing that the rest of modelForCall() uses on the legacy path (added in #3145): notifyFailover(...) is never called for chain candidates, so agents configured with fallbackModels(...) silently lose failover observability that single-fallback users already have.

Could FallbackChainModel take an optional FailoverListener and emit one notification per switch (candidate -> next candidate, with the causing error)? That keeps both paths behaviourally consistent and is the first thing an operator debugging a broken provider will look for.

Comment on lines +4025 to +4030
// Multi-level fallback chain (the pluggable extension point): when configured, wrap the
// primary model so failures transparently try the next candidate. Failure classification
// and per-candidate cooldown live in FallbackChainModel. Cooldown state is shared at
// agent scope (survives across reasoning rounds and successive requests), while the
// active-model reference stays per-call so concurrent calls do not interfere.
if (!fallbackModels.isEmpty()) {

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.

[Warning] fallbackModels(...) and the legacy fallbackModel(...) can both be configured at the same time, and the chain then silently wins (this if returns before the legacy block). A builder-time check that rejects or at least logs the combination would prevent a very quiet misconfiguration — e.g. chain=[a,b] plus fallbackModel=c, where c is never tried and never reported.

candidateName,
error.getMessage(),
candidates
.get(Math.min(index + 1, candidates.size() - 1))

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.

[Warning] When the switchable candidate is the last one in the chain, Math.min(index + 1, candidates.size() - 1) logs the model that just failed as "switching to fallback candidate", and then line 191 recurses into the exhausted-chain guard and errors out. During an outage that log line reads as if a switch succeeded — exactly when someone is grepping the logs.

Suggest resolving the actual next eligible candidate before logging, or emitting "chain exhausted after " when index + 1 >= candidates.size().

(signal, flux) -> {
if (signal.isOnError()) {
Throwable error = signal.getThrowable();
return switch (classify(error)) {

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.

[Warning] activeModel (line 169) is a single field on a wrapper shared by all in-flight calls, and it is mutated at assembly time here — attempt() runs eagerly from stream(), so candidate.stream(...) is invoked before subscription. The class Javadoc presents the active-model reference as per-call, but with one agent instance serving concurrent sessions it is effectively global.

That means getModelName() (line 266), supportsNativeStructuredOutput() and getContextWindowSize() can report a model that is not the one serving the caller's request — and getContextWindowSize() drives compaction decisions while supportsNativeStructuredOutput() drives request construction, so the mismatch is not only cosmetic. Consider binding the chosen candidate per call (pass the resolved Model down the response pipeline) instead of an AtomicReference on the shared wrapper.

/**
* Failure classification for fallback switching.
*
* <p>{@code SWITCHABLE}: another candidate may succeed — rate limit (429), server error

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.

[Warning] Two related issues with the cooldown table:

  1. It is keyed by getModelName(), so two candidates that expose the same model name behind different keys/endpoints share one entry — failing one cools the other within the window.
  2. Entries are only ever put, never evicted. The map is agent-scoped and agents are long-lived (this is the stated design), so it grows with every distinct model name ever seen.

A composite key (name + endpoint/key hash) plus eviction of expired entries on write would keep the map bounded and the semantics precise.

}

Model candidate = candidates.get(index);
String candidateName = candidate.getModelName();

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.

[Info] If every candidate is inside its cooldown window, attempt() walks off the end of the chain without ever failing and returns ModelException("All model candidates in the fallback chain failed") — nothing was tried in this call, so the message is misleading during a transient burst (e.g. two requests inside the same 30s window after one provider outage).

Consider counting the skipped candidates and raising a distinct message such as "all N candidates are in cooldown, earliest recovery in s", so callers can tell "providers broken" apart from "we are rate-protecting ourselves".

* @return this builder
*/
public Builder fallbackModels(List<Model> fallbacks) {
this.flatFallbackModels = fallbacks == null ? List.of() : List.copyOf(fallbacks);

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.

[Info] The Javadoc above promises the list "may be empty or contain nulls" and that "null entries are skipped", but List.copyOf(fallbacks) throws NPE on a null element and performs no filtering (the varargs overload does filter). Either filter here the same way, or drop the promise from the doc.

// agent scope (survives across reasoning rounds and successive requests), while the
// active-model reference stays per-call so concurrent calls do not interfere.
if (!fallbackModels.isEmpty()) {
return new FallbackChainModel(

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.

[Info] FallbackChainModel implements the same switch-on-first-error contract as the anonymous Model wrapper a few lines below in this method. Folding the single-fallback case into the chain (new FallbackChainModel(model, List.of(fallbackModel), ...)) would leave one implementation of switchOnFirst semantics to maintain instead of two that can drift — the only thing to preserve is the notification ordering the existing failover tests assert (primary first, then the fallback's stream).

@@ -0,0 +1,543 @@
/*

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.

[Info] Nice coverage overall (cause-chain classification, cooldown lazy recovery, shared table across wrapper instances, mid-stream non-switching, capability delegation). Two paths are still untested and both are the ones most likely to regress, and CallRecordingModel could drive them cheaply: (a) every candidate cooling at once, which exercises the index >= candidates.size() guard with lastFailure == null; (b) a REQUEST_SIDE failure reached after a SWITCHABLE one, i.e. that the chain stops immediately instead of continuing to walk.

Introduces FallbackChainModel, a pluggable Model wrapper that tries an ordered chain of candidates: on a switchable failure (429/5xx/timeout/network/401/403) it moves to the next candidate; on a request-side failure (400/422 and other 4xx) it fails fast without consuming the chain. Per-candidate cooldown (default 30s) with lazy recovery avoids hammering broken models, and the cooldown table is shared at agent scope so it survives reasoning rounds and successive requests. ReActAgent.Builder.fallbackModels(...) is the opt-in switch; without a chain the legacy single-fallback path is unchanged.

Closes agentscope-ai#2863
Previous run failed on agentscope-harness JsonSessionDefaultLocationTest with 'Failed to close extension context' (JUnit @tempdir cleanup). Reproduced locally with 3/3 passing; failure is environmental, not related to the fallback chain change.
…builder overloads, fromAgent)

Adds tests for ModelHttpException (429/422/no-status), HttpTransportException without status, IO/unknown/wrapped-cause classification, supportsNativeStructuredOutputWithTools delegation, null shared cooldown table, varargs fallbackModels overload, empty-varargs chain disable, and Builder.fromAgent chain copy.
…tempt

Replaces the switch statement (with its unreachable default arm) by an exhaustive switch expression over the closed FailureCategory enum, so every category is covered at compile time and the dead default branch is eliminated.
…ty, bounded cooldown

Review follow-up for agentscope-ai#2864 (github-manager-bot, 9 findings):

- FailoverListener: FallbackChainModel now takes an optional FailoverListener (same contract as the legacy path) and notifies once per switch with the failed candidate; ReActAgent.modelForCall wires the agent's listener into the chain. Exceptions from the listener are contained.
- Per-call identity: removed the shared AtomicReference<Model> activeModel; capability queries (getModelName / supportsNativeStructuredOutput(WithTools) / getContextWindowSize) now report the primary — the chain's stable identity — so concurrent calls can never observe another call's active candidate. Active candidate is observable via FailoverListener + warn logs.
- Cooldown table: composite key (modelName + instance identity) so same-named candidates on different endpoints do not cool each other; expired entries are evicted on write, keeping the agent-scoped table bounded.
- Logging: last-candidate failure now logs 'chain exhausted' instead of a misleading 'switching to fallback candidate'; all-cooling case reports a distinct message ('all N candidates are in cooldown; nothing was attempted').
- Builder: fallbackModels(...) and fallbackModel(...) now reject each other (IllegalStateException) instead of silently letting the chain win; fallbackModels(List) filters nulls like the varargs overload (matches javadoc).
- Tests: capability delegation asserts primary identity; new coverage for all-cooling message, REQUEST_SIDE-after-SWITCHABLE stop, listener notification + exception containment, builder conflict rejection, null elements in List overload.
@Letter2025

Copy link
Copy Markdown
Contributor Author

@oss-maintainer all 9 findings addressed — branch rebased onto current main (conflict resolved), CI green (ubuntu + windows + codecov), all fixes in 23cdc2a7. Point-by-point:

#1 FailoverListener — fixed. FallbackChainModel now accepts the io.agentscope.core.agent.config.FailoverListener (the #3145 contract) and notifies once per switch with the failed candidate + causing error, matching the legacy path's semantics. ReActAgent.modelForCall() wires the agent's listener into the chain. Listener exceptions are contained (logged, switch proceeds).

#2 dual config — fixed. fallbackModels(...) + fallbackModel(...) in either order now throw IllegalStateException instead of silently letting the chain win (documented on both methods).

#3 last-candidate log — fixed. "switching to fallback candidate X" is only logged when a next candidate exists; the last candidate logs "Fallback chain exhausted after candidate X failed".

#4 activeModel under concurrency — fixed by design change. Removed the shared AtomicReference<Model>. Capability queries (getModelName / supportsNativeStructuredOutput(WithTools) / getContextWindowSize) now report the primary — the chain's stable identity — so concurrent calls never observe another call's active candidate and compaction/structured-output decisions see a consistent value. The active candidate per call is observable via FailoverListener + warn logs. Javadoc updated.

#5 cooldown key/growth — fixed. Composite key modelName + instance identity; expired entries evicted on write so the agent-scoped table stays bounded.

#6 all-cooling message — fixed. Unambiguous error: "All N fallback candidates are in cooldown; nothing was attempted this call".

#7 List javadoc vs NPE — fixed. fallbackModels(List) filters nulls like the varargs overload, matching the javadoc.

#8 folding single fallback into the chain — deliberately not done. The legacy path is official stable behaviour (switch on any first-signal error), while the chain classifies failures (request-side 4xx fail fast instead of switching). Folding would change existing single-fallback semantics for 400/422. Both paths share the same FailoverListener contract and warn-log shape, so observability no longer drifts. Happy to revisit with a shared helper if you prefer.

#9 missing tests — added. Every-candidate-cooling (distinct message, zero attempts), REQUEST_SIDE-after-SWITCHABLE stop (third candidate never attempted), listener notified once per switch, listener exception containment, builder conflict both orders, null elements in List overload, capability delegation on primary.

Local: FallbackChainModelTest 26/26, ReActAgentFallbackChainTest 9/9, model+agent package 370 tests green, spotless applied. @mentioning for re-review.

@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

Re-review of e5c775aa..23cdc2a7 (rebased, force-pushed). All nine items from the previous round are addressed, and the two hardest ones were handled properly rather than patched around: FailoverListener is now threaded into the chain and invoked at each switch site with listener exceptions contained, and the shared AtomicReference<Model> activeModel is gone — capability queries report the primary as the chain's stable identity, so concurrent calls can no longer observe each other's candidate. Cooldown is keyed per instance with eviction on write, the builder rejects fallbackModel + fallbackModels in either order, the exhausted-chain log line no longer reads like a successful switch, and the null-list javadoc mismatch is fixed. The added tests match the claims: 26 in FallbackChainModelTest and 9 integration tests in ReActAgentFallbackChainTest, including the two adversarial cases I most wanted pinned (REQUEST_SIDE after a SWITCHABLE stops the chain immediately; every-cooling reports a distinct message with zero attempts). CI green on 23cdc2a7, CLA signed.

On #8 (not folding the legacy single fallback into the chain) — I buy the reasoning. Switch-on-any-first-signal-error versus failure-classified switching are observably different contracts for 400/422, and preserving the stable path outranks deduplicating ~40 lines. Sharing the FailoverListener contract across both is the right compromise; no need to revisit.

Findings

Nothing here is a logic bug in the switching path. The one item I would fix before merge is documentation-vs-code drift introduced by the fix for #4:

  • [Warning] docs/v2/en/docs/building-blocks/agent.md:657 still says capability queries "delegate to the currently active candidate" — the pre-fix behaviour you just removed. The class javadoc was updated, the user doc wasn't, so the documented contract now contradicts FallbackChainModel:338-360.
  • [Warning] FallbackChainModel:338 — reporting the primary turns an occasional race into a systematic capability mismatch: once switched, supportsNativeStructuredOutput() and getContextWindowSize() describe a model that is not serving the call. Needs either a build-time compatibility check across the chain or an explicit "candidates must be capability-compatible" contract.
  • [Warning] FallbackChainModel:240 — mid-stream failures cool the candidate on the same 30s terms as first-signal failures, even though a post-first-chunk error is far more likely to be request-shaped, and the table is agent-scoped so one bad request parks the primary for every concurrent session.
  • [Warning] FallbackChainModel:185 — the all-cooling ModelException carries no cause, and 401/403 is classified SWITCHABLE, so an expired key degrades from "clear auth error" into "all candidates in cooldown; nothing was attempted this call" with the real reason only in the logs. Message also counts the primary as a "fallback candidate".
  • [Info] FallbackChainModel:258 tautological size() > 0 && !isEmpty() guard; :286 identityHashCode is not guaranteed unique where the chain index would be; agent.md:626 the new section has no ZH counterpart.

Inline comments have the details and suggested shapes. Fix the agent.md:657 line and decide on the capability-mismatch question (a doc sentence is acceptable for #2 if you'd rather not add validation), and this is good to go from my side. Merge decision stays with the maintainers.


Automated review by github-manager-bot

fallback: switching mid-response can duplicate already-delivered content. The failure is
recorded (cooldown applies) and propagated as-is.
- Capability queries (`getModelName`, `supportsNativeStructuredOutput`,
`getContextWindowSize`) delegate to the currently active candidate.

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.

This bullet states the opposite of what fix #4 just changed the code to do. FallbackChainModel.getModelName() / supportsNativeStructuredOutput() / getContextWindowSize() all return the primary's values (see FallbackChainModel.java:338-360), and the class javadoc was updated to say exactly that ("report the primary model's values — the chain's stable identity"). The user-facing doc still says they "delegate to the currently active candidate", which was the pre-fix behaviour and the thing you removed because it raced.

Suggest:

- Capability queries (`getModelName`, `supportsNativeStructuredOutput`,
  `getContextWindowSize`) report the **primary** model — the chain's stable identity — so they
  never observe another concurrent call's active candidate. Use the `FailoverListener` (or the
  warn logs) to see which candidate actually served a call.

This one matters more than it looks: it's the documented contract users will rely on when they put a smaller-context or non-structured-output model into the chain.

}

@Override
public String getModelName() {

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.

Reporting the primary fixes the concurrency race, but it converts an occasional race into a systematic capability mismatch, and I don't think the tradeoff is finished yet.

ReActAgent feeds modelForCall() straight into new ModelCallInput(messages, tools, options, modelForCall()) (ReActAgent.java:2576), and the structured-output / compaction paths ask the model what it can do. With a chain of qwen-plus -> gpt-4o-mini (your own docs example), once the chain has switched:

  • supportsNativeStructuredOutput() returns the primary's true, so the request is still built with a native response_format/tool-schema shape the actual candidate may reject — which then classifies as a 400/422 REQUEST_SIDE failure and fails the whole call instead of falling back;
  • getContextWindowSize() returns the primary's window, so compaction triggers on the wrong budget for a smaller-window candidate.

Both are new-by-design rather than new-by-accident, so the minimum I'd want before this is mergeable is one of:

  1. a build-time check that the chain is capability-homogeneous (getModelName aside) — reject or warn when a candidate reports a smaller getContextWindowSize() or a different supportsNativeStructuredOutput*() than the primary; or
  2. documenting the requirement on fallbackModels(...) and on this class's javadoc: "candidates must be capability-compatible with the primary; the chain reports the primary's capabilities regardless of which candidate serves the call."

(1) is the better default here — an inconsistent chain is almost certainly a config mistake, and catching it at build() is a one-time cost on a path that already constructs a List.copyOf.

midStreamError -> {
// Mid-stream failure: do not switch (content may already have
// been delivered); record the cooldown and propagate as-is.
recordFailure(candidateKey);

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.

Cooling a candidate for a mid-stream failure is a different risk from cooling it for a first-signal failure, and this line makes the two identical. switchOnFirst sees an error before any content is delivered — a provider/transport problem, where skipping the candidate for 30s is right. Here the candidate already started streaming: the cause is just as likely to be this particular request (a prompt that makes the provider abort mid-generation, a tokenizer edge case, a too-large payload) as the candidate being unhealthy. Because coolUntilMillis is agent-scoped and shared across concurrent calls (ReActAgent.java:249-252), one request-shaped mid-stream failure parks the primary for every other session of that agent for 30 seconds.

The escalation path is what makes this worth changing: after the primary is parked, the next call's first signal comes from the fallback; if that one also blips, all candidates end up cooling and the call now fails with the synthetic message at line 181-187 that carries no cause at all — the original error is only in the logs.

Minimal change: classify before cooling, and don't park on non-transport mid-stream errors:

.onErrorResume(midStreamError -> {
    if (classify(midStreamError) == FailureCategory.SWITCHABLE) {
        recordFailure(candidateKey);
    }
    return Flux.error(midStreamError);
})

cooldownSkips > 0
? "All "
+ cooldownSkips
+ " fallback candidates are in cooldown;"

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.

Two problems in this message, one cosmetic and one operational.

Cosmetic: cooldownSkips counts every skipped candidate including the primary, so with a primary + 2 fallbacks all cooling this prints "All 3 fallback candidates are in cooldown" when only 2 of them are fallbacks. "All 3 candidates in the fallback chain are in cooldown" is accurate.

Operational: this ModelException is constructed with no cause, so the caller — and anything upstream doing failure classification, retry or alerting — loses the reason the chain is cooling. classify() treats 401/403 as SWITCHABLE (line 331 comment), so an expired API key is a guaranteed path here: first call rotates through every candidate, cools all of them, second call onwards fails with "...in cooldown; nothing was attempted this call" and no cause, which reads like a capacity problem rather than a credential problem. Two options, both small:

  • keep the last real failure (e.g. in the shared table or an AtomicReference<Throwable> alongside it) and pass it as the cause; or
  • don't cool auth failures at all — a wrong credential will not fix itself inside 30s, so failing fast with the provider's 401 message preserves the signal.

The first is strictly better than today and I'd take it on its own; the second is the one I'd actually prefer for 401/403.

*/
private void recordFailure(String key) {
long now = System.currentTimeMillis();
if (coolUntilMillis.size() > 0 && !coolUntilMillis.isEmpty()) {

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.

coolUntilMillis.size() > 0 and !coolUntilMillis.isEmpty() are the same predicate, so one of the two is dead code — and isEmpty() on a ConcurrentHashMap walks the whole thing via sumCount() anyway. if (!coolUntilMillis.isEmpty()) reads cleaner; the removeIf on entrySet() is already a no-op on an empty map, so the guard could also just go away.

Nit, not a blocker — the eviction-on-write idea itself is right and keeps the agent-scoped table bounded at chain length.

* down; the instance identity keeps their entries separate.
*/
private static String candidateKey(Model model) {
return model.getModelName() + '@' + System.identityHashCode(model);

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.

Using System.identityHashCode for instance identity gets you the semantics you document (same-name, different-instance candidates don't cool each other), but it leans on a hash that is explicitly not guaranteed unique, and the composite key silently merges two distinct instances in the unlikely collision case — a cooldown applied to a candidate that never failed.

Since candidates is a List.copyOf fixed at construction and the table is agent-scoped, the list index is a collision-free key with the same property:

private static String candidateKey(int index, Model model) {
    return index + "@" + model.getModelName(); // chain position is stable and unique
}

Only worth doing while the key is being threaded through anyway (it also makes the shared-table contract in the 4-arg constructor easier to reason about — index is meaningful across wrapper instances because the chain order is fixed). Also worth one line of javadoc on the shared-table constructor: two FallbackChainModels sharing a table must expose their candidates in the same order for the entries to mean what they appear to mean.

the middlewares. Implementations must be non-blocking and thread-safe; exceptions they throw are
logged and ignored without affecting the switch.

#### Multi-level fallback chain (fallbackModels)

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.

Small repo-convention nit: the new section is EN-only. docs/v2/zh/docs/building-blocks/agent.md has the adjacent failoverListener section (zh line ~615) but no fallbackModels counterpart, so the Chinese page now documents the single-fallback path only. Recent PRs in this repo (including the nacos-mcp one) ship EN and ZH together — worth mirroring here, even a short translation of the five bullets.

…g semantics

Follow-up to the re-review (all 4 warnings + 3 infos addressed):

- Capability contract (agentscope-ai#338): ReActAgent validates the chain at build time and warns when a candidate reports a smaller context window or different structured-output support than the primary (the chain reports the primary's capabilities). FallbackChainModel javadoc documents the compatibility requirement; agent.md EN+ZH updated.
- Cooldown semantics (agentscope-ai#185, agentscope-ai#240): auth failures (401/403) are no longer cooled — a wrong credential will not fix itself and the real auth error must surface; they still switch. Mid-stream failures only cool the candidate when classified SWITCHABLE (request-shaped failures like oversized payloads do not park the primary for other sessions). The all-cooling error now propagates the last real failure as cause (remembered per candidate) instead of a bare synthetic message; wording no longer counts the primary as a 'fallback candidate'.
- Cooldown key (agentscope-ai#286): replaced System.identityHashCode with the stable chain index (collision-free across wrapper instances sharing a table with the same candidate order).
- Cleanup (agentscope-ai#258): removed the tautological size() > 0 && !isEmpty() guard (removeIf is a no-op on an empty map).
- Docs (agentscope-ai#657, agentscope-ai#626): agent.md EN capability bullet now matches the code (reports the primary); added the ZH fallbackModels section mirroring the EN one.

Tests: 3 new cases (auth-not-cooled, mid-stream request-side not cooled, all-cooling preserves cause); existing cooldown-message test updated to assert the propagated last failure; FallbackChainModelTest 29/29, ReActAgentFallbackChainTest 9/9, model+agent package 373 green.
@Letter2025

Copy link
Copy Markdown
Contributor Author

@oss-maintainer second-round findings addressed in 69e72bb1 — CI green (ubuntu + windows + codecov + validate/Mintlify), all inline items handled:

[Warning] agent.md:657 doc drift — fixed. EN capability bullet now says capability queries report the primary (stable identity) and points to the FailoverListener/warn logs for the serving candidate. Class javadoc and user doc now agree.

[Warning] FallbackChainModel:338 capability mismatch — fixed with a build-time check. ReActAgent validates the chain at construction and warns when a candidate reports a smaller getContextWindowSize() or different supportsNativeStructuredOutput(WithTools) than the primary (unknown capabilities are tolerated silently). Chose warn over reject: models legitimately report 0/default for unknown capabilities, and a hard reject would break valid chains whose candidates simply don't expose metrics. The fallbackModels(...) javadoc and this class's javadoc now state the capability-compatibility requirement explicitly.

[Warning] FallbackChainModel:240 mid-stream cooling — fixed. Mid-stream failures now only cool the candidate when classify(...) returns SWITCHABLE (and it is not an auth failure). Request-shaped mid-stream errors (oversized payload, parse abort, etc.) no longer park the primary for other concurrent sessions.

[Warning] FallbackChainModel:185 all-cooling error — fixed in both directions. (a) 401/403 are no longer cooled at all — they still switch to the next candidate, but a wrong credential won't repair itself in 30s and the real auth error must surface instead of a cooldown message. (b) The all-cooling error now propagates the last real failure as cause (remembered per candidate), so diagnostics/alerting keep the original reason. Message wording no longer counts the primary as a "fallback candidate".

[Info] FallbackChainModel:258 tautological guard — fixed. The size() > 0 && !isEmpty() guard is gone; removeIf on an empty map is already a no-op.

[Info] FallbackChainModel:286 identityHashCode — fixed. Cooldown key is now the stable chain index + model name (index@name), collision-free across wrapper instances sharing a table with the same candidate order; noted on the shared-table constructor javadoc.

[Info] agent.md:626 no ZH counterpart — fixed. Added the fallbackModels section to docs/v2/zh/docs/building-blocks/agent.md, mirroring the EN bullets (cooldown/auth-not-cooled, mid-stream classification, primary-identity capabilities, builder compatibility warning).

Tests: 3 new cases (auth failures not cooled; request-shaped mid-stream failure not cooled; all-cooling error preserves the last real failure as cause). Updated the existing all-cooling test to assert the propagated cause. Locally: FallbackChainModelTest 29/29, ReActAgentFallbackChainTest 9/9, model+agent package 373 green, spotless applied. @mentioning for re-review.

@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

Round 3 of this PR (23cdc2a7..69e72bb1) addresses every item from the previous round — doc drift on capability delegation, the build-time compatibility check, mid-stream cooling narrowed to transport-class failures, 401/403 excluded from cooldown, the last-failure cause on all-cooling errors, the tautological eviction guard, and a ZH counterpart for the new section. CI is green on the current head (build (ubuntu) / build (windows) / validate / Check License / Check Module Sync / codecov/patch) and license/cla is signed. Thanks for the thorough, point-by-point responses — the direction is clearly right.

The delta introduces a handful of new issues worth resolving before merge; none of them are design-level, so I'm leaving this as a comment rather than a change request:

  • [Warning] ReActAgent:753 — the new validation calls Model-SPI getters unguarded from the constructor, so a throwing third-party capability implementation now breaks agent construction.
  • [Warning] ReActAgent:770 — the javadoc claims unknown capabilities are tolerated silently, but supportsNativeStructuredOutput() has no unknown state (interface default is false), so legitimate mixed-provider chains warn on every build.
  • [Warning] FallbackChainModel:175 — lastFailureByKey is per-wrapper while the cooldown table is shared, so the new cause propagation degrades to the synthetic message for every wrapper but the one that recorded the failure.
  • [Warning] FallbackChainModel:326 — index@name fixes the unstable-identity point but drops the instance separation the previous javadoc required: shared tables can now park a differently-credentialed candidate with the same model name.
  • [Info] auth failures are switchable but never cooled, so a revoked key costs a doomed round-trip on every call with no backpressure; the per-failure sweep of a shared table is now unconditional; and the new builder check has no test coverage.

Suggestions

For the cooldown key, the cleanest way to get both stability and instance separation is to key on the candidate itself (ConcurrentHashMap<Model, Long>, which is identity-based unless a provider overrides equals) — that survives wrapper rebuilds and keeps two same-named instances behind different endpoints apart. If you keep the string key, please state the "same table ⇒ same candidate identity" contract on the shared-table constructor javadoc, since that is where a multi-tenant caller will look.

For the capability check, gating on nativeOut && !primaryNative (only a candidate that positively claims more/less than the primary is actionable) keeps the signal you added while honouring the "unknown is silent" promise in the javadoc.


Automated review by github-manager-bot

if (fallbackModels.isEmpty() || model == null) {
return;
}
int primaryWindow = model.getContextWindowSize();

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.

[Warning] This validation runs inside the ReActAgent constructor and calls Model-SPI getters (getContextWindowSize(), supportsNativeStructuredOutput[WithTools](), getModelName()) on every candidate with no guard. Model is a public plugin interface (each provider extension implements it), so one third-party implementation that throws from a capability getter now turns into an agent that cannot be built at all — previously that getter was never called on the fallbacks. Wrap the per-candidate probe in a try/catch (RuntimeException) that logs at debug and skips the candidate, so a diagnostic check can never fail construction.

model.getModelName(),
primaryWindow);
}
if (nativeOut != primaryNative || nativeWithTools != primaryNativeWithTools) {

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.

[Warning] Javadoc/code mismatch: the comment at :745-747 promises "Unknown capabilities (getContextWindowSize() == 0, default supportsNativeStructuredOutput()) are tolerated silently", but only the window case is. supportsNativeStructuredOutput() has no unknown state — the Model interface default is false — so a candidate that simply does not override it is indistinguishable from one that genuinely lacks support. Result: a perfectly legitimate mixed chain (primary = DashScope with native structured output, fallback = any provider that leaves the default) logs a warning on every agent build, which is exactly the noise the "tolerated silently" sentence was meant to avoid. Either compare only when the candidate positively declares support (nativeOut && !primaryNative), or make the capability tri-state (Boolean / Optional) so "unknown" is representable, and align the javadoc either way.

this.sysPrompt = builder.sysPrompt;
this.model = builder.model;
this.fallbackModels = List.copyOf(builder.flatFallbackModels);
validateFallbackChainCapabilities();

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.

[Info] The new builder-side check has no test — grepping the PR head for validateFallbackChainCapabilities / "smaller context window" hits only ReActAgent.java itself, and ReActAgentFallbackChainTest is untouched. Since this method can throw (see the getter guard above) and its whole purpose is to distinguish "known-incompatible" from "unknown", one test per branch with a stub Model (window 0, default native flags, and a throwing getter) would pin the intended behaviour cheaply.

this.primary = primary;
this.cooldown = cooldown != null ? cooldown : DEFAULT_COOLDOWN;
this.coolUntilMillis = sharedCoolUntilMillis;
this.lastFailureByKey = new ConcurrentHashMap<>();

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.

[Warning] lastFailureByKey is per-wrapper while coolUntilMillis is deliberately shared, which defeats the purpose of this change in exactly the configuration the shared-table constructor exists for. When several FallbackChainModel instances share one cooldown table (agent wiring rebuilds the wrapper per call — see ReActAgent#modelForCall), wrapper B skips a candidate that wrapper A cooled and looks the failure up in B's own empty map: remembered == null, lastFailure == null, so the caller still gets the bare synthetic message. Store the last failure in the shared structure (e.g. ConcurrentHashMap<String, long[]>-style entry carrying untilMillis plus Throwable, or take a second shared map in the constructor) so the diagnostic survives across wrappers.

* (which the agent wiring does — it reuses the same candidate list every call).
*/
private static String candidateKey(int index, Model model) {
return index + "@" + model.getModelName();

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.

[Warning] Dropping instance identity here removes a protection the previous javadoc called out explicitly: "Two candidates that expose the same model name behind different endpoints/keys are distinct instances and must not cool each other down." With index@name, two wrappers sharing one table — the documented multi-call/multi-wrapper mode — collide whenever they place same-named but differently-credentialed candidates at the same index: one tenant's 429 parks another tenant's healthy key for the whole window. That matters for the multi-tenant wiring this class is designed to support. System.identityHashCode was unstable, true, but the replacement trades a missed share for a false share. Consider keying on the Model instance itself (ConcurrentHashMap<Model, Long> — identity semantics unless a provider overrides equals) or on index@name@endpoint; otherwise, please state the new contract in the shared-table constructor javadoc so callers know a shared table requires identical candidate identity, not just identical order.

// credential will not fix itself inside the window, so cooling
// would hide the real auth error behind a cooldown message. The
// candidate still switches (next one may hold valid credentials).
if (!isAuthFailure(error)) {

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.

[Info] Not cooling auth failures keeps the real error visible, which is right, but it also removes all backpressure: with a revoked/expired primary key every single call now pays a doomed primary round-trip (plus the switch warn log) before reaching a healthy candidate, for the lifetime of the process. Suggest a middle ground — a dedicated, much longer auth suppression (or a consecutive-failure threshold that parks the candidate) while still surfacing the original 401/403 as the cause, so the error stays diagnosable without a per-call penalty.

private void recordFailure(String key, Throwable error) {
long now = System.currentTimeMillis();
// removeIf on an empty map is a no-op, so no guard is needed.
coolUntilMillis.entrySet().removeIf(entry -> entry.getValue() <= now);

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.

[Info] The guard removal is correct (the old size() > 0 && !isEmpty() was tautological), but note the side effect: the sweep of the shared table now runs on every recorded failure. With one agent-scoped table this is free; with a table shared across many chains (thousands of entries, contended from several sessions) each failure walks the whole map. If a shared table is a supported deployment shape, evicting lazily (e.g. on the Nth write, or only when size() crosses a threshold) keeps the same bounded-memory guarantee without the per-failure O(n).

…yed shared tables

Follow-up to re-review (round 3, 4 warnings + 3 infos addressed):

- Guarded capability probe: validateFallbackChainCapabilities wraps each candidate's Model-SPI getter call in try/catch (RuntimeException) logged at debug, so a throwing third-party implementation can never fail agent construction.
- Noisy default-false warning removed: structured-output capability is compared only when the candidate positively declares support (nativeOut && !primaryNative); a default false (no override) is 'unknown' and tolerated silently, per javadoc.
- Cooldown/last-failure tables keyed by candidate Model identity (ConcurrentHashMap<Model, Long> / <Model, Throwable>): shared tables now keep instance separation (same-named candidates behind different endpoints stay apart) AND the remembered last failure survives wrapper rebuilds (the all-cooling error keeps its cause across wrappers sharing the tables). Shared-table constructor javadoc states the identity contract.
- Eviction on a shared table is now lazy: sweep only when the table grows past a threshold (64) instead of on every recorded failure, avoiding per-failure O(n) on large shared tables.
- New tests: capability validation tolerates unknown capabilities silently; survives throwing getters; warns on positive mismatch; stays silent when the fallback merely lacks primary capability. FallbackChainModelTest 30/30, ReActAgentFallbackChainTest 13/13, model+agent package 378 green.
@Letter2025

Copy link
Copy Markdown
Contributor Author

@oss-maintainer round-3 findings addressed in fc609eb7 — CI green (ubuntu + windows + codecov + validate + License + Module Sync). Point-by-point:

[Warning] ReActAgent:753 unguarded Model-SPI getters — fixed. validateFallbackChainCapabilities now wraps each candidate probe in try/catch (RuntimeException) logged at debug; a throwing third-party capability implementation can no longer fail agent construction (which is exactly the "diagnostic check must never break the build" contract).

[Warning] ReActAgent:770 default-false noise — fixed. Structured-output support is now compared only when the candidate positively declares it (nativeOut && !primaryNative, same for withTools). A candidate that simply leaves the interface default (false = unknown) no longer warns on every build; the javadoc now matches the code. The reverse direction (fallback lacking the primary's capability) stays silent for the same reason — false is indistinguishable from "not overridden".

[Warning] FallbackChainModel:175 per-wrapper last-failure table — fixed. lastFailureByKey is now shared alongside the cooldown table: the constructor takes both maps (keyed by candidate Model identity), and the agent wiring passes both agent-scoped tables through modelForCall(). The remembered last failure now survives wrapper rebuilds, so the all-cooling error keeps its real cause in exactly the multi-wrapper configuration the shared-table constructor exists for.

[Warning] FallbackChainModel:326 index@name losing instance separation — fixed. Cooldown and last-failure tables are now keyed by the candidate Model instance (ConcurrentHashMap<Model, Long> / <Model, Throwable>), preserving identity semantics: same-named candidates behind different endpoints/credentials stay apart even when their wrappers share one table. The shared-table constructor javadoc states the identity contract explicitly.

[Info] auth-not-cooled backpressure — noted, deliberately kept. A revoked key keeps surfacing the real 401/403 (the whole point of not cooling auth), and each call does pay the switch warn log before a healthy candidate. I kept the current semantics because (a) the round-2 reasoning stands — a wrong credential will not repair itself inside the window, and the auth error must not be masked by a cooldown message; (b) the shared-table last-failure propagation now keeps the underlying reason visible for diagnosis. If maintainers prefer, a follow-up could add a longer auth-specific suppression; I'd rather not add another knob to this PR.

[Info] per-failure O(n) sweep of a shared table — fixed. Eviction is now lazy: the expired-entry sweep only runs when the table grows past a threshold (64 entries), keeping the bounded-memory guarantee without a per-failure walk of large contended shared tables.

[Info] no test for the builder-side check — fixed. Four new tests in ReActAgentFallbackChainTest: unknown capabilities tolerated silently (both default-false models build without issue); throwing capability getters survive construction; positive mismatch (fallback declares native support the primary lacks) warns but still builds; fallback merely lacking the primary's capability stays silent. Locally FallbackChainModelTest 30/30, ReActAgentFallbackChainTest 13/13, model+agent package 378 green, spotless applied. @mentioning for re-review.

@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

Round 4 check of the delta 69e72bb1..fc609eb7. All five items from the previous round are genuinely fixed: the shared tables now survive wrapper rebuilds, the cooldown key is instance-stable, the capability probe is guarded, the doc bullet has a ZH counterpart, and capabilityValidationSurvivesThrowingGetters covers the throwing-SPI case. CI is green on the current head (build (ubuntu) / build (windows) / Check License / Check Module Sync / validate / codecov/patch) and license/cla is signed. Thanks for the point-by-point responses.

The delta introduces five smaller issues, none of them design-level, so this stays a comment rather than a change request:

  • [Warning] ReActAgent.java:812 — the new catch handler calls fallback.getModelName(), i.e. the same untrusted SPI surface, so a broken getModelName() still fails build().
  • [Warning] ReActAgent.java:796 — narrowing to nativeOut && !primaryNative silences the direction that can actually fail a request after a switch (candidate supports less than the primary) and keeps only the harmless one.
  • [Warning] docs/v2/en/docs/building-blocks/agent.md:664 — the bullet now promises a bidirectional build-time warning that the code no longer performs; the ZH page needs the same wording.
  • [Info] FallbackChainModel.java:323 — size() >= 64 is unreachable for a chain fixed at construction, so the sweep is dead code and each remembered Throwable is pinned for the agent lifetime (bounded, not a leak).
  • [Warning] ReActAgentFallbackChainTest.java:289 / :336 — the two "warns"/"stays silent" tests only assert assertNotNull(agent), so neither contract can regress.

Suggestions

The two that most affect users are the guard hole in the catch block (one-line fix) and the doc/code mismatch — the docs are the contract a multi-tenant operator reads when mixing providers, so please make the EN/ZH wording match what validateFallbackChainCapabilities() actually reports. For the capability direction, an explicit "is this capability declared or merely defaulted" signal on ChatModelBase would let the check be bidirectional without warning on every build of a legitimate mixed chain.

Cross-repo Note

None — this is contained to agentscope-core; the new public FallbackChainModel constructors are not yet released, so the signature change is not a compatibility break for downstream users.


Automated review by github-manager-bot

} catch (RuntimeException e) {
log.debug(
"Skipping capability check for fallback candidate {}: getter threw",
fallback.getModelName(),

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.

[Warning] The catch handler itself calls a Model-SPI getter. fallback.getModelName() is on the same untrusted surface that just threw, so a third-party implementation with a broken getModelName() escapes validateFallbackChainCapabilities() and fails build() — exactly the failure mode this try/catch was added to prevent.

Resolve the label defensively before the guarded block, e.g.:

String label;
try {
    label = fallback.getModelName();
} catch (RuntimeException e) {
    label = fallback.getClass().getName();
}

and use label in both the warn and debug calls (a nested try/catch around the log.debug also works). capabilityValidationSurvivesThrowingGetters keeps getModelName() working, so this path is currently uncovered.

boolean nativeWithTools = fallback.supportsNativeStructuredOutputWithTools();
// Only compare when the candidate positively declares support; a default false
// (no override) means "unknown", which is tolerated silently per the javadoc.
if ((nativeOut && !primaryNative) || (nativeWithTools && !primaryNativeWithTools)) {

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.

[Warning] Gating on the positive declaration only drops the direction that actually breaks requests. nativeOut && !primaryNative warns when the candidate is more capable than the primary — the harmless case (the extra support just goes unused). The failure-prone case is the reverse: primary declares native structured output, the request is built on that assumption, and a failover then hands that request to a candidate that cannot serve it.

I understand why the reverse direction was silenced (false is also the interface default, so "unknown" is indistinguishable from "explicitly unsupported"). Could we make those two states distinguishable instead of losing the check? Options, cheapest first:

  1. Treat a candidate as "declaring" support only when its class overrides the default, and warn when it overrides to false while the primary supports it (e.g. an capabilitiesDeclared()-style marker on ChatModelBase, or comparing getClass() against the interface default owner).
  2. Keep the current silence but surface it at runtime instead: FallbackChainModel could skip a candidate whose supportsNativeStructuredOutput() is false when the request needs native structured output, rather than failing the call.
  3. Document the residual gap explicitly in the javadoc bullet below and in the user docs (see the agent.md comment) so nobody reads the check as bidirectional.

never observe another concurrent call's active candidate. Use the `FailoverListener` (or the
warn logs) to see which candidate actually served a call. Candidates should therefore be
**capability-compatible** with the primary (same or larger context window, same
structured-output support); the builder warns at build time when they are not.

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.

[Warning] This sentence overpromises what the builder now checks. After the nativeOut && !primaryNative narrowing in ReActAgent.validateFallbackChainCapabilities(), the builder warns only for (a) a smaller context window when both sides report one, and (b) a candidate that claims more structured-output support than the primary. A candidate that supports less than the primary — the direction that can actually fail a request after a switch — is deliberately silent.

Suggest narrowing the wording, e.g.: "Candidates should therefore be capability-compatible with the primary; the builder warns when a candidate reports a smaller context window or declares structured-output support the primary lacks, but cannot detect a candidate that supports less than the primary (supportsNativeStructuredOutput() has no 'unknown' state), so that has to be verified by the caller."

Please mirror the same wording in docs/v2/zh/docs/building-blocks/agent.md — this is the second round where the EN bullet and the check have drifted.

*/
private void recordFailure(Model candidate, Throwable error) {
long now = System.currentTimeMillis();
if (coolUntilMillis.size() >= EVICTION_SWEEP_THRESHOLD) {

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.

[Info] This gate is unreachable in the wiring the tables exist for. Both maps are keyed by the candidate instances of a chain that is fixed at construction (List.copyOf), so coolUntilMillis.size() can never exceed the chain length — nobody configures a 64-deep fallback chain. Net effect versus the previous unconditional sweep: expired entries are never removed at all, and each remembered Throwable (with its stack trace and whatever its cause chain retains) is pinned for the agent's whole lifetime.

Size is still bounded, so this is not a leak, but the sweep is now dead code. Either:

  • drop the sweep and say so in the javadoc ("both tables are bounded by the chain length; entries are overwritten, never evicted"), which is honest and removes a branch, or
  • evict the pair on the success path of a candidate (clear its coolUntilMillis/lastFailureByKey entry once it serves a call), which also removes the stale cause a long-lived agent would otherwise report from an all-cooling error.


@Test
@DisplayName("Capability validation warns when a positive capability mismatch is detected")
void capabilityValidationWarnsOnPositiveMismatch() {

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.

[Warning] capabilityValidationWarnsOnPositiveMismatch (and capabilityValidationSilentWhenFallbackLacksPrimaryCapability at :336) only assert assertNotNull(agent). They therefore pass whether or not the check logs anything — the "warns"/"stays silent" in the names is not actually verified, and capabilityValidationToleratesUnknownCapabilities cannot regress either.

agentscope-core has no logging-binding test dependency, so the cheapest way to make these assertions real is to extract the diagnostics from the validation into a package-private seam, e.g.:

/** Package-private for tests: returns the capability warnings for every candidate. */
List<String> fallbackCapabilityWarnings()

have validateFallbackChainCapabilities() log whatever that method returns, and assert on the list size/contents (hasSize(1), empty(), message prefix) instead of on the built agent. That covers the positive-mismatch and the silence contracts without touching the classpath.

… contract, bounded tables

Follow-up to the round-4 re-review (4 warnings + 1 info):

- ReActAgent:812 — the capability-check catch handler called fallback.getModelName(), which is the same untrusted SPI surface; it now routes through safeModelName(), so a throwing name getter can no longer fail build(). The whole validation was also converted from log-and-void into a package-visible List<String> validator, making every branch directly assertable.
- ReActAgent:796 / agent.md:664 — doc/code contract aligned in EN + ZH: the build-time warning fires for an explicitly smaller context window, or structured-output support the candidate declares that the primary lacks. The reverse direction (candidate merely lacks the primary's support) is not reported because supportsNativeStructuredOutput() has no 'unknown' state; the docs now state this explicitly instead of promising a bidirectional check the code (and the SPI) cannot deliver.
- FallbackChainModel:323 — removed the unreachable EVICTION_SWEEP_THRESHOLD sweep (entries are keyed by the chain's fixed candidates, so the table is bounded at chain length by construction); javadoc now says a remembered Throwable is pinned for the agent lifetime as bounded retention, not a leak.
- Tests — new ReActAgentCapabilityValidationTest asserts the warning list directly for each branch (unknown tolerated, throwing getters skipped, smaller window warns, positive native mismatch warns, reverse silent, empty/null safe); removed the four assertNotNull-only capability tests from ReActAgentFallbackChainTest. Locally 380 tests green, spotless applied.
@Letter2025

Copy link
Copy Markdown
Contributor Author

@oss-maintainer round-4 findings addressed in bf0ae5e7 — CI green (ubuntu + windows + validate + license + codecov), all five items handled. Point-by-point:

[Warning] ReActAgent:812 catch handler calls fallback.getModelName() (same untrusted SPI) — fixed. The diagnostic path no longer touches the SPI outside the guarded try: getModelName() calls in warnings and in the catch handler now route through a private safeModelName() that returns "<unknown>" on any RuntimeException, so a broken name getter can no longer fail build(). Bonus: the whole check was converted from log-and-void into a package-visible List<String> validateFallbackChainCapabilities(...), which is what makes the new test class able to assert every branch directly.

[Warning] ReActAgent:796 one-directional comparison — kept, with the docs corrected and the reasoning pinned in code. The reverse direction (candidate supports less than the primary) is not reportable: supportsNativeStructuredOutput() has no "unknown" state — interface default false is indistinguishable from a genuine lack of support, and warning on every build of a legitimate mixed-provider chain (primary=DashScope native, fallback=default-false provider) would be exactly the noise the "tolerated silently" sentence promised to avoid. I chose to align the docs with the check rather than silence the one direction that is actually actionable. Your ChatModelBase "declared vs defaulted" signal idea is a good follow-up for making the check bidirectional; I'd rather not widen the SPI in this PR (Model is a public plugin interface), but noted for a future change.

[Warning] docs:664 EN/ZH promise vs code — fixed. Both pages now state precisely what the check reports: an explicitly smaller context window, or structured-output support the candidate declares that the primary lacks; and explicitly that the reverse direction is not reported for the no-"unknown"-state reason above, with a hint to check selected model capabilities yourself when mixing providers.

[Info] FallbackChainModel:323 unreachable size() >= 64 sweep — fixed. Removed the dead sweep entirely (entries are keyed by the chain's candidates, fixed at construction, so the table is bounded at chain length by construction). Javadoc now says a remembered Throwable is pinned for the agent lifetime as bounded retention, not a leak.

[Warning] ReActAgentFallbackChainTest:289/:336 assertNotNull-only — fixed properly. New ReActAgentCapabilityValidationTest calls the validator directly and asserts the returned warning list per branch: unknown capabilities → empty; throwing getters (window/native/name) → skipped, empty, no throw; smaller window → one warning naming the candidate; positive native mismatch → one warning; reverse direction → silent; empty chain / null primary → empty. Removed the four assertNotNull-only tests they replace. Locally: FallbackChainModelTest 30/30, ReActAgentFallbackChainTest 9/9, ReActAgentCapabilityValidationTest 6/6, model+agent package 380 green, spotless applied. @mentioning for re-review.

@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

Round-5 delta fc609eb7..bf0ae5e7 closes four of the five round-4 items cleanly: the catch path no longer trusts getModelName() (safeModelName()), the capability check is now a pure static returning warnings so ReActAgentCapabilityValidationTest can assert on the actual messages instead of assertNotNull(agent), the one-directional structured-output check is documented in both the javadoc and the EN/ZH docs (so docs and code agree again), and the unreachable size() >= 64 sweep is gone. Two remaining gaps, both about the scope of the new guarantees rather than the design — hence a comment rather than a change request. CI is green on the current head (build (ubuntu-latest) / build (windows-latest) / Check License / Check Module Sync / validate / codecov/patch) and license/cla is signed.

Findings

  • [Warning] ReActAgent.java:781-783 — the primary model's capability getters are read outside the try, so a throwing third-party primary still fails build(); the new javadoc claim and the test suite cover the candidate side only.
  • [Warning] FallbackChainModel.java:325 — dropping the sweep also drops the bound on the injectable shared tables; a caller sharing one map across wrappers with different candidate instances now grows it unbounded, pinning a Throwable per entry.

Suggestions

The primary-getter fix is a few lines and is the one that can actually break a user at construction time, so it is worth doing before merge; the shared-table one can be resolved either by the conditional cleanup or by one sentence in the constructor javadoc, whichever you consider the supported contract. If you decide the injectable maps are strictly agent-scoped and never caller-managed, say so in the javadoc and this reviewer is happy to call the delta complete.

Cross-repo Note

None — contained to agentscope-core; validateFallbackChainCapabilities is package-private and FallbackChainModel is unreleased, so no downstream compatibility impact.


Automated review by github-manager-bot

return warnings;
}
int primaryWindow = model.getContextWindowSize();
boolean primaryNative = model.supportsNativeStructuredOutput();

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.

[Warning] The new javadoc states that "a throwing capability getter from a third-party Model implementation is caught and skipped ... a diagnostic check must never fail agent construction", but the guard only covers the candidates: primaryWindow, primaryNative and primaryNativeWithTools are read here before the try at :784. A third-party primary whose getContextWindowSize() / supportsNativeStructuredOutput() throws still aborts ReActAgent.builder().build() — which is the same class of hole safeModelName() just closed on the catch path. Reading the three primary values through small safe helpers (primaryWindow(model) returning 0 on throw, primaryFlag(model, fn) returning false) inside the existing try, or wrapping the whole body, makes the code match the contract. Worth noting: ReActAgentCapabilityValidationTest.throwingGettersAreSkipped only makes the fallback throw, so a regression here stays green — adding a throwing-primary case would pin it.

*/
private void recordFailure(Model candidate, Throwable error) {
long now = System.currentTimeMillis();
coolUntilMillis.put(candidate, now + cooldown.toMillis());

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.

[Warning] Deleting the sweep is the right call for the agent-scoped maps, but it removes the only bound on the publicly injectable ones. coolUntilMillis / lastFailureByKey arrive through the shared-table constructors (:150, :173) and are documented as "pass fresh maps per wrapper to bound cooldown to a single stream call", so a caller that shares one long-lived map across wrappers whose candidate instances differ (per-request model objects are common in multi-tenant setups) now grows it forever, with each entry pinning a Throwable — stack trace, message, and any request context it carries. Two cheap options: keep the removeIf(entry -> entry.getValue() <= now) cleanup but run it only when size() exceeds the candidate count (so it never fires in the agent case and still caps the injected case), or state in the shared-table javadoc that a shared map must not outlive a fixed candidate set.

…ables

Follow-up to the round-5 re-review (2 warnings, both about the scope of the guarantees):

- ReActAgent.validateFallbackChainCapabilities: the primary model's capability getters (getContextWindowSize / supportsNativeStructuredOutput[WithTools]) were read outside the try block, so a throwing third-party *primary* still failed build(). They are now read inside a guarded try: any getter throw on the primary skips the whole check (debug log) — the diagnostic never fails construction on either side of the chain.
- FallbackChainModel.recordFailure: re-added a conditional eviction sweep that only runs when the shared table outgrows this chain's fixed candidate count (chain length + 1 grace). Normal wiring (wrappers share the agent's tables with identical candidate instances) never triggers it — bounded at chain length by construction; a caller sharing the injectable tables across *different* candidate instances gets expired entries swept on write, so the escape hatch cannot grow unbounded. The shared-table constructor javadoc now states this contract explicitly.
- Tests: new case in ReActAgentCapabilityValidationTest for a throwing *primary* getter (skips, never throws); FallbackChainModelTest shared-table tests still green with the conditional sweep. Locally 381 tests green, spotless applied.

@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

Round 6 on bf0ae5e7..a21988e5: both round-5 items are closed and the fixes are the right shape. The three primary-model reads now sit inside their own try, so a throwing third-party primary returns an empty warning list and the agent still builds — matching the javadoc, which now says the guard covers "both the primary and the candidates" — and throwingPrimaryGetterIsSkipped pins it at the unit level (the case the round-5 test suite missed). The shared tables keep the no-sweep fast path for the agent wiring while the new size() >= candidates.size() + EVICTION_SWEEP_GRACE condition bounds the cross-chain escape hatch, and the added "Shared-table contract" paragraph states the ownership rule explicitly, which is what the API needed. Check License, Check Module Sync and validate are green and license/cla is signed; build (ubuntu-latest) / build (windows-latest) were still queued on this head at review time, so this approval is on the content, not on those two jobs.

Findings

None. Approved with one non-blocking note for the escape-hatch case: the sweep evicts only expired entries, so if a caller shares one table across many chains and every entry is still inside its cooldown window, size() stays above candidates.size() + 1 and each subsequent recordFailure pays an removeIf pass over that table until something expires. That is a per-failure O(n) cost on a path that already runs on the failure hot path, and it only appears in the documented escape hatch — worth a sentence in the contract paragraph if a global shared table ever becomes a supported configuration.

Suggestions

Nothing further from this reviewer. Six rounds in, the fallback chain is well tested (the pure static capability check plus FallbackChainModelTest cover both the happy and adversarial SPI paths) and the documented contract now matches the implementation.

Cross-repo Note

None — contained to agentscope-core; FallbackChainModel is unreleased, so no downstream compatibility impact.


Automated review by github-manager-bot

@Letter2025

Copy link
Copy Markdown
Contributor Author

@oss-maintainer round-5 findings addressed in a21988e5 — CI green on the new head (ubuntu + windows + codecov + validate + license). Point-by-point:

[Warning] ReActAgent:781-783 primary getters unguarded — fixed. The primary model's capability getters (getContextWindowSize / supportsNativeStructuredOutput[WithTools]) are now read inside a guarded try: any throw on the primary skips the whole check (debug log) and returns no warnings, mirroring the candidate-side guard. The javadoc now says "on both the primary and the candidates". A throwing third-party model can no longer fail build() from either side of the chain. New test in ReActAgentCapabilityValidationTest (throwingPrimaryGetterIsSkipped) pins exactly this: broken primary + healthy fallback → empty warnings, no throw.

[Warning] FallbackChainModel:325 dropping the sweep drops the bound on injectable shared tables — fixed both ways you suggested. (a) Conditional cleanup restored: recordFailure now sweeps expired entries only when the shared table outgrows this chain's fixed candidate count (chain length + 1 grace). Normal wiring — wrappers sharing the agent's tables with identical candidate instances — never triggers it (the table is bounded at chain length by construction, O(1) amortized); a caller sharing the injectable tables across different candidate instances gets expired entries evicted on write, so the escape hatch cannot accumulate unbounded. (b) The 5-arg shared-table constructor javadoc now states the contract explicitly: intended usage is same-candidate-instance sharing (agent wiring); cross-instance sharing is supported as an escape hatch, with the sweep bounding accumulation and the caller owning the semantics.

No other delta. Local verification: FallbackChainModelTest 30/30, ReActAgentCapabilityValidationTest 7/7, ReActAgentFallbackChainTest 9/9, model+agent package 381 green, spotless applied. @mentioning for re-review — happy to pick up anything else the maintainers flag.

@jujn jujn added the P2 重要不紧急 label Nov 4, 2026

This branch has not been deployed

No deployments
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.

[Feature]: Multi-level model fallback chain (fallbackModels) with failure classification and per-candidate cooldown

3 participants