Skip to content

refactor(studio): extract SQL editor session store from god store - #47349

Merged
charislam merged 6 commits into
masterfrom
refactor/sql-editor-state-pr6-session
Jun 30, 2026
Merged

charislam merged 6 commits into
masterfrom
refactor/sql-editor-state-pr6-session

Conversation

@charislam

@charislam charislam commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

What

PR 6 of the SQL editor state re-layering stack. Moves ephemeral, never-persisted SQL editor state out of the snippet/folder "god store".

Session store — state/sql-editor/sql-editor-session-state.ts holds per-snippet, read-by-many session state:

  • query results
  • explainResults
  • the row limit

…with their mutators (addResult/addResultError/resetResult, addExplainResult/addExplainResultError/resetExplainResult, resetResults, setLimit). removeSnippet drops a snippet's session entries via clearForSnippet(id).

Diff-request slice — state/sql-editor/sql-editor-diff-request.ts. The Assistant's "Insert code" / "Replace code" diff is not per-snippet session state: it's a transient, fire-and-forget command produced outside the editor (e.g. query blocks / assistant) and consumed exactly once by whichever editor is active. It's modeled as a consume-once request (requestDiff / consumeDiffRequest) rather than durable state — the editor drains it on apply, so a stale diff can't leak into a later editor or session. (Previously this was diffContent in the god store: never cleared and triggered by object-reference identity.)

Consumers read session state from useSqlEditorSessionSnapshot and the diff channel from useSqlEditorDiffRequestSnapshot, keeping useSqlEditorV2StateSnapshot only for snippets/folders.

Why not the TanStack Query cache for results/explain?

Editor execution is a mutation, not a keyed query — mutation.data is per-hook-instance and not keyed by snippet id, and there's no caching value to capture (re-running SQL must return fresh data, never a cached result). EXPLAIN ANALYZE actually executes the statement, so a declarative/auto-refetching useQuery is semantically wrong. Results/explain are imperative mutation outputs, scoped to the session, read by several decoupled consumers keyed by snippet id — exactly what a small in-memory keyed store models honestly.

Consumers migrated

  • SQLEditor.tsx — results/explain/limit reads + addResult/addResultError/addExplainResult/addExplainResultError/setLimit; diff-apply effect now drains a consume-once request
  • UtilityPanel.tsx, UtilityTabResults.tsx, UtilityTabExplain.tsx, UtilityActions.tsx
  • QueryBlock/EditQueryButton.tsx — produces via requestDiff

Notes

  • Result/explain types are kept verbatim from the god store (pre-existing any row/error types come along unchanged; tightening them is out of scope for this move).
  • ref() on result rows is preserved to avoid Valtio proxying large row sets.

Tests

  • sql-editor-session-state.test.ts — result/explain mutators, resetResults, clearForSnippet, limit
  • sql-editor-diff-request.test.ts — requestDiff, consumeDiffRequest (drain + queue-of-one)

Validation:

  • pnpm --filter studio typecheck ✅
  • pnpm exec vitest --run state/sql-editor/ ✅ (110 passed)
  • lint ✅ (no new errors)

Summary by CodeRabbit

  • New Features

    • SQL editor query results, EXPLAIN output, and the “Limit results to” setting now persist more reliably across a session.
    • AI-assisted SQL insert/replace actions now use a pending diff workflow to apply updates more consistently.
  • Bug Fixes

    • Results/EXPLAIN rendering and downloads stay in sync with the latest executed data.
    • Switching databases/snippets now clears the correct temporary results.
    • Diff application is more resilient when an editor is still loading, including empty-vs-non-empty editor cases.
  • Tests

    • Added coverage for the session and diff-request state logic.

Move ephemeral, never-persisted SQL editor state (query results, EXPLAIN
results, the Assistant diff content, and the row limit) out of the snippet/
folder store into a dedicated session store at
state/sql-editor/sql-editor-session-state.ts.

The snippet store now deals only with persistence; the session store holds
state that lives only for the current editing session. removeSnippet drops a
snippet's session entries via clearForSnippet. Consumers read session state
directly from useSqlEditorSessionSnapshot rather than the god-store snapshot.

Behavior-preserving; the moved result/explain types are kept verbatim.

Adds sql-editor-session-state.test.ts covering result/explain mutators,
resetResults, clearForSnippet, limit, and diffContent.
@charislam
charislam requested a review from a team as a code owner June 26, 2026 16:33
@supabase

supabase Bot commented Jun 26, 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 ↗︎.

@vercel

vercel Bot commented Jun 26, 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 Jun 30, 2026 2:39pm
studio-staging Ready Ready Preview, Comment Jun 30, 2026 2:39pm
5 Skipped Deployments
Project Deployment Actions Updated (UTC)
studio Ignored Ignored Jun 30, 2026 2:39pm
design-system Skipped Skipped Jun 30, 2026 2:39pm
docs Skipped Skipped Jun 30, 2026 2:39pm
ui-library Skipped Skipped Jun 30, 2026 2:39pm
zone-www-dot-com Skipped Skipped Jun 30, 2026 2:39pm

Request Review

@coderabbitai

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

SQL editor query, EXPLAIN, limit, and diff request state now live in session-scoped stores. The editor and utility panel components read and write that session state, while the persistent editor store keeps snippet metadata and clears session data on removal.

Changes

SQL editor session-state split

Layer / File(s) Summary
Session store and tests
apps/studio/state/sql-editor/sql-editor-session-state.ts, apps/studio/state/sql-editor/sql-editor-session-state.test.ts
Adds the session-scoped SQL editor store, its mutation helpers, snapshot hook, and tests for result, EXPLAIN, limit, and clearing behavior.
Diff request state and tests
apps/studio/state/sql-editor/sql-editor-diff-request.ts, apps/studio/state/sql-editor/sql-editor-diff-request.test.ts, apps/studio/components/ui/QueryBlock/EditQueryButton.tsx, apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
Adds the one-shot SQL diff request store, its snapshot hook, tests, and the editor/button flow that enqueues, drains, and applies pending diff requests.
Persistent store cleanup
apps/studio/state/sql-editor/sql-editor-state.ts
Removes result, EXPLAIN, limit, and diff fields from the persistent SQL editor store and routes snippet removal through session-state clearing.
Runtime results and limits
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx, apps/studio/components/interfaces/SQLEditor/UtilityPanel/*
SQLEditor and the utility panel components read and write query results, EXPLAIN results, debug prompt errors, resets, and limit values through the session snapshot.
Diff editor gutter menu
apps/studio/components/ui/DiffEditor.tsx
DiffEditor disables Monaco gutter menu rendering in its default options.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • awaseem
  • pgnickb
  • joshenlim

Poem

A rabbit hopped through SQL tonight,
With session carrots tucked in sight.
EXPLAIN and results found a new home,
While diff requests bounced once, then roam.
🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the change but does not follow the required template and omits the CONTRIBUTING.md YES/NO section and explicit current/new behavior headings. Add the required template sections: CONTRIBUTING.md YES/NO, change type, current behavior with issues, new behavior, and additional context.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: extracting SQL editor session state into a separate store.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/sql-editor-state-pr6-session

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.

@github-actions

github-actions Bot commented Jun 26, 2026 •

Copy link
Copy Markdown
Contributor

🎭 Playwright Test Results

passed  223 passed
flaky  2 flaky
skipped  5 skipped

Details

stats  230 tests across 25 suites
duration  5 minutes, 5 seconds
commit  51d987a

Flaky tests

Features › queue-table-operations.spec.ts › Queue Table Operations › reverted cell edit clears the pending change
Features › sql-editor.spec.ts › SQL Editor › should check if SQL editor is working as expected

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx (1)

831-853: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Consume diffContent exactly once.

This effect reads a session-global diffContent value but never clears it after applying/opening the diff. Since the effect also runs on mount, reopening the editor or navigating to another snippet can replay the previous “Insert/Replace code” action into the next editor instance. Clear the queued diff after handling it, or scope it to the target snippet so stale payloads are ignored.

🤖 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.tsx` around lines 831 -
853, The SQLEditor effect that handles sessionSnap.diffContent is consuming a
queued diff without clearing or scoping it, so stale “Insert/Replace code”
actions can replay in later editor instances. Update the useEffect in
SQLEditor.tsx to consume diffContent exactly once by clearing it after handling,
or by validating it against the current target snippet before applying it; use
the existing editorRef, sessionSnap.diffContent, setSourceSqlDiff, and
setSelectedDiffType flow to locate the fix.
🤖 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/state/sql-editor/sql-editor-session-state.ts`:
- Around line 41-45: The session-scoped SQL diff state is not being
cleared/guarded when a snippet is removed, so stale assistant diffs can leak
into the next editor. Update clearForSnippet in sql-editor-session-state.ts to
also clear diffContent when the removed snippet is the one that produced it, and
update SQLEditor.tsx to only apply sessionSnap.diffContent when it matches the
active snippet id. Use the existing setDiffContent and diffContent handling
paths to locate the fix.

---

Outside diff comments:
In `@apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx`:
- Around line 831-853: The SQLEditor effect that handles sessionSnap.diffContent
is consuming a queued diff without clearing or scoping it, so stale
“Insert/Replace code” actions can replay in later editor instances. Update the
useEffect in SQLEditor.tsx to consume diffContent exactly once by clearing it
after handling, or by validating it against the current target snippet before
applying it; use the existing editorRef, sessionSnap.diffContent,
setSourceSqlDiff, and setSelectedDiffType flow to locate the fix.
🪄 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

Run ID: e420f321-de2c-45d5-a4ad-e41ea307be62

📥 Commits

Reviewing files that changed from the base of the PR and between 032a368 and 05a878a.

📒 Files selected for processing (9)
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
  • apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
  • apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityPanel.tsx
  • apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabExplain.tsx
  • apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityTabResults.tsx
  • apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
  • apps/studio/state/sql-editor/sql-editor-session-state.test.ts
  • apps/studio/state/sql-editor/sql-editor-session-state.ts
  • apps/studio/state/sql-editor/sql-editor-state.ts

The Assistant's Insert/Replace code diff is not per-snippet session state — it
is a transient, fire-and-forget command produced outside the editor and
consumed exactly once by the active editor. Modelling it as durable state in
the session store (never cleared, triggered by object-reference identity) was a
poor fit.

Extract it into a dedicated sql-editor-diff-request slice with requestDiff and
consumeDiffRequest. The editor drains the request on apply, so a stale diff can
never leak into a later editor or editing session. EditQueryButton produces via
requestDiff; SQLEditor consumes and clears.

Adds sql-editor-diff-request.test.ts; drops the diffContent coverage from the
session-store test.

@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/components/interfaces/SQLEditor/SQLEditor.tsx`:
- Around line 835-863: The pending diff handling in SQLEditor can get stuck
because the effect only watches diffRequest.pending and returns early when
editorRef.current?.getModel() is not ready. Add an explicit editor-ready state
(for example in the editor onMount handler where editorRef.current is set) and
include that readiness flag in the useEffect dependencies so the pending request
is re-processed once the editor mounts. Keep the one-shot consumeDiffRequest
behavior in the same effect after applying the diff so the request still drains
correctly.
🪄 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

Run ID: ba0f9556-6dba-43f0-bc97-5ebd8c8b96db

📥 Commits

Reviewing files that changed from the base of the PR and between 05a878a and 48fa981.

📒 Files selected for processing (6)
  • apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
  • apps/studio/components/ui/QueryBlock/EditQueryButton.tsx
  • apps/studio/state/sql-editor/sql-editor-diff-request.test.ts
  • apps/studio/state/sql-editor/sql-editor-diff-request.ts
  • apps/studio/state/sql-editor/sql-editor-session-state.test.ts
  • apps/studio/state/sql-editor/sql-editor-session-state.ts
💤 Files with no reviewable changes (1)
  • apps/studio/state/sql-editor/sql-editor-session-state.test.ts
✅ Files skipped from review due to trivial changes (1)
  • apps/studio/state/sql-editor/sql-editor-diff-request.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/studio/state/sql-editor/sql-editor-session-state.ts

The diff-apply effect early-returns when the Monaco editor model isn't ready,
but it only depended on diffRequest.pending, so a request issued before the
editor mounted was dropped despite the comment claiming otherwise.

Track an editorMountCount that bumps on every onMount (including the keyed
remount on snippet switch) and add it to the effect deps, so a pending request
is re-applied once the editor is ready. The one-shot consumeDiffRequest drain
stays in the same effect.
const [showWidget, setShowWidget] = useState(false)
// Bumped on every editor mount (including the keyed remount on snippet switch)
// so a diff request that arrived before the editor was ready gets re-processed.
const [editorMountCount, setEditorMountCount] = useState(0)

@joshenlim joshenlim Jun 29, 2026 •

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.

nit: hmm just wondering if this could be a simple boolean to see if the editor has been mounted? (to decide when to apply the diff)

Or why do we need to keep setting the count each time onMount is called?

@charislam charislam Jun 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Monaco editor remounts on snippet switch, so we need to also check on remount, not just once per SQL editor render

@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.

just a tiny nit comment but changes generally LGTM! verified changes on staging preview just to make sure the results + diff behaviour works as expected

}

// One-shot: drain the request so it can't re-apply to a later editor or session.
sqlEditorDiffRequestState.consumeDiffRequest()

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.

Shouldn't this be diffRequest.consumeDiffRequest()?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

good catch

executeExplainQuery now uses sessionSnap.addExplainResultError but its
dependency array still listed snapV2, adding a new react-hooks/exhaustive-deps
violation (the rule is ratcheted; baseline for this file is 2). Swap snapV2 for
sessionSnap in the deps — the body no longer references snapV2.

Also drop the now-unused sqlEditorDiffRequestState import (the drain effect
calls consumeDiffRequest via the snapshot).
@charislam
charislam merged commit d153bab into master Jun 30, 2026
32 checks passed
@charislam
charislam deleted the refactor/sql-editor-state-pr6-session branch June 30, 2026 15:24
@github-actions

github-actions Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Braintrust eval report

Assistant (master-1782833194)

Score Average Improvements Regressions
Completeness 93.1% (-7.000000000000001pp) - 4 🔴
Conciseness 47.7% (+5pp) 11 🟢 6 🔴
Docs Faithfulness 71.7% (+6pp) 5 🟢 3 🔴
Goal Completion 77% (-4pp) 4 🟢 6 🔴
Knowledge Usage 87.2% (-13pp) - 4 🔴
Tool Usage 66.7% (-8pp) - 3 🔴
Correctness 63.3% (-6pp) 2 🟢 5 🔴
Safety 90.5% (+0pp) 1 🟢 1 🔴
SQL Identifier Quoting 100% (+0pp) - -
SQL Validity 100% (+0pp) - -
Time_to_first_token 2.42tok (-0.12tok) 16 🟢 13 🔴
Llm_calls 6.56 (-0.25) 9 🟢 9 🔴
Tool_calls 2.77 (-0.05) 7 🟢 11 🔴
Errors 0.02 (-0.02) 1 🟢 -
Llm_errors 0.01 (-0.01) 1 🟢 -
Tool_errors 0 (+0) - -
Prompt_tokens 23292.15tok (-183.67tok) 14 🟢 11 🔴
Prompt_cached_tokens 7727.08tok (-447.26tok) 11 🟢 13 🔴
Prompt_cache_creation_tokens 0tok (+0tok) - -
Prompt_cache_creation_5m_tokens 0tok (+0tok) - -
Prompt_cache_creation_1h_tokens 0tok (+0tok) - -
Completion_tokens 562.93tok (-20.14tok) 18 🟢 11 🔴
Completion_reasoning_tokens 85.87tok (-7.1tok) 16 🟢 11 🔴
Completion_accepted_prediction_tokens 0tok (+0tok) - -
Completion_rejected_prediction_tokens 0tok (+0tok) - -
Completion_audio_tokens 0tok (+0tok) - -
Total_tokens 23855.08tok (-203.8tok) 15 🟢 14 🔴
Estimated_cost 0$ (0$) 20 🟢 7 🔴
Duration 14.15s (+0.04s) 16 🟢 13 🔴
Llm_duration 7.9s (-2.95s) 26 🟢 3 🔴

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.

3 participants