Repository navigation
[type:bug] Fix AiProxy switching providers after partial SSE output - #7022
zhang-arvin wants to merge 4 commits into
Conversation
Aias00
left a comment
There was a problem hiding this comment.
Request Changes — two blocking issues
This PR bundles several fixes that overlap with other open PRs (#7008 fault-tolerance NPE guards, #7009 cryptor/sign removeRule, #7011 size-guard removal). That consolidation is fine, but it inherits two defects that must be fixed before merge.
Blocker 1 — RateLimiterPlugin does not compile (import missing)
RateLimiterPlugin.doExecute adds if (Objects.isNull(limiterHandle)) { return chain.execute(exchange); } but the file does not import java.util.Objects (verified on the head branch: the only Objects occurrence is the new usage at line 74, no import line). This is the exact same compile error already flagged on #7008. Add import java.util.Objects; to RateLimiterPlugin.java.
Blocker 2 — stale-config cleanup still passes bare names to delConfig (incomplete, same as #7011)
In AbstractNodeDataChangedListener.onCommonChanged, the REFRESH branch is now:
final List<String> configDataNames = this.getConfigDataNames(configKeyPrefix);
if (Objects.nonNull(configDataNames)) {
configDataNames.removeAll(changeNames);
configDataNames.forEach(this::delConfig);
}getConfigDataNames (line 347) returns the bare names parsed from the LIST node (configKeyPrefix + LIST_STR), and changeNames are also bare names (changedList.map(mapperToKey)). So delConfig is invoked with bare names. But the actual entries — and the DELETE branch at line 126, and delConfig itself — use the full key configKeyPrefix + name. As a result, stale entries published at configKeyPrefix + name are not deleted. This is the same incompleteness as #7011; #7014 already fixed it by calling delConfig(configKeyPrefix + name). Please apply the same prefix fix here:
configDataNames.forEach(name -> delConfig(configKeyPrefix + name));Non-blocking note — AiProxyExecutorService behavior change
.retryWhen(Retry.max(1))…onErrorResume(NonTransientAiException…) is replaced with a single .onErrorResume(throwable -> handleFallbackStream(...)). This drops the one retry and falls back immediately on any error. That matches the PR goal ("switch providers after partial SSE output"), but it does reduce resilience — please confirm the retry removal is intentional and not needed for transient upstream failures.
Coordination
Since this PR duplicates #7008 / #7009 / #7011, please coordinate so we don't end up with duplicate or conflicting merges (either close the superseded individual PRs or keep only this consolidated one).
Conclusion
Request changes pending the Objects import fix and the delConfig(configKeyPrefix + name) prefix fix. The fault-tolerance / cryptor-sign / controller ideas themselves are sound.
38e4405 to
773b5b5
Compare
|
Thanks for the review @Aias00! Fixed:
Please take another look. |
Aias00
left a comment
There was a problem hiding this comment.
Re-review: [type:bug] Fix AiProxy switching providers after partial SSE output
Re-reviewed at head 773b5b5. My previous REQUEST_CHANGES identified two hard blockers; both are resolved, plus the related fault-tolerance NPE fixes are included:
1. RateLimiterPlugin missing import java.util.Objects; (was a compile error) — FIXED
RateLimiterPlugin.java line 69 adds import java.util.Objects; (verified: exactly one occurrence, no duplicate) and a null-handle guard (lines 77-79). Module now compiles.
2. onCommonChanged delConfig passed bare name — FIXED
Line 13: configDataNames.forEach(name -> delConfig(configKeyPrefix + name)); uses the full key, matching how publishConfig writes data, so stale config nodes are actually removed on REFRESH/MYSELF. Verified every delConfig call site in the class uses the configKeyPrefix + ... form (lines 126, 136, 225, 251, 264, 278) — no bare-name path remains.
3. Additional fixes bundled in this combined PR
HystrixPlugin/Resilience4JPlugin/SentinelPlugin: null-handle guards (safe fall-through tochain.execute).AbstractCryptorPluginDataHandler.removeRule/SignPluginDataHandler.removeRule: unconditionalremoveHandle(drops theOptional.ofNullable(ruleData.getHandle())guard that skipped cache clearing when handle was null).onSelectorChanged: null-safe namespace prefix viaStringUtils.defaultString(getNamespaceId(), SYS_DEFAULT_NAMESPACE_ID).AiProxyExecutorService.executeStream(lines 30-43): replaced theRetry.max(1)+ customNonTransientAiException+onErrorResume(NonTransientAiException.class, ...)chain with a singleonErrorResume(throwable -> handleFallbackStream(...)).
Non-blocking note on the AiProxy change: removing the bounded Retry.max(1) means the main stream is no longer retried once before falling back — any error (including transient ones) immediately triggers provider switch. For the stated goal ("switching providers after partial SSE output") this is reasonable, but if you want resilience against transient upstream blips you could re-add a small bounded retry before the fallback. Not required for approval.
All blockers resolved. Approving.
|
@zhang-arvin hi, pls fix conflict |
|
Rebased onto latest master, conflicts resolved |
e2b1e29 to
4a58de7
Compare
|
@Aias00 conflict fixed — rebased onto latest master, thanks! |
f367ca6 to
b0fad20
Compare
There was a problem hiding this comment.
🟡 Changes recommended
Partial-stream failures still invoke fallback, and the required regression coverage is missing.
Get a fresh assessment by requesting another Copilot review.
Pull request overview
Attempts to prevent mixed AI-provider SSE output, but fallback remains unconditional after partial emission.
Changes:
- Removes streaming retry behavior.
- Defaults null selector namespaces in admin listener keys.
File summaries
| File | Description |
|---|---|
AiProxyExecutorService.java |
Removes retry while retaining unconditional fallback. |
AbstractNodeDataChangedListener.java |
Adds unrelated default-namespace handling. |
Review details
- Files reviewed: 2/2 changed files
- Comments generated: 3
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| "Direct stream failed after 1 retry. Triggering fallback.", | ||
| retrySignal.failure()); | ||
| })) | ||
| .onErrorResume(e -> handleDirectFallbackStream(e, fallbackCtxOpt, requestBody, stream)); |
| "Direct stream failed after 1 retry. Triggering fallback.", | ||
| retrySignal.failure()); | ||
| })) | ||
| .onErrorResume(e -> handleDirectFallbackStream(e, fallbackCtxOpt, requestBody, stream)); |
| } | ||
| SelectorData selectorData = changed.stream().findFirst().orElseThrow(() -> new ShenyuException("selectorData is null")); | ||
| final String configKeyPrefix = selectorData.getNamespaceId() + DefaultNodeConstants.JOIN_POINT + changeData.getSelectorDataId() + DefaultNodeConstants.JOIN_POINT; | ||
| final String configKeyPrefix = StringUtils.defaultString(selectorData.getNamespaceId(), SYS_DEFAULT_NAMESPACE_ID) + DefaultNodeConstants.JOIN_POINT + changeData.getSelectorDataId() + DefaultNodeConstants.JOIN_POINT; |
Aias00
left a comment
There was a problem hiding this comment.
REQUEST_CHANGES (PMC Aias00): the main build job is failing — this PR does not compile/pass tests, so it cannot be merged. Please fix the compilation/test failures and re-run CI, then request a re-review.
Only switch to the fallback provider while the main stream has not emitted any chunk; once a chunk has been delivered, propagate the error instead of mixing partial main output with a complete fallback response (apache#7021). Also drop the unrelated selector namespace key change, which is covered by its own PR, and sync the affected unit test assertion with the removal of the retry wrapper.
b0fad20 to
ccd5263
Compare
|
@Copilot Thanks for the review — you're right on both points, and the second one was a real defect I had missed. 1. Unrelated namespace change removed. You were correct that the selector key change ( 2. The fallback was still invoked after partial output — fixed. This was a genuine bug, not just a missing test. Fix: if (chunkAlreadyEmitted) {
LOG.warn("Main direct stream failed after emitting at least one chunk; "
+ "not switching to fallback to avoid mixing partial and fallback output.", throwable);
return Flux.error(throwable);
}3. Regression test added, covering the case you asked for: a main stream that emits a chunk and then errors, with a fallback configured, must emit only the main chunk, propagate the error, and never subscribe to the fallback ( 4. One more defect found while testing: removing the retry wrapper in this PR also removed its
@Aias00 @dengliming the branch is rebased on current |
Aias00
left a comment
There was a problem hiding this comment.
The core diagnosis is right — and I agree the fallback must not engage after a chunk has been emitted — but I'm keeping this at REQUEST_CHANGES because of how the fix gets there.
1. Please don't drop retryWhen from executeDirectStream.
The PR deletes the entire retryWhen(Retry.max(1).filter(AiProxyExecutorService::isRetryable)...) block. That conflates two different concerns: "don't retry/fallback after emission" (the actual #7021 bug) and "don't retry at all" (a much broader change). A transient failure that occurs before any chunk is emitted is still perfectly safe to retry — nothing has reached the client — and that capability is being removed silently.
Note there is now an approved PR (#7205) that fixes the same issue by keeping the retry and simply gating it:
return Flux.defer(() -> {
AtomicBoolean emitted = new AtomicBoolean();
return mainApi.chatCompletionStream(request)
.doOnNext(chunk -> emitted.set(true))
.retryWhen(Retry.max(1).filter(error -> !emitted.get() && isRetryable(error)) ...)
.onErrorResume(error -> emitted.get()
? Flux.error(error)
: handleDirectFallbackStream(...));
});I'd rather see this PR aligned with that shape — it fixes the reported corruption and preserves retry for the pre-emission case. If you'd prefer to keep this PR minimal, please at least state explicitly in the description that dropping retry is intentional.
2. chunkEmitted should be per-subscription, not per-invocation.
final AtomicBoolean chunkEmitted = new AtomicBoolean(false); is allocated in the method body, outside the returned Flux. chatCompletionStream returns a cold Flux that can be subscribed more than once; if that ever happens, the second subscription starts with the flag already true from the first, and fallback would be suppressed incorrectly. Wrapping the body in Flux.defer(...) as #7205 does makes the flag subscription-scoped.
Everything else looks good:
- The
emitted ? Flux.error(throwable) : fallbackdecision, with aLOG.warnexplaining why the fallback was skipped, is the right behaviour and good for operability. - The comment above the flag clearly states the rationale for future readers.
- Both tests are meaningful and cover both sides:
testExecuteDirectStreamDoesNotFallbackAfterChunkEmittedasserts the fallback is never subscribed after one chunk, andtestExecuteDirectStreamFallbackAfterErrorWithoutChunksasserts fallback still works when nothing was emitted. That second test is important — it's the one that catches an over-broad fix. isRetryableis still used elsewhere in the class (line 91), so removing it from this path doesn't leave dead code.
Address items 1 and 2 and I'll approve immediately.
…iceTest testExecuteDirectStreamErrorWithNoFallback asserted NonTransientAiException, but executeDirectStream propagates the upstream error unchanged when no fallback context is present (handleDirectFallbackStream returns Flux.error(throwable)). Assert the original RuntimeException and its message instead.
|
This change is now covered by #7205 ("avoid retrying partial AI streams"), which is already on master, so this PR is no longer needed. On master ( AtomicBoolean emitted = new AtomicBoolean();
.doOnNext(chunk -> emitted.set(true))
.retryWhen(Retry.max(1).filter(error -> !emitted.get() && isRetryable(error)))
.onErrorResume(error -> emitted.get()
? ... // stream already committed -> propagate
: handleDirectFallbackStream(...)); // nothing emitted yet -> fallback is safeThat covers the scenario tracked in #7021 - an unconditional fallback after the first emitted chunk producing a mixed Happy to close this PR if you agree - flagging it here rather than closing silently. Thanks @Aias00 for keeping an eye on it. |
Fixes #7021
Problem
When the main AI provider emits partial SSE content and then fails mid-stream, the
executeStreammethod usesretryWhen(Retry.max(1))to retry the main provider. This causes:Fix
Remove the
retryWhenfrom the streaming path. For streaming, retrying after partial content has already been emitted to the client is always problematic. Instead, immediately fall back to the fallback provider on any error.Changes
shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyExecutorService.java: RemovedretryWhenfromexecuteStreammethod, replaced with directonErrorResumeto fallback provider