🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore(query-ast): add tier 5-7 catalog shapes (#16846)
Niklas Semmler5014380b4b16
diff --git a/packages/shared/src/server/query-ast/kysely/catalog.golden.test.ts b/packages/shared/src/server/query-ast/kysely/catalog.golden.test.tsindex cf83074d08..ecb3dfb0d3 100644--- a/packages/shared/src/server/query-ast/kysely/catalog.golden.test.ts+++ b/packages/shared/src/server/query-ast/kysely/catalog.golden.test.ts@@ -98,3 +98,66 @@ describeWithClickhouseLocal("catalog JOIN execution", () => {);});});++// Full in-memory schema for the tier 5-7 shapes. Column sets mirror+// `schema.ts` so the analyzer sees the same types the compiler assumes.+const CATALOG_MEMORY_DDL = `+ CREATE TABLE events_core (+ environment String,+ project_id String,+ start_time DateTime64(3),+ span_id String,+ trace_id String,+ event_ts DateTime64(3),+ type String,+ total_cost Float64,+ metadata_names Array(String),+ metadata_values Array(String)+ ) ENGINE = Memory;+ CREATE TABLE observations (+ environment String,+ project_id String,+ start_time DateTime64(3),+ trace_id String,+ cost_details Map(String, Float64),+ usage_details Map(String, Float64)+ ) ENGINE = Memory;+ CREATE TABLE traces (+ environment String,+ project_id String,+ timestamp DateTime64(3),+ id String+ ) ENGINE = Memory;+`;++// Syntactic parity (`compile(AST) ≡ referenceSql` under `clickhouse format`)+// proves the text matches; it does not prove the text is *valid, analyzable*+// ClickHouse. Executing each new shape against empty Memory tables forces the+// analyzer to resolve every column, alias, and function — catching an+// alias-in-GROUP-BY that doesn't resolve, a correlated reference that doesn't+// bind, or a map function applied to the wrong type — none of which `format`+// (a parser) can see.+const EXECUTABLE_TIER_5_7 = [+ "correlated_latest_per_trace",+ "metadata_group_by",+ "map_keys_has_filter",+ "variant_events_unbounded",+ "variant_events_time_bounded",+ "variant_legacy_union",+];++describeWithClickhouseLocal("catalog tier 5-7 execution", () => {+ for (const id of EXECUTABLE_TIER_5_7) {+ it(`${id} compiles to valid analyzable ClickHouse`, () => {+ const entry = CATALOG.find((e) => e.id === id);+ expect(entry).toBeDefined();+ if (!entry) return;++ const compiled = compileClickhouseQuery(entry.build(), {+ projectId: CATALOG_PROJECT_ID,+ });+ const executable = substituteNamedParams(compiled.sql, compiled.params);+ executeClickhouseLocal(`${CATALOG_MEMORY_DDL}\n${executable}`);+ });+ }+});diff --git a/packages/shared/src/server/query-ast/kysely/catalog.ts b/packages/shared/src/server/query-ast/kysely/catalog.tsindex f9c9ad5ebd..95df98fa28 100644--- a/packages/shared/src/server/query-ast/kysely/catalog.ts+++ b/packages/shared/src/server/query-ast/kysely/catalog.ts@@ -1,8 +1,16 @@+import type { SqlBool } from "kysely";+import type { ClickhouseCompilable } from "./compile";import { getClickhouseKysely } from "./dialect";-import { arrayJoin, limitBy, mapKeys, mapValues } from "./extensions";+import {+ arrayJoin,+ limitBy,+ mapKeys,+ mapValues,+ metadataValue,+} from "./extensions";-type CatalogTier = 0 | 1 | 2 | 3 | 4;+type CatalogTier = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;export type CatalogEntry = {id: string;@@ -19,6 +27,33 @@ function db() {return getClickhouseKysely();}+/**+ * One "distinct environments" template that emits structurally different SQL+ * per write mode, plus an optional time bound applied through `$if`. This is+ * the same branch shape `environments.ts` carries in production (events_core+ * vs. the legacy traces∪observations UNION, and the `fromTimestamp` guard).+ * The variant entries below prove each branch of this one builder round-trips.+ */+function environmentsVariant(spec: {+ writeMode: "events" | "legacy";+ fromTimestamp?: Date;+}): ClickhouseCompilable {+ if (spec.writeMode === "events") {+ return db()+ .selectFrom("events_core")+ .select("environment")+ .distinct()+ .$if(spec.fromTimestamp !== undefined, (qb) =>+ qb.where("start_time", ">=", spec.fromTimestamp!),+ );+ }+ return db()+ .selectFrom("traces")+ .select("environment")+ .distinct()+ .unionAll(db().selectFrom("observations").select("environment").distinct());+}+/*** Catalog of reference query shapes, one entry per complexity tier.* Reference SQL is the intended ClickHouse shape, not a dump of Kysely's@@ -212,6 +247,120 @@ export const CATALOG: CatalogEntry[] = [.as("rk"),]),},+ {+ // Correlated scalar subquery: the inner SELECT references the outer row+ // (`inner.trace_id = e.trace_id`) to keep only the latest event per trace.+ // Proves (a) the outer-row reference survives compilation as a real+ // ReferenceNode and (b) tenancy injection recurses into the subquery — its+ // own `inner.project_id` predicate is injected independently of the outer.+ id: "correlated_latest_per_trace",+ tier: 5,+ referenceSql: `+ SELECT e.span_id+ FROM events_core AS e+ WHERE (e.project_id = {p1:String}) AND (e.event_ts = (+ SELECT max(inner.event_ts) AS m+ FROM events_core AS inner+ WHERE (inner.project_id = {p1:String}) AND (inner.trace_id = e.trace_id)+ ))+ `,+ build: () =>+ db()+ .selectFrom("events_core as e")+ .select("e.span_id")+ .where((eb) =>+ eb(+ "e.event_ts",+ "=",+ eb+ .selectFrom("events_core as inner")+ .select((ieb) => ieb.fn.max("inner.event_ts").as("m"))+ .whereRef("inner.trace_id", "=", "e.trace_id"),+ ),+ ),+ },+ {+ // Metadata-map access in projection and GROUP BY. `metadata[key]` lowers to+ // the `metadata_values[indexOf(metadata_names, {key})]` array-pair subscript+ // (ArrayIndexNode), aliased and then grouped by that alias.+ id: "metadata_group_by",+ tier: 6,+ referenceSql: `+ SELECT e.metadata_values[indexOf(e.metadata_names, {p1:String})] AS model, count(*) AS n+ FROM events_core AS e+ WHERE e.project_id = {p2:String}+ GROUP BY model+ `,+ build: () =>+ db()+ .selectFrom("events_core as e")+ .select((eb) => [+ metadataValue("e", "model").as("model"),+ eb.fn.countAll().as("n"),+ ])+ .groupBy("model"),+ },+ {+ // mapKeys/mapValues filtering in a WHERE position over a real Map column.+ // `has(mapKeys(cost_details), {key})` keeps rows whose cost map carries a+ // given key. The predicate is a bound function call, not raw SQL.+ id: "map_keys_has_filter",+ tier: 6,+ referenceSql: `+ SELECT environment+ FROM observations+ WHERE (project_id = {p1:String}) AND has(mapKeys(cost_details), {p2:String})+ `,+ build: () =>+ db()+ .selectFrom("observations")+ .select("environment")+ .where((eb) =>+ eb+ .fn("has", [mapKeys("cost_details"), eb.val("input")])+ .$castTo<SqlBool>(),+ ),+ },+ {+ // Variant template — write mode `events`, no time bound. Same builder as the+ // two entries below; the `$if` time-bound branch is inactive here.+ id: "variant_events_unbounded",+ tier: 7,+ referenceSql: `+ SELECT DISTINCT environment+ FROM events_core+ WHERE project_id = {p1:String}+ `,+ build: () => environmentsVariant({ writeMode: "events" }),+ },+ {+ // Variant template — write mode `events`, `$if` time bound active.+ id: "variant_events_time_bounded",+ tier: 7,+ referenceSql: `+ SELECT DISTINCT environment+ FROM events_core+ WHERE (project_id = {p1:String}) AND (start_time >= {p2:DateTime64(3)})+ `,+ build: () =>+ environmentsVariant({ writeMode: "events", fromTimestamp: FROM_TS }),+ },+ {+ // Variant template — write mode `legacy`, structurally a UNION ALL rather+ // than a single-table read. Proves the same template's other branch.+ id: "variant_legacy_union",+ tier: 7,+ referenceSql: `+ SELECT DISTINCT environment+ FROM traces+ WHERE project_id = {p1:String}+ UNION ALL+ SELECT DISTINCT environment+ FROM observations+ WHERE project_id = {p1:String}+ `,+ build: () => environmentsVariant({ writeMode: "legacy" }),+ },];export const CATALOG_PROJECT_ID = PROJECT_ID;