Skip to content

Resolve aggregator conflicts for resources, templates and prompts - #6075

Merged
JAORMX merged 3 commits into
mainfrom
fix-aggregator-conflicts
Jul 28, 2026
Merged

JAORMX merged 3 commits into
mainfrom
fix-aggregator-conflicts

Conversation

@JAORMX

@JAORMX JAORMX commented Jul 28, 2026 •

Copy link
Copy Markdown
Collaborator

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.URITemplate or Prompt.Name both appeared in the aggregated view, undiagnosed. Worse, MergeCapabilities keys 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:

  • Prompt names are names, like tool names: prompts/get already translates the advertised name back to the backend's own name via BackendTarget.GetBackendCapabilityName, so renaming does not break invocation. Every prompt is renamed unconditionally to its backend-prefixed form — conflictResolutionConfig.prefixFormat applied to the backend ID (default {workload}_), the same formatting path PrefixConflictResolver uses 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.go passes it to Cedar, which builds Prompt::"<advertised name>" entities), so a membership-dependent rename would silently detach permit and forbid policies from the prompt they were written for — the forbid case 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. backend b1 prompt x_y vs backend b1_x prompt y, both b1_x_y — is ambiguous between backends and now fails aggregation loudly with ErrUnresolvedConflicts instead of silently dropping a prompt.
  • Resource URIs and template strings are locators, not names — the client passes them back verbatim (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's name/description/mimeType are 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. priority and manual remain tool-only knobs (their configuration is tool-shaped); prefixFormat is 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 next prompts/list for listing; that gap predates this PR and applies to tools equally.

Closes #6060

Client-visible behaviour, before → after (both revisions, including Legacy)

Type Before After
Prompts, unique name advertised as-is; prompts/get works advertised as {backendID}_{name} (per prefixFormat); prompts/get on the prefixed name forwards the backend's own name; the bare name → not found
Prompts, name in N backends listed N times under one name; prompts/get hit a nondeterministic backend N distinct prefixed names, each routing deterministically to its backend
Prompts, prefix ambiguity (b1+x_y vs b1_x+y) both listed under distinct names; fine by accident aggregation fails with ErrUnresolvedConflicts naming both backends and both prompts
Resources, duplicated URI listed once per backend; resources/read hit a nondeterministic backend listed once, owned by the first backend in sorted-ID order; reads route there deterministically
Resource templates, duplicated template same as resources same as resources
Resource/template/prompt list ordering unspecified (backend-map iteration order; a Legacy client could see a different order per process) sorted by URI / template string / resolved name
Tools (list, order, routing) sorted by name since #5709 unchanged in production; the no-resolver fallback (reachable only in tests — both production call sites always pass a resolver) now picks first-wins in sorted backend order

How routing became deterministic

  • ResolveConflicts iterates 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 the capability_conflicts.go header).
  • MergeCapabilities no 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 direct MergeCapabilities callers — in the pipeline these guards can never fire, because ResolveConflicts runs first.
  • Known residual nondeterminism, now documented instead of overclaimed: the prefix and manual tool resolvers still iterate the backend map, so a tool collision after prefixing or a manual override picks a nondeterministic winner (docs/arch/10-virtual-mcp-architecture.md says 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

  • Bug fix

Test plan

  • Unit tests (task test) — passes except the three pre-existing environment-dependent failures (TestNewServer_ReadTimeoutConfigured, TestSecurityHeaders, TestCompositeProvider_RealProviders)
  • Linting (task lint) — 0 issues; go vet ./... clean

Not 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), the b1+x_y / b1_x+y ambiguity (pinned as a loud error), prefixFormat: "{workload}." honoured for prompts, a routing-table merge against an empty registry asserting GetBackendCapabilityName("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

File Change
pkg/vmcp/aggregator/capability_conflicts.go Per-type conflict resolution: unconditional backend-prefixing for prompts (ambiguity → ErrUnresolvedConflicts), URI/template dedupe; policy rationale + enforcement-point note in the header
pkg/vmcp/aggregator/conflict_resolver.go Shared applyPrefixFormat helper, defaultPrefixFormat const, promptPrefixFormatFromConfig
pkg/vmcp/aggregator/prefix_resolver.go, priority_resolver.go Delegate to the shared helper/const (no behaviour change)
pkg/vmcp/aggregator/default_aggregator.go Prompt prefix-format wiring; no-resolver fallback iterates sorted backend IDs; merge guards documented as defence in depth
pkg/vmcp/aggregator/aggregator.go ResolvedCapabilities.Prompts becomes []ResolvedPrompt (embeds vmcp.Prompt + OriginalName); docs reflect unconditional prefixing
pkg/vmcp/config/config.go + generated CRDs + docs/operator/crd-api.md prefixFormat field doc now covers prompts (CRD YAML/docs regenerated)
pkg/vmcp/cli/init.go Generated-config template comment mentions prompt prefixing
pkg/vmcp/server/modern_pagination.go Comment-only: keys are now unique upstream, but the generic paginator keeps its collision-safety (defence in depth)
docs/arch/10-virtual-mcp-architecture.md Conflict Resolution section documents the per-type policies; determinism claim scoped honestly

Does this introduce a user-facing change?

Yes — every prompt advertised through vMCP is renamed. Prompts are now always advertised as {backendID}_{name} (or per conflictResolutionConfig.prefixFormat), whether or not their name collides. Anything referencing an advertised prompt name must be updated:

  • Cedar authorization policies on prompts: Prompt::"review" must become Prompt::"github_review" (etc.). This matters most for forbid policies — a stale name silently stops matching, and a broad permit would then admit the call.
  • Clients that pin prompt names must switch to the prefixed names (prompts/list advertises 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):

  1. Prompts — rename, lossless. prompts/get/completions already translate advertised → backend name via BackendTarget.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 detaches forbid policies (fails open). Every prompt becomes prefixFormat(backendID) + name; exact intra-backend duplicates drop with a WARN; cross-backend prefix ambiguity aborts aggregation with ErrUnresolvedConflicts.
  2. Resources / resource templates — dedupe, never rewrite. URIs are locators: template-matched reads forward the client's concrete URI verbatim (template targets deliberately have empty OriginalCapabilityName), subscriptions and notifications/resources/updated carry 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.
  3. Determinism — ResolveConflicts iterates backends in sorted-ID order and emits key-sorted lists; MergeCapabilities gets 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.
  4. Out of scope, unchanged — production tools path (all three resolver strategies; their residual map-order iteration is now documented rather than overclaimed), Modern paginator collision-safety (generic code must not depend on a caller invariant).

Special notes for reviewers

  • The production tools path is behaviourally untouched (ConflictResolver, all three strategies, and MergeCapabilities' 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.
  • The Modern paginator's (LastKey, Delivered) collision-safe cursor is deliberately retained even though aggregated keys are now unique — paginateModern is generic and its signature cannot enforce a caller invariant.
  • Prompt prefixing intentionally applies even to a single-backend group: exempting it would reintroduce membership-dependent names (the second backend joining would rename the first backend's prompts).

Generated with Claude Code

@github-actions github-actions Bot added the size/L Large PR: 600-999 lines changed label Jul 28, 2026
@codecov

codecov Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.51515% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.30%. Comparing base (e2c4441) to head (d443ba1).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pkg/vmcp/aggregator/default_aggregator.go 83.33% 9 Missing and 4 partials ⚠️
pkg/vmcp/aggregator/prefix_resolver.go 50.00% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@JAORMX
JAORMX force-pushed the fix-aggregator-conflicts branch from 7177963 to abe41f1 Compare July 28, 2026 07:52
@github-actions github-actions Bot added size/L Large PR: 600-999 lines changed and removed size/L Large PR: 600-999 lines changed labels Jul 28, 2026

@jhrozek jhrozek 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.

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.

JAORMX added a commit that referenced this pull request Jul 28, 2026
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
@JAORMX
JAORMX force-pushed the fix-aggregator-conflicts branch from abe41f1 to eec5605 Compare July 28, 2026 09:20
@JAORMX
JAORMX requested review from blkt and reyortiz3 as code owners July 28, 2026 09:20
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/L Large PR: 600-999 lines changed size/XL Extra large PR: 1000+ lines changed labels Jul 28, 2026
JAORMX and others added 3 commits July 28, 2026 09:58
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
@JAORMX
JAORMX force-pushed the fix-aggregator-conflicts branch from eec5605 to d443ba1 Compare July 28, 2026 09:59
@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Jul 28, 2026

@jhrozek jhrozek 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.

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.

@JAORMX
JAORMX merged commit de1953e into main Jul 28, 2026
64 of 65 checks passed
@JAORMX
JAORMX deleted the fix-aggregator-conflicts branch July 28, 2026 11:37
JAORMX added a commit that referenced this pull request Jul 28, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/XL Extra large PR: 1000+ lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Aggregator does not resolve conflicts for resources, templates or prompts

2 participants