Repository navigation
Add CancellationToken overloads to TaskHubWorker.StartAsync and StopAsync - #1446
Ming (MaxonT) wants to merge 4 commits into
Conversation
…sync Signed-off-by: Ym <173550318+MaxonT@users.noreply.github.com>
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
There was a problem hiding this comment.
🟡 Changes recommended
The new tests are excluded from compilation on case-sensitive filesystems due to the uppercase directory path, and they do not verify that canceled and live tokens forward the correct forced-stop flag.
2 open issues
What changed in this PR
Adds cancellation-token overloads to TaskHubWorker to simplify use from hosted services, without implementing IHostedService or adding a hosting dependency.
Changes:
- Allows cancellation before startup begins while preserving the existing parameterless API.
- Uses forced shutdown when the stop token is already canceled; otherwise stops gracefully.
- Adds emulator-based tests for token-aware startup, shutdown, and worker restartability.
| File | Description |
|---|---|
Test/DurableTask.Core.Tests/TaskHubWorkerCancellationTests.cs |
Adds three tests for token-aware worker lifecycle behavior. |
src/DurableTask.Core/TaskHubWorker.cs |
Adds and documents cancellation-token overloads, preserving existing overloads. |
Review effort: Balanced
| /// </param> | ||
| public async Task StopAsync(CancellationToken cancellationToken) | ||
| { | ||
| await this.StopAsync(cancellationToken.IsCancellationRequested); |
There was a problem hiding this comment.
Fair point, the idle emulator would have hidden a wrong flag. 3124536 adds StopAsyncWithToken_ForwardsForcedFlagFromToken, which uses a spy on the service's StopAsync(bool) to check that a canceled token forwards true and a live token forwards false. I haven't run the test locally; CI is green on this head.
There was a problem hiding this comment.
One correction to my reply above, and the one on the start-lock thread: I wrote that CI is green on 3124536, but only license/cla has run there. The CodeQL run is waiting for a maintainer to approve workflows, so no build or test workflow has run on this head yet. I have now run TaskHubWorkerCancellationTests locally on net8.0: 5 passed. Reverting the token to WaitAsync() makes the start-lock test fail, and passing false as the forced flag makes the forced-flag test fail, so both tests do catch those regressions. I haven't run the net48 target.
…on layout Signed-off-by: Ym <173550318+MaxonT@users.noreply.github.com>
There was a problem hiding this comment.
🟡 Changes recommended
The tests do not cover cancellation while waiting for the start lock or verify that stop forwards the correct forced/graceful flag, leaving both new behaviors vulnerable to undetected regressions.
3 open issues
Review effort: Balanced
| /// <exception cref="OperationCanceledException">The token was canceled before the worker began to start.</exception> | ||
| public async Task<TaskHubWorker> StartAsync(CancellationToken cancellationToken) | ||
| { | ||
| await this.slimLock.WaitAsync(cancellationToken); |
There was a problem hiding this comment.
Thanks, that test was missing. 3124536 adds StartAsyncWithToken_CanceledWhileWaitingForStartLock_ThrowsBeforeFirstStartCompletes: it blocks a first start inside the service's StartAsync, queues a second start, cancels it, and asserts the second call throws while the first is still pending. I haven't run it locally; CI is green on this head.
There was a problem hiding this comment.
Correcting my reply above: CI is not green on 3124536. Only license/cla has run on that head. No build or test workflow has run yet, so the only test evidence for this head is my local net8.0 run of TaskHubWorkerCancellationTests (5 passed). The net48 target and the rest of DurableTask.Core.Tests have not been run.
…ing for the start lock Signed-off-by: Ym <173550318+MaxonT@users.noreply.github.com>
|
Correction to my earlier inline replies: I said CI was green on this head, but the only check on the PR is license/cla, so that wasn't evidence for the new tests. I have now run |
|
Hi sophiatev, could you please review this when you have a moment? In short: Add CancellationToken overloads to TaskHubWorker.StartAsync and StopAsync. I think this will be really valuable. You may want to take a look. Thanks! |
sophiatev
left a comment
There was a problem hiding this comment.
Please address the shutdown deadline before merging. The new orchestration test should also stop its worker when the wait or an assertion fails.
| /// </param> | ||
| public async Task StopAsync(CancellationToken cancellationToken) | ||
| { | ||
| await this.StopAsync(cancellationToken.IsCancellationRequested); |
There was a problem hiding this comment.
[P1] Honor cancellation during graceful shutdown
A host normally passes a live token and cancels it when its shutdown grace period expires. Reading IsCancellationRequested here fixes the stop mode before the worker acquires its lock. In a local test with one activity held open, StopAsync returned 8.05 seconds after cancellation and the backend still received isForced: false. Canceling while the stop was queued behind startup also produced false.
Please have the in-progress stop observe the token while draining work and switch to forced cleanup when the deadline expires. A regression test can hold an activity open, start a graceful stop, cancel the token, and check that the backend receives isForced: true before the normal drain timeout.
| OrchestrationState state = await client.WaitForOrchestrationAsync(instance, Timeout); | ||
| Assert.AreEqual(OrchestrationStatus.Completed, state.OrchestrationStatus); |
There was a problem hiding this comment.
[P3] Stop the test worker if the test fails
If this 30-second wait times out or the status assertion fails, the test exits before either StopAsync call. The emulator scheduler and worker dispatchers keep running during later tests in the same process. Please put await worker.StopAsync(true) in a finally block or a [TestCleanup] method so the worker is stopped on failure as well.
There was a problem hiding this comment.
Thanks for catching this one. Fixed in c29a5b9: the body of StartAsyncWithToken_RunsOrchestration_AndStopAsyncWithTokenStopsWorker now runs in a try, and the finally calls worker.StopAsync(true). That call is a no-op once the worker has already stopped, so a failed wait or assertion no longer leaves the emulator dispatchers running into later tests. I ran TaskHubWorkerCancellationTests locally on net8.0 (.NET 11 SDK with roll forward): 5 passed. I did not run net48 or the rest of DurableTask.Core.Tests, and only license/cla has reported on this commit. The shutdown-deadline comment is not addressed by this change and is still open.
The wait or an assertion in StartAsyncWithToken_RunsOrchestration_AndStopAsyncWithTokenStopsWorker could exit before StopAsync, leaving the emulator dispatchers running for later tests. Stop the worker in a finally block; StopAsync(true) is a no-op once the worker has stopped.

TaskHubWorker gets StartAsync(CancellationToken) and StopAsync(CancellationToken) overloads here, but the class still doesn't implement IHostedService, so is that second step better as its own PR? Tests ran on net8.0 only.
The issue asks for StartAsync and StopAsync overloads that take a CancellationToken, so a TaskHubWorker is easier to host from a background service. This adds those two overloads to TaskHubWorker.
StartAsync(CancellationToken)throws OperationCanceledException when the token is already canceled, or is canceled while it waits for the worker's start lock, before anything is started. Once startup has begun it runs to completion; the token is not passed down to the dispatchers.StopAsync(CancellationToken)does a graceful stop. If the token is already canceled when it is called, it stops forcefully, the same asStopAsync(true). It never skips the stop because of the token, so a worker is not left running after a host shutdown.StartAsync()now calls the new overload withCancellationToken.None; its behavior is unchanged. Overloads rather than optional parameters, so existing callers keep binary compatibility.This does not add an IHostedService implementation or the Microsoft.Extensions.Hosting dependency; the issue's implementation note only mentions the overloads, so I kept to that. A token that is canceled while a graceful stop is already in progress does not switch it to a forced stop. I can follow up on either if you want them.
One source-level side effect: a call written as
StopAsync(default)was bound toStopAsync(bool)before and is now ambiguous, becausedefaultfits both parameter types. I found no such call in this repository.Refs #596.
Tests:
TaskHubWorkerCancellationTestshas 5 tests (emulator-based): start and stop with a live token run an orchestration to completion; a canceled token makes StartAsync throw and leaves the worker startable; a canceled token still stops the worker; a spy checks that a canceled token forwardstrueto StopAsync(bool) and a live token forwardsfalse; a start queued behind a held start lock throws when its token is canceled. Checks on head 3124536: the author ran these 5 tests locally on net8.0 (.NET 9 SDK with roll forward) and they passed; with the start-lock wait changed back toWaitAsync()and with the forced flag changed tofalse, the matching tests fail. CI: only license/cla has run on this head; CodeQL is waiting for a maintainer to approve the workflows.Not run: the net48 target, the rest of the test suite, and the Azure Storage, Service Bus and Service Fabric projects.