🪢 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: tighten matches operator semantics (#13928)
Valery Meleshkin632aafa77973
diff --git a/fern/apis/server/definition/observations.yml b/fern/apis/server/definition/observations.ymlindex 3e69e2a2fa..3934c71b26 100644--- a/fern/apis/server/definition/observations.yml+++ b/fern/apis/server/definition/observations.yml@@ -157,11 +157,11 @@ service:- `promptVersion` (number) - Associated prompt version### Structured Data- - `input` (string) - Observation input. Supports accelerated token search with the `matches` operator.- - `output` (string) - Observation output. Supports accelerated token search with the `matches` operator.+ - `input` (string) - Observation input. Supports accelerated indexed literal search with the `matches` operator.+ - `output` (string) - Observation output. Supports accelerated indexed literal search with the `matches` operator.- `metadata` (stringObject/numberObject/categoryOptions) - Metadata key-value pairs. Use `key` parameter to filter on specific metadata keys.- The `matches` operator is only supported for `input`, `output`, and stringObject `metadata` filters. It performs token-based full-text search using the events table text indexes. Case sensitivity differs by target: `input` and `output` matches are case-insensitive, while metadata value matches are case-sensitive. Use `contains` for substring semantics. Any v2 `input` or `output` filter must be accompanied by at least one `=` or `matches` filter on `input` or `output`; standalone `contains`, `starts with`, `ends with`, and `does not contain` filters on these columns are rejected.+ The `matches` operator is only supported for `input`, `output`, and stringObject `metadata` filters. It performs indexed literal search with token-boundary pruning using the events table text indexes. Case sensitivity differs by target: `input` and `output` matches are case-insensitive, while metadata value matches are case-sensitive. Unlike SQL `LIKE`, `%` and `_` are treated as literal characters. Use `contains` for legacy substring semantics where the API allows it. Any v2 `input` or `output` filter must be accompanied by at least one `=` or `matches` filter on `input` or `output`; standalone `contains`, `starts with`, `ends with`, and `does not contain` filters on these columns are rejected.## Filter Examples```jsondiff --git a/packages/shared/src/server/queries/clickhouse-sql/fts.ts b/packages/shared/src/server/queries/clickhouse-sql/fts.tsindex dab429868d..7775d815f2 100644--- a/packages/shared/src/server/queries/clickhouse-sql/fts.ts+++ b/packages/shared/src/server/queries/clickhouse-sql/fts.ts@@ -76,17 +76,23 @@ export const hasFtsSearchToken = (value: string): boolean =>const normalizeFtsTextExpr = (expr: string): string =>`${FTS_TEXT_NORMALIZER}(${expr})`;+export const ftsTextTokenPredicate = (+ fieldExpr: string,+ valueParam: string,+): string =>+ `hasAllTokens(${normalizeFtsTextExpr(fieldExpr)}, ${normalizeFtsTextExpr(valueParam)})`;+export const ftsTextTokenConjunct = (fieldExpr: string,valueParam: string,): string =>- `(empty(tokens(${normalizeFtsTextExpr(valueParam)})) OR hasAllTokens(${normalizeFtsTextExpr(fieldExpr)}, ${normalizeFtsTextExpr(valueParam)}))`;+ `(empty(tokens(${normalizeFtsTextExpr(valueParam)})) OR ${ftsTextTokenPredicate(fieldExpr, valueParam)})`;-export const ftsTextMatchesCondition = (+export const ftsTextIndexedSubstringCondition = (fieldExpr: string,valueParam: string,): string =>- `hasAllTokens(${normalizeFtsTextExpr(fieldExpr)}, ${normalizeFtsTextExpr(valueParam)})`;+ `(position(${normalizeFtsTextExpr(fieldExpr)}, ${normalizeFtsTextExpr(valueParam)}) > 0 AND ${ftsTextTokenPredicate(fieldExpr, valueParam)})`;export const ftsMetadataArrayHas = (arrayExpr: string,@@ -114,6 +120,14 @@ type FtsOperatorDescriptor = {metadataArrayCondition: (ctx: FtsMetadataArrayConditionContext) => string;};+export const ftsMetadataArrayIndexedSubstringCondition = ({+ hasKey,+ valuesColumn,+ valueAccessor,+ valueParam,+}: FtsMetadataArrayConditionContext): string =>+ `${hasKey} AND ${ftsMetadataArrayTokenConjunct(valuesColumn, valueParam)} AND (position(${valueAccessor}, ${valueParam}) > 0)`;+type FtsOperatorDescriptors = {[operator in FtsAcceleratedStringOperator]: FtsOperatorDescriptor;};@@ -132,20 +146,15 @@ export const FTS_OPERATOR_DESCRIPTORS = {},[FTS_MATCH_OPERATOR]: {textCondition: (fieldExpr, valueParam, _exactCondition) =>- ftsTextMatchesCondition(fieldExpr, valueParam),- metadataArrayCondition: ({- hasKey,- valuesColumn,- valueAccessor,- valueParam,- }) =>- `${hasKey} AND ${ftsMetadataArrayTokenConjunct(valuesColumn, valueParam)} AND ${ftsMetadataArrayTokenConjunct(valueAccessor, valueParam)}`,+ ftsTextIndexedSubstringCondition(fieldExpr, valueParam),+ metadataArrayCondition: ftsMetadataArrayIndexedSubstringCondition,},} satisfies FtsOperatorDescriptors;// StringFilter rewrites must preserve filter API semantics. Limit transparent// text-index rewrites to equality because substring filters are expected to-// match inside larger tokens. `matches` is an explicit token-search operator.+// match inside larger tokens. `matches` is an explicit indexed literal-search+// operator.export const FTS_TEXT_OPERATORS: ReadonlySet<FtsStringOperator> = new Set(Object.keys(FTS_OPERATOR_DESCRIPTORS) as FtsAcceleratedStringOperator[],);diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 1efc58c64e..6e278e0528 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -3399,11 +3399,11 @@ paths:### Structured Data- - `input` (string) - Observation input. Supports accelerated token- search with the `matches` operator.+ - `input` (string) - Observation input. Supports accelerated indexed+ literal search with the `matches` operator.- - `output` (string) - Observation output. Supports accelerated token- search with the `matches` operator.+ - `output` (string) - Observation output. Supports accelerated+ indexed literal search with the `matches` operator.- `metadata` (stringObject/numberObject/categoryOptions) - Metadatakey-value pairs. Use `key` parameter to filter on specific metadata@@ -3411,14 +3411,16 @@ paths:The `matches` operator is only supported for `input`, `output`, and- stringObject `metadata` filters. It performs token-based full-text- search using the events table text indexes. Case sensitivity differs- by target: `input` and `output` matches are case-insensitive, while- metadata value matches are case-sensitive. Use `contains` for- substring semantics. Any v2 `input` or `output` filter must be- accompanied by at least one `=` or `matches` filter on `input` or- `output`; standalone `contains`, `starts with`, `ends with`, and- `does not contain` filters on these columns are rejected.+ stringObject `metadata` filters. It performs indexed literal search+ with token-boundary pruning using the events table text indexes.+ Case sensitivity differs by target: `input` and `output` matches are+ case-insensitive, while metadata value matches are case-sensitive.+ Unlike SQL `LIKE`, `%` and `_` are treated as literal characters.+ Use `contains` for legacy substring semantics where the API allows+ it. Any v2 `input` or `output` filter must be accompanied by at+ least one `=` or `matches` filter on `input` or `output`; standalone+ `contains`, `starts with`, `ends with`, and `does not contain`+ filters on these columns are rejected.## Filter Examplesdiff --git a/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts b/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.tsindex a9dd473cc3..b75432e733 100644--- a/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts+++ b/web/src/__tests__/server/createFilterFromFilterState-filterTypeValidation.servertest.ts@@ -311,7 +311,7 @@ describe("createFilterFromFilterState filter type validation", () => {const paramName = Object.keys(params)[0];expect(query).toBe(- `hasAllTokens(lower(e.output), lower({${paramName}: String}))`,+ `(position(lower(e.output), lower({${paramName}: String})) > 0 AND hasAllTokens(lower(e.output), lower({${paramName}: String})))`,);expect(params).toEqual({ [paramName]: "needle" });});@@ -358,8 +358,9 @@ describe("createFilterFromFilterState filter type validation", () => {expect(query).toContain("has(e.metadata_names,");expect(query).toContain("hasAllTokens(e.metadata_values,");expect(query).toContain(- "hasAllTokens(e.metadata_values[indexOf(e.metadata_names,",+ "position(e.metadata_values[indexOf(e.metadata_names,",);+ expect(query).not.toContain("hasAllTokens(e.metadata_values[indexOf");expect(query).not.toContain("lower(");expect(Object.values(params)).toEqual(["source", "needle"]);});diff --git a/web/src/__tests__/server/fts-rewrites.servertest.ts b/web/src/__tests__/server/fts-rewrites.servertest.tsindex 9496eb2a24..40c5dc9e68 100644--- a/web/src/__tests__/server/fts-rewrites.servertest.ts+++ b/web/src/__tests__/server/fts-rewrites.servertest.ts@@ -1,6 +1,7 @@import { env } from "@/src/env.mjs";import {FTS_EVENTS_TABLES,+ FTS_MATCH_OPERATOR,FTS_TEXT_FIELDS,FTS_TEXT_OPERATORS,StringFilter,@@ -33,6 +34,10 @@ const filterFixture = `('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']),+ ('input-phrase-alpha-beta', 'alpha beta token', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-phrase-alpha-beta-uppercase', 'ALPHA BETA token', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-phrase-beta-alpha', 'beta alpha token', 'unrelated output', ['topic'], ['unrelated metadata']),+ ('input-phrase-alpha-gap-beta', 'alpha gap beta', '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']),@@ -44,11 +49,20 @@ const filterFixture = `('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']),+ ('output-phrase-alpha-beta', 'unrelated input', 'alpha beta token', ['topic'], ['unrelated metadata']),+ ('output-phrase-alpha-beta-uppercase', 'unrelated input', 'ALPHA BETA token', ['topic'], ['unrelated metadata']),+ ('output-phrase-beta-alpha', 'unrelated input', 'beta alpha token', ['topic'], ['unrelated metadata']),+ ('output-phrase-alpha-gap-beta', 'unrelated input', 'alpha gap beta', ['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-phrase-alpha-beta', 'unrelated input', 'unrelated output', ['topic'], ['alpha beta token']),+ ('metadata-phrase-alpha-beta-uppercase', 'unrelated input', 'unrelated output', ['topic'], ['ALPHA BETA token']),+ ('metadata-phrase-beta-alpha', 'unrelated input', 'unrelated output', ['topic'], ['beta alpha token']),+ ('metadata-phrase-alpha-gap-beta', 'unrelated input', 'unrelated output', ['topic'], ['alpha gap beta']),+ ('metadata-split-alpha-beta', 'unrelated input', 'unrelated output', ['topic', 'other'], ['alpha', 'beta']),('metadata-other-key-alpha', 'unrelated input', 'unrelated output', ['other'], ['alpha']),('miss', 'unrelated input', 'unrelated output', ['topic'], ['unrelated metadata'])) AS e@@ -202,4 +216,55 @@ maybeEventsTable("FTS filter rewrites", () => {);},);++ it.each(+ Array.from(FTS_EVENTS_TABLES).flatMap((table) =>+ Array.from(FTS_TEXT_FIELDS).map((field) => ({ table, field })),+ ),+ )(+ "uses indexed literal search for $table $field matches",+ async ({ table, field }) => {+ const fieldExpr = `e.${field}`;+ const rewritten = new StringFilter({+ clickhouseTable: table,+ field: fieldExpr,+ operator: FTS_MATCH_OPERATOR,+ value: "alpha beta",+ }).apply();++ expect(rewritten.query).toContain(`position(lower(${fieldExpr}), lower(`);+ expect(rewritten.query).toContain(`hasAllTokens(lower(${fieldExpr}),`);+ await expect(matchingIds(rewritten)).resolves.toEqual([+ `${field}-phrase-alpha-beta`,+ `${field}-phrase-alpha-beta-uppercase`,+ ]);+ },+ );++ it.each(Array.from(FTS_EVENTS_TABLES))(+ "uses case-sensitive key-scoped literal search for $table metadata matches",+ async (table) => {+ const rewritten = new StringObjectFilter({+ clickhouseTable: table,+ field: "metadata",+ operator: FTS_MATCH_OPERATOR,+ key: "topic",+ value: "alpha beta",+ tablePrefix: "e",+ }).apply();++ expect(rewritten.query).toContain("has(e.metadata_names,");+ expect(rewritten.query).toContain("hasAllTokens(e.metadata_values,");+ expect(rewritten.query).toContain(+ "position(e.metadata_values[indexOf(e.metadata_names,",+ );+ expect(rewritten.query).not.toContain(+ "hasAllTokens(e.metadata_values[indexOf",+ );+ expect(rewritten.query).not.toContain("lower(");+ await expect(matchingIds(rewritten)).resolves.toEqual([+ "metadata-phrase-alpha-beta",+ ]);+ },+ );});diff --git a/web/src/__tests__/server/observations-api-v2.servertest.ts b/web/src/__tests__/server/observations-api-v2.servertest.tsindex 5ad8ac5673..f7672757e4 100644--- a/web/src/__tests__/server/observations-api-v2.servertest.ts+++ b/web/src/__tests__/server/observations-api-v2.servertest.ts@@ -610,17 +610,22 @@ describe("/api/public/v2/observations API Endpoint", () => {expect(matchedObs?.name).toBe("nested-metadata-obs-1");});- it("supports token-based matches filters for IO and metadata", async () => {+ it("supports indexed literal matches filters for IO and metadata", async () => {const traceId = randomUUID();const timestamp = new Date();const timeValue = timestamp.getTime() * 1000;const tokenMatchId = randomUUID();const punctuationMatchId = randomUUID();const embeddedOnlyId = randomUUID();+ const ioPhraseMatchId = randomUUID();+ const ioPhraseReverseId = randomUUID();+ const ioPhraseGapId = randomUUID();const metadataCaseMatchId = randomUUID();const metadataCaseMismatchId = randomUUID();const metadataWrongKeyId = randomUUID();const metadataMultiTokenMatchId = randomUUID();+ const metadataMultiTokenReverseId = randomUUID();+ const metadataMultiTokenGapId = randomUUID();const metadataSplitAcrossValuesId = randomUUID();const metadataMultiTokenWrongKeyId = randomUUID();@@ -658,6 +663,39 @@ describe("/api/public/v2/observations API Endpoint", () => {start_time: timeValue + 2000,output: "foobarneedle cadabra",}),+ createEvent({+ id: ioPhraseMatchId,+ span_id: ioPhraseMatchId,+ trace_id: traceId,+ project_id: projectId,+ name: "io-phrase-match",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue + 3000,+ output: "prefix alpha beta suffix",+ }),+ createEvent({+ id: ioPhraseReverseId,+ span_id: ioPhraseReverseId,+ trace_id: traceId,+ project_id: projectId,+ name: "io-phrase-reverse",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue + 4000,+ output: "prefix beta alpha suffix",+ }),+ createEvent({+ id: ioPhraseGapId,+ span_id: ioPhraseGapId,+ trace_id: traceId,+ project_id: projectId,+ name: "io-phrase-gap",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue + 5000,+ output: "prefix alpha gap beta suffix",+ }),createEvent({id: metadataCaseMatchId,span_id: metadataCaseMatchId,@@ -666,7 +704,7 @@ describe("/api/public/v2/observations API Endpoint", () => {name: "metadata-case-match",type: "GENERATION",level: "DEFAULT",- start_time: timeValue + 3000,+ start_time: timeValue + 6000,metadata: { source: "needle API" },metadata_names: ["source"],metadata_values: ["needle API"],@@ -679,7 +717,7 @@ describe("/api/public/v2/observations API Endpoint", () => {name: "metadata-case-mismatch",type: "GENERATION",level: "DEFAULT",- start_time: timeValue + 4000,+ start_time: timeValue + 7000,metadata: { source: "Needle API" },metadata_names: ["source"],metadata_values: ["Needle API"],@@ -692,7 +730,7 @@ describe("/api/public/v2/observations API Endpoint", () => {name: "metadata-wrong-key",type: "GENERATION",level: "DEFAULT",- start_time: timeValue + 5000,+ start_time: timeValue + 8000,metadata: { other: "needle API" },metadata_names: ["other"],metadata_values: ["needle API"],@@ -705,11 +743,37 @@ describe("/api/public/v2/observations API Endpoint", () => {name: "metadata-multi-token-match",type: "GENERATION",level: "DEFAULT",- start_time: timeValue + 6000,+ start_time: timeValue + 9000,metadata: { source: "alpha beta" },metadata_names: ["source"],metadata_values: ["alpha beta"],}),+ createEvent({+ id: metadataMultiTokenReverseId,+ span_id: metadataMultiTokenReverseId,+ trace_id: traceId,+ project_id: projectId,+ name: "metadata-multi-token-reverse",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue + 10000,+ metadata: { source: "beta alpha" },+ metadata_names: ["source"],+ metadata_values: ["beta alpha"],+ }),+ createEvent({+ id: metadataMultiTokenGapId,+ span_id: metadataMultiTokenGapId,+ trace_id: traceId,+ project_id: projectId,+ name: "metadata-multi-token-gap",+ type: "GENERATION",+ level: "DEFAULT",+ start_time: timeValue + 11000,+ metadata: { source: "alpha gap beta" },+ metadata_names: ["source"],+ metadata_values: ["alpha gap beta"],+ }),createEvent({id: metadataSplitAcrossValuesId,span_id: metadataSplitAcrossValuesId,@@ -718,7 +782,7 @@ describe("/api/public/v2/observations API Endpoint", () => {name: "metadata-split-across-values",type: "GENERATION",level: "DEFAULT",- start_time: timeValue + 7000,+ start_time: timeValue + 12000,metadata: { source: "alpha", other: "beta" },metadata_names: ["source", "other"],metadata_values: ["alpha", "beta"],@@ -731,7 +795,7 @@ describe("/api/public/v2/observations API Endpoint", () => {name: "metadata-multi-token-wrong-key",type: "GENERATION",level: "DEFAULT",- start_time: timeValue + 8000,+ start_time: timeValue + 13000,metadata: { source: "unrelated", other: "alpha beta" },metadata_names: ["source", "other"],metadata_values: ["unrelated", "alpha beta"],@@ -744,7 +808,7 @@ describe("/api/public/v2/observations API Endpoint", () => {query: `SELECT count() as count FROM events_core WHERE project_id = {projectId: String} AND trace_id = {traceId: String}`,params: { projectId, traceId },});- expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(9);+ expect(Number(result[0]?.count)).toBeGreaterThanOrEqual(14);},5000,10,@@ -769,6 +833,24 @@ describe("/api/public/v2/observations API Endpoint", () => {);expect(ioIds).not.toContain(embeddedOnlyId);+ const ioPhraseFilterParam = JSON.stringify([+ {+ type: "string",+ column: "output",+ operator: "matches",+ value: "alpha beta",+ },+ ]);+ const ioPhraseResponse = await getObservations(+ `/api/public/v2/observations?traceId=${traceId}&fields=basic,io&filter=${encodeURIComponent(ioPhraseFilterParam)}`,+ );+ const ioPhraseIds = ioPhraseResponse.body.data.map((obs: any) => obs.id);++ expect(ioPhraseResponse.status).toBe(200);+ expect(ioPhraseIds).toContain(ioPhraseMatchId);+ expect(ioPhraseIds).not.toContain(ioPhraseReverseId);+ expect(ioPhraseIds).not.toContain(ioPhraseGapId);+const metadataFilterParam = JSON.stringify([{type: "stringObject",@@ -806,6 +888,8 @@ describe("/api/public/v2/observations API Endpoint", () => {expect(multiTokenMetadataResponse.status).toBe(200);expect(multiTokenMetadataIds).toContain(metadataMultiTokenMatchId);+ expect(multiTokenMetadataIds).not.toContain(metadataMultiTokenReverseId);+ expect(multiTokenMetadataIds).not.toContain(metadataMultiTokenGapId);expect(multiTokenMetadataIds).not.toContain(metadataSplitAcrossValuesId);expect(multiTokenMetadataIds).not.toContain(metadataMultiTokenWrongKeyId);});