Skip to content

refactor(ai-proxy): decompose orchestration and consolidate extension contracts - #8468

Open
hengyuss wants to merge 14 commits into
apache:masterfrom
hengyuss:refactor/ai-proxy-engine-8302
Open

hengyuss wants to merge 14 commits into
apache:masterfrom
hengyuss:refactor/ai-proxy-engine-8302

Conversation

@hengyuss

Copy link
Copy Markdown
Contributor

Fixes #8302

Problem and change

AiProxyEngine had accumulated request planning, retry/fallback coordination, response consumption, observation, and extension wiring in one execution path. This made lifecycle state difficult to reason about and allowed status failures to be represented indirectly across multiple reactive stages.

This PR keeps the current AI Proxy behavior while making those responsibilities explicit:

  • extracts exchange planning, execution state, attempt planning/execution/orchestration, response consumption, and logical-call observation into focused components;
  • uses AiAttemptOutcome to represent response-versus-retry outcomes directly, so a handled 429/5xx path is not also resumed as a successful attempt;
  • consolidates engine construction behind one builder and keeps concrete converter wiring in the Spring Boot starter;
  • consolidates the Provider preparation/capability contract and adds default-safe Protocol inspection/cache hooks, migrating every in-repository implementation and consumer atomically;
  • preserves built-in configuration, native wire paths, retry/fallback eligibility, Retry-After, shared deadlines, response commitment, streaming/backpressure, cancellation, cache compatibility, response metadata, and observation privacy;
  • adds focused planner/orchestration/extension-contract tests and the durable repository contract for the capability.

The Java Provider/Protocol extension contracts intentionally change in this PR; there are currently no user-supplied AI engine integrations in the repository, and all built-in implementations and starters are migrated together. Adding Anthropic or Gemini implementations is outside this PR; their concrete requirements should drive any further extension work.

Planning: #8465, #8466, #8467. No unmerged PR dependency.

IssueSpec

IssueSpec-Mode: full
IssueSpec-Reason: This refactor changes public Java Provider/Protocol extension contracts and the AI Proxy orchestration lifecycle while preserving built-in runtime behavior.
IssueSpec-Proposal: #8465
IssueSpec-Design: #8466
IssueSpec-Implement: #8467
IssueSpec-Specs: SPEC-8465001
IssueSpec-Tasks: TASK-8466001
IssueSpec-Validation: Full workflow gate and traceability passed; durable-spec check passed for commit 2dbb815 with zero blockers; affected Maven-wrapper tests and Checkstyle passed. Root clean install was attempted but stopped in unrelated shenyu-protocol-mqtt ConnectTest with 8 existing sessionRepository initialization errors.

Verification:

  • ./mvnw -pl shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy -am test -Dmaven.javadoc.skip=true -Drat.skip=true -Djacoco.skip=true — passed; AI Proxy 526 tests, 0 failures/errors, and all selected reactor modules passed.
  • ./mvnw -pl shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy,shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway -am test -Dtest='AiProxyPluginConfigurationTest,AiProxyHttpClientResourcesTest,AgentGovernanceHttpTest' -Dsurefire.failIfNoSpecifiedTests=false -Dmaven.javadoc.skip=true -Drat.skip=true -Djacoco.skip=true — passed; 22 AI Proxy starter tests and 4 governance HTTP tests.
  • ./mvnw clean install -Dmaven.javadoc.skip=true — attempted; modules through shenyu-protocol-mqtt compiled and validated, then 8 unrelated ConnectTest cases errored because sessionRepository was null; downstream modules were skipped.
  • git diff --check origin/master..HEAD — passed.

Make sure that:

  • You have read the contribution guidelines.
  • You submit test cases (unit or integration tests) that back your changes.
  • Your local test passed ./mvnw clean install -Dmaven.javadoc.skip=true (attempted; blocked by the unrelated MQTT test failure documented above).

@Aias00 Aias00 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Stream Agent analysis

Reviewed the frozen evidence for #8468 (refactor(ai-proxy): decompose orchestration and consolidate extension contracts) at head fb76092. The engine ledger records the full 379,655-character pinned diff scan and the 45,579-character AiProxyEngine.java path scan as complete, and targeted head reads of the extracted AiAttemptOrchestrator/AiAttemptOutcome were obtained. However, CI is entirely queued/pending with passed=false, so no PASS can be supported, and no concrete HIGH/CRITICAL defect was verified, so no NEEDS_CHANGES can be supported. Verdict is INCONCLUSIVE, with an analysis refresh required before automatic publication.

Evidence

  • Frozen evidence: PR #8468, head fb76092, comparison base 6cb63d0, 71 files, WHOLE_PR/VERSIONED_DIFF; ENGINE_READ_PROGRESS records complete=true with next_unread_offset equal to total_characters for both the full diff (379655) and the AiProxyEngine.java path (45579).
  • Frozen CI: check_count 11, all reported checks queued with null conclusions, legacy_state pending, status_count 0, failed_checks [], passed=false; there is no passing CI conclusion to anchor a PASS.
  • Head read of AiAttemptOrchestrator.java lines 79-118 routes >=400 statuses to handleStatusFailure, adapts/consumes successful responses, and emits attempt events; AiAttemptOutcome is a sealed interface with Completed/Transition. No concrete HIGH/CRITICAL defect was verified in the diff.

Recommended next steps

  • Wait for all 11 queued CI checks to reach final conclusions, then re-evaluate the verdict with completed results.
  • Refresh the analysis against the observed current GitHub head fb76092 before automatic Review publication, as requested in the follow-up.
  • Re-verify the extracted AiAttemptOrchestrator, AiResponseConsumer and extension-contract wiring once CI conclusions are available, since several targeted reads returned archived observations only.

Scope: captured diff and GitHub check metadata only; no local tests were executed.

Task: da08b578-0eb2-445b-a413-cfa47af55d07 · Commit: fb760920e7801cd0a171f7703684e9ab876426f5

Review verdict: INCONCLUSIVE

Full pinned-diff coverage is recorded, but coverage does not prove correctness: the frozen CI snapshot has all 11 checks queued with null conclusions and passed=false (legacy_state pending), so the required passing-CI condition for PASS is absent. NEEDS_CHANGES is also unsupported because no concrete HIGH/CRITICAL defect anchored to a diff path, side and line was verified; several targeted cross-file verification calls returned only archived observations and added no new evidence. The follow-up explicitly requests a refreshed analysis for the observed current GitHub head before automatic Review publication and asks to preserve uncertainty, so no final approval or rejection is asserted. No tests, merge or review submission were performed by me; the authorized business adapter handles delivery.

Publication: COMMENT (REVIEW_EVIDENCE_MISSING)

@wy471x wy471x left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Two-axis review

Reviewed the head fb760920e7801cd0a171f7703684e9ab876426f5 against master (71 files; main code, touched tests and starter wiring). Build/RAT/scope/policy checks are green on this head.

Standards

  1. README states a compatibility guarantee the code no longer provides (blocking). shenyu-plugin-ai-proxy/README.md still says "Existing custom implementations keep their interface contract and the OpenAi(ProviderProfile) constructor remains available", while AiProxyProvider.buildRequest is deleted, capabilities() becomes abstract and prepareRequest is required (provider/AiProxyProvider.java lines ~44-77), and all public AiProxyEngine constructors are replaced by AiProxyEngine.builder(...). That is a source/binary break for external providers and programmatic engine users. The issue explicitly allows the Java API migration, so the fix is a migration note (what to replace, e.g. buildRequest -> prepareRequest, capabilities required, builder usage), not necessarily compatibility shims. As written the README is wrong and will mislead extension authors.
  2. Additional undocumented API moves (major). AiProxyAttemptListener/AiProxyAttemptEvent move to service.event, AiObservationSupport to service.observation, and AiUpstreamUsageTap becomes public in service.observation. These are public types an integrator can compile against; the issue does not name them. Either keep deprecated forwarders or list them in the same migration note.
  3. Cache eligibility contract changed silently (minor). The old gate was provider instanceof OpenAi || provider instanceof OpenAiCompatible; the new one is provider.isExactResponseCacheCompatible(targetProtocol) (AiExchangePlanner.createPreparedExchange). For the built-in providers the result is equivalent (OpenAi returns true for openai-chat, OpenAiCompatible delegates, OpenAiResponses keeps the default false), but the capability is now a new public opt-in that is not documented. State in the README that custom providers must override it to participate in exact caching (and that the default is off), and add a test for a custom provider.
  4. Detection precedence tie-break changed (minor). AiProxyProtocolFactory now sorts by (detectionOrder desc, name asc) for every protocol; with the default detectionOrder() == 0, third-party protocols that both match one envelope now resolve alphabetically instead of in registration order. If the hook is needed, keep registration order as the tie-break for equal precedence.
  5. Out-of-scope shared-module behaviour change (minor). shenyu-common/.../AiRequestObservation.freeze() now rewrites Framing.NOT_INSPECTED to NONE for a cancelled stream (AiRequestObservation.java ~323-327). It is tested and arguably more accurate, but it changes metrics semantics for every consumer and is not part of issue #8302; split it into its own change or justify it in the PR description.
  6. Small smells (minor). AiAttemptOrchestrator.applyOutcome has an unreachable case FORWARD_RESPONSE -> throw IllegalStateException (AiAttemptOutcome.Transition already excludes it); AiAttemptExecutor.selectedModel keeps a second ObjectMapper and re-parses the upstream body per attempt.

Spec

The core goals are met: AiProxyEngine is a small builder-based facade, planning/execution/attempt/response/observation are separated (AiExchangePlanner, AiExecutionCoordinator, AiAttemptOrchestrator, AiAttemptExecutor, AiResponseConsumer), AiAttemptOutcome makes response-vs-retry explicit, and the retry/fallback/deadline/replay logic moved without obvious semantic change (4xx-exhausted failures now classify as ERROR rather than falling through to SUCCESS, which looks like a fix). Missing/partial: the issue requires that "README and durable specification document the resulting ownership and Java extension contract" — the README ownership section is good, but the compatibility sentence contradicts the delivered contract, and issue-spec/specs/ai-proxy-orchestration-contracts/spec.md does not name the extracted component ownership, the builder as the single construction contract, or the removed buildRequest hook.

Verdict

REQUEST CHANGES. The refactor itself looks sound and well tested, but the delivered contract and the README disagree; correct the compatibility/migration documentation (and record the package moves and the cache opt-in) before merge.

…ngine-8302

# Conflicts:
#	shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/provider/OpenAi.java
#	shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java
#	shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/AiProxyPluginTest.java
#	shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/test/java/org/apache/shenyu/plugin/ai/proxy/enhanced/handler/AiProxyPluginHandlerTest.java
@hengyuss
hengyuss requested review from Aias00 and wy471x November 19, 2026 02:17

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Task][AI Proxy] Decompose AiProxyEngine orchestration and consolidate extension contracts

3 participants