Skip to content

Prototype opt-in scroll-region progress renderer to keep console output intact - #12606

Draft
Amaury Levé (Evangelink) wants to merge 2 commits into
mainfrom
dev/amauryleve/mtp-console-output
Draft

Amaury Levé (Evangelink) wants to merge 2 commits into
mainfrom
dev/amauryleve/mtp-console-output

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: e39480d0feb78f4ef960b88e67c32bdbb34bc99e

Dimension Assessment Rationale
Change confidence 6/10 ↑ 558/558 targeted unit tests and 16/16 terminal-reporter contract tests (net10.0, net11.0) pass at this revision.
↑ Mutations M1–M6 each turn the new tests red at this revision.
↑ Real conhost run: 0 of 106 user lines lost with the scroll region vs 27 lost with classic progress.
↓ No live run yet on Windows Terminal, VS Code, macOS or a Linux tty.
↓ xterm.js drops a pending wrap across a frame (known limitation).
↓ Small behavior change in the default renderer (no redraw after teardown erase).
↓ CI has not run on this head yet.
Diagnosis confidence 9/10 ↑ Reproduced #4425 with TUnit 0.6.43 on MTP 1.4.3: 2 of 5 user lines visible with progress, 5 of 5 with --no-progress.
↑ Cause traced to the cursor-up erase and redraw of the progress frame landing on lines written directly to the console.
Evidence fit 8/10 ↑ The reproduction shows the reported overwritten and missing lines.
↓ The reporters' exact terminals and test frameworks are not confirmed.

Pull request

Summary

Important

Draft prototype, not ready to merge. The feature is opt-in (MTP_PROGRESS_SCROLL_REGION=1). This PR stays in draft until every item in the Before marking ready for review checklist below is checked.

Relates to #4425 (intentionally does not close it).

Problem. In an interactive ANSI terminal, the Microsoft.Testing.Platform progress renderer erases and redraws its frame by moving the cursor up. Test code that writes directly to Console.Out, Console.Error or native stdout bypasses MTP, so the next redraw lands on those lines and overwrites or erases them. --no-progress avoids it, at the cost of live progress.

Change (Microsoft.Testing.Platform, opt-in). When MTP_PROGRESS_SCROLL_REGION is set to an on value (1, true, on, enable; trimmed, case-insensitive) and the cursor-based progress renderer is in use:

  • Progress rows are reserved at the bottom of the window with a DECSTBM scroll region (CSI 1;n r). All other output, including direct console writes from tests, scrolls above it, so progress never moves the cursor over user output.
  • Each frame is drawn as save cursor, disable origin mode, draw, restore cursor, in a single write through the new internal IConsole.WriteAtomically.
  • There is no Console.Out interception and no lock on the console write path.
  • The rows are released (CSI r, then clear) on normal teardown and from AppDomain.ProcessExit. The exit handler takes no lock: it waits up to 250 ms for a batch being written by another thread, then claims the written state with Interlocked.Exchange, so exactly one writer releases it.

Without the environment variable the classic renderer is used, with the one change below.

Note

Default-mode change (review finding F2). TestProgressStateAwareTerminal no longer redraws progress after teardown has erased it, and the teardown erase now runs under the existing _lock. This also applies to the default renderer: before, a write after teardown could redraw a stale progress frame.

Before marking ready for review

  • Live end-to-end runs on Windows Terminal, conhost, the VS Code terminal (xterm.js), macOS Terminal and a Linux tty, covering: concurrent console writes, Ctrl+C once and twice, resize during a run, the shell prompt after exit, --output detailed, multiple test assemblies, and hot reload. Assert terminal cells, not only captured bytes.
  • Decide whether the xterm.js pending-wrap overwrite (see Demonstration) is acceptable.
  • Handle or bound Unix partial writes in WriteAtomically.
  • Add an acceptance test asserting that the final output resets the region (CSI r).
  • Decide between the environment variable and a --progress value; if an option is added, update the --help/--info acceptance expectations.
  • Port IConsole.WriteAtomically to the vendored terminal-reporter copy in dotnet/sdk (its IConsole implementations, such as CapturingConsole, must implement it).
  • Gather feedback from the Testing Platform overwriting/removing user console output #4425 reporters.
  • Decide whether the scroll region becomes the default.
  • Fix or explicitly defer the remaining minor review findings: per-frame allocations, InternalAPI entry ordering, and the init accessor on the internal options type.
  • Green CI on the final head.
  • Add this PR's link to the changelog entry in docs/Changelog-Platform.md.
  • Refresh the agent assessment for the final head.

Known residual risks (detailed in the decision record):

  • SIGKILL or a crash leaves the margins set until the terminal is reset.
  • A timed-out exit wait can leave one stale frame.
  • There is a single DECSC slot, so user code that saves and restores the cursor, positions it absolutely, or uses the alternate screen can be disturbed.
  • Terminals without DECSTBM support are not detected.
  • Many active workers are truncated to the reserved rows.
  • A resize between measuring and writing can draw one frame at stale coordinates.
  • On .NET Framework, ProcessExit handlers share about 2 s in total.

Files changed:

  • Core: AnsiTerminal.cs, AnsiCodes.cs, AnsiTerminalTestProgressFrame.Render.cs, CursorProgressRenderer.cs, TestProgressStateAwareTerminal.cs, TerminalTestReporter.cs, TerminalTestReporterOptions.cs, ProgressReportingConfiguration.cs, TerminalOutputDevice.Initialization.cs, IConsole.cs and SystemConsole.cs, plus InternalAPI.Unshipped.txt.
  • Tests: TerminalTestReporterTests.cs and the new ProgressReportingConfigurationTests.cs. Three test IConsole fakes gain WriteAtomically.
  • Docs: the decision record, the glossary, and the changelog.

Design and decision record

Decision record: docs/decisions/scroll-region-progress.md. It covers the contract, the producer-consumer boundary with dotnet/sdk, the experiments, the review history and the open questions.

Alternatives considered:

  • --no-progress or non-ANSI output. This is the existing workaround, but it loses live progress.
  • A lock around MTP's console writes. Rejected: test code writes straight to Console.Out or native handles and never takes that lock.
  • Replacing Console.Out early with an MTP-owned writer that coordinates with the renderer. A probe kept all 5 of 5 lines, and a multi-model review converged on a design. It was rejected for two reasons. First, it must serialize arbitrary user writes against the renderer, which carries a high deadlock risk from writes in finalizers, in ProcessExit, or under user locks. Second, it still misses native and handle-level writes.
  • Scroll region (chosen). The terminal separates progress from output, with no interception and no lock on the write path. It is opt-in to limit exposure while the terminal matrix is validated.

Demonstration

No screenshots or GIFs were captured; the results below are from reading the real terminal buffer back.

Original repro (#4425): TUnit 0.6.43 on MTP 1.4.3, 5 user lines written during the run. With progress on, 2 of 5 were visible; with --no-progress, all 5 were.

conhost (Windows). A probe test host runs 3 workers that write lines directly to Console.Out while progress renders, then writes 45 lines after the run. It used the repository-built Microsoft.Testing.Platform.dll (hash-checked against artifacts) in a fresh conhost.exe. The screen buffer was read back with ReadConsoleOutputCharacterW.

Mode Expected lines Missing Progress residue rows
Classic progress 106 27 3
MTP_PROGRESS_SCROLL_REGION=1 106 0 0
Scroll region with Environment.Exit(7) mid-run 106 0 0

Linux pty. A WSL Debian pty (120x30, TERM=xterm-256color) was recorded and replayed through @xterm/headless 5.5.0. Classic mode lost 28 lines and the scroll region lost 0. This ran before the last review fixes and has not been re-run since.

Known xterm.js limitation (pending wrap). On a 10x6 @xterm/headless 5.5.0 terminal with region 1;4, the sequence is: write AAAAAAAAAA (exactly fills the row, leaving a pending wrap), draw a progress frame, then write B. The row ends as AAAAAAAAAB instead of wrapping. This happens because xterm.js clears the pending-wrap flag on cursor restore, while conhost preserves it. It only affects output that ends exactly at the right margin with no newline when a frame is drawn in between. It cannot be fixed without interception, and is an undraft decision item.

Not yet inspected: Windows Terminal, the VS Code terminal (live), macOS Terminal, a Linux tty, resize, Ctrl+C, --output detailed, multiple assemblies, and hot reload.

Validation and regression proof

All runs used source state e39480d0feb78f4ef960b88e67c32bdbb34bc99e, Debug, Windows, with the repository-local SDK.

Command Result
dotnet build src\MTP\Microsoft.Testing.Platform\Microsoft.Testing.Platform.csproj -c Debug --no-restore (all TFMs) exit 0, 0 warnings, 0 errors
dotnet run --project test\UnitTests\Microsoft.Testing.Platform.UnitTests -f net10.0 --no-build -- --filter "FullyQualifiedName~ProgressReportingConfigurationTests|FullyQualifiedName~Terminal" exit 0; total 558, failed 0, succeeded 558, skipped 0
dotnet run --project test\UnitTests\Microsoft.Testing.Platform.TerminalReporterContract.UnitTests -f net10.0 --no-build exit 0; total 16, failed 0, succeeded 16
dotnet run --project test\UnitTests\Microsoft.Testing.Platform.TerminalReporterContract.UnitTests -f net11.0 --no-build exit 0; total 16, failed 0, succeeded 16
npx --yes markdownlint-cli2 docs/decisions/scroll-region-progress.md docs/glossary.md docs/Changelog-Platform.md 0 errors

Requirement-to-test map:

  • Region reserve, frame, and release sequences; atomic batch writes; resize and small windows; process-exit release. Covered by the AnsiTerminal_ScrollRegion_* unit tests in TerminalTestReporterTests.cs.
  • No progress redraw after teardown, in both modes. Covered by the TestProgressStateAwareTerminal_ScrollRegion_* tests.
  • Environment variable parsing. Covered by ProgressReportingConfigurationTests.
  • Rendered terminal surface. Checked manually on conhost only (see Demonstration). No automated acceptance test asserts terminal cells or the final CSI r yet; that is an undraft item.

Not run: acceptance or integration tests (no -pack), live runs on non-conhost terminals, macOS, Linux CI, and the dotnet/sdk vendored build.

Test-value evidence

These are executed mutation checks at e39480d0feb78f4ef960b88e67c32bdbb34bc99e. For each mutation, the production change was replaced in place, then the harness:

  1. ran dotnet build test\UnitTests\Microsoft.Testing.Platform.UnitTests\Microsoft.Testing.Platform.UnitTests.csproj -c Debug --no-restore -f net10.0 (exit 0 in every case);
  2. ran dotnet run --project test\UnitTests\Microsoft.Testing.Platform.UnitTests -f net10.0 --no-build -- --filter "FullyQualifiedName~ScrollRegion|FullyQualifiedName~TestProgressStateAwareTerminal|FullyQualifiedName~ProgressReportingConfigurationTests";
  3. restored the original bytes.

git status was clean afterward. Every red result below is an assertion failure, not a build or launch failure.

Mutation (counterfactual) Exit Total / failed / succeeded Failing tests
M0: none (baseline) 0 40 / 0 / 40 none
M1: exit handler does nothing 2 40 / 4 / 36 AnsiTerminal_ScrollRegion_ProcessExitReleasesPinnedRowsAtomically, ..._FrameThatReservesRowsWhileProcessExitsReleasesThemAgain, ..._ProcessExitWaitsForBatchOfAnotherThread, ..._ProcessExitReleasesRowsWhoseReleaseIsNotWritten
M2: a batch finished during exit does not release again 2 40 / 1 / 39 AnsiTerminal_ScrollRegion_FrameThatReservesRowsWhileProcessExitsReleasesThemAgain
M3: remove the _progressErased teardown gate 2 40 / 1 / 39 TestProgressStateAwareTerminal_ScrollRegion_WritesAfterProgressStoppedDoNotPinProgressAgain
M4: env var accepts only 1 and true 2 40 / 3 / 37 IsScrollRegionEnabled_AcceptsOnlyOnValues cases "on", " TRUE ", "enable"
M5: exit handler does not wait for another thread's batch 2 40 / 1 / 39 AnsiTerminal_ScrollRegion_ProcessExitWaitsForBatchOfAnotherThread
M6: written state is claimed before the release is written 2 40 / 1 / 39 AnsiTerminal_ScrollRegion_ProcessExitReleasesRowsWhoseReleaseIsNotWritten

The rendered-surface benefit (27 lines lost to 0) is shown by the manual conhost run above, not by an automated test. The mutation log is local to the authoring session and not attached.

Pin interactive progress to rows reserved at the bottom of the terminal
with a DECSTBM scroll region, so output written by the code under test
scrolls above the progress instead of being overwritten by cursor-up
redraws. Opt in with TESTINGPLATFORM_PROGRESS_SCROLL_REGION=1.

No Console.Out interception and no new locks: frames are emitted as a
single atomic console write, and the lock order (reporter lock, then
Console.Out) is unchanged from the classic renderer.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- Publish pinned-row state only after the batch is written, and let the
  ProcessExit handler wait (bounded) for another thread's batch before
  claiming it, so exactly one path writes each release.
- Stop redrawing progress after teardown erased it, under the terminal lock.
- Rename the opt-in switch to MTP_PROGRESS_SCROLL_REGION and accept the
  standard on values.
- Add the decision record, glossary entry, and changelog entry.

Relates to #4425

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 24, 2026 12:29

public void Write(StringBuilder value) => _output.Append(value.ToString());

public void WriteAtomically(StringBuilder value) => _output.Append(value.ToString());
public void WriteAtomically(StringBuilder value)
{
AtomicWriteCount++;
_output.Append(value.ToString());
Comment on lines +549 to +552
catch
{
// The process is exiting, so nothing can be done when the console cannot be written to.
}
Comment on lines +587 to +590
catch
{
// The process is exiting, so nothing can be done when the console cannot be written to.
}
Comment on lines +632 to +636
catch
{
// Treat a window whose size cannot be read as a window of unknown size.
return int.MaxValue;
}
@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Nov 24, 2026
@github-actions github-actions Bot removed the state/needs-review Awaiting review from the team. label Nov 24, 2026

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.

🟡 Changes recommended

Exit cleanup can hang indefinitely on Unix when another thread holds Console.Out because the 250 ms timeout does not bound subsequent geometry and output calls.

1 open issue
What changed in this PR

Adds an opt-in Microsoft.Testing.Platform progress renderer intended to preserve direct console output, addressing #4425 while remaining a draft prototype.

Changes:

  • Reserves bottom terminal rows for progress using ANSI scroll regions and single-call output batches.
  • Adds teardown and process-exit cleanup, and prevents stale progress redraws after teardown in both rendering modes.
  • Adds configuration and lifecycle tests, plus documentation of experiments and limitations.

Test-value evidence: At e39480d0feb78f4ef960b88e67c32bdbb34bc99e, the author reports 558 passing targeted tests, 16 passing contract tests per framework, and six detected mutations. Execution artifacts were not independently verified; acceptance tests and broader live-terminal validation remain outstanding.

Confidence at a glance — 🟡 MTP terminal lifecycle

Static code and relevant .NET runtime locking behavior were inspected. No builds or tests were run during this review.

File Description
test/​UnitTests/​Microsoft.Testing.Platform.UnitTests/​Services/​CTRLPlusCCancellationTokenSourceTests.cs Updates console fake for atomic writes.
test/​UnitTests/​Microsoft.Testing.Platform.UnitTests/​OutputDevice/​Terminal/​TerminalTestReporterTests.cs Tests scroll-region rendering, resize, and cleanup.
test/​UnitTests/​Microsoft.Testing.Platform.UnitTests/​OutputDevice/​ProgressReportingConfigurationTests.cs Tests opt-in environment-variable parsing.
test/​UnitTests/​Microsoft.Testing.Platform.UnitTests/​Helpers/​SystemWrappersTests.cs Updates recording console fake.
test/​UnitTests/​Microsoft.Testing.Platform.UnitTests/​DynamicExtensions/​DynamicExtensionLoaderTests.cs Updates console fake for the new interface member.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​TerminalOutputDevice.Initialization.cs Wires configuration into reporter options.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​Terminal/​TestProgressStateAwareTerminal.cs Serializes teardown and prevents later progress redraws.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​Terminal/​TerminalTestReporterOptions.cs Adds the scroll-region option.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​Terminal/​TerminalTestReporter.cs Passes the option to terminal and renderer.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​Terminal/​CursorProgressRenderer.cs Avoids erasing pinned progress before output.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​Terminal/​AnsiTerminalTestProgressFrame.Render.cs Collects and renders pinned progress rows.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​Terminal/​AnsiTerminal.cs Manages scroll regions, batches, and exit cleanup.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​Terminal/​AnsiCodes.cs Adds cursor and scroll-region escape sequences.
src/​MTP/​Microsoft.Testing.Platform/​OutputDevice/​ProgressReportingConfiguration.cs Parses the experimental opt-in setting.
src/​MTP/​Microsoft.Testing.Platform/​InternalAPI/​InternalAPI.Unshipped.txt Records new internal API members.
src/​MTP/​Microsoft.Testing.Platform/​Helpers/​System/​SystemConsole.cs Implements best-effort single-call stream writes.
src/​MTP/​Microsoft.Testing.Platform/​Helpers/​System/​IConsole.cs Defines the atomic-write abstraction.
docs/​glossary.md Documents experimental configuration.
docs/​decisions/​scroll-region-progress.md Records design, experiments, risks, and validation gaps.
docs/​Changelog-Platform.md Announces the opt-in prototype.

Review effort: Balanced

Comment on lines +584 to +585
AppendReleaseSequence(release, rows, pinnedHeight: (int)(state >> 32), TryGetHeight());
_console.WriteAtomically(release);
@microsoft-github-policy-service microsoft-github-policy-service Bot added the state/needs-review Awaiting review from the team. label Nov 24, 2026
@github-actions github-actions Bot removed the state/needs-review Awaiting review from the team. label Nov 24, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Final test-triage resolution — Azure Pipelines build 1696954

Status: inconclusive (evidence incomplete; 1 test-artifact download failed). No issue created.

Failing leg: Windows Release, task "Test affected changes" (exit code 2).

Signature: Dispose_BlockedHandlersAndCallback_ReturnsWithinTheDocumentedBound [net462] (ServerMode.Client.Sources unit tests) failed with Assert.IsLessThan(13s, stopwatch.Elapsed). Actual elapsed time was 13.08s against a 13s bound, so it missed by about 80 ms.

Assessment (medium confidence): timing-sensitive environmental one-off.

  • The same test passed on net10.0 and net11.0 on Linux Release and on net10.0 on Windows Debug (about 10.0s each).
  • There was no retry record, so this is not a proven fail-then-pass flake.
  • The collected history has no prior occurrence, but the evidence is incomplete, so I can't claim there were none.
  • There are no crash or hang diagnostics.
  • This wall-clock assertion on a loaded agent isn't evidence of a regression from this PR.

Other failed records in the results (the PR's own-change relevance is unverified). Failures appeared in ModernUwp...Deployment, NativeTests.Outcome, PackagedWinUI...RetryTestMethod_PassesOnSecondAppContainerHost and WinUIMtpPackagedApp...RetryFailsFirstAttempt. These look like deliberate failure-fixture or retry-fixture assets, and the timeline attributes the failed job to the net462 assertion above. I did not investigate them further.

Next step: Re-run the Windows Release leg. If the net462 test fails again with a similar margin, treat the 13s bound as too tight for slower Windows/.NET Framework agents. That would be a test-hardening issue, separate from this PR.

🤖 Automated content by GitHub Copilot. Generated by the Pipeline Test Triage workflow. · copilot · auto (Claude Sonnet 5.5) · ~28 AIC · ⌖ ~1 AIC · ⊞ 11.1K

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.

2 participants