Skip to content

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

fix: Function 'hasAllTokens' supports a max of 64 search tokens (#14114)

Valery Meleshkinee36a6aaf48f
diff --git a/packages/shared/src/server/queries/clickhouse-sql/fts.ts b/packages/shared/src/server/queries/clickhouse-sql/fts.ts
index 7775d815f2..a038a9ce6b 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/fts.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/fts.ts
@@ -18,6 +18,7 @@ export const FTS_MATCH_TARGET_ERROR =
"`matches` is only supported for input, output, and metadata filters.";
export const FTS_TEXT_NORMALIZER = "lower";
+export const FTS_HAS_ALL_TOKENS_MAX_SEARCH_TOKENS = 64;
export const FTS_EVENTS_TABLES: ReadonlySet<string> = new Set(
EVENTS_TABLE_NAMES,
@@ -76,17 +77,35 @@ export const hasFtsSearchToken = (value: string): boolean =>
const normalizeFtsTextExpr = (expr: string): string =>
`${FTS_TEXT_NORMALIZER}(${expr})`;
+const ftsSearchTokensExpr = (valueParam: string, normalize: boolean): string =>
+ `arrayDistinct(tokens(${normalize ? normalizeFtsTextExpr(valueParam) : valueParam}))`;
+
+const ftsSearchTokenPrefilterExpr = (
+ valueParam: string,
+ normalize: boolean,
+): string =>
+ `arraySlice(${ftsSearchTokensExpr(valueParam, normalize)}, 1, ${FTS_HAS_ALL_TOKENS_MAX_SEARCH_TOKENS})`;
+
+// `hasAllTokens` can only accept up to 64 search tokens. This predicate is only
+// an index prefilter; exact equality, ILIKE, or position() enforces semantics.
+const ftsTokenPrefilterPredicate = (
+ fieldExpr: string,
+ valueParam: string,
+ normalizeValue: boolean,
+): string =>
+ `hasAllTokens(${fieldExpr}, ${ftsSearchTokenPrefilterExpr(valueParam, normalizeValue)})`;
+
export const ftsTextTokenPredicate = (
fieldExpr: string,
valueParam: string,
): string =>
- `hasAllTokens(${normalizeFtsTextExpr(fieldExpr)}, ${normalizeFtsTextExpr(valueParam)})`;
+ ftsTokenPrefilterPredicate(normalizeFtsTextExpr(fieldExpr), valueParam, true);
export const ftsTextTokenConjunct = (
fieldExpr: string,
valueParam: string,
): string =>
- `(empty(tokens(${normalizeFtsTextExpr(valueParam)})) OR ${ftsTextTokenPredicate(fieldExpr, valueParam)})`;
+ `(empty(${ftsSearchTokensExpr(valueParam, true)}) OR ${ftsTextTokenPredicate(fieldExpr, valueParam)})`;
export const ftsTextIndexedSubstringCondition = (
fieldExpr: string,
@@ -102,7 +121,7 @@ export const ftsMetadataArrayHas = (
export const ftsMetadataArrayTokenConjunct = (
arrayExpr: string,
valueParam: string,
-): string => `hasAllTokens(${arrayExpr}, ${valueParam})`;
+): string => ftsTokenPrefilterPredicate(arrayExpr, valueParam, false);
type FtsMetadataArrayConditionContext = {
hasKey: string;
diff --git a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts
index 2109cc1f24..f4d81a2de9 100644
--- a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts
+++ b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts
@@ -14,6 +14,9 @@ const maybeEventsTable =
? describe
: describe.skip;
+const alphabeticSearchToken = (index: number, prefix: string = "needle") =>
+ `${prefix}${String.fromCharCode(97 + Math.floor(index / 26))}${String.fromCharCode(97 + (index % 26))}`;
+
const searchFixture = `
SELECT *
FROM values(
@@ -163,6 +166,40 @@ describe("clickhouseSearchCondition", () => {
expect(ftsIds).toEqual(baseIds);
});
+ it("handles FTS-prefiltered searches with more than 64 tokens", async () => {
+ const longQuery = Array.from({ length: 65 }, (_, index) =>
+ alphabeticSearchToken(index),
+ ).join(" ");
+ const search = clickhouseSearchCondition({
+ query: longQuery,
+ searchType: ["content"],
+ tablePrefix: "e",
+ searchColumns: ["id", "name"],
+ useEventsTablePath: true,
+ });
+
+ await expect(
+ queryClickhouse<{ count: number }>({
+ query: `
+ SELECT count() AS count
+ FROM events_full AS e
+ WHERE e.project_id = {projectId: String}
+ ${search.query}
+ `,
+ params: {
+ projectId: randomUUID(),
+ ...search.params,
+ },
+ preferredClickhouseService: "EventsReadOnly",
+ tags: {
+ feature: "clickhouse-search-condition-test",
+ type: "events",
+ kind: "test",
+ },
+ }),
+ ).resolves.toEqual([{ count: 0 }]);
+ });
+
it("matches JSON-escaped Unicode content on events tables with the FTS prefilter", async () => {
const search = clickhouseSearchCondition({
query: "東京",
@@ -177,11 +214,15 @@ describe("clickhouseSearchCondition", () => {
searchStringEscaped: "%\\u6771\\u4eac%",
});
expect(search.query).toContain("{searchStringEscaped: String}");
+ expect(search.query).toContain("arraySlice");
+ expect(search.query).toContain(
+ "hasAllTokens(lower(e.input), arraySlice(",
+ );
expect(search.query).toContain(
- "hasAllTokens(lower(e.input), lower({searchStringEscaped: String}))",
+ "hasAllTokens(lower(e.output), arraySlice(",
);
expect(search.query).toContain(
- "hasAllTokens(lower(e.output), lower({searchStringEscaped: String}))",
+ "tokens(lower({searchStringEscaped: String}))",
);
await expect(
diff --git a/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts b/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts
index b75432e733..d92c48fd3d 100644
--- a/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts
+++ b/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts
@@ -310,9 +310,14 @@ describe("createFilterFromFilterState filter type validation", () => {
const { query, params } = result.apply();
const paramName = Object.keys(params)[0];
- expect(query).toBe(
- `(position(lower(e.output), lower({${paramName}: String})) > 0 AND hasAllTokens(lower(e.output), lower({${paramName}: String})))`,
+ expect(query).toContain(
+ `position(lower(e.output), lower({${paramName}: String})) > 0`,
+ );
+ expect(query).toContain("arraySlice");
+ expect(query).toContain(
+ `hasAllTokens(lower(e.output), arraySlice(arrayDistinct(tokens(lower({${paramName}: String}))), 1, 64))`,
);
+ expect(query).toContain(`tokens(lower({${paramName}: String}))`);
expect(params).toEqual({ [paramName]: "needle" });
});
@@ -333,7 +338,8 @@ describe("createFilterFromFilterState filter type validation", () => {
const { query } = result.apply();
expect(query).toContain("e.input =");
- expect(query).toContain("hasAllTokens(lower(e.input), lower(");
+ expect(query).toContain("arraySlice");
+ expect(query).toContain("hasAllTokens(lower(e.input), arraySlice(");
});
it("generates case-sensitive FTS SQL for event metadata matches", () => {