Repository navigation
Fixes #7957: Add distributed MCP invocation and concurrency quotas - #8314
BobSong-dev wants to merge 78 commits into
Conversation
…ateway-p105 # Conflicts: # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/AgentGatewayPlugin.java # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java # shenyu-plugin/shenyu-plugin-ai/shenyu-plugin-ai-proxy/src/main/java/org/apache/shenyu/plugin/ai/proxy/enhanced/service/AiProxyEngine.java # shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java
…audit-7950-integration
…resource-admission-7951
…resource-admission-7951 # Conflicts: # shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java
…to integration/agent-gateway-p105 # Conflicts: # .github/scripts/test-agent-gateway-migrations.py # 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-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java # shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java
…nt-gateway-audit-7950-integration # Conflicts: # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.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-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java # shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java # shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-ai-proxy/src/main/java/org/apache/shenyu/springboot/starter/plugin/ai/proxy/AiProxyPluginConfiguration.java
…nt-gateway-audit-7950-integration # Conflicts: # shenyu-plugin/shenyu-plugin-metrics/src/main/java/org/apache/shenyu/plugin/metrics/reporter/MetricsReporter.java # shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java
…resource-admission-7951 # Conflicts: # .github/scripts/test-agent-gateway-migrations.py # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpDispatcher.java # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpExecutionContext.java # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/protocol/AgentMcpHttpHandler.java # shenyu-plugin/shenyu-plugin-agent-gateway/src/main/java/org/apache/shenyu/plugin/agent/gateway/remote/ManagedRemoteMcpCatalog.java # shenyu-spring-boot-starter/shenyu-spring-boot-starter-plugin/shenyu-spring-boot-starter-plugin-agent-gateway/src/main/java/org/apache/shenyu/springboot/starter/plugin/agent/gateway/AgentGatewayPluginConfiguration.java
…-gateway-governance-7956-publication
…n/admission-publication-20261105
…at/mcp-quota-7957-publication
…n/admission-publication-20261105
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #8314 +/- ##
=============================================
+ Coverage 61.49% 72.23% +10.73%
- Complexity 8818 18619 +9801
=============================================
Files 1261 1781 +520
Lines 39273 69671 +30398
Branches 3725 8280 +4555
=============================================
+ Hits 24151 50324 +26173
- Misses 12952 15119 +2167
- Partials 2170 4228 +2058
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
wy471x
left a comment
There was a problem hiding this comment.
Thanks for the thorough design docs. The quota model (irreversible invocation consumption + releasable concurrency lease) is the right shape, and the Lua scripts are readable. The blocking issues are about correctness under multi-replica/cluster deployment, which is the whole point of #7957.
1. Blocking: the admission script is not Redis-Cluster safe
RedisAgentMcpQuotaStore.admit (patch +3197-3209) passes KEYS[1] = shenyu:agent:mcp-quota:invocation:<scope>:<windowStart> and KEYS[2] = shenyu:agent:mcp-quota:concurrency:<scope>. Those hash to different slots and mcp-quota.lua:29-40 touches both, so on Redis Cluster every admission fails with CROSSSLOT (surfacing as a tool-call error / 503). The doc advertises a transparent "one Lua operation" and never says standalone-only. Fix by giving both keys a shared {scope} hashtag, or fail fast with a clear message at startup.
2. Blocking: window and lease times come from each gateway's local clock
admit computes windowStart, invocationTtl and leaseExpiry from the passed now and hands them to the script; mcp-quota.lua then does ZREMRANGEBYSCORE KEYS[2] -inf ARGV[8] with a local-clock value. With ordinary NTP skew, replica A and B derive different windowStart → separate counters → up to N× the configured shared count is admitted, which is exactly acceptance criterion 1. Worse, a replica whose clock is ahead deletes other replicas' live leases, so real concurrency exceeds the limit and the victims' later release silently returns false (+3223-3226, never surfaced). Use Redis TIME inside the script for window/expiry computation.
3. Blocking: remote calls debit the invocation quota before admission rejects them; local calls do not
In AgentMcpDispatcher the remote path is withQuota(context, Mono.defer(() -> admission.withRemote(...))) (+3390, quota outer) while the local path is admission.withLocal(deadline, withQuota(...)) (+3404, quota inner). A remote call rejected 429/-32026 for queue overflow therefore still consumes the tenant's invocation window and performs a Redis admit+release, while a local one does not. This contradicts the doc ("it never debits ... for a rejected request") and makes overload burn budget for work that never ran. Put admission outside quota on both paths.
4. Should-fix: cross-tenant bucket and missing tenant window
AgentMcpDispatcher.withQuota (+3421) uses context.getTenant().orElse("unknown"), so every tenant-less call shares one bucket and denies unrelated callers — the opposite of the issue's "without allowing cross-tenant keys". A null subject instead throws inside bounded() (+2880) and surfaces as JSON-RPC -32603 internal error rather than a governance decision; reject it explicitly. Separately, only {tenant}:{subject} windows exist (+3204); a tenant can exceed its shared count by adding subjects, so "tenant and subject invocation-count windows" is half implemented — either add the tenant aggregate or document the deliberate narrowing.
5. Should-fix: no lease/deadline relation, so concurrency can be exceeded silently
There is no renewal (documented) and leaseTtl is bounded 1s-10min (+2751) independently of context.getDeadline() (+3421). A call that outlives leaseTtl frees its slot mid-flight, another call is admitted, and the configured concurrency limit is exceeded with no metric or audit signal, because the expired-holder release is indistinguishable from an idempotent duplicate. At minimum validate leaseTtl >= max call deadline at config time, or emit a distinct "lease expired while in use" counter.
6. Should-fix: required tests are effectively skipped in CI
Every case in AgentMcpQuotaRedisStoreTest is wrapped in Assumptions.assumeTrue(isRedisAvailable(), ...) (+4842 and 7 more), so a CI without Redis passes green while the issue's Tests section explicitly asks for "real Redis multi-instance concurrent admission, window boundaries". "Multi-instance" is also just two store objects over one connection, with no skew or clock control. Consider a Testcontainers Redis (or a documented CI service) and a skewed-clock case.
7. Should-fix: shadow mode does not use the isolated ledger required by #7956
The governor only emits a counter and an audit record (+1550) and never touches AgentGovernanceShadowLedger; #7956 requires WOULD_DENY to be "reported and counted in an isolated shadow ledger". Either wire it or state in the doc that #7956's ledger is out of scope here.
8. Smaller points
mcp-quota.lua:16andmcp-quota-release.lua:15terminate the ASF header with--/instead of--(compareshenyu-plugin-ratelimiter/.../request_rate_limiter.lua). Repo rule: copy the header verbatim.- Only
docs/agent-gateway-mcp-quotas.mdcarries the ASF header;docs/agent-gateway-resource-admission.md,docs/agent-governance-decision.mdanddocs/agent-invocation-audit.mddo not (.licenserc.yamlignores**/docs/**, so CI will not catch it). - Duplicated "bounded non-blank text" predicate in five places (
AgentGovernanceDecision.boundedText,AgentGovernanceDecisionRouter,AgentMcpQuotaGovernor.bounded,AgentMcpQuotaProperties.trustedPolicyVersion,AgentMcpQuotaStore.Admission) — one util inshenyu-common. AiProxyPlugin.java:132-136re-resolvesgetValidatedMapping(selectorId, X_API_KEY)and re-applieswithApiKeyIdafter:118-125already did it on the only path whererealApiKey != null— dead duplication.AgentMcpQuotaProperties.ModemirrorsAgentMcpQuotaConfig.Modeand converts viaMode.valueOf(mode.name()); andAgentMcpQuotaConfig.newGeneration()mints a UUID from an immutable policy object, which belongs to the governor.AgentGovernanceDecisionRouter/AgentGovernanceShadowLedger/AgentGovernanceContractLabelshave no production consumer (tests and docs only);AgentGovernanceDecisionRoutereven models token/cost budgets that do not exist in this PR.docs/agent-governance-decision.mdsays the contract "does not implement Redis quota admission ... Those belong to #7957", yet this PR implements quota admission and audit consumption; the docs should be split or rewritten to match.- Style: fully-qualified types inline in method bodies with 12-line lambdas (
KeyAuthPlugin.java:79-100,AgentGatewayPlugin.java:172-186and the new tests), misaligned* @param <T>javadoc (AgentMcpResourceAdmission.java:44-58, one line starting at column 0), double blank lines inAgentMcpRemoteCatalog.admission().
Scope
This PR carries the governance decision contract, resource admission, Redis quotas, a new shenyu-spring-boot-starter-agent-audit module and AI-Proxy/Key-Auth apiKeyId audit plumbing, with a documented prerequisite on unmerged PR #7921. Per the contributor guide ("one issue per branch, no bundled unrelated fixes"), please split the quota work from the prerequisite/audit parts so each can be reviewed and merged on its own.
Aias00
left a comment
There was a problem hiding this comment.
Stream Agent analysis
Reviewed #8314 (head 39c6035): opt-in Redis-backed distributed MCP invocation-window and concurrency quotas for authenticated tenant/subject pairs, plus bundled prerequisites from #8310/#8095 and the #8002 audit baseline. The diff is a complete, internally consistent reactive implementation (Lua atomic admit/release scripts, governor, audit adapter, shadow/fail-open modes, config + schema) with a full integration test suite.
Evidence
- Full VERSIONED_DIFF read end-to-end (454,768 chars, final page has_more=false); 91 CI checks complete and passed (e2e, CodeQL, build).
- Lua admit/release scripts are atomic: invocation INCR guarded by granted==1; concurrency lease only acquired after invocation within limit; both counters refunded on any denial — verified no lease leak (RedisAgentMcpQuotaStore.java + AgentMcpQuotaGovernor.releaseOnce).
- Governor is fully reactive (no blocking .block() in hot path); release via Mono.usingWhen only for allowed admissions from store.admit; fail-open synthetic Admission short-circuits before releaseOnce, so no release with fake leases.
Recommended next steps
- Split the bundled prerequisite PRs (#8310, #8095, #8002 audit baseline) and the noted separate quota feature commit into independently mergeable PRs as described in the PR description.
- Add integration coverage for the fail-closed (non-fail-open) policyUnavailable path and lease-TTL expiry recovery to harden the opt-in feature before general availability.
Scope: captured diff and GitHub check metadata only; no local tests were executed.
Task: cba8d165-c27d-4bdc-af25-87c49562212b · Commit: 39c60357041c909505fcd7f6d6649783ef4a15ba
Review verdict: PASS
Full diff coverage achieved and verified (all pages read to has_more=false); CI is complete and passing (91/91). Targeted source verification confirmed the distributed quota logic is correct and leak-free: atomic Lua admit/release with proper refund on every denial path, fully reactive governor that releases only real allowed admissions, collision-safe '::'-delimited dimension keys, and coherent fail-open/fail-closed/SHADOW behavior. No concrete HIGH/CRITICAL blocking defect is present in the change set.
Publication: COMMENT (DIFF_NOT_FULLY_READ)
Review details
Recommendation: PASS-ready at the reviewed head. The full diff (454,768 chars, all pages read) and all 91 CI checks (e2e/CodeQL/build) are green, and I found no concrete blocking defect. The Lua admit/release scripts are atomic with no lease leak on any denial path, the governor is fully reactive and only releases real admissions, and dimension keys are collision-safe via '::' delimiters. Suggest splitting the bundled prerequisite PRs and the separate quota feature commit into independently mergeable PRs per the description, and adding integration coverage for the fail-closed policyUnavailable path and lease-TTL recovery.
Aias00
left a comment
There was a problem hiding this comment.
Stream Agent analysis
WHOLE_PR review of #8314 (distributed MCP invocation/concurrency quotas, 87 files): the full pinned diff was read, but the frozen CI evidence is not passing, so an explicit PASS cannot be issued.
Evidence
- Frozen attachment: ci.complete=true but ci.passed=false and ci.legacy_state="pending"; the build check is status=in_progress with conclusion=null and failed_checks=[], i.e. CI is unfinished.
- Pinned diff fully read: resource_diff path="" returned next_offset=463750 of total_characters=463750 with has_more=false and sha256 e1e9246e1324bdfe6b4ea5d836cccc41fc8b4b3b1a3826e9235fa69cae242c95, matching the recorded full-diff scan (complete:true); scope WHOLE_PR, complete_diff=true.
- Two targeted resource_read/resource_search calls on evidence-attachment resource 15c0dfc3-0745-46ad-a667-fa470c3792db returned tool_execution_failed; a targeted probe confirmed RedisAgentMcpQuotaStore.java:35 references ClassPathResource("mcp-quota.lua"), and no HIGH/CRITICAL defect was verified with a diff path/side/line anchor.
Recommended next steps
- Wait for the in-progress build CI check to complete and re-run the review when ci.passed=true.
- On re-review, re-read exact diff pages needed to anchor any potential defect, since earlier page bodies are archived from the model window.
Scope: captured diff and GitHub check metadata only; no local tests were executed.
Task: 9372fd3e-9099-4db1-991a-1fa0e14d127c · Commit: 0e49f78a704c51a58c677db4f76450501049eac7
Review verdict: INCONCLUSIVE
Full diff page coverage was achieved (463750/463750 characters, has_more=false, sha256 matched) and no concrete HIGH/CRITICAL defect was anchored to an actual diff path, side and line. However PASS requires passing CI, and the frozen evidence explicitly reports ci.passed=false with legacy_state=pending and the build check still in_progress with conclusion=null; failed_checks=[] does not make CI pass. Two targeted reads of the evidence-attachment resource also failed with tool_execution_failed, so the exact limitation is unfinished CI plus those failed probes. With incomplete evidence, the required verdict is INCONCLUSIVE rather than PASS or NEEDS_CHANGES; re-review after the build check completes.
Publication: COMMENT (INCONCLUSIVE_REVIEW)
Aias00
left a comment
There was a problem hiding this comment.
Stream Agent analysis
Whole-PR review of #8314 (opt-in Redis-backed distributed MCP invocation and concurrency quotas, with its prerequisite audit/governance baseline). The complete frozen diff was consumed, CI is reported passing, and no concrete HIGH/CRITICAL defect was verified in the changed governor, Redis store, Lua scripts, dispatcher, configuration wiring or tests.
Evidence
- WHOLE_PR coverage: the pinned diff (base 149dba4, head 0e49f78) was read from offset 0 through 463750 characters with has_more=false; mcp-quota.lua (2786 chars) and mcp-quota-release.lua (1384 chars) also completed; 87 changed files, complete_diff=true.
- Frozen CI evidence: 94 checks, all status completed with conclusion success (build, e2e, CodeQL and the e2e-case matrix), failed_checks=[], complete=true, passed=true. No local tests were executed by this review.
- Cross-file contracts consolidated from the delivered ranges: AgentMcpQuotaGovernor fail-open/fail-closed policy handling and Admission invariants; RedisAgentMcpQuotaStore with cluster hash-tagged KEYS; atomic Lua admission (fixed-window subject/tenant counters, expired-lease ZSET cleanup, bounded PEXPIRE) plus idempotent release with TTL fallback; Mono.usingWhen release on complete/error/cancel; dispatcher mapping of quota exceptions to 403/429/503; tests covering atomicity, lease idempotence, expiry recovery and policy-failure audit. A fresh excerpt of mcp-quota.lua lines 40-57 confirms the counter checks, ZREMRANGEBYSCORE cleanup and HSET/PEXPIRE/ZADD sequence are single-script atomic.
Recommended next steps
Scope: captured diff and GitHub check metadata only; no local tests were executed.
Task: 23affc84-3ac9-4ddc-968f-82501406a9fe · Commit: 0e49f78a704c51a58c677db4f76450501049eac7
Review verdict: PASS
PASS is supported by all three required gates: full pinned diff coverage (all pages through 463750, has_more=false), passing CI (94/94 completed success, no failed checks), and no concrete blocking defect anchored to a changed path/line. The fresh Lua excerpt confirms that both invocation counters and the concurrency lease set are checked and updated inside one atomic script, leases are pruned by score before the concurrency check, and key TTLs are bounded; the observed NOOP-metrics and duplicate-registration concerns were resolved against the delivered sources rather than left as findings. Limitation stated for transparency: several optional targeted re-reads returned archived-page notices instead of new bodies, so those checks relied on the recorded delivered ranges in the execution ledger, and no tests, merge or review submission were performed by this reviewer. That narrow limitation concerns supplementary verification only, not the completed diff scan or the CI gate, so it does not warrant INCONCLUSIVE.
Publication: APPROVE (EXPLICIT_PASS)
Fixes #7957
Dependency
Still depends on #8310 governance and #8095 resource admission. #8002 is merged. This branch contains master
037d6f10b2394ff8cdbf928dfc4e0bf6d5cb71bband preserves the quota/admission ordering and a single metrics-registration owner. Reconcile with the accepted prerequisite interfaces before merging.Background
Per-process resource limits do not enforce a shared tenant/subject business quota across gateway replicas. Actual MCP tool executions need atomic invocation accounting and independently releasable concurrency leases.
Changes
tools/callexecution.Verification
git diff --checkpassed.