Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/trace-aware-scorers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"braintrust": minor
---

feat(sdk): Add trace-aware scorers
5 changes: 5 additions & 0 deletions e2e/config/pr-comment-scenarios.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
8 changes: 8 additions & 0 deletions e2e/scenarios/trace-context-and-continuation/invoke-scorer.ts
Original file line number Diff line number Diff line change
@@ -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");
}
});
16 changes: 14 additions & 2 deletions e2e/scenarios/trace-context-and-continuation/scenario.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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);
},
);
});
3 changes: 3 additions & 0 deletions e2e/scenarios/trace-context-and-continuation/scenario.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import assert from "node:assert/strict";
import {
flush,
extractTraceContextFromHeaders,
Expand Down Expand Up @@ -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({
Expand All @@ -49,6 +51,7 @@ async function main() {
currentChild.end();
});

console.log(await rootSpan.export());
rootSpan.end();

await withParent(propagatedRoot, async () => {
Expand Down
10 changes: 10 additions & 0 deletions e2e/scenarios/trace-context-and-continuation/scorer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineScorer, traced } from "braintrust";

export default defineScorer(({ output, expected }) =>
traced(
() => traced(() => Number(output === expected), { name: "score-child" }),
{
name: "score",
},
),
);
2 changes: 1 addition & 1 deletion js/src/edge-runtime-bootstrap.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
1 change: 1 addition & 0 deletions js/src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ export {
Eval,
Reporter,
defaultErrorScoreHandler,
defineScorer,
} from "./framework";

export type { WorkflowEvalStore } from "./workflow-eval";
Expand Down
74 changes: 74 additions & 0 deletions js/src/framework.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { type ExperimentEvent } from "../util";
import {
defaultErrorScoreHandler,
defineScorer,
Eval,
EvalScorer,
runEvaluator,
Expand All @@ -23,6 +24,7 @@ import {
injectTraceContext,
TestBackgroundLogger,
_internalWithParent,
_internalGetGlobalState,
} from "./logger/core";
import { parseBaggage } from "./propagation";
import { configureNode } from "./node/config";
Expand All @@ -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<string, string, string>;
const result: Promise<number | null> = 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",
Expand Down
37 changes: 37 additions & 0 deletions js/src/framework.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import {
StartSpanArgs,
currentSpan,
flush,
login,
logError as logSpanError,
startSpan,
traced,
Expand Down Expand Up @@ -190,6 +191,42 @@ export type EvalScorer<
args: EvalScorerArgs<Input, Output, Expected, Metadata>,
) => OneOrMoreScores | Promise<OneOrMoreScores>;

/**
* 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<unknown, unknown, void> & {
expected?: unknown;
metadata?: Record<string, unknown>;
},
Result extends OneOrMoreScores,
>(
callback: (args: Args) => Result | Promise<Result>,
): (args: Args) => Promise<Result> {
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<
Expand Down
15 changes: 9 additions & 6 deletions js/src/logger/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1383,6 +1383,7 @@ export class BraintrustState {
}
}

const stateKey = Symbol.for("braintrust-state-v4");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Coordinate instrumentation ownership with the isolated state

When an older SDK copy registers provider instrumentation first, this new state key separates the newer copy's logger and current span, but instrumentation remains shared: instrumentation/registry.ts still deduplicates providers through braintrust.registry.global-hooks.v2, and the invocation hooks retain protocol version 2. Consequently, the newer copy skips registering its own tracing interceptors, and provider calls inside its traced() or defineScorer() callbacks execute the older copy's tracing functions against the older state. Those calls can become no-op spans or log to the older logger instead of joining the new trace. Coordinate instrumentation ownership with the state isolation so mixed-version processes retain correctly parented provider spans.

AGENTS.md reference: AGENTS.md:L53-L53

Useful? React with 👍 / 👎.

let _globalState: BraintrustState;

/**
Expand All @@ -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;
Expand Down Expand Up @@ -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 {
Expand All @@ -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}).
Expand Down Expand Up @@ -5806,7 +5809,7 @@ export async function flush(options?: OptionalStateArg): Promise<void> {
globalThis as typeof globalThis & {
[key: symbol]: BraintrustState | undefined;
}
)[Symbol.for("braintrust-state")];
)[stateKey];
await state?.bgLogger().flush();
}

Expand Down
9 changes: 8 additions & 1 deletion js/src/logger/lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -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;
}
});
Expand Down
43 changes: 43 additions & 0 deletions js/src/propagation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ import {
initLogger,
injectTraceContext,
startSpan,
_internalWithParent,
withCurrent,
NOOP_SPAN,
} from "./logger/core";
import {
BAGGAGE_HEADER,
Expand Down Expand Up @@ -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();
Expand Down
2 changes: 1 addition & 1 deletion js/src/wrappers/mastra.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down