BI-P029: the cited parity test did not exist, and it caught a real bug
CI (SIAX Cloud) / security (push) Successful in 14s
Security Scan (SIAX Cloud) / security (push) Successful in 15s
CI (SIAX Cloud) / integration (push) Successful in 46s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 20s
CI (SIAX Cloud) / security (pull_request) Successful in 25s
CI (SIAX Cloud) / quality (push) Successful in 54s
CI (SIAX Cloud) / integration (pull_request) Successful in 46s
CI (SIAX Cloud) / quality (pull_request) Successful in 48s

`semantic-provider.ts` cited tests/integration/semantic-parity.integration.test.ts
as the proof of the one BI-P029 DoD surface it claimed was closed, and
`providerReadiness().proven` asserted the comparison had been made against live
ClickHouse. The file did not exist. The citation was the evidence.

Writing it exposed a divergence that had been shipping:
`compileRequestToClickHouse` had no notion of a metric's OWN filters
(BI-P028 `MetricSpec.filters`). `ResolvedMetric` did not carry them and the
compiler never asked, so a metric defined as "invoiced revenue EXCLUDING
internal transfers" executed as "invoiced revenue". On the committed fixture
that is 11 249 instead of 1 250 for one country -- a plausible-looking number,
9x too large, under the correct canonical metric id. The registry, the
governance checks and the MetricFlow manifest all carried the filter; only the
thing that actually ran did not.

  * `ResolvedMetric` gains `definition_filters`, already resolved onto the
    physical dim_names key so the compilers stay dumb.
  * The ClickHouse compiler folds them into THAT metric's conditional
    aggregate, never into the shared WHERE -- two metrics in one request may
    exclude different rows, and a shared predicate would apply one metric's
    meaning to the other. `renderFilter`'s uniquifier becomes a string so
    request filter `0` and metric filter `0_0m` cannot collide in the
    parameter map.
  * `compileRequestToSemantic` carries them through, and
    `MetricFlowProvider.compile` emits them per metric.

The test runs both compile paths against one live ClickHouse: 0pt's `sumIf`
compiler, and a renderer driven only by the provider's structured query that
shares no SQL-generation code and emits `sum(if(...))` with inlined literals.
It asserts the two SQL strings differ, so parity is not vacuous. Backing the
fix out reproduces the pre-fix numbers, and the suite records them itself
rather than quoting a console: evidence/bi-p029/semantic-parity.json.

Three of BI-P029's four DoD surfaces stay OPEN and still say so: MetricFlow
itself is not executed (no Python runtime is provisioned here), Superset is not
implemented, and the AI Analyst path has not been compared.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
Claude Opus 5
2026-09-07 08:23:43 +02:00
parent cafe9cbe81
commit 468a87c00c
6 changed files with 652 additions and 13 deletions
+35 -10
View File
@@ -38,14 +38,19 @@ const GRAIN_FN: Record<TimeGrain, string> = {
/**
* Aggregation -> conditional-aggregate template. `count_distinct` uses
* `uniqExactIf` so a multi-metric request stays one scan instead of N.
*
* The argument is the WHOLE per-metric predicate, not just the metric-key
* comparison, because a metric definition can carry its own filters (BI-P028
* `MetricSpec.filters`) and those belong INSIDE this metric's `If` — one
* request may carry two metrics that exclude different rows.
*/
const AGG_IF: Record<string, (mParam: string) => string> = {
sum: (p) => `sumIf(value, metric = {${p}:String})`,
avg: (p) => `avgIf(value, metric = {${p}:String})`,
min: (p) => `minIf(value, metric = {${p}:String})`,
max: (p) => `maxIf(value, metric = {${p}:String})`,
count: (p) => `countIf(metric = {${p}:String})`,
count_distinct: (p) => `uniqExactIf(event_id, metric = {${p}:String})`,
const AGG_IF: Record<string, (predicate: string) => string> = {
sum: (p) => `sumIf(value, ${p})`,
avg: (p) => `avgIf(value, ${p})`,
min: (p) => `minIf(value, ${p})`,
max: (p) => `maxIf(value, ${p})`,
count: (p) => `countIf(${p})`,
count_distinct: (p) => `uniqExactIf(event_id, ${p})`,
};
export interface ClickHouseCompileOptions {
@@ -124,7 +129,19 @@ export function compileRequestToClickHouse(
if (!template) {
throw new SiaxError('INVALID_REQUEST', '0pt.analytics', `unsupported aggregation "${m.aggregation}"`);
}
selectParts.push(`${template(key)} AS ${alias}`);
// The metric's own definition filters (BI-P028) join the metric-key
// comparison inside THIS metric's `If`. Bound, never spliced, and scoped
// to this metric — putting them in the shared WHERE would apply one
// metric's meaning to every other metric in the same request.
const metricConditions = [`metric = {${key}:String}`];
(m.definition_filters ?? []).forEach((f, j) => {
assertSafeIdentifier(f.field_name, 'metric definition filter dimension');
const nameKey = `mf${i}_${j}`;
params[`param_${nameKey}`] = f.field_name;
const lhs = `dim_values[indexOf(dim_names, {${nameKey}:String})]`;
metricConditions.push(renderFilter(lhs, nameKey, f.operator, [...f.values], `${i}_${j}m`, params));
});
selectParts.push(`${template(metricConditions.join(' AND '))} AS ${alias}`);
params[`param_${key}`] = m.event_metric_key;
metricKeyParams.push(`{${key}:String}`);
metricAliases[alias] = m.name;
@@ -156,7 +173,9 @@ export function compileRequestToClickHouse(
const nameKey = `fn${i}`;
params[`param_${nameKey}`] = entry.dimension.field_name;
const lhs = `dim_values[indexOf(dim_names, {${nameKey}:String})]`;
conditions.push(renderFilter(lhs, nameKey, entry.filter.operator, entry.filter.values ?? [], i, params));
conditions.push(
renderFilter(lhs, nameKey, entry.filter.operator, entry.filter.values ?? [], String(i), params),
);
});
// ── order by: resolved back onto compiler-generated aliases only ──────
@@ -202,7 +221,13 @@ function renderFilter(
nameKey: string,
operator: FilterOperator,
values: string[],
index: number,
/**
* Uniquifies this filter's bound-value parameter names. A STRING, not a
* number, because request filters and per-metric definition filters share
* one parameter map: `0` and `0_0m` must not collide, and two collided
* bindings would silently make one filter win over the other.
*/
index: string,
params: Record<string, string>,
): string {
const bind = (v: string, suffix: string): string => {
+25 -1
View File
@@ -24,6 +24,14 @@ export interface SemanticMetricRef {
/** Canonical SIAX metric id — stable across semantic-engine replacement. */
metric_id: string;
name: string;
/**
* The metric DEFINITION's own filters, carried through so the semantic
* target computes the same number as the ClickHouse target. Dropping them
* on one side and not the other is how one canonical metric id comes to
* mean two different things — the divergence BI-P029's DoD is written to
* catch. Structured, like every other filter here: never predicate text.
*/
definition_filters?: readonly SemanticWhere[];
}
export interface SemanticGroupBy {
@@ -81,7 +89,23 @@ export function compileRequestToSemantic(resolved: ResolvedQuery): SemanticQuery
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 })),
metrics: resolved.metrics.map((m) => ({
metric_id: m.metric_id,
name: m.name,
...(m.definition_filters?.length
? {
definition_filters: m.definition_filters.map((f) => ({
// Already resolved onto the physical key; the dimension id is
// the same value here because the definition names a field, not
// a caller-supplied alias.
dimension_id: f.field_name,
name: f.field_name,
operator: f.operator,
values: [...f.values],
})),
}
: {}),
})),
groupBy,
where: resolved.filters.map((f) => ({
dimension_id: f.dimension.dimension_id,
+29
View File
@@ -351,6 +351,27 @@ function parseOrderBy(raw: unknown, index: number): AnalyticsOrderBy {
* What a metric NAME resolves to. Supplied from `MetricDefinition` rows
* (BI-P002/BI-P028); the compilers never invent one.
*/
/**
* A filter that belongs to the METRIC DEFINITION rather than to the request
* (BI-P028 `MetricSpec.filters`) — "net revenue excludes internal transfers"
* is part of what the metric MEANS, not something a caller asks for.
*
* It is carried in ALREADY-RESOLVED form: `field_name` is the physical key
* inside `dim_names`, mapped from the definition's dimension name by whoever
* builds the resolution. The compilers stay dumb — they bind and render, they
* never look a dimension up — and `assertSafeIdentifier` still applies.
*
* These filters are NOT optional decoration. A compile path that drops them
* answers a different question under the same canonical metric id, which is
* exactly the divergence BI-P029's DoD exists to catch; see
* tests/integration/semantic-parity.integration.test.ts.
*/
export interface ResolvedMetricFilter {
field_name: string;
operator: FilterOperator;
values: readonly string[];
}
export interface ResolvedMetric {
name: string;
metric_id: string;
@@ -360,6 +381,14 @@ export interface ResolvedMetric {
/** Dimension names this metric may legitimately be sliced by. */
allowed_dimensions: readonly string[];
unit?: string;
/**
* The metric definition's own filters. Applied PER METRIC — folded into that
* metric's conditional aggregate — never into the shared WHERE clause: a
* request may ask for two metrics whose definitions exclude different rows,
* and a shared predicate would silently apply one metric's meaning to the
* other.
*/
definition_filters?: readonly ResolvedMetricFilter[];
}
/** What a dimension NAME resolves to. Supplied from `DimensionDefinition` rows. */
+23 -2
View File
@@ -16,8 +16,11 @@
* happen first — `METRICFLOW_PINNED_VERSION` below records the intended pin
* and is explicitly marked unverified).
*
* So what IS proven, in tests/integration/semantic-parity.integration.test.ts,
* is the part that does not need MetricFlow: the SAME golden metric, taken
* So what IS proven, in tests/integration/semantic-parity.integration.test.ts
* — a path this header cited from the day it was written, while the file
* itself did not exist until BI-P029's gap review; the citation was the
* evidence, which is no evidence at all — is the part that does not need
* MetricFlow: the SAME golden metric, taken
* from the SAME registry version, executed against the SAME live ClickHouse
* data by TWO INDEPENDENT compilers — 0pt's metric compiler, and a renderer
* driven only by the engine-neutral `SemanticQuerySpec` — returns the same
@@ -169,10 +172,28 @@ export class MetricFlowProvider implements SiaxSemanticProvider {
}
}
const timeBucket = spec.groupBy.find((g) => g.grain);
// Per-metric definition filters (BI-P028 `MetricSpec.filters`), kept
// SEPARATE from the request's `where`. Folding them together would apply
// one metric's meaning to every metric in the query; omitting them would
// make this provider compute a different number from the ClickHouse
// target for the same canonical metric id.
const metric_filters: Record<
string,
Array<{ dimension: string; operator: string; values: string[] }>
> = {};
for (const m of spec.metrics) {
if (!m.definition_filters?.length) continue;
metric_filters[m.metric_id] = m.definition_filters.map((f) => ({
dimension: f.name,
operator: f.operator,
values: [...f.values],
}));
}
return {
provider: this.provider,
query: {
metrics: spec.metrics.map((m) => m.metric_id),
...(Object.keys(metric_filters).length ? { metric_filters } : {}),
group_by: spec.groupBy.filter((g) => !g.grain).map((g) => g.name),
...(timeBucket ? { time_granularity: timeBucket.grain } : {}),
// STRUCTURED, not a `--where` SQL string. MetricFlow accepts predicate