Repository navigation
perf(reconciler): gate V1 ReactorState tagging on HasCallbacks (spec 047 §4.4 follow-up) - #468
Conversation
…047 §4.4 follow-up)
The post-§4.5 V1 dispatch adapter tagged every mounted control with a
ReactorState via the attached DP, allocating one per leaf mount. The
legacy reconciler only tagged callback-bearing elements (see
ChildReconciler.cs:91, Reconciler.Update.cs:83), leaving display leaves
(TextBlock / Border / StackPanel / Image — the bulk of any real tree)
untagged. The unconditional tag was a +21.6% bytes/render regression on
the Mount_Leaf_NoCallback benchmark (1,071 → 1,302 B/render vs.
pre-V1).
Gate V1HandlerAdapter.Mount/Update through a new SetElementTagIfNeeded
helper that:
- Cheap-refreshes Element on an existing ReactorState (callback-bearing,
pooled-reuse, or echo-scope controls).
- Skips the allocation + attached-DP write when the element has no
callbacks and the control has no state yet.
Routed-input modifiers (.OnPointerPressed etc.) dispatch via
ModifierEventHandlerState.Current* slots refreshed each render by
ApplyEventHandlers — they do not resolve via the tag, so they are
intentionally outside the gate. Implicit composition animations
registered by ApplyPropertyAnimation continue to fire on direct visual
writes, so .Animate() on callback-free leaves still works without a tag.
Benchmark deltas vs. pre-V1 baseline (5000 iterations):
M1 Mount_Leaf_NoCallback: 1,302 → 980 B/render (−24.7%; -8.5% vs pre-V1)
M3 Mount_Leaf_ThreeCallbacks: 8,461 → 8,428 B/render (no change; tag still set)
M8 Update_OneLeafChanged: 362 → 310 B/render (−14.4%; -27% vs pre-V1)
Validation: full selftest suite (982 fixtures) — 1 failure matching
baseline (pre-existing GridViewLazy flake unrelated to this change).
Key targeted fixtures pass: Trampoline*, EventStateSplit*, EchoSuppress*,
Modifier*, Selection*, Pool* (Marquee pool reset uses the public
SetElementTag API, which remains unchanged).
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
This PR aims to reduce mount/update allocations in the V1 protocol path by avoiding ReactorState (attached DP) tagging for controls whose elements have no callbacks, aligning the V1 adapter behavior with the legacy reconciler’s allocation discipline.
Changes:
- Route V1 handler adapter tagging through a new
Reconciler.SetElementTagIfNeeded(...)helper. - Add
SetElementTagIfNeededto skip allocating/writingReactorStatewhenElement.HasCallbacks == falseand no state exists yet.
Show a summary per file
| File | Description |
|---|---|
| src/Reactor/Core/V1Protocol/V1HandlerAdapter.cs | Switches Mount/Update tagging to the new gated helper to reduce per-control allocations. |
| src/Reactor/Core/Reconciler.cs | Introduces SetElementTagIfNeeded to conditionally allocate/write ReactorState based on callback presence. |
Copilot's findings
Tip
Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- Files reviewed: 2/2 changed files
- Comments generated: 1
| internal static void SetElementTagIfNeeded(FrameworkElement control, Element element) | ||
| { | ||
| if (control.GetValue(ReactorAttached.StateProperty) is ReactorState state) | ||
| { | ||
| // State already allocated (callback-bearing control, pooled reuse, | ||
| // or echo/setter scope) — refresh the live element with no alloc. | ||
| state.Element = element; | ||
| return; | ||
| } | ||
| if (!element.HasCallbacks) return; // no trampoline will read the tag | ||
| control.SetValue( | ||
| ReactorAttached.StateProperty, | ||
| new ReactorState { Element = element }); | ||
| } |
…llow-up)
The initial gate (HasCallbacks only) missed two readback paths that the
legacy reconciler implicitly preserved by tagging every control:
1. ChildReconciler.cs:303,392 reads the child's tag to extract the
stable Key during keyed reorders. A callback-free keyed element
(e.g. `Border(...).WithKey("a")`) lost its identity, causing
AAF_FlexColumn_MoveUnderAnimate_AttachesImplicitOffset to fail
under both Selftests and AOT Selftests in CI.
2. Several Element.Extensions features have engine paths that read
the live element back through GetElementTag — exit transitions
(ElementTransition), connected-animation snapshots
(ConnectedAnimationKey), InteractionStates, KeyframeAnimations,
and friends. Flagged by the Copilot PR reviewer.
Extend the gate to `HasCallbacks || Key != null || Extensions != null`.
The `Extensions != null` check is a coarse but robust catch-all —
`Extensions` being null is spec 047 §4.4's "truly inert leaf"
signal, so any element with bucketed extras pays the tag rather than
risk a future readback regression. Bare TextBlock/Border/StackPanel
leaves (the M1 benchmark target) have no callbacks, no key, no extras
— gate still applies, perf savings preserved.
Validation: full selftest suite (991 fixtures) — 1 pre-existing flake
(GridViewLazy, unrelated, same on baseline). The keyed-reorder fixture
that regressed in CI now passes 3/3 in isolation and clean in the full
run.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
|
Pushed Root causeThe CI failure (
FixExtend the gate to Perf preservedThe M1 benchmark target (bare ValidationFull selftest suite (991 fixtures) — 1 pre-existing flake ( |
PR #468 (`SetElementTagIfNeeded`) gates the V1 adapter's `SetElementTag` on `_handler.HasCallbacks`, so callback-free leaves no longer allocate a `ReactorState` + attached-DP write per mount. M12 (`Pool_Rent_HotPath`) was the worst hit of the spec-047 Phase-4 allocation regressions and is the clean validation target for this gate. Re-capture on the spec-047 baseline box (`LAPTOP-4MEP83VI`, ARM64, Release, .NET 10.0.8, same harness, same iters/reps as the 2026-05-29 capture): M12 bytes/render (mean across 5 reps × 1000 iters): Variant Baseline (2026-05-25) Phase 4 (2026-05-29) Post-gate (now) Direct 773 772 752 ReactorToday 1,102 1,324 968 (-12.2% vs base) Reactor (V1) 1,102 1,289 968 (-12.2% vs base) Framework overhead (Reactor - Direct): Baseline 329 B/op Phase 4 517 B/op (+57%) Post-gate 216 B/op (-34% vs baseline) The ~113 B/op overhead drop vs baseline matches the predicted savings from skipping the `ReactorState` allocation + `SetValue(StateProperty, ...)` on the callback-free TextBlock path that M12 exercises in a tight loop. Changes: - Add `2026-05-30-arm64-postgate/RESULTS.md` with the M12-only comparison table, framework-overhead delta, and verdict; raw data committed alongside as `perfbench-controlmodel-m12.jsonl`. - Annotate the existing 2026-05-29 Phase-4 RESULTS.md: 📌 callout pointing at the post-gate folder, strikethrough on the M12 cell with the new number, inline update note in the prose, and a fixed/✅ marker in the bottom-line bullet. M1 is flagged as likely also closed (per PR #468's commit message reporting M1=980 B/render) but is intentionally NOT re-captured here — out of scope for this change. Out of scope (follow-ups): - Independent M1/M2/M3 re-capture on this box to validate the §11.6 byte-gate. - §15.5-isolated timing-axis re-capture. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Fourth Copilot review on #1147. Pass-throughs are no longer intercepted at all. When/If/Expr return the caller's element verbatim, and the first-stamp-wins guard only defers when that element already has a location. An element built while mapping was off (or served from a memo cache) has none, so the wrapper would write its own line and report itself as the creator of something built elsewhere - a confident wrong answer, which is worse than no answer. TryDescribe now declines them outright; the guard stays as defence for a factory returning a cached element it did not build on this call. The name list has a drift guard rather than a comment asking people to be careful. PassThroughFactoryDriftTests derives the pass-through set structurally - a factory returning the BASE Element that takes a nullary Func<Element> is handing back something it did not construct - and fails if that stops matching the generator's list. That guard earned its keep on first run by flagging a fourth candidate, ForEach. It is not a pass-through: it takes Func<T, Element> and builds new GroupElement(...) from the projected results, so the ForEach( line really is the creator. My first predicate matched any Func yielding an Element, which would have silently dropped every ForEach from the source map. Narrowed to nullary producers, with ForEach pinned as an explicit negative control. Three documentation claims contradicted the implementation. The ReactorApp setter comment and the ReactorSourceMap XML docs both described flipping NeedsTag and tagging every control - the design this PR explicitly avoided in order to keep PR #468's per-leaf allocation win. The architecture diagram still showed the feature as "Designed" with [CallerFilePath], Element.Source and a separate attached DP; corrected at the pipeline source and regenerated. Verified: spike 31/31 (3 new), unit 13655 with 0 failed (3 new), DocPipeline 435/435, SourceMap selftests 25/25, Release solution build clean apart from the three vs-reactor projects that cannot restore without nuget.org. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
Fourteenth Copilot review on #1147. NuGet only flows build\ to a DIRECT PackageReference, so an app that picks Reactor up through an intermediate library got the compile assets and the DSL but never the targets - no generator, no REACTOR_SOURCEMAP, every CallSite silently null. Worse than a build error, because the feature simply appears not to work with nothing to point at. The targets and the generator DLL now pack to buildTransitive\ as well. Since a direct consumer could evaluate both copies, the file carries an idempotence guard so a second import does not append the <Analyzer> item and the InterceptorsNamespaces entry twice. Verified against the real package rather than by inspection - it now contains build/Microsoft.UI.Reactor.targets, build/sourcemap/..., buildTransitive/Microsoft.UI.Reactor.targets and buildTransitive/sourcemap/... . The sample also overstated the PR #468 argument for the second time. The Borders calling .Background(Theme.*) carry ThemeBindings, so they have a non-null extras bucket and NeedsTag tags them with or without source mapping. Only the callback-free TextBlocks and stacks demonstrate the untagged-leaf gap. Corrected in the README and the class summary, naming the Borders explicitly so the distinction is not lost again. Verified: sample builds, SourceMap selftests 28/28, DocPipeline 435/435, Release solution build clean apart from the three vs-reactor projects that cannot restore without nuget.org. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Spike (spec 010 Route B): source mapping via Roslyn interceptors
Competing spike against the CallerInfo route. Proves that C# interceptors
(stable in C# 14 / .NET 10) can stamp Element.CallSite at every DSL call
site without changing a single factory signature -- including the 39
`params Element?[] children` factories that [CallerLineNumber] structurally
cannot reach.
Core:
- SourceLocation readonly record struct (FilePath, LineNumber).
- Element.CallSite slot. NOT #if DEBUG -- the library ships Release, so
the API is always present and only the cost is gated. Named CallSite,
not Source as spec 010 proposes: five element records already declare
an incompatible positional Source member (CS8866/CS0108) and
ElementExtensions declares a Source extension method.
- Diagnostics.ReactorSourceMap: Enabled flag (mirrors the devtools
session switch, also seedable via REACTOR_SOURCEMAP=1) plus the read
path UIElement -> ReactorState -> Element.CallSite.
- Reconciler.NeedsTag gains a trailing Enabled arm so leaf controls
become readable while source mapping is on. Measured at 0 bytes when
off, so PR #468's leaf-tagging win is preserved.
Generator: src/Reactor.SourceMap.Generator, an IIncrementalGenerator that
runs in the CONSUMER's compilation and emits same-signature interceptors
via SemanticModel.GetInterceptableLocation. Emits nothing unless the
consumer sets ReactorSourceMap=true, because emitting an interceptor into
a project that has not opted into InterceptorsNamespaces is CS9137, a hard
build error rather than a no-op. Packed into analyzers/dotnet/cs and
paired with the InterceptorsNamespaces line in Reactor.targets so the two
can never drift apart.
Tests: tests/Reactor.SourceMap.Spike (runtime coverage + allocation
measurement, generator enabled for real), SourceMapElementSlotTests
(provider-independent slot contract, headless), and three selftest
fixtures for the live-control read path with a flag-off negative control.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Match Roslyn's PathMap separator normalization in the interceptor generator
Under a deterministic build (Directory.Build.props turns on
DeterministicSourcePaths when CI=true) the compiler rewrites
[CallerFilePath] through the PathMap AND normalizes the remaining
separators to the replacement's style. A generator-emitted string literal
gets no such treatment, so naive prefix substitution produced
'/_/tests\Foo\Bar.cs' where CallerInfo produces '/_/tests/Foo/Bar.cs' --
the two source-map providers would have disagreed on the path string.
Adds InterceptorPath_MatchesWhatCallerFilePathWouldProduce, which asserts
the emitted literal against a live [CallerFilePath] captured on the same
line, so the two routes are pinned to each other rather than to a
hard-coded expectation. Verified failing before the fix and passing after,
in both CI=true and local-path builds.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Bucket Element.CallSite into ElementExtras; eliminate the flag-off cost
Adopted from the Route A spike, which found that the +24 B/op flag-off
regression was a storage decision, not a slot decision. CallSite now lives
in the spec 047 §4.4 ElementExtras bucket alongside Attached and
ThemeBindings, reached through a public shim on Element identical in shape
to its 14 siblings.
Measured on M12 (x64 Release, 1000 iterations, 5 reps, Reactor variant):
flag-off is now byte-identical to the main baseline REP FOR REP --
1103848 / 1185872 / 1104112 / 1103848 / 1103848 on both trees, reproducing
the baseline's own bimodal outliers. Was +24.0 B/op inline; now +0.00.
The stamp itself got MORE expensive, not less: the element clone shrank
from 184 B to 160 B (the 24 B slot leaving, exactly), but a stamped element
now also allocates the 152 B extras bucket, so TextBlock stamping goes
184 -> 312 B/call. That is the right trade: flag-off is paid by every
retail app forever, flag-on only during a debugging session.
Two consequences of bucketing, both verified rather than assumed:
- A stamped element has non-null Extensions, which ALREADY satisfies
Reconciler.NeedsTag. The source-map arm added there is therefore
redundant for any element a provider stamped, and now earns its keep
only for unstamped ones (generic factories, third-party factories,
direct `new XElement(...)`). The existing flag-off negative control
caught this by failing; the fixture set was rewritten to assert the
new invariants across all four quadrants of stamped x flag.
- ElementFactory's keyed-memo and component-compare fast paths gate on
`Extensions is null`, so stamped elements decline them while the flag
is on. Flag-off behaviour is unchanged.
Public API cost is +1 line, not zero: ElementExtras.CallSite is public for
consistency with all 14 sibling extras, so the index records CallSite on
both Element and ElementExtras.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Interceptors DO cover generic factories; remove the exclusion
Answers the last binary unknown for Route B. Generic factories are NOT a
wall: an interceptor can restate type parameters and constraints, and all
six probed shapes bind correctly -- including Component<T, TProps>, whose
`where T : Component<TProps>, new()` is an inter-parameter constraint and
was the crux risk.
The one real defect was mine, not the language's. GetSymbolInfo on a
generic call returns the CONSTRUCTED method, whose Parameters carry
SUBSTITUTED types. Rendering those while also declaring <T, TProps>
produced an interceptor mixing an open signature with closed parameter
types -- which fails to bind, and leaks the caller's type arguments into
the interceptor signature (observed as CS0122 when one was a private
nested type). Signatures now come from method.OriginalDefinition; only the
call site comes from the constructed symbol.
Roslyn does NOT require exact constraint equality on the interceptor.
Probed by deliberately omitting `new()`: the result was CS0310 on the
forwarding call inside the interceptor BODY, not a signature-mismatch
diagnostic. So constraint rendering only has to be strong enough to
satisfy the forward, and any shortfall is a loud, local, compile-time
error rather than a silent non-application.
Verified at scale: Reactor.AppTests.Host builds clean with generics on,
emitting 267 generic interceptors across 10 distinct generic factories
(5,247 sites total, up from 4,976). ReactorGallery emits 116 generic of
1,660 total.
Tests are three-way discriminating -- applied-and-correct vs
applied-and-wrong vs never-applied -- with line numbers anchored to an
independent [CallerLineNumber] probe on the same physical line, and a
positive control proving the generator emitted for the same file so that a
null is provably "did not apply" rather than "test could not tell".
Also adds the same opt-in measurement harness to ReactorGallery that
AppTests.Host carries. Both are inert unless -p:ReactorSourceMap=true.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Source mapping follows the build configuration, like XamlDebuggingInformation
Replaces the bespoke two-property opt-in with the platform's own pattern,
and fixes two virtualization regressions the PR review found.
OPT-IN. ReactorSourceMap now defaults to true in Debug and is absent in
Release, mirroring WPF's XamlDebuggingInformation (true in Debug, false in
Release; VisualDiagnostics.GetXamlSourceInfo returns null without it) and
WinUI 3's requirement of a Debug configuration for Live Visual Tree. The
app author sets nothing: Debug builds carry the capability, Release builds
generate nothing and bake no source paths into shipped binaries. Verified
by evaluating the property in both configurations rather than assuming
$(Configuration) is available that early -- it is, so the in-repo and
PackageReference paths now behave identically and the previous asymmetry
(where only PackageReference consumers got the one-property experience) is
gone.
Cost of the Debug default, measured on samples/ReactorGallery (9,272
lines, 1,660 intercepted call sites): +0.99s incremental, +2.18s clean.
Scales at roughly 0.5-0.6 ms per call site.
TWO FAST-PATH REGRESSIONS (review H4/H5, upgraded from medium on
cross-check). Bucketing CallSite into ElementExtras made a stamped
element's Extensions non-null, which silently disqualified it from two
gates that tested `Extensions is null`: the virtualized keyed-memo cache
(ElementFactory.cs:231) and safe component adoption (:757). Those gates
exist to exclude BEHAVIOR that resolution or adoption would drop or
mis-key; a source location installs no runtime bookkeeping. They now test
Element.HasBehavioralExtras, which ignores a CallSite-only bucket. Left
unfixed this would have altered virtualization behavior in exactly the
builds a developer is profiling.
NEEDSTAG ARM REMOVED (review M6). A stamped element already satisfies
NeedsTag via its non-null Extensions bucket, so the arm only ever tagged
UNSTAMPED elements -- which by definition have no location to read back --
while re-introducing the per-leaf ReactorState allocation PR #468 removed.
Deleting it makes M12 byte-identical to the main baseline with the flag
ON as well as off (was +168 B/op); the only remaining runtime cost is the
`with` clone at genuinely stamped call sites.
Also from the review: the new generator DLL is added to the official
signing list (H2 -- it would otherwise have shipped unsigned inside the
nupkg), the spike suite is wired into PR CI (H1 -- it is the only gate
proving the generator emits code that binds), and the source-mapping guide
template no longer describes the feature as unimplemented (H3). Adds the
ReactorSourceMap build property and CS9137 to the reactor-build-and-check
agent-kit skill (M2), a real default-value assertion (M10), and coverage
for the NormalizeExtras collapse contract (M5).
Selftest fixtures were rewritten to exercise the REAL interceptor chain
now that AppTests.Host builds with the generator on, rather than
hand-stamped stand-ins: they assert the actual file and line of their own
call sites against an independent [CallerLineNumber] oracle, with a
distinct-lines fixture guarding against a present-but-constant stamp.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Add source-map-explorer sample for hands-on testing
An interactive app for exercising spec 010 per-element source mapping
without reading a test log.
"Scan visual tree" walks the realized WinUI tree and prints every control
with its file:line. Verified end to end: 14 of 14 controls mapped, and
each reported line matches the factory call in App.cs exactly, including
the VStack/HStack entries -- the params factories CallerInfo structurally
cannot reach.
The "Source mapping" toggle flips ReactorSourceMap.Enabled live and
remounts the panel via a key bump, so the scan goes 14/14 -> 0/14 -> 14/14.
The remount is deliberate: without it the toggle reads as "8 of 14",
because the flag only governs NEW stamps and an unchanged TextBlock takes
the reconciler's shallow-skip path, keeping the ReactorState it mounted
with. That is correct behaviour -- the element really did come from that
line -- but it obscures what the gate does, so the sample forces the
issue rather than leaving a confusing number on screen.
Nothing in the inspected panel carries a callback, key, or reference
modifier, so every leaf is one the reconciler deliberately does not tag
(NeedsTag / PR #468). They are addressable only because of the stamp.
The csproj sets no source-map property at all -- the Debug default does
it. Confirmed the Release build generates no interceptors and bakes no
source paths.
Click-to-inspect is wired through a hit-test on the panel root (so the
leaves stay callback-free) but is UNVERIFIED: this session cannot inject
pointer input, which was confirmed by a coordinate click on a plain Button
also doing nothing. The scan and toggle paths were driven through UI
automation and do work.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Share one inspection path between click and a mouse-free button
The pointer handler could not be verified: this environment blocks input
injection (a coordinate click on a plain Button does nothing, and the
synthetic pen path is refused outright), so the click-to-inspect route was
committed untested.
Extracts the hit-test into InspectAtPoint and adds an "Inspect deepest
leaf" button that drives it without a mouse: walk to the deepest mapped
leaf, compute that control's own centre in host coordinates, hit-test that
point, and compare the result against what the walk reported. The
comparison is the assertion -- a wrong hit-test prints DISAGREES rather
than a plausible-looking location.
Verified through UI automation: TextBlock App.cs:188, hit-test at its own
centre (102,261) resolves to the same TextBlock and the same line, AGREES.
App.cs:188 is TextBlock("Wireless keyboard"). That leaves only WinUI's
PointerPressed delivery unverified, which is event plumbing rather than
source-map code.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Fix three CI failures
1. Selftests: the Debug default never fired in CI. Reactor.targets is
imported by the repo's Directory.Build.props at the TOP of a project,
where $(Configuration) has not been defaulted yet, so it is EMPTY for
any build that does not pass -c explicitly -- which is exactly what CI
does. Every local run passed -c Debug, which masked it. The condition
now treats empty as Debug, matching MSBuild's own default; a real
Release build passes Configuration as a global property, so it is set
by that point and still correctly declines. Verified all three shapes:
no -c => true, -c Debug => true, -c Release => empty.
2. Unit tests: Reactor.SourceMap.Spike reported "Zero tests ran" (exit 5)
because CI passes the hangdump option to every xUnit suite and the
project did not reference Microsoft.Testing.Extensions.HangDump, so MTP
rejected the unknown option. Reproduced locally with the exact CI
command, then bisected to that single flag. Adds the package, as
Reactor.Tests already does.
3. Docs build: merges origin/main, which added InlineSnippetLedgerTests --
a gate that did not exist at this branch's merge-base, so the failure
was only ever visible in CI's merge result. It requires hand-typed C#
in the guides to be snippet-backed or ledgered, on the grounds that a
plain csharp fence compiles for nobody and has shipped real API
defects. Rather than ledger an exemption, the usage example now
extracts from a compiled snippet region in the source-map-explorer
sample, so CI type-checks the documented API.
Full sweep after the merge: unit 13652, selftests 1557, doc pipeline 435
(including the new gate), spike 19 under CI's exact flags. Release
solution build matches the main baseline.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Skip source-map assertions on a build that has no interceptors
Fixes the AOT Selftests job, which publishes Release. The fixtures asserted
on interceptor-stamped locations unconditionally, so on a build with no
interceptors compiled in they failed 7 checks rather than reporting that
they could not run.
The gate is a BUILD fact, not a runtime probe. Reactor.targets now defines
REACTOR_SOURCEMAP alongside InterceptorsNamespaces, and the fixtures key
their #if on that constant. Skipping on "GetSource returned null" instead
would have been the classic comforting negative: a generator that silently
stopped emitting would skip green forever, and the suite would establish
nothing. Keying on the constant means a Debug build always asserts hard --
which is what PR CI runs -- and only a build that genuinely cannot answer
the question skips. Each fixture still asserts an observable precondition
(the control mounted) before skipping, per the harness guidance, so a
broken harness stays red.
Verified both directions rather than assuming: Debug asserts all 16 checks
with zero skips; Release skips exactly the 7 generator-dependent ones while
the 9 configuration-independent checks still run and pass.
The constant is also useful to consumers, who can guard inspector UI that
would otherwise show empty locations.
Also resolves three code-quality comments about foreach loops that
implicitly filter -- InspectAtPoint, the interceptor emit loop, and the
PathMap prefix scan now filter explicitly with .Where(). Behaviour is
unchanged in all three: same order, same first match, same result when
nothing matches.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
* Address Copilot review: stamp theft, stale tags, and generator load cost
Five findings from the review on #1147, each with a test that reddens without
the fix.
Pass-through factories were stealing the stamp. When/If/Expr return their
then() argument verbatim, so the interceptor at the outer call site overwrote
the location the inner factory had already recorded, and a conditional subtree
reported the line of the conditional rather than the line of the element. The
emitted interceptor now keeps the first stamp it finds.
Two ways a tag could go stale once mapping is on. A shallow skip kept the old
element on a branch switch, so the reported line stayed on the branch that had
been replaced; CallSiteChangedOnSkip declines the skip for that case only,
following the #721 gesture/drag precedent. Adoption dropped the tag entirely,
so an adopted control reported nothing; both successful adoption paths now
refresh it.
The generator no longer loads in every consumer compilation. Anything under
analyzers/dotnet/cs is loaded unconditionally, and this generator's syntax
provider classifies every invocation semantically, so gating only its emit
still paid the whole discovery pass. It now packs to build/sourcemap and
Reactor.targets adds it as an Analyzer item only when ReactorSourceMap is true.
Verified against the real package: the DLL is at build/sourcemap/ and absent
from analyzers/dotnet/cs/, where the other three generators remain.
REACTOR_SOURCEMAP now means what it says. It was defined from shared targets,
including for projects that never reference the generator, which would make
guarded inspector code read an unavailable provider as a broken one. It is now
defined only in the same conditional block that adds the analyzer, and by the
handful of in-repo projects that wire the generator by ProjectReference.
Confirmed both directions: defined for AppTests.Host, the explorer sample, the
gallery and the spike; absent for Reactor.TestApp and minesweeper.
Verified: spike 22/22 under CI flags, unit 13652 with 0 failed, DocPipeline
435/435, selftests green, Release solution build clean apart from the three
vs-reactor projects that cannot restore without nuget.org. Public API remains
additive only, with both reactor.api.txt copies in sync.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Scope the wrapper-factory gap, and correct the packaging comments
Second Copilot review on #1147. Five findings were stale comments I left
behind when the generator moved out of analyzers/dotnet/cs; the sixth was
real.
Wrapper factories are genuinely unmapped, and cannot be fixed here.
[GenerateReactorWrapper] emits its factory as a static on the element type
(FooWrapperElement.Foo(...)), not on Factories, so the containing-type filter
never sees it. I tried widening the filter to accept any Element-derived owner
and measured both outcomes: it covered those calls in the WinUI app project
(which compiles twice, so the second pass sees the first pass's generated
files) and covered nothing in the single-pass spike. The cause is
architectural, not a rendering bug - Roslyn runs every source generator
against the same input compilation, so this generator cannot see symbols
another generator emitted. Coverage that silently varies with project shape is
worse than a uniform documented gap, so the filter stays narrow and the gap is
now pinned by WrapperFactoryInterceptionTests and documented in the guide.
That test asserts the absence with a positive control on the same file, so a
null reads as "this shape is not intercepted" rather than "the generator never
ran" - and it fails loudly if a real integration path ever lands, forcing the
docs to be updated with it. Writing it caught two things worth noting: the
first version failed its own positive control because ReactorSourceMap.Enabled
is process-global and the class had not joined the SourceMap collection.
Emit no longer hardcodes the Factories qualifier. Signature carries the
declaring type, so the forwarding call names the real owner instead of an
assumption that has to stay in sync with the filter.
The signing inventory comment is corrected too, but signing itself was never
broken: files_to_sign globs the project bin\ dir, not the package path.
Verified: spike 25/25 (3 new), unit 13652 with 0 failed, DocPipeline 435/435,
SourceMap selftests 21/21, Release solution build clean apart from the three
vs-reactor projects that cannot restore without nuget.org. No public API
change.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Honour #line, isolate the global flag, and drop the sample's remount
Third Copilot review on #1147.
#line directives were ignored. GetLineSpan reports the physical position in a
generated .cs, while [CallerLineNumber] and [CallerFilePath] both follow the
directive - so any DSL call in T4/Razor/codegen output reported a line nobody
edits, breaking the CallerInfo parity this route claims. Now reads the mapped
span.
The path half had a trap the first fix walked straight into. A directive names
its file relatively (#line 5000 "virtual-source.cs") and CallerInfo reports it
RESOLVED against the physical file's directory, so emitting the mapped span's
bare Path yields "virtual-source.cs" where the other route yields an absolute
path - same file, different string, and consumers compare strings. I only
caught it because the test asserts against a live [CallerFilePath] probe rather
than a hand-written expectation; my first reading of the failure was wrong and
concluded the parity was asymmetric. Reading the whole value rather than the
first differing character showed it was relative-vs-resolved.
LineDirectiveParityTests pins both halves plus a no-directive positive control;
mutation-checked, both redden on revert.
The source-map flag is no longer raced. ReactorSourceMap.Enabled and
ReactorApp.DevtoolsEnabled are one flag in two guises - the setter mirrors it
and ResetDevtoolsEnabledForTests writes it directly - so DevtoolsUseAndMenuTests
could clear it between another class's set and assert while both ran in the
parallel pool. Both now share a SourceMapGlobals collection.
ReactorFeaturesTests already had exclusivity through ConsoleTests.
The explorer sample's generation-key remount is gone. It predated
CallSiteChangedOnSkip and is now redundant: with the flag off the new element's
CallSite is null while the mounted one's is not, so the skip is declined and the
tag refreshes in place. Verified rather than assumed - the new
SourceMapReadPath_FlagOffClears selftest asserts the count clears without a
remount, and fails when CallSiteChangedOnSkip is neutered.
Also: the guide template still described the analyzers/dotnet/cs layout this PR
moved away from, the spike's csproj comment claimed the wrapper test proves
positive coverage when it pins a limitation, and the generator's own summary
still named the rejected Element.Source API.
Verified: spike 28/28 (3 new), unit 13652 with 0 failed, DocPipeline 435/435,
SourceMap selftests 25/25, Release solution build clean apart from the three
vs-reactor projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Never stamp pass-through factories, and resync the stale design docs
Fourth Copilot review on #1147.
Pass-throughs are no longer intercepted at all. When/If/Expr return the
caller's element verbatim, and the first-stamp-wins guard only defers when that
element already has a location. An element built while mapping was off (or
served from a memo cache) has none, so the wrapper would write its own line and
report itself as the creator of something built elsewhere - a confident wrong
answer, which is worse than no answer. TryDescribe now declines them outright;
the guard stays as defence for a factory returning a cached element it did not
build on this call.
The name list has a drift guard rather than a comment asking people to be
careful. PassThroughFactoryDriftTests derives the pass-through set structurally
- a factory returning the BASE Element that takes a nullary Func<Element> is
handing back something it did not construct - and fails if that stops matching
the generator's list.
That guard earned its keep on first run by flagging a fourth candidate, ForEach.
It is not a pass-through: it takes Func<T, Element> and builds
new GroupElement(...) from the projected results, so the ForEach( line really is
the creator. My first predicate matched any Func yielding an Element, which
would have silently dropped every ForEach from the source map. Narrowed to
nullary producers, with ForEach pinned as an explicit negative control.
Three documentation claims contradicted the implementation. The ReactorApp
setter comment and the ReactorSourceMap XML docs both described flipping
NeedsTag and tagging every control - the design this PR explicitly avoided in
order to keep PR #468's per-leaf allocation win. The architecture diagram still
showed the feature as "Designed" with [CallerFilePath], Element.Source and a
separate attached DP; corrected at the pipeline source and regenerated.
Verified: spike 31/31 (3 new), unit 13655 with 0 failed (3 new), DocPipeline
435/435, SourceMap selftests 25/25, Release solution build clean apart from the
three vs-reactor projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Match Roslyn's PathMap casing, and make the env contract testable
Fifth Copilot review on #1147. The summary said "no new comments", but the
suppressed section carried five findings and two were real bugs, so this
addresses those rather than the summary line.
PathMap matching was case-insensitive; Roslyn's is not. Roslyn's
PathUtilities.NormalizePathPrefix - which backs SourceFileResolver and therefore
[CallerFilePath] - uses StringComparison.Ordinal, and says so in its own comment:
"we expect the client to use consistent capitalization; we use ordinal
(case-sensitive) comparisons". With a differently-cased PathMap key this
generator rewrote a path the compiler left alone, so the two providers reported
different strings for the same file. Verified against the Roslyn source rather
than inferred.
PathMapParityTests covers it directly. The existing end-to-end parity test only
exercises whatever map the current build sets, which is exactly-cased, so it
could never reach this. Reactor.Tests now references the generator as a plain
ProjectReference (not an Analyzer - running it here would rewrite this suite's
own call sites) and calls ApplyPathMap. Seven cases: casing, both separator
normalization directions, first-match-wins, and identity. Mutation-checked -
restoring OrdinalIgnoreCase reddens exactly the casing case.
Enabled_DefaultsToFalse asserted a mutable process-global that its own supported
opt-in sets. Running the suite with REACTOR_SOURCEMAP=1 is documented, and
correctly initializes the flag to true, so the test failed under the very
scenario it was meant to describe. The contract is now a testable parser,
IsEnabledByEnvironment, asserted directly. Confirmed with a positive control
rather than by reasoning: the old assertion really does fail with the variable
set and pass without it, which also proves the variable reaches the test host.
Three more ReactorSourceMap doc claims still described the rejected design -
that Enabled is read on the mount hot path via Reconciler.NeedsTag. The real
read site is the generated interceptor, at element creation. GetSource's null
conditions were also wrong: they coupled null to control tagging, when a control
can be tagged for unrelated reasons and still report no location, and a
hand-stamped element reports one with the flag off.
Verified: unit 13663 with 0 failed (8 new), spike 31/31, DocPipeline 435/435,
SourceMap selftests 25/25, Release solution build clean apart from the three
vs-reactor projects that cannot restore without nuget.org. No public API change.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Cover the package delivery path, and correct four wrong mechanism claims
Sixth Copilot review on #1147.
The package path had no test. Every binding test loads the generator through a
ProjectReference, which is not how a consumer receives it - a consumer gets it
from build/sourcemap inside the nupkg, added as an Analyzer by the packaged
targets. That wiring is guarded by Exists(...), so a packing or path regression
does not fail, it silently disables mapping while every ProjectReference test
stays green. SourceMapPackageConsumerTests builds a real PackageReference
consumer against the local feed and asserts a DSL call is stamped with the right
line in Debug and unstamped in Release. Both directions in one pair, since a
Debug-only check passes if the generator is unconditionally on and vice versa.
It needs network access to restore the Windows App SDK, so it cannot pass on
this machine. Verified that is environmental rather than a defect in the test:
the pre-existing CreateTemplateTests fails identically with NU1301 here, and CI
runs this suite with network access.
I described CallSiteChangedOnSkip backwards. It does not decline the shallow
skip - it is evaluated inside the skip arm and refreshes the back-pointer
without a full update (ChildReconciler.cs:237-241). The selftest comment and the
sample README both claimed the opposite, which would mislead anyone maintaining
that fast path. The XML doc on the method itself was already correct.
Element.CallSite's docs claimed tagging is keyed on the runtime flag. It is not:
NeedsTag keys off the non-null Extensions bucket, so a hand-assigned CallSite is
tagged even with the flag off - which HandStampedLeafIsTaggedWithFlagOff already
asserts, so the docs contradicted a passing test.
The guide said Release generation is impossible while the next paragraph
documented the override that enables it. The generator is gated on
ReactorSourceMap alone, not Configuration, so a Release consumer opting in does
generate interceptors and embed mapped source paths. Now described as defaults
with an explicit warning. The agent-kit skill also claimed locations only
populate under devtools, which would tell embedded-inspector and benchmark users
their supported opt-ins cannot work; it now covers direct assignment and the
REACTOR_SOURCEMAP seed.
Verified: unit 13663 with 0 failed, spike 31/31, DocPipeline 435/435, SourceMap
selftests 25/25, Release solution build clean apart from the three vs-reactor
projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Serialize the packaging tests, and stop tying CallSite's contract to the flag
Fixes the Integration Tests break my previous commit caused, plus nine review
threads.
Two packaging test classes cannot pack concurrently. Adding a second class that
uses TemplatePackageTestFixture gave each its own instance via IClassFixture, so
both ran `dotnet pack src/Reactor` at once and hit the XAML/SignaturesGen race
AGENTS.md documents: "The process cannot access the file ... input.json". They
now share one ICollectionFixture with DisableParallelization, which also drops
the ~2-minute pack from twice to once. Verified by sampling the fixture's temp
directory during a run: exactly one instance ever exists, where the racing
arrangement had two.
The other CI failure, Merged coverage, is not from this branch. It is the
Issue487 scroll fixture, which is timing-sensitive and fails under coverage
instrumentation; the plain Selftests job passed on the same commit, the fixture
has zero references to anything here, and an interleaved A/B against main
earlier in this branch showed main failing it identically.
Element.CallSite's summary tied nullability to the live runtime flag. It is a
property of the element, fixed at construction: a stamped element stays non-null
after the flag is turned off, a hand-assigned value is honoured with the flag
off, and an element the provider never reached stays null forever. The flag
governs whether the interceptor stamps, nothing more.
The guide's status banner still said source mapping is "absent from Release"
two sections above the override that enables it there. Now "off by default in
Release", with the path-embedding warning inline, since that is the
safety-sensitive claim someone skims.
Code-quality findings on the new test: Path.Combine silently drops earlier
arguments when a later one is rooted, so those calls are now Path.Join, and the
cleanup catch names IOException/UnauthorizedAccessException rather than
swallowing everything.
Verified: unit 13663 with 0 failed, DocPipeline 435/435, integration tests build
and run (they still need network for the Windows App SDK restore, same as their
pre-existing sibling).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Test the devtools activation path and the adoption tag refresh
Seventh Copilot review on #1147. Two findings were untested behaviour that a
deletion would have left entirely green, which is the standard that matters.
The devtools mirror had no test. Every source-map test set
ReactorSourceMap.Enabled directly, while the path users actually take is
--devtools app/run, which reaches it through the ReactorApp.DevtoolsEnabled
setter. Deleting that assignment left the whole source-map suite passing while
devtools produced no stamps. Three tests now cover enable, disable, and the
reset helper, which writes the backing field directly and so bypasses the
mirroring setter. Mutation-checked: all three redden when the assignment is
removed, and the four pre-existing devtools tests stay green.
The adoption tag refresh had no test either. Added an ElementFactory selftest
that drives the RefreshRealizedItems adoption path with two component rows on
different source lines and asserts the still-realized control reports the
replacement's location. Mutation-checked: removing the refresh reddens it.
Writing it corrected an assumption. I expected the initially realized row to
report its own call site; it reports nothing, because first realize goes through
the framework's realize channel and tags the wrapper with its own element rather
than the stamped Component<> one. The fixture now asserts that explicitly rather
than quietly expecting otherwise, so a future change there is visible.
The second adoption site is still uncovered, and I would rather say so than
imply the finding is fully closed. Removing it alone leaves all 104 EFR_ checks
green - verified, not assumed. Reaching its success branch needs a decorator
that both substitutes a control and is safely adoptable; the existing suite only
exercises the refused form, where Flyout state does not live in the component
subtree. See the thread reply for detail.
Three build-file comments claimed a Release consumer "never loads" the
generator. The targets key on ReactorSourceMap alone, so an explicit true does
load it in Release and does embed source paths - the same defaults-not-a-lock
correction already made in the guide.
Verified: unit 13666 with 0 failed, EFR_ selftests 104/104, SourceMap selftests
25/25, DocPipeline 435/435, Release solution build clean apart from the three
vs-reactor projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Make composition wrappers resolvable through GetSource
Eighth Copilot review on #1147, and a genuine functional gap rather than a
documentation one.
Component<T>(), RenderEachTime, Memo and ErrorBoundary each mount a Border
wrapper, and none of them tagged it. So an intercepted Component<T>() call had a
perfectly good Element.CallSite that GetSource could never reach - the read path
silently excluded the DSL call a devtools inspector most wants to resolve, while
every existing test passed because they all read leaf controls.
All four mount paths now tag their wrapper, and both update paths refresh it.
The update half matters for the same reason CallSiteChangedOnSkip does: the
wrapper survives a re-render, so without a refresh it would keep naming the
previous render's element. Tagging is free when unstamped - NeedsTag is false
for a callback-free, key-free, extras-free element, so no ReactorState is
allocated and the flag-off path is unchanged.
The reviewer spotted this from a symptom I had already observed and
misattributed. My adoption fixture recorded that the initially realized row
reported no location; I wrote that off as "the realize channel tags the wrapper
with its own element" and pinned it as expected behaviour. It was actually this
bug, one layer down.
That characterization assertion then failed once the mounts were fixed, which is
exactly what it was there for - a fixture noticing its own premise had gone
stale. It now asserts the initial realize reports the arm that built it, which
makes the whole fixture a stronger oracle: before is arm A, after adoption is
arm B.
Also added a live-control regression test that walks from a rendered leaf up to
its component wrapper and asserts the reported line, mutation-checked by
removing the MountComponent tag.
Verified: unit 13666 with 0 failed, full selftest suite 1560 passed / 0 failed,
DocPipeline 435/435, Release solution build clean apart from the three
vs-reactor projects that cannot restore without nuget.org. No public API change.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Measure and document the extras-bucket tax instead of claiming zero cost
Ninth Copilot review on #1147. The first finding is the one that matters: my
zero-runtime-cost claim was measured on a benchmark that structurally cannot
observe the cost it was denying.
CallSite is a nullable struct, so it is stored inline in ElementExtras and
widens that bucket for everyone. Measured rather than reasoned about: the bucket
is 152 B/instance, and Unsafe.SizeOf<SourceLocation?> is 24 B of that. Every
element carrying a behavioral extra - attached properties, theme bindings,
animations, resource overrides, context values - allocates that bucket anyway
and pays the 24 bytes whether or not source mapping is enabled, and whether or
not the consumer has the generator at all.
M12 cannot see it because M12's leaves are extras-free and allocate no bucket,
so "byte-identical flag-off" was true and narrow at the same time. That is the
uncomfortable kind of wrong: a real measurement answering a different question
than the claim it was supporting.
The cost is accepted, not removed. It is bounded, proportional to elements that
already allocate this object, and the alternative measured worse: declaring
CallSite inline on the record cost +24 B on EVERY element in every build.
ElementExtrasAllocationTests now pins both halves - the 24 B field width, the
152 B bucket starting from a non-null behavioral bucket, and the fact that an
unstamped leaf still allocates no bucket at all, so the trade-off cannot be
quietly inverted later. The guide and the field's own docs state the tax
explicitly.
Two sample comments also overstated things. The panel root has a ref and a
pointer handler and the toolbar buttons have callbacks, so they are tagged
regardless - the untagged-leaf argument applies only to the descendants Walk
traverses. And turning the flag off does not stop tagging: a tagged control
keeps its ReactorState and reconciliation refreshes it to point at the newly
built element, which is unstamped, so the location reads back null.
Verified: unit 13722 with 0 failed, DocPipeline 435/435, sample builds.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Correct the sample README transcript, which had drifted from App.cs
Tenth Copilot review on #1147. The captured scan output still cited App.cs
lines 126-132, which now contain unrelated method code - so a reader following
the instructions would see the feature appear broken when it was working.
Updated to the current call sites and verified each one against the source
rather than re-deriving them by eye, which is how they drifted in the first
place: 181 VStack, 183/186/187 TextBlock, 184 Border, 185 VStack. The
inspect-deepest-leaf example moved from 188 (a .Spacing call) to 187.
Also added a line saying the numbers are a capture from one run and move
whenever App.cs is edited. That is the feature working rather than the
transcript rotting, and it tells the next reader to compare the shape instead of
the digits - the numbers have now drifted twice in this PR alone.
Verified: DocPipeline 435/435.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Refresh the wrapper tag on hot-reload migration too
Eleventh Copilot review on #1147, and the finding lands squarely on this route's
headline claim.
TryHotReloadMigrateComponent calls ReconcileComponent directly, so it never
inherited the refresh added to UpdateComponent. The wrapper is deliberately
PRESERVED across a migration - that is the point of migrating - so its
back-pointer kept naming the pre-edit element. A Component<T>() call site that
moved during a hot-reload edit therefore reported its old line.
That is precisely the staleness this PR argues interceptors avoid and CallerInfo
does not. Having it in the one path where line numbers actually move would have
undercut the comparison the whole spike exists to make, in the scenario a
developer is most likely to hit.
Extended the existing migration fixture rather than adding a parallel one, since
it already sets up the migration: it now captures both call sites, asserts the
reported location follows the migrated element, and asserts it is not the stale
one. Mutation-checked - removing the refresh reddens exactly those two while the
"the two sites really differ" guard stays green, so the assertion cannot pass by
coincidence.
Verified: unit 13722 with 0 failed, full selftests 1564 passed with only the
known Issue487 scroll flake (zero references to anything here, and shown earlier
in this branch to fail identically on main), Release solution build clean apart
from the three vs-reactor projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Stop cloning the EmptyElement singleton
Twelfth Copilot review on #1147. A pure-cost bug: the interceptor stamped
Empty(), which returns the shared EmptyElement.Instance.
The `with` clone broke the singleton's reference identity and materialized a
152-byte extras bucket on every conditional-empty render - and bought nothing,
because Mount filters EmptyElement out before it becomes a control
(Reconciler.Mount.cs:121), so the location could never be read back. Verified
both halves rather than taking them on faith: Empty() is
`public static Element Empty() => EmptyElement.Instance` over a
`static readonly` field, and Mount has an explicit `EmptyElement => null` arm.
It lands on hot paths too: any conditional-empty render, plus factories like
DevtoolsMenu that yield the sentinel when switched off.
The emitted interceptor now returns an EmptyElement unchanged. Three tests, with
the identity and allocation halves asserted separately because either could hold
while the other broke, plus a positive control proving the guard is specific to
EmptyElement rather than a blanket stop-stamping. Mutation-checked: removing the
guard reddens exactly the two Empty tests and leaves the control green.
Verified: spike 34/34, unit 13722 with 0 failed, SourceMap selftests 28/28,
EFR_ 104/104, HotReload 19/19.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Emit the EmptyElement guard only where it can compile
Fixes the Build solution / Pack break my previous commit caused.
The guard was emitted for every interceptor, including factories that return a
concrete record. For those the compiler proves `__e is EmptyElement` is always
false and reports CS0184 - harmless in Debug, a build error in Release where
TreatWarningsAsErrors is on. It now emits only when the declared return type is
the base Element or EmptyElement itself, which is exactly where an EmptyElement
can actually turn up.
This is the trap AGENTS.md warns about, and I walked into it by skipping the one
gate that catches it: I verified the previous commit with Debug tests only. A
green Debug build does not clear the Build solution job. Re-verified here with
`dotnet build Reactor.slnx -c Release` (CS0184 gone) and an ARM64 Release build
of the spike, since ARM64 was the configuration CI reported.
The guard itself still works: spike 34/34, including the two Empty tests that
redden when it is removed.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Compare the drift guard against the generator's real set
Thirteenth Copilot review on #1147. The guard I added last round was weaker than
it looked.
PassThroughFactoryDriftTests compared the discovered pass-through set against a
hand-copied array in the test, so it guarded the DSL surface but not the thing it
was named for: edit PassThroughFactories in the generator and the test kept
comparing against its own unchanged copy and stayed green, while interception
coverage silently drifted.
PassThroughFactories is now internal and the test reads it directly, through the
InternalsVisibleTo("Reactor.Tests") added earlier for ApplyPathMap. Confirmed the
difference rather than assuming it: dropping "Expr" from the generator's set now
fails with `discovered: [Expr, If, When]` vs `generator: [If, When]`, where
before that edit produced a green run.
Worth noting this is the second time a duplicated constant in this PR turned out
to be the weak link - the same shape as the byte-identical claim measured on a
benchmark that could not see the case it was denying. A test that restates
production state tests only itself.
Verified: unit 13722 with 0 failed, Release solution build clean apart from the
three vs-reactor projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Flow the source-map targets to transitive consumers
Fourteenth Copilot review on #1147.
NuGet only flows build\ to a DIRECT PackageReference, so an app that picks
Reactor up through an intermediate library got the compile assets and the DSL but
never the targets - no generator, no REACTOR_SOURCEMAP, every CallSite silently
null. Worse than a build error, because the feature simply appears not to work
with nothing to point at.
The targets and the generator DLL now pack to buildTransitive\ as well. Since a
direct consumer could evaluate both copies, the file carries an idempotence guard
so a second import does not append the <Analyzer> item and the
InterceptorsNamespaces entry twice. Verified against the real package rather than
by inspection - it now contains build/Microsoft.UI.Reactor.targets,
build/sourcemap/..., buildTransitive/Microsoft.UI.Reactor.targets and
buildTransitive/sourcemap/... .
The sample also overstated the PR #468 argument for the second time. The Borders
calling .Background(Theme.*) carry ThemeBindings, so they have a non-null extras
bucket and NeedsTag tags them with or without source mapping. Only the
callback-free TextBlocks and stacks demonstrate the untagged-leaf gap. Corrected
in the README and the class summary, naming the Borders explicitly so the
distinction is not lost again.
Verified: sample builds, SourceMap selftests 28/28, DocPipeline 435/435, Release
solution build clean apart from the three vs-reactor projects that cannot restore
without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Fix CallSite doc type names and pin the non-Factories entry-point gap
Co-authored-by: azchohfi <527713+azchohfi@users.noreply.github.com>
* Prove the transitive package path end to end
Fifteenth Copilot review on #1147. I had deferred this test last round and
argued the package-level verification was enough; the reviewer pushed back, and
they are right about why it matters.
The targets guard the analyzer with Exists(...), so a wrong or missing
buildTransitive path does not fail a downstream build - it silently yields null
locations everywhere. That is precisely the failure the direct-consumer test
cannot see, which makes "I checked the package layout" the wrong standard here.
TransitiveConsumerAlsoGetsStampedCallSites now builds an intermediate library
that references Reactor directly, packs it to the same local feed, and then
builds a downstream app that references ONLY that library - so Reactor arrives
transitively and build/ never applies. Asserts the stamped line in Debug and null
in Release, the same both-directions shape as the direct test.
Like its siblings it needs network access for the Windows App SDK restore, so it
cannot pass on this machine. Confirmed it fails at the intermediate library's
restore with NU1301 - the same boundary the existing packaging tests hit - rather
than earlier for some other reason, which is as much as can be established here.
CI's Integration Tests job runs it with network.
Verified: integration tests compile, Release solution build clean apart from the
three vs-reactor projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Resolve decorator targets so GetSource names the real creator
Sixteenth Copilot review on #1147. A genuine misattribution, and the same class
of bug as the pass-through stamp theft fixed earlier.
Flyout/MenuFlyout/CommandBarFlyout mount their Target's control and then
deliberately replace that control's tag with themselves, because their
Opened/Closed handlers read it back. That is load-bearing and cannot simply be
removed. But the realized control is still the target's: a Button inside a
Flyout(...) was created by the Button( line, so GetSource was reporting the
Flyout( line as its creator.
GetSource now walks through target-wrapping decorators to the innermost target.
A loop rather than a single hop, so nested decorators resolve correctly.
The resolver names the three types explicitly, and a hand-maintained list drifts
- which matters more than usual here because a fourth decorator would not crash
or return null, it would report a confidently wrong line. DecoratorTargetDriftTests
therefore derives the set structurally (first positional parameter is an Element
named Target) and asks the real resolver about each one, rather than comparing
against a copy. Mutation-checked: dropping CommandBarFlyoutElement from the
switch fails with that type named in the message.
Also added the live Flyout(Button(...)) fixture the review asked for, with a
lines-differ guard so it cannot pass by coincidence. Mutation-checked: removing
the walk reddens both location assertions and leaves the guard green.
Verified: unit 13725 with 0 failed, full selftests 1565 passed with only the
known Issue487 scroll flake, Release solution build clean apart from the three
vs-reactor projects that cannot restore without nuget.org, and no public API
signature change.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Unwrap decorators in the skip predicate, and label the test honestly
Seventeenth Copilot review on #1147, a follow-on from the decorator resolution I
added last round.
CallSiteChangedOnSkip compared only the outer element, so a stable Flyout( whose
Target switches between otherwise-equal elements built on different lines has an
unchanged CallSite of its own. It now compares the EFFECTIVE call site - the one
GetSource reports - unwrapping target-wrapping decorators, and only pays that
unwrap when a side actually is a decorator so the flag-off path is unchanged.
The accompanying fixture is labelled a characterization, not a regression guard,
because that is what it is. Mutation-checking it showed it passes with and
without the unwrap: this shape never reaches the skip arm, something upstream
routes the decorator through a full update which re-tags via the decorator
adapter. I could not construct a shape that does reach it.
I kept the fix anyway rather than reverting: ShallowEquals returns true for
(FlyoutElement, FlyoutElement) regardless of Target, so the skip is reachable in
principle, and the unwrap is cheap and obviously correct. But the fixture's
summary now says plainly that it does not isolate the predicate, so nobody later
reads it as proof that it does. What it does prove - a decorated target reports
the live branch rather than the retired one - is worth keeping on its own.
Verified: SourceMap selftests 38/38, unit 13725 with 0 failed, Release solution
build clean apart from the three vs-reactor projects that cannot restore without
nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Forward build/ to a single buildTransitive/ body
Eighteenth Copilot review on #1147. The reviewer found that my idempotence guard
covered only the source-map blocks, leaving CompilerVisibleProperty and three
None groups to duplicate on a second import.
Probing that turned up something worse than the reported bug: the guard did not
work at all. MSBuild evaluates every PropertyGroup in a file before any ItemGroup,
so the sentinel set by the "second" import was already visible when the FIRST
import's items were evaluated - a two-copy probe produced CVP=[] , i.e. the
wiring suppressed entirely rather than merely de-duplicated. Extending the same
guard to the remaining groups would have made that worse, not better.
So there is now one body, not two copies. build\Microsoft.UI.Reactor.targets is a
forwarder that imports buildTransitive\Microsoft.UI.Reactor.targets, which holds
everything; the generator DLL ships once, under buildTransitive\sourcemap, since
the body's Exists() probe and <Analyzer Include> resolve relative to its own
folder. An <Import Condition> IS evaluated in file order, unlike a group
condition, so the sentinel works there.
Verified all three shapes rather than reasoning about NuGet's selection rule:
build\ alone, buildTransitive\ alone, and both imported together each yield
exactly one CompilerVisibleProperty. Package layout confirmed from the real
nupkg: build/Microsoft.UI.Reactor.targets,
buildTransitive/Microsoft.UI.Reactor.targets,
buildTransitive/sourcemap/Reactor.SourceMap.Generator.dll.
Verified: SourceMap selftests 38/38, Release solution build clean apart from the
three vs-reactor projects that cannot restore without nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Test the documented overrides, and fix the package path in the guide
Nineteenth Copilot review on #1147.
The guide still said the generator ships under build/sourcemap. My own forwarder
change moved it to buildTransitive/sourcemap the round before, so the consumer
guide was pointing at a path that no longer exists in the package.
The package tests also only covered the Release default-off branch. The
documented override is what actually matters for safety - an explicit
<ReactorSourceMap>true</ReactorSourceMap> in Release is what embeds mapped source
paths into a shipped binary - and if it silently stopped loading the packaged
analyzer the guide would be promising something that no longer happens while
every default-path test stayed green.
ExplicitOverridesWinOverTheConfigurationDefault covers both directions against a
real PackageReference consumer: Release plus explicit true must stamp the call
site, Debug plus explicit false must not. Both, because a single direction would
pass for a property that is read but ignored.
Like its siblings it needs network for the Windows App SDK restore, so CI's
Integration Tests job is where it runs.
Verified: integration tests compile, DocPipeline 435/435, Release solution build
clean apart from the three vs-reactor projects that cannot restore without
nuget.org.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Point every sourcemap reference at buildTransitive
Twentieth Copilot review on #1147. The forwarder change moved the generator to
buildTransitive/sourcemap and I updated only the packing line, leaving stale
build/sourcemap references in the generator project, the targets file, the host,
gallery and sample projects, the package-consumer test, the signing inventory,
and the PR description.
All now point at the real location. The PR description also carried two claims
that had gone stale in a way worth correcting rather than quietly editing:
- It said the package layout was verified but not an end-to-end restore by a
real PackageReference consumer. That caveat is obsolete - there are now three
package-consumer tests (direct, transitive, and both documented overrides) and
they pass in CI's Integration Tests job.
- "Flag-off is byte-identical to baseline" now carries the measured caveat that
M12 structurally cannot see: CallSite widens the shared ElementExtras bucket by
24 bytes for any element that already carries a behavioral extra.
Verified: guard scan clean on every edited build file, the pipeline YAML still
parses, ReactorSourceMap still resolves for a wired project, and the integration
tests compile.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Remove trailing whitespace from source map reference sweep
Co-authored-by: azchohfi <527713+azchohfi@users.noreply.github.com>
* Rename Reactor.SourceMap.Spike to Reactor.SourceMap.Tests
The name was a leftover. This started as a competitive spike - Route B
(interceptors) against Route A (CallerInfo) - to answer one question: can
interceptors reach the 40 params Element?[] factories that [CallerFilePath]
structurally cannot? Route A was disqualified and this hardened into a shipping
feature, but the project kept the exploratory name.
It had become actively misleading. "Spike" reads as throwaway, and this is the
only suite that compiles with interception enabled, which makes it the gate
proving the generator emits code that actually binds - the most load-bearing test
project in the change, named as if it were scratch work. Renamed to match the
Reactor.Tests / Reactor.SelfTests / Reactor.DocPipeline.Tests family.
Also retired the vestigial wording it left elsewhere: "the Route B spike
consumer", "the generic spike", "the end-to-end check in the spike", and the
SpikeBorderWrapperElement fixture type. Where a comment framed something as an
open question the spike would answer, it now states the answer - Roslyn does
accept restated type parameters and constraints, proven by
GenericFactoryInterceptorTests.
Git recorded all seven files as renames, so history survives.
Verified: Reactor.SourceMap.Tests 37/37 under the new name, unit 13725 with 0
failed, Release solution build clean apart from the three vs-reactor projects
that cannot restore without nuget.org, ci.yml still parses and points at the new
path, and the slnx entry resolves.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Remove stray trailing blank line from ci.yml and Reactor.slnx
7f3f500b was titled "Remove trailing whitespace" but added a trailing
blank line to these two files while removing them elsewhere. ci.yml was
left as the only one of 16 .github/workflows/*.yml files ending in a
blank line; .editorconfig governs both under [*] (the only
insert_final_newline exemptions are [*.{ps1,psm1,psd1}] and
[**/node_modules/**]).
Verified both still parse after the change: ci.yml loads as YAML with 15
jobs, Reactor.slnx loads as XML with 123 projects and its
Reactor.SourceMap.Tests path still resolves.
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Keep CallSite out of synthesized record equality
Element.CallSite is bucketed in ElementExtras, and a record synthesizes
Equals/GetHashCode over every instance field, so two otherwise identical
elements stamped on different lines compared unequal and hashed
differently. Spec 010 requires source metadata to be inert, and with
source mapping on in a Debug run an Assert.Equal over elements would
start failing purely because the two were built on different lines.
The reconciler was never affected (it uses ShallowEquals/CanSkipUpdate,
already pinned), and with the flag off CallSite is null everywhere and
NormalizeExtras collapses the bucket, so this only ever manifested with
source mapping active.
Fixed at the storage level with an EqualityIgnored<T> wrapper whose
Equals is unconditionally true and GetHashCode unconditionally zero,
rather than hand-writing Equals/GetHashCode on ElementExtras: that record
has 15 fields and a hand-written pair would silently stop comparing any
field added to it later.
Verified: the 3 new RecordEquality_* tests fail before the fix and pass
after, and re-fail when the wrapper is mutated back to real equality
(controls stay green throughout). Two controls included --
PositiveControl pins that equality still detects real differences, and
AttachedControl pins that independently-built .Grid() elements are
already unequal via reference-equality Attached, so a future reader
cannot "fix" the shared-base test into a false regression report.
Reactor.Tests 13730/0, Reactor.SourceMap.Tests 37/37, Release solution
build 0 warnings (only the 3 known vs-reactor NU1301 network failures).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3663
* Fix doc-comment attachment, docs table, and pin LangVersion compatibility
Three review findings:
1. Inserting EqualityIgnored<T> put its <summary> directly after the
pre-existing ElementExtras <summary>, so both attached to the internal
wrapper and the public record shipped with only a <remarks>. Moved the
struct above that summary. Verified against the real artifact: the
generated Reactor.xml now carries the "Cross-cutting extras bucket"
text on T:Microsoft.UI.Reactor.Core.ElementExtras.
2. The diagnostics table said the read path was Debug-only, contradicting
the same guide's documented <ReactorSourceMap>true</ReactorSourceMap>
Release opt-in. Reworded to "when source mapping is enabled at build
time" and regenerated; only that line changed in the compiled guide.
3. The LangVersion concern does not reproduce -- measured rather than
reasoned. Interceptors are gated by the InterceptorsNamespaces opt-in
the targets already supply, NOT by LangVersion: the real generator
emits 62 InterceptsLocation attributes into Reactor.SourceMap.Tests
and that project compiles and passes 37/37 under LangVersion 13, and
still builds under LangVersion 12 (verified after deleting the
generated file and forcing -t:Rebuild, so the result is not a stale
artifact). Added the requested consumer regression test anyway, in
Debug so it covers the default-on upgrade path: it pins the property
so a future Roslyn adding a language-version gate surfaces in CI as a
consumer-breaking change instead of on user upgrade.
Reactor.Tests 13730/0, Release solution build 0 warnings (only the 3
known vs-reactor NU1301 network failures).
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: b028599c-cd90-4f42-9578-dfa1b11a3…
What
Gate
V1HandlerAdapter'sReactorStateattached-DP write onElement.HasCallbacks, restoring the legacy reconciler's allocation discipline for callback-free leaves (TextBlock / Border / StackPanel / Image — the bulk of any real tree).Why
Spec-047 §4.5 collapsed all built-in controls onto the V1 dispatch adapter. The adapter tagged every mounted control with a
ReactorState(one allocation + one attached-DP write per mount), where the legacy hand-coded reconciler had only tagged callback-bearing elements (seeChildReconciler.cs:91andReconciler.Update.cs:83). That regressed the bytes-per-render of the most common element in any real tree — a callback-free display leaf — by +21.6%.Routed-input modifiers (
.OnPointerPressedetc.) dispatch throughModifierEventHandlerState.Current*slots refreshed each render byApplyEventHandlersand do not resolve via the tag, so they are intentionally outside the gate. Implicit composition animations registered byApplyPropertyAnimationcontinue to fire on direct visual writes, so.Animate()on callback-free leaves still works without a tag.Change
New
Reconciler.SetElementTagIfNeeded(FrameworkElement, Element)helper:Elementon an existingReactorState(callback-bearing controls, pooled reuse, echo/setter scope) — no alloc.V1HandlerAdapter.Mount/Updatenow callSetElementTagIfNeededinstead ofSetElementTag. The publicReconciler.SetElementTagAPI is unchanged.Perf results
5000 iterations on the same dev box that captured the pre-V1 baseline (bytes/render =
allocBytes ÷ 5000):Read-out
ElementExtrasbucketing genuinely shrank the element once the tagging tax is removed.Validation
Selftest suite (982 fixtures): 1 pre-existing flake (
GridViewLazy_RealizedCount=252_LessThanHalf) on both baseline and this branch — no new failures introduced.Targeted fixtures pass:
Trampoline_*— event dispatch / handler rebind after rerenderEventStateSplit_*—ModifierEventHandlerStateallocation discipline (verifies state IS allocated for callback-bearing controls)EchoSuppress_*— value-controlled echo round-tripsModifier_*— routed-input handlersSelection_*— selection eventsPool_*(incl.ExtProof_Pool_TagSet) — pool rent/return tag contract (uses publicSetElementTagAPI, unchanged)ValueChange_*,TextBox_*— text/value callbacksRisk
Low. The gate exactly mirrors the legacy reconciler's
HasCallbacksdiscipline (ChildReconciler.cs:91,Reconciler.Update.cs:83), which has shipped for the entire history of the codebase. The set of code paths that readReactorState.Elementfor callback-free controls is empty: routed-input dispatches viaCurrent*slots, implicit animations fire on visual writes, andGetListState/GetItemViewSource/ChangeEchoSuppressorare only installed on controls whose elements have callbacks.Co-authored-by: Copilot 223556219+Copilot@users.noreply.github.com