Skip to content

feat: add client-side trace sampling - #2368

Draft
Giran Moodley (giranm) wants to merge 2 commits into
mainfrom
giran/SDK-191-support-trace-sampling-javascript
Draft

feat: add client-side trace sampling#2368
Giran Moodley (giranm) wants to merge 2 commits into
mainfrom
giran/SDK-191-support-trace-sampling-javascript

Conversation

@giranm

Copy link
Copy Markdown

Summary

Adds deterministic client-side head sampling for native Braintrust JavaScript traces. Sampling decisions are trace-id based, so independently created children and distributed continuations stay coherent.

Usage

import { initLogger } from "braintrust";

const logger = initLogger({
  projectName: "production",
  sampleRate: 0.2, // Record approximately 20% of new project-root traces.
});

// Override the logger default for an exceptional new root trace.
const priority = logger.startSpan({
  name: "priority-request",
  sampleRate: 1,
});

Expected behavior

  • sampleRate accepts a finite fraction from 0 through 1 and defaults to 1; invalid values throw.
  • The decision for a new native project root is deterministic from its trace ID. Its native children inherit that decision, and span.isRecording() exposes it.
  • A sampled-out trace preserves context, stable IDs, and traceparent propagation with trace flags 00, but queues no Braintrust rows or instrumentation payload work.
  • An existing local, exported, W3C, or OpenTelemetry parent takes precedence over either configured rate. New local Experiment roots remain recorded, except when continuing an unsampled parent.
  • When OpenTelemetry owns creation, its provider sampler is authoritative. The @braintrust/otel bridge preserves that result without applying Logger.sampleRate a second time.

Implementation

  • Add Logger.sampleRate, root-span overrides, and Span.isRecording().
  • Preserve trace flags in native export tokens, native context, W3C propagation, and OpenTelemetry context.
  • Skip trace extraction and export work for sampled-out instrumentation spans while retaining lifecycle and context behavior.
  • Add documentation, changesets, unit coverage, and the trace-sampling E2E scenario.

Validation

  • Focused native tests: 282 passed; final logger, propagation, and sampling set: 248 passed.
  • Trace-sampling E2E scenario passed repeatedly.
  • Isolated OpenTelemetry v1 and v2 fixture suites: 123 passed each.
  • Type checks, build, API compatibility, formatting, lint, and diff checks passed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants