Every Effect.fn and withSpan call rebuilds the fiber context cache
メンテナーはふだん 1 日以内に返信
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 30/100
- issue の種類
- バグ
- 明瞭さ
- 明確に書かれている
- 活発さ
- 停滞
- 技術スタック
- node.js, typescript
- 領域
- performance
調査の方向性
Start with setContext and makeFiberContextCache in packages/effect/src/internal/effect.ts, then read CurrentStackFrameKey and ParentSpanKey in packages/effect/src/internal/fiberCachedKeys.ts. The reproduction files and benchmark results in the issue show the affected calls and how to measure them. The issue says a pull request with the change and tests follows, so check linked PR #11069 for the current implementation and tests.
索引モデルが issue の本文から書いたものです。
説明
What happens
CurrentStackFrame and ParentSpan are fiber-cached keys, so Context.add of either starts a new cache root, and FiberImpl.setContext then calls makeFiberContextCache, which reads all eleven cached keys from the new context. Every Effect.fn call adds a stack frame, and every span adds a parent span, so each traced call rebuilds the whole cache although only one field changed. With nested calls the context is an overlay chain, so each of those reads walks the chain before reaching the base map.
The rows with Error.stackTraceLimit = 0 switch off the call-site stack capture, which otherwise dominates the timing, so that the rest of the call can be read on its own: six nested Effect.fn calls take 2.7 µs there, against 0.8 µs for six nested Effect.fnUntraced calls.
Measurements
Measured on main at ddc5b58 (4.1.7), Node.js 24.22, Apple silicon. Bytes are heap growth per operation with no collection during the loop, median of seven rounds. Timings were taken on a machine under other load and vary by about 20% between runs.
| Case | main | with change |
|---|---|---|
Effect.fnUntraced call (for scale) |
598 B, 172 ns | 598 B, 195 ns |
Effect.fn call, no span |
2,049 B, 945 ns | 1,959 B, 857 ns |
Effect.fn("named") call |
4,359 B, 1,674 ns | 4,183 B, 1,634 ns |
6 nested Effect.fn calls, no span |
12,355 B, 5,782 ns | 11,785 B, 5,370 ns |
6 nested Effect.fn("named") calls |
25,053 B, 10,747 ns | 24,013 B, 9,090 ns |
Effect.fn call, no span, Error.stackTraceLimit = 0 |
1,868 B, 512 ns | 1,773 B, 397 ns |
Effect.fn("named") call, Error.stackTraceLimit = 0 |
4,083 B, 1,258 ns | 3,880 B, 1,024 ns |
6 nested Effect.fn calls, no span, Error.stackTraceLimit = 0 |
10,470 B, 2,689 ns | 9,916 B, 1,837 ns |
6 nested Effect.fn("named") calls, Error.stackTraceLimit = 0 |
22,976 B, 8,677 ns | 22,072 B, 5,908 ns |
Reproduction
Save the two files below in packages/effect/alloc-repro/ in a checkout of this repository and run:
node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 fn-nested.repro.ts
harness.ts
/**
* Shared measurement helper: bytes and nanoseconds per operation.
* node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 <file>.ts
* Heap growth is read across N operations with a forced GC before and a young
* generation large enough that no collection runs in between: the
* operation count is cut so one round stays under BUDGET bytes.
*/
import * as Effect from "effect/Effect"
const gc = (globalThis as { gc?: () => void }).gc
if (gc === undefined) throw new Error("run with --expose-gc")
export const ROUNDS = 7
const BUDGET = 256 * 1024 * 1024
const sized = (n: number, probeBytes: number) => Math.max(50, Math.min(n, Math.floor(BUDGET / Math.max(probeBytes, 1))))
const median = (xs: Array<number>) => xs.toSorted((a, b) => a - b)[Math.floor(xs.length / 2)]
export const row = (label: string, bytes: number, ns: number) =>
console.log(`${label.padEnd(64)} ${bytes.toFixed(0).padStart(8)} B/op ${ns.toFixed(0).padStart(8)} ns/op`)
/** Measures a synchronous operation. */
export const measureSync = (label: string, n: number, op: (i: number) => unknown) => {
for (let i = 0; i < 5000; i++) op(i)
gc()
const probe = process.memoryUsage().heapUsed
for (let i = 0; i < 50; i++) op(i)
n = sized(n, (process.memoryUsage().heapUsed - probe) / 50)
const bytes: Array<number> = []
const nanos: Array<number> = []
for (let r = 0; r < ROUNDS; r++) {
gc()
const before = process.memoryUsage().heapUsed
const start = process.hrtime.bigint()
for (let i = 0; i < n; i++) op(i)
const end = process.hrtime.bigint()
bytes.push((process.memoryUsage().heapUsed - before) / n)
nanos.push(Number(end - start) / n)
}
row(label, median(bytes), median(nanos))
return median(bytes)
}
/** Measures an Effect run `n` times inside one fiber, so the fiber context is the one supplied by `wrap`. */
export const measureEffect = <E, R>(
label: string,
n: number,
op: (i: number) => Effect.Effect<unknown, E, R>,
wrap: (self: Effect.Effect<void, E, R>) => Effect.Effect<void, E, never>
) => {
const bytes: Array<number> = []
const nanos: Array<number> = []
const loop = (count: number) =>
Effect.gen(function*() {
for (let i = 0; i < count; i++) yield* op(i)
})
const program = Effect.gen(function*() {
yield* loop(5000)
gc()
const probe = process.memoryUsage().heapUsed
yield* loop(50)
n = sized(n, (process.memoryUsage().heapUsed - probe) / 50)
for (let r = 0; r < ROUNDS; r++) {
gc()
const before = process.memoryUsage().heapUsed
const start = process.hrtime.bigint()
yield* loop(n)
const end = process.hrtime.bigint()
bytes.push((process.memoryUsage().heapUsed - before) / n)
nanos.push(Number(end - start) / n)
}
})
Effect.runSync(wrap(program))
row(label, median(bytes), median(nanos))
return median(bytes)
}
fn-nested.repro.ts
/**
* Effect.fn: cost of a traced call, alone and nested, against Effect.fnUntraced.
* The stack capture is switched off for the second half so that the rest of the
* call can be read on its own.
*
* node --expose-gc --min-semi-space-size=1024 --max-semi-space-size=1024 fn-nested.repro.ts
*/
import * as Effect from "effect/Effect"
import { measureEffect } from "./harness.ts"
const N = 20000
const id = <A, E>(self: Effect.Effect<A, E>) => self
const step = Effect.sync(() => 1)
const untraced = Effect.fnUntraced(function*(n: number) {
return (yield* step) + n
})
const unnamed = Effect.fn(function*(n: number) {
return (yield* step) + n
})
const named = Effect.fn("named")(function*(n: number) {
return (yield* step) + n
})
const nest = (
make: (body: (n: number) => Generator<Effect.Effect<number>, number, number>) => (n: number) => Effect.Effect<number>,
depth: number
) => {
let f = make(function*(n) {
return (yield* step) + n
})
for (let i = 1; i < depth; i++) {
const inner = f
f = make(function*(n) {
return yield* inner(n)
})
}
return f
}
const untraced6 = nest((body) => Effect.fnUntraced(body), 6)
const unnamed6 = nest((body) => Effect.fn(body), 6)
const named6 = nest((body) => Effect.fn("named")(body), 6)
const withSpan = (n: number) => Effect.withSpan(untraced(n), "span", { captureStackTrace: false })
const limit = Error.stackTraceLimit
for (const label of ["default", "stackTraceLimit 0"]) {
if (label !== "default") Error.stackTraceLimit = 0
measureEffect(`${label}: Effect.fnUntraced call`, N, (i) => untraced(i), id)
measureEffect(`${label}: Effect.fn call, no span`, N, (i) => unnamed(i), id)
measureEffect(`${label}: Effect.fn("named") call`, N, (i) => named(i), id)
measureEffect(`${label}: Effect.withSpan, no stack capture`, N, withSpan, id)
measureEffect(`${label}: 6 nested Effect.fnUntraced calls`, N, (i) => untraced6(i), id)
measureEffect(`${label}: 6 nested Effect.fn calls, no span`, N, (i) => unnamed6(i), id)
measureEffect(`${label}: 6 nested Effect.fn("named") calls`, N, (i) => named6(i), id)
}
Error.stackTraceLimit = limit
Cause
setContext and makeFiberContextCache in packages/effect/src/internal/effect.ts, with CurrentStackFrameKey and ParentSpanKey in packages/effect/src/internal/fiberCachedKeys.ts.
Possible fix
When the new context is the previous one plus a single overlay entry for CurrentStackFrame or ParentSpan, copy the previous root's cache with that one field replaced. Fiber.Cache keeps its shape and is still computed once per cache root.
Context
Found by profiling traced calls after CPU profiles of a production Node.js service on effect 4.0.1 showed Effect.fn wrappers among the larger costs. A pull request with the change and tests follows.
- 主要言語
- TypeScript
- スター
- 16.7k
- フォーク
- 808
- 平均マージ
- 21時間 22分
- マージ済み PR(30日)
- 486
環境構築
このプロジェクトには開発コンテナ、Dockerfile、コントリビューションガイドがありません。まず README を読み、一般的な手順ははじめてのコントリビューションガイドを参照してください。
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
Effect-TS/effect のほかの issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 68/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
`@effect/ui-native` (Effect-TS/ui): `kit/VirtualList` `list` part widens `R` to `any`, poisoning enclosing components対応中かも @effect-bot が今日担当しました。 オープン
Effect-TS/effect#11097 · 担当者 1 名 ·
メンテナーはふだん 1 日以内に返信
-
`@effect/ui-native` (Effect-TS/ui): Controlled `input` rejected-edit restore never calls `host.commit()`対応中かも @effect-bot が今日担当しました。 オープン
Effect-TS/effect#11096 · 担当者 1 名 ·
メンテナーはふだん 1 日以内に返信
Effect-TS/effect の issue をすべて見る
似ている issue
-
check:failed streams:edit
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
iptv-org/iptv#60585 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 67/100
メンテナーはふだん 1 日以内に返信
-
[Bug]: Critical path skips a child span that ends exactly when the next one starts対応中かも @Piyush4801 が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
jaegertracing/jaeger-ui#4865 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
bug
難易度 2/5 1〜3時間 初心者へのやさしさ 90/100
anthropics/claude-code#112972 ·
-
Type: Improvement
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
メンテナーはふだん 1 日以内に返信