Repository navigation
Fix KeyNotFoundException in TerminalTestReporter.AssemblyRunCompleted (#51608) - #54437
Conversation
…#51608) When a test host process exits before TestSessionStarted runs, the execution id is never registered in the reporter's _assemblies dictionary, so the indexer access in AssemblyRunCompleted throws KeyNotFoundException and the real reason for the process exit is lost in noise. Use TryGetValue and fall back to HandshakeFailure for unknown execution ids so the user gets actionable output instead of a stack trace. Co-authored-by: Copilot <[email protected]>
There was a problem hiding this comment.
Pull request overview
This PR hardens TerminalTestReporter.AssemblyRunCompleted against an unregistered execution id so that early test-host exits no longer throw KeyNotFoundException and instead surface as a handshake failure (making the real stdout/stderr/exit code visible and causing the run to be marked failed). It also adds a regression unit test for the unknown-executionId scenario.
Changes:
- Replace
_assemblies[executionId]indexing withTryGetValueinAssemblyRunCompletedand fall back toHandshakeFailurewhen the id is missing. - Add a unit test ensuring the unknown execution id path does not throw and sets
HasHandshakeFailure.
Show a summary per file
| File | Description |
|---|---|
| src/Cli/dotnet/Commands/Test/MTP/Terminal/TerminalTestReporter.cs | Avoids KeyNotFoundException by handling unknown execution ids and reporting a handshake failure instead. |
| test/dotnet.Tests/CommandTests/Test/TerminalTestReporterTests.cs | Adds a regression test covering AssemblyRunCompleted when the execution id was never registered. |
Copilot's findings
- Files reviewed: 2/2 changed files
- Comments generated: 2
Co-authored-by: Copilot <[email protected]>
Evangelink
left a comment
There was a problem hiding this comment.
Expert reviewer — summary
| # | Dimension | Verdict |
|---|---|---|
| 13 | Test Completeness & Coverage | 🟡 1 MODERATE |
| 17 | Documentation Accuracy | 🟢 1 NIT |
✅ 19/21 dimensions clean.
- Test Completeness — added test exercises the new defensive guard inside
TerminalTestReporter, not the handler-levelTestApplicationHandler.OnTestProcessExitedregression that #52308 fixed (and that the linked issue says"still need to write a test for"). - Documentation Accuracy — in-source comment misattributes registration to
TestSessionStarted; registration actually happens atAssemblyRunStartedtime (from theTestHosthandshake).
No blocking issues. The defensive guard itself is correct: ConcurrentDictionary.TryGetValue is thread-safe, the ?? string.Empty coalescing on stdout/stderr matches HandshakeFailure's contract, and HandshakeFailure already uses Interlocked.Increment so HasHandshakeFailure is set safely. No API / cross-TFM / perf / localization / IPC / security concerns. See the separate PR comment for two non-blocking design notes.
Expert reviewer — design notes (non-blocking)Two observations that are not tied to a single diff line: 1. PR description mechanism is inaccurate. The description states that 2. Fallback discards caller context. When the new defensive branch fires,
If the handler-level regression test suggested in the inline comment is added, option 1 becomes more defensible because the handler-level routing is then guarded too. Neither point blocks the PR. |
- Reword the in-source comment in TerminalTestReporter.AssemblyRunCompleted to reflect the actual registration site (AssemblyRunStarted, via the TestHost handshake) instead of TestSessionStarted. - Add TestApplicationHandlerTests.OnTestProcessExited_WhenOnlyControllerHandshakeReceived_RoutesToHandshakeFailureWithModuleContext to cover the handler-level fix from #52308: when only a controller (non-TestHost) handshake is received and the process then exits, the handler must route to HandshakeFailure with the module TargetPath/TargetFramework preserved rather than hitting the defensive empty-path fallback in TerminalTestReporter. Co-authored-by: Copilot <[email protected]>
| // Defense in depth: AssemblyRunCompleted is normally only invoked for an executionId that | ||
| // AssemblyRunStarted already registered in _assemblies (via GetOrAddAssemblyRun, gated on the | ||
| // TestHost handshake by TestApplicationHandler). If a future regression or lifecycle race | ||
| // (e.g., _assemblies.Clear() running before this completes) hands us an unknown id, surface | ||
| // a handshake failure instead of throwing a KeyNotFoundException that buries the real exit | ||
| // cause. |
There was a problem hiding this comment.
The explanation doesn't make much sense.
There is no race involved or anything.
It's simply that we got handshake from the controller but not from the testhost.
Also this doesn't fully address the other concerns in the issue.
Follow-up to PR dotnet#54437 addressing review feedback (dotnet#54437 (review)) and remaining concerns from dotnet#51608: - Reword the misleading 'race' comment in AssemblyRunCompleted. Controller- only handshake is already routed to HandshakeFailure by TestApplicationHandler.OnTestProcessExited, so the defensive branch is unreachable in normal operation; the new comment reflects that. - Track each HandshakeFailure (assembly, tfm, exit code, stdout, stderr) in a List<T> guarded by a lock so we can re-print the details at end of run. - Fix summary-line precedence so 'Failed!' wins over 'Zero tests ran' when every assembly failed its handshake (previously the headline implied a benign empty run). - Append a 'Handshake failures:' recap section after the summary listing each failing assembly with its exit code and captured output so users do not have to scroll to find the cause. - Extract CapturingConsole into a shared test helper and add tests covering the recap, multiple-failure ordering, no-failure path, and the existing defensive AssemblyRunCompleted branch. - Add HandshakeFailuresHeader resource string (xlf files auto-generated via /t:UpdateXlf, left in state='new' for translators). Co-authored-by: Copilot <[email protected]>
Fixes #51608.
Summary
TerminalTestReporter.AssemblyRunCompletedaccessed_assemblies[executionId]via the ConcurrentDictionary indexer. When the test host process exited before sendingTestSessionStarted(which is what callsGetOrAddAssemblyRun), the execution id was never registered, and the indexer threwKeyNotFoundException. The real exit cause was hidden by the spurious stack trace.Fix
Use
TryGetValueand, when the execution id is unknown, fall back toHandshakeFailure(...)so the user sees actionable output (stdout/stderr/exit code) andHasHandshakeFailurebecomes true, which causes the run to be flagged as failed in the summary.Design notes
The reporter has four sites that index
_assemblies(TestCompleted,TestDiscovered,TestInProgress,AssemblyRunCompleted). OnlyAssemblyRunCompletedis called fromTestApplicationHandler.OnTestProcessExited, which can fire in scenarios where the in-process messages (which register the execution id) never arrived. The other three are dispatched from session/test messages which only flow afterTestSessionStarted, so they cannot reach an unknown id under the current contract. To keep this fix minimal we only harden the affected entry point; if the same race surfaces elsewhere, the sameTryGetValue + HandshakeFailurepattern should be applied.Alternatives considered
TestSessionStarted. Cleaner conceptually, but requires plumbing the assembly path through earlier and changes contract semantics; out of scope for a backportable fix.Tests
TerminalTestReporterTests.AssemblyRunCompleted_WhenExecutionIdUnknown_DoesNotThrowAndReportsHandshakeFailure— new unit test that callsAssemblyRunCompletedwith an unregistered id and asserts no exception +HasHandshakeFailure == true.Co-authored-by: Copilot [email protected]