Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
252 changes: 252 additions & 0 deletions docs/components/backend/analytics/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,24 @@
],
"type": "object"
},
"ImportResponse": {
"description": "Result of `POST /v1/queries/import`: how many rows were created versus\nskipped as a same-name collision.",
"properties": {
"imported": {
"minimum": 0,
"type": "integer"
},
"skipped": {
"minimum": 0,
"type": "integer"
}
},
"required": [
"imported",
"skipped"
],
"type": "object"
},
"MetricDefinitionListResponse": {
"description": "Response body for `GET /v1/metric-definitions`. Metrics are sorted by\n`metric_key` ascending so the payload is byte-stable for caching and\ndiff tooling.",
"properties": {
Expand Down Expand Up @@ -1177,6 +1195,28 @@
],
"type": "object"
},
"PortableSavedQuery": {
"description": "One record of the export/import document.\n\nPortable by construction: it carries only `name`, `description`, and `sql` —\nno id, tenant, or timestamps. The SQL is contract-relative and the tenant is\nsession-injected at run time, so the record is stand-independent and import\nre-homes it to the importing session's tenant.",
"properties": {
"description": {
"type": [
"string",
"null"
]
},
"name": {
"type": "string"
},
"sql": {
"type": "string"
}
},
"required": [
"name",
"sql"
],
"type": "object"
},
"Problem": {
"description": "RFC 9457 problem+json. `context` varies by error category.",
"properties": {
Expand Down Expand Up @@ -1279,6 +1319,21 @@
],
"type": "object"
},
"SavedQueryExport": {
"description": "Body of `GET /v1/queries/export` and `POST /v1/queries/import` — the portable\ndocument that carries a tenant's saved queries between stands.",
"properties": {
"queries": {
"items": {
"$ref": "#/components/schemas/PortableSavedQuery"
},
"type": "array"
}
},
"required": [
"queries"
],
"type": "object"
},
"SavedQueryListResponse": {
"description": "Response envelope for `GET /v1/queries` (`{ \"items\": [SavedQuerySummary] }`).",
"properties": {
Expand Down Expand Up @@ -1971,6 +2026,203 @@
"summary": "Create a saved query"
}
},
"/v1/queries/export": {
"get": {
"operationId": "analytics_api.queries.export",
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SavedQueryExport"
}
}
},
"description": "Portable saved-query document"
},
"400": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Bad Request"
},
"401": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Unauthorized"
},
"403": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Forbidden"
},
"404": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Not Found"
},
"409": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Conflict"
},
"429": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Too Many Requests"
},
"500": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Internal Server Error"
}
},
"security": [
{
"bearerAuth": []
}
],
"summary": "Export saved queries"
}
},
"/v1/queries/import": {
"post": {
"operationId": "analytics_api.queries.import",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/SavedQueryExport"
}
}
},
"description": "Portable saved-query document to bulk-create",
"required": true
},
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ImportResponse"
}
}
},
"description": "Imported and skipped counts"
},
"400": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Bad Request"
},
"401": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Unauthorized"
},
"403": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Forbidden"
},
"404": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Not Found"
},
"409": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Conflict"
},
"429": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Too Many Requests"
},
"500": {
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/Problem"
}
}
},
"description": "Internal Server Error"
}
},
"security": [
{
"bearerAuth": []
}
],
"summary": "Import saved queries"
}
},
Comment on lines +2127 to +2230

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Document the actual import failure responses.

POST /v1/queries/import returns 415 for text/plain and 422 for off-schema JSON. This contract declares 400 but omits both actual responses. Clients generated from this OpenAPI document cannot rely on the documented error contract.

Add the 415 and 422 responses, or map extractor failures to the documented status code.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/components/backend/analytics/openapi.json` around lines 2122 - 2225, Add
415 Unsupported Media Type and 422 Unprocessable Entity responses to the POST
operation identified by operationId analytics_api.queries.import, using the
existing application/problem+json Problem schema pattern. Preserve the current
400 response and accurately document the actual text/plain and off-schema JSON
failure statuses.

"/v1/queries/{id}": {
"delete": {
"operationId": "analytics_api.queries.delete",
Expand Down
11 changes: 10 additions & 1 deletion docs/domain/presentation-layer/specs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ Requirements that significantly influence architecture decisions.
| `cpt-presentation-fr-namespace` | New empty `presentation` database for new gold, saved-query results, and scratch; legacy gold left read-only in `insight` |
| `cpt-presentation-fr-saved-query-crud` | The saved query (`presentation.queries` logically; the `saved_queries` table physically) is a SeaORM entity in the analytics **service database (MariaDB)**, like metric definitions; CRUD mutates that metadata, not ClickHouse. Only `/run` reaches ClickHouse — it reuses the existing read path and executes the stored SQL as `presentation_ro`, so no write grant on the contract is ever needed. Shipped (#1965) |
| `cpt-presentation-fr-query-params` | Named parameters, `tenant` always injected from context (not client SQL), `period` supported |
| `cpt-presentation-fr-saved-query-export-import` | Two thin endpoints over the saved-query CRUD: `GET /v1/queries/export` dumps the tenant's queries as portable JSON (`name`/`description`/`sql` only), `POST /v1/queries/import` bulk-creates from that JSON, re-gating each SQL and re-homing it to the importing session's tenant with a fresh id; same-name collisions are skipped. Promotes tier-3 experiment queries dev to prod alongside the FE (#2259) |
| `cpt-presentation-fr-tenant-filter` | Literal leading `tenant_id = <ctx.tenant>` injected in one place — the compiler's shared `WHERE` (and the peer-cohort CTE reads) — replacing the no-op. `tenant_id` is the column the gold observation and cohort contract exposes (silver's `insight_tenant_id`, aliased to `tenant_id` in gold); filtering on it sidesteps the #1596 name drift, which affects other tables, not this read surface. Shipped for the structured `metric_results` read path (#1967). The legacy per-metric `query_ref` path (`execute_metric_query`) remains unscoped and is explicitly outside this guarantee until protected — see the component boundaries below. |
| `cpt-presentation-fr-contract-surface-doc` | Contract surface documented as the read boundary in [CONTRACT-SURFACE.md](./CONTRACT-SURFACE.md): the `class_*`/`fct_*`/`mtr_*`/`dim_*` silver families and `person.*`/`identity.*` objects, with the additive-only rules and the granted `insight` legacy gold. Shipped (#1968) |
| `cpt-presentation-fr-contract-version-stamp` | Engineering stamps `silver.contract_version` (single-row constant view, ledgerless CH migration); analytics pins `PINNED_CONTRACT_VERSION` and verifies the stamp in a periodic post-boot sweep, logging a mismatch or missing stamp without gating boot. Shipped (#1969) |
Expand Down Expand Up @@ -281,12 +282,16 @@ Plain CRUD over stored queries so a new analytics slice needs no engineering cha
- Validate SQL via the query gate (`validate_single_select`) on create, update, **and** run — the run-side re-validation keeps a stored SQL from reaching ClickHouse as anything but a single read.
- Run: execute the stored single-SELECT read-only as `presentation_ro` and return untyped JSON rows (`JSONEachRow`, same shape as the existing metric query path).
- Bind named parameters on run (#1966): `{tenant}` is always bound from the session `SecurityContext` (never client-settable); `{period}` is bound when supplied on the run request body. Values are passed as ClickHouse server-side parameters (`Query::param` → `param_<name>`), so a value can never change query structure; the gate already tolerates `{name:Type}` placeholders. A query that references a parameter left unbound (e.g. `{period}` with no period supplied) fails as a 400, not a 5xx.
- Export/import (#2259): `GET /v1/queries/export` reuses the tenant-scoped list read and returns each row as `{ name, description, sql }` — no id, tenant, or timestamps, so the document is stand-independent. `POST /v1/queries/import` bulk-creates from that document, re-validating each `sql` through the same gate as create and binding `ctx.subject_tenant_id()` with a fresh `Uuid::now_v7()`; the document carries no id or tenant to re-home. A row whose `name` already exists for the tenant is skipped (not overwritten), so a re-import is idempotent; the response reports the imported and skipped counts.

##### Responsibility boundaries

- Does NOT carry metric metadata, thresholds, or passports — those are Phase B.
- Does NOT bypass the gate.
- Does NOT bypass the gate — import re-gates every SQL exactly as create does.
- Does NOT string-interpolate parameter values — binding is server-side only.
- Does NOT trust any id or tenant on an imported document — both are dropped and re-homed to the importing session's tenant, so an import can never write cross-tenant or resurrect a stale id.
- Does NOT overwrite on import — a same-name collision is skipped, never clobbered; changing an existing query stays an explicit update.
- Does NOT seed curated/product queries — auto-seeding sanctioned definitions to every stand is definitions-as-data (semantic epic #2213), not this bespoke export/import.
- Does NOT yet inject the tenant-row filter (#1967) — the run path binds the `{tenant}` *value* but does not yet add an `insight_tenant_id = {tenant}` predicate to queries that omit it; that cross-cutting concern lands in its own sub-issue.

##### Related components (by ID)
Expand Down Expand Up @@ -476,9 +481,13 @@ Entity `presentation.queries`: `{ id, insight_tenant_id, name, description, sql,
| `PUT` | `/v1/queries/{id}` | Update (re-validates SQL) | unstable |
| `DELETE` | `/v1/queries/{id}` | Delete | unstable |
| `POST` | `/v1/queries/{id}/run` | Execute read-only as `presentation_ro`, return rows; optional body `{ "period": "<value>" }` binds `{period}`; `{tenant}` always bound from context (tenant-row *filter* deferred to #1967 — the run path binds the tenant value but adds no `insight_tenant_id` predicate yet) | unstable |
| `GET` | `/v1/queries/export` | Dump the tenant's saved queries as portable JSON `{ "queries": [{ name, description, sql }] }` — no id, tenant, or timestamps | unstable |
| `POST` | `/v1/queries/import` | Bulk-create from `{ "queries": [{ name, description, sql }] }`; each `sql` re-gated, re-homed to the session tenant with a fresh id; same-name rows skipped. Returns `{ imported, skipped }` counts | unstable |

`run` executes as `presentation_ro` and returns untyped JSON rows, the same shape as the existing metric query path. The request body is optional; named parameters (`tenant`/`period`, #1966) are bound as ClickHouse server-side parameters. No metric metadata, thresholds, or passports in Phase A.

`export`/`import` (#2259) move saved queries across stands so a promoted tier-3 experiment arrives with the queries it needs. The document is `{ name, description, sql }` only — portable by construction because the SQL is contract-relative and the tenant is session-injected at run time, never stored. `import` reuses the create path: it re-validates each `sql` through the single-SELECT gate, drops any source id/tenant, generates a fresh id, and binds the importing session's tenant, so an import can never write cross-tenant. A row whose `name` already exists for the tenant is skipped (not overwritten), making re-import idempotent; the response reports imported vs skipped counts.

### 3.4 Internal Dependencies

| Dependency Module | Interface Used | Purpose |
Expand Down
13 changes: 12 additions & 1 deletion docs/domain/presentation-layer/specs/PRD.md
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,16 @@ The system **MUST** support named query parameters, always injecting `tenant` fr

**Actors**: `cpt-presentation-actor-analyst`, `cpt-presentation-actor-analytics-svc`

#### Saved-Query Export and Import

- [ ] `p2` - **ID**: `cpt-presentation-fr-saved-query-export-import`

The system **MUST** let an analyst export the calling tenant's saved queries as a portable JSON document (`[{ name, description, sql }]`) and import such a document to bulk-create saved queries. Import **MUST** re-validate every `sql` through the single-SELECT gate, **MUST** drop any source id or tenant and re-home each query to the importing session's tenant (fresh id, session tenant), and **MUST NOT** overwrite an existing query of the same name (name collisions are skipped, so re-import is idempotent). Export **MUST** carry no id, tenant, or timestamps, so the document is stand-independent.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

**Rationale**: A tier-3 experiment's saved queries are authored on a dev stand; the frontend promotes to production by PR, but the queries it depends on are otherwise stranded on the dev stand's database. Export/import lets the queries travel dev to prod alongside the frontend. Because SQL is contract-relative and the tenant is session-injected at run time, the document is portable with no rewriting.

**Actors**: `cpt-presentation-actor-analyst`, `cpt-presentation-actor-analytics-svc`

### 5.3 Tenant Isolation (p1)

#### Server-Injected Tenant Filter
Expand Down Expand Up @@ -348,7 +358,7 @@ Contract reads for tenant A **MUST NOT** return rows from tenant B, regardless o

**Stability**: unstable

**Description**: CRUD and read-only run over saved queries, tenant-scoped. The one new surface Phase A adds. Detailed endpoint contracts live in DESIGN. (CRUD + run shipped in #1965; named parameters shipped in #1966.)
**Description**: CRUD and read-only run over saved queries, tenant-scoped, plus tenant-wide export and import for promoting experiment queries across stands. The one new surface Phase A adds. Detailed endpoint contracts live in DESIGN. (CRUD + run shipped in #1965; named parameters shipped in #1966; export/import added for the tier-3 experiment loop.)

**Breaking Change Policy**: Unstable in Phase A; contract hardens in a later phase.

Expand Down Expand Up @@ -416,6 +426,7 @@ Contract reads for tenant A **MUST NOT** return rows from tenant B, regardless o
- [ ] No presentation-side operation can write, alter, or drop contract objects (adversarial SQL included).
- [ ] The single-SELECT gate rejects empty input, multiple statements, non-read (DDL/DML) statements, and unparseable input on write and run.
- [ ] An analyst can create, list, fetch, update, delete, and run a saved query with no engineering change.
- [ ] An analyst can export the tenant's saved queries as portable JSON and import that document into another stand, where each query is re-gated, re-homed to the importing tenant, and a same-name collision is skipped rather than overwritten.
- [ ] Every contract read carries a server-injected tenant predicate the client cannot widen.
- [ ] Cross-tenant reads return no rows.
- [ ] The `presentation` namespace exists and legacy gold remains read-only in `insight`.
Expand Down
Loading
Loading