🪢 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
perf(clickhouse): prune event name search with ngram skip indexes (#17190)
Niklas Semmler9f180069716d
diff --git a/packages/shared/clickhouse/migrations/canonical/0049_add_events_name_ngram_indexes.down.sql b/packages/shared/clickhouse/migrations/canonical/0049_add_events_name_ngram_indexes.down.sqlnew file mode 100644index 0000000000..d0facd362d--- /dev/null+++ b/packages/shared/clickhouse/migrations/canonical/0049_add_events_name_ngram_indexes.down.sql@@ -0,0 +1,4 @@+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} DROP INDEX IF EXISTS idx_ngram_name SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} DROP INDEX IF EXISTS idx_ngram_trace_name SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} DROP INDEX IF EXISTS idx_ngram_user_id SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} DROP INDEX IF EXISTS idx_ngram_session_id SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};diff --git a/packages/shared/clickhouse/migrations/canonical/0049_add_events_name_ngram_indexes.up.sql b/packages/shared/clickhouse/migrations/canonical/0049_add_events_name_ngram_indexes.up.sqlnew file mode 100644index 0000000000..a3e18829bd--- /dev/null+++ b/packages/shared/clickhouse/migrations/canonical/0049_add_events_name_ngram_indexes.up.sql@@ -0,0 +1,6 @@+-- Indexes new parts only. Do not MATERIALIZE INDEX here (rewriting existing parts is a full-table mutation). Old parts stay correct but unpruned and persist until project retention deletes or a partition drop removes them, as events_full is partitioned monthly with no table TTL.+-- Only the human-readable substring-search columns get an ngram index. The UUID-shaped id columns (span_id, trace_id) match by equality against their existing bloom_filter/primary key, so a leading-wildcard ngram bloom on hex+hyphen would barely prune and is not worth its write cost. The query builder must emit lower(col) LIKE for these four and col = for the id columns, or ClickHouse discards the input/output text indexes for the OR.+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} ADD INDEX IF NOT EXISTS idx_ngram_name lower(name) TYPE ngrambf_v1(3, 4096, 2, 0) GRANULARITY 1 SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} ADD INDEX IF NOT EXISTS idx_ngram_trace_name lower(trace_name) TYPE ngrambf_v1(3, 4096, 2, 0) GRANULARITY 1 SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} ADD INDEX IF NOT EXISTS idx_ngram_user_id lower(user_id) TYPE ngrambf_v1(3, 4096, 2, 0) GRANULARITY 1 SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};+ALTER TABLE events_full {CLICKHOUSE_CLUSTER_CLAUSE} ADD INDEX IF NOT EXISTS idx_ngram_session_id lower(session_id) TYPE ngrambf_v1(3, 4096, 2, 0) GRANULARITY 1 SETTINGS enable_full_text_index = 1{CLICKHOUSE_CLUSTERED_ONLY:, alter_sync = 2};diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.tsindex 3df9d6b455..69faf47b89 100644--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts@@ -4,10 +4,27 @@ import {TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,type TracingSearchType,} from "../../../interfaces/search";-import { ftsTextTokenConjunct } from "./fts";+import { bareFtsField, ftsTextTokenConjunct } from "./fts";const regexIndefiniteCharacters = "%";+// events_full ngrambf_v1 skip indexes are defined on lower(<col>). ILIKE on the+// raw column cannot use them; the query must match lower(col) LIKE lower(...).+// Every leading-wildcard disjunct in the search OR must be index-usable or+// ClickHouse discards the input/output text indexes for the whole query.+const NGRAM_SUBSTRING_COLUMNS = new Set([+ "name",+ "trace_name",+ "user_id",+ "session_id",+]);++// span_id/trace_id are UUID-shaped: an ngrambf on hex+hyphen prunes almost+// nothing, so we match by equality against their existing bloom_filter (and,+// for span_id, the primary key) instead of adding an index. Exact-match and+// case-sensitive on the events path; callers paste whole ids.+const EQUALITY_ID_COLUMNS = new Set(["span_id", "trace_id"]);+/*** Re-encodes a string the way a JSON serializer with `ensure_ascii=True` does (e.g. Python's* `json.dumps`, used by the Langfuse Python SDK's EventSerializer / the OpenTelemetry ingestion@@ -68,6 +85,19 @@ export const clickhouseSearchCondition = ({? `(${col} ILIKE ${param} AND ${ftsTextTokenConjunct(col, param)})`: `${col} ILIKE ${param}`;+ const idLaneMatch = (col: string) => {+ if (useEventsTablePath) {+ const bare = bareFtsField(col);+ if (EQUALITY_ID_COLUMNS.has(bare)) {+ return `${col} = {searchStringExact: String}`;+ }+ if (NGRAM_SUBSTRING_COLUMNS.has(bare)) {+ return `lower(${col}) LIKE lower({searchString: String})`;+ }+ }+ return `${col} ILIKE {searchString: String}`;+ };+const defaultCols = [`${prefix}id`, `t.user_id`, `${prefix}name`];const cols = (searchColumns ?? defaultCols).map((col) =>col.includes(".") ? col : `${prefix}${col}`,@@ -100,7 +130,7 @@ export const clickhouseSearchCondition = ({// The default cols include t.user_id for callers querying via traces CTE (traces.ts, observations.ts).const conditions = [!searchType || searchType.includes("id")- ? cols.map((col) => `${col} ILIKE {searchString: String}`).join(" OR ")+ ? cols.map((col) => idLaneMatch(col)).join(" OR "): null,searchType && searchType.includes("content")? `${ioColumnMatch(inputCol)} OR ${ioColumnMatch(outputCol)}`@@ -117,6 +147,8 @@ export const clickhouseSearchCondition = ({params: query? {searchString: `${regexIndefiniteCharacters}${query}${regexIndefiniteCharacters}`,+ // Unwrapped for the events-path equality columns (span_id/trace_id).+ ...(useEventsTablePath ? { searchStringExact: query } : {}),...(hasEscapedVariant? {searchStringEscaped: `${regexIndefiniteCharacters}${escapedQuery}${regexIndefiniteCharacters}`,diff --git a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts b/web/src/__tests__/server/clickhouseSearchCondition.servertest.tsindex a0ce401747..69e66a292b 100644--- a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts+++ b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts@@ -4,6 +4,7 @@ import {clickhouseSearchCondition,createEvent,createEventsCh,+ eventSearchCondition,getObservationsWithModelDataFromEventsTable,queryClickhouse,} from "@langfuse/shared/src/server";@@ -164,6 +165,91 @@ describe("clickhouseSearchCondition", () => {},);+ const explainText = (rows: Record<string, string>[]) =>+ rows.map((row) => Object.values(row).join(" ")).join("\n");++ it("uses idx_ngram_name to prune an absent name substring on events_full", async () => {+ const uniqueProjectId = randomUUID();+ await createEventsCh([+ createEvent({+ project_id: uniqueProjectId,+ name: "chat-completion",+ type: "GENERATION",+ input: "unrelated input",+ output: "unrelated output",+ }),+ ]);++ const plan = await queryClickhouse<Record<string, string>>({+ query: `+ EXPLAIN indexes = 1+ SELECT e.span_id+ FROM events_full AS e+ WHERE e.project_id = {projectId: String}+ AND lower(e.name) LIKE lower({searchString: String})+ `,+ params: {+ projectId: uniqueProjectId,+ searchString: "%zzzxqnotpresentxyz%",+ },+ preferredClickhouseService: "EventsReadOnly",+ });++ const text = explainText(plan);+ expect(text).toContain("idx_ngram_name");+ expect(text).toMatch(/Parts:\s*0\//);+ });++ it("keeps the input text index live on a combined id+content search", async () => {+ const uniqueProjectId = randomUUID();+ await createEventsCh([+ createEvent({+ project_id: uniqueProjectId,+ name: "chat-completion",+ trace_name: "user-query",+ type: "GENERATION",+ input: "unrelated input",+ output: "unrelated output",+ }),+ ]);++ const search = eventSearchCondition({+ query: "zzzxqnotpresentxyz",+ searchType: ["id", "content"],+ });++ const plan = await queryClickhouse<Record<string, string>>({+ query: `+ EXPLAIN indexes = 1+ SELECT e.span_id+ FROM events_full AS e+ WHERE e.project_id = {projectId: String}+ ${search.query}+ `,+ params: {+ projectId: uniqueProjectId,+ ...search.params,+ },+ preferredClickhouseService: "EventsReadOnly",+ });++ const text = explainText(plan);+ expect(text).toContain("idx_ngram_name");+ expect(text).toContain("idx_ngram_trace_name");+ expect(text).toMatch(/idx_fts_input_low|idx_fts_output_low/);+ expect(text).toMatch(/Granules:\s*0\//);+ });++ it("matches name case-insensitively via lower() LIKE on the events path", async () => {+ await expect(+ matchingIds({+ query: "ALPHA",+ searchType: ["id"],+ useEventsTablePath: true,+ }),+ ).resolves.toEqual(["id-match"]);+ });+it("does not add FTS to id search on events tables", async () => {const baseIds = await matchingIds({query: "alpha",@@ -342,4 +428,59 @@ describe("clickhouseSearchCondition", () => {expect(ftsSearch.query).not.toContain("hasAllTokens");});++ it("rewrites events-table id-lane search: ngram columns to lower() LIKE, id columns to equality", () => {+ const search = clickhouseSearchCondition({+ query: "alpha",+ searchType: ["id"],+ tablePrefix: "e",+ searchColumns: [+ "span_id",+ "name",+ "trace_name",+ "user_id",+ "session_id",+ "trace_id",+ ],+ useEventsTablePath: true,+ });++ // Human-readable columns prune via the lower() ngram indexes.+ expect(search.query).toContain(+ "lower(e.name) LIKE lower({searchString: String})",+ );+ expect(search.query).toContain(+ "lower(e.trace_name) LIKE lower({searchString: String})",+ );+ expect(search.query).toContain(+ "lower(e.user_id) LIKE lower({searchString: String})",+ );+ expect(search.query).toContain(+ "lower(e.session_id) LIKE lower({searchString: String})",+ );++ // UUID-shaped id columns match by equality against their bloom_filter/PK.+ expect(search.query).toContain("e.span_id = {searchStringExact: String}");+ expect(search.query).toContain("e.trace_id = {searchStringExact: String}");+ expect(search.query).not.toContain("lower(e.span_id)");+ expect(search.query).not.toContain("lower(e.trace_id)");+ expect(search.query).not.toContain("e.name ILIKE");+ expect(search.query).not.toContain("e.span_id ILIKE");++ // Equality param is unwrapped (no leading-wildcard %).+ const params = search.params as Record<string, string>;+ expect(params.searchStringExact).toBe("alpha");+ expect(params.searchString).toBe("%alpha%");+ });++ it("keeps ILIKE name search off the events table path", () => {+ const search = clickhouseSearchCondition({+ query: "alpha",+ searchType: ["id"],+ tablePrefix: "t",+ });++ expect(search.query).toContain("t.name ILIKE {searchString: String}");+ expect(search.query).not.toContain("lower(t.name)");+ });});