Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): stop idle private-memory growth from immortal parent spans #5411

ClosedBenchance(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/5411/headopened View on GitHub

Summary

  • Fixes steady ~25–30 MB/h Private growth in the desktop server while idle (tracked in #5410).
  • Long-lived forkParked roots and the PortDiscovery poll loop were inheriting Effect ParentSpan from short-lived startup/make spans, so hot-path nested spans kept parenting under immortal spans.
  • Detach ambient ParentSpan in forkParked, untrace idle port polls + secret gets, and drop PortDiscovery.make's wrapping span.

Test plan

  • vp test run src/serverActivation.test.ts src/preview/PortScanner.test.ts (apps/server)
  • Restart desktop build with this change; leave idle/unfocused for 2–3 hours
  • Confirm server Private bytes stay roughly flat (ignore Working Set trims)
  • Confirm server.trace.ndjson no longer floods with PortDiscovery.pollTick / ServerSecretStore.get under startup.phase=reactors.start
  • Spot-check provider health / preview port discovery still work when used

Fixes #5410


Note

Low Risk Changes only Effect tracing context and span emission on background fibers and secret reads; no auth, data, or business-logic paths. Main risk is reduced trace detail during idle periods, not functional regression.

Overview Fixes steady idle Private memory growth (#5410) by breaking the link between short-lived startup spans and long-lived background work.

Adds withoutAmbientParentSpan in serverActivation.ts to remove Tracer.ParentSpan from an effect’s context. forkParked now forks through that helper so reactor and other long-running roots no longer pin immortal parent spans.

PortDiscovery polling: the retain-count idle check lives outside Effect.fn so no-op ticks don’t create spans; the repeating poll fiber runs inside withoutAmbientParentSpan. The PortDiscovery.make wrapper span is removed.

ServerSecretStore.get switches from a per-call named span to Effect.withTracerEnabled(false), cutting trace noise on a hot path.

Observability: fewer or no spans for idle poll ticks, secret reads, and some layer roots; preview port discovery behavior is unchanged when retained.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 655748bf3a0c3eabec1ceef50b731c51e97ee506. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Stop idle private-memory growth from immortal parent spans in background fibers

  • Adds withoutAmbientParentSpan helper in serverActivation.ts that strips Tracer.ParentSpan from an effect's context, preventing long-lived forked fibers from holding a reference to a parent span.
  • Applies withoutAmbientParentSpan in forkParked so all long-running roots it forks no longer inherit an ambient parent span.
  • Refactors PortDiscovery polling in PortScanner.ts so idle no-op ticks skip span creation entirely, and the background polling fiber runs without an inherited parent span.
  • Disables tracing on ServerSecretStore.get in ServerSecretStore.ts instead of creating a named span per call.
  • Behavioral Change: named tracing spans are no longer emitted for idle poll ticks, ServerSecretStore.get, or the PortDiscovery.make and forkParked roots.
Macroscope summarized 655748b.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 35947756-e453-402a-83ae-5f16291f2e75

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

      ❤️ Share
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. @@ -6,11 +7,21 @@
      67 export class ServerActivation extends Context.Reference<Effect.Effect<void> | undefined>(
      78 "t3/serverActivation",
      89 { defaultValue: () => undefined },
      910 ) {}
      1011
      12+// Clear inherited ParentSpan so long-lived forks don't pin short-lived startup spans (#5410).
      13+export const withoutAmbientParentSpan = <A, E, R>(
      14+ effect: Effect.Effect<A, E, R>,
      15+): Effect.Effect<A, E, R> =>
      16+ Effect.updateContext(
      17+ effect,
      18+ (context) => Context.omit(Tracer.ParentSpan)(context) as Context.Context<NoInfer<R>>,
      19+ );
      20+
      1121 /** Forks a long-running root before commit and proves it is parked at the activation boundary. */
      1222 export const forkParked = <A, E, R>(
      1323 effect: Effect.Effect<A, E, R>,
      1424 ): Effect.Effect<void, never, Scope.Scope | R> =>
      1525 Effect.gen(function* () {
      1626 const activation = yield* ServerActivation;
      27+ const detached = withoutAmbientParentSpan(effect);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High src/serverActivation.ts:25

      withoutAmbientParentSpan casts the context after removing Tracer.ParentSpan back to Context.Context<NoInfer<R>>, so the return type still claims to satisfy effects whose environment explicitly includes Tracer.ParentSpan. If an effect passed to withoutAmbientParentSpan (or to forkParked, which wraps every input with it) directly uses Tracer.ParentSpan, the code type-checks but the forked fiber fails at runtime with Service not found because the service was removed from the child context. The cast masks a missing-service defect rather than surfacing it as a type error. Consider constraining the input type so Tracer.ParentSpan cannot appear in R.

      -    (context) => Context.omit(Tracer.ParentSpan)(context) as Context.Context<NoInfer<R>>,
      +    (context) => Context.omit(Tracer.ParentSpan)(context) as Context.Context<Exclude<NoInfer<R>, Tracer.ParentSpan>>,
      +    // Note: this cast is unsafe if R explicitly requires Tracer.ParentSpan;
      +    // callers should ensure the input does not use that service directly.
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/serverActivation.ts around lines 25-27:
      
      `withoutAmbientParentSpan` casts the context after removing `Tracer.ParentSpan` back to `Context.Context<NoInfer<R>>`, so the return type still claims to satisfy effects whose environment explicitly includes `Tracer.ParentSpan`. If an effect passed to `withoutAmbientParentSpan` (or to `forkParked`, which wraps every input with it) directly uses `Tracer.ParentSpan`, the code type-checks but the forked fiber fails at runtime with `Service not found` because the service was removed from the child context. The cast masks a missing-service defect rather than surfacing it as a type error. Consider constraining the input type so `Tracer.ParentSpan` cannot appear in `R`.

      Addressed in 17580be — return type is now Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>> with a matching context cast, so the stripped env is reflected in the type.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    4. Pull request overview

      Fixes idle private-memory growth in the desktop/server process by preventing long-lived fibers (parked roots + background pollers) from inheriting short-lived startup Tracer.ParentSpan context, and by reducing tracing work on hot/idle paths.

      Changes:

      • Add withoutAmbientParentSpan and apply it in forkParked to detach inherited Tracer.ParentSpan for long-lived roots.
      • Reduce tracing overhead on idle/background loops (PortDiscovery polling, secret reads) and remove the PortDiscovery.make wrapping span.
      • Add a focused unit test validating that withoutAmbientParentSpan clears inherited Tracer.ParentSpan without affecting sibling effects.

      Reviewed changes

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

      Show a summary per file
      FileDescription
      apps/server/src/serverRuntimeStartup.tsDocuments why parked startup roots must detach ambient ParentSpan to avoid pinning startup spans.
      apps/server/src/serverActivation.tsIntroduces withoutAmbientParentSpan and applies it to all forkParked forks.
      apps/server/src/serverActivation.test.tsAdds a unit test asserting ParentSpan detachment behavior.
      apps/server/src/preview/PortScanner.tsDetaches the poll fiber from ambient parent spans and disables tracing in the poll loop; removes PortDiscovery.make span wrapper.
      apps/server/src/auth/ServerSecretStore.tsDisables tracing for frequent secret reads to reduce idle trace volume and span retention.

      💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

      @@ -23,0 +31,21 @@
      31+ traceId: "00000000000000000000000000000001",
      32+ spanId: "0000000000000001",
      33+ sampled: true,
      34+ });
      35+
      36+ const sawParent = yield* Effect.serviceOption(Tracer.ParentSpan).pipe(
      37+ Effect.map(Option.isSome),
      38+ withoutAmbientParentSpan,
      39+ Effect.provideService(Tracer.ParentSpan, ambient),
      40+ );
      41+
      42+ expect(sawParent).toBe(false);
      43+
      44+ const stillHasParent = yield* Effect.serviceOption(Tracer.ParentSpan).pipe(
      45+ Effect.map(Option.isSome),
      46+ Effect.provideService(Tracer.ParentSpan, ambient),
      47+ );
      48+ expect(stillHasParent).toBe(true);
      49+
      50+ const stripped = Context.omit(Tracer.ParentSpan)(Context.make(Tracer.ParentSpan, ambient));
      51+ expect(Context.getOption(stripped, Tracer.ParentSpan)._tag).toBe("None");
      copilot-pull-request-reviewer[bot](GitHub profile, opens in a new tab)commented

      Avoid asserting on the internal ._tag representation of Option values; it’s more robust to use the public Option.isNone/isSome helpers (and Option is already imported here).

      Fixed in 17580be — switched to Option.isNone.

      @@ -309,6 +310,14 @@
      309310 );
      310311
      311312 // Single layer-scoped polling fiber. Ticks are no-ops when no client is
      312- // currently retained, so the cost is one Ref.get every POLL_INTERVAL.
      313- yield* Effect.forkScoped(pollTick().pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
      314-
      313+ // currently retained. Run detached from any ambient ParentSpan (e.g.
      314+ // PortDiscovery.make) and without tracing idle no-ops — otherwise every
      315+ // 3s tick parents under an immortal span and grows server private memory.
      316+ yield* Effect.forkScoped(
      317+ withoutAmbientParentSpan(
      318+ pollTick().pipe(
      319+ Effect.repeat(Schedule.spaced(POLL_INTERVAL)),
      320+ Effect.withTracerEnabled(false),
      321+ ),
      322+ ),
      323+ );
      copilot-pull-request-reviewer[bot](GitHub profile, opens in a new tab)commented

      Effect.withTracerEnabled(false) is currently applied to the entire pollTick().repeat(...) loop, which disables tracing even when retainCount > 0 (active scans). The PR description and the inline comment both say this should only be untraced for idle no-op ticks, so this change silently drops useful traces during real preview usage.

      Good catch — fixed in 17580be. Idle early-return now sits outside Effect.fn("PortDiscovery.pollTick") so no-op ticks create no span, and the blanket withTracerEnabled(false) on the poll loop is gone so active scans still get traced. ParentSpan detach stays via withoutAmbientParentSpan.

    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      1 blocking correctness issue found. This memory-leak fix modifies span/tracing behavior for long-lived server processes. An unresolved high-severity comment identifies a type cast that could mask runtime 'Service not found' errors, which warrants human review to ensure correctness.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Closing in favor of #9824, which reimplements the same idle ParentSpan / background-fiber diagnosis with a type-safe withDetachedSpan re-root (and is current on main with green CI).

      Thanks @Benchance — the original analysis and first fix attempt here were what unblocked the follow-up.

Sign in to join this conversation.