Repository navigation
feat(studio): assistant logs context and reports guard - #48514
Conversation
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
5 Skipped Deployments
|
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughAdds logs-source handling across SQL execution, AI debugging, assistant attachments, assistant context generation, and report rendering. Logs snippets receive ClickHouse-aware formatting and guidance, while report blocks avoid executing unsupported log queries. ChangesLogs-aware SQL and AI flows
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant SQL_Editor
participant AIAssistant
participant SQL_API
participant Assistant_Response
SQL_Editor->>AIAssistant: attach source-aware snippet
AIAssistant->>SQL_API: send snippet metadata
SQL_API->>Assistant_Response: pass includesLogsSnippets
Assistant_Response-->>SQL_API: add ClickHouse logs context
SQL_API-->>AIAssistant: generate assistant response
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts`:
- Around line 571-576: Update buildDebugPromptText in
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts (lines 571-576)
to derive the SQL fence language from source, using clickhouse for logs and sql
otherwise. Update the related assertion in
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts (lines
1489-1496) to require the logs prompt to contain a clickhouse fence.
In `@apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx`:
- Around line 340-352: Update the metadata construction in the message-building
flow around containsLogsSnippets so it is only true when logs snippets are
actually included in finalContent. Respect the aiOptInLevel === 'disabled' path
that omits snippets, preventing the server from injecting ClickHouse context for
messages without a logs attachment.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro Plus
Run ID: dd978035-e409-40f6-8396-3e22db1085c9
📒 Files selected for processing (23)
apps/studio/components/interfaces/Reports/ReportBlock/LogsSnippetReportBlock.tsxapps/studio/components/interfaces/Reports/ReportBlock/ReportBlock.tsxapps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.tsapps/studio/components/interfaces/SQLEditor/SQLEditor.utils.tsapps/studio/components/interfaces/SQLEditor/querySource.test.tsapps/studio/components/interfaces/SQLEditor/querySource.tsapps/studio/components/interfaces/SQLEditor/useRunSource.tsapps/studio/components/interfaces/SQLEditor/useSqlEditorAi.test.tsxapps/studio/components/interfaces/SQLEditor/useSqlEditorAi.tsapps/studio/components/ui/AIAssistantPanel/AIAssistant.tsxapps/studio/components/ui/AIAssistantPanel/AIAssistant.types.tsapps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.test.tsapps/studio/components/ui/AIAssistantPanel/AIAssistant.utils.tsapps/studio/components/ui/AIAssistantPanel/AIOnboarding.tsxapps/studio/components/ui/AIAssistantPanel/AssistantChatForm.tsxapps/studio/components/ui/AIAssistantPanel/SnippetRow.tsxapps/studio/lib/ai/assistant-context.test.tsapps/studio/lib/ai/assistant-context.tsapps/studio/lib/ai/assistant-message-metadata.test.tsapps/studio/lib/ai/assistant-message-metadata.tsapps/studio/lib/ai/generate-assistant-response.tsapps/studio/pages/api/ai/sql/generate-v4.tsapps/studio/state/ai-assistant-state.tsx
💤 Files with no reviewable changes (1)
- apps/studio/components/ui/AIAssistantPanel/AIAssistant.types.ts
| export function buildDebugPromptText( | ||
| sql: string, | ||
| errorMessage: string, | ||
| source: SqlSnippetSource | ||
| ): string { | ||
| return `${buildDebugRequestText(errorMessage, source)}\n\nSQL Query:\n\`\`\`sql\n${sql}\n\`\`\`` |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use a ClickHouse fence for logs debug prompts.
Line 576 always emits ```sql, so copied logs prompts contradict the dialect-specific formatting contract and can be interpreted as Postgres SQL.
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts#L571-L576: derive the fence language fromsource(clickhousefor logs,sqlotherwise).apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts#L1489-L1496: assert the logs prompt contains a```clickhousefence.
📍 Affects 2 files
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts#L571-L576(this comment)apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts#L1489-L1496
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts` around lines
571 - 576, Update buildDebugPromptText in
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts (lines 571-576)
to derive the SQL fence language from source, using clickhouse for logs and sql
otherwise. Update the related assertion in
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts (lines
1489-1496) to require the logs prompt to contain a clickhouse fence.
| // Read off the attachments this message actually carries, so detaching the | ||
| // "Current Query" chip also drops the claim. Rides on the message rather than the | ||
| // request: a Retry then reproduces the context the message was asked in. | ||
| const metadata: AssistantMessageMetadata = { | ||
| containsLogsSnippets: containsLogsSnippets(snap.sqlSnippets), | ||
| } | ||
|
|
||
| const payload = { | ||
| role: 'user', | ||
| createdAt: new Date(), | ||
| parts: [{ type: 'text', text: finalContent }], | ||
| id: uuidv4(), | ||
| metadata, |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Gate logs metadata with snippet inclusion.
When aiOptInLevel === 'disabled', Line 667 omits snippets from finalContent, but Line 344 can still set containsLogsSnippets: true. The server then injects ClickHouse context for a message that carries no logs attachment.
Proposed fix
const metadata: AssistantMessageMetadata = {
- containsLogsSnippets: containsLogsSnippets(snap.sqlSnippets),
+ containsLogsSnippets:
+ aiOptInLevel !== 'disabled' && containsLogsSnippets(snap.sqlSnippets),
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // Read off the attachments this message actually carries, so detaching the | |
| // "Current Query" chip also drops the claim. Rides on the message rather than the | |
| // request: a Retry then reproduces the context the message was asked in. | |
| const metadata: AssistantMessageMetadata = { | |
| containsLogsSnippets: containsLogsSnippets(snap.sqlSnippets), | |
| } | |
| const payload = { | |
| role: 'user', | |
| createdAt: new Date(), | |
| parts: [{ type: 'text', text: finalContent }], | |
| id: uuidv4(), | |
| metadata, | |
| // Read off the attachments this message actually carries, so detaching the | |
| // "Current Query" chip also drops the claim. Rides on the message rather than the | |
| // request: a Retry then reproduces the context the message was asked in. | |
| const metadata: AssistantMessageMetadata = { | |
| containsLogsSnippets: | |
| aiOptInLevel !== 'disabled' && containsLogsSnippets(snap.sqlSnippets), | |
| } | |
| const payload = { | |
| role: 'user', | |
| createdAt: new Date(), | |
| parts: [{ type: 'text', text: finalContent }], | |
| id: uuidv4(), | |
| metadata, |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@apps/studio/components/ui/AIAssistantPanel/AIAssistant.tsx` around lines 340
- 352, Update the metadata construction in the message-building flow around
containsLogsSnippets so it is only true when logs snippets are actually included
in finalContent. Respect the aiOptInLevel === 'disabled' path that omits
snippets, preventing the server from injecting ClickHouse context for messages
without a logs attachment.
🎭 Playwright Test Results (tanstack)Details
Flaky testsFeatures › table-editor.spec.ts › table editor › shortcut saves fk before column update Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
c69fa0b to
0649bd1
Compare
0649bd1 to
23317cf
Compare
joshenlim
left a comment
There was a problem hiding this comment.
Preview test — ✅ all pass
Ran through the flag-gated logs-context work on the studio-staging preview (sqlEditorLogsSource + otelLegacyLogs enabled via the dev toolbar). No explicit "To test" section on this PR, so I inferred the checklist from the description — the Assistant fencing/metadata, the debug flow, and the negative (Postgres) regressions for each. Reports guard was intentionally left out of scope — the report snippet picker filters to type: 'sql' so there's no UI path to reach that state on the preview, and it's already covered by the PR's own new unit tests.
| # | Test | Result |
|---|---|---|
| 1 | "Create a new logs query" appears in the SQL Editor + menu with both flags on |
✅ Opens a tab at ?source=logs, toolbar shows "Query source: Logs" instead of "Role: postgres" |
| 2 | Assistant fences an attached logs query as ClickHouse + sets metadata | ✅ Outgoing message: ```clickhouse\nselect count() from logs\n```, metadata.containsLogsSnippets: true |
| 3 | Regression — normal query still fences as sql | ✅ ```sql\nselect 1\n```, containsLogsSnippets: false |
| 4 | ClickHouse block isn't offered as runnable Postgres | ✅ Rendered clickhouse block only has a copy button, no Run affordance (Run is gated on language === 'sql') |
| 5 | Debug flow names the dialect for a failing logs query | ✅ Prefilled prompt: "...This query runs against the Supabase logs table on a ClickHouse-backed engine, not Postgres.", ```clickhouse fence, containsLogsSnippets: true |
| 6 | Regression — debug flow for a failing Postgres query stays untouched | ✅ Real 42P01 error, no ClickHouse mention, ```sql fence, containsLogsSnippets: false |
Notes:
- Reports guard (logs snippet → placeholder instead of executing) wasn't UI-reachable on this preview and was skipped by design — deferred to the PR's own unit tests for that path.
- Heads up unrelated to the ClickHouse logic: if an org's AI opt-in level is set to "Disabled," the "Current Query" chip still shows as attached in the Assistant panel, but the snippet content is silently dropped from the outgoing message. Worth a look separately, not a regression from this PR.
- No console errors beyond an expected 400 from the deliberately-invalid query in test 6.
- No screenshots — nothing visual to verify, everything checked at the network/DOM level.
joshenlim
left a comment
There was a problem hiding this comment.
Changes generally LGTM - minimally tested on preview
- Debug with Assistant for logs query
- Debug with Assistant for SQL query
just lemme know if there's anything else i should be looking out for tho!
Final PR of the SQL editor logs-source stack. Two independent pieces:
Assistant panel — the "Current Query" chip now records which backend the
attached query targets, and that travels to the model two ways: each
attachment is fenced with its own dialect in the message text
(```clickhouse vs ```sql), and a containsLogsSnippets flag rides on the
user message as AI SDK metadata. The server reads the flag off the
conversation and prepends the ClickHouse dialect rules plus the logs
schema reference as a non-cached context message.
Putting this on the message rather than the request body is what makes
Retry and the tool-approval continuation reproduce the context a message
was originally asked in — neither passes a per-call body. Deriving it
from the attachments is what makes detaching the chip drop the claim.
The clickhouse fence also keeps a logs query out of MessageMarkdown's
`sql` branch, which offers to run the block against Postgres and brands
it with untrustedSql — a boundary this stack's distinct brands exist to
prevent crossing.
The debug flow ("Debug with Assistant") attaches its query with a source
for the same reason, and names the dialect in the prompt text so the
copyable version stands on its own outside the app.
Reports — a report only stores a snippet id, so whether it queries the
logs backend is only knowable after the content loads. ReportBlock now
guards on the fetched type and renders a LogsSnippetReportBlock
placeholder instead of running ClickHouse SQL against Postgres.
Also extracts buildAssistantContextMessages out of
generate-assistant-response, and replaces a schema-access sentinel that
was duplicated as a string literal across two files with one constant.
Two review follow-ups, both cases of the dialect claim drifting from what the message actually carries. The debug prompt fenced its SQL as ```sql regardless of source, so a logs query read as Postgres in the copyable "Copy prompt" text — inconsistent with how the attachment formatter labels the same query. Both now derive the fence from one shared sqlSourceToFenceLanguage, rather than adding a third copy of the mapping. containsLogsSnippets was computed independently of whether attachments are sent at all. With AI opt-in disabled the "Current Query" chip still renders but the chat form drops the query from the message text, so the flag claimed a logs attachment for a message holding no query and the server prepended ClickHouse context for nothing. Both now read one hoisted includeSnippetsInMessage, so they can't disagree.
23317cf to
3d05a08
Compare
Braintrust eval report
|
I have read the CONTRIBUTING.md file.
YES
What kind of change does this PR introduce?
Feature — final PR (9/9) of the SQL editor logs-source stack.
Base branch:
charislam/sql-editor-inline-ai-clickhouse-dialect(PR 8). Nothing here is user-visible: entry points stay behindsqlEditorLogsSource+otelLegacyLogs, and flag rollout happens after the whole stack merges.What is the current behavior?
```sqland nothing tells the model otherwise.sqlfence is whatMessageMarkdowntreats as runnable Postgres, an attached ClickHouse query is rendered with a Run-against-Postgres affordance and branded withuntrustedSql.log_sqlsnippet runs its ClickHouse SQL against the user's Postgres database and surfaces the resulting error.What is the new behavior?
Assistant panel. The "Current Query" chip records which backend the attached query targets. That reaches the model two ways: each attachment is fenced with its own dialect (
```clickhousevs```sql), and acontainsLogsSnippetsflag rides on the user message as AI SDKmetadata. The server reads the flag off the conversation and prepends the ClickHouse dialect rules plus the logs schema reference as a non-cached context message.Two design points worth calling out in review:
The
clickhousefence also keeps a logs query out ofMessageMarkdown'ssqlbranch, so it's no longer offered as runnable Postgres or branded withuntrustedSql— a boundary this stack's distinct brands exist to prevent crossing.Debug flow.
buildDebugChatArgsattaches its query with a source for the same reason, and names the dialect in the prompt text so the copyable version stands on its own outside the app.Reports. A report only stores a snippet id, so whether it queries the logs backend is only knowable once the content loads.
ReportBlockguards on the fetched type and renders aLogsSnippetReportBlockplaceholder instead of executing. Double-guarded: nosqlfor a logs snippet (so it's out of the query key andqueryFnshort-circuits even on an explicitrefetch) andenabledexcludes it.Incidental cleanups.
buildAssistantContextMessagesextracted out ofgenerate-assistant-response; a schema-access sentinel that was duplicated as a string literal across two files (and compared against) replaced with one exported constant;SqlSnippetdeduplicated to a single declaration;resolveSnippetSource/isLogsSourceshared instead of re-implemented per surface.Tests. 4 new/extended suites. Notable cases pinned: a message with no metadata must validate (
safeValidateUIMessagesappliesmetadataSchemato every message, so a required schema would 400 every existing conversation); only user messages count, so a model reply can't talk the server into a different dialect; a mixed-attachment message is flagged without overclaiming a single source; andReportBlockregisters no pg-meta mock for the logs cases, so an unhandled request failing the test is the assertion that logs SQL never reaches Postgres.Verified:
pnpm typecheck,lint:ratchet(no regression), Prettier, and the full Studio suite (459 files / 4969 tests).Additional context
Summary by CodeRabbit
New Features
Bug Fixes