Repository navigation
fix: preserve task serialization on request cancellation - #3079
Conversation
|
@zyzyzyryxy, please review this PR (automatically distributed) |
OrKoN
left a comment
There was a problem hiding this comment.
Please check the following:
-
Rebase onto
mainand redesign the attachment point. #3149 removed the 60 s race around the tool body, so#raceWithTimeoutnow wraps onlycontext.ensureBrowser(); the PR's cancellation race around the handler has no place to attach, andToolHandler.handle()onmainusesToolLockGuard,ToolLockControl.releaseIfYielding()/reacquire(), and#runBrowserTool/#runBrowserlessTool. -
Make the abandoned call skip
lock.reacquire()after cancellation. Onmain, the handler body ends withfinally { await lock.reacquire(); }; whenhandle()returns early on abort and disposesguard, the still-running body later acquires a new guard that nothing releases, so the mutex is held forever and the bug returns. -
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
responsestate that the next call reads. -
Use one outcome for a cancelled call. Cancellation while waiting for the lock throws
signal.reason, but cancellation during execution returns{isError: true}; throwsignal.reasonin both paths, since the SDK drops any result for a cancelled request. -
Remove the
signal?.removeEventListeneroptional chaining in#raceWithTimeout;signalis defined wheneveronAbortis set. Move the cancellation promise into a small helper (for examplerejectOnAbort(signal)) so the race reads asPromise.race([promise, timeout, rejectOnAbort(signal)]). -
In
tests/index.test.ts, replace the fixedsetTimeout(…, 1_000)with a poll or with a server-side signal that the evaluation started, and assert the rejection byerr.name === 'AbortError'rather thanassert.rejects(pendingEvaluation)with no matcher. A fixed sleep is flaky under load and a barerejectspasses for any error. -
In
tests/ToolHandler.test.ts, assert the lock state directly (mutexis free after the cancelled call) in addition to runningnext_tool, and replace/aborted/iwith{name: 'AbortError'}. The current assertions pass for any error that releases the lock, not only for cancellation. -
Add a unit test in
tests/McpServer.test.ts(ortests/index.test.tswith mocks) that#registerToolpassesctx.mcpReq.signaltohandler.handle. Thesrc/index.tschange has no test that observes the forwarded signal.
3c0d1e3 to
055549d
Compare
|
Thanks for iterations! Actually this starts to look fairly complicated and I am gonna rework the locking so let's revisit after that. |
|
@lisa0314 could please update on top of the new concurrency model? |
055549d to
e148b7c
Compare
|
The main changes are:
|
OrKoN
left a comment
There was a problem hiding this comment.
Please check the following:
-
In
src/utils/TaskRunner.ts#scheduleTask(), makeonAbortact only on a waiting entry (!entry.running), share that logic with#cancel()in one helper, and return the guard afterawait startedwithout thesignal.throwIfAborted()check. This mirrors howdispose()treats a running entry, matches the TSDoc "after acquisition, the caller owns the guard", and the caller inToolHandler.handle()already checks the signal afterusing guard. -
In
src/utils/TaskRunner.ts#scheduleTask(), declaresignal?: AbortSignalinstead of the defaultnew AbortController().signal.pause()and every uncancellable call otherwise allocate a controller that nothing uses. -
In
src/ToolHandler.ts, remove thesignal.throwIfAborted()calls that followPromise.race([this.getContext(), cancellation])and#raceWithTimeout(). Both races already reject withsignal.reason, so the checks never throw. -
In
tests/McpServer.test.ts, remove theregisteredCallback === truevariant that replaces thetools/callhandler and callsregistration.executor. The SDK marksexecutoras@hidden, and#setToolCallRequestHandler()overridestools/call, so the variant tests a path that the server never runs. -
In
tests/utils/TaskRunner.test.ts, drop the{timeout: 30_000}added to the top-leveldescribe. The new tests usesettle()and resolve in milliseconds, and the change affects the existing tests in the suite. -
In
src/ToolHandler.tshandle(), shorten the four-sentence inline comment beforeexecutionto one sentence and move the trade-off text to the TSDoc ofhandle().AGENTS.mdlimits inline comments to one sentence, and the trade-off is part of the method contract. -
In
src/ToolHandler.tshandle(), log the cancellation (logger?.(\${tool.name} cancelled`)) before thecatchblock rethrowssignal.reason. Thecatch` block now skips the error log on abort, so a cancelled call leaves no log line at all. -
In
src/ToolHandler.tsrejectOnAbort(), return{promise, [Symbol.dispose]}instead ofObject.assign(promise, {...}). Adding a property to aPromiseinstance hides theDisposablein the type intersection and is not a pattern used elsewhere insrc/. -
In
tests/ToolHandler.test.ts, moveawait new Promise(resolve => setImmediate(resolve))(three copies) to asettle()helper intests/utils.tsand reuse it fromtests/utils/TaskRunner.test.ts, which already defines the same function.AGENTS.mdrequires one helper for a repeated block. -
In
tests/ToolHandler.test.ts("skips work after page cancellation"), assertnotCalledonMcpResponse.prototype.setPage(via a spy) instead ofrun.AGENTS.mdrequires thenotCalledtarget to be the first method called after the step under test, andresponse.setPage()runs beforetool.handler. -
In
tests/McpServer.test.tsandtests/index.test.ts, replace the assertions onSdkError/SdkErrorCode.RequestTimeoutwith a check thatpendingrejects and that the server-side signal is aborted. The mapping of an aborted request toRequestTimeoutis SDK-internal and changes between SDK versions. -
In
tests/index.test.ts, removeserver.restore(). TheTestServeris new in the test, so there is no state to restore.
OrKoN
left a comment
There was a problem hiding this comment.
we probably still want telemetry for cancelled logs (currently seems to be skipped)
735c77b to
e8f591a
Compare
|
@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. |
3744a08 to
f35ec80
Compare
|
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 PTAL. Thanks! |
OrKoN
left a comment
There was a problem hiding this comment.
Please check the following:
-
In
src/ToolHandler.tshandle(), remove theif (!signal.aborted)check infinallyand update thelogToolInvocationassertions intests/ToolHandler.test.tsand the PR description. Telemetry must still record cancelled tool invocations withsuccess: false, whilesignal.throwIfAborted()in#runBrowserTool()prevents the abandoned execution from collecting DevTools data later. -
In
src/index.ts#registerTool(), revert(args, ctx) => handler.handle(args, {signal: ctx.mcpReq.signal})back toargs => handler.handle(args)and update the PR description to state that signal forwarding happens in#setToolCallRequestHandler().#setToolCallRequestHandler()overrides thetools/callhandler, so the callback in#registerTool()never receives MCP requests and has no test coverage.
f35ec80 to
7a2ec1d
Compare
|
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. |
7a2ec1d to
dc7c24a
Compare
|
@zyzyzyryxy or @Lightning00Blade could you please review and land next week? |
dc7c24a to
4fa7cc6
Compare
OrKoN
left a comment
There was a problem hiding this comment.
Please check the following:
-
Replace
rejectOnAbortinsrc/ToolHandler.tswith the existingraceWithSignalhelper fromsrc/tools/input.ts, moved tosrc/utils/. Both race a promise againstsignal.reasonand remove the listener on settle; the repository rule is one helper per repeated block. -
Update the TSDoc of
ToolHandler.#raceWithTimeoutto state that the race also ends onsignalabort and that abort does not callonTimeout(). The current text describes only the timeout. -
Remove the e2e test
cancels a request and resumes its queue after evaluation settlesintests/index.test.ts.tests/McpServer.test.tsalready covers the SDK cancellation path (same_onrequestcode overInMemoryTransport) andtests/ToolHandler.test.tscovers queue retention; the e2e test launches Chrome under a 90 s budget and its assertions cannot prove serialization becausefinish.resolve()runs beforelist_pagesis awaited. -
Remove the
{timeout: 30_000}options on thecancellationdescribe intests/ToolHandler.test.tsand on the dispatcher test intests/McpServer.test.ts.scripts/test.jspasses--test-timeout=120000, so a per-test value only lowers the budget. -
Nit:
TaskRunner.#cancelEntry(entry, reason: Error)receivessignal.reason, which the SDK sets to the string fromnotifications/cancelledparams.reason(see_oncancel). Type the parameterunknown, or document onTaskQueue.scheduleTaskthat a cancelled task can reject with a non-Errorvalue. 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
left a comment
There was a problem hiding this comment.
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.
e640d38 to
5214ff2
Compare
🤖 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]>
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
noneremain 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.