Skip to content

Fix AzureDevOpsReport teardown crash and silent live-publishing failures - #10291

Merged
Amaury Levé (Evangelink) merged 10 commits into
mainfrom
dev/amauryleve/glowing-parakeet
Jul 28, 2026
Merged

Amaury Levé (Evangelink) merged 10 commits into
mainfrom
dev/amauryleve/glowing-parakeet

Conversation

@Evangelink

Copy link
Copy Markdown
Member

Fixes #10191.

What was wrong

Microsoft.Testing.Extensions.AzureDevOpsReport crashed the test host at teardown with an unhandled ObjectDisposedException, failing the pipeline task after every test had passed and results had already been published:

Test run summary: Failed!   error: 1
  total: 558   failed: 0   succeeded: 558

Unhandled exception. System.ObjectDisposedException: The CancellationTokenSource has been disposed.
   at Microsoft.Testing.Extensions.AzureDevOpsReport.AzureDevOpsTestResultsPublisher.Dispose()
   at Microsoft.Testing.Platform.Hosts.CommonHost.DisposeServiceProviderAsync(...)

My earlier fix in #10195 did not actually fix this. It removed a duplicate disposal within a single disposal pass, but the console host runs two passes with separate bookkeeping — ConsoleTestHost.InternalRunAsync disposes the service provider with a fresh alreadyDisposed list, then CommonHost.RunAsync disposes it again with its own. So Dispose() is still called twice and still calls Cancel() on a disposed CancellationTokenSource. I reproduced the exact crash on current main, both directly and through dotnet test.

The reporter then followed up saying the crash was gone on 2.3.3 but results were no longer published. That turned out to be a second, distinct bug — see below.

Fix 1 — make Dispose() idempotent

Dispose() now guards with Interlocked.Exchange. Dispose is required to be idempotent, so this is the extension's bug to fix regardless of the platform behaviour.

Fix 2 — stop failing silently

Investigating the follow-up produced the more interesting finding. The AzDO extension is byte-identical between 2.3.2 and 2.3.3 (git diff v4.3.2..v4.3.3 over that folder is empty), so the upgrade cannot have changed publishing behaviour. And since the crash only happens once publishing has actually started — _backgroundFlushCts is only assigned after CreateTestRunAsync succeeds — a 2.3.3 run that doesn't crash is a run where the test run was never created. The missing crash and the missing results are the same event.

The reason nobody could tell is that every failure path in the publisher reported only through _logger.LogWarning, which writes to the diagnostic file log that is off by default. I reproduced two separate ways to get "task succeeds, no results, zero output":

  • Azure DevOps rejects run creation (403 — job authorization scope / Manage test runs).
  • SYSTEM_ACCESSTOKEN not reaching the process.

So live-publishing failures now also go to the output device, which renders as an Azure Pipelines warning:

##vso[task.logissue type=warning]Azure DevOps live publishing failed to create the test run.
Azure DevOps REST API request failed with status code 403. Response: {"message":"TF400813: user is not authorized"}

##vso[task.logissue type=warning]'--publish-azdo-test-results' was set, but Azure DevOps live publishing
is disabled because the following environment variables are missing or invalid: SYSTEM_ACCESSTOKEN.

Covered failures: missing configuration, run creation, results that could not be published, attachment uploads, and run finalization. The finalization one matters more than it looks — a run left in InProgress does not appear in the build's Tests tab, so previously every result could upload successfully and the user would still see an empty tab with no explanation. That warning now says so explicitly.

Two notes on how this is reported:

  • Results and attachments are summarised once at session end with a count, not per failed batch — the background loop retries on an interval and would otherwise spam a warning every 5 seconds.
  • IsEnabledAsync() no longer validates configuration (it just checks the option). Validation moved to OnTestSessionStartingAsync so there is somewhere to report from; previously a bad configuration silently disabled the extension before it could say anything.

Also fixed along the way

  • ConsumeAsync renewed the coordination lease before enqueuing the result. RenewLeaseAsync does file I/O that can throw (sharing violation against the owner reading lease files), which dropped the result before it reached any queue — invisible to the new accounting. Now enqueues first.
  • WarnAsync never propagates. It is called from error-recovery paths and from session teardown, and the platform does not guard lifetime handlers, so a throwing output device would have turned a warning into a failed run — the same class of bug as the crash above.

Verification

  • Reproduced the original crash on main, and confirmed it is gone: run created, results published, run marked Completed, exit code 0.
  • Reproduced both silent-failure modes against a local fake Azure DevOps REST endpoint and confirmed each now emits a ##vso[task.logissue type=warning].
  • Mutation-tested the new assertions: reverting the fix makes the corresponding test fail.
  • 792 unit tests pass; build clean with 0 warnings.

Follow-up (not in this PR)

The double disposal is a platform bug, not an extension bug: every IDisposable reached via messageBus.DataConsumerServices is disposed twice in the console host, including third-party extensions. Sharing CommonHost.RunAsync's alreadyDisposed list with InternalRunAsync would remove the whole class of bug. I kept that out of here to limit the blast radius — happy to open a separate issue.

The Azure DevOps live test-results publisher is disposed twice during
teardown (once when the test host disposes its services, once again during
process shutdown). Its Dispose() called Cancel() on an already disposed
CancellationTokenSource, which crashed the test host with an unhandled
ObjectDisposedException after all tests had passed and after results had
already been published. #10195 removed one duplicate-dispose path inside a
single disposal pass but the crash still reproduces end to end, so make
Dispose() idempotent.

The follow-up symptom (no crash, but no published results) has the same
root cause surface: when the Azure DevOps environment is incomplete the
publisher silently disabled itself from IsEnabledAsync and only logged to
the diagnostic file log, so users saw neither a test run nor a reason.
Keep the extension enabled whenever --publish-azdo-test-results is set and
report the missing configuration on the output device instead.

Fixes #10191

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89
…ures

- WarnAsync no longer propagates output-device exceptions. It is called from
  error-recovery paths and from session teardown, where CommonTestHost does not
  guard lifetime handlers, so a throw would have turned a diagnostic warning
  into a failed run - the same class of bug this change set fixes.
- Reset the publisher state before reporting the run-creation failure so a
  display failure can never leave it half-initialized.
- Route the post-run failures through the output device too. These are the ones
  that produce the reported symptom: a run left in InProgress does not appear in
  the Tests tab, and results left in the retry queue after the session-end flush
  are never retried. Report dropped results once with a count rather than per
  failed batch, to avoid spamming a warning every flush interval.
- Replace the double-dispose-without-session test, which passed with and without
  the fix, by one covering the inert-but-registered path that keeping the
  extension enabled now creates (ConsumeAsync/OnTestSessionFinishingAsync/Dispose
  on a misconfigured publisher).

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89
…ting, message accuracy

- Attachment failures were still log-only. They are swallowed per attachment so
  one bad file cannot abort the drain, which made the outer catch unreachable and
  the changelog claim wrong. Count them at the real failure sites (run-level,
  result-level, and the batch skipped when result IDs cannot be parsed) and
  report one summary at session end. Coverage files and dumps no longer go
  missing without explanation.
- ConsumeAsync renewed the coordination lease before enqueuing the result, so an
  I/O failure there dropped the result before it reached a queue and the
  end-of-session count could not see it. Enqueue first.
- WarnAsync's fallback reused 'failed to publish test results' for a failure to
  write to the output device, which in the finalize path claimed results had
  failed to publish when they had all succeeded. Use a dedicated message.
- Make the missing-configuration warning provably non-null via [NotNullWhen(false)]
  rather than falling back to the unformatted resource string, which would have
  shown a raw '{0}' on the console.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89
Per-attachment failures are counted inside UploadResultAttachmentsAsync, so the
only non-cancellation exception the surrounding catch can see is one thrown by
RenewLeaseAsync - in which case no upload is attempted and the whole attachment
set was dropped without being counted, making the end-of-session summary
under-report. Assert the summary from the existing result-attachment failure test
so the common counting path is covered.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89

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

Fixes Azure DevOps live-publishing teardown crashes and exposes previously silent publishing failures.

Changes:

  • Makes publisher disposal idempotent and preserves results during lease-renewal failures.
  • Emits user-visible warnings for publishing, attachment, configuration, and finalization failures.
  • Adds tests, localized resources, API tracking, and changelog entries.
Show a summary per file
File Description
AzureDevOpsLivePublishingTests.cs Adds regression and warning tests.
AzureDevOpsResources.cs.xlf Adds Czech resource entries.
AzureDevOpsResources.de.xlf Adds German resource entries.
AzureDevOpsResources.es.xlf Adds Spanish resource entries.
AzureDevOpsResources.fr.xlf Adds French resource entries.
AzureDevOpsResources.it.xlf Adds Italian resource entries.
AzureDevOpsResources.ja.xlf Adds Japanese resource entries.
AzureDevOpsResources.ko.xlf Adds Korean resource entries.
AzureDevOpsResources.pl.xlf Adds Polish resource entries.
AzureDevOpsResources.pt-BR.xlf Adds Portuguese resource entries.
AzureDevOpsResources.ru.xlf Adds Russian resource entries.
AzureDevOpsResources.tr.xlf Adds Turkish resource entries.
AzureDevOpsResources.zh-Hans.xlf Adds Simplified Chinese resource entries.
AzureDevOpsResources.zh-Hant.xlf Adds Traditional Chinese resource entries.
AzureDevOpsResources.resx Defines new warning messages.
InternalAPI.Unshipped.txt Tracks changed internal constructors.
AzureDevOpsTestResultsPublisher.Flush.cs Counts failed attachment uploads.
AzureDevOpsTestResultsPublisher.cs Implements disposal safety and visible warnings.
AzureDevOpsTestResultsPublisher.Configuration.cs Adds nullability contracts.
AzureDevOpsExtensions.cs Injects the output device.
Changelog-Platform.md Documents both fixes.

Review details

  • Files reviewed: 21/21 changed files
  • Comments generated: 2
  • Review effort level: Medium

@Evangelink Amaury Levé (Evangelink) added the state/needs-review Awaiting review from the team. label Jul 28, 2026
…g-parakeet

# Conflicts:
#	docs/Changelog-Platform.md
Copilot AI review requested due to automatic review settings July 28, 2026 13:29

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.

Review details

Comments suppressed due to low confidence (4)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:179

  • WarnAsync is documented and used as non-throwing, but this first logging call is outside the try. The platform logger invokes providers directly (Microsoft.Testing.Platform/Logging/Logger.cs:14-22), so a failing diagnostic sink can prevent the output warning and escape a session lifetime handler, failing the test run. Guard both logging attempts independently so output reporting is still attempted and no fallback diagnostic propagates.
        _logger.LogWarning(message);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:343

  • The internally created cleanupCts is passed to the client as its user cancellation token, so when this 90-second cleanup budget expires, UpdateTestRunStateAsync can throw OperationCanceledException. The current filter excludes that exception, bypassing this warning and propagating through the unguarded lifetime handler; the run remains InProgress and an otherwise successful test process can fail during teardown. Catch this private cleanup cancellation as a finalization failure too.
            await WarnAsync(
                $"{AzureDevOpsResources.AzureDevOpsLivePublishingCompleteRunFailed} {ex.Message} {AzureDevOpsResources.AzureDevOpsLivePublishingRunLeftInProgress}",
                CancellationToken.None).ConfigureAwait(false);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:280

  • This count misses a batch when cancellation occurs after FlushPendingResultsAsync has dequeued it: the publish then throws OperationCanceledException, that path does not requeue the local batch, and this sum sees neither the in-flight results nor the loss. Requeue the batch before rethrowing cancellation (or track in-flight results) so canceled session-end publishing still emits the promised dropped-result count.
        int unpublishedResultCount = _retryResults.Count + _pendingResults.Count;

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:306

  • A canceled session can still lose attachments silently here. UploadPendingRunAttachmentsAsync dequeues an attachment before awaiting the upload and rethrows cancellation; the caller swallows it, while neither that attachment nor the still-queued attachments increments _failedAttachmentCount. Consequently this summary is absent or under-counted precisely on canceled teardown. Account for the dequeued and remaining attachments, or perform the bounded final drain with a fresh token.
        // Attachment failures are swallowed per attachment so that one bad file cannot abort the drain.
        // Report them once here, otherwise coverage files and dumps go missing with no explanation.
        int failedAttachmentCount = Volatile.Read(ref _failedAttachmentCount);
  • Files reviewed: 21/21 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

Copilot AI review requested due to automatic review settings July 28, 2026 13:34

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.

Review details

Comments suppressed due to low confidence (3)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:179

  • WarnAsync is documented as never throwing, but both _logger.LogWarning calls remain outside a protective catch. MTP's composite logger directly invokes providers (Microsoft.Testing.Platform/Logging/Logger.cs:14-22), so a provider failure can still escape this teardown/error path; the first failure also prevents the output warning from being attempted. Guard the two logging attempts independently from the output-device attempt.
        _logger.LogWarning(message);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:337

  • A finalization timeout is still silent. The fresh cleanupCts above cancels when the configured cleanup window expires, causing FinalizeRunAsync to throw OperationCanceledException; this filter excludes it, so the run remains InProgress without the new output warning. Because this token is not the session token, timeout cancellation should be reported like every other finalization failure.
        catch (Exception ex) when (ex is not OperationCanceledException)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:280

  • The normal teardown cancellation can make this count miss an entire in-flight batch. If the background loop has already dequeued a batch when _backgroundFlushCts.Cancel() runs, FlushPendingResultsAsync rethrows OperationCanceledException without requeuing it; after the loop exits, neither queue contains those results, so this computes zero and publishing/attachment loss remains silent. Preserve or account for the in-flight batch on cancellation, or cancel only the delay rather than an active flush.
        int unpublishedResultCount = _retryResults.Count + _pendingResults.Count;
  • Files reviewed: 21/21 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

WarnAsync documents a never-throws contract but called _logger.LogWarning
outside any guard. Logger invokes each registered provider directly, so a
failing provider propagated out of the helper - including out of its own
catch block, where it replaced the exception being handled. Route both
logging attempts through TryLogWarning so a broken diagnostic logger can
neither suppress the output-device attempt nor escape the recovery path.

Run finalization excluded OperationCanceledException from its catch, but it
runs on its own cleanupCts rather than the session token, so an expiry there
(or an HttpClient TaskCanceledException) escaped this lifetime handler and
could fail an otherwise successful run - exactly the teardown crash this
change set exists to prevent. Treat it like the other finalization failures.

Both regressions are covered by tests that fail when the fix is reverted.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89
Copilot AI review requested due to automatic review settings July 28, 2026 13:41

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.

Review details

Comments suppressed due to low confidence (3)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:175

  • The never-throws guarantee is bypassed by teardown's direct logger calls. If a publish failure makes FlushPendingResultsAsync log through a throwing provider, the catch at lines 291-293 logs directly again and OnTestSessionFinishingAsync propagates before the new output-device summary; the analogous background-task catch at lines 271-274 has the same problem. Route those recovery logs through TryLogWarning so the tested logger-failure behavior also covers teardown.
    /// <remarks>
    /// Never throws: this is a best-effort diagnostic invoked from error-recovery paths and from
    /// session teardown, where propagating would turn a warning into a failed run.

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:326

  • This summary omits attachments lost when session cancellation interrupts the drain. UploadPendingRunAttachmentsAsync dequeues an attachment and rethrows OperationCanceledException without incrementing the counter, while the remaining queue is also excluded; result attachments can similarly be lost after their result batch was removed. Account for in-flight and queued attachments (or drain with a bounded cleanup token) before emitting the summary.
        // Attachment failures are swallowed per attachment so that one bad file cannot abort the drain.
        // Report them once here, otherwise coverage files and dumps go missing with no explanation.
        int failedAttachmentCount = Volatile.Read(ref _failedAttachmentCount);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Flush.cs:33

  • Incrementing only on exceptions still leaves known attachment drops silent. Both real client upload methods return successfully when TryBuildAttachmentRequest rejects a missing, oversized, unreadable, or invalid file, so this counter remains unchanged and the new end-of-session warning reports nothing. Make the client return an upload outcome (or validate before calling it) and count rejected payloads.
            catch (Exception ex)
            {
                Interlocked.Increment(ref _failedAttachmentCount);
                _logger.LogWarning($"{AzureDevOpsResources.AzureDevOpsLivePublishingRunAttachmentFailed} {ex.Message}");
  • Files reviewed: 21/21 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

@github-actions

This comment has been minimized.

@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.

🤖 Automated content by GitHub Copilot. Generated by the Grade Tests on PR (on open / sync) workflow. · sonnet46 76.5 AIC · ⌖ 4.9 AIC · ⊞ 11.7K · ◷

OnTestSessionFinishingAsync is a lifetime handler and the platform does not
guard those, so a throwing log provider in its recovery catches escaped and
failed an otherwise successful run - the same defect already fixed inside
WarnAsync, one frame away. Route the background-flush and session-end flush
catches through TryLogWarning, plus the matching ConsumeAsync catch so the
recovery paths are consistent.

Covered by a test that drives a publish failure and then breaks the log
provider before teardown; it fails when the guard is reverted.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89
Copilot AI review requested due to automatic review settings July 28, 2026 13:54
@Evangelink

Copy link
Copy Markdown
Member Author

Following up on the three low-confidence notes in the latest review summary.

Accepted — teardown recovery logging (AzureDevOpsTestResultsPublisher.cs:175). Correct, and it was the same defect I had just fixed inside WarnAsync, one frame away. OnTestSessionFinishingAsync is a lifetime handler and the platform does not guard those, so a throwing log provider in its recovery catches escaped and failed an otherwise successful run. Routed the background-flush and session-end flush catches through TryLogWarning in 083a8f2, plus the matching ConsumeAsync catch so the recovery paths are consistent. Covered by a test that breaks the log provider right before teardown and fails when the guard is reverted.

Declined — attachments lost to session cancellation (AzureDevOpsTestResultsPublisher.cs:326). Accurate as a description, but I do not think it is worth accounting for. It only happens when the run was already cancelled, in which case the test run is separately marked Aborted and missing artifacts are expected rather than surprising. Adding in-flight and queued accounting on the cancellation path buys little signal for real complexity on a teardown path.

Deferred — attachments rejected by TryBuildAttachmentRequest (Flush.cs:33). This one is a genuine gap: a missing, oversized, or unreadable file is skipped silently and the counter never moves, so the end-of-session summary under-reports. It is pre-existing behavior though (see ConsumeAsync_SkipsOversizedFileAttachment), and the suggested fix means changing IAzureDevOpsTestResultsClient to return an upload outcome, which touches the interface, its implementation, the test double, and the InternalAPI baseline. That is a bigger change than belongs in a teardown-crash fix, so I would rather do it separately than expand this PR. Happy to open a follow-up issue if that sounds right.

The test only asserted that one line reached the output device, so a mutation
emitting an arbitrary string or the wrong resource key would have survived.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89

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.

Review details

Comments suppressed due to low confidence (4)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Flush.cs:57

  • The outer catch does not only represent RenewLeaseAsync failures: this direct log can throw after the individual failure was already counted. The outer catch then adds the whole attachment set again and stops processing the remaining attachments, producing an inflated summary. Route this through TryLogWarning so the helper continues draining and each failure is counted once.
                Interlocked.Increment(ref _failedAttachmentCount);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:326

  • This summary omits attachments lost to cancellation. UploadPendingRunAttachmentsAsync dequeues the current attachment before awaiting, then rethrows cancellation without incrementing this counter; any attachments still queued are also excluded. Account for the dequeued and remaining run attachments on cancellation so the best-effort warning is not silently skipped or undercounted.
        int failedAttachmentCount = Volatile.Read(ref _failedAttachmentCount);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Flush.cs:33

  • A logging provider can throw here (the new TryLogWarning helper exists for exactly that case). That exception exits the drain after the first failed upload, so remaining queued run attachments are neither attempted nor included in _failedAttachmentCount. Use the non-throwing helper so one provider cannot abort attachment processing.

This issue also appears on line 57 of the same file.

                Interlocked.Increment(ref _failedAttachmentCount);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:300

  • This queue-only count misses an in-flight batch when cancellation occurs after FlushPendingResultsAsync dequeues it: OperationCanceledException is rethrown without requeueing or accounting for that batch. The session-end warning can therefore report zero even though the whole batch was dropped. Track canceled in-flight results separately and include them here; avoid blindly retrying because the REST request may already have been accepted.

This issue also appears on line 326 of the same file.

        int unpublishedResultCount = _retryResults.Count + _pendingResults.Count;
  • Files reviewed: 21/21 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

Copilot AI review requested due to automatic review settings July 28, 2026 13: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.

Review details

Comments suppressed due to low confidence (3)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Flush.cs:57

  • A throwing log provider escapes this per-attachment catch. The caller then treats it like a pre-upload lease failure and adds the entire attachment set again, so the summary can double-count failures, count earlier successful uploads as failed, and skip later uploads. Route this through TryLogWarning to preserve the drain and its accounting.
                Interlocked.Increment(ref _failedAttachmentCount);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Flush.cs:198

  • This recovery path still calls the logger directly. If lease renewal fails and a logging provider also throws, the exception exits the batch loop after counting only this result's attachments; attachments on later already-published results are then silently skipped and absent from the summary. Use TryLogWarning so the loop continues.
                        Interlocked.Add(ref _failedAttachmentCount, batch[i].Attachments.Count);

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.Flush.cs:33

  • _logger.LogWarning can throw because the platform logger invokes providers directly. After the first failed run attachment, that aborts this drain, leaves the remaining queued attachments unattempted, and makes the new end-of-session count under-report them. Use the non-throwing helper so per-attachment processing continues.

This issue also appears in the following locations of the same file:

  • line 57
  • line 198
                Interlocked.Increment(ref _failedAttachmentCount);
  • Files reviewed: 21/21 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

@github-actions

Copy link
Copy Markdown
Contributor

🧪 Test quality grade — PR #10291

GradeTestMutationNotesHow to improve
A (90–100) mod AzureDevOpsLivePublishingTests.
OnTestSessionStartingAsync_
JsonExceptionLogsWarningAndDoesNotThrow
3/3 killed RunId null-check plus both logger and output-device string assertions cover all key mutations. —
A (90–100) new AzureDevOpsLivePublishingTests.
Dispose_
CalledTwiceAfterSession_
DoesNotThrow
1/1 killed No-throw verification is the contract; removing the idempotency guard causes a thrown exception that fails the test. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionStartingAsync_
MissingConfiguration_
StaysEnabledAndWarnsOnOutputDevice
4/4 killed Enabled state, null RunId, empty client calls, output-device count and content all asserted. —
A (90–100) new AzureDevOpsLivePublishingTests.
MissingConfiguration_
ConsumeFinishAndDispose_
AreSafeNoOps
4/4 killed All four client-call lists are asserted empty, covering every no-op pathway. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
FinalizeFailure_
WarnsRunMayNotAppearOnOutputDevice
2/2 killed Both required warning resource keys are checked on the output device. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
ResultsCouldNotBePublished_
WarnsWithCountOnOutputDevice
2/2 killed Format-string assertion with count=1 kills both the missing-message and wrong-count mutations. —
A (90–100) mod AzureDevOpsLivePublishingTests.
ConsumeAsync_
AttachmentUploadFailureLogsWarningAndDoesNotRetryPublish
5/5 killed publish-call count, upload-call count, logger warning, and new session-summary output-device assertion all asserted. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
AttachmentUploadFailure_
WarnsWithCountOnOutputDevice
2/2 killed Format-string with count=1 verifies both that the message is emitted and that the count is correct. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionStartingAsync_
LogProviderThrows_
DoesNotFailTheRun
2/2 killed Count and content of output-device lines verified; a crashing logger propagating out fails the test. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
PublishFailsAndLogProviderThrows_
DoesNotFailTheRun
2/2 killed Format-string assertion verifies the console summary survives even when the diagnostic logger is broken. —
A (90–100) new AzureDevOpsLivePublishingTests.
OnTestSessionFinishingAsync_
FinalizeCanceled_
DoesNotFailTheRun
2/2 killed Both warning keys verified on output device; removing the cancellation catch causes the test to throw. —

This advisory comment was generated automatically. Grades are heuristic and informational — they do not block merging. Re-run with /grade-tests.

🤖 Automated content by GitHub Copilot. Generated by the Grade Tests on PR (on open / sync) workflow. · sonnet46 112.4 AIC · ⌖ 4.62 AIC · ⊞ 11.7K · [◷]( · ◷)

A throwing log provider escaping these catches did more than fail the run: it
aborted the attachment drain so the rest of the queue was never attempted and
never counted, and when it escaped the per-attachment catch the caller treated
it as a pre-upload lease failure and added the whole attachment set again,
double-counting failures and mis-reporting successful uploads as failed.

Route every recovery-path log in the publisher through TryLogWarning so the
loops continue and the end-of-session counts stay accurate. The invariant is
now checkable: the only direct _logger.LogWarning call left is the one inside
TryLogWarning itself.

Covered by a test that fails two run attachments with a broken log provider and
asserts both are attempted and counted; it fails when the guard is reverted.

Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89
Copilot AI review requested due to automatic review settings July 28, 2026 14:13
@Evangelink

Copy link
Copy Markdown
Member Author

Update on the latest two review rounds.

Fixed — the repeated Flush.cs logging notes (lines 33, 57, 198, plus 86, 154 and 166 for consistency), in 5277a18. The reviewer was right that this was more than a "run fails" problem. A throwing provider escaping the per-attachment catch aborted the drain so the rest of the queue was never attempted or counted, and when it escaped UploadResultAttachmentsAsync the caller treated it as a pre-upload lease failure and added the whole attachment set again, double counting failures and reporting already-successful uploads as failed.

Every recovery-path log in the publisher now goes through TryLogWarning, so the invariant is checkable: the only direct _logger.LogWarning call left in the type is the one inside TryLogWarning itself. Covered by a test that fails two run attachments with a broken log provider and asserts both are attempted and counted.

Still declined — the cancellation accounting notes (AzureDevOpsTestResultsPublisher.cs:300 and :326). Both are mechanically accurate: a batch dequeued by FlushPendingResultsAsync and a dequeued or queued run attachment are dropped without being counted when the session is cancelled. I am leaving them because they only occur on cancellation, where the test run is separately marked Aborted and incomplete results are expected rather than surprising. Tracking in-flight batches would add teardown state for a case the user already knows about, and as the note itself points out the retry is not safe anyway since the REST request may already have been accepted.

Happy to revisit if a maintainer disagrees on that trade-off.

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.

Review details

Comments suppressed due to low confidence (2)

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:300

  • This snapshot misses a batch that is canceled while the forced flush is in flight. FlushPendingResultsAsync removes the batch from both queues before renewing the lease/publishing, and OperationCanceledException bypasses the retry push; the catch above then swallows it, so this count can be zero even though those results are no longer tracked. Preserve and report an in-flight/uncertain result count on cancellation (without blindly republishing, since the request may already have reached Azure DevOps).
        int unpublishedResultCount = _retryResults.Count + _pendingResults.Count;

src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/AzureDevOpsTestResultsPublisher.cs:326

  • _failedAttachmentCount still does not cover attachments the real client drops locally. Both upload methods return successfully when TryBuildAttachmentRequest rejects a missing, unreadable, or oversized file (AzureDevOpsTestResultsClient.cs:110-116,127-133), and the existing oversized-file test explicitly documents that behavior at AzureDevOpsLivePublishingTests.cs:615-645. Such attachments remain silently absent while this count stays zero. Have the client return an upload/skipped outcome (or validate before calling it) and include skipped attachments in this summary.
        // Attachment failures are swallowed per attachment so that one bad file cannot abort the drain.
        // Report them once here, otherwise coverage files and dumps go missing with no explanation.
        int failedAttachmentCount = Volatile.Read(ref _failedAttachmentCount);
  • Files reviewed: 21/21 changed files
  • Comments generated: 0 new
  • Review effort level: Medium

@Evangelink
Amaury Levé (Evangelink) enabled auto-merge (squash) July 28, 2026 14:21

@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.

🤖 Automated content by GitHub Copilot. Generated by the Grade Tests on PR (on open / sync) workflow. · sonnet46 114.5 AIC · ⌖ 4.04 AIC · ⊞ 11.7K · ◷

@Evangelink
Amaury Levé (Evangelink) merged commit 8205776 into main Jul 28, 2026
40 checks passed
@Evangelink
Amaury Levé (Evangelink) deleted the dev/amauryleve/glowing-parakeet branch July 28, 2026 15:54
@Evangelink

Copy link
Copy Markdown
Member Author

/backport to rel/4.3

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Amaury Levé (@Evangelink) backporting to rel/4.3 failed, the patch most likely resulted in conflicts:

$ git am --3way --empty=keep --ignore-whitespace --keep-non-patch changes.patch

Applying: Fix AzureDevOpsReport teardown crash and silent live-publishing disable
Using index info to reconstruct a base tree...
M	docs/Changelog-Platform.md
A	src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/InternalAPI/InternalAPI.Unshipped.txt
M	test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AzureDevOpsLivePublishingTests.cs
Falling back to patching base and 3-way merge...
Auto-merging docs/Changelog-Platform.md
CONFLICT (content): Merge conflict in docs/Changelog-Platform.md
CONFLICT (modify/delete): src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/InternalAPI/InternalAPI.Unshipped.txt deleted in HEAD and modified in Fix AzureDevOpsReport teardown crash and silent live-publishing disable.  Version Fix AzureDevOpsReport teardown crash and silent live-publishing disable of src/Platform/Microsoft.Testing.Extensions.AzureDevOpsReport/InternalAPI/InternalAPI.Unshipped.txt left in tree.
Auto-merging test/UnitTests/Microsoft.Testing.Extensions.UnitTests/AzureDevOpsLivePublishingTests.cs
error: Failed to merge in the changes.
hint: Use 'git am --show-current-patch=diff' to see the failed patch
hint: When you have resolved this problem, run "git am --continue".
hint: If you prefer to skip this patch, run "git am --skip" instead.
hint: To restore the original branch and stop patching, run "git am --abort".
hint: Disable this message with "git config set advice.mergeConflict false"
Patch failed at 0001 Fix AzureDevOpsReport teardown crash and silent live-publishing disable
Error: The process '/usr/bin/git' failed with exit code 128

NOTE: A PR will be created, but needs to be revised manually!

Amaury Levé (Evangelink) added a commit that referenced this pull request Aug 7, 2026
…res by @Evangelink in #10291 (backport to rel/4.3) (#10504)

Co-authored-by: Amaury Levé <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Copilot-Session: b564deae-b8d2-49aa-96d3-9308ec461d89
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

state/needs-review Awaiting review from the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Microsoft.Testing.Extensions.AzureDevOpsReport crashes during teardown after successful live Azure DevOps test-result publishing

3 participants