nodejs / nodejs/node

AsyncLocalStorage is captured on the first console.log which prevents garbage collection of objects in the storage

オープン
#48,651 コメント 4 件 リアクション 3 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

async_hooks
主要言語
JavaScript
スター
122k
フォーク
37.3k
平均マージ
4日 2時間
マージ済み PR(30日)
283

説明

Version

v20.3.0

Platform

Linux 5.19.0-46-generic #47~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC Wed Jun 21 15:35:31 UTC 2 x86_64 x86_64 x86_64 GNU/Linux

Subsystem

async_hooks

What steps will reproduce the bug?

Run the following with node --expose-gc:

import { AsyncLocalStorage } from "node:async_hooks";

const storage = new AsyncLocalStorage();

const finalizer = new FinalizationRegistry((token) => {
    console.log("COLLECTED", token);
});

const wr = new WeakRef({});
finalizer.register(wr.deref(), "obj");

// Whether COLLECTED is printed depends on whether this is present or not
// console.log("OUTER LOG");

storage.run({ obj: wr.deref() }, () => {
    console.log(storage.getStore()?.obj);
});

await new Promise((resolve) => setTimeout(resolve, 1000));

gc();
How often does it reproduce? Is there a required condition?

This happens consistently.

What is the expected behavior? Why is that the expected behavior?

The object stored in the WeakRef should be collected when gc() is hit, but whether this happens depends on whether the line:

// console.log("OUTER LOG");

is commented or not.

What do you see instead?

The object is not collected if the first console.log happens under the storage.run callback.

Additional information

For whatever reason wherever the first console.log happens this is where the async resource for the TTY is made. This causes objects in the AsyncLocalStorage to be eternally referenced and never eligible for garbage collection.

To allow GC of values in AsyncLocalStorage, the fix here would be to simply create the TTY's async resource using the root's async scope rather than whatever happens to be active.

(I can't see large reason why the current behaviour would be desirable as it just makes GC of values dependent on first console.log. If anyone needed such behaviour legitimately it'd make more sense to expose an initTTY function or similar that captures the async scope at that time).

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、提供された再現手順を node --expose-gc で実行し、最初の console.log によって作成される TTY リソースの async_hooks による処理を調べます。そのリソースがアクティブな async scope をどのようにキャプチャするかを追跡します。外側の console.log が先に実行されるかどうかにかかわらずオブジェクトが回収可能になり、両方のケースに対するリグレッションテストが用意されていれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
javascript
領域
backend
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
活発
明瞭さ
おおむね明確
初心者へのやさしさ
52/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。