Skip to content

test(devtools): add stress harnesses for MCP startup/shutdown lifecycle - #38

Merged
Chris Anderson (codemonkeychris) merged 1 commit into
mainfrom
test/devtools-stress-harness
Apr 19, 2026
Merged

Chris Anderson (codemonkeychris) merged 1 commit into
mainfrom
test/devtools-stress-harness

Conversation

@codemonkeychris

Copy link
Copy Markdown
Collaborator

Summary

Adds two stress runners under Reactor.AppTests.Host to help reproduce a customer-reported crash in CoreMessagingXP.dll (0xc000027b stowed WinRT exception) that surfaces while using the devtools MCP surface.

Both are gated on new CLI flags on the existing test host binary — no new project, no new build artifact.

--devtools-stress — in-process cycling

Cycles DevtoolsMcpServer Start/Dispose thousands of times inside a single WinUI process. Isolates HTTP listener bind/unbind from the surrounding WinUI lifetime.

Reactor.AppTests.Host.exe --devtools-stress --iterations 10000 --ping

Flags: --iterations N, --delay MS, --ping (GET /mcp each cycle), --bg (cycle off the UI thread), --pin-port (reuse one port to stress TIME_WAIT), --log PATH.

--devtools-stress-e2e — process-level cycling

Parent repeatedly spawns a fresh child via --stress-child --devtools run, reads the devtools-ready JSON sentinel from stdout to learn the child-allocated MCP port, runs a light MCP validation (initialize + tools/list + tools/call version), then terminates and repeats. Goes through the real ReactorApp.Run<T>(devtools: true) path — full 19-tool registration, AnnounceReady on first render, Window.Closed → mcp.Dispose chain.

Reactor.AppTests.Host.exe --devtools-stress-e2e --iterations 100
Reactor.AppTests.Host.exe --devtools-stress-e2e --iterations 200 --hard-kill

Flags: --iterations N, --ready-timeout MS, --grace-ms MS, --hard-kill (race listener teardown against TerminateProcess), --no-dump, --log PATH.

Post-mortem capture

  • Flush-per-iteration log at %TEMP% so the last persisted line is a breadcrumb after a native crash
  • Exit codes flagged as SUSPICIOUS when they match the NT status range (0xCxxxxxxx) or the CLR rethrow tag (0xE0434352); our own Kill (0xFFFFFFFF) and graceful exit (0) are excluded
  • Child stdout/stderr tail dumped on suspicious exit or MCP failure
  • COMPlus/DOTNET_DbgEnableMiniDump env vars set on each child so a faulting child drops a full-heap .dmp under %TEMP%\reactor-stress-dumps

Results on the author's box

Run Result
10k in-process with --ping clean, 0 failures, avg 29 ms/cycle
100 E2E graceful clean, all exit:0x00000000, avg 466 ms/cycle
50 E2E --hard-kill clean, all exit:0xFFFFFFFF (our Kill), avg 428 ms/cycle

Customer crash not reproduced locally — merging so the customer can run it in their environment where the fault actually fires.

Test plan

  • dotnet build tests/Reactor.AppTests.Host/Reactor.AppTests.Host.csproj clean
  • --devtools-stress --iterations 10 --ping — cycle count + port rotation verified via live window title and log
  • --devtools-stress-e2e --iterations 3 — spawn/ready/initialize/tools-list/version/graceful verified in log
  • --devtools-stress-e2e --iterations 100 — full soak, 0 suspicious exits
  • --devtools-stress-e2e --iterations 50 --hard-kill — teardown-race soak, 0 suspicious exits, 0 dumps
  • Customer runs the harness against their repro environment

…ycle

Two runners under tests/Reactor.AppTests.Host, both gated on new CLI flags:

  --devtools-stress       In-process: cycles DevtoolsMcpServer Start/Dispose
                          thousands of times inside a single WinUI process.
                          Isolates HTTP listener bind/unbind from the
                          surrounding process lifetime.

  --devtools-stress-e2e   Process-level: parent repeatedly spawns a fresh
                          child via `--stress-child --devtools run`, reads
                          the devtools-ready JSON sentinel from stdout to
                          learn the child-allocated MCP port, runs a light
                          MCP validation (initialize + tools/list +
                          tools/call version), then terminates and repeats.
                          Goes through the real ReactorApp.Run<T>(devtools:
                          true) path — full tool registration,
                          AnnounceReady on first render, Window.Closed →
                          mcp.Dispose chain. --hard-kill bypasses the
                          graceful close to race listener teardown against
                          process termination.

Captured for post-mortem:
  * flush-per-iteration log at %TEMP% so the last persisted line is a
    breadcrumb after a native crash
  * exit codes flagged as SUSPICIOUS when they match NT status range
    (0xCxxxxxxx) or the CLR rethrow tag (0xE0434352); our own Kill
    (0xFFFFFFFF) and graceful exit (0) are excluded
  * child stdout/stderr tail dumped on suspicious exit or MCP failure
  * COMPlus/DOTNET_DbgEnableMiniDump env vars set so crashing children
    drop a full-heap .dmp under %TEMP%\reactor-stress-dumps

Written to reproduce a customer-reported crash in CoreMessagingXP.dll
(0xc000027b stowed WinRT exception) while using the devtools MCP. 10k
in-process, 100 E2E graceful, and 50 E2E hard-kill runs on the
author's machine came back clean — shipping the harness so the
customer can try it in their environment where the repro actually
fires.
@codemonkeychris
Chris Anderson (codemonkeychris) merged commit 3b3656b into main Apr 19, 2026
3 checks passed
@codemonkeychris
Chris Anderson (codemonkeychris) deleted the test/devtools-stress-harness branch May 28, 2026 19:11
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Jun 26, 2026
Hot keyed list-diff path (grid steady state) allocated heavily and missed
fast-paths even when keys were unchanged. Eliminate per-diff allocations and
add the missing fast-path, preserving diff behavior exactly.

ChildReconciler.cs:
- Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit
  that the positional path has, so stable keyed rows no longer re-diff every
  tick (#30); cache children.Count once instead of re-reading the COM
  IVector.get_Size per suffix iteration (#37).
- Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto
  filling a pooled bool mask; pool tails/tailIndices/predecessors from
  ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests.
- Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two
  key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared
  and returned on every exit (#33).
- Filter: count-pass + single Element[] fill, no List+ToArray (#36).
- GetKey: cache Type.Name via ConcurrentDictionary (#38).

KeyedListDiff.cs:
- Rent newKeys from ArrayPool<string>, threading explicit newCount (rented
  array may be larger); returned clearArray:true in a finally (#2).
- Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate
  scan so the steady-state grid case never allocates/scans a dup set (#1).
- Fold the churn-bailout decision into ApplyGeneral, computed from the same
  post-prefix/suffix scratch map the general walk builds (diff-range churn ==
  full-range churn), removing the O(2n) null-marker pre-pass (#34).
- Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over
  [0,removes), cleared+returned) (#3).
- Lazy-allocate movedRows only on an actual move under an ambient (#35).
- In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10).
- HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh
  HashSet (#11); cached null-key diagnostic sample (#41).

Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count,
interleaved independent states, randomized stress vs oracle with survivor
identity, pooled doomed removes, churn with shared prefix+suffix, Scratch
reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full
Reactor.Tests suite green (9693 passed); core lib Release build is
warning-clean (AOT/trim).

Closes #653

Co-authored-by: Copilot <[email protected]>
Alexandre Zollinger Chohfi (azchohfi) added a commit that referenced this pull request Jun 27, 2026
…ff (#657)

* perf: eliminate per-diff allocations in ChildReconciler + KeyedListDiff

Hot keyed list-diff path (grid steady state) allocated heavily and missed
fast-paths even when keys were unchanged. Eliminate per-diff allocations and
add the missing fast-path, preserving diff behavior exactly.

ChildReconciler.cs:
- Keyed prefix/suffix loops now take the Element.CanSkipUpdate early-exit
  that the positional path has, so stable keyed rows no longer re-diff every
  tick (#30); cache children.Count once instead of re-reading the COM
  IVector.get_Size per suffix iteration (#37).
- Replace HashSet-returning ComputeLIS with allocation-free ComputeLISInto
  filling a pooled bool mask; pool tails/tailIndices/predecessors from
  ArrayPool (#31/#32). Keep a thin ComputeLIS(int[]) wrapper for tests.
- Pool ReconcileKeyedMiddle's working arrays (ArrayPool) and the two
  key->index maps (re-entrancy-safe ThreadStatic dict pool); buffers cleared
  and returned on every exit (#33).
- Filter: count-pass + single Element[] fill, no List+ToArray (#36).
- GetKey: cache Type.Name via ConcurrentDictionary (#38).

KeyedListDiff.cs:
- Rent newKeys from ArrayPool<string>, threading explicit newCount (rented
  array may be larger); returned clearArray:true in a finally (#2).
- Move the no-op (SequenceEqual) + empty/empty fast paths ABOVE the duplicate
  scan so the steady-state grid case never allocates/scans a dup set (#1).
- Fold the churn-bailout decision into ApplyGeneral, computed from the same
  post-prefix/suffix scratch map the general walk builds (diff-range churn ==
  full-range churn), removing the O(2n) null-marker pre-pass (#34).
- Pool the doomed ReactorRow[] (ArrayPool, descending IComparer sort over
  [0,removes), cleared+returned) (#3).
- Lazy-allocate movedRows only on an actual move under an ambient (#35).
- In-place SyncLastKeysToSource instead of LastKeys Clear()+Add (#10).
- HasDuplicates reuses state.Scratch (TryAdd) for 4+ keys instead of a fresh
  HashSet (#11); cached null-key diagnostic sample (#41).

Tests: add pooling non-corruption coverage (rented-buffer-larger-than-count,
interleaved independent states, randomized stress vs oracle with survivor
identity, pooled doomed removes, churn with shared prefix+suffix, Scratch
reuse for the dup scan) and ComputeLISInto bool-mask coverage. Full
Reactor.Tests suite green (9693 passed); core lib Release build is
warning-clean (AOT/trim).

Closes #653

Co-authored-by: Copilot <[email protected]>

* perf: address PR review on keyed-diff allocation fixes

Review follow-ups on #657 (keyed list-diff allocation work):

- ChildReconciler.ReconcileKeyedMiddle: return the pooled matched and inLis
  bool[] buffers with clearArray:false instead of true (Copilot review).
  Both are value-typed (no reference pinning) and have their used range
  fully (re)initialized before any read - matched via the Array.Clear on
  rent, inLis via ComputeLISInto leading clear - so the full-array wipe on
  return was avoidable O(rented-capacity) work on the hot path. Matches how
  the int[] newToOld already returns. Reference-typed pooled buffers
  (string[]/ReactorRow[] in KeyedListDiff) still clear.

- Tests (ChildReconcilerLisIntoTests): replace the circular oracle that
  compared ComputeLISInto against ComputeLIS (now a thin wrapper over it)
  with an independent brute-force LIS-length DP that honors the -1 unmapped
  sentinel, asserting the mask marks a valid strictly-increasing subsequence
  of maximal length.

- Tests (ChildReconcilerKeyedSkipTests, new): cover the #30 keyed
  CanSkipUpdate fast path - an identical keyed list skips every row with no
  ops and no child-control access, across repeated stable frames.

Co-authored-by: Copilot <[email protected]>

* fix: correct keyed-middle reorder identity (C1/H1) + reorder & alloc tests

The keyed-middle reconciliation in ChildReconciler patched surviving
controls by their FINAL panel index while the panel was only partially
rearranged, so on reorders a survivor was patched against the wrong
control (C1, CRITICAL): e.g. rotation [a,b,c,d]->[b,c,d,a] rendered "c"
at slot 0 and scrambled keyed identity (focus/animation/state landed on
the wrong row). A related stale keyToIndex (only the moved key was
rewritten) left shifted siblings mis-indexed after an insert/move (H1).

Fix: extract the index logic into RunKeyedMiddleCore<TSink> behind a
struct-generic IKeyedMiddleSink seam (devirtualized, AOT-clean) and
replace the left-to-right loop with the canonical right-to-left LIS walk.
Each item is positioned immediately before its already-placed right
neighbour; LIS members stay put and only out-of-LIS movers relocate
(minimal moves). Every survivor is patched at its CURRENT live position,
resolved from a pooled oldRelToPanel int[] that is mutated in lock-step
with every Insert/Move so it stays exact -- fixing C1 and H1 together.
The production RealKeyedMiddleSink drives the identical Mount/Move/
UpdateChild/Unmount/Replace + ambient enter/move behaviour as before.
oldRelToPanel replaces the second pooled key->index dict (one fewer
rented dict per call).

Tests:
- ChildReconcilerKeyedMiddleCoreTests (new): a headless SimKeyedMiddleSink
  drives the SAME RunKeyedMiddleCore over identity cells (exact production
  parity, no live-WinUI selftest wall), with a 4-invariant oracle (length,
  prefix/suffix untouched, per-slot identity+content, every patch hits its
  claimed survivor) across rotation, full reverse, scramble, block-swap,
  inserts/removes/duplicates and prefix/suffix offsets. A faithful
  pre-fix reproduction proves the rotation regression test has teeth (the
  buggy walk corrupts content[0] and mis-patches; the real core is clean).
- KeyedListDiffPoolingTests: two GC.GetAllocatedBytesForCurrentThread
  budgets guarding the #1/#2/#11 pooling -- no-op steady-state diff is
  0 B/iter and a 128-key reorder is 72 B/diff; reverting the pooling
  (a new string[128] + a 128-entry HashSet per diff) fails them.

Diff correctness preserved; pooled buffers returned on every exit.

Co-authored-by: Copilot <[email protected]>

* fix: gate keyed no-op fast path on duplicate-free state + test hardening

Address Copilot re-review of e664f9f.

KeyedListDiff: the no-op fast path runs above the duplicate scan (#1), so
an UNCHANGED list that already holds duplicate keys -- the state a prior
duplicate bailout leaves behind, since ReactorListState.Reset preserves
the dups in Source/LastKeys but collapses ByKey to first occurrences --
would match LastKeys and return Empty, silently skipping the duplicate
bailout/diagnostic and leaving the diff in an invalid duplicate state.
Gate the fast path on `state.ByKey.Count == oldCount`: true exactly for
the duplicate-free steady state (allocation-free path preserved), false
when dups were collapsed (re-takes the bailout). The check is O(1) and
short-circuits before the O(n) SequenceEqualOrdinal, so the common
unique-key path pays nothing. No-op steady-state allocation stays 0 B/iter.

Tests:
- KeyedListDiffTests: new Apply_Unchanged_Duplicate_List_Re_Bails_Instead_
  Of_NoOp_FastPath -- proves an unchanged duplicate list re-bails; verified
  to FAIL without the guard (takes the no-op path and returns Empty).
- ChildReconcilerLisIntoTests: strengthen the LIS oracle to assert selected
  indices are never the unmapped -1 sentinel (a buggy impl could swap a real
  member for a -1 and still satisfy strictly-increasing + length).
- KeyedListDiffPoolingTests: drop the unused `using System.Buffers;`
  (fully-qualify the one ArrayPool cref) flagged by the reviewer.

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
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.

1 participant