Files
supabase/apps/studio/lib/ai/braintrust-logger.sdk.test.ts
Matt Rossman afe5b4ed58 fix(studio): remove Braintrust tool output masking workaround (#53244)
Removes the temporary `TODO:` tool output masking introduced in
https://github.com/supabase/supabase/pull/52106 now that [Braintrust
3.40.0](https://github.com/braintrustdata/braintrust-sdk-javascript/releases/tag/braintrust%403.40.0)
logs `toModelOutput` in tool spans and parent span results. SQL error
redaction remains in place.

Verified locally at the `schema` opt-in level by running the Assistant
against a development project. The Braintrust traces for [SQL
rows](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=2bca625a69c40d34ee41289acc073ea5&sid=a6304c155ecf7eed),
[SQL
error](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=b6f0581cbd273c7cd1d70bb6713877d8&sid=43fbbf283faa0da9),
and [notebook
results](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=05409f3af4e66131efa768a03bb8a67f&sid=321520afdd3fa7af)
omit the sample rows and errors shown in Studio.

| Studio | Braintrust |
| --- | --- |
| <a
href="https://github.com/user-attachments/assets/dbf43dda-c78e-4782-acf7-951d8920a283"><img
src="https://github.com/user-attachments/assets/dbf43dda-c78e-4782-acf7-951d8920a283"
width="350" alt="Notebook results at limited sharing"></a> | <a
href="https://github.com/user-attachments/assets/4ff513ae-c76c-47ad-ba1f-0dbc8bcfeee7"><img
src="https://github.com/user-attachments/assets/4ff513ae-c76c-47ad-ba1f-0dbc8bcfeee7"
width="350" alt="Braintrust notebook output with redacted results"></a>
|

Closes AI-1374
2026-11-11 17:28:48 -05:00

144 lines
5.6 KiB
TypeScript

import * as ai from 'ai'
import { convertArrayToReadableStream, MockLanguageModelV4 } from 'ai/test'
import { expect, it } from 'vitest'
import { z } from 'zod'
import { hideToolErrorsFromModel } from './generate-assistant-response.utils'
import { toModelExecuteSqlOutput } from './tools/execute-sql-output'
import { contract as runNotebookContract } from './tools/run-notebook'
type DoStream = Extract<
NonNullable<ConstructorParameters<typeof MockLanguageModelV4>[0]>['doStream'],
(...args: never[]) => unknown
>
type StreamPart =
Awaited<ReturnType<DoStream>>['stream'] extends ReadableStream<infer Part> ? Part : never
// Exercise SDK span exports and approval continuation together.
// approved [rows, error, error] → parallel execution → model step
it('hides rows and errors from the model and Braintrust', async () => {
process.env.BRAINTRUST_API_KEY = 'test'
process.env.BRAINTRUST_PROJECT_ID = '00000000-0000-4000-8000-000000000000'
const braintrust = await import('braintrust')
const { setInitialTestState, simulateLoginForTests, useTestBackgroundLogger } =
braintrust._exportsForTestingOnly
setInitialTestState()
await simulateLoginForTests()
const uploads = useTestBackgroundLogger()
const { hideSpanErrorFromTrace } = await import('./braintrust-logger')
// Use a named test project to avoid a network lookup.
braintrust.initLogger({ projectId: process.env.BRAINTRUST_PROJECT_ID, projectName: 'test' })
const queryErrors = [
new Error('invalid input syntax for type integer: "Walk dog"'),
new Error('invalid input syntax for type integer: "Feed cat"'),
]
const usage = {
inputTokens: { total: 1, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
outputTokens: { total: 1, text: undefined, reasoning: undefined },
}
const prompts: unknown[] = []
const doStream: DoStream = async ({ prompt }) => {
prompts.push(prompt)
return {
stream: convertArrayToReadableStream<StreamPart>([
{ type: 'text-start', id: 'text' },
{ type: 'text-delta', id: 'text', delta: 'done' },
{ type: 'text-end', id: 'text' },
{ type: 'finish', finishReason: { unified: 'stop', raw: undefined }, usage },
]),
}
}
const toolCall = (toolCallId: string, failure: number | null) => ({
type: 'tool-call' as const,
toolCallId,
toolName: 'execute_sql',
input: { failure },
})
const { streamText } = braintrust.wrapAISDK(ai)
const result = streamText({
model: new MockLanguageModelV4({ doStream }),
messages: [
{ role: 'user', content: 'Count signups' },
{
role: 'assistant',
content: [
toolCall('rows', null),
{ type: 'tool-call', toolCallId: 'notebook', toolName: 'run_notebook', input: {} },
{ type: 'tool-approval-request', approvalId: 'approve-notebook', toolCallId: 'notebook' },
{ type: 'tool-approval-request', approvalId: 'approve-rows', toolCallId: 'rows' },
toolCall('error-0', 0),
{ type: 'tool-approval-request', approvalId: 'approve-error-0', toolCallId: 'error-0' },
toolCall('error-1', 1),
{ type: 'tool-approval-request', approvalId: 'approve-error-1', toolCallId: 'error-1' },
],
},
{
role: 'tool',
content: [
{ type: 'tool-approval-response', approvalId: 'approve-rows', approved: true },
{ type: 'tool-approval-response', approvalId: 'approve-notebook', approved: true },
{ type: 'tool-approval-response', approvalId: 'approve-error-0', approved: true },
{ type: 'tool-approval-response', approvalId: 'approve-error-1', approved: true },
],
},
],
prepareStep: ({ messages }) => ({ messages: hideToolErrorsFromModel(messages, 'schema') }),
tools: {
execute_sql: ai.tool({
inputSchema: z.object({ failure: z.number().nullable() }),
needsApproval: true,
execute: async ({ failure }) => {
if (failure === null) {
return { rows: [{ title: 'Buy milk' }], totalRows: 1, optInLevel: 'schema' as const }
}
hideSpanErrorFromTrace()
throw queryErrors[failure]
},
toModelOutput: ({ output }) => ({
type: 'json',
value: toModelExecuteSqlOutput(output, 'schema'),
}),
}),
run_notebook: ai.tool({
inputSchema: z.object({}),
needsApproval: true,
execute: async () => ({
id: 'nb',
name: 'Notebook',
updated_at: '2026-10-21',
optInLevel: 'schema' as const,
cells: [
{
cell_id: 'a',
title: 'Results',
source: 'database' as const,
status: 'success' as const,
rows: [{ title: 'Notebook secret' }],
},
],
}),
toModelOutput: ({ output }) => ({
type: 'json',
value: runNotebookContract.toModelOutput(output, 'schema'),
}),
}),
},
})
const streamParts = []
for await (const part of result.fullStream) streamParts.push(part)
await braintrust.flush()
// Redaction must preserve the errors streamed to the UI.
for (const error of queryErrors) {
expect(streamParts).toContainEqual(expect.objectContaining({ type: 'tool-error', error }))
}
expect(prompts).toHaveLength(1)
const promptsJson = JSON.stringify(prompts)
const uploadsJson = JSON.stringify(await uploads.drain())
for (const secret of ['Buy milk', 'Notebook secret', 'Walk dog', 'Feed cat']) {
expect(promptsJson).not.toContain(secret)
expect(uploadsJson).not.toContain(secret)
}
})