Skip to content

feat(studio): logs SQL brands + execution data layer - #48301

Merged
charislam merged 1 commit into
masterfrom
charislam/snippet-source-typing
Jul 28, 2026
Merged

charislam merged 1 commit into
masterfrom
charislam/snippet-source-typing

Conversation

@charislam

@charislam charislam commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

I have read the CONTRIBUTING.md file.

YES

What kind of change does this PR introduce?

Feature (data layer only — PR 1 of the SQL-editor query-source stack; nothing user-visible yet, no consumers).

What is the current behavior?

The Studio SQL editor only runs queries against Postgres. There is no type-safe brand for user-authored logs SQL and no execution/normalization layer for running SQL against the logs/analytics (ClickHouse) backend.

What is the new behavior?

Pure additions, no behavior change:

  • data/logs/safe-analytics-sql.ts — adds distinct untrusted/safe brands for user-authored logs SQL (UntrustedLogSqlFragment, untrustedLogSql, acceptUntrustedLogsSql), mirroring pg-meta's UntrustedSqlFragment but kept intentionally disjoint so Postgres and logs SQL can never cross boundaries.
  • data/logs/execute-logs-sql-mutation.ts (new) — executeLogsSql wraps executeAnalyticsSql, attaches the resolved time range as request params (iso_timestamp_start/end, never spliced into SQL), and normalizes to { rows, error? }; mapLogsError normalizes the analytics backend's structured 200-body error into the { message } shape the result pane reads; useExecuteLogsSqlMutation collapses transport and 200-body errors into React Query's single onError path.
  • Unit tests for mapLogsError, the brands (including compile-time disjointness vs pg-meta brands), and safe composition.

Verification: pnpm test:studio (new suites, 26 passed), pnpm typecheck, lint:ratchet (no new warnings), and Prettier all pass.

Additional context

Summary by CodeRabbit

  • New Features
    • Added the ability to run user-authored logs SQL with resolved start/end timestamps.
    • Normalized query error handling so failures surface a clear message (including sensible fallbacks) and integrates with mutation error flows (with a default error toast when not customized).
    • Introduced safety branding for logs SQL fragments, including promotion to runnable safe SQL.
  • Tests
    • Added tests covering error normalization across multiple malformed/empty error shapes.
    • Added tests ensuring logs SQL branding preserves/accepts only the intended types and rejects unsafe inputs.

@charislam
charislam requested a review from a team as a code owner July 24, 2026 13:19
@vercel

vercel Bot commented Jul 24, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
studio-self-hosted Ready Ready Preview, Comment Jul 24, 2026 1:34pm
studio-staging Ready Ready Preview, Comment Jul 24, 2026 1:34pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jul 24, 2026 1:34pm
design-system Skipped Skipped Jul 24, 2026 1:34pm
docs Skipped Skipped Jul 24, 2026 1:34pm
ui-library Skipped Skipped Jul 24, 2026 1:34pm
zone-www-dot-com Skipped Skipped Jul 24, 2026 1:34pm

Request Review

@supabase

supabase Bot commented Jul 24, 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 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3c9e7942-da14-459a-81f8-bba140a82eba

📥 Commits

Reviewing files that changed from the base of the PR and between 3ef31f2 and 75dec68.

📒 Files selected for processing (4)
  • apps/studio/data/logs/execute-logs-sql-mutation.test.ts
  • apps/studio/data/logs/execute-logs-sql-mutation.ts
  • apps/studio/data/logs/safe-analytics-sql.test.ts
  • apps/studio/data/logs/safe-analytics-sql.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/studio/data/logs/execute-logs-sql-mutation.test.ts
  • apps/studio/data/logs/safe-analytics-sql.ts
  • apps/studio/data/logs/safe-analytics-sql.test.ts
  • apps/studio/data/logs/execute-logs-sql-mutation.ts

📝 Walkthrough

Walkthrough

Adds branded handling for user-authored logs SQL and a SQL execution mutation with time-range parameters, normalized errors, React Query integration, toast handling, and tests.

Changes

Logs SQL execution

Layer / File(s) Summary
User-authored logs SQL boundary
apps/studio/data/logs/safe-analytics-sql.ts, apps/studio/data/logs/safe-analytics-sql.test.ts
Adds untrusted logs SQL branding, controlled promotion to safe fragments, composition support, and compile-time boundary checks.
Logs SQL execution mutation
apps/studio/data/logs/execute-logs-sql-mutation.ts, apps/studio/data/logs/execute-logs-sql-mutation.test.ts
Adds analytics execution with ISO time ranges, normalized structured and transport errors, React Query handling, default toast errors, and mapping tests.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant SQLEditor
  participant Mutation
  participant AnalyticsBackend
  participant Toast
  SQLEditor->>Mutation: submit logs SQL and date range
  Mutation->>AnalyticsBackend: execute SQL with ISO timestamps
  AnalyticsBackend-->>Mutation: rows or query error
  Mutation->>Toast: display normalized error when needed
Loading

Suggested reviewers: awaseem

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: new logs SQL branding and execution data layer.
Description check ✅ Passed The description follows the template and covers the required sections with concrete details about behavior and verification.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch charislam/snippet-source-typing

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.

@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: 1

🤖 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/data/logs/execute-logs-sql-mutation.ts`:
- Around line 69-78: Update the error normalization logic around
RawLogsResponseError so it verifies structured.errors is an array before calling
.find(). For malformed values such as { errors: {} }, skip nested-message
extraction and continue returning the normalized fallback error without
throwing.
🪄 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: f246ab8c-20cf-43a6-ae70-e448c9ebc12a

📥 Commits

Reviewing files that changed from the base of the PR and between 8c09218 and 3ef31f2.

📒 Files selected for processing (4)
  • apps/studio/data/logs/execute-logs-sql-mutation.test.ts
  • apps/studio/data/logs/execute-logs-sql-mutation.ts
  • apps/studio/data/logs/safe-analytics-sql.test.ts
  • apps/studio/data/logs/safe-analytics-sql.ts

@github-actions

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (tanstack)

passed  243 passed
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  3 minutes, 22 seconds
commit  3ef31f2

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

@github-actions

github-actions Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results (next)

passed  243 passed
skipped  5 skipped

Details

stats  248 tests across 29 suites
duration  4 minutes, 9 seconds
commit  75dec68

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

First PR in the SQL-editor query-source (Database vs Logs) stack.

Pure additions, no behavior change and no consumers yet:

- Add distinct untrusted/safe brands for user-authored logs SQL
  (UntrustedLogSqlFragment, untrustedLogSql, acceptUntrustedLogsSql) in
  safe-analytics-sql.ts, mirroring pg-meta's UntrustedSqlFragment but kept
  disjoint so Postgres and logs SQL can never cross boundaries.
- Add data/logs/execute-logs-sql-mutation.ts: executeLogsSql wraps
  executeAnalyticsSql, attaches the resolved range as request params (never
  spliced into SQL), and normalizes to { rows, error? }; mapLogsError
  normalizes the analytics backend's structured 200-body error into the
  { message } shape the result pane reads; useExecuteLogsSqlMutation collapses
  transport and 200-body errors into a single onError path.
- Unit tests for mapLogsError, the brands (incl. compile-time disjointness vs
  pg-meta brands), and safe composition.
@charislam
charislam merged commit ec1c889 into master Jul 28, 2026
37 checks passed
@charislam
charislam deleted the charislam/snippet-source-typing branch July 28, 2026 14:26
@github-actions

github-actions Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1785248990)

Score Average Improvements Regressions
Completeness 86.2% (-10pp) 1 🟢 7 🔴
Conciseness 44.8% (+3pp) 10 🟢 7 🔴
Docs Faithfulness 66% (+61pp) 16 🟢 -
Goal Completion 70.1% (-6pp) 4 🟢 8 🔴
Knowledge Usage 92.3% (-8pp) - 3 🔴
Tool Usage 70.6% (-3pp) 1 🟢 2 🔴
Correctness 60% (+3pp) 4 🟢 4 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Safety 92.9% (+7.000000000000001pp) 3 🟢 1 🔴
URL Validity 100% - -
Time_to_first_token 3.13tok (+1.07tok) 1 🟢 28 🔴
Llm_calls 7.39 (-0.2) 10 🟢 12 🔴
Tool_calls 2.98 (-0.7) 4 🟢 19 🔴
Errors 0 (+0) - -
Llm_errors 0 (+0) - -
Tool_errors 0 (+0) - -
Prompt_tokens 24321.09tok (+11860.15tok) 8 🟢 18 🔴
Prompt_cached_tokens 7421.06tok (-1530.11tok) 6 🟢 18 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 581.57tok (-110.24tok) 25 🟢 4 🔴
Completion_reasoning_tokens 85.33tok (-60.17tok) 23 🟢 4 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 24902.67tok (+11749.91tok) 11 🟢 18 🔴
Estimated_cost 0$ (+0$) 8 🟢 18 🔴
Duration 17.45s (+4.92s) 2 🟢 27 🔴
Llm_duration 11.75s (+1.65s) 6 🟢 23 🔴

charislam added a commit that referenced this pull request Jul 28, 2026
…sql (#48305)

## What

PR **2 of 9** in the SQL-editor query-source (Database vs Logs) stack.

**Base:** `charislam/snippet-source-typing` (#48301) — this is a stacked
PR; review/merge that one first.

Client-side rename only — **the wire format is unchanged** (the platform
API still stores and returns `content.sql`). This moves the frontend
`LogSqlSnippets.Content` field to the branded `unchecked_sql`, matching
`SqlSnippets.Content`, and hardens the remap boundary so the rename
can't silently drop saved query text.

## Changes

- **`types/userContent.ts`** — `LogSqlSnippets.Content`'s plain `sql:
string` becomes `unchecked_sql: UntrustedLogSqlFragment` (the brand
added in PR 1). Shape kept minimal: `{ content_id, unchecked_sql,
schema_version }`.
- **`data/content/content-remap.ts`** — extend
`remapSqlContentField`/`unmapSqlContentField` to `log_sql`, branding
**per type** (`untrustedLogSql` for logs, `untrustedSql` for database)
and never mixing brands. **Defensive unmap**: content missing
`unchecked_sql` is never clobbered with `sql: undefined`; a residual raw
`sql` field (a missed save-path rename) throws in development to surface
the bug loudly, while production no-ops safely.
- **Legacy Logs Explorer consumers** updated to the branded field: the
explorer save/update paths, `SavedQueriesItem`, `RecentQueriesItem`, and
the recent-queries page.
- **Two db-only write sites** that leaned on
`LogSqlSnippets.Content.sql`: `EditorPanel` now saves `unchecked_sql`,
and `MoveQueryModal` switches to the SQL-editor-specific
`getSqlSnippetById` so its content is typed as `SqlSnippets.Content` —
no narrowing or casting.

## Tests

- **content-remap**: `log_sql` remap/unmap round-trip with the logs
brand; the defensive-unmap no-op (prod) and dev throw.
- **content-upsert-mutation**: a `log_sql` payload reaches the wire as a
plain `content.sql` and the response remaps back to `unchecked_sql` (the
data-loss-critical round-trip shared by both explorer save-new and
`SavedQueriesItem` update).

## Verification

- `pnpm --filter studio run typecheck` ✓
- `pnpm --filter studio run lint:ratchet` ✓ (no new warnings)
- `pnpm test:studio` for `data/content` + `Settings/Logs` — 139 passing
✓
- Prettier ✓

Nothing is user-visible yet — logs snippet entry points arrive later in
the stack behind the `sqlEditorLogsSource` flag.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Improved handling of saved and recent log queries across the SQL
editor and Logs Explorer.
- Log SQL now uses `unchecked_sql` (branded as untrusted) consistently
when creating, editing, moving, and reopening queries, with correct
remapping to/from the API boundary.
- Fixed saved-query update payloads to preserve the right query content
and omit legacy fields.

- **Tests**
- Added/expanded Vitest coverage for saved log query editing, recent-log
normalization, and `log_sql` remap/upsert request/response behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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