Skip to content

fix(hr): harden the collectible analyzer loader (review follow-up of #23863) - #23947

Merged
dr1rrb merged 3 commits into
masterfrom
dev/dr/hr-analyzer-loader-review-round4
Aug 4, 2026
Merged

dr1rrb merged 3 commits into
masterfrom
dev/dr/hr-analyzer-loader-review-round4

Conversation

@dr1rrb

@dr1rrb dr1rrb commented Aug 3, 2026

Copy link
Copy Markdown
Member

Follow-up to #23863 — the review-round-4 changes: the PR auto-merged the moment its last review conversations were resolved, before these fixes were pushed, so the "Done" replies on those threads describe the changes delivered here.

Changes (all on CollectibleAnalyzerAssemblyLoader)

Validation

  • Uno.HotReload.Tests: 120/120 passing, including two new regression tests — When_CompilerContextResolvesLazily_Then_AnalyzerRequestsUnifyToIt (lazily-resolving compiler context + same-directory copy of the assembly: the request must materialize in the compiler context; fails on the previous enumeration-based code) and When_MultipleVersionsRegistered_Then_RequestedVersionWins (two registered versions: the exact requested one must win over the first registered).
  • Uno.HotReload compiles warning-free on both flavors: net9.0 (Roslyn 4.14) and net10.0 (Roslyn 5.6).

…follow-up)

Delegate resolution to the compiler context (LoadFromAssemblyName, like
Roslyn's own loader) so host dependencies it has not loaded yet unify to it
instead of loading a split-identity analyzer-local copy; publish shadow
copies via a staging file + atomic rename so concurrent loads (threads or
dev-server processes sharing the temp root) never observe a partial PE;
retain every dependency location registered per file name and resolve to
the best version (exact match, else highest compatible) instead of
first-registered-wins; Path.Join throughout.
Copilot AI lite review requested due to automatic review settings August 3, 2026 17:06
@github-actions

github-actions Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 4m 50s —— View job


Code Review

  • Gather context and read changed files
  • Review CollectibleAnalyzerAssemblyLoader.cs
  • Review Given_CollectibleAnalyzerAssemblyLoader.cs
  • Post inline findings
  • Write summary

Overall: ship after addressing the two findings below (one test coverage gap, one code clarity nit).

Verdict: fix-first (nit scale — nothing blocking correctness)

The four pillars described in the PR are mechanically sound:

  • Compiler-context delegation: LoadFromAssemblyName + bare catch is the established Roslyn pattern. Avoids the split-identity duplicate and the linear Assemblies scan.
  • Atomic shadow-copy publish: staging + File.Move correctly handles the cross-thread and cross-process race. PDB published before DLL maintains the "bundle visible only when complete" invariant even in the concurrent case.
  • Best-candidate resolution: ImmutableHashSet + AddOrUpdate is a correct lock-free accumulation. The loop correctly tracks exact match (early exit) vs. highest-compatible fallback, and OrderBy makes tie-breaking deterministic.
  • Path.Join throughout: clean.

Findings

1 — Test coverage (moderate): When_MultipleVersionsRegistered_Then_RequestedVersionWins (test line 185) exercises only the exact-version-match fast path. The bestPath/bestVersion accumulation in GetBestKnownPath — the lines executed when no exact match exists — is never reached by the new tests. See inline comment for a minimal fix that fits in the existing test.

2 — GetBestKnownPath null coupling (low): requested.Name + ".dll" at loader line 85 relies silently on the caller's assemblyName.Name is not { Length: > 0 } guard rather than being self-contained. Forwarding simpleName as a separate parameter (already extracted by Load) would make the invariant explicit. See inline comment.

Informational (no action needed)

  • The bare catch in Load (line 228) swallows all exceptions from _compilerContext.LoadFromAssemblyName. In .NET Core, the truly catastrophic ones (OOM, stack overflow) terminate the process and can't be meaningfully caught anyway, so the blast radius is the same as Roslyn's own loader. The comment documents the intentional parity.
  • candidates.First() on a 1-element ImmutableHashSet (line 94) allocates a LINQ enumerator for a guaranteed-single-element set. Not worth changing on a non-hot path, but noted.

Copilot AI 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.

Pull request overview

This PR hardens CollectibleAnalyzerAssemblyLoader in Uno.HotReload to more closely mirror Roslyn’s analyzer loading semantics: delegating dependency resolution to the compiler AssemblyLoadContext, making shadow-copy publication atomic, and selecting the best dependency candidate when multiple versions are registered.

Changes:

  • Delegate dependency resolution to _compilerContext.LoadFromAssemblyName(...) (Roslyn-like behavior; avoids split-identity duplicates and avoids a linear scan).
  • Make shadow-copy publication atomic via staging + File.Move, and publish PDB before DLL.
  • Track multiple dependency locations per file name and resolve to the best match (exact version preferred, otherwise highest compatible).

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/Uno.HotReload/Roslyn/CollectibleAnalyzerAssemblyLoader.cs Implements compiler-context delegated resolution, atomic shadow-copy publication, and best-candidate dependency path selection.
src/Uno.HotReload.Tests/Roslyn/Given_CollectibleAnalyzerAssemblyLoader.cs Adds regression tests for lazy compiler-context resolution and multi-version dependency selection, plus fixture helpers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@unodevops

Copy link
Copy Markdown
Contributor

@carldebilly carldebilly left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Panel review of the loader hardening. The change is sound and faithfully mirrors Roslyn's own loader shape: the compiler-context delegation (LoadFromAssemblyName + bare-catch fall-through) matches AnalyzerAssemblyLoader.Core.cs, the staging-to-rename publish is a same-volume atomic move with the destination-exists race handled, a crash between the PDB and DLL publishes self-heals on retry, and both new regression tests genuinely fail on the previous code. No public-surface change; the multi-version registry keeps the lock-free/immutable idiom.

Approving — nothing below blocks. Inline: 8 medium and a handful of low/info suggestions. The two most valuable follow-ups are per-user isolation of the shared shadow-copy root and verifying the winner after a lost publish race; the rest are identity-check uniformity on the single-candidate path, diagnosability of the silent fallbacks, staging-file cleanup on non-race failures, and test coverage for the highest-compatible-version fallback and the atomic-publish guarantees.

@autocarl autocarl left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Follow-up review on exact head ceae5b4f517f39cc87bef13da28e8aa4e04f0130.

The three findings carried over from #23863 are correctly addressed for a clean cache: compiler-context resolution now delegates through LoadFromAssemblyName, registered same-name candidates are retained and version-selected, and new shadow copies are published by staging + atomic rename.

Validation on this head:

  • Uno.HotReload Release builds for net9.0 and net10.0: 0 warnings / 0 errors;
  • Uno.HotReload.Tests net10.0: 120/120 passed;
  • net9.0 test binary: 120/120 passed under the installed net10 roll-forward (the local host does not have the net9 runtime);
  • hosted checks: 49 success, 2 neutral, no failing check;
  • isolated regression probe: the legacy partial-final-cache scenario is reproducible.

One blocking upgrade-path issue remains inline: this implementation keeps the exact cache namespace/key used by the previously merged direct-copy code and trusts any existing final DLL, so the interrupted-copy artifact this change is intended to recover from remains permanently poisoned after upgrading. Requesting changes until existing entries are versioned or validated/rebuilt.

GetBestKnownPath now takes the already-validated simpleName (self-contained
lookup and identity comparison instead of relying on a guard in its caller),
and the highest-compatible-version fallback gets dedicated coverage — in a
fresh context, since a context that already loaded the simple name answers
later requests from its own by-name cache without calling Load() again.
Copilot AI review requested due to automatic review settings August 4, 2026 00:33
@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 2m 13s —— View job


Code Review

  • Gather context and read changed files
  • Review CollectibleAnalyzerAssemblyLoader.cs
  • Review Given_CollectibleAnalyzerAssemblyLoader.cs
  • Address autocarl's HIGH blocking issue (cache poisoning / upgrade path)
  • Post inline findings
  • Write summary

Verdict: fix-first (one-liner unblock)

The two previous findings from the last Claude review are correctly addressed in head 781487c6:

  • GetBestKnownPath(string simpleName, AssemblyName requested) — simpleName is now forwarded by Load, removing the implicit null dependency on the caller guard. ✓
  • When_RequestedVersionNotRegistered_Then_HighestCompatibleWins — a separate context requests 1.5.0.0 against registered v1/v2; the scan must pick v2 (the highest compatible). This correctly exercises the bestPath/bestVersion accumulation that the previous test didn't reach. ✓

Remaining blocker

1 — _shadowCopyRoot not versioned (HIGH) — autocarl's CHANGES_REQUESTED finding from the prior review round is still open. The root path remains "uno-devserver/analyzers", identical to the already-merged code. Any user whose old copy was interrupted mid-write has a partial .dll at the deterministic (path|timestamp) key; the new File.Exists guard skips Publish and returns the poisoned path, causing a permanent BadImageFormatException until the source timestamp changes. Bumping to analyzers-v2 (one-character change at line 45) is sufficient — see inline comment.

Informational (no action needed)

  • Nit: Path.ChangeExtension(fullPath, ".pdb") is { } pdb (line 150) — the pattern match is always true; var pdb = Path.ChangeExtension(...) + File.Exists(pdb) says the same thing with no dead branch. Inline suggestion posted.
  • All other findings from carldebilly's panel review remain at medium/low and were not newly introduced by the 781487c6 commit — no regression there.

Copilot AI 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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@unodevops

Copy link
Copy Markdown
Contributor

@unodevops

Copy link
Copy Markdown
Contributor

⚠️⚠️ The build 225598 has failed on Uno.UI - CI.

The shadow cache root moves from the shared temp directory to per-user
LocalApplicationData (user-only mode on Unix): this closes the shared-root
pre-plant/swap surface and retires, by namespace, anything a pre-atomic-
publish version of the cache may have left truncated at still-reachable
keys. The key now folds in the file size, staging files are never leaked
(cleanup on every failure path plus an age-gated startup sweep), the
identity check applies to every registered candidate (single-candidate
fast path removed), an optional IReporter traces candidate selection and
compiler-context fallbacks, and simple names carrying invalid file-name
characters are rejected before any probing.
Copilot AI review requested due to automatic review settings August 4, 2026 14:46
@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @dr1rrb's task in 5m 35s —— View job


Code Review

  • Gather context and understand the PR
  • Read CollectibleAnalyzerAssemblyLoader.cs
  • Read Given_CollectibleAnalyzerAssemblyLoader.cs
  • Read supporting files (RoslynExtensions.AnalyzerReferences.cs, ServerHotReloadProcessor.MetadataUpdate.cs)
  • Post inline findings
  • Write summary

Verdict: ship (one low-severity nit)

All findings from the previous two Claude review rounds and from autocarl's blocking CHANGES_REQUESTED are correctly resolved in head f0113784:

  • Cache namespace / upgrade path (autocarl HIGH): shadow root moved wholesale to LocalApplicationData/uno-devserver/analyzers — the old temp-rooted path is unreachable, so every poisoned entry from the pre-atomic-publish code is retired, not validated or migrated. The relocation also resolves carldebilly's shared-/tmp first-writer-owns security concern. ✓
  • GetBestKnownPath null coupling: simpleName forwarded explicitly by Load, no longer depends on caller guard. ✓
  • Single-candidate fast path skipped identity check: fast path removed; every candidate, including a lone one, goes through name/PKT filtering — a stale mismatched registration falls through to runtime resolution instead of being force-loaded. ✓ Pinned by When_RequestedTokenDoesNotMatch_Then_CandidatesAreSkipped.
  • Highest-compatible fallback untested: When_RequestedVersionNotRegistered_Then_HighestCompatibleWins covers it with a fresh context requesting 1.5.0.0 against registered 1.0/2.0, asserting 2.0 wins. ✓
  • Atomic-publish recovery untested: When_ShadowDirectoryHoldsPartialState_Then_LoadRecovers pre-plants orphaned staging + pdb-without-dll debris at the exact computed key and asserts the load succeeds. ✓
  • Staging file cleanup on non-race failures: File.Copy and File.Move now share the try, cleanup resets read-only attribute before deletion, catches IOException | UnauthorizedAccessException. ✓
  • IReporter threading: WithCollectibleAnalyzerReferences accepts and passes through _reporter; ambiguous multi-candidate decisions and compiler-context fallbacks are Verbose-traced. ✓
  • Path.ChangeExtension dead branch: cleaned to var pdb = ... ; if (File.Exists(pdb)). ✓
  • simpleName path-traversal / hostile-reference rejection: SearchValues<char> over GetInvalidFileNameChars() guards before both directory and registered-location probes. ✓
  • Ordinal sort comment: now states the determinism intent explicitly. ✓
  • Candidate probe exception filter: now also catches UnauthorizedAccessException and ArgumentException. ✓
  • Key now includes file size: {path}|{timestamp}|{length} guards common timestamp-preserving rewrites; residual (same-time, same-size content swap) documented. ✓
  • Same-path-same-instance: asserted by the existing When_LoadFromPath_Then_LoadsCollectible_And_SharesContextPerDirectory. ✓

Findings

1 — PDB publish failure is fatal to the DLL load (LOW): Publish(pdb, ...) at loader line 235 can throw IOException if the source .pdb disappears between the File.Exists(pdb) guard and File.Copy inside Publish (common during a concurrent build clean). The exception propagates out of EnsureShadowCopy before the DLL is shadow-copied, causing the analyzer load to fail — even though the PDB is optional debug symbols. A bare try { ... } catch (IOException) { } wrapping the PDB publish call is the minimal fix. See inline comment.

Informational (no action needed)

  • #nullable enable not declared: the file uses nullable annotations throughout (IReporter?, string?, Version?, etc.) but does not declare #nullable enable at the top. AGENTS.md recommends enabling it on refactored files; adding it would make the annotations enforced by the compiler rather than advisory. No change required for this PR.
  • GetShadowCopyPath makes two separate filesystem calls (File.GetLastWriteTimeUtc + new FileInfo(...).Length): the same file change that the existing timestamp window can't catch also affects this; using a single FileInfo instance with a manual Refresh() doesn't actually close the window either. Documented as a known residual in the code comment.
  • candidates.OrderBy(...) allocates on every Load miss for the registered-location probe: non-hot path (each (context, simpleName) pair resolves at most once due to ALC caching); not worth changing.

Copilot AI 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.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.

Suppressed comments (2)

src/Uno.HotReload.Tests/Roslyn/Given_CollectibleAnalyzerAssemblyLoader.cs:285

  • This test deliberately writes staging/PDB debris into the real shadow-copy cache under LocalApplicationData (via GetShadowCopyPath) but only deletes the temp "root" directory. That leaves persistent artifacts in the user's profile (and in CI agents), which can accumulate and potentially affect later runs. Clean up the per-key shadow directory in the finally block as best-effort test hygiene.
		finally
		{
			Directory.Delete(root, recursive: true);
		}

src/Uno.HotReload/Roslyn/CollectibleAnalyzerAssemblyLoader.cs:107

  • GetBestKnownPath always orders the candidate set with OrderBy, which forces a full buffer+sort even when there is only a single registered location (likely the common case). This adds avoidable allocations/CPU on every dependency bind attempt; only sort when there are multiple candidates (ties) to keep determinism.
		// Ordinal order is load-bearing, not cosmetic: ImmutableHashSet enumeration order is
		// unspecified, and a deterministic scan keeps the winner stable when candidates tie.
		foreach (var path in candidates.OrderBy(static p => p, StringComparer.Ordinal))
		{

@unodevops

Copy link
Copy Markdown
Contributor

@dr1rrb
dr1rrb merged commit f519028 into master Aug 4, 2026
69 checks passed
@dr1rrb
dr1rrb deleted the dev/dr/hr-analyzer-loader-review-round4 branch August 4, 2026 17:53
@kazo0

kazo0 commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

@Mergifyio backport release/stable/6.7

@mergify

mergify Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

backport release/stable/6.7

✅ Backports have been created

Details

kazo0 added a commit that referenced this pull request Aug 11, 2026
…6.7/pr-23947

fix(hr): harden the collectible analyzer loader (review follow-up of #23863) (backport #23947)
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.

6 participants