πͺ’ 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(search-bar): recover self-corrected filter arrays in Ask AI parser (LFE-11007) (#15165)
Nikita Kabardin3d8a819203ee
diff --git a/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.tsindex ef504315b9..44cd772c6c 100644--- a/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts+++ b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts@@ -353,4 +353,180 @@ describe("parseGeneratedFilters β score-name validation", () => {const { unknownScoreNames } = parseGeneratedFilters(completion, scoreNames);expect(unknownScoreNames).toEqual(["ghost_score"]);});++ const booleanScoreFilter = (column: string, key: string) => ({+ type: "booleanObject",+ column,+ key,+ operator: "=",+ value: true,+ });++ it("corrects a separator variant of a boolean score name in place", () => {+ // Same dead-filter class as numeric/categorical: a boolean score addressed+ // by a misspelled name round-trips cleanly and matches nothing. The+ // observed set (`score_booleans`) lets us correct it.+ const completion = JSON.stringify([+ booleanScoreFilter("score_booleans", "is_flagged"),+ ]);+ const { filters, droppedCount, unknownScoreNames } = parseGeneratedFilters(+ completion,+ { ...scoreNames, booleans: ["is-flagged"] },+ );+ expect(filters).toHaveLength(1);+ expect(filters[0]).toMatchObject({+ column: "score_booleans",+ key: "is-flagged",+ });+ expect(droppedCount).toBe(0);+ expect(unknownScoreNames).toEqual([]);+ });++ it("drops an unknown trace-boolean score name and reports it", () => {+ const completion = JSON.stringify([+ booleanScoreFilter("trace_score_booleans", "ghost_flag"),+ ]);+ const { filters, droppedCount, unknownScoreNames } = parseGeneratedFilters(+ completion,+ { ...scoreNames, traceBooleans: ["is-reviewed"] },+ );+ expect(filters).toHaveLength(0);+ expect(droppedCount).toBe(1);+ expect(unknownScoreNames).toEqual(["ghost_flag"]);+ });++ it("passes a boolean score filter through when its set was not provided", () => {+ // No `booleans` set loaded β no enforcement for that column (a boolean+ // score filter must never be dropped just because the set is absent).+ const completion = JSON.stringify([+ booleanScoreFilter("score_booleans", "anything_goes"),+ ]);+ const { filters, unknownScoreNames } = parseGeneratedFilters(completion, {+ numeric: ["accuracy"],+ });+ expect(filters).toHaveLength(1);+ expect(filters[0]).toMatchObject({ key: "anything_goes" });+ expect(unknownScoreNames).toEqual([]);+ });+});++describe("parseGeneratedFilters β extraction robustness", () => {+ const levelFilter = (value: string) => ({+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: [value],+ });++ it("applies the model's self-corrected array, not the earlier draft", () => {+ // The model drafts an array, second-guesses itself in prose, then emits a+ // corrected array. A greedy first-`[`..last-`]` match spans BOTH arrays plus+ // the prose between them and fails to JSON.parse β losing a correct answer.+ // The parser must return the LAST (corrected) array.+ const completion = [+ "Here is a first attempt:",+ JSON.stringify([levelFilter("DEBUG")]),+ "On reflection you asked for errors, not debug logs. Corrected filters:",+ JSON.stringify([levelFilter("ERROR")]),+ ].join("\n");+ const { filters, droppedCount } = parseGeneratedFilters(completion);+ expect(filters).toHaveLength(1);+ expect(filters[0]).toMatchObject({ column: "level", value: ["ERROR"] });+ expect(droppedCount).toBe(0);+ });++ it("parses a single array embedded in prose unchanged", () => {+ const completion = [+ "Sure β here you go:",+ JSON.stringify([levelFilter("WARNING")]),+ ].join("\n");+ const { filters, droppedCount } = parseGeneratedFilters(completion);+ expect(filters).toHaveLength(1);+ expect(filters[0]).toMatchObject({ column: "level", value: ["WARNING"] });+ expect(droppedCount).toBe(0);+ });++ it("does not let a `]` inside a string value break balance tracking", () => {+ // The closing bracket lives inside a metadata value string; naive depth+ // tracking would close the array early and fail to parse.+ const completion = [+ "Filters:",+ JSON.stringify([+ {+ type: "stringObject",+ column: "metadata",+ key: "note",+ operator: "=",+ value: "arr]end",+ },+ ]),+ "Let me know if that works.",+ ].join("\n");+ const { filters, droppedCount } = parseGeneratedFilters(completion);+ expect(filters).toHaveLength(1);+ expect(filters[0]).toMatchObject({+ column: "metadata",+ key: "note",+ value: "arr]end",+ });+ expect(droppedCount).toBe(0);+ });++ it("returns the empty result when brackets appear but no array is valid JSON", () => {+ const completion =+ "Use the [level] and [environment] fields to build that filter.";+ const { filters, queryText, droppedCount } =+ parseGeneratedFilters(completion);+ expect(filters).toHaveLength(0);+ expect(queryText).toBe("");+ expect(droppedCount).toBe(0);+ });++ it("honors an explicit `[]` retraction over an earlier drafted filter", () => {+ // The prompt asks for `[]` when no filter applies. If the model drafts a+ // filter, reconsiders in prose, then emits `[]` as its FINAL answer, we must+ // honor the retraction β NOT apply the draft it explicitly walked back.+ const completion =+ "Attempt: " ++ JSON.stringify([+ {+ type: "stringOptions",+ column: "level",+ operator: "any of",+ value: ["ERROR"],+ },+ ]) ++ " Actually that cannot be expressed here. No filter applies: []";+ const { filters, droppedCount } = parseGeneratedFilters(completion);+ expect(filters).toHaveLength(0);+ expect(droppedCount).toBe(0);+ });++ it("reports the LARGEST all-malformed array's size when nothing validates", () => {+ // Reversed candidate iteration visits the trailing stray array first. When+ // NO candidate yields a valid filter, `droppedCount` must reflect the+ // largest array the model emitted (the one it most plausibly intended), not+ // whichever was visited first. Here a 4-element all-malformed filter array+ // precedes a stray 2-element prose list; the count must be 4, not 2.+ const malformed = (column: string) => ({+ type: "stringOptions",+ column,+ operator: "equals", // not a valid stringOptions operator β fails singleFilter+ value: "x",+ });+ const completion = [+ "My first attempt (four filters):",+ JSON.stringify([+ malformed("level"),+ malformed("environment"),+ malformed("name"),+ malformed("userId"),+ ]),+ "Actually, ignore those and just consider these two tags:",+ JSON.stringify(["a", "b"]),+ ].join("\n");+ const { filters, droppedCount } = parseGeneratedFilters(completion);+ expect(filters).toHaveLength(0);+ expect(droppedCount).toBe(4);+ });});diff --git a/web/src/features/search-bar/lib/observed-options.ts b/web/src/features/search-bar/lib/observed-options.tsindex 9637d86431..b3cb98cca4 100644--- a/web/src/features/search-bar/lib/observed-options.ts+++ b/web/src/features/search-bar/lib/observed-options.ts@@ -137,8 +137,10 @@ export const MAX_SCORE_NAME_LENGTH = 256;export type ObservedScoreNames = {numeric?: string[];categorical?: string[];+ booleans?: string[];traceNumeric?: string[];traceCategorical?: string[];+ traceBooleans?: string[];};/**@@ -167,8 +169,10 @@ export function observedScoreNamesFromOptions(return {numeric: names("scores_avg"),categorical: names("score_categories"),+ booleans: names("score_booleans"),traceNumeric: names("trace_scores_avg"),traceCategorical: names("trace_score_categories"),+ traceBooleans: names("trace_score_booleans"),};}diff --git a/web/src/features/search-bar/server/parseFilterCompletion.ts b/web/src/features/search-bar/server/parseFilterCompletion.tsindex b626b0fcf5..cba9fad6eb 100644--- a/web/src/features/search-bar/server/parseFilterCompletion.ts+++ b/web/src/features/search-bar/server/parseFilterCompletion.ts@@ -51,44 +51,118 @@ function isEventsContractCompatible(f: FilterState[number]): boolean {}/**- * Extract a `FilterState` from the model's completion. Tries the whole string,- * then the widest bracketed array (greedy, so it survives nested objects), and- * tolerates a `{ "filters": [...] }` wrapper. Returns the structurally-valid+ * Scan `text` for balanced, top-level `[...]` substrings. Tracks bracket depth+ * while treating brackets inside JSON string literals as inert, so a `]` in a+ * value (`"array[0]"`) never closes an array early. Nested arrays (a value+ * array inside a filter object, depth > 1) are part of their enclosing+ * top-level array, not returned on their own. Returned in document order.+ */+function extractTopLevelArrays(text: string): string[] {+ const arrays: string[] = [];+ let depth = 0;+ let start = -1;+ let inString = false;+ let escaped = false;+ for (let i = 0; i < text.length; i++) {+ const ch = text[i];+ if (inString) {+ // Inside a string literal only `\` (escape) and an unescaped `"` (close)+ // are meaningful; brackets here must not move the depth.+ if (escaped) escaped = false;+ else if (ch === "\\") escaped = true;+ else if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') {+ inString = true;+ } else if (ch === "[") {+ if (depth === 0) start = i;+ depth++;+ } else if (ch === "]" && depth > 0) {+ depth--;+ if (depth === 0 && start !== -1) {+ arrays.push(text.slice(start, i + 1));+ start = -1;+ }+ }+ }+ return arrays;+}++/**+ * Extract a `FilterState` from the model's completion. Tries the whole string+ * (a bare array or a `{ "filters": [...] }` wrapper) first, then every balanced+ * top-level `[...]` in the prose, LAST-FIRST. Returns the structurally-valid* filters plus `rawCount` (how many elements the model actually emitted), so* the caller can count the malformed ones as dropped. `rawCount` is 0 when* nothing parses.+ *+ * Last-first matters: the model sometimes emits a DRAFT array, some prose, then+ * a corrected SECOND array (self-correction). A single greedy `\[[\s\S]*\]`+ * match spans from the first `[` to the last `]` β swallowing both arrays plus+ * the prose between them, so `JSON.parse` fails and a correct answer is lost.+ * Scanning balanced candidates and trying the LAST one first applies the+ * model's self-correction instead of discarding it.*/function parseFilterArray(completion: string): {filters: FilterState;rawCount: number;} {- const arrayMatch = completion.match(/\[[\s\S]*\]/)?.[0];- const candidates = [completion, arrayMatch].filter((c): c is string =>- Boolean(c),- );+ const candidates = [+ completion,+ ...extractTopLevelArrays(completion).reverse(),+ ];+ // A candidate that parses to a NON-EMPTY array but holds no structurally-valid+ // filter (e.g. an all-malformed array, or a stray bracketed list in the prose)+ // is remembered so `rawCount` still reflects what the model emitted, but it+ // does NOT win over a later candidate that DOES contain a valid filter. This+ // keeps a trailing non-filter array (`... use the [ERROR] level`) from+ // shadowing the real filter array that preceded it.+ let fallback: { filters: FilterState; rawCount: number } | null = null;for (const candidate of candidates) {+ let parsed: unknown;try {- const parsed = JSON.parse(candidate);- const raw = Array.isArray(parsed) ? parsed : parsed.filters;- if (!Array.isArray(raw)) continue;- // Parse PER ELEMENT, not the whole array: `z.array(singleFilter).parse`- // is all-or-nothing, so one off-spec element (wrong operator, missing- // key, value-as-string, unknown type β common on weaker models) would- // discard the valid siblings and surface a misleading "couldn't build- // filters". Keep the structurally-valid ones; the rejects show up in the- // dropped count below, mirroring the per-element keep/drop the two- // downstream guardrails already use.- const kept: FilterState = [];- for (const item of raw) {- const result = singleFilter.safeParse(item);- if (result.success) kept.push(result.data);- }- return { filters: kept, rawCount: raw.length };+ parsed = JSON.parse(candidate);} catch {- // try the next candidate+ continue;+ }+ const raw = Array.isArray(parsed)+ ? parsed+ : (parsed as { filters?: unknown } | null)?.filters;+ if (!Array.isArray(raw)) continue;+ // An explicitly EMPTY array is the model's "no filter applies" answer (the+ // prompt asks for `[]` in exactly that case). Honor it as a real answer that+ // WINS: return immediately rather than falling through to an earlier draft+ // the model reconsidered β otherwise we'd silently apply a filter it+ // retracted. Distinct from a non-empty array that yields no VALID filter+ // (below): that stays a fallback so a stray prose list can't shadow a real+ // earlier filter array. Last-first order means a trailing `[]` is the+ // model's FINAL word, so this is safe to treat as the intended retraction.+ if (raw.length === 0) return { filters: [], rawCount: 0 };+ // Parse PER ELEMENT, not the whole array: `z.array(singleFilter).parse`+ // is all-or-nothing, so one off-spec element (wrong operator, missing+ // key, value-as-string, unknown type β common on weaker models) would+ // discard the valid siblings and surface a misleading "couldn't build+ // filters". Keep the structurally-valid ones; the rejects show up in the+ // dropped count below, mirroring the per-element keep/drop the two+ // downstream guardrails already use.+ const kept: FilterState = [];+ for (const item of raw) {+ const result = singleFilter.safeParse(item);+ if (result.success) kept.push(result.data);+ }+ if (kept.length > 0) return { filters: kept, rawCount: raw.length };+ // Had elements, none valid. Remember the LARGEST such array as the fallback:+ // when nothing validates, `droppedCount` should reflect the biggest array+ // the model emitted (the one it most plausibly intended as the answer), not+ // whichever candidate happened to be visited first. Reversed iteration+ // visits the last text array first, which might be a stray 2-element prose+ // list while the intended (all-malformed) array had more elements.+ if (fallback === null || raw.length > fallback.rawCount) {+ fallback = { filters: [], rawCount: raw.length };}}- return { filters: [], rawCount: 0 };+ return fallback ?? { filters: [], rawCount: 0 };}// Which ObservedScoreNames set holds the real names for each score column β@@ -99,8 +173,10 @@ const SCORE_NAME_SET_BY_COLUMN: Record<> = {[SCORE_COLUMNS.observation.numeric]: "numeric",[SCORE_COLUMNS.observation.categorical]: "categorical",+ [SCORE_COLUMNS.observation.boolean]: "booleans",[SCORE_COLUMNS.trace.numeric]: "traceNumeric",[SCORE_COLUMNS.trace.categorical]: "traceCategorical",+ [SCORE_COLUMNS.trace.boolean]: "traceBooleans",};// Case/separator-insensitive form for the confident-correction match:@@ -145,7 +221,11 @@ function validateScoreNames(const kept: FilterState = [];const unknown: string[] = [];for (const filter of filters) {- if (filter.type !== "numberObject" && filter.type !== "categoryOptions") {+ if (+ filter.type !== "numberObject" &&+ filter.type !== "categoryOptions" &&+ filter.type !== "booleanObject"+ ) {kept.push(filter);continue;}diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.tsindex 4435527ae8..3837df5a32 100644--- a/web/src/features/search-bar/server/router.ts+++ b/web/src/features/search-bar/server/router.ts@@ -57,8 +57,10 @@ const GenerateFilterInput = z.object({.object({numeric: scoreNameList.optional(),categorical: scoreNameList.optional(),+ booleans: scoreNameList.optional(),traceNumeric: scoreNameList.optional(),traceCategorical: scoreNameList.optional(),+ traceBooleans: scoreNameList.optional(),}).optional(),});