/** * src/analytics/contract/compile-semantic.ts * =========================================== * BI-P016, compile target 2 of 2 — and the thing that makes BI-P016's DoD * ("same request can compile to ClickHouse/semantic engine without consumer * rewrite") a testable claim rather than a design intention. * * A `SemanticQuerySpec` is the engine-neutral form a semantic layer consumes. * It is deliberately shaped like MetricFlow's query interface (metrics / * group-by / where / order / limit / time-constraint) so BI-P029's * `MetricFlowProvider` can execute it without an adapter, but it names * nothing MetricFlow-specific: swapping MetricFlow for Cube or a hand-rolled * compiler changes this file's CONSUMER, not this file, and never the * product API. * * The `where` clauses here are STRUCTURED, not SQL strings. A semantic layer * that accepts SQL predicate text (MetricFlow's `--where` does) would put a * raw-SQL hole behind the closed DSL — so the spec carries operator+values * and the provider renders them itself under its own escaping rules. */ import type { FilterOperator, ResolvedQuery, TimeGrain } from './query-request'; export interface SemanticMetricRef { /** Canonical SIAX metric id — stable across semantic-engine replacement. */ metric_id: string; name: string; } export interface SemanticGroupBy { dimension_id: string; name: string; /** Set when this group-by is a time bucket rather than a categorical one. */ grain?: TimeGrain; } export interface SemanticWhere { dimension_id: string; name: string; operator: FilterOperator; values: string[]; } export interface SemanticOrderBy { ref: string; direction: 'asc' | 'desc'; } export interface SemanticTimeConstraint { /** Inclusive lower bound. */ start?: string; /** EXCLUSIVE upper bound — matched to the ClickHouse target exactly. */ end?: string; dimension?: string; } export interface SemanticQuerySpec { dataset_id: string; semantic_model_version?: number; metrics: SemanticMetricRef[]; groupBy: SemanticGroupBy[]; where: SemanticWhere[]; orderBy: SemanticOrderBy[]; limit: number; timeConstraint?: SemanticTimeConstraint; format: 'json' | 'arrow_ipc'; } export function compileRequestToSemantic(resolved: ResolvedQuery): SemanticQuerySpec { const groupBy: SemanticGroupBy[] = resolved.dimensions.map((d) => ({ dimension_id: d.dimension_id, name: d.name, })); const grain = resolved.request.timeRange?.grain; if (grain) { groupBy.push({ dimension_id: resolved.request.timeRange?.dimension ?? '__time', name: resolved.request.timeRange?.dimension ?? '__time', grain, }); } return { dataset_id: resolved.dataset_id, semantic_model_version: resolved.semantic_model_version, metrics: resolved.metrics.map((m) => ({ metric_id: m.metric_id, name: m.name })), groupBy, where: resolved.filters.map((f) => ({ dimension_id: f.dimension.dimension_id, name: f.dimension.name, operator: f.filter.operator, values: f.filter.values ?? [], })), orderBy: (resolved.request.orderBy ?? []).map((o) => ({ ref: o.ref, direction: o.direction })), limit: resolved.request.limit ?? 1000, timeConstraint: resolved.request.timeRange && (resolved.request.timeRange.from || resolved.request.timeRange.to) ? { start: resolved.request.timeRange.from, end: resolved.request.timeRange.to, dimension: resolved.request.timeRange.dimension, } : undefined, format: resolved.request.format ?? 'json', }; } /** * The comparable SHAPE of a compiled query, target-independent. * * BI-P016's DoD is about semantic equivalence, and the honest way to test * that is to project both targets onto the same tuple and demand equality — * not to eyeball two strings. `tests/analytics/query-request-contract.test.ts` * builds this from the ClickHouse SQL by PARSING the compiled artefact, so a * compiler that quietly drops a filter fails the comparison. */ export interface QueryShape { dataset_id: string; metrics: string[]; dimensions: string[]; filters: Array<{ dimension: string; operator: FilterOperator; values: string[] }>; order: string[]; limit: number; timeFrom?: string; timeTo?: string; grain?: TimeGrain; } export function shapeOfSemanticSpec(spec: SemanticQuerySpec): QueryShape { const timeBucket = spec.groupBy.find((g) => g.grain); return { dataset_id: spec.dataset_id, metrics: spec.metrics.map((m) => m.name).sort(), dimensions: spec.groupBy .filter((g) => !g.grain) .map((g) => g.name) .sort(), filters: spec.where .map((w) => ({ dimension: w.name, operator: w.operator, values: [...w.values] })) .sort((a, b) => (a.dimension + a.operator).localeCompare(b.dimension + b.operator)), order: spec.orderBy.map((o) => `${o.ref}:${o.direction}`), limit: spec.limit, timeFrom: spec.timeConstraint?.start, timeTo: spec.timeConstraint?.end, grain: timeBucket?.grain, }; }