Skip to content

[tests] Report build errors and logcat evidence in test failures - #13706

Closed
simonrozsival wants to merge 5 commits into
mainfrom
simonrozsival-generic-failedbuild-flakes
Closed

simonrozsival wants to merge 5 commits into
mainfrom
simonrozsival-generic-failedbuild-flakes

Conversation

@simonrozsival

@simonrozsival simonrozsival commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Context: #4451

These are diagnostics only. They don't fix any flaky test; they make the next flake show its actual cause.

Why

Several MSBuildDeviceIntegration tests failed once in pipeline 333 PR builds (Nov 20–21) and then passed on (Auto-Retry): CoreCLRAssemblyStoreConcurrentLoads, AppWithStyleableUsageRuns, BundleToolNoAbiSplitTests.InstallAndRun, and CustomLinkDescriptionPreserve. The first attempts failed with a bare FailedBuildException (for example Build failure: UnnamedProject.csproj) during Build,Install, which carries no error text.

When the retry passes, the job skips its artifact uploads, so build.log, the binlogs, and logcat*.log are never published. RunSlicedTests also removes the failed first-attempt TRX results. Only the console log survives, so the root causes can't be recovered from CI. InstallAndRun failed four times, always on macOS-1 as the first test after the emulator started.

CustomLinkDescriptionPreserve(SdkOnly,CoreCLR) in build 1693432 failed differently. Run succeeded in 10s, then the test waited the full 90 seconds without logging All regression tests completed., failing with only Linker test app did not run successfully. The retry on the same emulator logged the marker immediately. A crash, launch failure, ANR, and hang can't be told apart without logcat. One unconfirmed suspect: the app runs HttpClientTest.Post synchronously in OnCreate, with HttpClient's default 100s timeout.

Changes

  • FailedBuildException messages from Builder now include the exit code or timeout, the build.log path, and up to 20 deduplicated MSBuild error lines (1000 chars each).
  • Clear the selected build log and process logs before each invocation, so an argument error before the file logger initializes cannot report a previous build's errors.
  • When the CustomLinkDescriptionPreserve marker is missing, the failure message includes the last 60 logcat.log lines matching XALINKERTESTS, the package name, AndroidRuntime, or F DEBUG. The 90s timeout is unchanged.

Pipeline artifact uploads are intentionally left unchanged.

Validation

Local Debug SDK on macOS arm64 (make prepare && make leeroy, succeeded).

  • ./dotnet-local.sh build tests/MSBuildDeviceIntegration/MSBuildDeviceIntegration.csproj: succeeded with 0 errors.
  • Deliberate failing build through the real Builder.BuildInternal: a probe project with <Error Code="TEST0001" … /> built using bin/Debug/dotnet/dotnet threw:
    Build failure: DeliberateFailure.proj (exit code 1)
    Build log recorded at …/bin/exception-validation/build.log
    Build errors:
      …/DeliberateFailure.proj(3,5): error TEST0001: Deliberate diagnostic validation failure
    
    build.log contains the error twice (the error plus the summary); the exception lists it once. With ThrowOnBuildFailure = false the build returned false, and the error appears in LastBuildOutput.
  • Focused device tests on a dedicated API 35 emulator (emulator-5558):
    Device=emulator-5558 ADB_TARGET='-s emulator-5558' ./dotnet-local.sh test bin/TestDebug/MSBuildDeviceIntegration/net11.0/MSBuildDeviceIntegration.dll --filter '(Name~CoreCLRAssemblyStoreConcurrentLoads)|(Name~AppWithStyleableUsageRuns&Name~NativeAOT)|(FullyQualifiedName~BundleToolNoAbiSplitTests&Name=InstallAndRun)|(Name~CustomLinkDescriptionPreserve&Name~SdkOnly)'
    
    Passed 7, Skipped 1 (InstallAndRun NativeAOT is [Ignore]d), Failed 0, 6m56s.
  • The new diagnostics also showed real errors during local runs:
    • A mistyped harness argument surfaced as error MSB4177: Invalid property. The name " -p:Device" contains an invalid character " ".
    • Without Device, _DetectIfAppWasUninstalled picked another emulator, and the logcat diagnostics correctly reported No app, crash, or ANR lines found in …/logcat.log.
  • ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj -c Debug --no-restore -v minimal -m:2 -nr:false -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false: passed.
  • ./dotnet-local.sh bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter 'Name~AndroidEnableMarshalMethodsFailsBuild' --minimum-expected-tests 2 --no-ansi --progress off --output Detailed: passed 2, failed 0.
  • Before removing the temporary BuilderTests fixture, both sequential-build cases failed in each of three independent runs against the prior c9ff613a5b Builder and passed in three runs with the fix.

simonrozsival and others added 2 commits November 21, 2026 16:17
Device tests that fail once and pass in (Auto-Retry) only report
'Build failure: UnnamedProject.csproj', and CI skips uploading build.log
when the job eventually succeeds, so the underlying error is lost.

Append the build exit code or timeout, plus up to 20 deduplicated
error lines from build.log (which includes process output such as adb
stderr), to the exception message so it appears in the console log.

Co-authored-by: Copilot App <[email protected]>
…es out

CustomLinkDescriptionPreserve(SdkOnly,CoreCLR) failed once in build
1693432 with only "Linker test app did not run successfully." `Run`
completed in 10s, then the test waited the full 90 seconds without
seeing "All regression tests completed."; the passing auto-retry saw
the marker immediately. Because the job passed after the retry, CI did
not upload logcat.log, logcat-failed.log, ui.xml, or the screenshot, so
a launch failure, crash, ANR, or hung regression test (for example
HttpClientTest.Post, which has a 100s default timeout) can't be told
apart.

When the marker is missing, append the app's XALINKERTESTS lines plus
package, AndroidRuntime, and native crash lines from logcat.log to the
failure message (last 60 lines, 1000 chars each). The timeout is
unchanged.

Co-authored-by: Copilot App <[email protected]>
Copilot AI balanced review requested due to automatic review settings November 21, 2026 16:59

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

Invocation logs are reused without clearing, allowing stale errors to misidentify the failure cause and exhaust the 20-error limit before the current command-line error appears.

1 open issue
What changed in this PR

This diagnostics-only PR builds on #4451 by including build errors and relevant device logs directly in test failures, so evidence remains available when a passing retry prevents artifact uploads. It does not fix the underlying flakes.

Changes:

  • Adds exit-code or timeout details and bounded, deduplicated error excerpts to FailedBuildException.
  • Includes filtered logcat excerpts when CustomLinkDescriptionPreserve misses its completion marker.
  • Leaves the 90-second timeout, retry behavior, and artifact uploads unchanged.
File Description
tests/​MSBuildDeviceIntegration/​Tests/​InstallAndRunTests.cs Adds relevant logcat evidence to linker-test timeout failures.
src/​Xamarin.Android.Build.Tasks/​Tests/​Xamarin.ProjectTools/​Common/​Builder.cs Enriches build-failure exceptions with process status and error excerpts.

Review effort: Balanced

if (BuildLogFile != null && File.Exists (buildLogFullPath)) {
message.AppendLine ().Append ($"Build log recorded at {buildLogFullPath}");
//NOTE: enormous logs will lock up IDE's UI, so only include a bounded number of error lines.
AppendBuildErrors (message, LastBuildOutput);
`Builder.BuildInternal()` appends `process.log` into the fresh `build.log`, but `process.log` accumulated output from every build of the project, so a later failure could report errors from an earlier build. Remove `process.log` and its native-crash `.bak` copy before each build.

Add unit tests for the reported-error parser: node-prefix deduplication, `MSBUILD : error`, `fatal error`, ignored warnings, and the 20-error cap.

Co-authored-by: Copilot App <[email protected]>
simonrozsival and others added 2 commits November 22, 2026 21:35
An MSBuild command-line error can occur before the file logger initializes, leaving a previous build log to be combined with the current process output. FailedBuildException and LastBuildOutput can then report unrelated errors.

Delete the selected build log alongside the process logs at the start of each invocation. Cover both throwing and non-throwing failures with sequential builds.

Validation: ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj -c Debug --no-restore -v minimal -m:2 -nr:false -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false (passed); ./dotnet-local.sh bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter FullyQualifiedName~Xamarin.Android.Build.Tests.BuilderTests (4 passed).

Co-authored-by: Copilot App <[email protected]>
Remove the BuilderTests fixture and return AppendBuildErrors to private visibility, since the fixture was its only external caller.

Validation: ./dotnet-local.sh build src/Xamarin.Android.Build.Tasks/Tests/Xamarin.Android.Build.Tests/Xamarin.Android.Build.Tests.csproj -c Debug --no-restore -v minimal -m:2 -nr:false -p:EnableSourceLink=false -p:EnableSourceControlManagerQueries=false (passed); ./dotnet-local.sh bin/TestDebug/net11.0/Xamarin.Android.Build.Tests.dll --filter Name~AndroidEnableMarshalMethodsFailsBuild --minimum-expected-tests 2 --no-ansi --progress off --output Detailed (2 passed).

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

Copy link
Copy Markdown
Member Author

/review

@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ Android PR Reviewer completed successfully!

Generated by Android PR Reviewer for #13706

@github-actions github-actions Bot 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.

⚠️ Needs Changes

Findings: 0 errors · 1 warning · 1 suggestion, posted inline.

The logcat filter excludes CoreCLR's DOTNET native-crash messages and managed stack frames, leaving useful causal evidence out of the surviving failure message. The additional suggestion is to retain the sequential-build regression tests described in the validation notes.

The previous stale-log finding is addressed: the selected build log, process log, and backup are cleared before each invocation. The exception output has explicit line-count/length limits, and the existing build-failure behavior and 90-second marker timeout are preserved.

CI: All 38 GitHub checks on 7d977bf56ddb1a5900759f0ee1e5e33982d95b57 completed successfully, including the dotnet-android check for build 1694551. Direct Azure build-result/timeline verification was blocked by Azure CLI errors/authentication requirements, so that part of CI verification remains incomplete.

Reviewed both full changed files, the builder callers/project configuration, the logcat monitor, and the linker app fixture. This was a static review; no build or device tests were run.

Generated by Android PR Reviewer for #13706 · copilot · gpt61 · 36.5 AIC · ⌖ 4.97 AIC · ⊞ 21K
Comment /review to run again

var lines = File.ReadLines (logcatPath)
.Where (l => l.Contains ("XALINKERTESTS", StringComparison.Ordinal) ||
l.Contains (proj.PackageName, StringComparison.Ordinal) ||
l.Contains ("AndroidRuntime", StringComparison.Ordinal) ||

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.

🤖 ⚠️ Error handling — This filter drops CoreCLR's native-crash diagnostics: E DOTNET : Got a SIGSEGV while executing native code and the subsequent managed stack frames generally contain none of these four strings. NativeCrashProducesManagedStackTrace in this same file documents and checks that exact output format. The F DEBUG tombstone can show that a crash occurred, but it does not replace the managed frames that identify the failing regression test; those would still be lost when the retry passes and artifacts are skipped. Please retain the relevant DOTNET error/crash lines too (preferably scoped to the app PID), while preserving the existing output limits.

{Rule: Include actionable details in exceptions}

// MSBuild may fail before its file logger initializes, so discard the previous build log too.
if (processLog != null) {
foreach (var path in new [] { buildLogFullPath, processLog, processLog + ".bak" }) {
if (File.Exists (path))

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.

🤖 💡 Testing — Could we retain the sequential-build regression cases mentioned in the PR description instead of leaving them as temporary validation? The distinction between a failure after the file logger starts and an argument-parsing failure before it starts is important here, and ordinary successful device runs do not exercise it. Using the same builder/project directory, assert that a second failing invocation reports its own diagnostic and excludes the first invocation's diagnostic, including the early argument-error case. This would protect the stale-log fix already made in response to the previous review.

{Rule: Bug fixes need regression tests}

@jonathanpeppers jonathanpeppers left a comment

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.

🤖 ✅ LGTM — CI is green (38/38). The change is diagnostics only, and clearing process.log per invocation also fixes stale output from earlier builds that appeared in LastBuildOutput.

4 💡 suggestions, all to make the diff smaller. The largest one: an ErrorsOnly MSBuild file logger can replace the regex error scraper.

const int MaxReportedBuildErrors = 20;
const int MaxReportedBuildErrorLength = 1000;

static readonly Regex buildErrorRegex = new Regex (

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.

🤖 💡 Code organization — The regex, node-prefix strip, dedup HashSet, and AppendBuildErrors (~30 lines) can be replaced by a second MSBuild file logger that writes only errors:

: string.Format ("/noconsolelogger \"/flp1:LogFile={0};Encoding=UTF-8;Verbosity={1}\" \"/flp2:LogFile={2};Encoding=UTF-8;ErrorsOnly;NoSummary\"", ...)

Then the failure message only needs the first N lines of errors.log. MSBuild formats each error once, without the 1> prefix and without the summary copy, so there is no regex to maintain. Trade-off: MSB1xxx command-line switch errors happen before loggers start and go only to process.log. Those are rare and are not intermittent CI failures.

var message = new StringBuilder ($"Build failure: {Path.GetFileName (projectOrSolution)}");
if (!ranToCompletion) {
message.Append ($" (timed out after {DefaultBuildTimeOut} minutes)");
} else if (exitCode.HasValue) {

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.

🤖 💡 Code organization — exitCode is non-null exactly when ranToCompletion is true, so else if (exitCode.HasValue) is always true here. A plain int exitCode = -1; plus message.Append (ranToCompletion ? $" (exit code {exitCode})" : $" (timed out after {DefaultBuildTimeOut} minutes)") removes the nullable and one branch.

: null;
// MSBuild may fail before its file logger initializes, so discard the previous build log too.
if (processLog != null) {
foreach (var path in new [] { buildLogFullPath, processLog, processLog + ".bak" }) {

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.

🤖 💡 Code organization — File.Delete does not throw when the file does not exist (the project directory always exists here), so the array and File.Exists checks are not necessary:

File.Delete (buildLogFullPath);
File.Delete (processLog);
File.Delete (processLog + ".bak");


// CI does not upload logcat files when the auto-retry passes, so surface enough
// to tell a launch failure, crash, ANR, or a hung regression test apart.
string getLinkerTestAppDiagnostics ()

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.

🤖 💡 Code organization — This 30-line local function is used by one assertion. TakeLast removes the count header, the empty-case branch, and the per-line truncation (Android already limits each logcat entry to about 4 KB):

if (!completed) {
	var lines = File.ReadLines (logcatPath)
		.Where (l => l.Contains ("XALINKERTESTS", StringComparison.Ordinal) ||
			l.Contains (proj.PackageName, StringComparison.Ordinal) ||
			l.Contains ("AndroidRuntime", StringComparison.Ordinal) ||
			l.Contains (" F DEBUG", StringComparison.Ordinal))
		.TakeLast (60);
	Assert.Fail ($"Linker test app did not run successfully. Relevant lines from {logcatPath}:{Environment.NewLine}{string.Join (Environment.NewLine, lines)}");
}

If other MonitorAdbLogcat callers need the same evidence later, move it to DeviceTest at that time.

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.

3 participants