πͺ’ 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
feat: initial FTS implementation (#13782)
Valery Meleshkind498437724bb
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 2e977ed591..8290adcf69 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -24,6 +24,7 @@ env:# env context in jobs.<job_id>.name, so matrix jobs use matrix.node-version# for their display names.NODE_VERSION: 24+ CLICKHOUSE_CLIENT_VERSION: "25.12.9.61"# Disable CI cache restores for fork PRs.#@@ -417,9 +418,8 @@ jobs:- name: Download and extract ClickHouse client for dev-tables setupif: matrix.deploy-mode == ''run: |- CH_VERSION="24.9.3.128"ARCH="amd64"- wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CH_VERSION}_${ARCH}.deb" -O clickhouse-client.deb+ wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CLICKHOUSE_CLIENT_VERSION}_${ARCH}.deb" -O clickhouse-client.deb# The binary is usually located in ./usr/bin/clickhouse in the archivedpkg-deb -x clickhouse-client.deb ch_client_dir@@ -530,9 +530,8 @@ jobs:- name: Download and extract ClickHouse client for dev-tables setupif: matrix.deploy-mode == ''run: |- CH_VERSION="24.9.3.128"ARCH="amd64"- wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CH_VERSION}_${ARCH}.deb" -O clickhouse-client.deb+ wget "https://packages.clickhouse.com/deb/pool/main/c/clickhouse/clickhouse-common-static_${CLICKHOUSE_CLIENT_VERSION}_${ARCH}.deb" -O clickhouse-client.debdpkg-deb -x clickhouse-client.deb ch_client_dirsudo cp ch_client_dir/usr/bin/clickhouse /usr/local/bin/- name: Setup Dev Tablesdiff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex b9f2ecf720..65e1f937be 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -2,7 +2,7 @@ services:clickhouse:# Upgrade from 24.3 to check behaviour on new events table.# Unit tests still verify 24.3 behaviour using -azure and -redis-cluster configs.- image: docker.io/clickhouse/clickhouse-server:25.8+ image: docker.io/clickhouse/clickhouse-server:25.12user: "101:101"container_name: ${CLICKHOUSE_CONTAINER_NAME:-langfuse-clickhouse}environment:diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex 72a8fb9c8b..c51850c760 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -132,6 +132,8 @@ SETTINGS ttl_only_drop_parts = 1;-- Create new events table for development setups.-- We expect this to be fully immutable and eventually replace observations.-- Remove IF NOT EXISTS when moving this to prod migrations.+SET enable_full_text_index=1;+CREATE TABLE IF NOT EXISTS events_full(project_id String,@@ -237,6 +239,18 @@ CREATE TABLE IF NOT EXISTS events_fullINDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,INDEX idx_created_at created_at TYPE minmax GRANULARITY 1,INDEX idx_updated_at updated_at TYPE minmax GRANULARITY 1,+ INDEX idx_fts_input_low lower(input) TYPE text(+ tokenizer = splitByNonAlpha+ ),+ INDEX idx_fts_output_low lower(output) TYPE text(+ tokenizer = splitByNonAlpha+ ),+ INDEX idx_fts_metadata_values metadata_values TYPE text(+ tokenizer = splitByNonAlpha+ ),+ INDEX idx_fts_metadata_names metadata_names TYPE text(+ tokenizer = splitByNonAlpha+ ),-- Full Text Search Indexes (We should try different index sizes, e.g. 2048, 4096, or 8192)-- Add after backfill as they limit backfill throughput performance@@ -374,7 +388,13 @@ CREATE TABLE IF NOT EXISTS events_coreINDEX 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_metadata_names metadata_names TYPE bloom_filter(0.01) GRANULARITY 1+ INDEX idx_metadata_names metadata_names TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_fts_metadata_values metadata_values TYPE text(+ tokenizer = splitByNonAlpha+ ),+ INDEX idx_fts_metadata_names metadata_names TYPE text(+ tokenizer = splitByNonAlpha+ ))ENGINE = ReplacingMergeTree(event_ts, is_deleted)PARTITION BY toYYYYMM(start_time)diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.tsindex 638d749e72..1a97e24a6f 100644--- a/packages/shared/src/server/clickhouse/client.ts+++ b/packages/shared/src/server/clickhouse/client.ts@@ -13,6 +13,20 @@ export type PreferredClickhouseService =| "ReadOnly"| "EventsReadOnly";+type ServiceClickhouseSettings = {+ enable_full_text_index?: 1;+};++/**+ * Remove these once we remove corresponding variables+ */+const EVENTS_TABLE_READ_PATH_ENV_KEYS = [+ "LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS",+ "LANGFUSE_ENABLE_EVENTS_TABLE_UI",+ "LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS",+ "LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS",+] as const;+/*** ClickHouseClientManager provides a singleton pattern for managing ClickHouse clients.* It creates and reuses clients based on their configuration to avoid creating@@ -45,21 +59,45 @@ export class ClickHouseClientManager {private generateClientSettings(opts: NodeClickHouseClientConfigOptions,preferredClickhouseService: PreferredClickhouseService = "ReadWrite",- ): NodeClickHouseClientConfigOptions {+ ): {+ settings: NodeClickHouseClientConfigOptions;+ serviceClickhouseSettings: ServiceClickhouseSettings;+ } {+ const serviceClickhouseSettings = this.getServiceClickhouseSettings(+ preferredClickhouseService,+ );const keyParams = {url: this.getClickhouseUrl(preferredClickhouseService),username: env.CLICKHOUSE_USER,password: env.CLICKHOUSE_PASSWORD,database: env.CLICKHOUSE_DB,http_headers: opts?.http_headers ?? {},- settings: opts?.clickhouse_settings,+ settings: {+ ...serviceClickhouseSettings,+ ...opts?.clickhouse_settings,+ },...(opts.request_timeout? { request_timeout: opts.request_timeout }: {}),// Include any other relevant config options};- return keyParams;+ return { settings: keyParams, serviceClickhouseSettings };+ }++ private getServiceClickhouseSettings(+ preferredClickhouseService: PreferredClickhouseService,+ ): ServiceClickhouseSettings {+ return preferredClickhouseService === "EventsReadOnly" &&+ this.isEventsTableReadPathEnabled()+ ? { enable_full_text_index: 1 }+ : {};+ }++ private isEventsTableReadPathEnabled(): boolean {+ return EVENTS_TABLE_READ_PATH_ENV_KEYS.some(+ (key) => process.env[key] === "true",+ );}private generateClientSettingsKey(@@ -95,7 +133,7 @@ export class ClickHouseClientManager {opts: NodeClickHouseClientConfigOptions,preferredClickhouseService: PreferredClickhouseService = "ReadWrite",): ClickhouseClientType {- const settings = this.generateClientSettings(+ const { settings, serviceClickhouseSettings } = this.generateClientSettings(opts,preferredClickhouseService,);@@ -160,6 +198,7 @@ export class ClickHouseClientManager {? { query_plan_optimize_lazy_materialization: 0 }: {}),...cloudOptions,+ ...serviceClickhouseSettings,...opts.clickhouse_settings,async_insert: 1,wait_for_async_insert: 1, // if disabled, we won't get errors from clickhousediff --git a/packages/shared/src/server/clickhouse/schema.ts b/packages/shared/src/server/clickhouse/schema.tsindex 3dd2a34bc1..1998b1df5a 100644--- a/packages/shared/src/server/clickhouse/schema.ts+++ b/packages/shared/src/server/clickhouse/schema.ts@@ -9,6 +9,7 @@ export const ClickhouseTableNames = {// Actual events tables used for dashboard/metrics query joins.events_core: "events_core",+ events_full: "events_full",// Virtual tables for dashboards// TODO: Check if we can do this more elegantly@@ -19,3 +20,14 @@ export const ClickhouseTableNames = {} as const;export type ClickhouseTableName = keyof typeof ClickhouseTableNames;++// Identifiers that map to the physical events_core/events_full tables at query+// time. events_proto is the column-mapping placeholder; events_core and+// events_full are the physical tables.+export const EVENTS_TABLE_NAMES = [+ ClickhouseTableNames.events_proto,+ ClickhouseTableNames.events_core,+ ClickhouseTableNames.events_full,+] as const satisfies readonly ClickhouseTableName[];++export type EventsTableName = (typeof EVENTS_TABLE_NAMES)[number];diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.tsindex 1f9df01df9..e945da0d21 100644--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts@@ -1,5 +1,11 @@import { filterOperators } from "../../../interfaces/filters";import { clickhouseCompliantRandomCharacters } from "../../repositories";+import {+ ftsMetadataArrayHas,+ ftsTextTokenConjunct,+ isFtsEventsTable,+ isFtsTextTarget,+} from "./fts";export type ClickhouseOperator =| (typeof filterOperators)[keyof typeof filterOperators][number]@@ -88,6 +94,10 @@ export class StringFilter implements Filter {query = `(${fieldWithPrefix} != '' AND ${query})`;}+ if (isFtsTextTarget(this.clickhouseTable, this.field, this.operator)) {+ query = `(${query} AND ${ftsTextTokenConjunct(fieldWithPrefix, `{${varName}: String}`)})`;+ }+return {query: query,params: { [varName]: this.value },@@ -300,16 +310,10 @@ export class StringObjectFilter implements Filter {const varValueName = `stringObjectValueFilter${clickhouseCompliantRandomCharacters()}`;const prefix = this.tablePrefix ? this.tablePrefix + "." : "";- // Events tables use array columns (metadata_names/metadata_values)- // Observations/traces tables use Map column (metadata)- const isEventsTable = [- "events_proto",- "events_core",- "events_full",- ].includes(this.clickhouseTable);-+ // Events tables use array columns (metadata_names/metadata_values);+ // observations/traces tables use a Map column (metadata).let query: string;- if (isEventsTable) {+ if (isFtsEventsTable(this.clickhouseTable)) {// 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.@@ -321,22 +325,23 @@ export class StringObjectFilter implements Filter {const valuesColumn = `${prefix}${this.field}_values`;const valueAccessor = `${valuesColumn}[indexOf(${namesColumn}, {${varKeyName}: String})]`;const hasKey = `has(${namesColumn}, {${varKeyName}: String})`;+ const valueParam = `{${varValueName}: String}`;switch (this.operator) {case "=":- query = `${hasKey} AND (${valueAccessor} = {${varValueName}: String})`;+ query = `${hasKey} AND ${ftsMetadataArrayHas(valuesColumn, valueParam)} AND (${valueAccessor} = ${valueParam})`;break;case "contains":- query = `${hasKey} AND (position(${valueAccessor}, {${varValueName}: String}) > 0)`;+ query = `${hasKey} AND (position(${valueAccessor}, ${valueParam}) > 0)`;break;case "does not contain":- query = `${hasKey} AND (position(${valueAccessor}, {${varValueName}: String}) = 0)`;+ query = `${hasKey} AND (position(${valueAccessor}, ${valueParam}) = 0)`;break;case "starts with":- query = `${hasKey} AND (startsWith(${valueAccessor}, {${varValueName}: String}))`;+ query = `${hasKey} AND (startsWith(${valueAccessor}, ${valueParam}))`;break;case "ends with":- query = `${hasKey} AND (endsWith(${valueAccessor}, {${varValueName}: String}))`;+ query = `${hasKey} AND (endsWith(${valueAccessor}, ${valueParam}))`;break;default:throw new Error(`Unsupported operator: ${this.operator}`);diff --git a/packages/shared/src/server/queries/clickhouse-sql/fts.ts b/packages/shared/src/server/queries/clickhouse-sql/fts.tsnew file mode 100644index 0000000000..9c0e4ae622--- /dev/null+++ b/packages/shared/src/server/queries/clickhouse-sql/fts.ts@@ -0,0 +1,58 @@+import { filterOperators } from "../../../interfaces/filters";+import { EVENTS_TABLE_NAMES } from "../../clickhouse/schema";++type StringOperator = (typeof filterOperators)["string"][number];++export const FTS_TEXT_NORMALIZER = "lower";++export const FTS_EVENTS_TABLES: ReadonlySet<string> = new Set(+ EVENTS_TABLE_NAMES,+);++export const FTS_TEXT_FIELDS: ReadonlySet<string> = new Set([+ "input",+ "output",+]);++// StringFilter rewrites must preserve filter API semantics. Limit transparent+// text-index rewrites to equality because substring filters are expected to+// match inside larger tokens.+export const FTS_TEXT_OPERATORS: ReadonlySet<StringOperator> =+ new Set<StringOperator>(["="]);++// Column mappings may carry a table prefix (e.g. "e.input"); strip to the bare+// field name before set lookup.+const bareField = (field: string): string => {+ const dot = field.lastIndexOf(".");+ if (dot === -1) return field;+ const tail = field.slice(dot + 1);+ return tail.replace(/^"(.*)"$/, "$1");+};++export const isFtsEventsTable = (+ clickhouseTable: string | undefined,+): boolean =>+ clickhouseTable !== undefined && FTS_EVENTS_TABLES.has(clickhouseTable);++export const isFtsTextTarget = (+ clickhouseTable: string,+ field: string,+ operator: StringOperator,+): boolean =>+ isFtsEventsTable(clickhouseTable) &&+ FTS_TEXT_FIELDS.has(bareField(field)) &&+ FTS_TEXT_OPERATORS.has(operator);++const normalizeFtsTextExpr = (expr: string): string =>+ `${FTS_TEXT_NORMALIZER}(${expr})`;++export const ftsTextTokenConjunct = (+ fieldExpr: string,+ valueParam: string,+): string =>+ `(empty(tokens(${normalizeFtsTextExpr(valueParam)})) OR hasAllTokens(${normalizeFtsTextExpr(fieldExpr)}, ${normalizeFtsTextExpr(valueParam)}))`;++export const ftsMetadataArrayHas = (+ arrayExpr: string,+ valueParam: string,+): string => `has(${arrayExpr}, ${valueParam})`;diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.tsindex b93006ab19..c0ec684f10 100644--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts@@ -1,19 +1,49 @@import { TracingSearchType } from "../../../interfaces/search";+import { ftsTextTokenConjunct } from "./fts";const regexIndefiniteCharacters = "%";-export const clickhouseSearchCondition = (- query?: string,- searchType?: TracingSearchType[],- tablePrefix?: string,- searchColumns?: string[],-) => {+export type ClickhouseSearchConditionOptions = {+ query?: string;+ searchType?: TracingSearchType[];+ tablePrefix?: string;+ searchColumns?: readonly string[];+ useEventsTablePath?: boolean;+};++export const clickhouseSearchCondition = ({+ query,+ searchType,+ tablePrefix,+ searchColumns,+ useEventsTablePath = false,+}: ClickhouseSearchConditionOptions) => {const prefix = tablePrefix ? `${tablePrefix}.` : "";+ const ilikeWithPrefilter = (+ col: string,+ param: string = "{searchString: String}",+ ) =>+ // Fast-mode UI search intentionally narrows IO search to token matches+ // before applying ILIKE. This gives ClickHouse an inverted-index lookup,+ // but drops embedded-word substring matches like "foobarneedle".+ useEventsTablePath+ ? `(${col} ILIKE ${param} AND ${ftsTextTokenConjunct(col, param)})`+ : `${col} ILIKE ${param}`;+const defaultCols = [`${prefix}id`, `t.user_id`, `${prefix}name`];const cols = (searchColumns ?? defaultCols).map((col) =>col.includes(".") ? col : `${prefix}${col}`,);+ const inputCol = `${prefix}input`;+ const outputCol = `${prefix}output`;+ const requiresEventsFull =+ Boolean(query) &&+ Boolean(+ searchType?.includes("content") ||+ searchType?.includes("input") ||+ searchType?.includes("output"),+ );// The default cols include t.user_id for callers querying via traces CTE (traces.ts, observations.ts).const conditions = [@@ -21,18 +51,19 @@ export const clickhouseSearchCondition = (? cols.map((col) => `${col} ILIKE {searchString: String}`).join(" OR "): null,searchType && searchType.includes("content")- ? `${prefix}input ILIKE {searchString: String} OR ${prefix}output ILIKE {searchString: String}`+ ? `${ilikeWithPrefilter(inputCol)} OR ${ilikeWithPrefilter(outputCol)}`: null,searchType && searchType.includes("input")- ? `${prefix}input ILIKE {searchString: String}`+ ? ilikeWithPrefilter(inputCol): null,searchType && searchType.includes("output")- ? `${prefix}output ILIKE {searchString: String}`+ ? ilikeWithPrefilter(outputCol): null,].filter(Boolean);return {query: query ? `AND (${conditions.join(" OR ")})` : "",+ requiresEventsFull,params: query? {searchString: `${regexIndefiniteCharacters}${query}${regexIndefiniteCharacters}`,diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.tsindex bc55e80f81..498d4be541 100644--- a/packages/shared/src/server/queries/index.ts+++ b/packages/shared/src/server/queries/index.ts@@ -24,7 +24,17 @@ export {orderByToEntries,} from "./clickhouse-sql/orderby-factory";export { createFilterFromFilterState } from "./clickhouse-sql/factory";-export { clickhouseSearchCondition } from "./clickhouse-sql/search";+export {+ clickhouseSearchCondition,+ type ClickhouseSearchConditionOptions,+} from "./clickhouse-sql/search";+export {+ FTS_EVENTS_TABLES,+ FTS_TEXT_FIELDS,+ FTS_TEXT_OPERATORS,+ isFtsEventsTable,+ isFtsTextTarget,+} from "./clickhouse-sql/fts";export { postgresSearchCondition } from "./postgres-sql/search";export {convertApiProvidedFilterToClickhouseFilter,diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex 7beeb088c5..cc4d8b7f92 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -490,13 +490,6 @@ async function getObservationsFromEventsTableInternal<T>(column === "trace scores (categorical)");});- const search = clickhouseSearchCondition(- opts.searchQuery,- opts.searchType,- "e",- ["span_id", "name", "trace_name", "user_id", "session_id", "trace_id"],- );-const orderByEntries = orderByToEntries([orderBy ?? null],eventsTableUiColumnDefinitions,@@ -522,6 +515,21 @@ async function getObservationsFromEventsTableInternal<T>(}}+ const search = clickhouseSearchCondition({+ query: opts.searchQuery,+ searchType: opts.searchType,+ tablePrefix: "e",+ searchColumns: [+ "span_id",+ "name",+ "trace_name",+ "user_id",+ "session_id",+ "trace_id",+ ],+ useEventsTablePath: true,+ });+// Handle positionInTrace via CTE with ROW_NUMBER()// All modes use the same pattern: rank observations per trace, pick rn = N.// `root` remains only for backward compatibility and maps to `first`.@@ -551,6 +559,7 @@ async function getObservationsFromEventsTableInternal<T>("e.span_id",`ROW_NUMBER() OVER (PARTITION BY e.trace_id ORDER BY e.start_time ${direction}, e.event_ts ${direction}, e.span_id ${direction}) as _rn`,)+ .when(search.requiresEventsFull, (b) => b.forceFullTable()).where(appliedNativeFilter).where(search);@@ -591,6 +600,7 @@ async function getObservationsFromEventsTableInternal<T>("ON ts.trace_id = e.trace_id AND ts.project_id = e.project_id",),)+ .when(search.requiresEventsFull, (b) => b.forceFullTable()).applyFilters(observationsFilter).where(search).when(orderByEntries.length > 0, (b) => b.orderByColumns(orderByEntries))diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.tsindex bee2f73d5c..c967787dcd 100644--- a/packages/shared/src/server/repositories/observations.ts+++ b/packages/shared/src/server/repositories/observations.ts@@ -748,11 +748,11 @@ const getObservationsTableInternal = async <T>(const appliedScoresFilter = scoresFilter.apply();const appliedObservationsFilter = observationsFilter.apply();- const search = clickhouseSearchCondition(- opts.searchQuery,- opts.searchType,- "o",- );+ const search = clickhouseSearchCondition({+ query: opts.searchQuery,+ searchType: opts.searchType,+ tablePrefix: "o",+ });const scoresCte = `WITH scores_agg AS (SELECTdiff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.tsindex 1f64b4ac62..5059a86f6b 100644--- a/packages/shared/src/server/repositories/traces.ts+++ b/packages/shared/src/server/repositories/traces.ts@@ -690,7 +690,10 @@ export const getTracesGroupedBySessionId = async ();const tracesFilterRes = tracesFilter.apply();- const search = clickhouseSearchCondition(searchQuery, undefined, "t");+ const search = clickhouseSearchCondition({+ query: searchQuery,+ tablePrefix: "t",+ });return measureAndReturn({operationName: "getTracesGroupedBySessionId",@@ -764,7 +767,10 @@ export const getTracesGroupedByUsers = async ();const tracesFilterRes = tracesFilter.apply();- const search = clickhouseSearchCondition(searchQuery, undefined, "t");+ const search = clickhouseSearchCondition({+ query: searchQuery,+ tablePrefix: "t",+ });return measureAndReturn({operationName: "getTracesGroupedByUsers",@@ -1168,7 +1174,10 @@ export const getTotalUserCount = async ();const tracesFilterRes = tracesFilter.apply();- const search = clickhouseSearchCondition(searchQuery, undefined, "t");+ const search = clickhouseSearchCondition({+ query: searchQuery,+ tablePrefix: "t",+ });return measureAndReturn({operationName: "getTotalUserCount",diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.tsindex 1ce7c80ec4..b811faf398 100644--- a/packages/shared/src/server/services/traces-ui-table-service.ts+++ b/packages/shared/src/server/services/traces-ui-table-service.ts@@ -401,7 +401,11 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {throw new Error(`Unknown select type: ${select}`);}- const search = clickhouseSearchCondition(searchQuery, searchType, "t");+ const search = clickhouseSearchCondition({+ query: searchQuery,+ searchType,+ tablePrefix: "t",+ });const defaultOrder = orderBy?.order && orderBy?.column === "timestamp";const orderByCols = [diff --git a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts b/web/src/__tests__/server/clickhouseSearchCondition.servertest.tsindex 351fd1cd6c..3bc39cd024 100644--- a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts+++ b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts@@ -1,57 +1,180 @@-import { clickhouseSearchCondition } from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";+import { type TracingSearchType } from "@langfuse/shared";+import {+ clickhouseSearchCondition,+ queryClickhouse,+} from "@langfuse/shared/src/server";-describe("clickhouseSearchCondition", () => {- it("should auto-prefix custom columns with tablePrefix", () => {- const result = clickhouseSearchCondition("test", undefined, "e", [- "span_id",- "name",- "user_id",- "session_id",- "trace_id",- ]);-- expect(result.query).toContain("e.span_id ILIKE");- expect(result.query).toContain("e.name ILIKE");- expect(result.query).toContain("e.user_id ILIKE");- expect(result.query).toContain("e.session_id ILIKE");- expect(result.query).toContain("e.trace_id ILIKE");- expect(result.params).toEqual({ searchString: "%test%" });- });+const maybeEventsTable =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ ? describe+ : describe.skip;- it("should not double-prefix columns that already have a qualifier", () => {- const result = clickhouseSearchCondition("test", undefined, "e", [- "t.user_id",- "name",- ]);+const searchFixture = `+ SELECT *+ FROM values(+ 'id String, name String, input String, output String',+ ('id-match', 'alpha name', 'unrelated input', 'unrelated output'),+ ('input-match-lowercase', 'plain name', 'contains alpha token', 'unrelated output'),+ ('output-match-lowercase', 'plain name', 'unrelated input', 'contains alpha token'),+ ('input-match-uppercase', 'plain name', 'contains ALPHA token', 'unrelated output'),+ ('output-match-uppercase', 'plain name', 'unrelated input', 'contains ALPHA token'),+ ('input-match-substring', 'plain name', 'contains alphabet token', 'unrelated output'),+ ('output-match-substring', 'plain name', 'unrelated input', 'contains alphabet token'),+ ('input-match-cyrillic', 'plain name', 'contains ΠΏΡΠΈΠ²Π΅Ρ token', 'unrelated output'),+ ('output-match-cyrillic', 'plain name', 'unrelated input', 'contains ΠΏΡΠΈΠ²Π΅Ρ token'),+ ('input-match-cjk', 'plain name', 'contains ζ±δΊ¬ token', 'unrelated output'),+ ('output-match-cjk', 'plain name', 'unrelated input', 'contains ζ±δΊ¬ token'),+ ('miss', 'plain name', 'unrelated input', 'unrelated output')+ ) AS e+`;++const matchingIds = async (opts: {+ query: string;+ searchType: TracingSearchType[];+ useEventsTablePath?: boolean;+}) => {+ const search = clickhouseSearchCondition({+ query: opts.query,+ searchType: opts.searchType,+ tablePrefix: "e",+ searchColumns: ["id", "name"],+ useEventsTablePath: opts.useEventsTablePath,+ });- expect(result.query).toContain("t.user_id ILIKE");- expect(result.query).toContain("e.name ILIKE");+ const rows = await queryClickhouse<{ id: string }>({+ query: `+ SELECT e.id AS id+ FROM (${searchFixture}) AS e+ WHERE 1 = 1+ ${search.query}+ ORDER BY e.id ASC+ `,+ params: search.params,+ preferredClickhouseService: "EventsReadOnly",+ tags: {+ feature: "clickhouse-search-condition-test",+ type: "events",+ kind: "test",+ },});- it("should use default columns with prefix when no custom columns provided", () => {- const result = clickhouseSearchCondition("test", undefined, "o");+ return rows.map((row) => row.id);+};++describe("clickhouseSearchCondition", () => {+ it.each([+ { query: undefined, searchType: ["content"], expected: false },+ { query: "alpha", searchType: undefined, expected: false },+ { query: "alpha", searchType: ["id"], expected: false },+ { query: "alpha", searchType: ["content"], expected: true },+ { query: "alpha", searchType: ["input"], expected: true },+ { query: "alpha", searchType: ["output"], expected: true },+ { query: "alpha", searchType: ["id", "content"], expected: true },+ ])(+ "detects whether $searchType search needs the full events table",+ ({ query, searchType, expected }) => {+ expect(+ clickhouseSearchCondition({+ query,+ searchType: searchType as TracingSearchType[] | undefined,+ }).requiresEventsFull,+ ).toBe(expected);+ },+ );++ maybeEventsTable("EventsReadOnly-backed search conditions", () => {+ it.each([+ {+ query: "alpha",+ searchType: ["content"],+ expectedIds: [+ "input-match-lowercase",+ "input-match-substring",+ "input-match-uppercase",+ "output-match-lowercase",+ "output-match-substring",+ "output-match-uppercase",+ ],+ },+ {+ query: "alpha",+ searchType: ["input"],+ expectedIds: [+ "input-match-lowercase",+ "input-match-substring",+ "input-match-uppercase",+ ],+ },+ {+ query: "alpha",+ searchType: ["output"],+ expectedIds: [+ "output-match-lowercase",+ "output-match-substring",+ "output-match-uppercase",+ ],+ },+ {+ query: "ΠΏΡΠΈΠ²Π΅Ρ",+ searchType: ["content"],+ expectedIds: ["input-match-cyrillic", "output-match-cyrillic"],+ },+ {+ query: "ζ±δΊ¬",+ searchType: ["content"],+ expectedIds: ["input-match-cjk", "output-match-cjk"],+ },+ ])(+ "preserves baseline substring search semantics for $query $searchType search",+ async ({ query, searchType, expectedIds }) => {+ await expect(+ matchingIds({+ query,+ searchType: searchType as TracingSearchType[],+ }),+ ).resolves.toEqual(expectedIds);+ },+ );++ it("does not add FTS to id search on events tables", async () => {+ const baseIds = await matchingIds({+ query: "alpha",+ searchType: ["id"],+ });+ const ftsIds = await matchingIds({+ query: "alpha",+ searchType: ["id"],+ useEventsTablePath: true,+ });- expect(result.query).toContain("o.id ILIKE");- expect(result.query).toContain("o.name ILIKE");- expect(result.query).toContain("t.user_id ILIKE");+ expect(baseIds).toEqual(["id-match"]);+ expect(ftsIds).toEqual(baseIds);+ });});- it("should return empty query and params when no search query provided", () => {- const result = clickhouseSearchCondition(undefined, undefined, "e", [- "name",- ]);+ it("generates FTS predicates for events input/output searches", () => {+ const search = clickhouseSearchCondition({+ query: "alpha",+ searchType: ["content"],+ tablePrefix: "e",+ useEventsTablePath: true,+ });- expect(result.query).toBe("");- expect(result.params).toEqual({});+ expect(search.query).toContain("hasAllTokens");+ expect(search.query).toContain("e.input");+ expect(search.query).toContain("e.output");});- it("should include content search when searchType includes content", () => {- const result = clickhouseSearchCondition("test", ["id", "content"], "e", [- "name",- ]);+ it("does not generate FTS predicates for id searches", () => {+ const ftsSearch = clickhouseSearchCondition({+ query: "alpha",+ searchType: ["id"],+ tablePrefix: "e",+ searchColumns: ["id", "name"],+ useEventsTablePath: true,+ });- expect(result.query).toContain("e.name ILIKE");- expect(result.query).toContain("e.input ILIKE");- expect(result.query).toContain("e.output ILIKE");+ expect(ftsSearch.query).not.toContain("hasAllTokens");});});diff --git a/web/src/__tests__/server/fts-rewrites.servertest.ts b/web/src/__tests__/server/fts-rewrites.servertest.tsnew file mode 100644index 0000000000..9496eb2a24--- /dev/null+++ b/web/src/__tests__/server/fts-rewrites.servertest.ts@@ -0,0 +1,205 @@+import { env } from "@/src/env.mjs";+import {+ FTS_EVENTS_TABLES,+ FTS_TEXT_FIELDS,+ FTS_TEXT_OPERATORS,+ StringFilter,+ StringObjectFilter,+ queryClickhouse,+} from "@langfuse/shared/src/server";++const maybeEventsTable =+ env.LANGFUSE_ENABLE_EVENTS_TABLE_V2_APIS === "true"+ ? describe+ : describe.skip;++type FilterResult = {+ query: string;+ params: Record<string, unknown>;+};++const filterFixture = `+ SELECT *+ FROM values(+ 'id String, input String, output String, metadata_names Array(String), metadata_values Array(String)',+ ('input-exact-alpha', 'alpha', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-exact-uppercase', 'ALPHA', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-exact-cyrillic', 'ΠΏΡΠΈΠ²Π΅Ρ', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-exact-cjk', 'ζ±δΊ¬', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-exact-email', '[email protected]', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-exact-punctuation', '!!!', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-prefix-alpha', 'alpha token', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-middle-alpha', 'contains alpha token', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-suffix-alpha', 'token alpha', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-substring-alpha', 'alphabet token', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-ending-substring-alpha', 'token betalpha', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('output-exact-alpha', 'unrelated input', 'alpha', ['topic'], ['unrelated metadata']),+ ('output-exact-uppercase', 'unrelated input', 'ALPHA', ['topic'], ['unrelated metadata']),+ ('output-exact-cyrillic', 'unrelated input', 'ΠΏΡΠΈΠ²Π΅Ρ', ['topic'], ['unrelated metadata']),+ ('output-exact-cjk', 'unrelated input', 'ζ±δΊ¬', ['topic'], ['unrelated metadata']),+ ('output-exact-email', 'unrelated input', '[email protected]', ['topic'], ['unrelated metadata']),+ ('output-exact-punctuation', 'unrelated input', '!!!', ['topic'], ['unrelated metadata']),+ ('output-prefix-alpha', 'unrelated input', 'alpha token', ['topic'], ['unrelated metadata']),+ ('output-middle-alpha', 'unrelated input', 'contains alpha token', ['topic'], ['unrelated metadata']),+ ('output-suffix-alpha', 'unrelated input', 'token alpha', ['topic'], ['unrelated metadata']),+ ('output-substring-alpha', 'unrelated input', 'alphabet token', ['topic'], ['unrelated metadata']),+ ('output-ending-substring-alpha', 'unrelated input', 'token betalpha', ['topic'], ['unrelated metadata']),+ ('metadata-exact-alpha', 'unrelated input', 'unrelated output', ['topic'], ['alpha']),+ ('metadata-prefix-alpha', 'unrelated input', 'unrelated output', ['topic'], ['alpha token']),+ ('metadata-middle-alpha', 'unrelated input', 'unrelated output', ['topic'], ['contains alpha token']),+ ('metadata-suffix-alpha', 'unrelated input', 'unrelated output', ['topic'], ['token alpha']),+ ('metadata-substring-alpha', 'unrelated input', 'unrelated output', ['topic'], ['alphabet token']),+ ('metadata-other-key-alpha', 'unrelated input', 'unrelated output', ['other'], ['alpha']),+ ('miss', 'unrelated input', 'unrelated output', ['topic'], ['unrelated metadata'])+ ) AS e+`;++const matchingIds = async (filter: FilterResult) => {+ const rows = await queryClickhouse<{ id: string }>({+ query: `+ SELECT e.id AS id+ FROM (${filterFixture}) AS e+ WHERE ${filter.query}+ ORDER BY e.id ASC+ `,+ params: filter.params,+ preferredClickhouseService: "EventsReadOnly",+ tags: {+ feature: "fts-rewrites-test",+ type: "events",+ kind: "test",+ },+ });++ return rows.map((row) => row.id);+};++const metadataBaselineFilter = (opts: {+ operator: ConstructorParameters<typeof StringObjectFilter>[0]["operator"];+ key: string;+ value: string;+}): FilterResult => {+ const namesColumn = "e.metadata_names";+ const valuesColumn = "e.metadata_values";+ const valueAccessor = `${valuesColumn}[indexOf(${namesColumn}, {metadataKey: String})]`;+ const hasKey = `has(${namesColumn}, {metadataKey: String})`;+ const valueParam = "{metadataValue: String}";++ let query: string;+ switch (opts.operator) {+ case "=":+ query = `${hasKey} AND (${valueAccessor} = ${valueParam})`;+ break;+ case "contains":+ query = `${hasKey} AND (position(${valueAccessor}, ${valueParam}) > 0)`;+ break;+ case "does not contain":+ query = `${hasKey} AND (position(${valueAccessor}, ${valueParam}) = 0)`;+ break;+ case "starts with":+ query = `${hasKey} AND (startsWith(${valueAccessor}, ${valueParam}))`;+ break;+ case "ends with":+ query = `${hasKey} AND (endsWith(${valueAccessor}, ${valueParam}))`;+ break;+ default:+ throw new Error(`Unsupported operator: ${opts.operator}`);+ }++ return {+ query,+ params: {+ metadataKey: opts.key,+ metadataValue: opts.value,+ },+ };+};++maybeEventsTable("FTS filter rewrites", () => {+ it.each(+ Array.from(FTS_EVENTS_TABLES).flatMap((table) =>+ Array.from(FTS_TEXT_FIELDS).flatMap((field) =>+ [+ { operator: "=", value: "alpha" },+ { operator: "=", value: "ALPHA" },+ { operator: "=", value: "ΠΏΡΠΈΠ²Π΅Ρ" },+ { operator: "=", value: "ζ±δΊ¬" },+ { operator: "=", value: "[email protected]" },+ { operator: "=", value: "!!!" },+ { operator: "contains", value: "alpha" },+ { operator: "starts with", value: "alpha" },+ { operator: "ends with", value: "alpha" },+ ].map((testCase) => ({+ table,+ field,+ ...testCase,+ })),+ ),+ ),+ )(+ "keeps $table $field `$operator` equivalent to the baseline for `$value`",+ async ({ table, field, operator, value }) => {+ const fieldExpr = `e.${field}`;+ const baseline = new StringFilter({+ clickhouseTable: "traces",+ field: fieldExpr,+ operator,+ value,+ }).apply();+ const rewritten = new StringFilter({+ clickhouseTable: table,+ field: fieldExpr,+ operator,+ value,+ }).apply();++ expect(rewritten.query.includes("hasAllTokens")).toBe(+ FTS_TEXT_OPERATORS.has(operator),+ );+ await expect(matchingIds(rewritten)).resolves.toEqual(+ await matchingIds(baseline),+ );+ },+ );++ it.each(+ Array.from(FTS_EVENTS_TABLES).flatMap((table) =>+ [+ { operator: "=", value: "alpha" },+ { operator: "contains", value: "alpha" },+ { operator: "starts with", value: "alpha" },+ { operator: "ends with", value: "alpha" },+ { operator: "does not contain", value: "alpha" },+ ].map((testCase) => ({+ table,+ ...testCase,+ })),+ ),+ )(+ "keeps $table.metadata `$operator` equivalent to the baseline for `$value`",+ async ({ table, operator, value }) => {+ const baseline = metadataBaselineFilter({+ operator,+ key: "topic",+ value,+ });+ const rewritten = new StringObjectFilter({+ clickhouseTable: table,+ field: "metadata",+ operator,+ key: "topic",+ value,+ tablePrefix: "e",+ }).apply();++ if (operator === "=") {+ expect(rewritten.query).toContain("has(e.metadata_values,");+ } else {+ expect(rewritten.query).not.toContain("hasAllTokens");+ }+ await expect(matchingIds(rewritten)).resolves.toEqual(+ await matchingIds(baseline),+ );+ },+ );+});diff --git a/worker/src/features/database-read-stream/event-stream.ts b/worker/src/features/database-read-stream/event-stream.tsindex bfaf75f3ab..1cf53f87d0 100644--- a/worker/src/features/database-read-stream/event-stream.ts+++ b/worker/src/features/database-read-stream/event-stream.ts@@ -35,6 +35,26 @@ import { fetchCommentsForExport } from "./fetchCommentsForExport";import { BatchExportEventsRow } from "./types";const BATCH_SIZE = 1000; // Fetch comments in batches for efficiency+const EVENT_SEARCH_COLUMNS = [+ "span_id",+ "name",+ "trace_name",+ "user_id",+ "session_id",+ "trace_id",+] as const;++const eventSearchCondition = (opts: {+ query?: string;+ searchType?: TracingSearchType[];+}) =>+ clickhouseSearchCondition({+ query: opts.query,+ searchType: opts.searchType,+ tablePrefix: "e",+ searchColumns: EVENT_SEARCH_COLUMNS,+ useEventsTablePath: true,+ });/*** Creates a stream of events from ClickHouse for batch export.@@ -119,14 +139,10 @@ export const getEventsStream = async (props: {const appliedEventsFilter = eventsFilter.apply();- const search = clickhouseSearchCondition(searchQuery, searchType, "e", [- "span_id",- "name",- "trace_name",- "user_id",- "session_id",- "trace_id",- ]);+ const search = eventSearchCondition({+ query: searchQuery,+ searchType,+ });// Build the query using EventsQueryBuilderconst eventsQuery = new EventsQueryBuilder({ projectId })@@ -146,6 +162,7 @@ export const getEventsStream = async (props: {"scores_agg s","ON s.trace_id = e.trace_id AND s.observation_id = e.span_id",)+ .when(search.requiresEventsFull, (b) => b.forceFullTable()).where(appliedEventsFilter).where(search).whereRaw("e.is_deleted = 0")@@ -398,19 +415,16 @@ export const getEventsStreamForEval = async (props: {const appliedEventsFilter = eventsFilter.apply();- const search = clickhouseSearchCondition(searchQuery, searchType, "e", [- "span_id",- "name",- "trace_name",- "user_id",- "session_id",- "trace_id",- ]);+ const search = eventSearchCondition({+ query: searchQuery,+ searchType,+ });const eventsQuery = new EventsQueryBuilder({ projectId }).selectFieldSet("eval").selectIO(false).selectFieldSet("metadata")+ .when(search.requiresEventsFull, (b) => b.forceFullTable()).where(appliedEventsFilter).where(search).whereRaw("e.is_deleted = 0")@@ -543,19 +557,16 @@ export const getEventsStreamForDataset = async (props: {const appliedEventsFilter = eventsFilter.apply();- const search = clickhouseSearchCondition(searchQuery, searchType, "e", [- "span_id",- "name",- "trace_name",- "user_id",- "session_id",- "trace_id",- ]);+ const search = eventSearchCondition({+ query: searchQuery,+ searchType,+ });const eventsQuery = new EventsQueryBuilder({ projectId }).selectFieldSet("core").selectIO(false).selectFieldSet("metadata")+ .when(search.requiresEventsFull, (b) => b.forceFullTable()).where(appliedEventsFilter).where(search).whereRaw("e.is_deleted = 0")@@ -658,17 +669,14 @@ export const getEventsStreamForAnnotationQueue = async (props: {const appliedEventsFilter = eventsFilter.apply();- const search = clickhouseSearchCondition(searchQuery, searchType, "e", [- "span_id",- "name",- "trace_name",- "user_id",- "session_id",- "trace_id",- ]);+ const search = eventSearchCondition({+ query: searchQuery,+ searchType,+ });const eventsQuery = new EventsQueryBuilder({ projectId }).selectFieldSet("core")+ .when(search.requiresEventsFull, (b) => b.forceFullTable()).where(appliedEventsFilter).where(search).whereRaw("e.is_deleted = 0")diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.tsindex 300cf51a70..f15a6f7c1a 100644--- a/worker/src/features/database-read-stream/observation-stream.ts+++ b/worker/src/features/database-read-stream/observation-stream.ts@@ -125,7 +125,11 @@ export const getObservationStream = async (props: {const appliedObservationsFilter = observationsFilter.apply();- const search = clickhouseSearchCondition(searchQuery, searchType, "o");+ const search = clickhouseSearchCondition({+ query: searchQuery,+ searchType,+ tablePrefix: "o",+ });const query = `diff --git a/worker/src/features/database-read-stream/trace-stream.ts b/worker/src/features/database-read-stream/trace-stream.tsindex 2e104c4d1b..248871897f 100644--- a/worker/src/features/database-read-stream/trace-stream.ts+++ b/worker/src/features/database-read-stream/trace-stream.ts@@ -110,7 +110,11 @@ export const getTraceStream = async (props: {const appliedScoresFilter = scoresFilter.apply();- const search = clickhouseSearchCondition(searchQuery, searchType, "t");+ const search = clickhouseSearchCondition({+ query: searchQuery,+ searchType,+ tablePrefix: "t",+ });const query = `WITH scores_agg AS (