Repository navigation
feat(studio): ClickHouse dialect for logs snippet AI + rewrite to ClickHouse - #48501
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
|
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:
📝 WalkthroughWalkthroughThe 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. ChangesClickHouse logs assistance
Error message normalization
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
Possibly related PRs
🚥 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.
|
🎭 Playwright Test Results (tanstack)Details
Flaky testsFeatures › table-editor.spec.ts › table editor › copying cell values preserves false and zero Skipped testsFeatures › auth-users.spec.ts › should show web3 users as enabled when the matching web3 provider is enabled |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (5)
apps/studio/components/interfaces/SQLEditor/LegacyLogsRewriteBanner.tsx (1)
57-76: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider 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 winUndebounced heuristic may cause the rewrite CTA to flicker while typing.
showRewriteCTAre-runs the legacy-dialect heuristic on every keystroke viaeditorValue, unlikeLegacyLogsRewriteBanner.tsx's debounced (500ms) equivalent, which exists specifically to avoid "mid-word" flapping. Consider debouncingeditorValuehere too for consistency. Also, as per coding guidelines, boolean names should be prefixed withis/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 tradeoffReducer tests are solid; consider covering the hook's async orchestration too.
This suite thoroughly tests
legacyLogsRewriteReducer, but the asyncrequestRewrite/dismisslogic inuseLegacyLogsRewrite(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 winParse the intercepted request body instead of casting it.
request.json()is external data; validate the expected{ sql: string }shape with Zod before readingsql.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 valueConsider logging swallowed fetch failures.
The catch silently returns
undefinedfor 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
📒 Files selected for processing (24)
apps/studio/components/interfaces/Integrations/Queues/SingleQueue/QueueSettings.tsxapps/studio/components/interfaces/SQLEditor/LegacyLogsRewriteBanner.tsxapps/studio/components/interfaces/SQLEditor/SQLEditor.utils.test.tsapps/studio/components/interfaces/SQLEditor/SQLEditor.utils.tsapps/studio/components/interfaces/SQLEditor/SQLEditorControllers.tsxapps/studio/components/interfaces/SQLEditor/SQLEditorEditorPanel.tsxapps/studio/components/interfaces/SQLEditor/useSqlEditorAi.test.tsxapps/studio/components/interfaces/SQLEditor/useSqlEditorAi.tsapps/studio/components/interfaces/Settings/Logs/LegacyLogsRewriteAdmonition.tsxapps/studio/components/interfaces/Settings/Logs/LogsExplorerOtelBanner.tsxapps/studio/data/logs/keys.tsapps/studio/data/logs/logs-sql-rewrite.test.tsapps/studio/data/logs/logs-sql-rewrite.tsapps/studio/data/logs/otel-log-keys-query.tsapps/studio/hooks/analytics/useLegacyLogsRewrite.test.tsapps/studio/hooks/analytics/useLegacyLogsRewrite.tsapps/studio/hooks/analytics/useLogsAttributeKeys.test.tsxapps/studio/hooks/analytics/useLogsAttributeKeys.tsapps/studio/lib/ai/clickhouse-logs.tsapps/studio/lib/ai/prompts.tsapps/studio/lib/get-error-message.test.tsapps/studio/lib/get-error-message.tsapps/studio/pages/api/ai/code/complete.tsapps/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
dc27387 to
cbdd4e6
Compare
joshenlim
left a comment
There was a problem hiding this comment.
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, andotelLegacyLogsfor the rewrite banner) — enabled both via thedevToolbar()debug panel (Flags tab) for this test.otelLegacyLogswas 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-metaon one reload, unrelated to this feature). - Side effect: left a few test snippets (a couple
log_sqlones, 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) |
There was a problem hiding this comment.
Tiny feedback but thinking we can include a rule to not use select * since the BE will return an error
|
Generally LGTM! Verified changes locally (Lol Vercel was overriding the cmd shift k shortcut so i couldnt test there 🙄 ) |
cbdd4e6 to
8399fb6
Compare
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.
a2d6fb2 to
61fa2be
Compare
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_sqlsnippet 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 throughsql-formatter, which mangles ClickHouse backticks andlog_attributesmap lookups.Legacy Logs Explorer saved queries open in the editor as
log_sqlsnippets. 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
promptverbatim 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.
sqlSourceToDialectmaps a snippet's source topostgres/clickhouseandbuildCompletionRequestBodythreads it through. For ClickHouse,useSqlEditorAistrips code fences from the response and skipsformatSql. 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 onotelLegacyLogs: 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.tsis 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_attributeskeys differently, and the Explorer formatted errors with anas Errorcast. Both now useuseLegacyLogsRewriteand 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.
useLogsAttributeKeysis imperative and goes throughqueryClient.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.getErrorMessagegains an optional typed fallback and no longer stringifies a bare object into'[object Object]'; every existing caller already hand-rolled a fallback, exceptQueueSettings, which interpolated the raw result and now passes one.Nothing here is user-visible until the
sqlEditorLogsSourceflag 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, andgetErrorMessage.Additional context
Summary by CodeRabbit
New Features
Bug Fixes