Skip to content
Closed
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/await-traced-promises.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"braintrust": patch
---

fix: Await PromiseLike results before ending traced spans
42 changes: 42 additions & 0 deletions js/src/logger-promise-realms.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { runInNewContext } from "node:vm";
import { expect, test, vi } from "vitest";
import { _exportsForTestingOnly, initLogger } from "./logger";
import { configureNode } from "./node/config";

configureNode();

test("Logger.traced keeps the span open until a foreign promise settles", async () => {
await _exportsForTestingOnly.simulateLoginForTests();
const memoryLogger = _exportsForTestingOnly.useTestBackgroundLogger();

try {
let resolve!: (value: number) => void;
const promise: Promise<number> = runInNewContext(
"new Promise(resolve => capture(resolve))",
{
capture: (resolvePromise: (value: number) => void) => {
resolve = resolvePromise;
},
},
);
const logger = initLogger({
projectName: "test",
projectId: "test-project-id",
});
let endCalls = () => 0;
const result = logger.traced((span) => {
const end = vi.spyOn(span, "end");
endCalls = () => end.mock.calls.length;
return promise;
});

expect(endCalls()).toBe(0);
resolve(42);
await expect(result).resolves.toBe(42);
expect(endCalls()).toBe(1);
await memoryLogger.flush();
} finally {
_exportsForTestingOnly.clearTestBackgroundLogger();
_exportsForTestingOnly.simulateLogoutForTests();
}
});
136 changes: 135 additions & 1 deletion js/src/util.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,139 @@
import { runInNewContext } from "node:vm";
import { expect, test } from "vitest";
import { LazyValue } from "./util";
import { LazyValue, runCatchFinally } from "./util";

function createForeignPromise(subclass = false) {
let resolve!: (value: string) => void;
let reject!: (reason: Error) => void;
const promise: Promise<string> = runInNewContext(
`${subclass ? "class ForeignPromise extends Promise {}" : ""}
new ${subclass ? "ForeignPromise" : "Promise"}((resolve, reject) => capture(resolve, reject))`,
{
capture: (
resolvePromise: (value: string) => void,
rejectPromise: (reason: Error) => void,
) => {
resolve = resolvePromise;
reject = rejectPromise;
},
},
);
return { promise, resolve, reject };
}

test("runCatchFinally waits for a promise from another realm", async () => {
const { promise, resolve } = createForeignPromise();
expect(promise).not.toBeInstanceOf(Promise);
const events: string[] = [];
const result = runCatchFinally(
() => promise,
(error) => {
throw error;
},
() => events.push("finally"),
);

expect(events).toEqual([]);
resolve("done");
await expect(result).resolves.toBe("done");
expect(events).toEqual(["finally"]);
});

test("runCatchFinally catches rejection from another realm before cleanup", async () => {
const { promise, reject } = createForeignPromise();
const error = new Error("foreign rejection");
const events: string[] = [];
const result = runCatchFinally(
() => promise,
(caught) => {
expect(caught).toBe(error);
events.push("catch");
throw caught;
},
() => events.push("finally"),
);

reject(error);
await expect(result).rejects.toBe(error);
expect(events).toEqual(["catch", "finally"]);
});

test("runCatchFinally preserves foreign Promise subclass chaining", async () => {
const { promise, resolve } = createForeignPromise(true);
const events: string[] = [];
const result = runCatchFinally(
() => promise,
(error) => {
throw error;
},
() => events.push("finally"),
);

expect(result.constructor).toBe(promise.constructor);
expect(events).toEqual([]);
resolve("foreign subclass");
await expect(result).resolves.toBe("foreign subclass");
expect(events).toEqual(["finally"]);
});

test("runCatchFinally preserves native Promise subclass chaining", async () => {
class SpecializedPromise<T> extends Promise<T> {}
const promise = new SpecializedPromise<string>((resolve) =>
resolve("native subclass"),
);
const result = runCatchFinally(
() => promise,
(error) => {
throw error;
},
() => {},
);

expect(result).toBeInstanceOf(SpecializedPromise);
await expect(result).resolves.toBe("native subclass");
});

test("runCatchFinally waits for a thenable without catch or finally methods", async () => {
const promise = Promise.resolve("thenable result");
const events: string[] = [];
const result = runCatchFinally(
() => ({ then: promise.then.bind(promise) }),
(error) => {
throw error;
},
() => events.push("finally"),
);

expect(events).toEqual([]);
expect(await result).toBe("thenable result");
expect(events).toEqual(["finally"]);
});

test("runCatchFinally preserves synchronous return and error handling", () => {
const events: string[] = [];
expect(
runCatchFinally(
() => 42,
() => 0,
() => events.push("finally"),
),
).toBe(42);
expect(events).toEqual(["finally"]);

expect(
runCatchFinally(
(): number => {
throw new Error("sync failure");
},
() => {
events.push("catch");
return 17;
},
() => events.push("finally"),
),
).toBe(17);
expect(events).toEqual(["finally", "catch", "finally"]);
});

test("LazyValue evaluates exactly once", async () => {
let callCount = 0;
Expand Down
15 changes: 13 additions & 2 deletions js/src/util.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isPromiseLike } from "../util";

export * from "../util";

export const GLOBAL_PROJECT = "Global";
Expand All @@ -13,10 +15,19 @@ export function runCatchFinally<R>(
let runSyncCleanup = true;
try {
const ret = f();
if (ret instanceof Promise) {
const isNativePromise = ret instanceof Promise;
if (isNativePromise || isPromiseLike(ret)) {
const promise =
isNativePromise ||
("catch" in ret &&
typeof ret.catch === "function" &&
"finally" in ret &&
typeof ret.finally === "function")
? ret
: Promise.resolve(ret);
runSyncCleanup = false;
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions, @typescript-eslint/no-explicit-any
return (ret as any).catch(catchF).finally(finallyF) as R;
return (promise as any).catch(catchF).finally(finallyF) as R;
} else {
return ret;
}
Expand Down