Repository navigation
[tests] Report build errors and logcat evidence in test failures - #13706
simonrozsival wants to merge 5 commits into
Conversation
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]>
There was a problem hiding this comment.
🟡 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
CustomLinkDescriptionPreservemisses 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]>
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]>
|
/review |
|
✅ Android PR Reviewer completed successfully!
|
There was a problem hiding this comment.
⚠️ 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) || |
There was a problem hiding this comment.
🤖 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)) |
There was a problem hiding this comment.
🤖 💡 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
left a comment
There was a problem hiding this comment.
🤖 ✅ 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 ( |
There was a problem hiding this comment.
🤖 💡 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) { |
There was a problem hiding this comment.
🤖 💡 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" }) { |
There was a problem hiding this comment.
🤖 💡 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 () |
There was a problem hiding this comment.
🤖 💡 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.

Context: #4451
These are diagnostics only. They don't fix any flaky test; they make the next flake show its actual cause.
Why
Several
MSBuildDeviceIntegrationtests failed once in pipeline 333 PR builds (Nov 20–21) and then passed on(Auto-Retry):CoreCLRAssemblyStoreConcurrentLoads,AppWithStyleableUsageRuns,BundleToolNoAbiSplitTests.InstallAndRun, andCustomLinkDescriptionPreserve. The first attempts failed with a bareFailedBuildException(for exampleBuild failure: UnnamedProject.csproj) duringBuild,Install, which carries no error text.When the retry passes, the job skips its artifact uploads, so
build.log, the binlogs, andlogcat*.logare never published.RunSlicedTestsalso removes the failed first-attempt TRX results. Only the console log survives, so the root causes can't be recovered from CI.InstallAndRunfailed four times, always on macOS-1 as the first test after the emulator started.CustomLinkDescriptionPreserve(SdkOnly,CoreCLR)in build 1693432 failed differently.Runsucceeded in 10s, then the test waited the full 90 seconds without loggingAll regression tests completed., failing with onlyLinker 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 runsHttpClientTest.Postsynchronously inOnCreate, withHttpClient's default 100s timeout.Changes
FailedBuildExceptionmessages fromBuildernow include the exit code or timeout, thebuild.logpath, and up to 20 deduplicated MSBuilderrorlines (1000 chars each).CustomLinkDescriptionPreservemarker is missing, the failure message includes the last 60logcat.loglines matchingXALINKERTESTS, the package name,AndroidRuntime, orF 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.Builder.BuildInternal: a probe project with<Error Code="TEST0001" … />built usingbin/Debug/dotnet/dotnetthrew:build.logcontains the error twice (the error plus the summary); the exception lists it once. WithThrowOnBuildFailure = falsethe build returnedfalse, and the error appears inLastBuildOutput.emulator-5558):InstallAndRunNativeAOT is[Ignore]d), Failed 0, 6m56s.error MSB4177: Invalid property. The name " -p:Device" contains an invalid character " ".Device,_DetectIfAppWasUninstalledpicked another emulator, and the logcat diagnostics correctly reportedNo 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.BuilderTestsfixture, both sequential-build cases failed in each of three independent runs against the priorc9ff613a5bBuilder and passed in three runs with the fix.