Skip to content

feat(studio): ClickHouse dialect for logs snippet AI + rewrite to ClickHouse - #48501

Merged
charislam merged 6 commits into
charislam/nav-logs-section-search-tabsfrom
charislam/sql-editor-inline-ai-clickhouse-dialect
Aug 4, 2026
Merged

charislam merged 6 commits into
charislam/nav-logs-section-search-tabsfrom
charislam/sql-editor-inline-ai-clickhouse-dialect

Conversation

@charislam

@charislam charislam commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

I have read the CONTRIBUTING.md file.

YES

What kind of change does this PR introduce?

Feature, plus a refactor of the shared logs-rewrite flow.

PR 8 of the SQL editor query-source series. Stacked on #48457 — review that one first, and merge this after it.

What is the current behavior?

A log_sql snippet runs against the ClickHouse-backed analytics endpoint, but the SQL editor's AI still writes Postgres: inline edits get Postgres system prompts, and the result is run through sql-formatter, which mangles ClickHouse backticks and log_attributes map lookups.

Legacy Logs Explorer saved queries open in the editor as log_sql snippets. Those are BigQuery dialect and error against the ClickHouse endpoint the editor runs them on, with no in-editor way out — only the Logs Explorer offered a rewrite.

The completion route was also asymmetric. It assembled a schema/code/instruction message for Postgres but forwarded prompt verbatim for ClickHouse, so a client wanting ClickHouse had to hand-build the equivalent string.

What is the new behavior?

Inline AI speaks ClickHouse for logs snippets. sqlSourceToDialect maps a snippet's source to postgres/clickhouse and buildCompletionRequestBody threads it through. For ClickHouse, useSqlEditorAi strips code fences from the response and skips formatSql. Execution and dialect both follow the snippet type, so a snippet's valid dialect never flips.

Rewrite to ClickHouse in the editor. A banner offers the rewrite for a logs snippet whose text trips looksLikeLegacyLogsQuery, and proposes the result through the editor's existing AI diff view rather than replacing the snippet, so it's accepted or discarded like any other AI edit. Gated on otelLegacyLogs: on a non-migrated org the BigQuery text is still correct, so rewriting it would break a working query.

The offer is a state machine (offered / rewriting / failed / noRewriteNeeded / dismissed) with a declarative table of valid transitions, so the states are mutually exclusive by construction and dismissal is terminal. A failure keeps its message and offers a retry; a response identical to the input is reported rather than opening an empty diff.

One place assembles completion prompts. The route now uses a single template for both dialects, branching only the schema section and — for intent: 'rewrite' — the instruction. lib/ai/clickhouse-logs.ts is the single home for ClickHouse-logs prompt content, replacing two independently maintained descriptions of the same table. Clients carry no prompt text.

The rewrite flow is shared with the Logs Explorer. Both surfaces previously hand-rolled the same sequence and had drifted: only one detected a no-op rewrite, they sourced log_attributes keys differently, and the Explorer formatted errors with an as Error cast. Both now use useLegacyLogsRewrite and the same state-driven banner, so the Explorer picks up no-op detection and typed error extraction.

Attribute keys are fetched on submit, not while typing. The detected source would otherwise feed a reactive query key, making every edit that changed it cost another network call. useLogsAttributeKeys is imperative and goes through queryClient.fetchQuery, so a source already cached — including by the Explorer header and query panel, which subscribe reactively — is reused. This also closes a gap where inline edits never received keys at all, unlike full rewrites.

getErrorMessage gains an optional typed fallback and no longer stringifies a bare object into '[object Object]'; every existing caller already hand-rolled a fallback, except QueueSettings, which interpolated the raw result and now passes one.

Nothing here is user-visible until the sqlEditorLogsSource flag is enabled.

Tests: dialect selection and request-body shape, the ClickHouse prompt content (including that the schema section does not restate the dialect rules), the reducer's valid and invalid transitions, shouldOfferLegacyLogsRewrite, on-submit key discovery with cache reuse, and getErrorMessage.

Additional context

Summary by CodeRabbit

  • New Features

    • Added an Assistant banner to help rewrite legacy BigQuery-style logs queries into ClickHouse SQL.
    • SQL assistance now adapts to the selected query type, including relevant log attribute context.
    • Rewrite suggestions can be reviewed as editor diffs before being applied.
  • Bug Fixes

    • Improved rewrite failure handling, retry options, dismissal behavior, and “no rewrite needed” messaging.
    • Error notifications now provide a clearer fallback message when details are unavailable.

@charislam
charislam requested a review from a team as a code owner July 30, 2026 16:55
@vercel

vercel Bot commented Jul 30, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
design-system Ready Ready Preview Aug 4, 2026 12:44pm
docs Ready Ready Preview, v0 Aug 4, 2026 12:44pm
studio-self-hosted Ready Ready Preview Aug 4, 2026 12:44pm
studio-staging Ready Ready Preview Aug 4, 2026 12:44pm
ui-library Ready Ready Preview Aug 4, 2026 12:44pm
zone-www-dot-com Ready Ready Preview, v0 Aug 4, 2026 12:44pm
1 Skipped Deployment
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Aug 4, 2026 12:44pm

Request Review

@supabase

supabase Bot commented Jul 30, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project xguihxuzqibwxjnimxev because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: f87b81a5-10c0-43f4-b6ac-3b14d25dac3e

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The PR adds ClickHouse-aware SQL completion and legacy BigQuery logs rewriting, including dynamic log attribute schemas, rewrite state management, editor diff integration, and new banner UI. It also normalizes error-message extraction and adds an explicit queue-save error fallback.

Changes

ClickHouse logs assistance

Layer / File(s) Summary
ClickHouse completion and rewrite API
apps/studio/lib/ai/clickhouse-logs.ts, apps/studio/lib/ai/prompts.ts, apps/studio/pages/api/ai/code/complete.ts, apps/studio/data/logs/logs-sql-rewrite.*
Completion requests accept ClickHouse schema metadata and rewrite intent, while legacy SQL is submitted through the completion API and cleaned of SQL fences.
Cached log attribute discovery
apps/studio/data/logs/keys.ts, apps/studio/data/logs/otel-log-keys-query.ts, apps/studio/hooks/analytics/useLogsAttributeKeys.*
OTEL log attribute keys use shared React Query options and source-specific caching through fetchAttributeKeys.
Source-aware editor completion
apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.*, apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.*, apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
Snippet sources map to SQL dialects, ClickHouse requests include available keys, and completion output uses dialect-specific formatting and fence handling.
Legacy rewrite orchestration
apps/studio/hooks/analytics/useLegacyLogsRewrite.*
A reducer and hook manage rewrite requests, proposals, failures, retries, no-op results, stale edits, and dismissal.
Rewrite banners and editor integration
apps/studio/components/interfaces/SQLEditor/*Banner.tsx, apps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsx, apps/studio/components/interfaces/Settings/Logs/LegacyLogsRewriteAdmonition.tsx, apps/studio/pages/project/[ref]/logs/explorer/index.tsx
The rewrite flow is wired into the SQL editor and logs explorer with status-based admonitions and editor diff proposals, replacing the former page-local implementation.

Error message normalization

Layer / File(s) Summary
Normalized error extraction
apps/studio/lib/get-error-message.*
getErrorMessage now trims valid messages, returns null for unusable values, and supports explicit fallbacks.
Queue error fallback
apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsx
Queue save errors now use an unknown error fallback.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LogsExplorer
  participant LegacyLogsRewrite
  participant CompletionAPI
  participant EditorDiff
  LogsExplorer->>LegacyLogsRewrite: Request rewrite for current SQL
  LegacyLogsRewrite->>CompletionAPI: Submit ClickHouse rewrite request
  CompletionAPI-->>LegacyLogsRewrite: Return rewritten SQL
  LegacyLogsRewrite->>EditorDiff: Publish original and modified SQL
  EditorDiff-->>LogsExplorer: Show modification diff
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.83% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: adding ClickHouse dialect support and logs rewrite flow.
Description check ✅ Passed The description matches the required template and covers the change, current behavior, and new behavior with useful context.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch charislam/sql-editor-inline-ai-clickhouse-dialect

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@charislam

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@github-actions

github-actions Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (tanstack)

passed  242 passed
flaky  1 flaky
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  4 minutes, 8 seconds
commit  61fa2be

Flaky tests

Features › table-editor.spec.ts › table editor › copying cell values preserves false and zero

Skipped tests

Features › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled
Features › sql-editor.spec.ts › SQL Editor › snippet favourite works as expected
Features › sql-editor.spec.ts › SQL Editor › share with team works as expected
Features › sql-editor.spec.ts › SQL Editor › folders works as expected
Features › sql-editor.spec.ts › SQL Editor › other SQL snippets actions work as expected

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (5)
apps/studio/components/interfaces/SQLEditor/LegacyLogsRewriteBanner.tsx (1)

57-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider tracking the rewrite action.

"Rewrite with Assistant" drives adoption of the new ClickHouse-backed logs engine — this could be a useful useTrack() event (e.g. legacy_logs_rewrite_requested) to measure activation of the migration path.

🤖 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/LegacyLogsRewriteBanner.tsx`
around lines 57 - 76, Track the rewrite action in the LegacyLogsRewriteBanner
flow by adding a useTrack event such as legacy_logs_rewrite_requested when the
user invokes requestRewrite through LegacyLogsRewriteAdmonition. Keep the
existing rewrite behavior and dismissal handling unchanged.

Source: Path instructions

apps/studio/pages/project/[ref]/logs/explorer/index.tsx (1)

181-184: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Undebounced heuristic may cause the rewrite CTA to flicker while typing.

showRewriteCTA re-runs the legacy-dialect heuristic on every keystroke via editorValue, unlike LegacyLogsRewriteBanner.tsx's debounced (500ms) equivalent, which exists specifically to avoid "mid-word" flapping. Consider debouncing editorValue here too for consistency. Also, as per coding guidelines, boolean names should be prefixed with is/has/can/should (e.g. shouldShowRewriteCTA).

🤖 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/pages/project/`[ref]/logs/explorer/index.tsx around lines 181 -
184, Debounce editorValue before passing it to shouldOfferLegacyLogsRewrite,
using the same 500ms behavior as LegacyLogsRewriteBanner, so the heuristic does
not run on every keystroke. Rename showRewriteCTA to shouldShowRewriteCTA and
update all references while preserving the existing CTA behavior.

Source: Coding guidelines

apps/studio/hooks/analytics/useLegacyLogsRewrite.test.ts (1)

1-88: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoff

Reducer tests are solid; consider covering the hook's async orchestration too.

This suite thoroughly tests legacyLogsRewriteReducer, but the async requestRewrite/dismiss logic in useLegacyLogsRewrite (stale-edit race guard, no-op detection, and the dismiss-during-rewrite side effect) isn't exercised anywhere in this file.

🤖 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/hooks/analytics/useLegacyLogsRewrite.test.ts` around lines 1 -
88, Add hook-level tests around useLegacyLogsRewrite’s requestRewrite and
dismiss orchestration, covering stale-edit race protection, no-op detection, and
the dismiss-during-rewrite side effect. Keep the existing reducer tests
unchanged and exercise the hook’s async behavior through its public API and
mocked rewrite dependencies.
apps/studio/hooks/analytics/useLogsAttributeKeys.test.tsx (1)

20-24: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Parse the intercepted request body instead of casting it.

request.json() is external data; validate the expected { sql: string } shape with Zod before reading sql.

Proposed fix
+import z from 'zod'
+
+const keyDiscoveryRequestSchema = z.object({ sql: z.string() })
+
 response: async ({ request }) => {
-  const body = (await request.clone().json()) as { sql: string }
+  const body = keyDiscoveryRequestSchema.parse(await request.clone().json())
   requests.push(body.sql)
🤖 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/hooks/analytics/useLogsAttributeKeys.test.tsx` around lines 20 -
24, Update the intercepted request handler in the test to validate the parsed
request body with the existing Zod pattern or schema before accessing sql.
Replace the type assertion on request.clone().json() with schema parsing that
enforces an object containing a string sql field, then push the validated sql
value to requests while preserving the existing fails response behavior.

Source: Coding guidelines

apps/studio/hooks/analytics/useLogsAttributeKeys.ts (1)

33-37: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider logging swallowed fetch failures.

The catch silently returns undefined for any failure (network error, auth error, etc.), which is fine functionally per the documented "keys are an enhancement" design, but makes real failures invisible during debugging.

       try {
         return await queryClient.fetchQuery(otelLogKeysQueryOptions({ projectRef, source }))
-      } catch {
+      } catch (error) {
+        console.error('[useLogsAttributeKeys] Failed to fetch attribute keys', error)
         return undefined
       }
🤖 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/hooks/analytics/useLogsAttributeKeys.ts` around lines 33 - 37,
Update the catch block in the query function using otelLogKeysQueryOptions to
log the fetch failure before returning undefined. Capture the caught error and
include relevant error details with the existing projectRef/source context,
while preserving the enhancement behavior of returning undefined.
🤖 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/Settings/Logs/LegacyLogsRewriteAdmonition.tsx`:
- Around line 86-90: The disabled Dismiss button in LegacyLogsRewriteAdmonition
should use the established ButtonTooltip pattern to explain that dismissal is
unavailable while rewriting is in progress. Wrap or integrate the existing
Button while preserving its variant, size, disabled condition, and onDismiss
behavior, and provide the appropriate in-flight rewrite explanation through the
tooltip.

In `@apps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsx`:
- Around line 186-201: The SQLEditorEditorPanel early return unmounts the
editor-related views during snippet loading. Remove the top-level isLoading
return so LegacyLogsRewriteBanner and the existing diff/main editor branch
remain mounted immediately; handle the loading spinner within SQLEditorMainView
or its existing editor loading mechanism instead.

In `@apps/studio/data/logs/logs-sql-rewrite.ts`:
- Around line 13-26: Update the bySource matching in detectLogSource to require
source as a whole-word identifier, preventing matches inside longer column names
such as resource or datasource. Preserve the existing alias normalization and
fallback to the bounded byFrom detection when no standalone source column
matches.

In `@apps/studio/hooks/analytics/useLegacyLogsRewrite.ts`:
- Around line 151-154: Update the dismiss function in useLegacyLogsRewrite so it
only invokes onDismissed when the current reducer state accepts the dismissed
transition; preserve the dispatch behavior while preventing callbacks during
rewriting or any other invalid state. Use the hook’s existing state/status
symbol to enforce the contract rather than relying on UI controls.

---

Nitpick comments:
In `@apps/studio/components/interfaces/SQLEditor/LegacyLogsRewriteBanner.tsx`:
- Around line 57-76: Track the rewrite action in the LegacyLogsRewriteBanner
flow by adding a useTrack event such as legacy_logs_rewrite_requested when the
user invokes requestRewrite through LegacyLogsRewriteAdmonition. Keep the
existing rewrite behavior and dismissal handling unchanged.

In `@apps/studio/hooks/analytics/useLegacyLogsRewrite.test.ts`:
- Around line 1-88: Add hook-level tests around useLegacyLogsRewrite’s
requestRewrite and dismiss orchestration, covering stale-edit race protection,
no-op detection, and the dismiss-during-rewrite side effect. Keep the existing
reducer tests unchanged and exercise the hook’s async behavior through its
public API and mocked rewrite dependencies.

In `@apps/studio/hooks/analytics/useLogsAttributeKeys.test.tsx`:
- Around line 20-24: Update the intercepted request handler in the test to
validate the parsed request body with the existing Zod pattern or schema before
accessing sql. Replace the type assertion on request.clone().json() with schema
parsing that enforces an object containing a string sql field, then push the
validated sql value to requests while preserving the existing fails response
behavior.

In `@apps/studio/hooks/analytics/useLogsAttributeKeys.ts`:
- Around line 33-37: Update the catch block in the query function using
otelLogKeysQueryOptions to log the fetch failure before returning undefined.
Capture the caught error and include relevant error details with the existing
projectRef/source context, while preserving the enhancement behavior of
returning undefined.

In `@apps/studio/pages/project/`[ref]/logs/explorer/index.tsx:
- Around line 181-184: Debounce editorValue before passing it to
shouldOfferLegacyLogsRewrite, using the same 500ms behavior as
LegacyLogsRewriteBanner, so the heuristic does not run on every keystroke.
Rename showRewriteCTA to shouldShowRewriteCTA and update all references while
preserving the existing CTA behavior.
🪄 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: c08cf338-3bb3-4bdf-bc30-28fb8e869982

📥 Commits

Reviewing files that changed from the base of the PR and between 3ae7d7a and 879bfa4.

📒 Files selected for processing (24)
  • apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsx
  • apps/studio/components/interfaces/SQLEditor/LegacyLogsRewriteBanner.tsx
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.utils.ts
  • apps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsx
  • apps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsx
  • apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.test.tsx
  • apps/studio/components/interfaces/SQLEditor/useSqlEditorAi.ts
  • apps/studio/components/interfaces/Settings/Logs/LegacyLogsRewriteAdmonition.tsx
  • apps/studio/components/interfaces/Settings/Logs/LogsExplorerOtelBanner.tsx
  • apps/studio/data/logs/keys.ts
  • apps/studio/data/logs/logs-sql-rewrite.test.ts
  • apps/studio/data/logs/logs-sql-rewrite.ts
  • apps/studio/data/logs/otel-log-keys-query.ts
  • apps/studio/hooks/analytics/useLegacyLogsRewrite.test.ts
  • apps/studio/hooks/analytics/useLegacyLogsRewrite.ts
  • apps/studio/hooks/analytics/useLogsAttributeKeys.test.tsx
  • apps/studio/hooks/analytics/useLogsAttributeKeys.ts
  • apps/studio/lib/ai/clickhouse-logs.ts
  • apps/studio/lib/ai/prompts.ts
  • apps/studio/lib/get-error-message.test.ts
  • apps/studio/lib/get-error-message.ts
  • apps/studio/pages/api/ai/code/complete.ts
  • apps/studio/pages/project/[ref]/logs/explorer/index.tsx
💤 Files with no reviewable changes (2)
  • apps/studio/components/interfaces/Settings/Logs/LogsExplorerOtelBanner.tsx
  • apps/studio/lib/ai/prompts.ts

@charislam
charislam force-pushed the charislam/sql-editor-inline-ai-clickhouse-dialect branch from dc27387 to cbdd4e6 Compare July 30, 2026 18:08

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Preview test — ✅ all pass

Ran through the ClickHouse-dialect-and-rewrite flows on the studio-staging preview. This PR's behavior is gated behind the sqlEditorLogsSource flag, and the rewrite banner further behind otelLegacyLogs — enabled both via the devToolbar() debug panel for this test.

# Test Result
1 Inline AI edit on a log_sql snippet uses ClickHouse dialect ✅ Request body carried dialect: "clickhouse"; response used valid ClickHouse syntax (log_attributes['request.method'] map lookups), no leftover code fences
2 Regression: inline AI edit on a normal Postgres snippet still works ✅ Request carried dialect: "postgres", response formatted normally, diff applied cleanly
3 Rewrite banner offers ClickHouse rewrite for a legacy BigQuery-style logs query (org has otelLegacyLogs on) ✅ Banner appeared ("Logs now run on a ClickHouse-backed engine..."), "Rewrite with Assistant" opened the AI diff view (not an instant replace), accepted cleanly
4 Regression: banner doesn't show when otelLegacyLogs is off ✅ Same legacy query, flag off → no banner, even after reload
5 Dismissing the banner is terminal ✅ Dismissed, reloaded twice — banner stayed gone for that snippet
6 Same rewrite flow works from the Logs Explorer (shared hook) ✅ Same banner text/buttons, same dialect+intent in the request; diff view opens there too (slightly different chrome — "Review the ClickHouse SQL rewrite before accepting it")
7 Attribute keys fetched on submit, not per keystroke ✅ Typing into the AI prompt fired zero logs.all.otel calls; exactly one fired on submit

Notes:

  • Skipped the unit tests mentioned in the description (dialect selection, prompt content, reducer transitions, getErrorMessage) — those are local-only (vitest), out of scope for a preview test.
  • Didn't manage to force a "rewrite failed" or "no rewrite needed" (identical output) state — those depend on actual AI output, not something I could deterministically trigger here.
  • This feature sits behind two flags that are off by default (sqlEditorLogsSource, and otelLegacyLogs for the rewrite banner) — enabled both via the devToolbar() debug panel (Flags tab) for this test. otelLegacyLogs was already true for the test org by default.
  • No console errors tied to any of the above (saw two pre-existing/unrelated CORS errors from pg-meta on one reload, unrelated to this feature).
  • Side effect: left a few test snippets (a couple log_sql ones, one regular) and one saved Logs Explorer query in the reused test project — didn't clean those up since they're low-stakes, happy to delete if you'd rather.


/** System-prompt half: the dialect rules that hold for every ClickHouse request. */
export const CLICKHOUSE_LOGS_COMPLETION_INSTRUCTIONS = `
# Supabase logs SQL (ClickHouse)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tiny feedback but thinking we can include a rule to not use select * since the BE will return an error

@joshenlim

Copy link
Copy Markdown
Member

Generally LGTM! Verified changes locally (Lol Vercel was overriding the cmd shift k shortcut so i couldnt test there 🙄 )

@joshenlim joshenlim left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified changes locally!

@charislam
charislam force-pushed the charislam/sql-editor-inline-ai-clickhouse-dialect branch from cbdd4e6 to 8399fb6 Compare July 31, 2026 13:43
PR 8 of the SQL editor query-source series. A log_sql snippet runs against
the ClickHouse-backed analytics endpoint, so the editor's AI has to speak
that dialect rather than Postgres, and legacy Logs Explorer saved queries
(BigQuery dialect) need an in-editor path to something runnable.

Inline AI:
- sqlSourceToDialect maps a snippet's source to postgres/clickhouse, and
  buildCompletionRequestBody threads an optional dialect through to the
  completion route (which already accepted it).
- useSqlEditorAi takes sqlSource and, for ClickHouse, swaps the raw
  instruction for buildLogsCompletionPrompt, strips code fences from the
  response, and skips formatSql — sql-formatter is Postgres-only and
  mangles ClickHouse backticks and map lookups.
- The clickhouse system prompt generalizes from rewriting to writing and
  editing. Since that sentence was the only thing making a rewrite
  mandatory, buildClickhouseRewritePrompt now states the requirement
  itself; without it the model echoes its input and the caller gets a diff
  with two identical sides.

Rewrite to ClickHouse:
- LegacyLogsRewriteBanner offers the rewrite for a logs snippet whose text
  trips looksLikeLegacyLogsQuery, and proposes the result through the
  editor's existing AI diff view instead of replacing content. Gated on
  otelLegacyLogs: on a non-migrated org the BigQuery text is still
  correct, so rewriting it would break a working query. That rule is now
  shared with the Logs Explorer as shouldOfferLegacyLogsRewrite.
- The offer is a state machine (offered/rewriting/failed/noRewriteNeeded/
  dismissed) with a declarative table of valid transitions, so the states
  are mutually exclusive by construction and dismissal is terminal.
  Failure keeps its message and offers a retry; an unchanged response is
  reported rather than opening an empty diff. The banner is mounted
  unconditionally and hides itself, so opening a diff cannot unmount it
  and discard a dismissal.
- The dialect heuristics run on a debounced value rather than per
  keystroke.

The presentational banner moves out of LogsExplorerOtelBanner into
LegacyLogsRewriteAdmonition so both surfaces share one copy of the text.

getErrorMessage gains an optional fallback, replacing the error casts at
the new call sites. Consolidating it also dropped its String(error)
catch-all, which surfaced a bare object as the literal '[object Object]'
and meant a fallback could never fire for one; it now yields the fallback
or null. Every existing caller already hand-rolled a fallback, except
QueueSettings, which interpolated the raw result and now passes one.
…r-side

Addresses code review on b626b3b.

Deduplicate the rewrite orchestration. The SQL editor banner and the Logs
Explorer each implemented the same sequence — read the live SQL, discover
the source's log_attributes keys, call the completion route, guard against
edits that landed mid-request, turn the result into a diff proposal — and
had already drifted: only the banner detected a no-op rewrite, they sourced
keys differently, and the Explorer formatted errors with an `as Error` cast
that would lie for a non-Error throw. Both now call useLegacyLogsRewrite,
which owns the request and the offer's state machine, so the Explorer picks
up no-op detection and typed error extraction. The presentational
LegacyLogsRewriteAdmonition covers every state of that machine, giving both
surfaces the same failure and no-rewrite-needed UI instead of toasts.

Assemble the completion prompt in one place. The route built a
schema/code/instruction message for Postgres but forwarded `prompt`
verbatim for ClickHouse, so the client hand-built an equivalent string.
That left two independent descriptions of the same logs table — one in the
system prompt, one injected client-side — and made
completionMetadata.textBeforeCursor/selection/textAfterCursor mean
different things per dialect. The route now uses one template for both,
branching only the schema section and (for intent: 'rewrite') the
instruction, and lib/ai/clickhouse-logs.ts is the single home for
ClickHouse-logs prompt content. buildLogsCompletionPrompt and
buildClickhouseRewritePrompt are gone; the "no code fences" contract is
stated once in the system prompt rather than three times.

The dialect split had also left inline edits ungrounded: availableKeys was
a parameter no inline call site passed, so an inline edit got weaker
grounding on real log_attributes keys than a full rewrite. Keys now travel
in completionMetadata and both paths supply them.

Move logs-sql-rewrite out of Settings/Logs. Two of its three consumers now
live outside that folder, so the import path was becoming misleading: the
dialect helpers and the fetch wrapper go to data/logs, the shared hook to
hooks/analytics, and the prompt text server-side to lib/ai.

One behavior note: the Explorer's persisted dismissal is not used to seed
the machine, because useLocalStorage reads as false during SSR and would
resurrect a dismissed banner on hydration. It gates the offer at render
instead, while an outcome the user just triggered still shows — a rewrite
started from the toolbar action has to report a failure somewhere.
useSqlEditorAi ran detectLogSource against the snippet's live store text,
which is written on every keystroke. The detected source is part of the
useOtelLogKeysQuery key, so typing a source name fired a separate analytics
request for each intermediate value (edge_l, edge_lo, edge_log, …) rather
than one for the finished name. The Logs Explorer had the same problem via
useLegacyLogsRewrite, which took the live editorValue — it only avoided it
before by fetching keys imperatively at click time.

The rewrite banner already debounced, so this was the same logic in three
places with one copy missing the guard. useLogsAttributeKeys now owns
detection and the lookup, and debounces the query text itself, so a caller
can't reintroduce the storm by forgetting to pre-debounce. The detected
source is memoized on the settled text to keep the query key referentially
stable across the keystroke-driven re-renders.

The debounce is trailing-only, so an already-open snippet still discovers
its keys immediately instead of waiting 500ms for a value that isn't going
to change.

Verified by removing the debounce: the burst test goes from 2 requests to 7.
The debounce made the request storm smaller but not bounded: the detected
source still fed a reactive query key, so every settled edit that changed
the source cost another week-long aggregation over the logs table, for keys
that are only needed once the user actually submits.

useLogsAttributeKeys is now imperative — callers await fetchAttributeKeys(sql)
at submit time, so there is one lookup per action the user took and none
while typing. The debounce is gone with it.

Cache reuse survives the change: the request goes through
queryClient.fetchQuery with shared queryOptions, so a source already fetched
(by an earlier submit, or by a component subscribed via useOtelLogKeysQuery
— the Logs Explorer header and query panel both are) is served from cache
instead of refetched. The query key moved into logsKeys alongside the other
logs keys.

This also simplifies the callers: useLegacyLogsRewrite no longer needs `sql`
or `isOffered` props at all, since key discovery was the only thing that
wanted a reactive value. The rewrite banner keeps its own debounce for the
dialect check that drives visibility — that one is local regex work, not a
request.

Discovery failures still resolve to undefined rather than throwing: keys are
an enhancement, and a rewrite must not be blocked by a failed lookup.
Review follow-ups on the logs rewrite flow.

detectLogSource matched `source` unanchored, so it read the value out of any
column ending in it — `resource = 'nope'` and `datasource = 'x'` both
resolved as log sources, sending key discovery after a source that doesn't
exist. Anchored with \b, which still allows a qualified `t.source`.

useLegacyLogsRewrite's dismiss called onDismissed even when the reducer
rejected the transition. The control is disabled mid-rewrite so this wasn't
reachable from the UI, but the hook shouldn't depend on that: the Explorer
persists dismissals, so a rejected one would have suppressed an offer that
was still live. It now consults the transition table before reporting.

The Logs Explorer ran the dialect heuristic on every keystroke, unlike the
SQL editor's banner. Both now debounce on a shared interval, and
showRewriteCTA is renamed to shouldShowRewriteCTA per the boolean naming
convention.

The Dismiss button explains itself while disabled, via ButtonTooltip as the
repo requires for disabled controls.

Not changed: the reviewer also asked to drop SQLEditorEditorPanel's
top-level isLoading return so the rewrite banner stays mounted during
snippet load. isLoading is monotonic per snippet id — deriveSnippetIdentity
flips it once when content lands, and the banner is keyed by id — so no
state is lost by mounting after load, and the banner has nothing to show
before then since it reads that content to decide visibility. Restructuring
it would also drop the top-level early return the fetch-state convention
asks for, and would mount Monaco before its snippet exists.
select * causes the backend to error, so AI should not write this kind
of ClickHouse SQL.
@charislam
charislam force-pushed the charislam/sql-editor-inline-ai-clickhouse-dialect branch from a2d6fb2 to 61fa2be Compare August 4, 2026 12:36
@charislam
charislam merged commit 8b38e0d into master Aug 4, 2026
44 of 62 checks passed
@charislam
charislam deleted the charislam/sql-editor-inline-ai-clickhouse-dialect branch August 4, 2026 13:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants