Skip to content

Add CancellationToken overloads to TaskHubWorker.StartAsync and StopAsync - #1446

Open
Ming (MaxonT) wants to merge 4 commits into
Azure:mainfrom
MaxonT:contrib/596-auto
Open

Ming (MaxonT) wants to merge 4 commits into
Azure:mainfrom
MaxonT:contrib/596-auto

Conversation

@MaxonT

@MaxonT Ming (MaxonT) commented Nov 27, 2026 •

Copy link
Copy Markdown

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 as StopAsync(true). It never skips the stop because of the token, so a worker is not left running after a host shutdown.
  • The existing parameterless StartAsync() now calls the new overload with CancellationToken.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 to StopAsync(bool) before and is now ambiguous, because default fits both parameter types. I found no such call in this repository.

Refs #596.

Tests: TaskHubWorkerCancellationTests has 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 forwards true to StopAsync(bool) and a live token forwards false; 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 to WaitAsync() and with the forced flag changed to false, 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.

…sync

Signed-off-by: Ym <173550318+MaxonT@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 04:03
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
There may be pipelines that require an authorized user to comment /azp run to run.

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

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);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 04:58

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

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);

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
Copilot AI balanced review requested due to automatic review settings November 27, 2026 05:38

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.

🟢 Approval recommended

No active review issues remain for the cancellation-token overloads that simplify hosted-service integration.

2 open issues
1 resolved since last review

Review effort: Balanced

@MaxonT

Copy link
Copy Markdown
Author

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 TaskHubWorkerCancellationTests on 3124536 (net8.0 only, .NET 9 SDK with roll forward): 5 passed, 0 failed. Two local mutation checks, both reverted and not pushed, confirm the new tests catch regressions. Changing StopAsync(CancellationToken) to call StopAsync(false) fails the forced-flag test. Changing the lock wait back to WaitAsync() fails the lock-contention test after its 30 s timeout. I did not run the net48 target, the rest of DurableTask.Core.Tests, or the other test projects.

@MaxonT

Copy link
Copy Markdown
Author

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

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);

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.

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

Comment on lines +52 to +53
OrchestrationState state = await client.WaitForOrchestrationAsync(instance, Timeout);
Assert.AreEqual(OrchestrationStatus.Completed, state.OrchestrationStatus);

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.

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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
Copilot AI balanced review requested due to automatic review settings December 4, 2026 23:14

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.

🟢 Approval recommended

No active review issues remain for the cancellation-token overload changes.

2 open issues

Review effort: Balanced

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