Skip to content

Fix KeyNotFoundException in TerminalTestReporter.AssemblyRunCompleted (#51608) - #54437

Merged
Evangelink merged 5 commits into
mainfrom
dev/amauryleve/fix-keynotfound-assemblyruncompleted
May 29, 2026
Merged

Evangelink merged 5 commits into
mainfrom
dev/amauryleve/fix-keynotfound-assemblyruncompleted

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Fixes #51608.

Summary

TerminalTestReporter.AssemblyRunCompleted accessed _assemblies[executionId] via the ConcurrentDictionary indexer. When the test host process exited before sending TestSessionStarted (which is what calls GetOrAddAssemblyRun), the execution id was never registered, and the indexer threw KeyNotFoundException. The real exit cause was hidden by the spurious stack trace.

Fix

Use TryGetValue and, when the execution id is unknown, fall back to HandshakeFailure(...) so the user sees actionable output (stdout/stderr/exit code) and HasHandshakeFailure becomes 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). Only AssemblyRunCompleted is called from TestApplicationHandler.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 after TestSessionStarted, 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 same TryGetValue + HandshakeFailure pattern should be applied.

Alternatives considered

  • Pre-register the execution id at handshake time instead of waiting for TestSessionStarted. Cleaner conceptually, but requires plumbing the assembly path through earlier and changes contract semantics; out of scope for a backportable fix.
  • Silently no-op on unknown id. Rejected: that's exactly the "buried" behavior the issue calls out. Surfacing as a handshake failure makes the exit cause visible.

Tests

  • TerminalTestReporterTests.AssemblyRunCompleted_WhenExecutionIdUnknown_DoesNotThrowAndReportsHandshakeFailure — new unit test that calls AssemblyRunCompleted with an unregistered id and asserts no exception + HasHandshakeFailure == true.

Co-authored-by: Copilot [email protected]

…#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]>
Copilot AI review requested due to automatic review settings May 25, 2026 21:51
@Evangelink
Evangelink requested a review from a team as a code owner May 25, 2026 21:51

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens 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 with TryGetValue in AssemblyRunCompleted and fall back to HandshakeFailure when 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

@Evangelink Evangelink left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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-level TestApplicationHandler.OnTestProcessExited regression 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 at AssemblyRunStarted time (from the TestHost handshake).

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.

@Evangelink

Copy link
Copy Markdown
Member Author

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 TestSessionStarted ... is what calls GetOrAddAssemblyRun. In the current code, GetOrAddAssemblyRun (TerminalTestReporter.cs:137) is called from AssemblyRunStarted (:110), which is invoked from TestApplicationHandler.OnHandshakeReceived only when hostType == "TestHost". The original #51608 race (handshake from controller, no TestHost handshake, then OnTestProcessExited calls AssemblyRunCompleted with an unregistered id) was already fixed in #52308 by gating on _receivedTestHostHandshake. This PR is correctly framed as defense-in-depth + the test that #52308 was missing — but the test is anchored at the wrong layer (see inline comment on the test file).

2. Fallback discards caller context. When the new defensive branch fires, HandshakeFailure is called with assemblyPath: string.Empty and targetFramework: null. The caller — TestApplicationHandler.OnTestProcessExited — has _module.TargetPath ?? _module.ProjectFullPath ?? string.Empty and _module.TargetFramework in scope, and the existing else-branch in that same method already passes them through. If this fallback is ever reachable in production (it's defensive, so presumably it should not be — but #52308 was also "not supposed to be needed"), the user will see a bare 0 tests ran line with no assembly/TFM identifier. Two options:

  • Treat it as truly unreachable and accept the bare output (current PR).
  • Pass module context through AssemblyRunCompleted so the fallback is as actionable as the existing handler-level HandshakeFailure path.

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.

Evangelink and others added 2 commits May 27, 2026 11:45
- 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]>
@Evangelink
Evangelink enabled auto-merge May 28, 2026 14:26
@Evangelink
Evangelink merged commit 622add7 into main May 29, 2026
25 checks passed
@Evangelink
Evangelink deleted the dev/amauryleve/fix-keynotfound-assemblyruncompleted branch May 29, 2026 07:59
Comment on lines +734 to +739
// 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview6 milestone May 29, 2026
pull Bot pushed a commit to pepe57/sdk that referenced this pull request Jun 2, 2026
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]>
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.

dotnet test for MTP throws hard-to-interpret KeyNotFoundException

4 participants