mirror of
https://github.com/supabase/supabase.git
synced 2026-10-06 01:45:10 +03:00
codex/fix-tanstack-e2e
1346
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c0e109f662 |
refactor(studio): borrow the wire schema's time range in the query-source registry (#49070)
Second of a stack. **Stacked on #49069** — review that one first; this PR's diff only makes sense on top of it. Base will retarget to `master` automatically when #49069 merges. Net `-72` lines. No behavior change beyond the one noted at the bottom. ## The problem The query-source registry carried its own `LogTimeRange` type and `logTimeRangeSchema`, which had drifted from the notebook wire schema's copy in four ways: | | wire schema | registry | |---|---|---| | discriminant | `_tag: 'relative_time_range'` | `type: 'relative'` | | absolute bounds | `start` / `end` | `from` / `to` | | relative units | minute…year | minute, hour, day | | validation | none | positive int, end-after-start | Two definitions of one concept, neither convertible to the other without a lossy mapping — and the notebook query cell was papering over it by discarding a log cell's persisted range and substituting a default. ## What changed #49069 moved the validations onto the wire schema's `timeRangeSchema` and exported it. This PR deletes the registry's copy and points every consumer at `TimeRange`. The registry keeps what is genuinely runtime: endpoints, labels, availability, defaults. The field renames ripple mechanically through the logs date-picker helpers, the time-range submenu, `useLogsCustomRange`, the SQL editor's session state, and their tests. Coverage for the absolute-range and unit rules moved to `notebook-schema.test.ts` in #49069, alongside the schema that now owns them. `ExplorerQuerySourceMenu` also drops its hand-rolled custom-range construction in favor of `customDateRangeToLogTimeRange`, which already existed and does the same clamping. ## One behavior change `logTimeRangeToDatePickerValue` now renders a range whose unit has no picker preset (week, month, year — allowed by the wire schema, not offered in the UI) as a resolved absolute range, instead of trying and failing to build a helper for it. Previously unreachable, since the registry's narrower unit set made those ranges unrepresentable. ## Verification Typecheck, Prettier, and the lint ratchet clean. 401 tests pass across the notebook schema, query sources, the logs source components, the SQL editor, and the Explorer surfaces. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved log time-range handling across Explorer and SQL Editor. * Custom date ranges now display and resolve correctly, including clamping invalid ranges. * Unsupported relative time units are converted to compatible absolute date-picker values. * **Refactor** * Standardized log queries on a shared time-range format for more consistent validation and behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
e126b68390 |
feat(studio): make the notebook wire schema the source of truth for query sources (#49069)
First of a stack. Groundwork only — additive, no behavior change, nothing else in the tree touched. The notebook content schema is the contract shared with the API and the agent tool surface, so it is where source parameters and their validation belong. A follow-up PR has the runtime query-source registry borrow from here instead of keeping its own parallel definitions, which had already drifted (different discriminant, different field names, a narrower set of relative units). ## What changed - **`timeRangeSchema` is exported**, and picks up the two validations that existed only in the registry's copy and not here: a positive integer `amount`, and an absolute range whose end follows its start. - **`databaseSourceSchema` / `logsSourceSchema`** give each backend's parameters a single definition. They are spread flat into their cells with `...shape` rather than nested under a `source` key, so the JSON an agent has to author stays shallow. - **`database_identifier`** lets a database cell persist a read-replica selection, which it previously had no field for. Named that rather than `identifier` because every cell already carries an `id`. - **`queryCellBaseSchema`** holds what every runnable cell shares (`title`, `view`, `chart`), which was duplicated across `database_cell` and `log_cell`. `sql` deliberately stays on the members so the domain transform can brand it per dialect and generic code holding a query cell can't hand it to the wrong wire boundary. - **`CELL_KINDS` + `isQueryCell`** classify cells for query-generic UI. The `satisfies Record<Cell['_tag'], CellKind>` clause makes this the registration point for a new backend: adding a cell type fails to compile until it is classified, and `QueryCell` widens on its own once it is. ## Wire compatibility The only wire shape change is the new optional `database_identifier`, so `schema_version` stays at 1 and no persisted content needs migrating. Notebooks are still behind the `explorer` flag, so there is no saved `user_content` to worry about either way. `view` keeps master's current handling — optional on the wire, defaulted to `'table'` in the domain transform — and `chart` stays persisted independently of it, so switching to the table view and back returns the user's chart settings rather than rebuilding them. ## Tests `notebook-schema.test.ts` covers the new validations (unit set, non-positive/fractional amounts, absolute ordering, which field an invalid bound is reported against), `database_identifier`, `isQueryCell` narrowing, and that a chart survives alongside `view: 'table'`. Typecheck, Prettier, and the lint ratchet all clean; 120 tests pass across `data/content/notebooks` and `lib/ai/tools`. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added support for database identifiers in notebook query configurations. - Improved handling of database and log query cells for more consistent notebook behavior. - Preserved chart configuration when switching to a table view. - **Bug Fixes** - Time ranges now require valid dates, positive whole-number relative amounts, and correctly ordered absolute start and end times. - Validation errors now identify the specific time-range field with invalid date values. - **Tests** - Expanded coverage for query-cell detection, time-range validation, optional database identifiers, and chart settings. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
67d4fed40d |
Joshenlim/fe 4157 explorer migrate results component into explorer (#49066)
## Context Related to Notebooks/Explorers - this one's just shifting files from the SQLEditor into more generic folders from a file organization POV, such that files under the Explorer folder have no dependency on files within the SQLEditor folder Mainly - UtilityTabResults.utils: `getSqlErrorLines` - Moved into `data/sql/utils.ts` - SQLEditor.utils: `applyAutoLimit`, `getSqlErrorLines`, `trimTrailingSemicolons` - Moved into `data/sql/utils.ts` - SQLEditor/UtilityPanel: `ResultCell`, `Results`, `CellDetailPanel` - Moved into `components/ui/DataGridResults` - Also shifted corresponding tests over here - Also addressed some `any` type casts ## To test - Just need to ensure that the SQL Editor still works as expected <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Standardized query results across the Studio with a shared data grid. * Improved result-table formatting, column sizing, clipboard handling, and large-value display. * Added safer automatic row limits for eligible SQL queries. * Centralized SQL error display and formatting utilities. * **Refactor** * Improved type safety for query rows and cell values. * **Tests** * Added comprehensive coverage for result-grid and SQL utility behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
2f89014f74 |
Add logs cells (#49064)
## Context Related to Explorer/Notebooks - adds the source selector for query cell within a notebook <img width="1108" height="648" alt="image" src="https://github.com/user-attachments/assets/d1434197-3738-41b0-a8ef-1919c91181d9" /> <img width="1103" height="633" alt="image" src="https://github.com/user-attachments/assets/97f8c6a3-629d-4a41-aab4-3fdc5e8b2c7e" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for displaying log cells in the query editor. * Added switching between database and log query sources. * Log and database cells can display results as tables or charts. * Log queries support optional row limits. * Improved reliability when changing query settings. * Notebook query views now default to table display when unspecified. * **Bug Fixes** * Log cells no longer appear blank or get omitted from notebook views. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
cc6fe2100a |
refactor(studio): centralize query sources (#49027)
## Summary - define application-owned database and logs source contracts, defaults, validation, labels, and execution endpoints - extract controlled database and logs parameter controls for reuse outside SQL snippets - adapt the SQL editor to the shared source model without changing snippet behavior - standardize source icons at 16px with a 2px stroke - keep relative logs ranges aligned with the existing date picker units ## To test 1. Open an existing query in the SQL Editor and run it against the database. 2. Switch the query source to Logs, change the time range, and confirm the query still runs as expected. ## Why Explorer queries and notebook query cells need to select an execution source without coupling that source to SQL snippets. This provides the shared registry and controlled UI foundation for those consumers. ## Impact Existing SQL snippets retain their current database/logs routing and session behavior. The registry documents the SQL editor legacy database-selector adapter while new consumers own their identifier inline. The shared Logs date picker remains unchanged; query ranges support its existing minute, hour, and day units. This PR does not add the Explorer query tab itself. ## Validation - pnpm --filter studio typecheck - focused Vitest coverage for the registry, canonical log-range utilities, SQL execution adapters, source filtering, retention locking, custom ranges, and preset selection - pnpm --filter studio run lint:ratchet Component and state tests cover this change per the Studio testing guidance; no E2E test is added. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a unified query-source menu for database queries and logs. * Added custom log time-range selection with calendar support and retention-aware upgrade prompts. * Added consistent source icons and improved database selection handling. * Added support for relative and absolute log time ranges. * **Bug Fixes** * Improved log-range validation, defaults, and current-time handling. * Updated query execution to use the correct source-specific endpoints. * **Tests** * Expanded coverage for query sources, log ranges, menus, and retention behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
b5477a89a3 |
chore: Update API types (#48981)
Update the API types by running `api:codegen`. Some of the changes are fixed in code, some of the type changes had to be reverted (JIT Access, SSO features). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Billing** * Updated subscription messaging to reflect AWS Marketplace billing. * Removed outdated partner-billing downgrade notices. * **Bug Fixes** * Improved request handling for API keys, custom domains, SQL snippets, branches, and storage operations. * Improved legacy signing-key compatibility. * Refined temporary database access availability messaging. * **Updates** * Removed Fly as an available cloud provider for region selection. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
d434c63bad |
joshen/fe 4150 explorer query cells result display settings (#49003)
## Context Related to Explorer / Notebooks - this adds chart functionality for the Query cells <img width="250" alt="image" src="https://github.com/user-attachments/assets/4ea37c14-87dc-4c43-ba7f-cb9436085c81" /> Query results can be rendered as either bar or line chart - using the chart packages from `ui-patterns` [NOTE]: For design team reviewers - am patching the chart packages to be agnostic to the `timestamp` property within the provided data set. Would love to use this component from a consistency POV instead of the old `BarChart` component we have. Have intentionally omitted log scale functionality from this PR - will have that separately 🙏 <img width="999" height="483" alt="image" src="https://github.com/user-attachments/assets/14356ee4-c658-4fd1-90e0-17c38dac4822" /> <img width="988" height="478" alt="image" src="https://github.com/user-attachments/assets/cd0ca088-9a03-4aa3-9884-17bc36d3cabf" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added chart views for notebook query results, including bar and line charts. - Added display settings for selecting X/Y columns, chart type, scale, cumulative values, and label visibility. - Added configurable X-axis support for charts. - Display preferences are saved with each notebook cell. - **Improvements** - New database cells default to table view. - Chart results better handle varied data types. - Empty results and incomplete chart settings now display clear placeholders. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
b9835e419c |
test(studio): mock notebook tools (#48952)
## Summary - Adds deterministic `list_notebooks`/`get_notebook` fixtures (two seeded notebooks, each with markdown/database/log cells) and stateful in-memory `create_notebook`/`update_notebook` mocks to `apps/studio/lib/ai/tools/mock-tools.ts`, so Braintrust evals can exercise notebook tool calls without a real project. - Both write-tool mocks force `needsApproval: false`, matching the existing `execute_sql`/`deploy_edge_function` mock pattern — the eval harness filters out tool-parts in `'approval-requested'` state and can never answer an approval gate. - All four notebook tools are wrapped from the real `getNotebookTools()` definitions (only `execute`/`needsApproval` overridden), so evals validate the model's arguments against the exact production schemas. - Dedupes `describeOperationError` (previously duplicated between this new mock and `notebook-tools.ts`) into a single exported `describeNotebookOperationError` in `notebook-operations.ts`. **Stacked on #48949** (`feature/notebooks-update-tool`) — this PR's base branch is that PR, not `master`, because it reuses `update_notebook` and the shared error helper that only exist there. Merge #48949 first, then retarget/merge this one. ## Test plan - [x] \`pnpm --filter studio typecheck\` passes - [x] \`pnpm --filter studio test\` — all notebook-related suites pass (\`mock-tools.test.ts\`, \`notebook-tools.test.ts\`, \`data/content/notebooks/*\`) - [x] \`eslint\` / \`prettier --check\` clean on all touched files |
||
|
|
75b90c5de1 |
Check the session's backend_start for cancelling or terminating sessions (#48929)
## Context Related to database connections - specifically for cancelling queries or terminating sessions PIDs can be re-used, so a more accurate check is to use both PID and `backend_start` to uniquely identify the session to cancel or terminate <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved query cancellation and session termination reliability by verifying the active database session before taking action. * Prevented actions from affecting a different session that reused the same process ID. * Added clearer guidance to refresh when a session has changed or is no longer available. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
cdfb5b310f |
Add cancel query action for database connections (#48922)
## Context Related to Database Connections - Adds a "cancel query" action for "active" sessions using `pg_cancel_backend` - Gentler alternative as the connection stays alive, unlike terminating the session - Not applicable for queries idle in transaction as there's no query running (Disabled in this case) - Rename "Terminate" to "Terminate session" - Rename "Abort query" to "Terminate session" For active queries: <img width="220" height="135" alt="image" src="https://github.com/user-attachments/assets/d6ca790d-bb6a-4582-8554-24431388483a" /> For idle in txn queries: <img width="433" height="135" alt="image" src="https://github.com/user-attachments/assets/615d0651-9f5b-4efc-a5cf-72f93727aa91" /> Also updating confirmation modal for terminating session CTA: For active queries: <img width="407" height="301" alt="image" src="https://github.com/user-attachments/assets/e5f56764-11b9-4c10-ba01-d7547aaec872" /> All other queries: <img width="410" height="212" alt="image" src="https://github.com/user-attachments/assets/8631633f-5d4a-40a7-b089-6980a5180219" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## New Features - Added a separate **Cancel query** action for active database queries. - Added **Terminate session** to close connections and roll back active transactions. - Added safeguards based on query activity and permissions. - Added confirmation guidance for active queries, including cancellation options. - Added loading, success, and error feedback for query cancellation and session termination. - Added telemetry for query-cancellation actions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
810d292121 |
feat(studio): notebook cell operations (#48940)
## Summary - Pure module (`data/content/notebooks/notebook-operations.ts`) for applying `update_notebook` cell edits client-side: `insert_cell` (`after_cell_id` incl. `'start'`), `replace_cell`, `delete_cell`, `move_cell`. - Never touches the safe-sql brands — SQL promotion still happens at the tool-execute boundary, matching `create_notebook`. - Stacked on #48938. No wiring yet — `update_notebook` tool wiring is next. Towards FE-4083 ## Test plan - [x] `pnpm vitest run data/content/notebooks/notebook-operations.test.ts` — 13 unit tests covering every op, combinations, and all three error cases. - [x] `pnpm exec tsc --noEmit` clean - [x] `pnpm exec eslint` clean on new files <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added support for applying notebook cell operations, including insertion, replacement, deletion, and movement. * Operations are applied in a predictable order, with support for anchoring new cells at the beginning or near existing cells. * Added validation for invalid references, conflicting operations, and self-referential moves. * Added clear handling when operations produce an empty notebook result. * **Tests** * Added comprehensive coverage for individual, combined, ordered, conflicting, invalid, and empty-result notebook operations. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
ddb3e2c442 |
feat(studio): create_notebook AI tool (#48938)
## Summary - Adds a `create_notebook` AI assistant tool (`needsApproval: true`) that lets the assistant create a new notebook after explicit user approval. - Cell SQL is promoted from untrusted to safe via `acceptUntrustedSql`/`acceptUntrustedLogsSql` inside `execute`, using the approval gate as the confirming user gesture (same pattern as `execute_sql`). - Input is validated against the existing agent-writable notebook schema, which rejects any agent-supplied cell `id` at the schema level. - Threads an optional auth-headers param through `upsertContent`/`createNotebook`/`updateNotebook` so the tool can pass its own bearer token server-side. - Registers the tool in the tool-filter (`SCHEMA` category, alongside `list_notebooks`/`get_notebook`) and adds a `## Notebooks` prompt section guiding the assistant on when to use `create_notebook` vs. one-off `execute_sql`. Resolves FE-4082 ## Test plan - [x] `notebook-tools.test.ts` covers: tool registration, `needsApproval`, cell-id rejection, valid input, PUT body shape, and the returned id — all passing - [x] Typecheck clean - [x] Lint clean (no new warnings) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added AI-assisted notebook creation for saving multi-step investigations. * Added support for database and log SQL cells in newly created notebooks. * Notebook creation requires approval before saving and returns the notebook’s name and identifier. * Added support for custom request headers during notebook and content operations. * Added guidance for choosing between one-time SQL execution and reusable notebooks when Explorer is enabled. * **Improvements** * Improved validation and normalization of notebook content before saving. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
4587d177c3 |
Add optional title field to notebook cells (#48937)
## Summary - Adds optional `title` field to `databaseCellSchema` and `logCellSchema` in notebook schema - Allows database and logs notebook cells to carry descriptive titles - Field automatically propagates through derived schemas (wire, writable, agent, domain) via Zod inheritance <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added optional titles to database and log notebook cells. * Cell titles are now preserved across notebook editing, viewing, and agent workflows. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
7798e42435 |
feat(studio): notebook read tools (#48908)
## Summary - Adds `list_notebooks` (cursor-paginated) and `get_notebook` AI tools in `lib/ai/tools/notebook-tools.ts`, modeled directly on `report-tools.ts`: server-side `getContent`/`getNotebook` with the `authorization` header forwarded, zod-validated input. - `get_notebook` resolves every cell and exposes `unchecked_sql` as a plain `sql` field for the agent to read — display only, per the `safe-sql-execution` skill; nothing here executes SQL. - Registers both tools in `lib/ai/tools/index.ts` (same platform branch as reports) and in `lib/ai/tool-filter.ts`'s `toolSetValidationSchema` + `TOOL_CATEGORY_MAP` (`SCHEMA` tier). - Adds an optional `headers` param to `content-infinite-query.ts`'s `getContent`, mirroring the sibling `content-query.ts`, so the cursor-paginated fetch can carry the `Authorization` header from a server context. - New tools are behind the Explorer feature flag. Stacked on #48907 (1.4 — notebook query and mutation hooks), per the Notebooks implementation plan (stack 2.1). Resolves FE-4081 Resolves FE-4080 ## Test plan - [x] `pnpm exec tsc --noEmit` — no new errors - [x] `pnpm exec vitest run lib/ai/tools/notebook-tools.test.ts lib/ai/tools/index.test.ts lib/ai/tools/report-tools.test.ts data/content/notebooks` — 36/36 passing - [x] `pnpm --filter studio run lint` — no new warnings - [x] `pnpm exec prettier --check` on changed files — clean <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added AI tools to list project notebooks with pagination. * Added AI support for retrieving notebook markdown and resolved SQL cell content. * Notebook tools now respect project and authorization context. * Notebook features are available only when Explorer access is enabled. * Content requests can forward custom request headers. * **Tests** * Added coverage for notebook tools, Explorer access, feature flags, authorization, pagination, and error handling. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
1296a1c745 |
feat(studio): notebook query and mutation hooks (#48907)
## Summary Implements the "notebook query and mutation hooks" step of the notebooks data layer: - `data/content/notebooks/notebook-query.ts` — `getNotebook`/`useNotebookQuery`, wrapping the existing `getContentById` and narrowing to `type: 'notebook'`. - `data/content/notebooks/notebooks-infinite-query.ts` — `useNotebooksInfiniteQuery`, a typed wrapper over `useContentInfiniteQuery` narrowing pages to notebook rows. - `data/content/notebooks/notebook-upsert-mutation.ts` — `createNotebook`/`updateNotebook` + their mutation hooks, PUTting through the existing `upsertContent`. Write-path correctness, worked out while building the mutation hooks: - Cell `id`s are always backend-generated, never client-supplied — a brand-new cell has no `id` at all; an existing cell being kept/edited in an update keeps its real id so the backend can diff it against the previous version. `notebook-schema.ts` gains `writableCellSchema`/`writableNotebookSchema` (ids optional per cell) and `WritableCell`/`WritableNotebook` types, derived from `z.infer` of those schemas rather than hand-duplicated, with only the `sql` field re-branded per cell type via a small distributive conditional type. - Cell SQL at this write boundary must already be `SafeSqlFragment`/`SafeLogSqlFragment` (proven user-authored at a save/run event handler), not `unchecked_sql` — matching the `safe-sql-execution` skill's provenance model. - `content-remap.ts`'s notebook `unmapSqlContentField` branch is simplified to a passthrough: notebook writes only ever arrive already wire-shaped via `createNotebook`/`updateNotebook`, so there's nothing left to unmap. Note: this was originally stacked on `feature/notebooks-types-convergence`, but that branch merged into `master` (#48905) while this PR was in progress, so it's rebased directly onto `master` now. ## Test plan - [x] `pnpm --filter studio run typecheck` passes - [x] `pnpm --filter studio exec vitest run data/content/notebooks data/content/content-remap.test.ts` — 38/38 passing - [x] `pnpm --filter studio exec eslint` clean on all touched files <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added notebook listing with pagination, filtering, sorting, and project-specific queries. * Added notebook retrieval for viewing individual notebooks. * Added notebook creation and editing with automatic content refresh. * Added support for preserving cell IDs and safely handling SQL content. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
957e9fec67 |
feat(studio): notebook content at the API boundary (#48815)
## Summary Stacked on #48813 (1.2: notebook content schema). Part of [FE-4109](https://linear.app/supabase/issue/FE-4109/notebooks-data-model) — see that issue for the rest of the notebooks data-model stack. - Teach `content-remap.ts`'s wire↔domain dispatcher about the `notebook` content type, branding each cell's `sql` per `_tag` via the notebook schemas added in 1.2 (parses through `notebookDomainSchema` on the way in, unbrands per cell on the way out). - Add `{ type: 'notebook'; content: Notebooks.Content }` to the `Content` union in `content-query.ts`, plus a `ContentOfType<T>` helper for narrowing it. - Fix the resulting narrowing fallout at call sites that assumed `Content` only ever meant `sql`/`report`/`log_sql`: two generated-query-param casts, and four report/logs call sites now narrowed via `ContentOfType<'report'>` / `ContentOfType<'log_sql'>`. ## Test plan - [x] `pnpm --filter studio vitest run data/content/` — 35 tests pass, including new notebook coverage in `content-remap.test.ts` (per-cell brand separation, missing-field throw, remap↔unmap round-trip) - [x] `pnpm typecheck` — clean (pre-existing unrelated `ui-patterns` error aside) - [x] `pnpm --filter studio lint` — no new warnings/errors on changed files - [x] `pnpm format` — clean --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
f8206a5f81 |
fix(studio): model scoped pat permissions as OR-of-AND alternatives - smaller version (#48809)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Breaking down #48635 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Scoped access tokens now support alternative permission requirements, enabling more precise access for APIs and tools. - Added clearer role and resource access evaluation, including project-specific permissions and partial read access. - Access reviews now identify unavailable or excessive permissions and group inaccessible resources for easier resolution. - **Bug Fixes** - Improved handling of legacy, incomplete, or invalid permission data with safer fallback behavior. - Corrected access filtering for MCP tools and API capabilities. - **Documentation** - Updated access-review wording to clarify the relationship between scopes and related MCP tools. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Wen Bo Xie <wenbox323@gmail.com> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
0b97e37ccf |
feat: notebook content schema (#48813)
Related to FE-4109. ## Summary - **API codegen workaround**: Platform API's `notebook` content type hasn't shipped to the OpenAPI spec yet, so `pnpm api:codegen` can't be run. Locally widened `ContentBase.type` to include `'notebook'` (marked with TODO for removal once spec publishes). - **Notebook schema & type system**: Introduced Zod schemas mirroring RFC-defined notebook shape (`schema_version: 1, cells: Cell[]`). Maintains wire/domain boundary (cell `sql` → `unchecked_sql` branded for security). Agent-writable schema for `create_notebook` tool omits cell IDs (backend-generated); future update operations will require them. All TypeScript types are `z.infer`'d from schemas (no hand-written parallel interfaces). - **IsoDateTimeString moved**: Extracted ISO datetime validator from `querySource.ts` to `lib/iso-datetime.ts` (data layer shouldn't import from components layer). Needed by notebook `time_range` fields. ## Test plan - [x] Unit tests: `notebook-schema.test.ts` (9 tests), `iso-datetime.test.ts` (3 tests), `querySource.test.ts` updated and passing (26 tests) - [x] Typecheck: no new errors - [x] Prettier: formatting clean <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added support for validating and processing notebook content, including markdown, database, log cells, time ranges, and chart configurations. - Added compatibility for notebook content types in content handling. - Added reliable ISO date-time validation for notebook data and related features. - **Tests** - Expanded coverage for valid and invalid notebook structures, cell requirements, time ranges, chart settings, and date-time values. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
cddb430310 |
feat(studio): scoped pat root branch (#48384)
## Description This is the Scoped PAT stacked PRs root branch ## How to test ### With the `scopedPAT` enabled (default on staging) Go to https://studio-staging-git-scopedpat-merge-token-lists-supabase.vercel.app/dashboard/account/tokens. - You shouldn't see two tabs anymore - If you had classic tokens, they should have the _Legacy_ badge - You can create scoped tokens - You have a way to copy newly created tokens before closing the form side panel ### With the `scopedPAT` disabled (use the devtool to override) - You shouldn't see two tabs anymore - If you had classic tokens, they should **not** have the _Legacy_ badge - You can create classic tokens - You have a way to copy newly created tokens above the list upon form submission <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Show classic and scoped access tokens together in one list, with classic tokens labeled “Legacy” when the scoped experience is enabled. * Add scoped access token creation with a two-step configure → review → success flow (when enabled). * Add a dismissible migration notice about scoped tokens with a link to API docs. * Show “View permissions” only for scoped tokens. * **Bug Fixes** * Token deletion now supports both classic and scoped tokens with the correct confirmation and success handling. * The scoped tokens page now redirects to the unified access tokens page. * **Accessibility** * Improved accessibility by adding a label to the token “more options” action. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Ali Waseem <waseema393@gmail.com> Co-authored-by: kemal.earth <606977+kemaldotearth@users.noreply.github.com> |
||
|
|
840127cd69 |
let inline error callers own mutation failures (#48640)
## What kind of change does this PR introduce? Code clean-up following #48470, #48471, #48472, #48473, and #48474. ## What is the current behavior? Mutation hooks provide fallback error toasts, so callers that already render errors inline must suppress those toasts with empty `onError` handlers. ## What is the new behavior? The affected callers own their error presentation. Inline interstitial errors remain unchanged, API authorisation retains its state-reset handlers, and Project Claim retains its combined caller-owned toast. ## To test There is no useful before-and-after visual check for this PR: the rendered error states should be identical on `master` and this branch. The change only removes the default-toast and no-op-handler pair underneath the UI. The existing [Organisation Invite](https://github.com/supabase/supabase/pull/48470), [API authorisation, AWS Marketplace](https://github.com/supabase/supabase/pull/48471), and [Stripe Projects](https://github.com/supabase/supabase/pull/48472) failure tests cover the inline errors and confirm that no duplicate toast appears. |
||
|
|
21919ec9b8 | feat(pipelines): Use new restart endpoint (#48737) | ||
|
|
51c5b9f013 |
chore: sync ssl enforcement and temporary access (#48743)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Chore - fix-up ## What is the current behavior? Temporary access depends on ssl enforcement. The frontend doesn't enforce this very well or keep state between the two configs. ## What is the new behavior? This updates the two configs to be interdependent and updates to each one triggers a frontend state change on the other. ## Additional context Before: https://github.com/user-attachments/assets/8f040b62-587c-4268-9e27-27dd09b052a3 After: https://github.com/user-attachments/assets/c62e006e-6147-4c94-b6cf-375ca300b890 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added confirmation dialogs and downtime warnings before changing database SSL enforcement. - Added loading states and success or failure notifications for SSL updates. - Enabled SSL enforcement directly from temporary database access settings. - **Bug Fixes** - Prevented SSL enforcement from being disabled while temporary database access is enabled. - Improved settings refresh after SSL enforcement changes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
a28214c236 |
feat(studio): add ClickHouse OTEL SQL for the Auth report's v2 metrics (#48750)
## Problem Part of DEBUG-73 (migrate reports queries to the OTEL/ClickHouse endpoint). The Auth report's v2 metrics (ActiveUsers, SignInAttempts, PasswordResetRequests, TotalSignUps, sign-in/sign-up processing time, error breakdowns) currently only query the BigQuery-backed logs.all endpoint. ## Fix Adds `AUTH_REPORT_SQL_OTEL`, a ClickHouse-dialect mirror of the existing `AUTH_REPORT_SQL`, covering all 10 metrics. Threads a `useOtel` parameter through `fetchLogs` and the three report config creators (`createUsageReportConfig`, `createErrorsReportConfig`, `createLatencyReportConfig`), defaulting to `false` everywhere. This PR is inert on its own: nothing yet passes `useOtel: true`, so it changes no runtime behavior. The follow-up PR (stacked on this one) wires the `otelReports` feature flag through the Auth report page to actually select the OTEL SQL. Also includes: one dataProvider now validates its raw rows with a Zod schema instead of casting to `any`, and removal of a few functions in this file that had zero callers (`AUTH_ERROR_CODE_VALUES`, `createAuthReportConfig`, an exact duplicate of a status-code color map, an unused hook). ## How to test - Unit: `cd apps/studio && npx vitest run data/reports/v2/auth.config.otel.test.ts` - No manual testing needed for this PR alone since it changes no runtime behavior (useOtel defaults to false, unwired). The follow-up PR covers manual testing of the actual flag-gated behavior. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added OpenTelemetry-backed authentication reports. * Authentication reports now include usage, errors, latency, sign-ins, sign-ups, and edge-log metrics. * Added filtering by provider, status code, action, and time range. * Added selectable telemetry sources for retrieving report logs. * **Bug Fixes** * Improved validation of authentication error codes. * Improved handling of missing report data with consistent empty results. * Improved report formatting for more consistent attribute display. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
aed332b663 |
feat: migrate Edge Functions report to ClickHouse OTEL logs (#48756)
## Problem
The Edge Functions report (`observability/edge-functions`) only queries
BigQuery. As part of the broader Reports→ClickHouse OTEL migration
(DEBUG-73), we need each report migrated one at a time behind the
`otelReports` flag.
## Fix
Adds a ClickHouse OTEL SQL variant (`METRIC_SQL_OTEL`) for the 4 Edge
Functions metrics (TotalInvocations, ExecutionStatusCodes,
InvocationsByRegion, ExecutionTime), querying the unified `logs` table
filtered to `source = 'function_edge_logs'`, with fields read from
`log_attributes` (`function_id`, `response.status_code`,
`response.headers.x_sb_edge_region`, `execution_time_ms`) — the same
mapping already used by `edge-functions-last-hour-stats-query.ts`.
`edgeFunctionReports()` now takes a `useOtel` flag that picks between
the BQ and OTEL query sets and forwards it to `fetchLogs`. The page
wires this up via `useFlag('otelReports')`, matching the pattern used
for the Auth report. No behavior change while the flag is off — report
still fetches from BigQuery.
Also removed two pieces of dead code spotted in `report.utils.ts` while
touching it: the unused `useEdgeFnIdToName` hook and a
`STATUS_CODE_COLORS` map that was an exact duplicate of
`REPORT_STATUS_CODE_COLORS` (the one actually imported elsewhere).
This PR is standalone — no dependency on the in-flight Auth report OTEL
stack.
## How to test
- `pnpm vitest run data/reports/v2/edge-functions.config.otel.test.ts` —
9 new tests covering the OTEL SQL shape (single logs table,
unix-microsecond timestamp bucketing, field mapping, filters).
- `pnpm vitest run data/reports` and `pnpm vitest run
data/edge-functions components/interfaces/Reports` — existing suites (46
+ 54 tests) still pass, confirming no regression to the BQ path.
- Manually: with `otelReports` flag enabled, visit a project's Edge
Functions observability report and confirm charts render from the
ClickHouse endpoint.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **New Features**
* Added OpenTelemetry support for Edge Functions observability metrics,
including invocations, status codes, regional activity, and execution
time.
* Reports can now dynamically use either the standard or OpenTelemetry
logs source.
* **Bug Fixes**
* Improved filtering and timestamp handling for OpenTelemetry-based Edge
Functions metrics.
* Added coverage for status, execution time, function, and region
filters.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
|
||
|
|
9b3e0a9060 |
show Vercel connection errors inline (#48473)
## What kind of change does this PR introduce? Bug fix. ## What is the current behavior? Vercel install and project-link failures use transient toasts. ## What is the new behavior? Failures remain visible below the relevant action and clear when the user retries or changes a selection. The Vercel mutation hooks expose errors without choosing their presentation. Interstitial callers render them inline, while existing non-interstitial callers explicitly retain their toasts. | Before | After | | --- | --- | | <img width="1024" height="759" alt="Install Vercel Integration Supabase" src="https://github.com/user-attachments/assets/6348cdd2-220a-4ad8-89f9-7fc51de36a3c" /> | <img width="1024" height="759" alt="Install Vercel Integration Supabase" src="https://github.com/user-attachments/assets/ecc50c4e-daab-4f6d-bf86-7282e2aff92c" /> | ## To test 1. Switch to `dnywh/inline-vercel-errors` (this branch). 2. Open `apps/studio/pages/integrations/vercel/install.tsx`. 3. Find the `actionError` assignment immediately below `useVercelIntegrationCreateMutation` and replace the whole assignment with: ```tsx const actionError = 'Creating Vercel integration failed: Test error' ``` 4. With local Studio running and while signed in, open `http://localhost:8082/integrations/vercel/install?code=test&configurationId=test&source=marketplace` 5. Confirm the error remains visible below **Install integration**. No Vercel installation or real authorisation code is required. 6. Revert the temporary edit. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Bug Fixes * Improved error handling across Vercel project connection and installation flows. * Validation, duplicate-connection, and connection failures now appear inline in the relevant setup steps. * Errors clear automatically when the selected project or organization changes. * Notifications remain available in supported flows, including new project creation and side-panel setup. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
8b38e0d1ed |
feat(studio): ClickHouse dialect for logs snippet AI + rewrite to ClickHouse (#48501)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/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 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## 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. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
b3c5c9fc04 |
feat(studio): logs snippets in SQL editor nav, search, and tabs (#48457)
## What PR 7 of the SQL-editor query-source (Database vs Logs) stack. Surfaces `log_sql` snippets as a distinct query source across the SQL editor sidebar. Stacked on **`charislam/toolbar-ui-creation-flow`** (PR 6 — toolbar UI + creation flow); review/merge that first. Nothing is user-visible until the flags roll out — every entry point requires **both** `sqlEditorLogsSource` **and** `otelLegacyLogs`. ## Changes - **Nav** — a flag-gated **Logs** section (`LogsSnippetsSection`) backed by its own single-type `log_sql` query. The active snippet is injected only into the section it belongs to, via a shared `withActiveSnippet(snippets, active, belongsPredicate)` helper (also DRYs the private/favorites/shared injections). - **Search** (`SearchList`) — a **Logs** result group with a shared, extracted `SqlSnippetTree`; the "N results found" count now sums database + logs, with loading/empty states covering both queries. - **Tabs** — an immutable `sqlSource` field on tab/recent-item metadata (set at tab creation, lazily backfilled once the snippet loads via `useEffectEvent`), and a distinct `ScrollText` icon via a shared `LogsSnippetIcon`. Tab cleanup treats `log_sql` tabs as live and only prunes them when logs data is authoritative (`canPruneLogsTabs`), so a disabled/erroring logs query never wrongly deletes logs tabs or blocks database-tab cleanup. - **Data layer** — `useSqlSnippetsQuery` gains an optional `type` param so logs reuse the same `SnippetWithContent` shape as the other sections (no casts). ## Tests - `state/tabs.test.ts` — `sqlSource` backfill + creation-time carry-through. - `components/layouts/Tabs/Tabs.utils.test.tsx` — cleanup prunes stale database/logs snippets, keeps live ones, and preserves logs tabs when logs data isn't authoritative. ## Verification - `pnpm --filter studio typecheck` ✓ - `pnpm --filter studio run lint:ratchet` ✓ - `pnpm test:studio` (affected suites) ✓ <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a collapsible Logs section to the SQL editor sidebar for browsing, sorting, selecting, renaming, and deleting log queries. * Expanded SQL search with separate, paginated results for database and log queries. * Added dedicated log-query icons across navigation, tabs, previews, and recent items. * **Bug Fixes** * Improved tab and recent-item cleanup while preserving active log queries and accurate source metadata. * **Tests** * Added coverage for log tab cleanup and SQL source metadata synchronization. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
9dc5c0faf3 |
feat: privatelink read replica (#48642)
Frontend changes for new privatelink functionality. The updates to the API are already live, but will be putting the UI changes behind a feature flag while we do some full end to end testing. Changes to Integration page: <img width="744" height="456" alt="image" src="https://github.com/user-attachments/assets/02026083-4b61-4f36-927b-1bac42cb73e2" /> Changes to create associations page: <img width="859" height="411" alt="image" src="https://github.com/user-attachments/assets/303b4ec5-3b5a-4eaf-8d22-45e1e63a0705" /> Fixes SEC-919 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - AWS PrivateLink connections can target the primary database or a read replica. - Connection lists and confirmation dialogs now identify the selected database clearly. - Replica details include improved status information and a “Manage replica” link. - **Bug Fixes** - Replica removal errors now provide clearer guidance and link to integration settings when PrivateLink issues occur. - **Updates** - Infrastructure diagrams focus on visualization, with replica management actions moved to dedicated management views. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
a0cec24f49 |
Remove references to fly (#48648)
## Context As per PR title - should not have any visual nor functional change <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Changes** - Standardized infrastructure, region, and database configuration around AWS-based environments. - Removed Fly.io-specific region and provider options from project creation, instance sizing, and infrastructure settings. - Enabled disk validation, spend-cap eligibility, backup restoration, and extension setup consistently across supported projects. - Updated billing and region displays to use the applicable AWS configuration. - **Bug Fixes** - Corrected project-specific restrictions that could incorrectly hide configuration and billing controls. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
2c53ca4a79 |
Support listing and reading custom reports from Assistant (#48530)
## Context This is pre-requisite work for adding support to managing custom reports from the Assistant. Planning to break this into a number of PRs, briefly - Adding read support for custom reports - Adding write support for custom reports - Adding run support for custom reports - Should be able to infer data from the results then This PR starts with adding support for listing and reading custom reports from the Assistant ## Other changes involved - Updates setting up of the home page report to have better title and description - Swaps the variant of the ToggleGroup in the SQL block for custom reports as the default variant blends into the background color of the PopoverContent ## To test - [ ] Assistant should be able to list custom reports + read its contents <img width="428" height="755" alt="image" src="https://github.com/user-attachments/assets/6a15b660-c0ee-4a06-984c-87eff3943eec" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added AI-assisted tools to list reports and retrieve report details, including chart counts, layouts, configurations, and SQL-backed chart information. - Added clearer empty-state messaging when no snippets are available. - **Improvements** - New homepage reports now use the name “Homepage Report” and include a descriptive project-home summary. - Updated query controls with refreshed visual styling. - Improved content requests to support additional request context. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
ec64135f9d |
perf(pg-meta): scope column privileges query to a single table (#48553)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Performance improvement ## What is the current behavior? The column privileges page in Studio only ever renders one table, but the underlying query still `aclexplode`s every column in the whole schema and filters the result client-side. ## What is the new behavior? Adds a scoped SQL path that prunes `pg_class`/`pg_namespace` to the requested schema+table before exploding ACLs, gated behind the `pgMetaScopedIntrospection` flag, with a plan-guard test asserting `pg_class`/`pg_attribute` stay index-driven. Studio's query hook and cache keys now thread the selected table through so column-privilege invalidation and cold-load races are scoped correctly, and the page fetches per-table instead of per-schema. ## Additional context <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * Column privileges are now scoped to the selected schema and table for more accurate results. * Changing schemas automatically updates the table selection and refreshes the displayed privileges. * Privilege updates now refresh only the relevant schema, table, and column data. * Loading states are handled more accurately when no table is selected. * **Bug Fixes** * Improved consistency between scoped and unscoped column privilege results, including table-, column-, and grant-option privileges. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
bc95a2f19a |
fix(studio): edge func exec time formatting in reports (#48539)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Fixes Edge Function Execution Time chart within our observability reports time formatting. This also fixes the non-hovered state which would lose the `ms` formatting. | Before | After | |--------|--------| | <img width="2160" height="652" alt="cleanshot_2026-07-29_at_02 15 53_2x" src="https://github.com/user-attachments/assets/cfd6dbc2-f283-4379-a133-581c76990cb5" /> | <img width="797" height="314" alt="Screenshot 2026-07-31 at 14 30 48" src="https://github.com/user-attachments/assets/f5f1ace5-b6ef-43db-aebd-e10d31631013" /> | <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Improved execution-time chart formatting with clearer millisecond values, thousands separators, and configurable precision. * Chart highlights now support custom value formatting alongside existing number, percentage, and byte formats. * **Bug Fixes** * Non-finite execution-time values now display safely as `0ms`. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
50e1eb7436 |
chore(eslint): bump eslint-config-next to v16 for useEffectEvent (#48458)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Chore / build (ESLint config upgrade + lint cleanup). ## What is the current behavior? `eslint-plugin-react-hooks` v5 (pulled in transitively by `eslint-config-next` v15) doesn't recognize stable `useEffectEvent`, so every effect that calls an effect-event handler needs an `eslint-disable react-hooks/exhaustive-deps` to silence a false positive. There are 30 such dead disables across Studio. ## What is the new behavior? Bumps `eslint-config-next` to v16, which pulls in `eslint-plugin-react-hooks` v7 whose `exhaustive-deps` understands `useEffectEvent`, and removes the 30 now-dead disable directives (and their orphaned explanatory comments). Supporting changes: - **Flat-config migration**: v16 is a native flat-config array (v15 was eslintrc), so `eslint-config-supabase` now spreads it directly instead of bridging through `FlatCompat`. - **React Compiler rules off**: v16 enables react-hooks v7's `recommended`, which layers the React Compiler lint rules on top of the two classic rules. These are switched off (derived dynamically from what next enables) to keep this change scoped to the `exhaustive-deps` improvement. - **Plugin-registration fallout** (v16 scopes plugin registration to a file glob rather than registering globally like FlatCompat did): stop re-registering `@typescript-eslint` (shared) and `jsx-a11y` (studio); scope our react / react-hooks / jsx-a11y rule overrides (studio, www) to v16's plugin glob so they don't error on files outside it (e.g. `.cjs`). - **Lint surface preserved**: v16's glob newly includes `.mts`/`.cts` (v15 didn't lint them), which surfaced pre-existing errors in tooling scripts. The shared config keeps the prior surface by leaving `.mts`/`.cts` unlinted; linting them is left as a separate change. - **Ratchet**: rebaselines `@tanstack/query/exhaustive-deps` 9 → 89. v15 forced next's `@babel/eslint-parser` onto `.ts` files, hiding these deps; v16 parses `.ts` with `@typescript-eslint/parser` and correctly surfaces the intentional `connectionString`-excluded-from-`queryKey` pattern. Worth a follow-up to review whether any are real cache-correctness bugs. - Drops three now-dead devDeps from `eslint-config-supabase`: `@eslint/eslintrc`, `@eslint/js`, `@typescript-eslint/eslint-plugin`. Verified locally: `turbo run lint` → 7/7 packages pass with 0 errors; Studio `lint:ratchet` passes; Prettier clean on changed files; typecheck unaffected. ## Additional context <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Chores** * Refined linting configuration and removed outdated lint suppressions across Studio. * Updated Next.js linting support and refreshed related development configuration. * Expanded lint baseline coverage for query-related code. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
c4c58ef3e3 |
feat: remove pandadoc dpa request flow (#48525)
Terms of Service v3 (effective August 1, 2026, #48482) incorporates the Data Processing Addendum by reference, so customers no longer sign a separate DPA. Legal confirmed the PandaDoc signing flow can go; previously signed DPAs remain binding. This removes the frontend flow only. I'll remove the platform endpoint (`POST /platform/organizations/{slug}/documents/dpa`) separately once the PandaDoc contract conversation wraps. **Changed:** - **Dashboard DPA card no longer requests PandaDoc documents**: the Request DPA button and confirm modal are replaced with a View DPA link to the canonical legal page, with evergreen copy explaining the DPA is part of the Terms. Tracked via the same `document_view_button_clicked` event the other document cards use. - **Legacy `/legal/dpa` page retired**: the page told users to request a signed DPA from the dashboard, which no longer exists. It now permanently redirects to `/legal/customer-resources/data-processing-addendum` (the follow-up already flagged in #48483), and the footer link is removed. The `dpa_pdf_opened` and `dpa_request_button_clicked` events are removed with their last call sites. The latest privacy version links the canonical page directly; archived v1/v2 keep their original `/legal/dpa` link, served by the redirect. - **Orphaned DPA PDFs removed**: the four dated `Supabase+DPA+*.pdf` files under `/downloads/docs` had zero remaining references once the signing flow is gone. No redirect: nothing links these URLs, so they 404. - **Subscription tracking**: the subprocessor updates form now fires `www_subprocessor_updates_subscribed` on successful submit, so we can measure uptake of the notification list that replaces per-customer DPA emails. ## To test Verified on the Vercel previews (Playwright): - [x] Studio: `/org/_/documents` shows the DPA card with the incorporation copy and a working View DPA link (href = canonical page); no Request DPA button, no PandaDoc mention; TIA/SOC2/ISO27001/HIPAA cards unaffected - [x] www: `/legal/dpa` permanently redirects to `/legal/customer-resources/data-processing-addendum`; footer no longer shows DPA; zero console errors - [x] www: subscribing on the subprocessor page succeeds (200 from the form route, profile created with topic_4) and fires `www_subprocessor_updates_subscribed` (201 from the telemetry endpoint); test profile unsubscribed afterwards - [x] www: `/downloads/docs/Supabase+DPA+260601.pdf` returns 404 with no redirect; DPA card copy verified without the effective date ## Linear - fixes GROWTH-1068 |
||
|
|
f9a1d2e983 |
Disable unsupported Studio features for HA projects (#48376)
## Summary More gating to support upcoming High Availability projects. - Keep the Recent Branch stat visible on the project home page for HA projects, but disable its interaction, reduce its opacity, and skip the branches query. - Treat Realtime as disabled for HA projects in the service-status dropdown so it does not make the project appear unhealthy or trigger unhealthy polling. - Show the shared unsupported-feature empty state for Custom Domains and skip its query on HA projects. - Disable the Enable Realtime checkbox in the table creation sheet for HA projects. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added High Availability–aware behavior across activity stats, service status, custom domains, and table realtime controls. - Introduced reusable Branch value UI that shows an “Unavailable” state in High Availability mode. - Added a dedicated realtime toggle UI that disables interaction and updates helper text when unavailable. - **Bug Fixes** - Ensured realtime is treated as disabled (not unhealthy) in High Availability and prevented realtime enabling/saving. - Reduced unnecessary data fetching by gating addon/custom-domain requests and disabling branch queries. - **Tests** - Added coverage for realtime status resolution, BranchStatValue “Unavailable” rendering, and TableRealtimeToggle behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
fa5eb17277 |
feat(studio): discriminated snippet union + source-aware writes (#48313)
Stacked on #48305. ## What PR 3 of the stacked SQL-editor query-source series (Database vs Logs). Stacked on the PR 2 branch `charislam/log-sql-content-shape`. Turns `SnippetWithContent` into a discriminated union on `type` and makes all snippet writes source-aware: - `data/content/sql-folders-query.ts`: `SnippetWithContent` is now `{ type: 'sql'; content?: SqlSnippets.Content } | { type: 'log_sql'; content?: LogSqlSnippets.Content } | { type: 'report'; content?: never }`. `report` is kept (the content endpoints' wire type carries it) but has no SQL content — its body is `Dashboards.Content`, loaded through the separate `Content` union. - `setSql` brands per type (`untrustedLogSql` vs `untrustedSql`). - `buildUpsertPayload` persists `snippet.type` (no longer hardcoded `'sql'`). - `createSqlSnippetSkeletonV2({ source })` emits the matching type + content shape with the `as any` cast removed. - New `components/interfaces/SQLEditor/querySource.ts`: `SqlSnippetSource` + `getSnippetSource`. - `seedSnippet` test helper gains a `source` arg. - New `remapWireSnippet` boundary helper in `content-remap.ts` concentrates the single wire->domain assertion, so `content-id-query` / `content-upsert-mutation` call sites are cast-free (no `as unknown as`). - Collateral: query result types aligned to the union; `updateSnippet` no longer accepts `type` (source is immutable); db-only editor read paths narrow away `log_sql`. ## Why Impossible-states-impossible typing: a snippet's brand follows its content type, so logs SQL and database SQL can never cross execution paths. No behavior change for existing database snippets. ## Testing - \`pnpm typecheck\` — clean - \`pnpm --filter studio run lint:ratchet\` — no new warnings - \`pnpm test:studio\` (data/content, SQLEditor, state/sql-editor) — passing, including new tests for \`getSnippetSource\`, source-aware \`setSql\`, type-aware \`buildUpsertPayload\`, and both skeleton shapes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added source-aware creation for SQL editor snippets, including log-based SQL snippets. * Introduced backend source mapping so log snippets are treated as log_sql. * **Bug Fixes** * Improved SQL retrieval/prettification so log snippets no longer use the wrong fallback content. * Ensured log snippets are sanitized and preserve correct type, content, identifiers, and statuses during save/upsert flows. * **Tests** * Expanded unit and integration coverage for log snippet creation, source mapping, editing, prettification, and upsert payloads. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
7743fee3ab |
feat(studio): log_sql content shape + remap content.sql to unchecked_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 --> |
||
|
|
ec1c889349 |
feat(studio): logs SQL brands + execution data layer (#48301)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/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 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## 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. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
8c092185ae |
feat: paused project restore window copy and backup downloads (#48279)
Shows the restore deadline as a date on the paused-project screens, and offers backup downloads while a paused project is still restorable (previously only after the restore window ended). Depends on a backend change — keep as draft until that is live. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Extended the paused-project restore window from 90 days to up to 1 year. * Added clearer, downloadable options for database backups and storage objects while a project is paused. * Paused-project screens now show an “available until” date when applicable (and updated resume guidance). * **Documentation** * Updated platform and troubleshooting guides to reflect the new 1-year restore window and post-window recovery limitations. * **Bug Fixes** * Standardized restore-window wording across the pause confirmation and paused-state UI. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
a06eb5f26f |
[FE-3724] feat(studio): add enable cleanup button to cron jobs page (#48200)
Adds a standalone **Enable cleanup** button to the Cron Jobs page header so users can schedule the daily `delete-job-run-details` cleanup job proactively — previously this was only reachable inside the conditional "table too big" overflow dialog. Addresses [FE-3724](https://linear.app/supabase/issue/FE-3724/enable-pg-cron-cleanup-job-from-ui-and-api) (the UI half; the Management API half needs platform-side work). **Added:** - `Enable cleanup` button in the cron jobs header (left of Refresh), hidden while the existence check loads and whenever a `delete-job-run-details` job already exists - Confirmation dialog with a retention-period select (defaults to 7 days), live SQL preview, and telemetry (`cron_job_cleanup_enable_button_clicked` with `origin` + `retentionInterval`) - Component tests (MSW) for visibility gating and the schedule/cancel flows - E2E regression test for the full schedule → delete → button-reappears cycle **Fixed:** - Name-based `useCronJobQuery` lookup: the `queryFn` dropped the `name` param, and a not-found job returned `undefined` (rejected by react-query v5) — now passes `name` through and returns `CronJob | null` - Cache invalidation gaps: create/delete now invalidate the whole cron-jobs prefix (list, count, job details), so the footer count updates after create/delete and the button reappears after the cleanup job is deleted. The schedule mutation deliberately invalidates only the existence check + count (see inline comment) - Pre-existing e2e leak: the cleanup-workflow test left `delete-job-run-details` scheduled; it now cleans up after itself ## Screenshots | Header button | Dialog | | --- | --- | | <img width="890" height="325" alt="Screenshot 2026-07-22 at 9 44 40 PM" src="https://github.com/user-attachments/assets/966cd640-d8a6-4c8f-92e7-73151bf4de9c" /> | <img width="512" height="461" alt="fe3724-dialog" src="https://github.com/user-attachments/assets/6be1785f-cc7e-4048-a648-9ef260b0949f" /> | ## To test - Go to a project's Integrations → Cron → Jobs with pg_cron enabled and no `delete-job-run-details` job → the `Enable cleanup` button shows next to Refresh - Open the dialog, switch retention intervals → the SQL preview updates; confirm → success toast, the job appears in the grid (`0 12 * * *`), and the button disappears without a reload - Delete the `delete-job-run-details` job from the grid → the button reappears without a reload - Create then delete any other job → the footer `Total: N jobs` count updates both ways without a reload - Regression: with the high-query-cost banner forced (or via the e2e), the overflow dialog's "Schedule cleanup job" step still shows its success state — the dialog must not close mid-flow <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Summary by CodeRabbit * **New Features** * Added an **Enable cleanup** action to the Cron Jobs tab header, including a retention selector and SQL preview. * Enabling schedules the daily cleanup, shows a success toast, updates the grid, and hides the enable button; **Cancel** closes the dialog without scheduling. * **Bug Fixes** * Improved cron job lookup to work by name when needed. * Refreshed related cron job data more reliably after scheduling and deletion. * **Telemetry** * Added an event for cleanup enable button clicks. * **Tests** * Added component and Playwright coverage for enable/cancel/schedule/delete and cleanup banner flows. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
b2b150fa3c |
feat(pipelines): Add UI selector for choosing which tables to skip copy of (#47808)
## Summary Adds initial-copy scoping to Pipelines in Studio. Users can copy all existing rows, skip all initial copies, copy only selected publication tables, or skip selected table copies. All publication tables continue streaming new changes regardless of the initial-copy policy. The policy now round-trips through create, edit, validation, and the generated Management API contract. Initial-copy estimates and table-restart confirmations use the same scope. Edit requests also preserve redacted credentials and pipeline settings that Studio does not own. This completes the Studio layer of the [ETL API change](https://github.com/supabase/etl/pull/897) and [Management API change](https://github.com/supabase/platform/pull/35479). ## Screenshots ### Selector <img width="1153" height="465" alt="image" src="https://github.com/user-attachments/assets/bf615e82-ee61-4222-979d-a8695a957e82" /> ### Select certain tables only <img width="1153" height="465" alt="image" src="https://github.com/user-attachments/assets/28adaa24-f239-4d1d-8fb8-fdb1988320cd" /> ### Confirm copy costs As the final step before the pipeline is created: <img width="597" height="619" alt="image" src="https://github.com/user-attachments/assets/a660bd87-bfb8-41c5-8099-4cdbdef943bf" /> ### Policy-aware initial-copy estimate #### Copy no table is selected <img width="407" height="464" alt="image" src="https://github.com/user-attachments/assets/99d859ec-2ec3-452a-ab69-11924a8db260" /> #### Some tables are selected <img width="407" height="464" alt="image" src="https://github.com/user-attachments/assets/e68aedf4-66bc-4372-98ef-0dd7fecef324" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added configurable “initial table copy” policies (copy/skip all and copy/skip selected) during replication setup, including table-picker behavior, pruning of stale selections, and updated restart/cost estimates. - **Bug Fixes** - Improved restart flows to consistently use `schema.table` identity and simplified “errored tables” targeting to match error-state tables. - Reduced unnecessary loading by gating publication/table fetches to when panels are visible; improved validation/toast handling when publication tables are unavailable. - **Tests** - Added/expanded coverage for destination form submission, table-copy selection, restart/cost dialogs, and copy-estimate summarization. - **Style** - Refreshed warning/label text for clearer configuration and confirmation messaging. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Victor Farazdagi <simple.square@gmail.com> Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
6c6a721cb7 |
fix(pg-meta): scope remaining O(catalog) introspection queries behind pgMetaScopedIntrospection (#48148)
## I have read the [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) file. YES ## What kind of change does this PR introduce? Bug fix (performance), follow-up to #47894, plus regression-guard tests. ## What is the current behavior? #47894 scoped the Table Editor and entity-definition introspection queries, but four more `@supabase/pg-meta` query families still do O(catalog) work per request. On a production project with a very large catalog (hundreds of schemas, ~465K `pg_constraint` rows) they run 5 to 55 seconds each, trip the 58s `statement_timeout`, and spill sorts to temp files. During a recent "DB CPU > 85%" incident on such a project, 24 of 27 active backends were running these queries concurrently. 1. **`tables.retrieve()` (single-table lookup by name+schema or id)**: the `tables`/`columns` CTEs scan the whole catalog (`pg_class`, `pg_constraint`, `pg_index`, all of `pg_attribute`, per-table sizes) and the one-table predicate is applied only on the outer select. Same bug class #47894 fixed for the OID-based table editor query; this sibling path never got the treatment. It accounted for 94 of the 96 statement-timeout cancellations in the incident. 2. **Types listing**: the `t_enums` and `t_attributes` subqueries aggregate the entire `pg_enum` and every composite relation before the wrapper's schema filter applies. 3. **Table privileges**: `aclexplode` + double `pg_roles` join + GROUP BY over every relation in the database; schema/OID filters applied only after aggregation, in both `list()` and `retrieve()`. 4. **Row counts**: `getTableRowsCountSql` treats `reltuples = -1` (never-analyzed table) as "small table, run exact count(*)". A freshly bulk-loaded multi-million-row table times out on every Table Editor pagination render. Two Studio-side amplifiers turned one slow query into a sustained load storm: - `useTableQuery` (behind `tables.retrieve()`) mounts once per visible foreign-key grid cell via `ForeignKeyFormatter`, so a single Table Editor view fires ~20 concurrent copies against the FK target table. A timed-out query caches nothing, and TanStack retries errored no-data queries on every observer mount by default, so scrolling kept re-issuing the 58s scan. - `useTableApiAccessQuery` fetched table privileges for the entire database and filtered down to one schema client-side. ## What is the new behavior? **pg-meta (all behind the existing `pgMetaScopedIntrospection` flag, same rollout mechanism as #47894; `scoped: false` keeps serving the current SQL):** - `tables.retrieve()`: the identifier is resolved to a scalar `targetOid` init-plan and pushed into the base scan, primary-key, relationships (both FK directions kept: `conrelid` or `confrelid`) and columns CTEs. A materialized `target` CTE was deliberately avoided: it acts as an optimization barrier and forces the very seq scans being removed. - Types: filter `pg_type`/`pg_namespace` first, then compute enums/attributes per surviving row via correlated index-scan subqueries (`pg_enum(enumtypid, enumsortorder)`, `pg_attribute(attrelid, attnum)`). - Table privileges: schema/OID predicates injected into the base WHERE before `aclexplode`/GROUP BY for `list()` and `retrieve()`. - Row counts: `reltuples = -1` is treated as "unknown" and gated on physical size via `pg_relation_size` (a cheap stat call; `relpages` is equally stale pre-vacuum). At or below `THRESHOLD_ESTIMATE_BYTES` (~10MB, derived from `THRESHOLD_COUNT` at a conservative ~200 bytes/row) the exact count runs as before: fast by construction, and it avoids bogus estimates since Postgres floors never-vacuumed heaps at 10 pages, so an empty table would otherwise report ~2K estimated rows. Above the gate the count routes through the EXPLAIN-based `pg_temp.count_estimate`, or returns `-1`/`is_estimate = true` in read-only contexts where the temp function cannot be created. The scoped branch embeds the estimated select via `literal()` instead of legacy's apostrophe-only escaping, so it stays correct under `standard_conforming_strings = off`. `enforceExactCount` unchanged. **Studio:** - The flag decision is contained in the data layer instead of prop-drilled: a small imperative accessor (`apps/studio/data/scoped-introspection.ts`) is hydrated from `useFlag` via a one-line `useSyncScopedIntrospection()` call in `DefaultLayout`, and the query functions read it internally when building the pg-meta SQL. `DefaultLayout` is shared by both the Next and TanStack router trees; hydrating from `_app.tsx` alone would leave TanStack-served pages permanently unscoped since `routes/__root.tsx` mounts its own flag provider. Cold loads cannot race the flag: the query functions await a readiness promise that resolves only after the sync hook has hydrated the accessor with a loaded flag store (immediately on self-hosted where flags are disabled; a 5s safety net armed lazily on the first `ready()` call - not at module import, which would let the timer expire before a project page ever mounts - bounds genuine ConfigCat outages). No component threading, no query-key changes (remaining tradeoff, documented in the module: a mid-session flag flip can serve stale-keyed caches until refetch, fine for a session-stable rollout flag). #47894's existing threading is left as-is and gets deleted together with the flag in the cleanup PR. Also fixes the previously-missing `scoped` pass-through in `getTableRowsCount`. - Flag-independent hardening: `useTableQuery` now sets `retryOnMount: false`, `refetchOnWindowFocus: false` and `staleTime: 5min`. Errored (timed-out) queries no longer refire on every grid cell remount, while stale successful metadata still revalidates on mount after `staleTime`. - `useTableApiAccessQuery` now passes `includedSchemas: [schemaName]`; the client-side filter stays as a safety net. - The rows-count query is `enabled`-gated on the permission check settling, so a transiently-false `canSQLAdminWrite` can no longer cache a read-only `-1` count for a writable user (read replicas short-circuit synchronously as before). **Regression guards (extending the #47894 infrastructure):** - Execution-based scoped-vs-legacy equivalence tests for all four queries: both variants run against the test database and are compared with raw `toEqual` - no normalization, ids included (types across 6 option combos, privileges incl. multi-grantee + PUBLIC, `tables.retrieve` for both identifier branches, row counts for every case where the two paths must agree). Two documented exceptions where only the LEGACY side is sorted, because a de-normalized diagnostic run proved legacy emits genuinely plan-dependent order there (an adversarial-FK fixture shows it is neither oid, name, nor creation order): the `types.list` outer row order (scoped adds `order by t.oid`; legacy has no ORDER BY) and the `tables.retrieve` relationships array (scoped orders by `constraint_name` + column-name tie-breakers - a composite two-column FK expands to 4 entries sharing one constraint_name). Everything else (privileges via `aclexplode` over the same relacl, columns by `ordinal_position`, primary keys by `indkey` order, enums by `enumsortorder`) is byte-identical between the two paths with no test-side help. The one intentional value divergence, never-analyzed tables above the size gate where legacy's exact count is the timeout bug itself, is asserted explicitly as a divergence. - Plan-guard budgets for every scoped query against the stress catalog (extended with 200 enums + 200 composite types). Residual seq scans are justified in-budget: `pg_constraint` max 2 (no index on `confrelid`), `pg_attrdef` max 1, `pg_authid` max 2 (scales with role count, not schema count). - Legacy templates carry a FROZEN do-not-edit marker (they must keep matching production behavior until the flag cleanup deletes them); the ordinary test suite runs against the legacy default, so behavioral drift there fails regular tests. ### Validation - pg-meta: typecheck clean; the affected suites (types, table-privileges, tables, rows-count, catalog-plan-guard) pass in full. - Cross-version: the scoped-vs-legacy equivalence and rows-count behavioral suites were validated on PostgreSQL 14, 15, and 17 (identical results on all three). Two version-marginal planner choices surfaced on 17 (`pg_type` / `pg_class` seq scan vs full-index bitmap for per-schema listings, both structurally unavoidable without an index leading on the namespace column) and are carried as justified plan-guard budget entries. A full 468-test suite run sequentially: 452 passed, 16 failures verified environmental (13 timeouts in an untouched file that passes 27/27 in isolation on the marathon-run cluster, 3 cluster-global role collisions from container reuse). - Studio: `pnpm --filter studio typecheck` clean; 39/39 tests across the touched data hooks; eslint clean on touched files. ### Rollout Same staged ConfigCat rollout as #47894 via `pgMetaScopedIntrospection` (user-email targeting first, then percentage, then 100%). The `useTableQuery` hardening and the API-access schema scoping ship unflagged (behavior-safe). Gate before percentage rollout: functionally verify the FK popover/selector UX under the new `staleTime`/`retryOnMount` settings (a just-edited FK target must not look stale anywhere Studio does not already refetch on save). Once fully rolled out, the legacy templates and flag get deleted together with #47894's in one cleanup PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
c7803b8b9b |
Chore/add sessions database connections (#48094)
## Context Initial work for Top for Postgres - adds a "Sessions" section under a new Observability segment "Database Connections" NOTE: All the copywriting and naming might change - not sure what's an ideal title for this We'll also be iteratively building on top of this UI, adding more actionable signals instead of just information Changes are featured flagged, off for public - This would essentially replace the "View ongoing queries" in the SQL Editor by providing a dedicated UI - It checks against `pg_stat_activity` as per the ongoing queries UI - We'll also subsequently deprecate the "Ongoing queries" UI in the SQL editor - Defaults into a "live mode" where the data is refreshed every 3 seconds via long-polling <img width="983" height="474" alt="image" src="https://github.com/user-attachments/assets/16402fe4-0b53-4f9e-9342-cdda26e3778a" /> - Supports filtering by state <img width="374" height="282" alt="image" src="https://github.com/user-attachments/assets/562f8fbe-2dc6-48e7-8ec0-de7ffb8348d1" /> - Users can also terminate queries through here <img width="247" height="164" alt="image" src="https://github.com/user-attachments/assets/23a639dc-8f96-473a-a823-605b0bab02ee" /> <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit # Release Notes * **New Features** * Added an Observability **Database Connections** page with a live **Sessions** activity table (state/roles filtering, blocked-by details, session duration, and per-session termination with confirmation). * Included a **Live/Pause** toggle to control automatic refresh (~3 seconds). * **Enhancements** * Improved Reports selection filtering: supports optional option quantities, better popover styling, sorted apply behavior, and shows quantity inline. * Query performance duration formatting now supports configurable decimal precision. * Tooltips can now render richer content (string or React node). <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
fa1e4c4bbf |
feat(studio): add ClickHouse replication destination (#46870)
Adds ClickHouse as a replication destination type in Studio.
- New ClickHouse option in the destination type selector, gated behind
the
`etlEnableClickHousePrivateAlpha` organization feature flag (off by
default).
- ClickHouse settings form: URL, user, password (optional), database,
and
- Client-side URL validation requires HTTPS and rejects URLs targeting
internal addresses (loopback, RFC 1918, link-local, CGNAT, IPv6
loopback/link-local/ULA, and IPv4-mapped/NAT64 forms). Server-side
validation remains authoritative.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
## New Features
- Added **ClickHouse** as a replication destination option (private
alpha), including support in destination selection/panel, replication
diagram rendering, and destination icons.
- Introduced a ClickHouse destination form with fields for URL, user,
optional password (masked toggle), database, and engine selection.
- Added ClickHouse destination config handling for create/update flows,
with normalization and engine support.
## Tests
- Expanded unit tests to cover ClickHouse validation and destination
config building/normalization, including HTTPS-only and blocking
localhost/internal targets.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
|
||
|
|
3c6ef31959 |
feat: add User Filter to the unified logs (#47879)
Offshoot from https://github.com/supabase/supabase/pull/47743. [Linear issue](https://linear.app/supabase/issue/FE-3939/add-user-logs-filter-to-the-logs-page) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added a `user` filter to Unified Logs with a user picker (email or ID). * Added “View user logs” actions from the Users table to jump to Unified Logs. * **Bug Fixes** * Updated Unified Logs searching so default log-type restrictions no longer block user-attributed results. * **UI Updates** * Unified Logs filter bar and reset behavior now include clearing the user filter. * Improved empty-state messaging when the selected user filter isn’t supported. * Refreshed highlighted styling in command list items. * **Tests** * Expanded coverage for user filter configuration and query edge cases. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: kemal.earth <606977+kemaldotearth@users.noreply.github.com> Co-authored-by: kemal <hello@kemal.earth> Co-authored-by: Joshen Lim <joshenlimek@gmail.com> |
||
|
|
58621818d0 |
feat(studio): switch TanStack skew protection to ?dpl= query params (#48008)
Switches the TanStack build's Vercel skew protection from the `__vdpl` session cookie to `?dpl=<deployment-id>` query params baked into asset URLs at build time. Assets stay pinned to the deployment that built them, while document navigations and API fetches always reach the latest deployment (with the cookie, a session stayed fully pinned — including reloads — until the tab closed). **Removed:** - `pinDeploymentForSession` (the `__vdpl` cookie) from `router.tsx`, plus the cookie clearing in the refresh toast and the `vite:preloadError` backstop - `credentials: 'omit'` on the deployment-commit check — its only purpose was escaping the cookie pin, and API fetches are now inherently unpinned **Added:** - `skewProtectionDpl` plugin + `experimental.renderBuiltUrl` in `vite.config.ts`, active only when `VERCEL_SKEW_PROTECTION_ENABLED=1`. Full coverage needs three mechanisms (Vite has no single hook for this — see [vitejs/vite#13834](https://github.com/vitejs/vite/discussions/13834#discussioncomment-7469745)): 1. `renderBuiltUrl` — CSS `url()`s, images, workers, and `__vite__mapDeps` preload lists 2. a `generateBundle` (`order: 'post'`) rewrite of chunk-to-chunk `import`/`from` specifiers, which Rolldown emits as bare relative paths that `renderBuiltUrl` never sees — with sourcemaps recombined per chunk (`magic-string` + `@jridgewell/remapping` devDeps) so Sentry columns stay exact 3. a post-`buildApp` patch of the prerendered `_shell.html` (script/preload tags + embedded router manifest come from TanStack, not Vite's asset pipeline); without it the entry graph double-downloads because preload and import URLs differ ## To test - Built with fake `VERCEL_SKEW_PROTECTION_ENABLED=1 VERCEL_DEPLOYMENT_ID=dpl_TESTPIN123abc`: every chunk import specifier (static + dynamic), `__vite__mapDeps` entry, CSS font URL, and `_shell.html` asset URL carries `?dpl=`; zero unpinned `/assets/` references remain - Sourcemap accuracy verified by tracing a minified position through the recombined map: resolves to the exact original file/line/column (`use-check-latest-deploy.tsx:62:8`) - Built without the env vars: output contains no `dpl=` anywhere (self-hosted/e2e builds unaffected) - `smoke:tanstack` passes on both builds; `tsc --noEmit` and eslint clean - On the preview: load the dashboard, check Network tab — chunk/CSS requests should carry `?dpl=` matching the deployment; hard reload should hit the latest deployment (no pin on document requests) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * Improved deployment consistency by pinning generated asset and module URLs to the current deployment (using `?dpl=`). * Simplified refresh and preload-error recovery to reduce reload-loop risk. * Kept API request behavior aligned with the updated deployment routing/pinning approach. * Preserved correct routing across deployment configurations. * **Developer Experience** * Added build-time tooling to rewrite pinned URLs for client assets while maintaining source map integrity. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com> |
||
|
|
0bcd2e196d |
fix: invalidate free project limit checks for all organizations when a project is deleted (#47569)
How to test: 1. Have multiple free orgs 2. Open the "create new project" page in those orgs (no need to create a project), notice the `/members/reached-free-project-limit'` API call 3. Delete any project in any of the orgs you have 4. Go to any of orgs and open the "create new project" page, the request should be sent again (it was purged from the cache) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved project deletion behavior so free project limit checks are refreshed across all organizations, reducing the chance of stale availability data. * Continued to refresh the deleted project’s details and, when applicable, the project list and organization details after deletion. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
591b621567 |
fix(studio): tighten time bounds on single-log inspection query (#47978)
## Summary - The unified log inspection point-lookup (`getUnifiedLogInspection` in `apps/studio/data/logs/unified-log-inspection-query.ts`, used by `ServiceFlowPanel` when a user selects a row to view its detail panel) previously reused the whole selected search date range for its `iso_timestamp_start`/`iso_timestamp_end` bounds, even though it looks up exactly one row by `id`. With a wide search range selected (days/weeks), this scans far more of the ClickHouse-backed `logs` table than necessary. - Since the selected row's own timestamp is already known client-side, the query now bounds itself to a ±1 hour window around that timestamp instead, falling back to the previous search-range behavior when no timestamp is available. - No SQL text changes for the time bound — the `iso_timestamp_start`/`iso_timestamp_end` params are the existing mechanism by which every other query in this file (and sibling logs queries) bounds time server-side, so this follows that same convention rather than adding a redundant inline `WHERE timestamp` clause. - Also added an explicit `AND source = '...'` filter to the OTEL point-lookup SQL. The logs table's primary key is `(project, source, timestamp)`, so filtering on `source` narrows the sorted range before the timestamp bound even applies — the service flow `type` already maps 1:1 to a `source` value, so no new data was needed at the call site. ## Test plan - [ ] Typecheck (couldn't run locally in this environment — no `node_modules` installed) - [ ] Manually verify in Studio: open Logs Explorer with a wide time range (e.g. 7 days), select a log row, confirm the detail/service-flow panel still loads the correct enriched data - [ ] Confirm behavior is unchanged when `logTimestampMs` is unavailable (falls back to search range) 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved unified log inspection accuracy by narrowing the inspection window to ±1 minute around the selected log event when a timestamp is available. * Updated service-flow and OTEL inspection lookups to use the selected log entry’s timestamp for tighter, more relevant results. * Preserved the prior broader time-range behavior when a timestamp isn’t available. * **Refactor** * Centralized log type → source mapping and generated the corresponding query filters from that shared mapping for consistency. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
a23f80dd40 |
feat(studio): identify unified logs analytics queries (#47963)
## What Unified Logs fires several `logs.all.otel` requests on load (row list, chart, sidebar facet counts, single-facet counts) plus inspection queries, all with no identifier — indistinguishable in the network tab. Adds a leading `-- unified logs: <what>` SQL comment to each query builder so each request is identifiable at a glance: - row list - severity chart (with bucket function) - sidebar facet counts - single-facet counts (with facet name) - inspect single log by id - edge function console logs for execution ## Notes `--` comments run to end of line; queries are sent multi-line, so the comment doesn't swallow the SQL. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Diagnostics** * Added descriptive labels to generated log queries, making SQL statements easier to identify in logs and diagnostics. * Added labels for unified log listings, facet counts, sidebar counts, severity charts, individual log inspections, and related console logs. * **Bug Fixes** * No changes to filtering, grouping, query results, or log retrieval behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> |
||
|
|
c9eb33abc7 | feat(pipelines): Add new cost estimation dialog (#47915) |