Skip to content

fix: memory leak in mainThreadTask - #331198

Draft
Simon Siefke (SimonSiefke) wants to merge 27 commits into
microsoft:mainfrom
SimonSiefke:fix/memory-leak-mainThreadTask
Draft

Simon Siefke (SimonSiefke) wants to merge 27 commits into
microsoft:mainfrom
SimonSiefke:fix/memory-leak-mainThreadTask

Conversation

@SimonSiefke

Copy link
Copy Markdown
Contributor

Details

The same AbstractTaskService is reused when the extension host restarts. Its task-system registrations kept callbacks from the old MainThreadTask instance in memory after each restart.

Change

registerTaskSystem now returns a disposable. MainThreadTask registers it for cleanup, so its callbacks are unregistered when the instance is disposed.

Before

Restarting extensions 37 times retained one additional set of uriProvider, resolveVariables, and findExecutable callbacks per restart:

extensions-restart-before-highlighted

After

The matching task-system callback growth is gone (162 rows before, 159 unrelated rows after).

extensions-restart-after

Test Video

test.mp4

Copilot AI balanced review requested due to automatic review settings August 17, 2026 12:45

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.

Pull request overview

Note

Copilot was unable to run its full agentic suite in this review.

This PR makes task system registrations disposable so callers can unregister task systems automatically (e.g., when the registering component is disposed).

Changes:

  • Change ITaskService.registerTaskSystem to return an IDisposable.
  • Implement unregister-on-dispose behavior in AbstractTaskService.registerTaskSystem.
  • Register the returned disposable in MainThreadTask and add a test to verify disposal unregisters task systems.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
src/vs/workbench/contrib/tasks/common/taskService.ts Updates the task service interface to return an IDisposable for task system registrations.
src/vs/workbench/contrib/tasks/browser/abstractTaskService.ts Returns a disposable that removes task system info from the internal registry on dispose.
src/vs/workbench/api/browser/mainThreadTask.ts Registers the task system disposable so it’s cleaned up when MainThreadTask is disposed.
src/vs/workbench/api/test/browser/mainThreadTask.test.ts Adds a unit test ensuring task system registrations are disposed/unregistered.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@dmitrivMS Dmitriy Vasyura (dmitrivMS) added freeze-slow-crash-leak VS Code crashing, performance, freeze and memory leak issues tasks Task system issues labels Sep 24, 2026
@dmitrivMS

Copy link
Copy Markdown
Collaborator

Potential remote-startup regression: removal can release task-system readiness

The new removal notification addresses the earlier review feedback, but it changes an assumption made by the readiness consumers.

At reviewed head 5107382b1fc7de88a7394d0632c4f3796959de23:

Consequently, if one host is disposed before initial remote readiness, its removal can release pending task discovery and automatic-task startup. getWorkspaceTasks awaits the now-resolved promise; configuration parsing falls back to the client platform when the folder's system info is absent. For example, a Windows client / Linux remote can select the wrong platform-specific task configuration during that interval.

Suggested deterministic reproduction / regression test (not yet executed)

  1. Initialize the task service's real readiness consumer with a nonempty remoteAuthority. Satisfy the other task-discovery prerequisites, but hold the remote host's first task-system registration pending.
  2. Register only the local host's task system. Confirm hasTaskSystemInfo === false and readiness is still pending.
  3. Dispose the local MainThreadTask bridge before allowing the remote registration or any local replacement. In the candidate this disposes the registration it owns.
  4. Flush pending promise continuations while keeping the remote registration held. Expected: readiness remains pending. From the current code: the removal event resolves _whenTaskSystemReady despite hasTaskSystemInfo === false. A waiting automatic-task consumer is likewise released.
  5. To exercise the downstream impact, use a remote-folder task with distinct harmless windows and linux overrides, and allow discovery to finish during that gap. Then release the remote registration before creating a replacement local host.

The ordering in step 5 matters for the baseline comparison: at true base e6a38b7e53d487c90c842a442ff7345820d26065, disposing the bridge does not unregister its info or emit a removal event. In this sequence, readiness is not released until the remote registration arrives, when the remote platform information is available. The separate pre-existing case where a replacement local registration arrives first does not negate this newly introduced removal-triggered path.

Please preserve removal notifications, but make the readiness consumers wait for a notification where hasTaskSystemInfo is actually true, and cover teardown before initial remote readiness. The new service-level [true, false] test checks notification delivery, but its Object.create(...) setup does not construct or exercise the readiness promise.

Validation scope: this is a source-backed, medium-severity correctness concern. The proposed sequence has not been run in Code OSS or as a unit test; no live reproduction or measured task failure is claimed.

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 consider feedback in the comment

@SimonSiefke
Simon Siefke (SimonSiefke) marked this pull request as draft October 5, 2026 16:36
@SimonSiefke

Copy link
Copy Markdown
Contributor Author

Added a separate PR #342418 to fix a task system race condition which should address the review feedback from this PR.

Megan Rogge (meganrogge) added a commit that referenced this pull request Oct 30, 2026
This PR is needed for #331198 

<br>


### Details

A task-system change notification can arrive before the required task
systems are ready. Readiness can also change before an awaiting callback
resumes, or the automatic-task contribution can be disposed while it
waits. These cases can start task discovery too early or after disposal.

### Change

Wait for notifications that satisfy `hasTaskSystemInfo`, recheck
readiness after each wait, and dispose pending listeners with their
owner. Stop automatic-task startup when the contribution has been
disposed.

### Before

Four readiness regression tests fail on the base branch: a removal
notification resolves readiness too early, automatic tasks start before
remote readiness, and pending startup work continues or leaves a
listener after disposal.

### After

All five readiness tests pass, including local startup, changes before
remote readiness, and disposal before or immediately after readiness.

### Test Video


https://github.com/user-attachments/assets/7a5a4570-74a6-4000-b2c5-7fc0d10af4fd

<br>

<sub>AI disclosure: Model: GPT-6.1 Sol. Worktime: 13 min</sub>
Preserve both task test suites and the readiness disposal guard. Dispose task-system registrations and command registrations in the integrated test fixtures.
@SimonSiefke
Simon Siefke (SimonSiefke) marked this pull request as ready for review October 30, 2026 22:27
@SimonSiefke

Copy link
Copy Markdown
Contributor Author

With the other PR merged, all feedback should be all addressed now!

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.

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 consider review comments

@SimonSiefke
Simon Siefke (SimonSiefke) marked this pull request as draft November 3, 2026 10:30
// Execution needs a live host; platform-only task discovery does not.
while (!this._store.isDisposed) {
const info = this._getTaskSystemInfo(key);
if (info || (key !== Schemas.vscodeRemote && !this._taskSystemPlatforms.has(key))) {

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.

Could execution require a compatible native registration here, rather than accepting any surviving registration for the scheme?

After a remote-native-only extension-host crash, a Web worker can remain registered under vscode-remote. Removing the native registration promotes that worker, so this condition immediately calls the execution callback with Platform.Web. On a Windows remote, TerminalTaskSystem then takes the Linux default-shell-profile branch and skips Windows shell-argument/process-executable handling. The remote pty host is separate from the extension host, so terminal creation can still proceed.

This is distinct from the earlier task-discovery/platform-cache issue, which the new metadata separation addresses. Before this PR the stale native registration's RPC rejected; the regression is substituting an incompatible execution provider, not breaking a previously successful crash-window run.

Suggested regression test (not executed): register native Windows and Web systems for the same remote workspace, dispose only the native registration while keeping the worker, then launch/rerun a shell or process task before native replacement. Verify that native execution does not use Web/Linux platform handling, then restore the native registration and verify correct execution. A global Restart Extension Host command may stop both hosts and miss this ordering.

Source-backed finding at 0f238cf; no runtime reproduction claimed.

return callback(info);
}
await Event.toPromise(Event.any(this.onDidChangeTaskSystemInfo,
listener => this._taskSystemInfoCancellation.onCancellationRequested(listener)));

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.

Could this wait also settle when the task is cancelled or the native host will not be restarted?

For a previously registered scheme with no surviving registration, this loop only wakes on registration changes or whole-task-service disposal. If the host never returns (for example after automatic restart is exhausted), the task stays pending indefinitely. TerminalTaskSystem inserts its active-task entry before awaiting execution and removes it in the execution promise's finally; that cleanup cannot run while this wait is pending. Terminate returns failure because no terminal exists yet, retries encounter the existing-instance policy, and manually restoring the host later can launch the abandoned request.

Before this change the stale host RPC rejected and the execution promise settled, allowing the active entry to be removed. The new indefinite wait therefore introduces a lifecycle regression, rather than merely preserving the existing host-loss failure.

Suggested regression test (not executed): remove the last native registration after initial readiness, run a configured task while withholding replacement, then cancel/terminate it. Verify the execution settles and the active entry is cleared; registering a replacement afterward must not launch the cancelled request. Cover both remote and previously registered local schemes, since retained platform metadata makes both enter this wait.

Source-backed finding at 0f238cf; no runtime reproduction claimed. Cancellation tied only to task-service disposal does not cover this task-level lifetime.

Dmitrii F. (lingeniare) pushed a commit to lingeniare/vegaide that referenced this pull request Nov 7, 2026
This PR is needed for microsoft/vscode#331198 

<br>


### Details

A task-system change notification can arrive before the required task
systems are ready. Readiness can also change before an awaiting callback
resumes, or the automatic-task contribution can be disposed while it
waits. These cases can start task discovery too early or after disposal.

### Change

Wait for notifications that satisfy `hasTaskSystemInfo`, recheck
readiness after each wait, and dispose pending listeners with their
owner. Stop automatic-task startup when the contribution has been
disposed.

### Before

Four readiness regression tests fail on the base branch: a removal
notification resolves readiness too early, automatic tasks start before
remote readiness, and pending startup work continues or leaves a
listener after disposal.

### After

All five readiness tests pass, including local startup, changes before
remote readiness, and disposal before or immediately after readiness.

### Test Video


https://github.com/user-attachments/assets/7a5a4570-74a6-4000-b2c5-7fc0d10af4fd

<br>

<sub>AI disclosure: Model: GPT-6.1 Sol. Worktime: 13 min</sub>
Preserve task system registration disposal tests alongside upstream task provider timeout regression coverage.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

freeze-slow-crash-leak VS Code crashing, performance, freeze and memory leak issues tasks Task system issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants