Skip to content

Don't start an AutoML trial after a stop was requested - #7964

Open
krwq wants to merge 4 commits into
dotnet:mainfrom
krwq:krwq-fix-7418-automl-cancel-test
Open

krwq wants to merge 4 commits into
dotnet:mainfrom
krwq:krwq-fix-7418-automl-cancel-test

Conversation

@krwq

@krwq krwq commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Note

This description was written by GitHub Copilot (AI) on my behalf.

AutoMLExperiment_return_current_best_trial_when_ct_is_canceled_with_trial_completed_Async was flaky because it timed the whole experiment with a stopwatch and required it to finish within 5 seconds. Each trial in the test takes 1 second, and the test cancels 100 ms into the second trial, so a run normally takes about 1.1 seconds. On CI, the test process sometimes slows down for several seconds; in the most recent failure, the run took 9 seconds. #7424 had already raised the limit from 2.5 to 5 seconds, and the test still failed. Less often, a bug in AutoMLExperiment.RunAsync added a full second: a stop that arrived while the second trial was still being set up was missed, so that trial ran to the end.

The test no longer measures time. Its first trial finishes right away, and the second trial waits until it's cancelled. The test cancels once the second trial is running and checks that the first trial is returned. If cancellation didn't work, the second trial would finish after a minute with a better result, so the test would fail instead of hanging. The test also drops its 10-second training time limit and its 100 ms cancellation timer, since both can misfire when the process slows down.

RunAsync now checks for a stop right after the tuner proposes a trial and again right before the trial starts, and doesn't start the trial if a stop was requested. Cancelling the trial's token instead isn't enough, because some trial runners still start training with a cancelled token. If the caller cancels and the tuner throws OperationCanceledException, RunAsync now returns the best trial so far instead of throwing. If a stop comes before any trial has finished, RunAsync now throws its documented TimeoutException instead of returning a trial that ran after the stop. I also corrected the RunAsync docs.

AutoMLExperiment_lgbm_cancel_trial_when_exceeds_memory_limit_Async is meant to check that LightGBM can be cancelled while it trains, but its memory limit stopped the trial before LightGBM started, even before this change. Now that a stopped trial doesn't start at all, the test no longer ran any training code. It's renamed to AutoMLExperiment_lgbm_cancel_trial_when_ct_is_canceled_during_training_Async, and it now cancels when LightGBM starts boosting and checks that the trial stops. The memory limit is still tested by AutoMLExperiment_cancel_trial_when_exceeds_memory_limit_Async. The old test also happened to be the only one covering the tuner's default cost for a trainer it has no cost estimate for, so a new tuner test covers that now.

I tested this locally over about 12 hours, in conditions close to CI. Each run was a new test process limited to 2 CPUs, with the same tests running alongside as in the failing CI run. To reproduce the CI failure, most runs slowed the test process down:

Slowdown of the test process Old test New test
None 0 of 100 runs failed; the slowest took 4.6 s, close to the 5 s limit 0 of 300 failed
Almost stopped for 3–8 s, repeatedly at random times 30 of 200 failed 0 of 200 failed
Almost stopped for 3–30 s while the test ran 47 of 50 failed 0 of 350 failed
At least 20 times slower for 3–30 s while the test ran 28 of 30 failed 0 of 300 failed
Almost stopped for 30–55 s while the test ran not run 0 of 30 failed
  • The other new and changed cancellation tests also ran at least 500 times each with random slowdowns, with no failures. The rewritten LightGBM test ran 110 times with no failures, 37 of them with the process almost stopped while it ran.
  • Each RunAsync change has a new test that fails without the change.
  • The Microsoft.ML.AutoML.Tests suite passes on net10.0 and net48. On net11.0, one unrelated test, AutoFitRankingCVTest, fails with or without this change.
  • Not run on Linux, macOS, x86 or Helix.

With high confidence, this test won't fail the way it did in #7418.

Fixes #7418

krwq and others added 2 commits November 26, 2026 17:27
AutoMLExperiment_return_current_best_trial_when_ct_is_canceled_with_trial_completed_Async
asserted that the whole run finished within 5 seconds (2.5 seconds before
dotnet#7424). On CI the test process sometimes runs several times slower than
usual (the latest failure took ~9 seconds), so no fixed threshold is
reliable and the test kept failing.

Rewrite the test so it no longer measures time. The first trial completes
immediately; later trials only finish early when they are canceled and
otherwise report a better metric after a minute. The test cancels once the
second trial is running, checks that it really started, and asserts that the
first trial is returned, which proves the running trial was canceled. The run
is limited to two trials, so if cancellation gets lost the test fails instead
of starting more trials.

Relates to dotnet#7418

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
AutoMLExperiment.RunAsync checks for a stop request at the top of its loop,
then proposes and sets up the next trial, and only then subscribes the
handler that cancels the trial when training should stop. A stop request
raised in between (for example the user token being canceled, or the
training time running out, while the tuner proposes the next trial) fired
OnStopTraining before the handler was subscribed, so that trial still ran
to completion and could even become the best trial. A stop requested while
the trial was starting, for example from the performance monitor's first
sample, only canceled the trial's token, and the trial still started.

Check for a stop request in two more places and leave the loop without
starting the trial if one was made:
- right after the tuner proposes the trial, so the trial isn't reported
  as running or set up;
- right before the trial runner starts, after the handler is subscribed
  and the startup callbacks have run.

Only canceling the trial's token isn't enough: SweepablePipelineRunner
still builds the pipeline and calls Fit with a canceled token, and
Fairlearn's grid search runner (GridSearchTrailRunner) ignores the token.

A tuner may also see the caller's cancellation itself and throw
OperationCanceledException from Propose or Update. If RunAsync's token was
canceled, treat that like any other stop: keep the trial that already
completed, save the results and return the best trial so far instead of
throwing. The exception's own token isn't checked, because a tuner may
combine RunAsync's token with one of its own. If RunAsync's token wasn't
canceled, exceptions from the tuner are handled as before.

Correct the RunAsync documentation. It said RunAsync calls
MLContext.CancelExecution and quoted a TimeoutException message that
doesn't match the code. It now says the cancellation is forwarded to the
running trial's token and RunAsync waits for that trial, and it documents
the parameter, the return value and the TimeoutException.

Add regression tests with a runner that ignores cancellation, so the
second trial would become the best one if it ran. They cancel while the
second trial is proposed (with the tuner returning or throwing), from the
performance monitor's first sample, and from the tuner's Update after the
first trial. They also check that a stop requested while proposing doesn't
report the trial as running or create its runner, and that a tuner
cancellation is still thrown when RunAsync's token wasn't canceled.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.94%. Comparing base (218d0b8) to head (7f16db8).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7964      +/-   ##
==========================================
+ Coverage   70.89%   70.94%   +0.04%     
==========================================
  Files        1421     1421              
  Lines      280133   280458     +325     
  Branches    27601    27615      +14     
==========================================
+ Hits       198597   198960     +363     
+ Misses      73393    73360      -33     
+ Partials     8143     8138       -5     
Flag Coverage Δ
Debug 70.94% <100.00%> (+0.04%) ⬆️
production 64.36% <100.00%> (+0.02%) ⬆️
test 90.78% <100.00%> (+0.04%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...oft.ML.AutoML/AutoMLExperiment/AutoMLExperiment.cs 85.00% <100.00%> (+9.10%) ⬆️
...Microsoft.ML.AutoML.Tests/AutoMLExperimentTests.cs 89.79% <100.00%> (+4.68%) ⬆️
test/Microsoft.ML.AutoML.Tests/TunerTests.cs 100.00% <100.00%> (ø)

... and 12 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Code coverage showed lines in the new test helpers that only run when the
product is broken: code after a throw, branches that record something only
if it happens after the stop, an IMonitor member that nothing calls, and
the end of a delay that the test always cancels. Restructure the helpers
so that every line runs, while each test still fails without the change it
covers.

The LightGBM memory-limit test never reached LightGBM: its memory limit is
exceeded at the performance monitor's first sample, before the trial
starts. It only covered SweepablePipelineRunner's cancellation path,
because the trial still started with a token that was already canceled,
so the runner canceled its MLContext and threw before LightGBM started.
With trials no longer started after a stop, it didn't cover even that.
The test now cancels the experiment when LightGBM logs its objective,
right before boosting, and uses the sweepable LightGBM trainer, which is
created on the trial's MLContext that the runner cancels. So it checks
what its comment says: that LightGBM can be canceled while training the
booster. The memory limit is still covered by
AutoMLExperiment_cancel_trial_when_exceeds_memory_limit_Async.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@krwq

krwq commented Nov 27, 2026

Copy link
Copy Markdown
Member Author

(addressed coverlet regression)

The old LightGBM cancellation test was, by accident, the only test that
covered the tuner's default cost for a trainer it has no cost estimate
for. The rewritten test no longer does, so add a small tuner test that
covers it on purpose.

Also create the does_not_set_up_trial test's monitor up front.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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.

AutoMLExperiment_return_current_best_trial_when_ct_is_canceled_with_trial_completed_Async fails in CI

1 participant