Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

perf(clickhouse): emit has(metadata_names) conjunct for events filters (#13369)

Valery Meleshkin02121f418195
diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.sh
index 240cb870a7..72a8fb9c8b 100644
--- a/packages/shared/clickhouse/scripts/dev-tables.sh
+++ b/packages/shared/clickhouse/scripts/dev-tables.sh
@@ -373,7 +373,8 @@ CREATE TABLE IF NOT EXISTS events_core
INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,
INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,
INDEX idx_provided_model_name provided_model_name TYPE bloom_filter(0.01) GRANULARITY 2,
- INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1
+ INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_metadata_names metadata_names TYPE bloom_filter(0.01) GRANULARITY 1
)
ENGINE = ReplacingMergeTree(event_ts, is_deleted)
PARTITION BY toYYYYMM(start_time)
diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts
index c33e811865..1f9df01df9 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts
@@ -310,26 +310,33 @@ export class StringObjectFilter implements Filter {
let query: string;
if (isEventsTable) {
- // For events tables, use array access: {field}_values[indexOf({field}_names, key)]
+ // ClickHouse's index analyzer cannot extract `has(names, k)` from
+ // `values[indexOf(names, k)] OP v` (cross-array arrayElement form), so a
+ // bloom_filter skipping index on `names` would never prune granules.
+ // Emitting an explicit `has(names, k) AND (...)` prefix conjunct makes
+ // the index actionable and corrects the absent-key matching semantic
+ // (Otherwise `arr[0] = ''` causes some predicates to match rows that never
+ // had the key — including `does not contain`).
const namesColumn = `${prefix}${this.field}_names`;
const valuesColumn = `${prefix}${this.field}_values`;
const valueAccessor = `${valuesColumn}[indexOf(${namesColumn}, {${varKeyName}: String})]`;
+ const hasKey = `has(${namesColumn}, {${varKeyName}: String})`;
switch (this.operator) {
case "=":
- query = `${valueAccessor} = {${varValueName}: String}`;
+ query = `${hasKey} AND (${valueAccessor} = {${varValueName}: String})`;
break;
case "contains":
- query = `position(${valueAccessor}, {${varValueName}: String}) > 0`;
+ query = `${hasKey} AND (position(${valueAccessor}, {${varValueName}: String}) > 0)`;
break;
case "does not contain":
- query = `position(${valueAccessor}, {${varValueName}: String}) = 0`;
+ query = `${hasKey} AND (position(${valueAccessor}, {${varValueName}: String}) = 0)`;
break;
case "starts with":
- query = `startsWith(${valueAccessor}, {${varValueName}: String})`;
+ query = `${hasKey} AND (startsWith(${valueAccessor}, {${varValueName}: String}))`;
break;
case "ends with":
- query = `endsWith(${valueAccessor}, {${varValueName}: String})`;
+ query = `${hasKey} AND (endsWith(${valueAccessor}, {${varValueName}: String}))`;
break;
default:
throw new Error(`Unsupported operator: ${this.operator}`);
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index 7e0b36c8a6..d164930091 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -1244,6 +1244,113 @@ describe("Clickhouse Events Repository Test", () => {
expect(resultBaz.length).toBe(0);
});
+
+ it("equality on absent key with empty value does NOT match", async () => {
+ // Today arr[indexOf(names, missing)] resolves to '' (Array(String)
+ // default), so `metadata.foo = ''` would match rows that never had
+ // the key. The has(metadata_names, ?) conjunct fixes this.
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const now = Date.now();
+ const filterTime = new Date(now - 5000);
+
+ await createEventsCh([
+ createEvent({
+ id: observationId,
+ span_id: observationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "no-foo-key-eq-empty",
+ metadata_names: ["bar"],
+ metadata_values: ["baz"],
+ start_time: now * 1000,
+ }),
+ ]);
+
+ const result = await getObservationsWithModelDataFromEventsTable({
+ projectId,
+ filter: [
+ {
+ type: "stringObject",
+ column: "metadata",
+ operator: "=",
+ key: "foo",
+ value: "",
+ },
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: ">=",
+ value: filterTime,
+ },
+ {
+ type: "string",
+ column: "traceId",
+ operator: "=",
+ value: traceId,
+ },
+ ],
+ limit: 1000,
+ offset: 0,
+ });
+
+ expect(result.length).toBe(0);
+ });
+
+ it("'does not contain' on absent key with non-empty needle does NOT match", async () => {
+ // Headline correctness fix: previously rows with the key absent
+ // matched `does not contain V` (because position('', V) = 0 is true
+ // for non-empty V). The has(metadata_names, ?) conjunct restricts
+ // the result to rows where the key actually exists.
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+ const now = Date.now();
+ const filterTime = new Date(now - 5000);
+
+ await createEventsCh([
+ createEvent({
+ id: observationId,
+ span_id: observationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "no-foo-key-dnc",
+ metadata_names: ["bar"],
+ metadata_values: ["baz"],
+ start_time: now * 1000,
+ }),
+ ]);
+
+ const result = await getObservationsWithModelDataFromEventsTable({
+ projectId,
+ filter: [
+ {
+ type: "stringObject",
+ column: "metadata",
+ operator: "does not contain",
+ key: "foo",
+ value: "anything",
+ },
+ {
+ type: "datetime",
+ column: "startTime",
+ operator: ">=",
+ value: filterTime,
+ },
+ {
+ type: "string",
+ column: "traceId",
+ operator: "=",
+ value: traceId,
+ },
+ ],
+ limit: 1000,
+ offset: 0,
+ });
+
+ expect(result.length).toBe(0);
+ });
});
});