Repository navigation
Resolve aggregator conflicts for resources, templates and prompts - #6075
Conversation
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #6075 +/- ##
==========================================
+ Coverage 72.26% 72.30% +0.04%
==========================================
Files 728 729 +1
Lines 75523 75632 +109
==========================================
+ Hits 54575 54689 +114
+ Misses 17045 17042 -3
+ Partials 3903 3901 -2 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
7177963 to
abe41f1
Compare
jhrozek
left a comment
There was a problem hiding this comment.
Read through the whole change. The core fix is right, and I like that the new tests actually construct collisions instead of minting unique keys — that's precisely why #6060 survived as long as it did. The mergePrompts switch to forward OriginalName rather than the advertised name is a genuine extra fix that came along for free.
Most of my comments trace back to one design decision: renaming only on collision. That makes a prompt's client-visible identity a function of what else happens to be deployed, and three separate problems fall out of it — Cedar policies keyed on the old name (the forbid case fails open), a prompt that never collided getting dropped, and a rename that emits no prompts/list_changed behind an add-only resync. Prefixing unconditionally, which is what PrefixConflictResolver already does for every tool, collapses all three at the cost of a one-time rename of every prompt. Worth deciding before this lands.
Two things that don't fit inline:
Test gaps beyond the one I flagged on mergePrompts: the reverse literal-prefix collision (incumbent holds the bare prefixed name, the renamer gets dropped) isn't pinned anywhere; the "first occurrence wins" case at capability_conflicts_test.go:66-76 can't observe which occurrence actually won, since both fixtures share BackendID: "solo" and the assertion map records only BackendID, so a keep-last regression would pass; and the conditional asserts at :123/:133 mean a future case that forgets to populate want silently asserts nothing.
pkg/vmcp/session/factory.go:344-375 still does first-wins-by-name with no renaming for prompts. It isn't reachable from clients today (nothing outside tests calls MultiSession.Prompts()/GetPrompt), so it isn't a bug, but it's now a second and contradictory encoding of the same policy. Probably worth a follow-up to drop prompts and resources from buildRoutingTable altogether.
One doc note: docs/operator/virtualmcpserver-api.md:222-231, docs/arch/02-core-concepts.md:248-251, docs/arch/09-operator-architecture.md:434-437 and examples/vmcp-config.yaml:94-105 all describe conflictResolution without mentioning that resource dedup and prompt prefixing now happen unconditionally outside it. Nothing false, but a short note in the user-facing docs would save someone a surprise.
Review of #6075 found that collision-only prompt renaming made the advertised name depend on group membership, and the advertised name is what Cedar authorizes on (Prompt::"<advertised name>"): an unrelated backend joining with the same prompt name detached existing permit and forbid policies, the forbid case failing open. Rename every prompt unconditionally instead, honouring conflictResolutionConfig.prefixFormat through the same formatting path the tool prefix strategy uses, so the advertised name is a pure function of (backendID, name). This also removes the case where a rename collided with another backend's literal "{backendID}_{name}" prompt and silently dropped one. The only residual collision — two (backendID, name) pairs composing to the same prefixed string — now aborts aggregation with ErrUnresolvedConflicts; an exact intra-backend duplicate is dropped with a warning. The no-resolver tool fallback now iterates backends in sorted order, and the architecture doc scopes the determinism claim to what actually holds. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01GvBj7nNWqDQ3rKYNeY6aam
abe41f1 to
eec5605
Compare
The vMCP aggregator resolved name conflicts for tools only; resources,
resource templates and prompts were plain-appended across backends, so
duplicate identities appeared in the aggregated lists undiagnosed while
MergeCapabilities' URI/name-keyed routing tables silently collapsed each
duplicate to a nondeterministically-chosen backend for reads.
Resolve the remaining three types with per-type policies. Prompt names
are names: prompts/get already translates the advertised name back to
the backend's own via GetBackendCapabilityName, so colliding prompts
are losslessly renamed to {backendID}_{name} for every collider.
Resource URIs and template strings are locators the client passes back
verbatim (reads, subscriptions, completion refs, embedded resource
links), so they are never rewritten: a duplicate is advertised once,
owned by the first backend in sorted-backend-ID order, and later
copies are dropped with a warning. Backends are iterated in sorted-ID
order and MergeCapabilities gains first-wins guards, so collision
outcomes and routing are deterministic across runs.
The Modern paginator keeps its collision-safe cursor even though
aggregated keys are now unique: it is generic and must not depend on a
caller invariant. Tools resolution is unchanged.
Closes #6060
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01GvBj7nNWqDQ3rKYNeY6aam
Review of #6075 found that collision-only prompt renaming made the advertised name depend on group membership, and the advertised name is what Cedar authorizes on (Prompt::"<advertised name>"): an unrelated backend joining with the same prompt name detached existing permit and forbid policies, the forbid case failing open. Rename every prompt unconditionally instead, honouring conflictResolutionConfig.prefixFormat through the same formatting path the tool prefix strategy uses, so the advertised name is a pure function of (backendID, name). This also removes the case where a rename collided with another backend's literal "{backendID}_{name}" prompt and silently dropped one. The only residual collision — two (backendID, name) pairs composing to the same prefixed string — now aborts aggregation with ErrUnresolvedConflicts; an exact intra-backend duplicate is dropped with a warning. The no-resolver tool fallback now iterates backends in sorted order, and the architecture doc scopes the determinism claim to what actually holds. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01GvBj7nNWqDQ3rKYNeY6aam
Unconditional prefixing gave prompts no escape hatch, while tools have one: the conformance harness patches the aggregation strategy to priority precisely so its fixtures' hardcoded tool names survive. Prompts are named API surface in the same way, so a client pinning a prompt name broke behind vMCP with no recourse -- four conformance prompts/get scenarios fail on that alone. Extend priority to prompts: backends listed in priorityOrder keep their own prompt names, everything else is prefixed as before, and prefix stays the default strategy. This preserves the property jhrozek's review asked for. The risk was a name moving because an unrelated backend deployed, which silently stops a Cedar forbid(... Prompt::"x") from matching. Under priority an incumbent's name never moves when a colliding backend joins -- the newcomer loses -- and backends outside priorityOrder get a prefix that is a pure function of (backendID, name). A name only changes on an explicit priorityOrder edit, which is when an admin reviews policy anyway. Also reword the vmcp init template comment so it no longer contains the literal prefixFormat token, which the conformance harness's template-drift guard matches against the whole generated file. Refs #6060
eec5605 to
d443ba1
Compare
jhrozek
left a comment
There was a problem hiding this comment.
LGTM — approving.
The two things that drove my original review are properly fixed. Unconditional prefixing kills the membership-dependent Cedar identity at the root rather than papering over it, and the drop-on-collision class is gone by construction instead of by policy. The priority escape hatch is the right response to the conformance problem, and I verified the harness motivation rather than taking it on trust.
Everything still open in my threads is a nit — take them or leave them. The docstring invariant wording, the commit-message rationale, and the three test-hygiene items (the :67 case can't observe which occurrence won since both fixtures share BackendID: "solo"; the conditional asserts at :124/:134; no fixture proving Description/Arguments survive the rename) are all fine as follow-ups or as nothing.
One of them isn't a nit, and I'm still not blocking on it: the prefix-composition ambiguity error fails the whole aggregated view, not just prompts, and needs no conflict-resolution config to reach. Your call entirely — it's fail-closed either way, so the worst case is an operational surprise rather than an authorization one. Drop-both if you want the smaller blast radius, leave it if you'd rather keep the loud signal.
The one change I'd genuinely encourage is the single sentence in the header comment saying the priority loser is dropped rather than re-prefixed deliberately. That drop is what keeps forbid fail-closed, and right now nothing in the file says so — it's the cheapest possible insurance against someone "fixing" it later.
Two calls of yours I think were better than my suggestions: keeping both dedup layers with an explicit enforcement-point comment (I'd missed that deleting dedupeByKey would let ResolvedCapabilities carry duplicate URIs against its documented contract), and deferring the resolver map-order iteration as a tools-path change out of scope here.
Drop ambiguous prompt names instead of erroring An advertised prompt name with no defined owner — two (backendID, name) pairs composing to the same string — failed the whole aggregation. That error propagated out of ResolveConflicts before the already-computed tools, resources and templates were returned, so one ambiguous prompt name took down tools/list, resources/list, resource-templates/list, prompts/list, Discover's presence flags and backend visibility for the entire group. Errors are never cached, so every request re-swept every backend and failed again while the condition persisted. Reaching it needs no conflict-resolution config, only an unlucky combination of operator-chosen workload names and backend-chosen prompt names. Drop every prompt claiming an ambiguous name instead, logging the name, the colliding backends and their original prompt names at ERROR. Dropping all claimants rather than only the loser (the tool precedent) is what makes this safe: a survivor would inherit the ambiguous name and with it any policy written for the prompt it collided with, since Cedar authorizes on the advertised name alone. Advertised by nobody, every permit and forbid on the name is vacuous and the rest of the group keeps serving. Also scope the header's stability invariant to the (backendID, name) pair it actually holds for, and state the caveat it does not cover: under priority, whoever wins a shared bare name inherits every permit written for it. forbid still fails closed because the priority loser is dropped rather than aliased — record that the drop is deliberate, so the obvious future "improvement" of re-prefixing the loser does not reopen the fail-open. Addresses post-merge review feedback on #6075. Co-authored-by: Claude Fable 5 <[email protected]>
Summary
The aggregator resolved name conflicts for tools only. Resources, resource templates and prompts were plain-appended across backends ("no conflict resolution for these yet"), so two backends exposing the same
Resource.URI,ResourceTemplate.URITemplateorPrompt.Nameboth appeared in the aggregated view, undiagnosed. Worse,MergeCapabilitieskeys the routing table by those identities, so duplicates silently collapsed to a nondeterministically-chosen backend for reads — whichever backend won the map write, potentially varying between runs. Two instances of the same server type were enough to hit this.This PR resolves conflicts for the remaining three capability types, with policies that deliberately differ by what the identity is:
prompts/getalready translates the advertised name back to the backend's own name viaBackendTarget.GetBackendCapabilityName, so renaming does not break invocation. Every prompt is renamed unconditionally to its backend-prefixed form —conflictResolutionConfig.prefixFormatapplied to the backend ID (default{workload}_), the same formatting pathPrefixConflictResolveruses for tools. The advertised name is therefore a pure function of (backendID, name) and never shifts when unrelated backends join or leave the group. That stability is a security property, not cosmetics: the advertised name is what authorization matches on (pkg/vmcp/core/admission.gopasses it to Cedar, which buildsPrompt::"<advertised name>"entities), so a membership-dependent rename would silently detachpermitandforbidpolicies from the prompt they were written for — theforbidcase failing open. This PR's first revision renamed only on collision and had exactly that instability; review caught it. An exact intra-backend duplicate (a backend advertising the same prompt name twice) is dropped with a WARN — both entries advertise and route identically, so nothing reachable is lost. The one residual collision unconditional prefixing cannot rule out — two distinct (backendID, name) pairs composing to the same string, e.g. backendb1promptx_yvs backendb1_xprompty, bothb1_x_y— is ambiguous between backends and now fails aggregation loudly withErrUnresolvedConflictsinstead of silently dropping a prompt.resources/read,resources/subscribe, completion refs), backends emit them in notifications and embedded resource contents, and template-matched reads forward the client's concrete URI untranslated. Rewriting them would break those round trips, so a duplicated URI/template is instead advertised once: the backend earliest in sorted-backend-ID order wins; later duplicates are dropped with a WARN naming the URI and both backend IDs. The trade-off, stated plainly: reads strictly improve (the routing table keys by URI, so at most one backend was ever readable per URI — previously an arbitrary one, now a stable one), while discoverability regresses (a URI existing on N backends is listed once instead of N times, and only the winning backend'sname/description/mimeTypeare advertised — a duplicate that differed in those fields loses them along with its entry). Dropping is still right because the protocol gives a client no way to address the other N−1 entries — they promised reads that could never be honoured. Surfacing collisions beyond the log (e.g. in aggregation metadata or a status endpoint) is possible follow-up, not built here.In effect prompts get the tool prefix strategy applied unconditionally.
priorityandmanualremain tool-only knobs (their configuration is tool-shaped);prefixFormatis honoured for prompts under every strategy, since it is the only prefix-format knob.Because prefixing is unconditional, group-membership changes no longer rename anything. Prompt-set changes on a live backend propagate to connected sessions through the list_changed resync path (
pkg/vmcp/server/serve_list_changed.go, #5748/#5969), which is add-only for prompts — a removed prompt stays advertised on already-registered sessions until they reconnect (toolhive-core#184). A backend joining or leaving the group emits no push signal today, so staleness there is bounded by the aggregator cache TTL for routing and by the client's nextprompts/listfor listing; that gap predates this PR and applies to tools equally.Closes #6060
Client-visible behaviour, before → after (both revisions, including Legacy)
prompts/getworks{backendID}_{name}(perprefixFormat);prompts/geton the prefixed name forwards the backend's own name; the bare name → not foundprompts/gethit a nondeterministic backendb1+x_yvsb1_x+y)ErrUnresolvedConflictsnaming both backends and both promptsresources/readhit a nondeterministic backendHow routing became deterministic
ResolveConflictsiterates backends in sorted-ID order (map iteration order was the nondeterminism source) and emits key-sorted, duplicate-free lists. It is the enforcement point for these policies (stated in thecapability_conflicts.goheader).MergeCapabilitiesno longer silently last-wins-overwrites routing entries: duplicate identities get a first-wins guard with a warning, applied to the routing table and the advertised list together so they can never disagree. This is defence in depth for directMergeCapabilitiescallers — in the pipeline these guards can never fire, becauseResolveConflictsruns first.docs/arch/10-virtual-mcp-architecture.mdsays so). Fixing those touches the tools path and is left for a follow-up PR.Every drop or rename is logged at WARN with the colliding key and both backend IDs.
Type of change
Test plan
task test) — passes except the three pre-existing environment-dependent failures (TestNewServer_ReadTimeoutConfigured,TestSecurityHeaders,TestCompositeProvider_RealProviders)task lint) — 0 issues;go vet ./...cleanNot run: e2e suites (no container runtime in this environment). No existing e2e or unit test asserted the old duplicate-tolerant list behaviour; the Modern paginator's duplicate-key tests exercise the generic paginator with synthetic collisions and are intentionally kept — the paginator must not depend on the aggregator's new uniqueness invariant.
New tests are adversarial by construction (the original bug survived because fixtures minted strictly unique keys): two backends sharing a URI, three sharing one, same-backend duplicates, prompts unique and shared, another backend literally advertising
b1_review(no longer collides — pinned as all-reachable), theb1+x_y/b1_x+yambiguity (pinned as a loud error),prefixFormat: "{workload}."honoured for prompts, a routing-table merge against an empty registry assertingGetBackendCapabilityName("b1_review") == "review"(the registry-miss branch this PR actually fixed), a duplicate placed exactly at the Modern page-size boundary (index 999/1000 of an 1100-item corpus), and repeated runs asserting winners never vary with map iteration order.Mutation-verified (each mutant fails at least one test): reverting unconditional prefixing to bare names; turning the ambiguity error into a silent drop; dropping the intra-backend duplicate guard (must drop, not error); reverting the no-resolver fallback to map-order iteration; forwarding the advertised name on registry miss; ignoring the configured
prefixFormat; disabling the URI/template dedupe.Changes
pkg/vmcp/aggregator/capability_conflicts.goErrUnresolvedConflicts), URI/template dedupe; policy rationale + enforcement-point note in the headerpkg/vmcp/aggregator/conflict_resolver.goapplyPrefixFormathelper,defaultPrefixFormatconst,promptPrefixFormatFromConfigpkg/vmcp/aggregator/prefix_resolver.go,priority_resolver.gopkg/vmcp/aggregator/default_aggregator.gopkg/vmcp/aggregator/aggregator.goResolvedCapabilities.Promptsbecomes[]ResolvedPrompt(embedsvmcp.Prompt+OriginalName); docs reflect unconditional prefixingpkg/vmcp/config/config.go+ generated CRDs +docs/operator/crd-api.mdprefixFormatfield doc now covers prompts (CRD YAML/docs regenerated)pkg/vmcp/cli/init.gopkg/vmcp/server/modern_pagination.godocs/arch/10-virtual-mcp-architecture.mdDoes this introduce a user-facing change?
Yes — every prompt advertised through vMCP is renamed. Prompts are now always advertised as
{backendID}_{name}(or perconflictResolutionConfig.prefixFormat), whether or not their name collides. Anything referencing an advertised prompt name must be updated:Prompt::"review"must becomePrompt::"github_review"(etc.). This matters most forforbidpolicies — a stale name silently stops matching, and a broadpermitwould then admit the call.prompts/listadvertises them).Additionally: duplicated resource URIs / resource templates are advertised once and reads deterministically route to the first backend in sorted-backend-ID order (previously listed per-backend with reads hitting an arbitrary backend that could change between runs), and aggregation now fails with an explicit error if two backends' prefixed prompt names compose to the same string.
Implementation plan
Approved implementation plan
Per-type conflict policies (the issue's "mirror the tool path" option is wrong for URIs):
prompts/get/completions already translate advertised → backend name viaBackendTarget.GetBackendCapabilityName(pkg/vmcp/client/client.go), identical to renamed tools. Revised in review round 1: renaming is unconditional (initially collision-only) — the advertised name is what Cedar authorizes on, and a membership-dependent rename detachesforbidpolicies (fails open). Every prompt becomesprefixFormat(backendID) + name; exact intra-backend duplicates drop with a WARN; cross-backend prefix ambiguity aborts aggregation withErrUnresolvedConflicts.OriginalCapabilityName), subscriptions andnotifications/resources/updatedcarry backend-native URIs, and embedded resource links in tool/prompt results are not rewritten by vMCP. Winner = first backend in sorted-backend-ID order; losers dropped with WARN. Reads strictly improve (routing could only ever serve one backend per URI); listing regresses from N indistinguishable entries to one.ResolveConflictsiterates backends in sorted-ID order and emits key-sorted lists;MergeCapabilitiesgets first-wins-with-WARN guards (defence in depth for direct callers), keeping the advertised lists and routing table in agreement. Revised in review round 1: the no-resolver tool fallback also iterates sorted backend IDs.Special notes for reviewers
ConflictResolver, all three strategies, andMergeCapabilities' tool handling); the only tools-path code change is the test-only no-resolver fallback becoming deterministic. The prefix and manual resolvers still iterate the backend map — fixing that is left to a follow-up so this PR stays scoped to the non-tool capability types.(LastKey, Delivered)collision-safe cursor is deliberately retained even though aggregated keys are now unique —paginateModernis generic and its signature cannot enforce a caller invariant.Generated with Claude Code