πͺ’ 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
fix: improve nullIf handling in v4 queries (#12472)
Valery Meleshkin017e628c6239
diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.tsindex 662eb19c63..a0ba4501a3 100644--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts@@ -22,6 +22,7 @@ export class StringFilter implements Filter {public value: string;public operator: (typeof filterOperators)["string"][number];public tablePrefix?: string;+ public emptyEqualsNull?: boolean;constructor(opts: {clickhouseTable: string;@@ -29,18 +30,38 @@ export class StringFilter implements Filter {operator: (typeof filterOperators)["string"][number];value: string;tablePrefix?: string;+ emptyEqualsNull?: boolean;}) {this.clickhouseTable = opts.clickhouseTable;this.field = opts.field;this.value = opts.value;this.operator = opts.operator;this.tablePrefix = opts.tablePrefix;+ this.emptyEqualsNull = opts.emptyEqualsNull;}apply(): ClickhouseFilter {const varName = `stringFilter${clickhouseCompliantRandomCharacters()}`;const fieldWithPrefix = `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}`;++ // '' β‘ NULL: when filtering with empty value, match both '' and NULL.+ // ClickHouse functions like startsWith/endsWith/position return NULL (not true)+ // for NULL inputs, so we need an explicit OR IS NULL guard.+ if (this.emptyEqualsNull && this.value === "") {+ if (+ this.operator === "=" ||+ this.operator === "contains" ||+ this.operator === "starts with" ||+ this.operator === "ends with"+ ) {+ return {+ query: `(${fieldWithPrefix} = '' OR ${fieldWithPrefix} IS NULL)`,+ params: {},+ };+ }+ }+let query: string;switch (this.operator) {case "=":@@ -62,6 +83,11 @@ export class StringFilter implements Filter {throw new Error(`Unsupported operator: ${this.operator}`);}+ // '' β‘ NULL: "does not contain" would match '' β guard against it+ if (this.emptyEqualsNull && this.operator === "does not contain") {+ query = `(${fieldWithPrefix} != '' AND ${query})`;+ }+return {query: query,params: { [varName]: this.value },@@ -141,6 +167,7 @@ export class StringOptionsFilter implements Filter {public values: string[];public operator: (typeof filterOperators.stringOptions)[number];public tablePrefix?: string;+ public emptyEqualsNull?: boolean;constructor(opts: {clickhouseTable: string;@@ -148,22 +175,40 @@ export class StringOptionsFilter implements Filter {operator: (typeof filterOperators.stringOptions)[number];values: string[];tablePrefix?: string;+ emptyEqualsNull?: boolean;}) {this.clickhouseTable = opts.clickhouseTable;this.field = opts.field;this.values = opts.values;this.operator = opts.operator;this.tablePrefix = opts.tablePrefix;+ this.emptyEqualsNull = opts.emptyEqualsNull;}apply(): ClickhouseFilter {const uid = clickhouseCompliantRandomCharacters();const varName = `stringOptionsFilter${uid}`;+ const fieldWithPrefix = `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}`;+ const hasEmpty = this.emptyEqualsNull && this.values.includes("");++ let query =+ this.operator === "any of"+ ? `${fieldWithPrefix} IN ({${varName}: Array(String)})`+ : `${fieldWithPrefix} NOT IN ({${varName}: Array(String)})`;++ if (hasEmpty && this.operator === "any of") {+ // '' β‘ NULL: also match NULL when '' is in the list+ query = `(${query} OR ${fieldWithPrefix} IS NULL)`;+ } else if (this.emptyEqualsNull && this.operator === "none of") {+ // '' β‘ NULL: exclude empty/null (which are equivalent)+ const guard = hasEmpty+ ? `${fieldWithPrefix} IS NOT NULL`+ : `${fieldWithPrefix} != ''`;+ query = `(${query} AND ${guard})`;+ }+return {- query:- this.operator === "any of"- ? `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} IN ({${varName}: Array(String)})`- : `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} NOT IN ({${varName}: Array(String)})`,+ query,params: { [varName]: this.values },};}@@ -374,22 +419,38 @@ export class NullFilter implements Filter {public field: string;public operator: (typeof filterOperators)["null"][number];public tablePrefix?: string;+ public emptyEqualsNull?: boolean;constructor(opts: {clickhouseTable: string;field: string;operator: (typeof filterOperators)["null"][number];tablePrefix?: string;+ emptyEqualsNull?: boolean;}) {this.clickhouseTable = opts.clickhouseTable;this.field = opts.field;this.operator = opts.operator;this.tablePrefix = opts.tablePrefix;+ this.emptyEqualsNull = opts.emptyEqualsNull;}apply(): ClickhouseFilter {+ const fieldWithPrefix = `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}`;++ // '' β‘ NULL: treat empty string and NULL as the same value+ if (this.emptyEqualsNull) {+ const isNull = this.operator === "is null";+ return {+ query: isNull+ ? `(${fieldWithPrefix} = '' OR ${fieldWithPrefix} IS NULL)`+ : `(${fieldWithPrefix} != '' AND ${fieldWithPrefix} IS NOT NULL)`,+ params: {},+ };+ }+return {- query: `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field} ${this.operator}`,+ query: `${fieldWithPrefix} ${this.operator}`,params: {},};}diff --git a/packages/shared/src/server/queries/clickhouse-sql/factory.ts b/packages/shared/src/server/queries/clickhouse-sql/factory.tsindex fcc919aa1e..85affe41f9 100644--- a/packages/shared/src/server/queries/clickhouse-sql/factory.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/factory.ts@@ -25,9 +25,6 @@ export class QueryBuilderError extends Error {}}-// Matches nullIf(expr, '') wrappers used in dimension SQL for display purposes.-const NULL_IF_EMPTY_RE = /^nullIf\((.+),\s*''\)$/;-// This function ensures that the user only selects valid columns from the clickhouse schema.// The filter property in this column needs to be zod verified.// User input for values (e.g. project_id = <value>) are sent to Clickhouse as parameters to prevent SQL injection@@ -51,6 +48,7 @@ export const createFilterFromFilterState = (operator: frontEndFilter.operator,value: frontEndFilter.value,tablePrefix: column.queryPrefix,+ emptyEqualsNull: column.emptyEqualsNull,});case "datetime":return new DateTimeFilter({@@ -67,6 +65,7 @@ export const createFilterFromFilterState = (operator: frontEndFilter.operator,values: frontEndFilter.value,tablePrefix: column.queryPrefix,+ emptyEqualsNull: column.emptyEqualsNull,});case "categoryOptions":return new CategoryOptionsFilter({@@ -121,37 +120,12 @@ export const createFilterFromFilterState = (tablePrefix: column.queryPrefix,});case "null":- // Events_* table uses empty string instead of NULL for parent_span_id- if (- frontEndFilter.column === "parentObservationId" &&- column.clickhouseTableName.startsWith("events")- ) {- const isNull = frontEndFilter.operator === "is null";- // When the dimension SQL wraps the column with nullIf(col, ''), the value- // is already NULL for empty strings β use a standard IS NULL / IS NOT NULL check.- // When there is no nullIf wrapper, the column stores '' directly β use = '' / != ''.- const hasNullIf = NULL_IF_EMPTY_RE.test(column.clickhouseSelect);- const fieldWithPrefix = column.queryPrefix- ? `${column.queryPrefix}.${column.clickhouseSelect}`- : column.clickhouseSelect;- const query = hasNullIf- ? `${fieldWithPrefix} IS ${isNull ? "" : "NOT "}NULL`- : `${fieldWithPrefix} ${isNull ? "=" : "!="} ''`;-- return {- clickhouseTable: column.clickhouseTableName,- field: column.clickhouseSelect,- operator: isNull ? ("=" as const) : ("!=" as const),- tablePrefix: column.queryPrefix,- apply: () => ({ query, params: {} }),- };- }-return new NullFilter({clickhouseTable: column.clickhouseTableName,field: column.clickhouseSelect,operator: frontEndFilter.operator,tablePrefix: column.queryPrefix,+ emptyEqualsNull: column.emptyEqualsNull,});default:// eslint-disable-next-line no-case-declarationsdiff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.tsindex e962908b13..c123373a4f 100644--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts@@ -232,6 +232,7 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [uiTableId: "parentObservationId",clickhouseTableName: "events_proto",clickhouseSelect: 'e."parent_span_id"',+ emptyEqualsNull: true,},{uiTableName: "Experiment Dataset ID",diff --git a/packages/shared/src/tableDefinitions/types.ts b/packages/shared/src/tableDefinitions/types.tsindex df221556c1..a48eeef951 100644--- a/packages/shared/src/tableDefinitions/types.ts+++ b/packages/shared/src/tableDefinitions/types.ts@@ -7,6 +7,7 @@ export type UiColumnMapping = Readonly<{clickhouseSelect: string;clickhouseTypeOverwrite?: string;queryPrefix?: string;+ emptyEqualsNull?: boolean;}>;export type SingleValueOption = {diff --git a/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.ts b/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.tsindex 1a6098ba2e..901fe02995 100644--- a/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.ts+++ b/web/src/__tests__/server/createFilterFromFilterState-nullIf.servertest.ts@@ -1,39 +1,31 @@import { createFilterFromFilterState } from "@langfuse/shared/src/server";/**- * Unit tests for the parentObservationId null-filter special case in- * createFilterFromFilterState (factory.ts).+ * Unit tests for the emptyEqualsNull flag on filter classes, passed through+ * createFilterFromFilterState via UiColumnMapping.** events_core stores parent_span_id as a non-nullable String β root events- * have ''. The view layer may wrap this with nullIf(col, '') so the UI sees- * NULL instead. The factory must detect the wrapper and emit IS NULL / IS NOT- * NULL (not = '' / != '') when nullIf is present.+ * have ''. When emptyEqualsNull is set, NullFilter treats '' and NULL as+ * equivalent.*/-describe("createFilterFromFilterState parentObservationId on events tables", () => {+describe("createFilterFromFilterState with emptyEqualsNull", () => {const baseMapping = {uiTableName: "parentObservationId",uiTableId: "parentObservationId",type: "string",};- // Column mapping that mirrors eventsObservationsView (nullIf wrapper present)- const withNullIf = {+ // Column mapping with emptyEqualsNull (used by v2 query engine for nullIf dimensions)+ const withEmptyEqualsNull = {...baseMapping,clickhouseTableName: "events_core",- clickhouseSelect: "nullIf(events_observations.parent_span_id, '')",+ clickhouseSelect: "events_observations.parent_span_id",queryPrefix: "",+ emptyEqualsNull: true,};- // Column mapping without nullIf (raw column, e.g. eventsTracesView)- const withoutNullIf = {- ...baseMapping,- clickhouseTableName: "events_core",- clickhouseSelect: "events_traces.parent_span_id",- queryPrefix: "",- };-- // Non-events table β should fall through to standard NullFilter- const nonEvents = {+ // Column mapping without emptyEqualsNull β standard NullFilter behavior+ const withoutFlag = {...baseMapping,clickhouseTableName: "observations",clickhouseSelect: "observations.parent_observation_id",@@ -43,44 +35,41 @@ describe("createFilterFromFilterState parentObservationId on events tables", ()it.each<{desc: string;operator: "is null" | "is not null";- mapping: typeof withNullIf;+ mapping: typeof withEmptyEqualsNull;expected: string;}>([{- desc: "nullIf + is null β IS NULL",+ desc: "emptyEqualsNull + is null β match '' and NULL",operator: "is null",- mapping: withNullIf,- expected: "nullIf(events_observations.parent_span_id, '') IS NULL",+ mapping: withEmptyEqualsNull,+ expected:+ "(events_observations.parent_span_id = '' OR events_observations.parent_span_id IS NULL)",},{- desc: "nullIf + is not null β IS NOT NULL",+ desc: "emptyEqualsNull + is not null β exclude '' and NULL",operator: "is not null",- mapping: withNullIf,- expected: "nullIf(events_observations.parent_span_id, '') IS NOT NULL",+ mapping: withEmptyEqualsNull,+ expected:+ "(events_observations.parent_span_id != '' AND events_observations.parent_span_id IS NOT NULL)",},{- desc: "raw column + is null β = ''",+ desc: "emptyEqualsNull + queryPrefix + is null",operator: "is null",- mapping: withoutNullIf,- expected: "events_traces.parent_span_id = ''",- },- {- desc: "raw column + is not null β != ''",- operator: "is not null",- mapping: withoutNullIf,- expected: "events_traces.parent_span_id != ''",+ mapping: { ...withEmptyEqualsNull, queryPrefix: "eo" },+ expected:+ "(eo.events_observations.parent_span_id = '' OR eo.events_observations.parent_span_id IS NULL)",},{- desc: "raw column + queryPrefix",+ desc: "no flag β standard NullFilter",operator: "is null",- mapping: { ...withoutNullIf, queryPrefix: "eo" },- expected: "eo.events_traces.parent_span_id = ''",+ mapping: withoutFlag,+ expected: "observations.parent_observation_id is null",},{- desc: "non-events table falls through to standard NullFilter",- operator: "is null",- mapping: nonEvents,- expected: "observations.parent_observation_id is null",+ desc: "no flag + is not null β standard NullFilter",+ operator: "is not null",+ mapping: withoutFlag,+ expected: "observations.parent_observation_id is not null",},])("$desc", ({ operator, mapping, expected }) => {const filter = {diff --git a/web/src/__tests__/server/nullIfEmptyFilter.servertest.ts b/web/src/__tests__/server/nullIfEmptyFilter.servertest.tsnew file mode 100644index 0000000000..454df34b20--- /dev/null+++ b/web/src/__tests__/server/nullIfEmptyFilter.servertest.ts@@ -0,0 +1,209 @@+import { NULL_IF_EMPTY_RE } from "@/src/features/query/server/nullIfEmptyFilter";+import {+ StringFilter,+ StringOptionsFilter,+ NullFilter,+} from "@langfuse/shared/src/server";++// βββ NULL_IF_EMPTY_RE βββββββββββββββββββββββββββββββββββββββββββββββββββββββ++describe("NULL_IF_EMPTY_RE", () => {+ it.each<{ input: string; match: string | null }>([+ {+ input: "nullIf(events_traces.user_id, '')",+ match: "events_traces.user_id",+ },+ { input: "nullIf(col, '')", match: "col" },+ {+ input:+ "COALESCE(nullIf(events_traces.trace_name, ''), nullIf(events_traces.name, ''))",+ match: null,+ },+ { input: "events_traces.user_id", match: null },+ ])("$input β $match", ({ input, match }) => {+ const m = NULL_IF_EMPTY_RE.exec(input);+ if (match === null) {+ expect(m).toBeNull();+ } else {+ expect(m).not.toBeNull();+ expect(m![1]).toBe(match);+ }+ });+});++// βββ Filter classes with emptyEqualsNull ββββββββββββββββββββββββββββββββββββ++const C = "t.user_id";++/** Replace random param names like `stringFilterAb3x` with `P` for stable assertions. */+const norm = (sql: string) =>+ sql.replace(/string(Filter|OptionsFilter)\w+/g, "P");++describe("StringFilter with emptyEqualsNull", () => {+ it.each<{+ desc: string;+ operator:+ | "="+ | "contains"+ | "does not contain"+ | "starts with"+ | "ends with";+ value: string;+ expectedQuery: string;+ paramValues: unknown[];+ }>([+ {+ desc: "= non-empty (unchanged)",+ operator: "=",+ value: "alice",+ expectedQuery: `${C} = {P: String}`,+ paramValues: ["alice"],+ },+ {+ desc: "= empty β match '' and NULL",+ operator: "=",+ value: "",+ expectedQuery: `(${C} = '' OR ${C} IS NULL)`,+ paramValues: [],+ },+ {+ desc: "contains (unchanged)",+ operator: "contains",+ value: "ali",+ expectedQuery: `position(${C}, {P: String}) > 0`,+ paramValues: ["ali"],+ },+ {+ desc: "does not contain β guard empty",+ operator: "does not contain",+ value: "ali",+ expectedQuery: `(${C} != '' AND position(${C}, {P: String}) = 0)`,+ paramValues: ["ali"],+ },+ {+ desc: "contains empty β match '' and NULL",+ operator: "contains",+ value: "",+ expectedQuery: `(${C} = '' OR ${C} IS NULL)`,+ paramValues: [],+ },+ {+ desc: "starts with (unchanged)",+ operator: "starts with",+ value: "ali",+ expectedQuery: `startsWith(${C}, {P: String})`,+ paramValues: ["ali"],+ },+ {+ desc: "starts with empty β match '' and NULL",+ operator: "starts with",+ value: "",+ expectedQuery: `(${C} = '' OR ${C} IS NULL)`,+ paramValues: [],+ },+ {+ desc: "ends with (unchanged)",+ operator: "ends with",+ value: "ice",+ expectedQuery: `endsWith(${C}, {P: String})`,+ paramValues: ["ice"],+ },+ {+ desc: "ends with empty β match '' and NULL",+ operator: "ends with",+ value: "",+ expectedQuery: `(${C} = '' OR ${C} IS NULL)`,+ paramValues: [],+ },+ ])("$desc", ({ operator, value, expectedQuery, paramValues }) => {+ const { query, params } = new StringFilter({+ clickhouseTable: "",+ field: C,+ operator,+ value,+ emptyEqualsNull: true,+ }).apply();++ expect(norm(query)).toBe(expectedQuery);+ expect(Object.values(params)).toEqual(paramValues);+ });+});++describe("StringOptionsFilter with emptyEqualsNull", () => {+ it.each<{+ desc: string;+ operator: "any of" | "none of";+ values: string[];+ expectedQuery: string;+ paramValues: unknown[];+ }>([+ {+ desc: "any of (no empty, unchanged)",+ operator: "any of",+ values: ["a", "b"],+ expectedQuery: `${C} IN ({P: Array(String)})`,+ paramValues: [["a", "b"]],+ },+ {+ desc: "any of (with empty) β OR IS NULL",+ operator: "any of",+ values: ["", "a"],+ expectedQuery: `(${C} IN ({P: Array(String)}) OR ${C} IS NULL)`,+ paramValues: [["", "a"]],+ },+ {+ desc: "none of (no empty) β AND != ''",+ operator: "none of",+ values: ["a"],+ expectedQuery: `(${C} NOT IN ({P: Array(String)}) AND ${C} != '')`,+ paramValues: [["a"]],+ },+ {+ desc: "none of (with empty) β AND IS NOT NULL",+ operator: "none of",+ values: ["", "a"],+ expectedQuery: `(${C} NOT IN ({P: Array(String)}) AND ${C} IS NOT NULL)`,+ paramValues: [["", "a"]],+ },+ ])("$desc", ({ operator, values, expectedQuery, paramValues }) => {+ const { query, params } = new StringOptionsFilter({+ clickhouseTable: "",+ field: C,+ operator,+ values,+ emptyEqualsNull: true,+ }).apply();++ expect(norm(query)).toBe(expectedQuery);+ expect(Object.values(params)).toEqual(paramValues);+ });+});++describe("NullFilter with emptyEqualsNull", () => {+ it.each<{+ desc: string;+ operator: "is null" | "is not null";+ expectedQuery: string;+ }>([+ {+ desc: "is null β match '' and NULL",+ operator: "is null",+ expectedQuery: `(${C} = '' OR ${C} IS NULL)`,+ },+ {+ desc: "is not null β exclude '' and NULL",+ operator: "is not null",+ expectedQuery: `(${C} != '' AND ${C} IS NOT NULL)`,+ },+ ])("$desc", ({ operator, expectedQuery }) => {+ const { query, params } = new NullFilter({+ clickhouseTable: "",+ field: C,+ operator,+ emptyEqualsNull: true,+ }).apply();++ expect(query).toBe(expectedQuery);+ expect(params).toEqual({});+ });+});diff --git a/web/src/features/query/server/nullIfEmptyFilter.ts b/web/src/features/query/server/nullIfEmptyFilter.tsnew file mode 100644index 0000000000..495cfb4a97--- /dev/null+++ b/web/src/features/query/server/nullIfEmptyFilter.ts@@ -0,0 +1,5 @@+/**+ * Matches `nullIf(expr, '')` wrappers used in dimension SQL for display purposes.+ * Capture group 1 is the raw column expression (e.g. `events_traces.user_id`).+ */+export const NULL_IF_EMPTY_RE = /^nullIf\((.+),\s*''\)$/;diff --git a/web/src/features/query/server/queryBuilder.ts b/web/src/features/query/server/queryBuilder.tsindex ac319743c2..6178eb7d90 100644--- a/web/src/features/query/server/queryBuilder.ts+++ b/web/src/features/query/server/queryBuilder.ts@@ -23,6 +23,7 @@ import {} from "@langfuse/shared/src/server";import { InvalidRequestError } from "@langfuse/shared";import { env } from "@/src/env.mjs";+import { NULL_IF_EMPTY_RE } from "./nullIfEmptyFilter";type AppliedDimensionType = {table: string;@@ -323,6 +324,7 @@ export class QueryBuilder {clickhouseSelect: string;queryPrefix: string;type: string;+ emptyEqualsNull?: boolean;}> = [];for (const filter of filters) {@@ -346,9 +348,18 @@ export class QueryBuilder {let queryPrefix: string = "";let clickhouseTableName: string = actualTableName;let type: string;+ let emptyEqualsNull: boolean | undefined;if (dimension) {- clickhouseSelect = dimension.sql;+ // Dimension with nullIf(col, ''): use raw column with emptyEqualsNull+ // flag for index-friendly filtering while preserving '' β‘ NULL semantic.+ const nullIfMatch = NULL_IF_EMPTY_RE.exec(dimension.sql);+ if (nullIfMatch) {+ clickhouseSelect = nullIfMatch[1];+ emptyEqualsNull = true;+ } else {+ clickhouseSelect = dimension.sql;+ }type = "string";if (dimension.relationTable) {clickhouseTableName = dimension.relationTable;@@ -390,6 +401,7 @@ export class QueryBuilder {clickhouseSelect,queryPrefix,type,+ emptyEqualsNull,});}