From fd611b5fddaa91a7ba6621205274219b08620880 Mon Sep 17 00:00:00 2001 From: lforst <8118419+lforst@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:30:38 +0000 Subject: [PATCH 1/2] feat(sdk): Add trace-aware scorers --- e2e/config/pr-comment-scenarios.json | 5 ++ .../invoke-scorer.ts | 8 ++ .../scenario.test.ts | 16 +++- .../scenario.ts | 3 + .../trace-context-and-continuation/scorer.ts | 10 +++ js/src/edge-runtime-bootstrap.test.ts | 2 +- js/src/exports.ts | 1 + js/src/framework.test.ts | 74 +++++++++++++++++++ js/src/framework.ts | 37 ++++++++++ js/src/logger/core.ts | 15 ++-- js/src/logger/lifecycle.test.ts | 9 ++- js/src/propagation.test.ts | 43 +++++++++++ js/src/wrappers/mastra.ts | 2 +- 13 files changed, 214 insertions(+), 11 deletions(-) create mode 100644 e2e/scenarios/trace-context-and-continuation/invoke-scorer.ts create mode 100644 e2e/scenarios/trace-context-and-continuation/scorer.ts diff --git a/e2e/config/pr-comment-scenarios.json b/e2e/config/pr-comment-scenarios.json index 36ed2472c..4d4d1286d 100644 --- a/e2e/config/pr-comment-scenarios.json +++ b/e2e/config/pr-comment-scenarios.json @@ -14,6 +14,11 @@ } ] }, + { + "scenarioDirName": "trace-context-and-continuation", + "label": "Trace continuation and inline scorers", + "metadataScenario": "trace-context-and-continuation" + }, { "scenarioDirName": "trace-primitives-basic", "label": "Trace primitives and project caching", diff --git a/e2e/scenarios/trace-context-and-continuation/invoke-scorer.ts b/e2e/scenarios/trace-context-and-continuation/invoke-scorer.ts new file mode 100644 index 000000000..266be4100 --- /dev/null +++ b/e2e/scenarios/trace-context-and-continuation/invoke-scorer.ts @@ -0,0 +1,8 @@ +import scorer from "./scorer"; +import { runMain } from "../../helpers/scenario-runtime"; + +runMain(async () => { + if ((await scorer({ input: "question", output: 1, expected: 1 })) !== 1) { + throw new Error("Unexpected score"); + } +}); diff --git a/e2e/scenarios/trace-context-and-continuation/scenario.test.ts b/e2e/scenarios/trace-context-and-continuation/scenario.test.ts index 49dafc0b9..75ec3e97b 100644 --- a/e2e/scenarios/trace-context-and-continuation/scenario.test.ts +++ b/e2e/scenarios/trace-context-and-continuation/scenario.test.ts @@ -27,8 +27,8 @@ const lateUpdatePayloadsSnapshotPath = resolveFileSnapshotPath( test("trace-context-and-continuation supports reattachment and late span updates", async () => { await withScenarioHarness( - async ({ payloads, runScenarioDir, testRunEvents, testRunId }) => { - await runScenarioDir({ scenarioDir }); + async ({ events, payloads, runScenarioDir, testRunEvents, testRunId }) => { + const { stdout } = await runScenarioDir({ scenarioDir }); const capturedEvents = testRunEvents(); const root = findLatestSpan(capturedEvents, "context-root"); @@ -76,6 +76,18 @@ test("trace-context-and-continuation supports reattachment and late span updates formatJsonFileSnapshot(mutationRows as Json), lateUpdatePayloadsSnapshotPath, ); + + await runScenarioDir({ + scenarioDir, + entry: "invoke-scorer.ts", + env: { BRAINTRUST_TRACE_PARENT: stdout.trim() }, + }); + const score = findLatestSpan(events(), "score"); + const child = findLatestSpan(events(), "score-child"); + expect(score?.row.project_id).toBe(root?.row.project_id); + expect(score?.span.parentIds).toEqual([root?.span.id]); + expect(child?.span.parentIds).toEqual([score?.span.id]); + expect(child?.span.rootId).toBe(root?.span.rootId); }, ); }); diff --git a/e2e/scenarios/trace-context-and-continuation/scenario.ts b/e2e/scenarios/trace-context-and-continuation/scenario.ts index bcf1371ba..bdd9507e0 100644 --- a/e2e/scenarios/trace-context-and-continuation/scenario.ts +++ b/e2e/scenarios/trace-context-and-continuation/scenario.ts @@ -1,3 +1,4 @@ +import assert from "node:assert/strict"; import { flush, extractTraceContextFromHeaders, @@ -30,6 +31,7 @@ async function main() { }, }); const propagatedRoot = extractTraceContextFromHeaders(rootSpan.inject()); + assert(propagatedRoot, "Expected trace context from the root span"); await withCurrent(rootSpan, async () => { const currentChild = startSpan({ @@ -49,6 +51,7 @@ async function main() { currentChild.end(); }); + console.log(await rootSpan.export()); rootSpan.end(); await withParent(propagatedRoot, async () => { diff --git a/e2e/scenarios/trace-context-and-continuation/scorer.ts b/e2e/scenarios/trace-context-and-continuation/scorer.ts new file mode 100644 index 000000000..72822dcff --- /dev/null +++ b/e2e/scenarios/trace-context-and-continuation/scorer.ts @@ -0,0 +1,10 @@ +import { defineScorer, traced } from "braintrust"; + +export default defineScorer(({ output, expected }) => + traced( + () => traced(() => Number(output === expected), { name: "score-child" }), + { + name: "score", + }, + ), +); diff --git a/js/src/edge-runtime-bootstrap.test.ts b/js/src/edge-runtime-bootstrap.test.ts index 47b6e2669..28f978d53 100644 --- a/js/src/edge-runtime-bootstrap.test.ts +++ b/js/src/edge-runtime-bootstrap.test.ts @@ -9,7 +9,7 @@ import { } from "vite-plus/test"; type EdgeEntrypoint = "./edge-light/index" | "./workerd/index"; -const braintrustStateSymbol = Symbol.for("braintrust-state"); +const braintrustStateSymbol = Symbol.for("braintrust-state-v4"); describe.each([ ["./workerd/index", "workerd"], diff --git a/js/src/exports.ts b/js/src/exports.ts index 5760310e6..eafab9dba 100644 --- a/js/src/exports.ts +++ b/js/src/exports.ts @@ -142,6 +142,7 @@ export { Eval, Reporter, defaultErrorScoreHandler, + defineScorer, } from "./framework"; export type { WorkflowEvalStore } from "./workflow-eval"; diff --git a/js/src/framework.test.ts b/js/src/framework.test.ts index c63e60f33..da8726313 100644 --- a/js/src/framework.test.ts +++ b/js/src/framework.test.ts @@ -10,6 +10,7 @@ import { import { type ExperimentEvent } from "../util"; import { defaultErrorScoreHandler, + defineScorer, Eval, EvalScorer, runEvaluator, @@ -23,6 +24,7 @@ import { injectTraceContext, TestBackgroundLogger, _internalWithParent, + _internalGetGlobalState, } from "./logger/core"; import { parseBaggage } from "./propagation"; import { configureNode } from "./node/config"; @@ -41,6 +43,78 @@ class NoopProgressReporter implements ProgressReporter { public increment() {} } +test("defineScorer keeps the score name and accepts sync and async callbacks", async () => { + const callback = ({ output }: { input: string; output: string }) => + Number(output.length > 0); + const scorer = defineScorer(callback); + expect(scorer.name).toBe(callback.name); + const score: number = await scorer({ input: "", output: "yes" }); + expect(score).toBe(1); + const asyncScorer = defineScorer(async ({ output, expected, trace }) => + trace ? null : Number(output === expected), + ) satisfies EvalScorer; + const result: Promise = asyncScorer({ + input: "question", + output: "answer", + expected: "answer", + }); + expect(await result).toBe(1); + + const evaluation = await runEvaluator( + null, + { + projectName: "proj", + evalName: "eval", + data: [{ input: "question", expected: "answer" }], + task: () => "answer", + scores: [scorer], + }, + new NoopProgressReporter(), + undefined, + undefined, + true, + ); + expect(evaluation.results[0].scores).toEqual({ callback: 1 }); +}); + +test("a hosted scorer logs in per invocation and flushes on success and failure", async () => { + const state = _internalGetGlobalState(); + const login = vi.spyOn(state, "login").mockResolvedValue(undefined); + const flush = vi + .spyOn(state.bgLogger(), "flush") + .mockResolvedValue(undefined); + const failure = new Error("scorer failed"); + const scorer = defineScorer(async ({ input }) => { + await Promise.resolve(); + expect(state.currentParent.getStore()).toBe(input); + expect(flush).not.toHaveBeenCalled(); + if (input === "second") throw failure; + return 1; + }); + try { + for (const parent of ["first", "second"]) { + const apiKey = `test-token-${parent}`; + vi.stubEnv("BRAINTRUST_API_KEY", apiKey); + vi.stubEnv("BRAINTRUST_TRACE_PARENT", parent); + const result = scorer({ input: parent, output: 1 }); + if (parent === "first") { + await expect(result).resolves.toBe(1); + } else { + await expect(result).rejects.toBe(failure); + } + expect(login).toHaveBeenCalledWith({ apiKey, forceLogin: true }); + expect(flush).toHaveBeenCalledOnce(); + expect(state.currentParent.getStore()).toBeUndefined(); + flush.mockClear(); + login.mockClear(); + } + } finally { + flush.mockRestore(); + login.mockRestore(); + vi.unstubAllEnvs(); + } +}); + test("meta (write) is passed to task", async () => { const metadata = { bar: "baz", diff --git a/js/src/framework.ts b/js/src/framework.ts index 66c09aa72..bd637c153 100644 --- a/js/src/framework.ts +++ b/js/src/framework.ts @@ -34,6 +34,7 @@ import { StartSpanArgs, currentSpan, flush, + login, logError as logSpanError, startSpan, traced, @@ -190,6 +191,42 @@ export type EvalScorer< args: EvalScorerArgs, ) => OneOrMoreScores | Promise; +/** + * Define an inline scorer or reuse it in an Eval scores array. + * With BRAINTRUST_TRACE_PARENT set, each invocation logs in from the environment, + * runs the callback with that parent, and flushes before it settles. + * Without a runtime parent, Eval or the caller owns the logging lifecycle. + * + * @example + * export default defineScorer(({ output, expected }) => Number(output === expected)); + */ +export function defineScorer< + Args extends EvalScorerArgs & { + expected?: unknown; + metadata?: Record; + }, + Result extends OneOrMoreScores, +>( + callback: (args: Args) => Result | Promise, +): (args: Args) => Promise { + const scorer = async (args: Args) => { + const parent = iso.getEnv("BRAINTRUST_TRACE_PARENT"); + if (!parent) { + return callback(args); + } + + // A reused worker can receive a different token or organization on each call. + await login({ apiKey: iso.getEnv("BRAINTRUST_API_KEY"), forceLogin: true }); + try { + return await _internalWithParent(parent, () => callback(args)); + } finally { + await flush(); + } + }; + Object.defineProperty(scorer, "name", { value: callback.name }); + return scorer; +} + type OneOrMoreClassifications = Classification | Classification[] | null; export type EvalClassifier< diff --git a/js/src/logger/core.ts b/js/src/logger/core.ts index 299391d6d..12658c3d2 100644 --- a/js/src/logger/core.ts +++ b/js/src/logger/core.ts @@ -1383,6 +1383,7 @@ export class BraintrustState { } } +const stateKey = Symbol.for("braintrust-state-v4"); let _globalState: BraintrustState; /** @@ -1398,11 +1399,10 @@ export function _internalSetInitialState(): void { if (_globalState) { return; } - const sym = Symbol.for("braintrust-state"); - let existing = (globalThis as any)[sym]; + let existing = (globalThis as any)[stateKey]; if (!existing) { const state = new BraintrustState({}); - (globalThis as any)[sym] = state; + (globalThis as any)[stateKey] = state; existing = state; } _globalState = existing; @@ -4906,7 +4906,10 @@ function getSpanParentObjectAndPropagatedState( return { parentObject: parentSpan, propagatedState: undefined }; } - const parent = options?.parent ?? state.currentParent.getStore(); + const parent = + options?.parent ?? + state.currentParent.getStore() ?? + iso.getEnv("BRAINTRUST_TRACE_PARENT"); const { parentSlug, propagatedState } = normalizeParent(parent, state); if (parentSlug) { return { @@ -4928,7 +4931,7 @@ function getSpanParentObjectAndPropagatedState( /** * Mainly for internal use. Return the parent object for starting a span in a global context. - * Applies precedence: current span > propagated parent > experiment > logger. + * Applies precedence: current span > propagated parent > environment parent > experiment > logger. * * `parent` may be an exported slug string or an opaque W3C trace-context (from * {@link extractTraceContextFromHeaders}). @@ -5806,7 +5809,7 @@ export async function flush(options?: OptionalStateArg): Promise { globalThis as typeof globalThis & { [key: symbol]: BraintrustState | undefined; } - )[Symbol.for("braintrust-state")]; + )[stateKey]; await state?.bgLogger().flush(); } diff --git a/js/src/logger/lifecycle.test.ts b/js/src/logger/lifecycle.test.ts index 1dd0613a8..506236118 100644 --- a/js/src/logger/lifecycle.test.ts +++ b/js/src/logger/lifecycle.test.ts @@ -1,16 +1,23 @@ import { expect, test, vi } from "vite-plus/test"; test("flush does not initialize an unused SDK", async () => { - const key = Symbol.for("braintrust-state"); + const key = Symbol.for("braintrust-state-v4"); const globals = globalThis as typeof globalThis & { [key: symbol]: unknown }; const previous = globals[key]; delete globals[key]; + const legacyState = { bgLogger: vi.fn() }; + vi.stubGlobal(Symbol.for("braintrust-state"), legacyState); vi.resetModules(); try { const sdk = await import("./core"); await sdk.flush(); expect(globals[key]).toBeUndefined(); + expect(sdk._internalGetGlobalState()).not.toBe(legacyState); + expect(legacyState.bgLogger).not.toHaveBeenCalled(); } finally { + vi.unstubAllGlobals(); + vi.resetModules(); + delete globals[key]; if (previous !== undefined) globals[key] = previous; } }); diff --git a/js/src/propagation.test.ts b/js/src/propagation.test.ts index 98b4b01fb..fb932fe0c 100644 --- a/js/src/propagation.test.ts +++ b/js/src/propagation.test.ts @@ -23,6 +23,9 @@ import { initLogger, injectTraceContext, startSpan, + _internalWithParent, + withCurrent, + NOOP_SPAN, } from "./logger/core"; import { BAGGAGE_HEADER, @@ -510,6 +513,46 @@ describe("inject / extract / round-trip", () => { return initLogger({ projectName: PROJECT_NAME }); } + test("environment parent follows the invocation and yields to scoped parents", async () => { + const parent = (spanId: string) => + new SpanComponentsV4({ + object_type: SpanObjectTypeV3.PROJECT_LOGS, + object_id: EXPERIMENT_ID, + row_id: uuidv4(), + span_id: spanId, + root_span_id: VALID_TRACE_ID, + }).toStr(); + const first = parent(VALID_SPAN_ID); + const secondId = "1111111111111111"; + try { + vi.stubEnv("BRAINTRUST_TRACE_PARENT", first); + const span = startSpan(); + expect(span.spanParents).toEqual([VALID_SPAN_ID]); + vi.stubEnv("BRAINTRUST_TRACE_PARENT", parent(secondId)); + const next = startSpan(); + expect(next.spanParents).toEqual([secondId]); + withCurrent(span, () => { + const child = startSpan(); + expect(child.spanParents).toEqual([span.spanId]); + child.end(); + }); + await _internalWithParent(first, () => { + const child = startSpan(); + expect(child.spanParents).toEqual([VALID_SPAN_ID]); + child.end(); + }); + const explicit = _internalStartSpan({ parent: first }); + expect(explicit.spanParents).toEqual([VALID_SPAN_ID]); + explicit.end(); + next.end(); + span.end(); + vi.stubEnv("BRAINTRUST_TRACE_PARENT", undefined); + expect(startSpan()).toBe(NOOP_SPAN); + } finally { + vi.unstubAllEnvs(); + } + }); + describe("inject", () => { test("traceparent well-formed and matches span", () => { const logger = makeLogger(); diff --git a/js/src/wrappers/mastra.ts b/js/src/wrappers/mastra.ts index b77283d2d..a9ce9b47a 100644 --- a/js/src/wrappers/mastra.ts +++ b/js/src/wrappers/mastra.ts @@ -255,7 +255,7 @@ export class BraintrustObservabilityExporter implements MastraObservabilityExpor // The auto-instrumentations bundle and the main braintrust bundle each // have their own module-scoped `_globalState`. The main bundle initializes // state via `configureNode`; this call rehydrates our bundle's copy from - // the shared `globalThis[Symbol.for("braintrust-state")]` so subsequent + // the shared `globalThis[Symbol.for("braintrust-state-v4")]` so subsequent // `currentSpan()` / `startSpan()` calls hit a real state, not undefined. _internalSetInitialState(); } From e58a579f40356cb4b7795a8a82794af3b0b8477d Mon Sep 17 00:00:00 2001 From: lforst <8118419+lforst@users.noreply.github.com> Date: Tue, 24 Nov 2026 19:37:31 +0000 Subject: [PATCH 2/2] chore: Add changeset for trace-aware scorers --- .changeset/trace-aware-scorers.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/trace-aware-scorers.md diff --git a/.changeset/trace-aware-scorers.md b/.changeset/trace-aware-scorers.md new file mode 100644 index 000000000..ac8552967 --- /dev/null +++ b/.changeset/trace-aware-scorers.md @@ -0,0 +1,5 @@ +--- +"braintrust": minor +--- + +feat(sdk): Add trace-aware scorers