Skip to content

fix(devserver): cross-add-in type sharing via file-system probe in AddInLoadContext - #23306

Closed
carldebilly wants to merge 4 commits into
masterfrom
dev/cdb/fix-addin-alc-shared-types
Closed

carldebilly wants to merge 4 commits into
masterfrom
dev/cdb/fix-addin-alc-shared-types

Conversation

@carldebilly

@carldebilly carldebilly commented May 21, 2026 •

Copy link
Copy Markdown
Member

Summary

#23287 moved DevServer add-in loading from Assembly.LoadFrom (everything in Default ALC) into a shared isolated AddInLoadContext. That fixed three cross-major-version FileNotFoundExceptions (Kiota, Mcp, ModelContextProtocol) and must stay in place.

Side effect: contract assemblies physically present in one add-in's directory but absent from every add-in's .deps.json could no longer be resolved across the ALC boundary. Uno.Licensing.Sdk.Contracts falls into this bucket — the Settings add-in provides it, but the Mcp and HotDesign add-ins consume it via DI without listing it in their own .deps.json. At runtime this produces:

fail: Uno.UI.RemoteControl.Host.RemoteControlServer
  Failed to create server processor Uno.UI.App.Mcp.Server.McpServerProcessor ...
  System.IO.FileNotFoundException: Could not load file or assembly
  'Uno.Licensing.Sdk.Contracts, Version=1.0.0.0, ...'
fail: Uno.UI.RemoteControl.Host.RemoteControlServer
  Failed to create server processor Uno.UI.HotDesign.HotDesignSourceProcessor ...
  System.InvalidOperationException: Unable to resolve service for type
  'Uno.Licensing.Sdk.ILicensingService'

The "Initializing Uno Platform Studio, please wait…" overlay never resolves because these two processors never register.

Fixes #23304.

Fix — zero knowledge of which add-ins are loaded

The DevServer host has no static list of which contract assemblies need to be shared (no white-list, no per-product glob). The published add-ins are not modified — they continue to ship as-is.

Root cause

The resolution chain inside AddInLoadContext.Load(AssemblyName) has three steps:

  1. TryBridgeBySimpleName(Default, …) — already-loaded in Default ALC ?
  2. Default.LoadFromAssemblyName(…) — listed in the host TPA ?
  3. Each add-in's AssemblyDependencyResolver.ResolveAssemblyToPath(…) — listed in any .deps.json ?

AssemblyDependencyResolver only consults .deps.json. It does not probe the file system. When a contract DLL is physically present in an add-in directory but absent from every add-in's .deps.json, all three steps return null and the runtime throws FileNotFoundException. Before PR #23287, Assembly.LoadFrom's implicit directory probing masked this packaging quirk.

Step 4 — file-system probe

AddInLoadContext.Load gains a fourth, last-resort step: a Dictionary<string,string> snapshot built at construction time enumerates every *.dll co-located with the registered add-ins, keyed by simple name. Step 4 looks up the snapshot and LoadFromAssemblyPath's the matching candidate into the shared add-in ALC. Every add-in then sees the same Type identity and DI resolves cleanly.

Properties:

  • Deterministic ordering: the snapshot is built in caller-supplied registration order, first-add-in-wins. Independent of host file-system enumeration order.
  • Version-downgrade guard: a candidate with a strictly-lower version than the request is refused, mirroring steps 1 and 2.
  • Per-candidate failure isolation: LoadFromAssemblyPath failures (BadImageFormatException, etc.) are caught and treated as misses so the chain stays consistent.
  • Path-traversal guard: AssemblyName.Name values containing path separators are rejected before any probe.
  • Cross-major scenarios untouched: step 1 still bridges Kiota's net8 System.Text.Encodings.Web 8.0.0.0 ref to the host's loaded v9/v10.

Asymmetric PKT match

TryBridgeBySimpleName and AddInLoadContext.Load step 2 enforce a PKT match only when the request carries a non-empty PublicKeyToken. Signed framework AssemblyRefs (e.g. System.Text.Json, System.Text.Encodings.Web from compiled add-ins) require matching PKT — preventing identity swaps even if a same-name candidate sits in Default ALC. Unsigned requests (cross-add-in unsigned contracts) skip the check. This is identity validation, not an allow-list.

Other cleanup

  • Removed the unused s_trustedPkts / IsTrustedPkt() and the misleading [ERROR] untrusted public key token warning that the VS "Uno Platform" output panel flagged on every host startup.
  • Step 4 successful probe-load messages go to Console.Out (informational); only genuine failures stay on Console.Error.
  • DevServer_ShouldResolveSharedContractAcrossAddIns… fixes the --addins arg format (semicolon-separated, not space-separated — the previous form silently dropped the consumer add-in).

…s-add-in type sharing

PR #23287 moved add-in loading into a shared AddInLoadContext. Side effect:
unsigned contract assemblies (e.g. Uno.Licensing.Sdk.Contracts) that are
present in one add-in's directory but absent from other add-ins' deps.json
could not be resolved across the ALC boundary, causing:

  - FileNotFoundException when McpServerProcessor's ctor inspects
    ILicensingService (Uno.Licensing.Sdk.Contracts not found)
  - InvalidOperationException: Unable to resolve service for type
    ILicensingService in HotDesignSourceProcessor (type identity broken)

Fix: before building AddInLoadContext, AssemblyHelper.Load now calls
EagerLoadFromDirectory for each add-in directory using the new
AddInSharedAssemblyPatterns glob ("Uno.Licensing.*.dll"). This loads the
contracts DLL into Default ALC, where TryBridgeBySimpleName (step 1 of
AddInLoadContext.Load) serves it to all add-ins with a single Type identity.

Also removes the misleading s_trustedPkts / IsTrustedPkt PKT warning in
EagerLoadFromDirectory — the warning fired for System.Reactive and
Microsoft.Extensions.AI.Abstractions, appearing as [ERROR] in VS even
though bridging still worked correctly via the symmetric PKT policy in
TryBridgeBySimpleName.

Tests: new unit tests for the patterns parameter and constants; new
cross-add-in type sharing integration test with three fixture projects
(Uno.Licensing.TestContracts, AddInWithSharedContractProvider,
AddInWithSharedContractConsumer) that reproduce the exact failure
scenario (contracts DLL only in provider's directory, absent from
consumer's deps.json) and verify the sentinel is written after the fix.

Fixes #23304
Copilot AI review requested due to automatic review settings May 21, 2026 19:46
@carldebilly
carldebilly marked this pull request as draft May 21, 2026 19:48

This comment was marked as resolved.

@unodevops

Copy link
Copy Markdown
Contributor

…e-system probe

The previous fix pre-loaded `Uno.Licensing.*.dll` from each add-in directory
into Default ALC via a hardcoded glob list (`AddInSharedAssemblyPatterns`).
That couples the generic DevServer host to specific Uno Platform product
names and grows every time a new contract assembly hits the same packaging
quirk. Replace the white-list with a probe that has zero knowledge of which
add-ins are loaded and requires no changes to the currently-published
add-in packages.

Root cause precisely: when a contract DLL is physically present in one
add-in's directory but absent from every add-in's deps.json, steps 1-3 of
`AddInLoadContext.Load` all return null because
`AssemblyDependencyResolver` only consults deps.json — it does not probe
the file system.

Fix: add a fourth resolution step inside `AddInLoadContext.Load` that scans
each registered add-in directory for a matching `{simpleName}.dll` and
loads it via `LoadFromAssemblyPath`. The DLL ends up in the shared add-in
ALC, so every add-in sees the same Type identity and DI resolves cleanly.
This mirrors the implicit probing `Assembly.LoadFrom` performed before
PR #23287 introduced ALC isolation.

Also drop unused machinery:
- Remove `AddInSharedAssemblyPatterns` constant and its companion eager-load
  loop in `AssemblyHelper.Load`.
- Drop the `patterns` parameter from `EagerLoadFromDirectory`. The default
  host-directory eager-load (`System.*` / `Microsoft.Extensions.*`) remains
  unchanged — it is what keeps the cross-major-version scenarios from
  PR #23287 working.
- Promote `DefaultEagerLoadPatterns` to `ImmutableArray<string>`.
- Strip the PKT symmetry check from `TryBridgeBySimpleName` and from step 2
  of `AddInLoadContext.Load`. Add-ins and contract DLLs are unsigned in
  practice; the guard never triggered. Dynamic-skip and version-downgrade
  guards stay.
- Replace duplicate kill-switch read in `Install()` with the existing
  `IsKillSwitchActive` property.
- Rename `_contract` primary-ctor parameter to `contract` in the consumer
  fixture.

Tests:
- New `Given_AddInLoadContext` step-4 tests (red->green TDD): file-system
  probe finds DLLs absent from every deps.json, probes every registered
  add-in directory (not only the first), and returns null/throws cleanly
  when nothing matches.
- Drop the `AddInSharedAssemblyPatterns_*` constant tests and the custom
  `patterns` parameter tests.
- Drop `TryBridgeBySimpleName_RejectsStrongNamedLoaded_WhenRequestedIsUnsigned`.
- `DevServer_ShouldResolveSharedContractAcrossAddIns_WhenContractOnlyInProviderDirectory`:
  switch `--addins` arg to semicolon-separated paths (host parses a single
  string, two space-separated tokens silently dropped the consumer),
  and assert the sentinel's AssemblyQualifiedName references the shared
  contracts assembly to prove single Type identity end-to-end.
… ordered probe map, error isolation

Addresses the review-panel findings on the cross-add-in type-sharing fix:

- **Ordered probe map (H2)**: replace `string[] _addInDirectories` derived from a
  `HashSet<string>` with a `Dictionary<string,string>` (simple name → full path)
  built once at construction. The dictionary is populated in caller-supplied
  registration order so "first add-in wins" when two directories ship the same
  simple name — `HashSet` enumeration order was unspecified and could flip
  silently across runs.

- **Version-downgrade guard (H1)**: step 4 now reads `AssemblyName.GetAssemblyName`
  on the candidate before loading and refuses a strictly-lower version than
  requested. Mirrors the symmetric guard in steps 1 and 2; prevents an older
  co-located DLL from silently satisfying a newer AssemblyRef and turning into
  `MissingMethodException` later.

- **Per-candidate load failure isolation (M1)**: wrap `LoadFromAssemblyPath` in
  the same `FileNotFoundException`/`FileLoadException`/`BadImageFormatException`
  catch as step 2. A malformed candidate now returns null (clean FNFE at the
  call site) instead of bubbling the raw `BadImageFormatException` and aborting
  the resolution chain.

- **Path-traversal guard**: reject `AssemblyName.Name` values containing path
  separators. The `AssemblyName(string)` constructor already validates this,
  but the public `Name` setter does not — so the guard is reachable through
  metadata-free construction and worth exercising.

- **Step 4 breadcrumbs (M3)**: log to stderr on probe hit (with resolved path)
  and on per-candidate load failure, so an operator can tell which add-in
  directory satisfied a cross-add-in contract resolve and distinguish "no
  candidate" from "had a candidate but failed to load". `ILoggerFactory` is
  unavailable at this layer; the stderr fallback matches the existing
  `EagerLoadFromDirectory` and ctor-failure breadcrumbs.

- **O(1) lookup (M5)**: the dictionary snapshot also removes the per-miss
  `File.Exists × N` directory scan. Hot reflection paths that resolve missing
  assemblies repeatedly now hit a single hash lookup.

- **Stale fixture XML comments (M4)**: rewrite the `AddInWithSharedContract*`
  csproj documentation. Both files still described the superseded white-list
  mechanism (`Uno.Licensing.*.dll` eager-load into Default ALC) and the
  inaccurate "no .deps.json produced" claim. Replaced with the step-4
  file-system probe semantics that the fixtures actually exercise.

- **Strengthened test assertions**: new `Load_StoresProbedAssemblyInAddInLoadContext_NotInDefault`
  uses `AssemblyLoadContext.GetLoadContext` to lock in that the probed assembly
  stays inside the add-in ALC (catches a future regression that loaded into
  Default and broke isolation). New tests for the version-downgrade refusal,
  path-traversal rejection, and load-failure isolation cover the new guards
  TDD-style (red → green).
Copilot AI review requested due to automatic review settings May 21, 2026 23:09

This comment was marked as resolved.

@unodevops

Copy link
Copy Markdown
Contributor

…eName and AddInLoadContext step 2

The earlier removal of the PKT check was over-aggressive. The argument
("add-ins are unsigned in practice") only holds for cross-add-in contract
assemblies (Uno.Licensing.Sdk.Contracts and friends) — but the bridge
also serves strong-named framework assemblies whose AssemblyRefs from
compiled add-ins do carry a PublicKeyToken (System.Text.Json, Kiota's
net8 ref to System.Text.Encodings.Web 8.0.0.0, etc.). For those, a
same-name candidate with a different (or absent) PKT must not silently
substitute the wrong identity.

Reintroduce a PKT match — not an allow-list — gated on the request side:

  - If the request carries a non-empty PublicKeyToken, the loaded
    candidate's PKT must match (signed identity validation).
  - If the request is unsigned, skip the PKT check entirely so
    cross-add-in contract loading (the file-system-probe scenario) is
    unaffected.

The change is symmetric across the two call sites:

  - `HostAssemblyResolution.TryBridgeBySimpleName` (step 1 of
    `AddInLoadContext.Load` and the `Default.Resolving` handler).
  - `AddInLoadContext.Load` step 2 (host TPA lookup): the assembly
    returned by `Default.LoadFromAssemblyName` is now PKT-validated
    against the request before being handed back.

No static `s_trustedPkts` allow-list is reintroduced. The previous
`IsTrustedPkt` logic was a different concern (warn-on-eager-load) and
not what defended bridging.

Test updates:
  - New `TryBridgeBySimpleName_RefusesBridge_WhenSignedRequestPktDoesNotMatchLoaded`
    (red-then-green) flips a byte of the real PKT and verifies the
    bridge refuses the swap.
  - New `TryBridgeBySimpleName_Bridges_WhenSignedRequestPktMatchesLoaded`
    locks in that the signed-framework happy path still works.
  - The three step-1 framework tests (System.Text.Json,
    Logging.Abstractions, System.Text.Encodings.Web) now set the real
    PKT on the request so they mirror how compiled AssemblyRefs reach
    the bridge.

Step 4 success log moved from `Console.Error` to `Console.Out`. The
"file-system probe loaded X" message is purely informational; IDE
output panels treat stderr as red ink and were flagging successful
startup as if something had failed. Failure paths stay on stderr.
@unodevops

Copy link
Copy Markdown
Contributor

@carldebilly carldebilly changed the title fix(devserver): pre-load Uno.Licensing.* from add-in dirs to fix cross-add-in type sharing fix(devserver): cross-add-in type sharing via file-system probe in AddInLoadContext May 21, 2026
@carldebilly

Copy link
Copy Markdown
Member Author

Closing — superseded by a different approach

This PR went through four iterations on the same branch and ultimately reached a structural dead end. Closing it (without merging) and starting fresh on a new branch is the cleaner path forward. Documenting the journey here so the lessons aren't lost.

What we tried

Commit Approach Verdict
f87cbd1db1 Pre-load Uno.Licensing.*.dll from each add-in directory into Default ALC via a hardcoded glob (AddInSharedAssemblyPatterns). Rejected — bakes product-specific knowledge into generic host infrastructure.
a9f4c3a790 Zero-knowledge file-system probe (step 4) inside AddInLoadContext.Load, scanning every registered add-in directory for {simpleName}.dll. Replaced — only addresses one of the three AssemblyLoadContexts in play.
3707062a6f Hardened step 4: version-downgrade guard, ordered probe map, per-candidate error isolation, path-traversal guard. Stabilises step 4 but doesn't change its structural limit.
063c378b24 Restored asymmetric PKT match in TryBridgeBySimpleName and AddInLoadContext step 2; success log moved off stderr. Necessary identity-validation; conceptually carries over.

Verified failure in production

Package 6.7.0-dev.204.ga6d055699e — i.e. the merge commit a6d055699e of 063c378b24 into master — installed in a real Uno 6.7 project:

fail: Failed to create server processor Uno.UI.App.Mcp.Server.McpServerProcessor
  System.IO.FileNotFoundException: Could not load file or assembly
  'Uno.Licensing.Sdk.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

fail: Failed to create server processor Uno.UI.HotDesign.HotDesignSourceProcessor
  System.InvalidOperationException: Unable to resolve service for type
  'Uno.Licensing.Sdk.ILicensingService' while attempting to activate
  'Uno.UI.HotDesign.HotDesignSourceProcessor'

The host log shows no file-system probe loaded breadcrumb, meaning step 4 either never matched Uno.Licensing.Sdk.Contracts (the DLL is not in any registered add-in directory) or matched silently in a code path we don't observe.

Crucially, the second failure is Unable to resolve service — not FileNotFoundException. That tells us the contracts DLL is loaded somewhere; what's broken is DI: the Type registered by the provider doesn't match the Type the consumer's constructor expects.

The structural insight

The DevServer host runs three AssemblyLoadContexts in parallel:

  1. Default ALC — host code, IServiceCollection, IServiceProvider.
  2. AddInLoadContext — add-ins loaded via --addins (e.g. Uno.UI.App.Mcp.Server, Uno.Settings.DevServer). Introduced by fix(devserver): isolate add-ins in a custom AssemblyLoadContext #23287.
  3. Per-applicationId ALC — client-app-side processors sent over the websocket (e.g. Uno.UI.HotDesign.HotDesignSourceProcessor), built by RemoteControlServer.GetAssemblyLoadContext.

When a provider in ALC #2 registers services.AddSingleton<ILicensingService, X>(), the ServiceDescriptor stores typeof(ILicensingService) as loaded into ALC #2. When a consumer in ALC #3 asks provider.GetService<ILicensingService>(), its Type is the one loaded into ALC #3. These are different Type instances of the same simple name — DI cannot match them. No amount of probing inside any single ALC fixes this.

This is the original sin of cross-ALC IoC and the reason the file-system probe couldn't succeed regardless of how robust it became.

Next direction (the new PR will link back here)

Revert the ALC isolation introduced by #23287. Use Assembly.LoadFrom for all add-ins so every type lives in Default ALC — a single Type per simple name, DI works naturally.

The cross-major-version scenarios that #23287 originally fixed (Kiota net8 → System.Text.Encodings.Web 8.0.0.0, Mcp net10 → Microsoft.Extensions.Configuration 10.0.0.0, ModelContextProtocol → v10 refs) are already handled by the Default.Resolving handler + TryBridgeBySimpleName, which exists independently of the ALC isolation and stays in place.

Two diagnostic additions to make future debugging easier:

  • Proactive at add-in load time — walk assembly.GetReferencedAssemblies() after each Assembly.LoadFrom, compare against the host's loaded set, log structured warnings on version/PKT mismatch with the add-in name. Surfaces conflicts before they manifest as runtime exceptions.
  • Reactive in TryBridgeBySimpleName — info-log successful bridges with version mismatch (requested vs returned), warn on misses with the list of currently-loaded variants of the same simple name. When something goes wrong the operator sees an actionable message.

Carries over to the new PR

  • The asymmetric PKT match + version-downgrade guard stabilised in 063c378b24.
  • The three test fixtures (Uno.Licensing.TestContracts, AddInWithSharedContractProvider, AddInWithSharedContractConsumer) and the cross-add-in integration test — they genuinely reproduce the production scenario and validate the single-ALC fix end-to-end.
  • The pre-existing AddInWithCrossMajorVersionRefs fixture remains relevant as a non-regression for fix(devserver): isolate add-ins in a custom AssemblyLoadContext #23287's three scenarios.

Follow-up out of scope here

A CI-side validation in src/Uno.Sdk/ of this repo: walk the add-in packages listed in src/Uno.Sdk/packages.json at SDK publish time, build a simpleName → (version, sourcePackage)[] index, fail the SDK build on misalignment. Catches the same class of issue before it ever reaches a user. Tracked separately.

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.

App is unresponsive when launched on An Android physical device

3 participants