Skip to content

fix: preserve task serialization on request cancellation - #3079

Merged
OrKoN merged 4 commits into
ChromeDevTools:mainfrom
lisa0314:fix/2934-cancellation
Nov 11, 2026
Merged

OrKoN merged 4 commits into
ChromeDevTools:mainfrom
lisa0314:fix/2934-cancellation

Conversation

@lisa0314

@lisa0314 lisa0314 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Related to #2934.

Cancellation rejects the request with its original signal reason and removes tasks that are still waiting in TaskRunner, including waiting exclusive tasks that block otherwise unrelated page queues. The MCP request dispatcher forwards the signal to ToolHandler.

Once execution starts, the execution owns the acquired queue guard until it settles, including page initialization, file validation, handler work, and response processing. Cancelling the request stops waiting for its result without releasing that guard early. Later tasks on related queues and TaskRunner.pause() still wait for the running work, so an old handler cannot race a subsequent selection or page operation. Unrelated page queues retain their existing concurrency, and tools with concurrency none remain queue-free.

Cancellation does not forcibly interrupt browser operations or undo side effects. A handler that never settles can therefore keep its queue blocked indefinitely; this change does not fully solve recovery from arbitrary hung scripts in #2934. It preserves serialization instead of allowing subsequent calls to race abandoned work. Cancellation neither closes Chrome nor abandons a shared connection attempt.

Cancelled executions are logged once with success: false. Cancellation checks prevent the abandoned execution from starting later response or DevTools data processing; processing that already started keeps the queue until it settles.

@OrKoN
OrKoN requested a review from zyzyzyryxy October 14, 2026 08:10
@OrKoN

OrKoN commented Oct 14, 2026

Copy link
Copy Markdown
Collaborator

@zyzyzyryxy, please review this PR (automatically distributed)

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please check the following:

  1. Rebase onto main and redesign the attachment point. #3149 removed the 60 s race around the tool body, so #raceWithTimeout now wraps only context.ensureBrowser(); the PR's cancellation race around the handler has no place to attach, and ToolHandler.handle() on main uses ToolLockGuard, ToolLockControl.releaseIfYielding()/reacquire(), and #runBrowserTool/#runBrowserlessTool.

  2. Make the abandoned call skip lock.reacquire() after cancellation. On main, the handler body ends with finally { await lock.reacquire(); }; when handle() returns early on abort and disposes guard, the still-running body later acquires a new guard that nothing releases, so the mutex is held forever and the bug returns.

  3. State in the PR description and in a code comment that a cancelled handler keeps running against the same page while the next tool call proceeds. The tool lock exists to serialize page operations; the change gives up that guarantee for cancelled calls, so the reviewer and the reader must see this trade-off, and the abandoned call must not write telemetry or response state that the next call reads.

  4. Use one outcome for a cancelled call. Cancellation while waiting for the lock throws signal.reason, but cancellation during execution returns {isError: true}; throw signal.reason in both paths, since the SDK drops any result for a cancelled request.

  5. Remove the signal?.removeEventListener optional chaining in #raceWithTimeout; signal is defined whenever onAbort is set. Move the cancellation promise into a small helper (for example rejectOnAbort(signal)) so the race reads as Promise.race([promise, timeout, rejectOnAbort(signal)]).

  6. In tests/index.test.ts, replace the fixed setTimeout(…, 1_000) with a poll or with a server-side signal that the evaluation started, and assert the rejection by err.name === 'AbortError' rather than assert.rejects(pendingEvaluation) with no matcher. A fixed sleep is flaky under load and a bare rejects passes for any error.

  7. In tests/ToolHandler.test.ts, assert the lock state directly (mutex is free after the cancelled call) in addition to running next_tool, and replace /aborted/i with {name: 'AbortError'}. The current assertions pass for any error that releases the lock, not only for cancellation.

  8. Add a unit test in tests/McpServer.test.ts (or tests/index.test.ts with mocks) that #registerTool passes ctx.mcpReq.signal to handler.handle. The src/index.ts change has no test that observes the forwarded signal.

@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch from 3c0d1e3 to 055549d Compare October 20, 2026 05:54
@OrKoN
OrKoN self-requested a review October 20, 2026 05:55
@OrKoN

OrKoN commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

Thanks for iterations! Actually this starts to look fairly complicated and I am gonna rework the locking so let's revisit after that.

@OrKoN

OrKoN commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

@lisa0314 could please update on top of the new concurrency model?

@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch from 055549d to e148b7c Compare October 21, 2026 02:10
@lisa0314

lisa0314 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor Author

The main changes are:

  • Adapted cancellation to TaskRunner. Reworked the implementation around context queues for exclusive tools, page queues for routed page tools, and queue-free execution for tools with concurrency: 'none'. Removed the previous mutex acquisition and reacquisition logic from the cancellation implementation.
  • Added cancellation support to queue acquisition. TaskQueue.scheduleTask() now accepts an AbortSignal. Cancelling a waiting request immediately removes its entry and allows scheduling to continue. This matters particularly for waiting exclusive tasks, which can otherwise block operations on other pages.
  • Handled guard ownership races. Covered cancellation before acquisition, while waiting, and immediately after acquiring a guard. An acquired guard remains the caller’s responsibility and is released exactly once. Also handled cancellation racing with queue disposal and cleaned up abort listeners.
  • Applied consistent cancellation behavior throughout tool execution. Forwarded the MCP request signal through both the request dispatcher and the registered tool callback. Context waits, queue acquisition, browser connection waits, and tool execution now propagate the signal’s original cancellation reason instead of returning a normal tool error result.
  • Prevented late handler results from entering subsequent processing. Added cancellation checks before starting later stages and after awaited operations. When an abandoned handler eventually completes or fails, it skips response processing and telemetry updates.
  • Documented the concurrency trade-off. Added a code comment and prepared an updated PR description explaining that cancellation cannot interrupt unsupported browser operations. An abandoned handler may continue operating on the same page while the next call proceeds, so serialization is relinquished for cancelled work.
  • Updated regression coverage for the new model. Added direct queue-acquisition and runner-pause checks, coverage for all concurrency modes, waiting parent queues, late completion and failure, initialization cancellation, and signal forwarding.

Comment thread src/utils/TaskRunner.ts Resolved
Comment thread src/utils/TaskRunner.ts Resolved
Comment thread src/utils/TaskRunner.ts Resolved
Comment thread tests/utils/TaskRunner.test.ts Resolved

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please check the following:

  1. In src/utils/TaskRunner.ts #scheduleTask(), make onAbort act only on a waiting entry (!entry.running), share that logic with #cancel() in one helper, and return the guard after await started without the signal.throwIfAborted() check. This mirrors how dispose() treats a running entry, matches the TSDoc "after acquisition, the caller owns the guard", and the caller in ToolHandler.handle() already checks the signal after using guard.

  2. In src/utils/TaskRunner.ts #scheduleTask(), declare signal?: AbortSignal instead of the default new AbortController().signal. pause() and every uncancellable call otherwise allocate a controller that nothing uses.

  3. In src/ToolHandler.ts, remove the signal.throwIfAborted() calls that follow Promise.race([this.getContext(), cancellation]) and #raceWithTimeout(). Both races already reject with signal.reason, so the checks never throw.

  4. In tests/McpServer.test.ts, remove the registeredCallback === true variant that replaces the tools/call handler and calls registration.executor. The SDK marks executor as @hidden, and #setToolCallRequestHandler() overrides tools/call, so the variant tests a path that the server never runs.

  5. In tests/utils/TaskRunner.test.ts, drop the {timeout: 30_000} added to the top-level describe. The new tests use settle() and resolve in milliseconds, and the change affects the existing tests in the suite.

  6. In src/ToolHandler.ts handle(), shorten the four-sentence inline comment before execution to one sentence and move the trade-off text to the TSDoc of handle(). AGENTS.md limits inline comments to one sentence, and the trade-off is part of the method contract.

  7. In src/ToolHandler.ts handle(), log the cancellation (logger?.(\${tool.name} cancelled`)) before the catchblock rethrowssignal.reason. The catch` block now skips the error log on abort, so a cancelled call leaves no log line at all.

  8. In src/ToolHandler.ts rejectOnAbort(), return {promise, [Symbol.dispose]} instead of Object.assign(promise, {...}). Adding a property to a Promise instance hides the Disposable in the type intersection and is not a pattern used elsewhere in src/.

  9. In tests/ToolHandler.test.ts, move await new Promise(resolve => setImmediate(resolve)) (three copies) to a settle() helper in tests/utils.ts and reuse it from tests/utils/TaskRunner.test.ts, which already defines the same function. AGENTS.md requires one helper for a repeated block.

  10. In tests/ToolHandler.test.ts ("skips work after page cancellation"), assert notCalled on McpResponse.prototype.setPage (via a spy) instead of run. AGENTS.md requires the notCalled target to be the first method called after the step under test, and response.setPage() runs before tool.handler.

  11. In tests/McpServer.test.ts and tests/index.test.ts, replace the assertions on SdkError/SdkErrorCode.RequestTimeout with a check that pending rejects and that the server-side signal is aborted. The mapping of an aborted request to RequestTimeout is SDK-internal and changes between SDK versions.

  12. In tests/index.test.ts, remove server.restore(). The TestServer is new in the test, so there is no state to restore.

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

we probably still want telemetry for cancelled logs (currently seems to be skipped)

@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch from 735c77b to e8f591a Compare October 22, 2026 06:19
@lisa0314

Copy link
Copy Markdown
Contributor Author

@OrKoN Please hold off on the review for now. Sorry, I need a bit of time to clean up the code. I’ll ping you when I’m ready.

@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch 2 times, most recently from 3744a08 to f35ec80 Compare October 22, 2026 12:01
@OrKoN
OrKoN self-requested a review October 22, 2026 12:03
@lisa0314

Copy link
Copy Markdown
Contributor Author

TaskRunner now shares cancellation cleanup for waiting entries, accepts an optional signal, and leaves acquired guards with the caller. I restored the Error types, removed the redundant abort checks, added cancellation logging, moved the concurrency trade-off into the method TSDoc, and changed rejectOnAbort() to return {promise, [Symbol.dispose]}. The tests now use a shared settle() helper, assert that setPage is not called after page initialization
is cancelled, and verify request rejection and server-side cancellation without relying on SDK-specific error codes.

PTAL. Thanks!

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please check the following:

  1. In src/ToolHandler.ts handle(), remove the if (!signal.aborted) check in finally and update the logToolInvocation assertions in tests/ToolHandler.test.ts and the PR description. Telemetry must still record cancelled tool invocations with success: false, while signal.throwIfAborted() in #runBrowserTool() prevents the abandoned execution from collecting DevTools data later.

  2. In src/index.ts #registerTool(), revert (args, ctx) => handler.handle(args, {signal: ctx.mcpReq.signal}) back to args => handler.handle(args) and update the PR description to state that signal forwarding happens in #setToolCallRequestHandler(). #setToolCallRequestHandler() overrides the tools/call handler, so the callback in #registerTool() never receives MCP requests and has no test coverage.

@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch from f35ec80 to 7a2ec1d Compare October 23, 2026 08:13
@lisa0314

Copy link
Copy Markdown
Contributor Author

Updated both points: handle() now records cancelled executions with success: false, and the tests verify exactly one invocation log, including after abandoned work settles. The abort checks still prevent late DevTools data collection and response processing. I also restored #registerTool() to args => handler.handle(args); signal forwarding remains in #setToolCallRequestHandler(), covered by the dispatcher test.

@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch from 7a2ec1d to dc7c24a Compare October 23, 2026 08:49
@OrKoN

OrKoN commented Oct 23, 2026

Copy link
Copy Markdown
Collaborator

@zyzyzyryxy or @Lightning00Blade could you please review and land next week?

Comment thread src/utils/TaskRunner.ts Resolved
@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch from dc7c24a to 4fa7cc6 Compare November 5, 2026 06:43
@lisa0314 lisa0314 changed the title fix: release tool lock on request cancellation fix: preserve task serialization on request cancellation Nov 5, 2026
@OrKoN
OrKoN self-requested a review November 5, 2026 11:45

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Please check the following:

  1. Replace rejectOnAbort in src/ToolHandler.ts with the existing raceWithSignal helper from src/tools/input.ts, moved to src/utils/. Both race a promise against signal.reason and remove the listener on settle; the repository rule is one helper per repeated block.

  2. Update the TSDoc of ToolHandler.#raceWithTimeout to state that the race also ends on signal abort and that abort does not call onTimeout(). The current text describes only the timeout.

  3. Remove the e2e test cancels a request and resumes its queue after evaluation settles in tests/index.test.ts. tests/McpServer.test.ts already covers the SDK cancellation path (same _onrequest code over InMemoryTransport) and tests/ToolHandler.test.ts covers queue retention; the e2e test launches Chrome under a 90 s budget and its assertions cannot prove serialization because finish.resolve() runs before list_pages is awaited.

  4. Remove the {timeout: 30_000} options on the cancellation describe in tests/ToolHandler.test.ts and on the dispatcher test in tests/McpServer.test.ts. scripts/test.js passes --test-timeout=120000, so a per-test value only lowers the budget.

  5. Nit: TaskRunner.#cancelEntry(entry, reason: Error) receives signal.reason, which the SDK sets to the string from notifications/cancelled params.reason (see _oncancel). Type the parameter unknown, or document on TaskQueue.scheduleTask that a cancelled task can reject with a non-Error value. Or ideally we should wrap it in an error.

@OrKoN
OrKoN self-requested a review November 10, 2026 08:28
@lisa0314

Copy link
Copy Markdown
Contributor Author

Please check the following:

  1. Replace rejectOnAbort in src/ToolHandler.ts with the existing raceWithSignal helper from src/tools/input.ts, moved to src/utils/. Both race a promise against signal.reason and remove the listener on settle; the repository rule is one helper per repeated block.
  2. Update the TSDoc of ToolHandler.#raceWithTimeout to state that the race also ends on signal abort and that abort does not call onTimeout(). The current text describes only the timeout.
  3. Remove the e2e test cancels a request and resumes its queue after evaluation settles in tests/index.test.ts. tests/McpServer.test.ts already covers the SDK cancellation path (same _onrequest code over InMemoryTransport) and tests/ToolHandler.test.ts covers queue retention; the e2e test launches Chrome under a 90 s budget and its assertions cannot prove serialization because finish.resolve() runs before list_pages is awaited.
  4. Remove the {timeout: 30_000} options on the cancellation describe in tests/ToolHandler.test.ts and on the dispatcher test in tests/McpServer.test.ts. scripts/test.js passes --test-timeout=120000, so a per-test value only lowers the budget.
  5. Nit: TaskRunner.#cancelEntry(entry, reason: Error) receives signal.reason, which the SDK sets to the string from notifications/cancelled params.reason (see _oncancel). Type the parameter unknown, or document on TaskQueue.scheduleTask that a cancelled task can reject with a non-Error value. Or ideally we should wrap it in an error.

Moved raceWithSignal from input.ts into src/utils/ and reused it in ToolHandler, replacing rejectOnAbort. The helper also observes late promise rejections when the signal is already aborted. Updated the timeout TSDoc to clarify that abort does not call onTimeout(), removed the redundant cancellation e2e and the two local timeout overrides, and changed the cancellation reason types to unknown so the original signal.reason is preserved.

@OrKoN OrKoN left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks! I think this looks good but we need to rebase

Rebase onto main and add "utils/raceWithSignal.ts" to src/BUILD.gn and "utils/raceWithSignal.test.ts" to tests/BUILD.gn. The branch predates the GN build (#3330, #3331); BUILD.gn lists source files explicitly, so after the merge npm run build does not compile the new helper or its test.

@lisa0314
lisa0314 force-pushed the fix/2934-cancellation branch from e640d38 to 5214ff2 Compare November 11, 2026 01:42
@OrKoN
OrKoN enabled auto-merge November 11, 2026 06:35
@OrKoN
OrKoN added this pull request to the merge queue Nov 11, 2026
Merged via the queue into ChromeDevTools:main with commit 03fd4e8 Nov 11, 2026
14 checks passed
Lightning00Blade pushed a commit to jaeminbird/chrome-devtools-mcp that referenced this pull request Nov 11, 2026
🤖 I have created a release *beep* *boop*
---


##
[1.13.0](ChromeDevTools/chrome-devtools-mcp@chrome-devtools-mcp-v1.12.0...chrome-devtools-mcp-v1.13.0)
(2026-11-11)


### 🎉 Features

* add logpoints built on the DevTools BreakpointManager
([ChromeDevTools#3211](ChromeDevTools#3211))
([0877ee0](ChromeDevTools@0877ee0))
* add page-scoped network mocks
([ChromeDevTools#3384](ChromeDevTools#3384))
([1d692d3](ChromeDevTools@1d692d3))
* support upstream network mock responses
([ChromeDevTools#3420](ChromeDevTools#3420))
([c4bf342](ChromeDevTools@c4bf342))


### 🛠️ Fixes

* **config:** accept config files with a UTF-8 BOM
([ChromeDevTools#3365](ChromeDevTools#3365))
([63170b1](ChromeDevTools@63170b1))
* **console:** stop resolving a cyclic Error.cause chain after 10 causes
([ChromeDevTools#3338](ChromeDevTools#3338))
([172656a](ChromeDevTools@172656a))
* disable set_logpoints when --no-javascript-evaluation is set
([ChromeDevTools#3415](ChromeDevTools#3415))
([11fcc59](ChromeDevTools@11fcc59)),
closes
[ChromeDevTools#3414](ChromeDevTools#3414)
* **extensions:** say list_extensions only lists unpacked extensions
([ChromeDevTools#3433](ChromeDevTools#3433))
([1383bb9](ChromeDevTools@1383bb9))
* ignore an invalid cached version in the update check
([ChromeDevTools#3392](ChromeDevTools#3392))
([3a9f378](ChromeDevTools@3a9f378))
* **input:** validate press_key and submitKey parameters in Zod schema
([ChromeDevTools#3382](ChromeDevTools#3382))
([375a269](ChromeDevTools@375a269))
* **network:** start an empty request list for navigations without a
request
([ChromeDevTools#3357](ChromeDevTools#3357))
([b701776](ChromeDevTools@b701776))
* normalize non-Error values thrown by tool handlers
([ChromeDevTools#3068](ChromeDevTools#3068))
([535a3dc](ChromeDevTools@535a3dc))
* **performance:** error when performance_stop_trace is called on a
non-recording page
([ChromeDevTools#2971](ChromeDevTools#2971))
([ChromeDevTools#3117](ChromeDevTools#3117))
([1ab630a](ChromeDevTools@1ab630a))
* **plugin:** launch the Claude Code MCP server with npx --prefix
([ChromeDevTools#3353](ChromeDevTools#3353))
([a24334d](ChromeDevTools@a24334d))
* preserve task serialization on request cancellation
([ChromeDevTools#3079](ChromeDevTools#3079))
([03fd4e8](ChromeDevTools@03fd4e8))
* report page loads that keep the URL
([ChromeDevTools#3395](ChromeDevTools#3395))
([3cc38bb](ChromeDevTools@3cc38bb))
* save binary request bodies byte for byte
([ChromeDevTools#3404](ChromeDevTools#3404))
([e3eb901](ChromeDevTools@e3eb901))
* suggest --headless when Chrome cannot find an X server
([ChromeDevTools#3428](ChromeDevTools#3428))
([8b0856a](ChromeDevTools@8b0856a))
* **url:** unwrap view-source: before all scheme checks in validateUrl
([ChromeDevTools#3335](ChromeDevTools#3335))
([7275268](ChromeDevTools@7275268))
* **wait:** explain whitespace-sensitive text matching
([ChromeDevTools#3350](ChromeDevTools#3350))
([81a0379](ChromeDevTools@81a0379))


### 📄 Documentation

* add Pi client configuration
([ChromeDevTools#3364](ChromeDevTools#3364))
([bc0d93e](ChromeDevTools@bc0d93e))
* clarify custom browser launch and connection options
([ChromeDevTools#3386](ChromeDevTools#3386))
([7e10c08](ChromeDevTools@7e10c08))
* **input:** note that press_key cannot drive native <select>
popups on macOS
([ChromeDevTools#3288](ChromeDevTools#3288))
([8e79bd0](ChromeDevTools@8e79bd0))


### ⚡ Performance

* **memory:** drop async parents of request initiators in
NetworkCollector
([ChromeDevTools#3345](ChromeDevTools#3345))
([ca6f834](ChromeDevTools@ca6f834)),
closes
[ChromeDevTools#3344](ChromeDevTools#3344)


### 🏗️ Refactor

* re-export only used Zod runtime members from third_party barrel
([ChromeDevTools#3439](ChromeDevTools#3439))
([6b056c8](ChromeDevTools@6b056c8))
* reuse Zod schemas and validate integer viewport dimensions
([ChromeDevTools#3367](ChromeDevTools#3367))
([3c609da](ChromeDevTools@3c609da))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: Alex Rudenko <[email protected]>
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.

2 participants