Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(search): don't apply incomplete filter tokens to the query (LFE-11017) (#15315)

Nikita Kabardina48b153e904d
diff --git a/web/src/features/search-bar/lib/langQ.ts b/web/src/features/search-bar/lib/langQ.ts
index 090dd3ad60..212cc14e4a 100644
--- a/web/src/features/search-bar/lib/langQ.ts
+++ b/web/src/features/search-bar/lib/langQ.ts
@@ -19,7 +19,7 @@
import type { ASTNode, CompareOp, FilterNode, Span, TextNode } from "./ast";
import { canonicalKey, operatorIssue, resolveField } from "./fields";
-import { NEEDS_QUOTES, unquote } from "./quoting";
+import { NEEDS_QUOTES, quote, unquote } from "./quoting";
// Re-exported for back-compat: quoting primitives now live in the shared
// dependency-free `quoting.ts` (so `fields.ts` can use them too).
@@ -854,8 +854,7 @@ export function serializeValue(value: string): string {
value.startsWith("!") ||
RESERVED_BARE_TOKEN.test(value)
) {
- // Escape \ before " β€” must be the exact inverse of unquote.
- return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
+ return quote(value);
}
return value;
}
@@ -917,15 +916,31 @@ function serializeSameFieldOr(filters: FilterNode[], negated = false): string {
* (implicit AND), OR joins with " OR ", OR children inside AND get parens,
* NOT serializes as "-" before a filter and "NOT (...)" before a group.
*/
+// Serialize a free-text node. A STANDALONE word that resolves to a field name
+// is treated as an incomplete filter by the validator (LFE-11017), so it must
+// serialize QUOTED β€” otherwise a committed free-text searchQuery like `type`
+// (e.g. a legacy URL/saved view) re-derives as a red chip instead of a valid
+// literal search. `phraseInternal` is true when the word is glued to another
+// free-text word (part of a multi-word phrase like `type error`): those must
+// NOT be quoted per-word, or the phrase corrupts to `"type" error`. Mirror
+// invariant with validate.ts's standalone-field-token check.
+function serializeText(node: TextNode, phraseInternal: boolean): string {
+ if (!phraseInternal && resolveField(node.value) !== null) {
+ return quote(node.value);
+ }
+ // Otherwise route through serializeValue so bare keywords (AND/OR/NOT) and
+ // leading-operator/hyphen free text still get quoted and reparse as text.
+ return serializeValue(node.value);
+}
+
export function serialize(ast: ASTNode | null): string {
if (ast === null) return "";
switch (ast.kind) {
case "filter":
return serializeFilter(ast);
case "text":
- // Always route through serializeValue so bare keywords (AND/OR/NOT) and
- // leading-operator/hyphen free text get quoted and reparse as text.
- return serializeValue(ast.value);
+ // A top-level lone text node is standalone by definition.
+ return serializeText(ast, false);
case "not": {
const child = ast.child;
if (child.kind === "filter") return `-${serializeFilter(child)}`;
@@ -940,13 +955,23 @@ export function serialize(ast: ASTNode | null): string {
// canonical text reparses to the same structure (a bare "a b AND c"
// would flatten).
return ast.children
- .map((c) => {
+ .map((c, i) => {
if (c.kind === "or") {
return sameFieldOrGroup(c) !== null
? serialize(c)
: `(${serialize(c)})`;
}
- return c.kind === "and" ? `(${serialize(c)})` : serialize(c);
+ if (c.kind === "and") return `(${serialize(c)})`;
+ // A text child glued to a text sibling is part of a phrase β€” don't
+ // force-quote a field-name word inside it (see serializeText).
+ if (c.kind === "text") {
+ const children = ast.children;
+ const phraseInternal =
+ children[i - 1]?.kind === "text" ||
+ children[i + 1]?.kind === "text";
+ return serializeText(c, phraseInternal);
+ }
+ return serialize(c);
})
.join(" ");
case "or": {
diff --git a/web/src/features/search-bar/lib/quoting.ts b/web/src/features/search-bar/lib/quoting.ts
index 9dd120e94d..76d9f4ec13 100644
--- a/web/src/features/search-bar/lib/quoting.ts
+++ b/web/src/features/search-bar/lib/quoting.ts
@@ -12,6 +12,15 @@ function escapeQuoted(value: string): string {
return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
+/**
+ * Always wrap `value` in double quotes (escaping inner quotes/backslashes) β€”
+ * the force-quote used when a bare token would re-lex as something other than
+ * literal text (a reserved keyword, a leading operator, or a field name).
+ */
+export function quote(value: string): string {
+ return `"${escapeQuoted(value)}"`;
+}
+
/**
* Quote `value` iff it contains grammar chars, so it re-lexes as a single
* token. Used for dot-path key segments (`scores."Rouge Score"`) and is the
diff --git a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
index a9da714c84..f74250a0fb 100644
--- a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
+++ b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
@@ -55,10 +55,14 @@ const eventsView: RegistryUnderTest = {
],
fieldValues: ["x", "ERROR", "5", "0.8", "2026-06-01", "true", "a b", "gpt-4"],
// Adversarial free text β€” the tokens the parser reserves/quotes. The bare
- // boolean keywords and `!`-prefix here are the exact #4 regression class.
+ // boolean keywords and `!`-prefix here are the exact #4 regression class;
+ // the bare field words (`type`, `level`) are the LFE-11017 class β€” a lone
+ // field-name free text must serialize QUOTED so it re-parses valid.
freeTextValues: [
"hello",
"refund policy",
+ "type",
+ "level",
"or",
"and",
"not",
diff --git a/web/src/features/search-bar/lib/validate.clienttest.ts b/web/src/features/search-bar/lib/validate.clienttest.ts
index 4eba95bbf7..7d3d9a437a 100644
--- a/web/src/features/search-bar/lib/validate.clienttest.ts
+++ b/web/src/features/search-bar/lib/validate.clienttest.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { parse } from "./langQ";
+import { parse, serialize } from "./langQ";
import { semanticDiagnostics, validateQuery } from "./validate";
function warnings(query: string): string[] {
@@ -79,3 +79,122 @@ describe("validateQuery β€” merged-diagnostic dedup", () => {
},
);
});
+
+// LFE-11017: a partial filter token that isn't a complete expression must not
+// silently apply to the query. A bare field word (`type`, no operator/value)
+// used to parse as free text and lower to a full-text searchQuery, wiping the
+// results with no signal β€” while `type:` already errored. It must now be
+// treated as an incomplete filter (excluded from the query, rendered red),
+// WITHOUT flagging deliberate multi-word free-text phrases.
+describe("validateQuery β€” incomplete bare field token (LFE-11017)", () => {
+ const errors = (query: string): string[] =>
+ validateQuery(query)
+ .diagnostics.filter((d) => d.severity === "error")
+ .map((d) => d.message);
+ const isValid = (query: string): boolean => validateQuery(query).valid;
+
+ it.each(["type", "level", "env", "tags", "TYPE", "metadata.region"])(
+ "flags a lone bare field word %s as an incomplete filter",
+ (query) => {
+ expect(isValid(query)).toBe(false);
+ expect(errors(query).some((m) => m.startsWith("Incomplete filter"))).toBe(
+ true,
+ );
+ },
+ );
+
+ it("flags a bare field word appended after an existing filter (the repro)", () => {
+ expect(isValid("name:foo type")).toBe(false);
+ expect(
+ errors("name:foo type").some((m) => m.startsWith("Incomplete filter")),
+ ).toBe(true);
+ });
+
+ it("does not flag a deliberate multi-word phrase containing a field word", () => {
+ expect(isValid("type error")).toBe(true);
+ expect(isValid("session timeout")).toBe(true);
+ expect(isValid("name:foo type error")).toBe(true);
+ });
+
+ // Adjacency (nit 1): the guard is per free-text RUN, not "sole text node".
+ it("flags a standalone field word isolated by a filter, even with other free text present", () => {
+ // `type` stands alone (the filter separates it from the free text `error`),
+ // so it is still an incomplete filter even though a second free-text token
+ // exists elsewhere in the query β€” the old "exactly one text node" scoping
+ // missed this.
+ expect(isValid("type name:foo error")).toBe(false);
+ expect(
+ errors("type name:foo error").some((m) =>
+ m.startsWith("Incomplete filter"),
+ ),
+ ).toBe(true);
+ });
+
+ it("leaves a field word glued to adjacent free text as a phrase (justified)", () => {
+ // Adjacent free-text words are ONE contiguous-substring phrase; we cannot
+ // tell `hello type` (phrase) from `hello` + an incomplete `type`, and
+ // flagging a glued/trailing word would break real phrases like `error
+ // type` / `content type`. So a word glued to other free text is never
+ // flagged β€” only a word standing on its own is.
+ expect(isValid("hello type")).toBe(true);
+ expect(isValid("error type")).toBe(true);
+ expect(isValid("content type")).toBe(true);
+ });
+
+ it("does not flag a quoted field word (explicit literal text search)", () => {
+ expect(isValid('"type"')).toBe(true);
+ expect(errors('"type"')).toEqual([]);
+ });
+
+ it("does not flag free text that is not a field name", () => {
+ expect(isValid("hello")).toBe(true);
+ expect(isValid("refund policy")).toBe(true);
+ });
+
+ it("still flags the colon-but-no-value form (unchanged existing error)", () => {
+ // `type:` keeps its own "Missing value" error β€” NOT the incomplete-filter one.
+ const msgs = errors("type:");
+ expect(msgs).toContain('Missing value after "type:"');
+ expect(msgs.some((m) => m.startsWith("Incomplete filter"))).toBe(false);
+ });
+
+ it("accepts a complete expression", () => {
+ expect(isValid("type:chat")).toBe(true);
+ expect(isValid("name:foo type:chat")).toBe(true);
+ });
+
+ it("round-trips a committed field-word free text as a quoted literal", () => {
+ // The reverse of the guard: a legacy searchQuery=`type` must serialize as
+ // `"type"` so it re-derives valid, not as a bare token that lands red.
+ const text = serialize({ kind: "text", value: "type" });
+ expect(text).toBe('"type"');
+ expect(isValid(text)).toBe(true);
+ });
+
+ // Serializer adjacency (nit 2): the field-name force-quote must be per-run,
+ // not per-word β€” a phrase word must NOT be quoted in isolation.
+ it("does not corrupt a multi-word phrase when serializing (no per-word quoting)", () => {
+ // Would have produced `"type" error` / `"session" timeout` before the fix.
+ expect(serialize(parse("type error").ast)).toBe("type error");
+ expect(serialize(parse("session timeout").ast)).toBe("session timeout");
+ expect(serialize(parse("error type").ast)).toBe("error type");
+ // …and each still re-parses valid (no red chip).
+ expect(isValid("type error")).toBe(true);
+ expect(isValid("session timeout")).toBe(true);
+ });
+
+ it("force-quotes a standalone field word beside a filter so the derive stays valid", () => {
+ // A searchQuery of `type` alongside a filter derives to `name:foo "type"`,
+ // not the red `name:foo type`. The word is standalone (a filter separates
+ // it), so it IS quoted β€” the phrase carve-out above does not apply.
+ const text = serialize({
+ kind: "and",
+ children: [
+ { kind: "filter", key: "name", op: "=", values: ["foo"] },
+ { kind: "text", value: "type" },
+ ],
+ });
+ expect(text).toContain('"type"');
+ expect(isValid(text)).toBe(true);
+ });
+});
diff --git a/web/src/features/search-bar/lib/validate.ts b/web/src/features/search-bar/lib/validate.ts
index 9b9180ae14..7859e51182 100644
--- a/web/src/features/search-bar/lib/validate.ts
+++ b/web/src/features/search-bar/lib/validate.ts
@@ -10,7 +10,7 @@
// span. `valid === true` therefore guarantees astToFilterState() lowers the
// whole query without errors.
-import type { ASTNode, Span } from "./ast";
+import type { ASTNode, Span, TextNode } from "./ast";
import { astToFilterState, type ScoreTypeContext } from "./adapter";
import { nullableFields, resolveField } from "./fields";
import { parse, type Diagnostic, type ParseResult } from "./langQ";
@@ -84,6 +84,81 @@ function hasFilterWarnings(
}
}
+/**
+ * Collect STANDALONE free-text nodes β€” a text node that is NOT immediately
+ * adjacent (within its containing AND/OR group) to another free-text node. A
+ * run of adjacent free-text words is one contiguous phrase (`type error`), so
+ * only a word standing on its own β€” alone, or isolated from other free text by
+ * a filter (`name:x type`, `type name:x error`) β€” is a candidate incomplete
+ * filter. `serializeText` in langQ.ts force-quotes with the SAME standalone
+ * rule so the flag and the round-trip quoting stay in lockstep (mirror
+ * invariant).
+ */
+function collectStandaloneTextNodes(node: ASTNode, out: TextNode[]): void {
+ switch (node.kind) {
+ case "text":
+ out.push(node); // top-level / sole child β€” standalone by definition
+ return;
+ case "not":
+ collectStandaloneTextNodes(node.child, out);
+ return;
+ case "and":
+ case "or": {
+ const kids = node.children;
+ for (let i = 0; i < kids.length; i++) {
+ const c = kids[i]!;
+ if (c.kind !== "text") {
+ collectStandaloneTextNodes(c, out);
+ continue;
+ }
+ // Adjacent to another free-text word β‡’ part of a phrase, not a
+ // standalone token β€” skip it.
+ const glued =
+ kids[i - 1]?.kind === "text" || kids[i + 1]?.kind === "text";
+ if (!glued) out.push(c);
+ }
+ return;
+ }
+ case "filter":
+ return;
+ }
+}
+
+/**
+ * A bare word that resolves to a field name (`type`, `level`, `env`, …) is
+ * almost always a filter the user started and did not finish β€” not free text.
+ * Left as free text it silently lowers to a full-text `searchQuery` and wipes
+ * the results with no signal (LFE-11017), while the analogous `type:` (colon, no
+ * value) already errors. Treat it as an incomplete filter so it renders red and
+ * is excluded from the query, consistent with the dangling dot-prefix guard
+ * (`metadata.`) in the adapter.
+ *
+ * Scoped to STANDALONE free-text tokens (see `collectStandaloneTextNodes`): a
+ * deliberate multi-word phrase that happens to contain a field word ("type
+ * error", "content type") is one contiguous-substring `searchQuery`, not a
+ * filter, so it is left untouched β€” a word glued to other free text is never
+ * flagged. Quoting escapes a single word back to literal text (`"type"`) β€” the
+ * same escape hatch the reserved keywords (`and`/`or`/`not`) use, and the reason
+ * the serializer force-quotes a standalone field-name free-text value.
+ */
+function incompleteFieldTokenDiagnostics(
+ ast: ASTNode,
+ out: Diagnostic[],
+): void {
+ const texts: TextNode[] = [];
+ collectStandaloneTextNodes(ast, texts);
+ for (const node of texts) {
+ if (node.quoted || node.span === undefined) continue;
+ if (resolveField(node.value) === null) continue;
+ out.push({
+ from: node.span.from,
+ to: node.span.to,
+ severity: "error",
+ message: `Incomplete filter "${node.value}" β€” add a value (e.g. ${node.value}:value) or quote "${node.value}" to search as text`,
+ });
+ }
+}
+
export function semanticDiagnostics(
ast: ASTNode | null,
textLength: number,
@@ -92,6 +167,11 @@ export function semanticDiagnostics(
const out: Diagnostic[] = [];
if (ast === null) return out;
+ // A standalone bare field-name word (no operator/value) is an incomplete
+ // filter, not free text β€” checked over the WHOLE tree (not per top-level
+ // node) so the adjacency scoping can see each text node's siblings.
+ incompleteFieldTokenDiagnostics(ast, out);
+
// Lower each top-level node independently so error spans point at the
// offending node instead of the whole query. The lowering must see the same
// scoreTypes the commit-time lowering does, or the two disagree on score