diff --git a/.changeset/await-traced-promises.md b/.changeset/await-traced-promises.md new file mode 100644 index 000000000..be7a2b537 --- /dev/null +++ b/.changeset/await-traced-promises.md @@ -0,0 +1,5 @@ +--- +"braintrust": patch +--- + +fix: Await PromiseLike results before ending traced spans diff --git a/js/src/logger-promise-realms.test.ts b/js/src/logger-promise-realms.test.ts new file mode 100644 index 000000000..3aa71f81d --- /dev/null +++ b/js/src/logger-promise-realms.test.ts @@ -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 = 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(); + } +}); diff --git a/js/src/util.test.ts b/js/src/util.test.ts index a6e98b579..acb54d217 100644 --- a/js/src/util.test.ts +++ b/js/src/util.test.ts @@ -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 = 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 extends Promise {} + const promise = new SpecializedPromise((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; diff --git a/js/src/util.ts b/js/src/util.ts index 97b2b0dc9..31cb36daf 100644 --- a/js/src/util.ts +++ b/js/src/util.ts @@ -1,3 +1,5 @@ +import { isPromiseLike } from "../util"; + export * from "../util"; export const GLOBAL_PROJECT = "Global"; @@ -13,10 +15,19 @@ export function runCatchFinally( 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; }