Skip to content
Source
Sign inSign up
pingdotgg/t3code

perf(server): traces keep ~40% more history and no longer block the event loop #19430

Mergedt3dotgg(GitHub profile, opens in a new tab)merged 5 commits intomain fromrefs/pull/19430/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHub

With about seven agents streaming, server traces covered only about 20 minutes (#18917). Each streamed event write recorded about 9 spans, and trace and provider log writes ran synchronously on the event loop, so a slow disk also stalled the server.

This combines and finishes two contributor PRs:

  • #18106 by @bompus: fewer low-value spans.
  • #19303 by @daniyal-sh: trace and provider log writes move off the event loop.

Fix

  • EventSink.write runs its transaction body with the tracer off. Each streamed event now records 2 spans (orchestrationV2.EventSink.write and sql.transaction), not about 9. Both spans still time the whole write, including the commit, which is how #15707's SQLite stalls were found. server.eventLoop.stall is unchanged.
  • Startup attributes (server.mode, server.port, server.host, startup.phase) stay on their own spans. annotateSpans had copied them onto every span the effect worker made for the life of the server.
  • The local trace and provider event logs write and rotate files through one async, serialized sink. A slow disk delays the writing fiber, not the event loop.

Changes from the original PRs

  • Command commits (commitCommand and the others) keep their statement spans. #18106 had untraced every EventSink transaction. Command commits are rare (about 2% of trace bytes), and per-statement timing is how a slow read inside a dispatch was found in #15707.
  • While a write is slow, the trace keeps up to one file of records (at least 4 MiB). #19303 also capped this at 1,024 records, only a few seconds of spans under heavy load, so a slow disk dropped the spans that explain the stall.
  • The flush loop uses Effect.timeoutOption, so it no longer needs a lint suppression.
  • The synchronous RotatingFileSink stays. This PR no longer calls it, but #19425 adds a stall log on it. Removing it here would break whichever PR merges second. After both land, the stall log can move to makeAsyncRotatingFileSink, so a stall's own record never blocks the loop, and the sync class can go.
  • Left out: #18106's project-lookup untracing. #16202 made the same change and was replaced by #16206. On current traces those spans are about 1% of bytes.

Verification

A real 112 MB trace from a busy desktop install on today's build: statement spans inside EventSink.write were 22% of its bytes, and leaked startup attributes were another 6% (31% of all spans carried them). Without both, the same 100 MB keeps about 40% more history.

401 realistic streamed event writes through the real EventSink and the real local file tracer:

Per event writemainthis PR
Spans8.392.00
Trace bytes4,552831

Real dev server (seeded from a snapshot), one real Codex turn, trace rotation set to 256 KB:

  • 5 trace files, 2,096 records, 0 torn lines, every file within the limit.
  • 35 spans that ended after SIGINT were flushed at shutdown.
  • 0 spans with leaked startup attributes.
  • EventSink.write transactions had 0 statement spans. commitCommand transactions kept 100.
  • The provider log had 23 well-formed, ordered lines. Startup retention removed an expired log and kept a recent one.

Tests: logging.test.ts, observability.test.ts, FoundationPersistence.test.ts, EventNdjsonLogger.test.ts, serverRuntimeStartup*.test.ts, EventLoopMonitor.test.ts, DesktopObservability.test.ts. The new trace backlog test fails with the 1,024-record cap, and the event-write span test fails without the untraced body. Typecheck is clean for shared, server, and desktop.

Not verified here: event-loop time on slow storage. This Linux box has a fast disk. #19303's Windows capture measured about 5 s of samples in the synchronous append path drop to 0.

Closes #18917.

Both contributors' commits keep their authorship, so the squash merge credits them as co-authors.

Reviewed with sol-loop: 2 rounds with GPT-6.1-Sol.

Made with Claude Opus 5.5 in Claude Code, running in T3 Code.

🤖 Generated with Claude Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

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

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR substantially rewires always-on trace and provider logging, including asynchronous rotation, bounded buffering and dropping behavior, shutdown draining, and changes to SQL/startup span coverage. The shared infrastructure and production server paths have enough complexity and runtime impact to warrant human review.

      Notes:

      • Diff unchanged. Approvability was decided on eligibility alone.
      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. juliusmarminge added labelsmacroscope-review

    4. Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire5.0 KiB5.0 KiB+7 B (+0.1%)6.8 KiB✅
      CodexThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      CodexLive turn WebSocket wire1.2 KiB1.2 KiB+7 B (+0.6%)2.0 KiB✅
      CodexLive turn WebSocket decoded20.9 KiB20.9 KiB0 B (0.0%)29.3 KiB✅
      CodexLive turn messages220 (0.0%)8✅
      ClaudeTotal thread wire5.0 KiB5.0 KiB−7 B (−0.1%)6.8 KiB✅
      ClaudeThread snapshot wire3.8 KiB3.8 KiB0 B (0.0%)4.9 KiB✅
      ClaudeLive turn WebSocket wire1.2 KiB1.2 KiB−7 B (−0.6%)2.0 KiB✅
      ClaudeLive turn WebSocket decoded21.2 KiB21.2 KiB0 B (0.0%)29.3 KiB✅
      ClaudeLive turn messages220 (0.0%)8✅

      Baseline: 8414d16 · PR result: 0386e80 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 108.5 KiB
      • Claude decoded thread snapshot: 108.8 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    5. Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Configuration used: Path: .coderabbit.config.ts
      • Review profile: CHILL
      • Plan: Team
      • Run ID: bb8eed05-17f3-48b1-9210-c169641fa033
      📥 Commits

      Reviewing files that changed from the base of the PR and between 8414d168191599dec08588080d0b77506c849424 and 0386e80776eff2292c5ee52061d5f884d2cca1fc.

      📒 Files selected for processing: 11
      • apps/server/src/orchestration-v2/EventSink.ts
      • apps/server/src/orchestration-v2/FoundationPersistence.test.ts
      • apps/server/src/provider/EventNdjsonLogger.test.ts
      • apps/server/src/provider/EventNdjsonLogger.ts
      • apps/server/src/serverRuntimeStartup.ts
      • docs/internals/performance-regressions.md
      • docs/operations/observability.md
      • packages/shared/src/logging.test.ts
      • packages/shared/src/logging.ts
      • packages/shared/src/observability.test.ts
      • packages/shared/src/observability.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

      📝 Walkthrough

      The change adds asynchronous rotating file writes for trace and provider logs, with buffering and shutdown draining. It also disables statement-level tracing inside event writes while retaining transaction spans, and sets startup metadata directly on startup spans.

      Changes: Telemetry Logging and Tracing

      Layer / File(s)Summary
      Asynchronous rotating file sink
      packages/shared/src/logging.ts, packages/shared/src/logging.test.ts
      Adds an Effect-based sink that serializes writes, rotates and prunes backups, and refreshes tracked file size after write failures. Tests cover concurrent writes, reopening, rotation, and recovery after an append failure.
      Buffered asynchronous trace writes
      packages/shared/src/observability.ts, packages/shared/src/observability.test.ts, docs/internals/performance-regressions.md
      Trace records are buffered and flushed in bounded batches through the asynchronous sink. The buffer has a byte cap, and flushes are serialized and uninterruptible. Tests cover blocked writes, queue limits, close behavior, and write failures.
      Provider log writes and shutdown
      apps/server/src/provider/EventNdjsonLogger.ts, apps/server/src/provider/EventNdjsonLogger.test.ts, docs/internals/performance-regressions.md
      Provider log batching, sink creation, retention scans, and deletions use asynchronous operations. Tests cover write attribution and confirm that close waits for pending writes.
      Event-write tracing and startup span attributes
      apps/server/src/orchestration-v2/EventSink.ts, apps/server/src/orchestration-v2/FoundationPersistence.test.ts, apps/server/src/serverRuntimeStartup.ts, docs/operations/observability.md
      Event-write SQL statements run with tracing disabled while the transaction span remains. Startup metadata is set directly on startup spans rather than through span annotations.

      Priority: ⬆️ High

      Estimated code review effort: 4 (Complex) | ~45 minutes

      Change: Bug fix · Severity of issue fixed: Medium

      Sequence Diagram(s)

      sequenceDiagram
        participant makeTraceSink
        participant makeAsyncRotatingFileSink
        participant FileSystem
        makeTraceSink->>makeAsyncRotatingFileSink: create sink for buffered flushes
        makeTraceSink->>makeAsyncRotatingFileSink: write bounded record batches
        makeAsyncRotatingFileSink->>FileSystem: append records and rotate files

      Suggested reviewers: juliusmarminge

      Merge Risk: ⚪ Minimal · up to 0386e

      No confirmed issue remains that blocks merging after normal checks.

      Pre-merge checks: Passed 3 · Failed 1
      Failed Failed checks: 1 warning
      Check nameStatusExplanationResolution
      Linked Issues checkWarning[#18917] The PR satisfies the event-write requirement. EventSink.write disables tracing for the transaction body, while orchestrationV2.EventSink.write and sql.transaction remain. The startup co…Untrace the three project-lookup helper operations identified by [#18917]. Add or update an automated test that verifies those helper spans are absent while the parent lookup span remains.
      Passed Passed checks: 3 passed
      Check nameStatusExplanation
      Title checkPassedThe title clearly describes the main changes: improved trace history retention and asynchronous writes that avoid blocking the event loop.
      Description checkPassedThe description covers the problem, implemented changes, scope decisions, detailed verification results, unverified conditions, and agent attribution. It references the related issue and pull requests…
      Out of Scope Changes checkPassedThe asynchronous trace and provider-log sinks, rotation changes, documentation, and tests support [#18917]. They reduce local observability write blocking and preserve trace retention during high stre…
      Full details: Linked Issues check

      Explanation

      [#18917] The PR satisfies the event-write requirement. EventSink.write disables tracing for the transaction body, while orchestrationV2.EventSink.write and sql.transaction remain. The startup code puts startup.phase on phase spans instead of propagating it to forked worker spans. The linked issue also identifies three project-lookup helper spans as low-value trace volume. The PR explicitly leaves that work out, and no changed file addresses it.

      • Fix all pre-merge checks with AI
      ✨ Finishing Touches
      📝 Generate docstrings
      • Commit to this branch
      • Create a new PR
      🧪 Generate unit tests (beta)
      • Commit to this branch
      • Create a new PR
      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
      Comment `@coderabbitai help` to get the list of available commands.

Sign in to join this conversation.