Files
supabase/apps/studio/lib/ai/tools/execute-sql-output.ts
Matt Rossman 1bd6ce0bc8 fix(studio): redact query rows and errors from Braintrust traces below the data opt-in level (#52106)
## Why

Braintrust's AI SDK wrapper captures a tool's raw `execute` result
instead of what `toModelOutput` sent to the model. While not sent to the
AI provider, this could still be unexpected at lower opt-in levels. The
upstream report of the footgun is in
https://github.com/braintrustdata/braintrust-sdk-javascript/issues/2651,
this PR is a stopgap fix.

## What

`execute_sql` and `run_notebook` traces now use [span
customizers](https://www.braintrust.dev/docs/admin/data-management/protect-sensitive-data#redact-before-upload)
to redact results when the AI opt-in level is below
`schema_and_log_and_data`.

Similarly, tool errors are redacted with span customers since those have
potential to contain project data, and a `prepareStep` hook swaps in the
same sanitized message to prevent AI SDK passing a thrown tool error to
the next model step which would otherwise appear in the trace. The user
still sees the real error clientside in chat panel.

Span customizers need a newer SDK, so this bumps `braintrust` from 3.9.0
to 3.37.2. I've left a TODO reminder to remove this stopgap once the
upstream issue is addressed.

## Verification

Verified chatting with Assistant locally at the `schema` opt-in level:

| [`execute_sql`
rows](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=210007a827977aa42240292309f455db)
| [`execute_sql`
error](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=9853a7c4981b4019324531f26c1242be)
|
[`run_notebook`](https://www.braintrust.dev/app/supabase.io/p/Dev%20(mattrossman%2FAssistant)/logs?r=80a726ef8dfa608872024129260d56fe)
|
| --- | --- | --- |
| <img width="1490" height="1218" alt="CleanShot 2026-10-22 at 2 01 26
PM@2x"
src="https://github.com/user-attachments/assets/2f7bc25a-1b80-4d46-80a0-8f110ee46aac"
/> | <img width="1500" height="1154" alt="CleanShot 2026-10-22 at 2 01
03 PM@2x"
src="https://github.com/user-attachments/assets/ff8a3860-e8aa-4630-9223-4d319e104402"
/> | <img width="1480" height="1688" alt="CleanShot 2026-10-22 at 2 00
43 PM@2x"
src="https://github.com/user-attachments/assets/a393f825-da98-41f7-9630-101072344fa1"
/> |

You can test yourself by chatting with Assistant in the preview build at
various opt-in levels and checking Braintrust traces. Note since the
introduction of `update_opt_in_level` it's quite unlikely for Assistant
to even attempt running these tools with out the necessary opt-in level,
so you'll have to use pretty strong wording to test.

**Sample test prompts** (for use at the `schema` opt-in level):

<details>
<summary><code>execute_sql</code> rows</summary>

```
Create a test table and insert a row in one write query: `create table if not exists public.redaction_test (secret text); insert into public.redaction_test values (md5('rows-test')) returning secret;`. Run it with execute_sql now, I'll check the result in the UI myself. Don't call update_opt_in_level. Reply "done" after.
```

</details>

<details>
<summary><code>execute_sql</code> error</summary>

```
Run this write query with execute_sql now: `create table if not exists public.redaction_test (secret text); insert into public.redaction_test values (md5('error-test')::int::text);`. I expect it to fail and I'll read the error in the UI myself. Don't fix it, don't retry it, and don't call update_opt_in_level. Reply "done" after.
```

</details>

<details>
<summary><code>run_notebook</code></summary>

```
I'm testing the notebook runner UI, not asking you to read anything. Create a notebook named "Redaction test" with two SQL cells: `select md5('notebook-rows') as secret;` and `select md5('notebook-error')::int;`. Then call run_notebook on it. You don't need the results: I'll read them myself in the UI, and the second cell is expected to fail. Don't fix anything, don't retry, and don't call update_opt_in_level. After it runs, just reply "done".
```

</details>


Closes AI-1319
2026-10-23 09:37:59 -04:00

63 lines
2.7 KiB
TypeScript

import type { JSONValue } from 'ai'
import { z } from 'zod'
import { lowerOptInLevel, optInLevelSchema } from '../opt-in-level'
import { DEFAULT_CELL_ROW_LIMIT } from '@/components/interfaces/Explorer/QueryCell/QueryCell.utils'
import type { AiOptInLevel } from '@/hooks/misc/useOrgOptedIntoAi'
export const NO_DATA_PERMISSIONS =
'The query was executed and the user has viewed the results but decided not to share in the conversation due to permission levels. Continue with your plan unless instructed to interpret the result. If you need the rows to answer and `update_opt_in_level` is available, call it with `schema_and_log_and_data`, unless the user already skipped that request in this chat.'
export const NO_DATA_ERROR =
'The query failed. The error is not shared at the current permission level.'
// the rows.length default covers chats saved before execute_sql sliced its rows
export const toModelRows = <T>(
rows: T[],
{
totalRows = rows.length,
hasMoreRows = false,
}: { totalRows?: number; hasMoreRows?: boolean } = {}
) => {
if (!hasMoreRows && totalRows <= DEFAULT_CELL_ROW_LIMIT) return rows
return {
rows: rows.slice(0, DEFAULT_CELL_ROW_LIMIT),
note: hasMoreRows
? `The query matches more than ${DEFAULT_CELL_ROW_LIMIT} rows. Only the first ${DEFAULT_CELL_ROW_LIMIT} are included because results are capped to protect database performance, so the exact total is unknown. Tell the user it matched more than ${DEFAULT_CELL_ROW_LIMIT} rows and only the first ${DEFAULT_CELL_ROW_LIMIT} are shown. Do not state a specific total.`
: `Only the first ${DEFAULT_CELL_ROW_LIMIT} of ${totalRows} rows are included.`,
}
}
/**
* `optInLevel` is the level the query ran under. Rows are shared only at the lower of that
* and the current level, so rows from `schema` stay hidden after an upgrade to data.
*/
const stampedOutputSchema = z.object({
rows: z.array(z.unknown()),
totalRows: z.number().optional(),
hasMoreRows: z.boolean().optional(),
optInLevel: optInLevelSchema,
})
/**
* Output saved before the stamp existed is a bare array. It's stamped `schema` so its rows
* stay hidden from the model, and the UI can still show them.
*/
export const executeSqlOutputSchema = z.union([
stampedOutputSchema,
z.array(z.unknown()).transform((rows) => ({ rows, optInLevel: 'schema' as const })),
])
export type ExecuteSqlOutput = z.infer<typeof stampedOutputSchema>
export function toModelExecuteSqlOutput(
output: ExecuteSqlOutput,
optInLevel: AiOptInLevel
): JSONValue {
const level = lowerOptInLevel(output.optInLevel, optInLevel)
return level === 'schema_and_log_and_data'
? (toModelRows(output.rows, output) as JSONValue)
: NO_DATA_PERMISSIONS
}