Skip to content

Commit 30aa6ef

Browse files
committed
fix(server): flatten tracing context before background forks
1 parent 87b5ae4 commit 30aa6ef

3 files changed

Lines changed: 129 additions & 69 deletions

File tree

‎apps/server/src/preview/PortScanner.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ import * as Semaphore from "effect/Semaphore";
3939
import { FetchHttpClient, HttpClient } from "effect/unstable/http";
4040

4141
import * as ProcessRunner from "../processRunner.ts";
42-
import { withDetachedSpan } from "../serverActivation.ts";
42+
import { forkScopedDetached } from "../serverActivation.ts";
4343

4444
export class PortDiscovery extends Context.Service<
4545
PortDiscovery,
@@ -587,9 +587,7 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
587587

588588
// Single layer-scoped polling fiber. Ticks are no-ops when no client is
589589
// currently retained, so the cost is one Ref.get every POLL_INTERVAL.
590-
yield* Effect.forkScoped(
591-
withDetachedSpan(pollTick.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL)))),
592-
);
590+
yield* forkScopedDetached(pollTick.pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
593591

594592
const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
595593
const wasIdle = yield* Ref.modify(stateRef, (state) => [

‎apps/server/src/serverActivation.test.ts‎

Lines changed: 111 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { expect, it } from "@effect/vitest";
2+
import * as Context from "effect/Context";
23
import * as Deferred from "effect/Deferred";
34
import * as Effect from "effect/Effect";
5+
import * as Fiber from "effect/Fiber";
46
import * as Option from "effect/Option";
57
import * as Tracer from "effect/Tracer";
68

7-
import { forkParked, ServerActivation, withDetachedSpan } from "./serverActivation.ts";
9+
import { forkParked, ServerActivation, forkScopedDetached } from "./serverActivation.ts";
810

911
it.effect("forkParked detaches the activation wait and keeps the same root after release", () =>
1012
Effect.scoped(
@@ -59,50 +61,58 @@ it.effect("proves a root is parked before returning and releases it with one gat
5961
),
6062
);
6163

62-
it.effect("withDetachedSpan re-roots instead of inheriting the ambient ParentSpan", () =>
63-
Effect.gen(function* () {
64-
const ambient = Tracer.externalSpan({
65-
traceId: "00000000000000000000000000000001",
66-
spanId: "0000000000000001",
67-
sampled: true,
68-
});
69-
70-
const detachedSpanId = yield* Effect.serviceOption(Tracer.ParentSpan).pipe(
71-
Effect.map(Option.map((span) => span.spanId)),
72-
withDetachedSpan,
73-
Effect.provideService(Tracer.ParentSpan, ambient),
74-
);
75-
expect(Option.isSome(detachedSpanId)).toBe(true);
76-
if (Option.isSome(detachedSpanId)) {
77-
expect(detachedSpanId.value).not.toBe("0000000000000001");
78-
}
79-
80-
const stillHasParent = yield* Effect.serviceOption(Tracer.ParentSpan).pipe(
81-
Effect.map(Option.map((span) => span.spanId)),
82-
Effect.provideService(Tracer.ParentSpan, ambient),
83-
);
84-
expect(Option.isSome(stillHasParent)).toBe(true);
85-
if (Option.isSome(stillHasParent)) {
86-
expect(stillHasParent.value).toBe("0000000000000001");
87-
}
88-
}),
64+
it.effect("forkScopedDetached re-roots instead of inheriting the ambient ParentSpan", () =>
65+
Effect.scoped(
66+
Effect.gen(function* () {
67+
const ambient = Tracer.externalSpan({
68+
traceId: "00000000000000000000000000000001",
69+
spanId: "0000000000000001",
70+
sampled: true,
71+
});
72+
73+
const detachedSpanId = yield* Effect.serviceOption(Tracer.ParentSpan).pipe(
74+
Effect.map(Option.map((span) => span.spanId)),
75+
forkScopedDetached,
76+
Effect.flatMap(Fiber.join),
77+
Effect.provideService(Tracer.ParentSpan, ambient),
78+
);
79+
expect(Option.isSome(detachedSpanId)).toBe(true);
80+
if (Option.isSome(detachedSpanId)) {
81+
expect(detachedSpanId.value).not.toBe("0000000000000001");
82+
}
83+
84+
const stillHasParent = yield* Effect.serviceOption(Tracer.ParentSpan).pipe(
85+
Effect.map(Option.map((span) => span.spanId)),
86+
Effect.provideService(Tracer.ParentSpan, ambient),
87+
);
88+
expect(Option.isSome(stillHasParent)).toBe(true);
89+
if (Option.isSome(stillHasParent)) {
90+
expect(stillHasParent.value).toBe("0000000000000001");
91+
}
92+
}),
93+
),
8994
);
9095

91-
it.effect("withDetachedSpan keeps ParentSpan-requiring effects working under the fresh root", () =>
92-
Effect.gen(function* () {
93-
const span = yield* Effect.service(Tracer.ParentSpan).pipe(
94-
withDetachedSpan,
95-
Effect.provideService(
96-
Tracer.ParentSpan,
97-
Tracer.externalSpan({
98-
traceId: "00000000000000000000000000000001",
99-
spanId: "0000000000000001",
100-
sampled: true,
101-
}),
102-
),
103-
);
104-
expect(span.spanId).not.toBe("0000000000000001");
105-
}),
96+
it.effect(
97+
"forkScopedDetached keeps ParentSpan-requiring effects working under the fresh root",
98+
() =>
99+
Effect.scoped(
100+
Effect.gen(function* () {
101+
const span = yield* Effect.service(Tracer.ParentSpan).pipe(
102+
forkScopedDetached,
103+
Effect.flatMap(Fiber.join),
104+
Effect.provideService(
105+
Tracer.ParentSpan,
106+
Tracer.externalSpan({
107+
traceId: "00000000000000000000000000000001",
108+
spanId: "0000000000000001",
109+
sampled: true,
110+
}),
111+
),
112+
);
113+
expect(span.spanId).not.toBe("0000000000000001");
114+
}),
115+
),
106116
);
107117

108118
it.effect("forkParked roots do not inherit the ambient ParentSpan", () =>
@@ -130,3 +140,61 @@ it.effect("forkParked roots do not inherit the ambient ParentSpan", () =>
130140
}),
131141
),
132142
);
143+
144+
// Inspect actual context references, including Effect's overlay/base/cache roots.
145+
// Service lookup alone hides replaced spans that are still retained underneath.
146+
const retainsReference = (root: unknown, target: object): boolean => {
147+
const seen = new Set<object>();
148+
const pending: unknown[] = [root];
149+
while (pending.length > 0) {
150+
const value = pending.pop();
151+
if (value === target) return true;
152+
if (typeof value !== "object" || value === null || seen.has(value)) continue;
153+
seen.add(value);
154+
pending.push(...(value instanceof Map ? value.values() : Object.values(value)));
155+
}
156+
return false;
157+
};
158+
159+
for (const gated of [false, true]) {
160+
it.effect(`forkParked drops retained parent references (${gated ? "gated" : "immediate"})`, () =>
161+
Effect.gen(function* () {
162+
const ambient = Tracer.externalSpan({ traceId: "ambient", spanId: "ambient" });
163+
const marker = Context.Service<{ readonly value: number }>("test/detached-marker");
164+
const service = { value: 42 };
165+
const observed = yield* Deferred.make<Context.Context<never>>();
166+
const stopped = yield* Deferred.make<void>();
167+
yield* Effect.scoped(
168+
Effect.gen(function* () {
169+
const observe = Effect.context<never>().pipe(
170+
Effect.flatMap((context) => Deferred.succeed(observed, context)),
171+
Effect.andThen(Effect.never),
172+
Effect.ensuring(Deferred.succeed(stopped, undefined)),
173+
);
174+
yield* forkParked(gated ? Effect.void : observe).pipe(
175+
Effect.provideService(ServerActivation, gated ? observe : undefined),
176+
Effect.provideService(marker, service),
177+
Effect.provideService(Tracer.ParentSpan, ambient),
178+
);
179+
const context = yield* Deferred.await(observed);
180+
expect(Context.getUnsafe(context, marker)).toBe(service);
181+
expect(retainsReference(context, ambient)).toBe(false);
182+
}),
183+
);
184+
expect(yield* Deferred.isDone(stopped)).toBe(true);
185+
}),
186+
);
187+
}
188+
189+
it.effect("forkScopedDetached gives the child a detached context before it starts", () =>
190+
Effect.scoped(
191+
Effect.gen(function* () {
192+
const ambient = Tracer.externalSpan({ traceId: "ambient", spanId: "ambient" });
193+
yield* Effect.gen(function* () {
194+
const fiber = yield* forkScopedDetached(Effect.never);
195+
expect(retainsReference(fiber.context, ambient)).toBe(false);
196+
expect(yield* Tracer.ParentSpan).toBe(ambient);
197+
}).pipe(Effect.provideService(Tracer.ParentSpan, ambient));
198+
}),
199+
),
200+
);
Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as Context from "effect/Context";
22
import * as Deferred from "effect/Deferred";
33
import * as Effect from "effect/Effect";
4+
import type * as Fiber from "effect/Fiber";
45
import type * as Scope from "effect/Scope";
56
import * as Tracer from "effect/Tracer";
67
import * as NodeCrypto from "node:crypto";
@@ -10,27 +11,24 @@ export class ServerActivation extends Context.Reference<Effect.Effect<void> | un
1011
{ defaultValue: () => undefined },
1112
) {}
1213

13-
// Detached background work runs under a fresh stateless root instead of the
14-
// ambient ParentSpan, so long-lived fibers never pin the short-lived span that
15-
// happened to be ambient at fork time (#5410). An external span carries only
16-
// trace/span ids and never accumulates children, so unlike a live startup span
17-
// it cannot pin unbounded tracing state. Re-rooting (instead of omitting
18-
// ParentSpan from the context) keeps every effect working: effects that
19-
// explicitly require a ParentSpan observe the fresh root instead of dying with
20-
// Service-not-found, which makes the Exclude in the return type honest.
21-
export const withDetachedSpan = <A, E, R>(
14+
// Replace and flatten the context before forking: Context.add retains the old
15+
// parent in its overlay, while providing inside the child retains a restoration
16+
// frame for the lifetime of the work. The external root does not collect children.
17+
export const forkScopedDetached = <A, E, R>(
2218
effect: Effect.Effect<A, E, R>,
23-
): Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>> =>
24-
Effect.flatMap(
25-
Effect.sync(() => {
19+
): Effect.Effect<Fiber.Fiber<A, E>, never, Scope.Scope | Exclude<R, Tracer.ParentSpan>> =>
20+
Effect.updateContext(
21+
Effect.forkScoped(effect),
22+
(context: Context.Context<Scope.Scope | Exclude<R, Tracer.ParentSpan>>) => {
2623
const traceId = NodeCrypto.randomUUID().replaceAll("-", "");
27-
return Tracer.externalSpan({
24+
const root = Tracer.externalSpan({
2825
traceId,
2926
spanId: traceId.slice(0, 16),
3027
sampled: true,
3128
});
32-
}),
33-
(root) => Effect.provideService(effect, Tracer.ParentSpan, root),
29+
const detached = Context.add(context, Tracer.ParentSpan, root);
30+
return Context.makeUnsafe<Scope.Scope | R>(new Map(detached.mapUnsafe));
31+
},
3432
);
3533

3634
/** Forks a long-running root before commit and proves it is parked at the activation boundary. */
@@ -40,16 +38,12 @@ export const forkParked = <A, E, R>(
4038
Effect.gen(function* () {
4139
const activation = yield* ServerActivation;
4240
if (activation === undefined) {
43-
yield* Effect.forkScoped(withDetachedSpan(effect));
41+
yield* forkScopedDetached(effect);
4442
return;
4543
}
4644
const parked = yield* Deferred.make<void>();
47-
yield* Effect.forkScoped(
48-
Deferred.succeed(parked, undefined).pipe(
49-
Effect.andThen(activation),
50-
Effect.andThen(effect),
51-
withDetachedSpan,
52-
),
45+
yield* forkScopedDetached(
46+
Deferred.succeed(parked, undefined).pipe(Effect.andThen(activation), Effect.andThen(effect)),
5347
);
5448
yield* Deferred.await(parked);
5549
});

0 commit comments

Comments
 (0)