## ClickHouse schema for widget queries

## Scoping

- `workspace_id` is on every table, and a row policy binds it to the caller's workspace. Do not filter on it.
- `project_id` on `traces`, `spans` and `authored_feedback_scores` is bound by the row policy to the saved query's project. If the saved query has no project, every project in the workspace is visible. Do not filter on it.
- Only the tables in this reference are readable.
- Every table here is `ReplicatedReplacingMergeTree`. Until parts merge, the same key can appear more than once. Use `FINAL` (`FROM t AS x FINAL`) or `argMax(col, last_updated_at)` to read one row per key. `uniqExact`/`max` counts need neither.
- No table has a name column for projects or datasets. Return the id under the key `project_id` or `dataset_id`, and the backend adds `project_name` / `dataset_name` to the row. Never reference `project_name` or `dataset_name` in SQL: they are not columns.

## Layout variants (traces, spans)

Types below are the classic layout. On a deployment cut over to the partitioned v2 layout (`traces_local_v2`, `spans_local_v2`), timestamps are `DateTime64(6)` and `end_time`, `duration` and `ttft` are non-Nullable, using sentinels: an unset `end_time` is the epoch and an unset `duration`/`ttft` is `NaN`. On v2, `spans.usage` is `Map(String, Int64)` and `spans.parent_span_id` is `FixedString(36)`, where an empty value still compares equal to `''`. Write queries that hold on both layouts:
- `avgIf(duration, NOT isNaN(duration))`
- unfinished: `end_time IS NULL OR toUnixTimestamp64Micro(end_time) = 0`
- finished: `end_time IS NOT NULL AND toUnixTimestamp64Micro(end_time) > 0`
- `sumIf(ttft, NOT isNaN(ttft))`, `countIf(NOT isNaN(duration))`: `avg`, `sum` and `count(x)` do not skip `NaN`; `quantile`, `min` and `max` do.
- Never compare `end_time` with an epoch constant such as `toDateTime64(0, 6)`. Inside a CTE or subquery the filter is pushed to the shards with the constant written as `'0'`, and the query fails with `Cannot parse DateTime`.

## traces
Sort key: `workspace_id, project_id, id`.

| name | type | meaning |
|---|---|---|
| id | FixedString(36) | trace id (UUIDv7) |
| project_id | FixedString(36) | project |
| name | String | trace name |
| start_time | DateTime64(9,'UTC') | start |
| end_time | Nullable(DateTime64(9,'UTC')) | end; missing = NULL or epoch |
| duration | Nullable(Float64) MATERIALIZED | end - start, ms; missing = NULL or NaN |
| ttft | Nullable(Float64) | time to first token, ms; missing = NULL or NaN |
| input, output | String | JSON strings, can be very large; do not select whole |
| input_slim, output_slim | String | reduced copies of input/output |
| truncated_input, truncated_output | String MATERIALIZED | first `truncation_threshold` (10001) chars |
| input_length, output_length, metadata_length | UInt64 MATERIALIZED | byte length of the payload |
| output_keys | Array(Tuple(key String, type String)) MATERIALIZED | top-level output keys and their JSON types |
| metadata | String | JSON string |
| tags | Array(String) | tags |
| error_info | String | JSON string, `''` when no error |
| thread_id | String | user-supplied thread id, `''` if none |
| source | Enum8('unknown','sdk','experiment','playground','optimization','evaluator') | origin. `sdk`/`unknown` (legacy) = user traffic. `evaluator` = Opik's own LLM-judge traces |
| environment | LowCardinality(String) | environment label, `''` if unset |
| visibility_mode | Enum8('unknown','default','hidden') | UI visibility |
| created_at | DateTime64(9,'UTC') | row created |
| last_updated_at | DateTime64(6,'UTC') | dedup version |
| created_by, last_updated_by | String | user |
| id_at | DateTime('UTC') MATERIALIZED | timestamp decoded from the UUIDv7 id |

## spans
Sort key: `workspace_id, project_id, trace_id, parent_span_id, id`.

| name | type | meaning |
|---|---|---|
| id | FixedString(36) | span id |
| trace_id | FixedString(36) | = `traces.id` (`traces` has no `trace_id`) |
| parent_span_id | String | parent span; `''` = root span |
| project_id | FixedString(36) | project |
| name | String | span name |
| type | Enum8('unknown','general','tool','llm','guardrail') | `llm` = model call |
| start_time | DateTime64(9,'UTC') | start |
| end_time | Nullable(DateTime64(9,'UTC')) | end; missing = NULL or epoch |
| duration | Nullable(Float64) MATERIALIZED | ms; missing = NULL or NaN |
| ttft | Nullable(Float64) | ms; missing = NULL or NaN |
| model | String | model name |
| provider | String | model provider |
| usage | Map(String, Int32) | token counts, e.g. `usage['prompt_tokens']`, `usage['completion_tokens']`, `usage['total_tokens']` |
| total_estimated_cost | Decimal(38,12) | estimated cost, USD; `toFloat64()` before `toString()` |
| total_estimated_cost_version | String | pricing version |
| input, output | String | JSON strings, can be very large; do not select whole |
| input_slim, output_slim, truncated_input, truncated_output | String | reduced copies, as on traces |
| input_length, output_length, metadata_length | UInt64 MATERIALIZED | payload lengths |
| metadata | String | JSON string |
| tags | Array(String) | tags |
| error_info | String | JSON string, `''` when no error |
| source | Enum8('unknown','sdk','experiment','playground','optimization','evaluator') | as on traces |
| environment | LowCardinality(String) | environment label |
| created_at | DateTime64(9,'UTC') | row created |
| last_updated_at | DateTime64(6,'UTC') | dedup version |
| created_by, last_updated_by | String | user |
| id_at | DateTime('UTC') MATERIALIZED | timestamp decoded from the UUIDv7 id |

## authored_feedback_scores
Scores written with an author (UI annotators, online scoring and similar). Sort key: `workspace_id, project_id, entity_type, entity_id, author, name, source_queue_id`.

| name | type | meaning |
|---|---|---|
| entity_id | FixedString(36) | scored entity: `traces.id`, `spans.id` or a thread id |
| entity_type | Enum8('unknown','span','trace','thread') | kind of entity |
| project_id | FixedString(36) | project |
| author | String | who produced the score; one row per (entity, name, author) |
| name | String | score name, e.g. `hallucination` |
| value | Decimal(18,9) | score value |
| category_name | String | category label for categorical scores |
| reason | String | free-text reason |
| source | Enum8('sdk','ui','online_scoring') | how it was written |
| source_queue_id | FixedString(36) | annotation queue that produced it; empty otherwise |
| created_at, last_updated_at | DateTime64(9,'UTC') | timestamps; `last_updated_at` = dedup version |
| created_by, last_updated_by | String | user |

## Join keys

- `spans.trace_id = traces.id`
- scores → entity: `entity_type = 'trace' AND entity_id = traces.id`. Same pattern for `span` → `spans.id`.

## Query rules

- Filter `source` on every read of `traces` and `spans`. A project also holds `experiment`, `playground`, `optimization` and `evaluator` rows; the last are Opik's own LLM-as-judge traces (`name = 'online_evaluation'`) and often far outnumber the user's. Unless the question is about one of those, add `source IN ('sdk', 'unknown')` to every reference to either table, including inside CTEs and on both sides of a join: one unfiltered reference inflates the result.
- Aggregate rather than scan: `count()`, `avg`, `sum`, `quantile(0.5|0.95|0.99)`, `topK`. Give a query that does not aggregate a `LIMIT`; 50 rows is usually plenty. Return slim or derived columns or lengths, not the `input`, `output` and `metadata` payloads.
- A subquery used as a value must not read a table. In the `SELECT` list, a comparison, a function argument or `WITH (SELECT ...) AS x` it is refused, because Opik cannot verify it ran under the row policy. Compute the value once in a CTE and join it in, or use a window function. Subqueries in `FROM` or `JOIN`, CTE bodies and subqueries under `IN` or `EXISTS` are fine.
  - GOOD: `WITH tot AS (SELECT count() AS n FROM spans WHERE source IN ('sdk','unknown')) SELECT toJSONString(map('model', model, 'share', toString(count() / any(tot.n)))) AS result FROM spans CROSS JOIN tot WHERE source IN ('sdk','unknown') GROUP BY model`
  - GOOD: `count() / sum(count()) OVER ()` for each group's share of the total
  - BAD: `count() / (SELECT count() FROM spans WHERE ...)`, `'total', toString((SELECT count() FROM sel))`
- Sum tokens with `sumMap(usage)['total_tokens']` or `sum(usage['total_tokens'])`.
- `authored_feedback_scores` holds one row per author for the same entity and name. Aggregate over authors, e.g. `avg(value)`, or pick one with `argMax(value, last_updated_at)`.

## ClickHouse dialect

This is not Postgres, MySQL or ANSI SQL. The most common failures:
- Time filters: constrain `start_time` with a relative or a full-precision expression.
  - GOOD: `start_time >= now() - INTERVAL 7 DAY`
  - GOOD: `start_time >= toDate('2026-06-05') AND start_time < toDate('2026-06-05') + 1` for a calendar day
  - GOOD: `parseDateTimeBestEffort('2026-06-05 00:00')` for an absolute string of unknown precision
  - BAD: `toDateTime('2026-06-05 00:00')`: a partial datetime is refused, it needs the full `HH:MM:SS`
- `FINAL` goes after the alias: `FROM spans AS s FINAL`, not `FROM spans FINAL s`.
- No inline `ORDER BY` in an aggregate. Order after collecting, or use `groupArraySorted(N)`.
  - GOOD: `arraySort(x -> x.2, groupArray((name, start_time))).1`
  - BAD: `groupArray(name ORDER BY start_time)`
- The window functions are `lagInFrame()` and `leadInFrame()`; `lag()` and `lead()` do not exist.
  - GOOD: `lagInFrame(value) OVER (PARTITION BY trace_id ORDER BY start_time)`
- `trace_id` is only on `spans`; `traces` is keyed by `id`. A CTE or subquery exposes only the columns its SELECT returns.
  - GOOD: `FROM spans AS s JOIN traces AS t ON s.trace_id = t.id WHERE s.source IN ('sdk','unknown') AND t.source IN ('sdk','unknown')`
  - BAD: `FROM spans AS s JOIN traces AS t ON s.trace_id = t.trace_id`

## Performance

- Bound `authored_feedback_scores` on `created_at` whenever you join it: an unbounded scan of it reads far more than a bounded one. Start the bound a few days before the earliest time the query reads, never with one computed by a subquery: with the window placeholders, e.g. `created_at >= subtractDays({{window_start}}, 7)`, from the previous window's start when the query reads it too; without them, a constant such as `created_at >= now() - INTERVAL 30 DAY` for a question about the last few weeks. With no time window to anchor it, filter `entity_id IN (SELECT ...)` on the traces you need instead: `entity_id` is in the table's sort key.
- Pre-aggregate `spans` before joining `traces`: group by `trace_id` in a CTE first, then join. Joining raw spans to traces exhausts the memory limit on a large project.
- Pair any `start_time` filter on `traces` with a `created_at` filter 7 to 10 days wider. `start_time` is not in the sort key and prunes nothing on its own.
