Skip to content

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

fix(search-bar): validate AI-generated score names against observed scores (LFE-10646) (#14813)

Nikita Kabardineb4e48d3d9b3
diff --git a/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
index 66785385c9..ef504315b9 100644
--- a/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
+++ b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
@@ -168,3 +168,189 @@ describe("parseGeneratedFilters", () => {
expect(droppedCount).toBe(0);
});
});
+
+describe("parseGeneratedFilters β€” score-name validation", () => {
+ // The observed score names by column type, as the client threads them from
+ // filterOptions. A field left undefined means "not loaded" β†’ no enforcement
+ // for that column.
+ const scoreNames = {
+ numeric: ["helpfulness-rating", "accuracy"],
+ categorical: ["sentiment"],
+ traceNumeric: ["overall-quality"],
+ traceCategorical: ["Hallucination Check"],
+ };
+
+ const numericScoreFilter = (key: string) => ({
+ type: "numberObject",
+ column: "scores_avg",
+ key,
+ operator: ">",
+ value: 0.8,
+ });
+
+ it("keeps an exactly-matching score name untouched", () => {
+ const completion = JSON.stringify([numericScoreFilter("accuracy")]);
+ const { filters, droppedCount, unknownScoreNames } = parseGeneratedFilters(
+ completion,
+ scoreNames,
+ );
+ expect(filters).toHaveLength(1);
+ expect(filters[0]).toMatchObject({ key: "accuracy" });
+ expect(droppedCount).toBe(0);
+ expect(unknownScoreNames).toEqual([]);
+ });
+
+ it("corrects underscore notation to the real hyphenated score name", () => {
+ // The motivating bug: the user wrote `helpfulness_rating`, the real score
+ // is `helpfulness-rating`, and the dead filter silently returned zero rows.
+ const completion = JSON.stringify([
+ numericScoreFilter("helpfulness_rating"),
+ ]);
+ const { filters, queryText, droppedCount, unknownScoreNames } =
+ parseGeneratedFilters(completion, scoreNames);
+ expect(filters).toHaveLength(1);
+ expect(filters[0]).toMatchObject({
+ column: "scores_avg",
+ key: "helpfulness-rating",
+ });
+ expect(queryText).toContain("helpfulness-rating");
+ expect(droppedCount).toBe(0);
+ expect(unknownScoreNames).toEqual([]);
+ });
+
+ it("corrects case/space/separator variants, preserving the column's level", () => {
+ const completion = JSON.stringify([
+ {
+ type: "categoryOptions",
+ column: "trace_score_categories",
+ key: "hallucination_check",
+ operator: "any of",
+ value: ["faithful"],
+ },
+ {
+ type: "numberObject",
+ column: "trace_scores_avg",
+ key: "Overall Quality",
+ operator: "<",
+ value: 0.5,
+ },
+ ]);
+ const { filters, droppedCount } = parseGeneratedFilters(
+ completion,
+ scoreNames,
+ );
+ expect(filters).toHaveLength(2);
+ expect(filters[0]).toMatchObject({
+ column: "trace_score_categories",
+ key: "Hallucination Check",
+ });
+ expect(filters[1]).toMatchObject({
+ column: "trace_scores_avg",
+ key: "overall-quality",
+ });
+ expect(droppedCount).toBe(0);
+ });
+
+ it("drops an unknown score name, reports it, and keeps valid siblings", () => {
+ const completion = JSON.stringify([
+ numericScoreFilter("nonexistent_score"),
+ {
+ type: "stringOptions",
+ column: "level",
+ operator: "any of",
+ value: ["ERROR"],
+ },
+ ]);
+ const { filters, droppedCount, unknownScoreNames } = parseGeneratedFilters(
+ completion,
+ scoreNames,
+ );
+ expect(filters).toHaveLength(1);
+ expect(filters[0]?.column).toBe("level");
+ expect(droppedCount).toBe(1);
+ expect(unknownScoreNames).toEqual(["nonexistent_score"]);
+ });
+
+ it("does not rescue a name across score types (numeric stays numeric)", () => {
+ // `sentiment` exists only as a categorical score; a numberObject filter on
+ // it cannot be corrected in place (operator/value shapes differ), so it is
+ // dropped and reported rather than silently retyped.
+ const completion = JSON.stringify([numericScoreFilter("sentiment")]);
+ const { filters, droppedCount, unknownScoreNames } = parseGeneratedFilters(
+ completion,
+ scoreNames,
+ );
+ expect(filters).toHaveLength(0);
+ expect(droppedCount).toBe(1);
+ expect(unknownScoreNames).toEqual(["sentiment"]);
+ });
+
+ it("drops when the normalized name is ambiguous between two real scores", () => {
+ const completion = JSON.stringify([numericScoreFilter("My Score")]);
+ const { filters, unknownScoreNames } = parseGeneratedFilters(completion, {
+ ...scoreNames,
+ numeric: ["my-score", "my_score"],
+ });
+ expect(filters).toHaveLength(0);
+ expect(unknownScoreNames).toEqual(["My Score"]);
+ });
+
+ it("still keeps an exact match when its normalization is ambiguous", () => {
+ const completion = JSON.stringify([numericScoreFilter("my_score")]);
+ const { filters, unknownScoreNames } = parseGeneratedFilters(completion, {
+ ...scoreNames,
+ numeric: ["my-score", "my_score"],
+ });
+ expect(filters).toHaveLength(1);
+ expect(filters[0]).toMatchObject({ key: "my_score" });
+ expect(unknownScoreNames).toEqual([]);
+ });
+
+ it("skips enforcement for a column whose name set was not provided", () => {
+ // Only the numeric sets are loaded; the categorical filter passes through
+ // unvalidated (its filter-options column has not loaded on the client).
+ const completion = JSON.stringify([
+ {
+ type: "categoryOptions",
+ column: "score_categories",
+ key: "anything_goes",
+ operator: "any of",
+ value: ["yes"],
+ },
+ ]);
+ const { filters, unknownScoreNames } = parseGeneratedFilters(completion, {
+ numeric: ["accuracy"],
+ });
+ expect(filters).toHaveLength(1);
+ expect(filters[0]).toMatchObject({ key: "anything_goes" });
+ expect(unknownScoreNames).toEqual([]);
+ });
+
+ it("skips enforcement entirely when no score-name context is passed", () => {
+ const completion = JSON.stringify([numericScoreFilter("anything_goes")]);
+ const { filters, unknownScoreNames } = parseGeneratedFilters(completion);
+ expect(filters).toHaveLength(1);
+ expect(filters[0]).toMatchObject({ key: "anything_goes" });
+ expect(unknownScoreNames).toEqual([]);
+ });
+
+ it("drops every score filter when the loaded set is empty (project has none)", () => {
+ const completion = JSON.stringify([numericScoreFilter("accuracy")]);
+ const { filters, droppedCount, unknownScoreNames } = parseGeneratedFilters(
+ completion,
+ { ...scoreNames, numeric: [] },
+ );
+ expect(filters).toHaveLength(0);
+ expect(droppedCount).toBe(1);
+ expect(unknownScoreNames).toEqual(["accuracy"]);
+ });
+
+ it("dedupes repeated unknown names in the report", () => {
+ const completion = JSON.stringify([
+ numericScoreFilter("ghost_score"),
+ { ...numericScoreFilter("ghost_score"), operator: "<", value: 0.2 },
+ ]);
+ const { unknownScoreNames } = parseGeneratedFilters(completion, scoreNames);
+ expect(unknownScoreNames).toEqual(["ghost_score"]);
+ });
+});
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsx
index 3b10c16b3a..6cbfc41037 100644
--- a/web/src/features/events/components/EventsTable.tsx
+++ b/web/src/features/events/components/EventsTable.tsx
@@ -112,7 +112,10 @@ import { useSearchBarEnabled } from "@/src/features/search-bar/hooks/useSearchBa
import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSearchBar";
import { EventsSearchBarRow } from "@/src/features/search-bar/components/EventsSearchBarRow";
import { buildAiContext } from "@/src/features/search-bar/lib/ai-context";
-import { toObservedOptions } from "@/src/features/search-bar/lib/observed-options";
+import {
+ observedScoreNamesFromOptions,
+ toObservedOptions,
+} from "@/src/features/search-bar/lib/observed-options";
import { CategoryPresetChips } from "@/src/features/events/components/CategoryPresetChips";
import { TableViewPresetsDrawer } from "@/src/components/table/table-view-presets/components/data-table-view-presets-drawer";
import { withMetadataPathOptions } from "@/src/features/search-bar/lib/metadata-paths";
@@ -688,6 +691,19 @@ export default function ObservationsEventsTable({
});
}, [searchBarMode, observedOptions, observations.rows, observations.status]);
+ // Observed score names by column type for the AI endpoint's score-name
+ // guardrail: the server validates/corrects the score keys the model returns
+ // against these. Structured (not re-parsed from the flattened dataContext
+ // above), and each set stays undefined until its filter-options column has
+ // loaded, so an in-flight fetch never makes a real score name look unknown.
+ const aiScoreNames = useMemo(
+ () =>
+ searchBarMode
+ ? observedScoreNamesFromOptions(observedOptions)
+ : undefined,
+ [searchBarMode, observedOptions],
+ );
+
const { scoreColumns, isLoading: isColumnLoading } =
useScoreColumns<EventsTableRow>({
scoreColumnKey: "scores",
@@ -1691,6 +1707,7 @@ export default function ObservationsEventsTable({
onApplyFilters={searchBarApplyFilters}
onRequestColumns={requestColumns}
aiDataContext={aiDataContext}
+ aiScoreNames={aiScoreNames}
/>
)}
{/* Toolbar spanning full width */}
diff --git a/web/src/features/search-bar/components/EventsSearchBarRow.tsx b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
index bb13aedc25..855051e461 100644
--- a/web/src/features/search-bar/components/EventsSearchBarRow.tsx
+++ b/web/src/features/search-bar/components/EventsSearchBarRow.tsx
@@ -18,7 +18,10 @@ import * as React from "react";
import { type FilterState } from "@langfuse/shared";
import { useLangfuseCloudRegion } from "@/src/features/organizations/hooks";
import { useQueryProject } from "@/src/features/projects/hooks";
-import type { ObservedOptions } from "@/src/features/search-bar/lib/observed-options";
+import type {
+ ObservedOptions,
+ ObservedScoreNames,
+} from "@/src/features/search-bar/lib/observed-options";
import { AI_GROUNDING_COLUMNS } from "@/src/features/search-bar/lib/ai-context";
import { ComposerWithPreview } from "@/src/features/search-bar/components/ComposerWithPreview";
import { SearchBarAiPrompt } from "@/src/features/search-bar/components/SearchBarAiPrompt";
@@ -34,6 +37,7 @@ export function EventsSearchBarRow({
onApplyFilters,
onRequestColumns,
aiDataContext,
+ aiScoreNames,
}: {
projectId: string;
store: SearchBarStore;
@@ -58,6 +62,9 @@ export function EventsSearchBarRow({
/** Project data context (observed values + metadata keys + result count) for
* the AI prompt β€” built by EventsTable from filterOptions + visible rows. */
aiDataContext?: string;
+ /** Observed score names by column type, for the server's score-name
+ * validation of the generated filters (undefined sets are not enforced). */
+ aiScoreNames?: ObservedScoreNames;
}) {
const [aiOpen, setAiOpen] = React.useState(false);
const { isLangfuseCloud } = useLangfuseCloudRegion();
@@ -81,6 +88,7 @@ export function EventsSearchBarRow({
projectId={projectId}
store={store}
dataContext={aiDataContext}
+ scoreNames={aiScoreNames}
onApply={onApplyFilters}
onExit={() => setAiOpen(false)}
/>
diff --git a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
index 3dd410ddbf..8896b2a1c6 100644
--- a/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
+++ b/web/src/features/search-bar/components/SearchBarAiPrompt.tsx
@@ -20,14 +20,26 @@ import { useStore } from "zustand";
import { type FilterState } from "@langfuse/shared";
import { KeyboardShortcut } from "@/src/components/ui/keyboard-shortcut";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import type { ObservedScoreNames } from "@/src/features/search-bar/lib/observed-options";
import type { SearchBarStore } from "@/src/features/search-bar/store/searchBarStore";
import { api } from "@/src/utils/api";
import { cn } from "@/src/utils/tailwind";
+// "No such score X" note for score filters the server dropped because their
+// name matches no observed score (exactly or normalized).
+function unknownScoresMessage(names: string[]): string {
+ const quoted = names.map((n) => `"${n}"`).join(", ");
+ return names.length === 1
+ ? `No score named ${quoted} exists in this project β€” that filter was not applied.`
+ : `No scores named ${quoted} exist in this project β€” those filters were not applied.`;
+}
+
export function SearchBarAiPrompt({
projectId,
store,
dataContext,
+ scoreNames,
onApply,
onExit,
}: {
@@ -37,6 +49,10 @@ export function SearchBarAiPrompt({
/** Observed values + metadata keys + result count, so the model maps to the
* project's real columns/values instead of guessing. */
dataContext?: string;
+ /** Observed score names by column type β€” the server validates/corrects the
+ * model's returned score keys against these (a misspelled name would
+ * otherwise apply as a dead filter that silently matches nothing). */
+ scoreNames?: ObservedScoreNames;
/** Apply generated filters via the bar's setFilterState (apply-immediately). */
onApply: (filters: FilterState) => void;
/** Leave AI mode and restore the grammar composer. */
@@ -97,6 +113,7 @@ export function SearchBarAiPrompt({
prompt,
currentQuery: refine.length > 0 ? refine : undefined,
dataContext,
+ scoreNames,
});
// Cancelled mid-flight (Back clicked while generating): don't apply.
if (cancelledRef.current) return;
@@ -110,10 +127,25 @@ export function SearchBarAiPrompt({
return;
}
if (result.filters.length === 0) {
- setError("Couldn't build filters from that β€” try rephrasing.");
+ // A dropped unknown score name explains the empty result better than
+ // the generic rephrase hint ("no such score X" beats a dead filter).
+ setError(
+ result.unknownScoreNames.length > 0
+ ? unknownScoresMessage(result.unknownScoreNames)
+ : "Couldn't build filters from that β€” try rephrasing.",
+ );
return;
}
onApply(result.filters as FilterState);
+ if (result.unknownScoreNames.length > 0) {
+ // Partial apply: the rest of the filters went through, so exit as
+ // usual but surface which score clause was dropped and why.
+ showErrorToast(
+ "Score filter skipped",
+ unknownScoresMessage(result.unknownScoreNames),
+ "WARNING",
+ );
+ }
onExit();
} catch {
if (cancelledRef.current) return;
diff --git a/web/src/features/search-bar/lib/ai-context.clienttest.ts b/web/src/features/search-bar/lib/ai-context.clienttest.ts
index fb47d620c9..a6b5ae6b2d 100644
--- a/web/src/features/search-bar/lib/ai-context.clienttest.ts
+++ b/web/src/features/search-bar/lib/ai-context.clienttest.ts
@@ -82,6 +82,28 @@ describe("buildAiContext", () => {
expect(ctx).toContain("metadata.customer.plan");
});
+ it("lists observed score names per column and level", () => {
+ const ctx =
+ buildAiContext({
+ observed: {
+ scores_avg: [{ value: "helpfulness-rating" }, { value: "accuracy" }],
+ score_categories: [{ value: "sentiment" }],
+ trace_scores_avg: [{ value: "overall-quality" }],
+ trace_score_categories: [{ value: "Hallucination Check" }],
+ },
+ sampleMetadata: [],
+ resultCount: null,
+ }) ?? "";
+ expect(ctx).toContain(
+ "scores.<name> (numeric): helpfulness-rating, accuracy",
+ );
+ expect(ctx).toContain("scores.<name> (categorical): sentiment");
+ expect(ctx).toContain("traceScores.<name> (numeric): overall-quality");
+ expect(ctx).toContain(
+ "traceScores.<name> (categorical): Hallucination Check",
+ );
+ });
+
it("caps observed value length and total context size", () => {
const ctx =
buildAiContext({
diff --git a/web/src/features/search-bar/lib/observed-options.clienttest.ts b/web/src/features/search-bar/lib/observed-options.clienttest.ts
new file mode 100644
index 0000000000..fca98432c3
--- /dev/null
+++ b/web/src/features/search-bar/lib/observed-options.clienttest.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ MAX_SCORE_NAME_LENGTH,
+ MAX_SCORE_NAMES_PER_TYPE,
+ observedScoreNamesFromOptions,
+} from "./observed-options";
+
+describe("observedScoreNamesFromOptions", () => {
+ it("returns undefined while the observed map is still loading", () => {
+ expect(observedScoreNamesFromOptions(undefined)).toBeUndefined();
+ });
+
+ it("keeps a set undefined until its column has loaded, [] when loaded empty", () => {
+ // scores_avg loaded with names, score_categories loaded but empty, the two
+ // trace columns not loaded yet. Only loaded sets are defined β€” the server
+ // must not enforce a set whose column simply hasn't arrived.
+ const names = observedScoreNamesFromOptions({
+ scores_avg: [{ value: "helpfulness-rating" }, { value: "accuracy" }],
+ score_categories: [],
+ });
+ expect(names).toEqual({
+ numeric: ["helpfulness-rating", "accuracy"],
+ categorical: [],
+ traceNumeric: undefined,
+ traceCategorical: undefined,
+ });
+ });
+
+ it("sends an over-cap set as undefined instead of truncating it", () => {
+ // A truncated set would make the un-sent names look unknown and get their
+ // filters dropped; skipping enforcement is the safe degradation.
+ const names = observedScoreNamesFromOptions({
+ scores_avg: Array.from(
+ { length: MAX_SCORE_NAMES_PER_TYPE + 1 },
+ (_, i) => ({
+ value: `score-${i}`,
+ }),
+ ),
+ score_categories: [{ value: "sentiment" }],
+ });
+ expect(names?.numeric).toBeUndefined();
+ expect(names?.categorical).toEqual(["sentiment"]);
+ });
+
+ it("sends a set containing an overlong name as undefined", () => {
+ const names = observedScoreNamesFromOptions({
+ scores_avg: [{ value: "x".repeat(MAX_SCORE_NAME_LENGTH + 1) }],
+ });
+ expect(names?.numeric).toBeUndefined();
+ });
+});
diff --git a/web/src/features/search-bar/lib/observed-options.ts b/web/src/features/search-bar/lib/observed-options.ts
index d08a1fbe9d..9637d86431 100644
--- a/web/src/features/search-bar/lib/observed-options.ts
+++ b/web/src/features/search-bar/lib/observed-options.ts
@@ -122,6 +122,56 @@ export function scoreTypeContextFromObserved(
};
}
+// Caps mirrored by the `searchBar.generateFilter` input schema (server/router.ts).
+// A set that exceeds them is sent as undefined β€” enforcement is skipped for it,
+// rather than an oversized payload failing the whole request with a Zod 400 or
+// a truncated set making a real (but un-sent) score name look unknown.
+export const MAX_SCORE_NAMES_PER_TYPE = 200;
+export const MAX_SCORE_NAME_LENGTH = 256;
+
+/**
+ * Observed score names by column type, threaded to `searchBar.generateFilter`
+ * so the server can validate/correct the score names the model returns (a
+ * misspelled name round-trips cleanly and would apply as a dead filter).
+ */
+export type ObservedScoreNames = {
+ numeric?: string[];
+ categorical?: string[];
+ traceNumeric?: string[];
+ traceCategorical?: string[];
+};
+
+/**
+ * Unlike `scoreTypeContextFromObserved` (which folds an absent column into an
+ * empty set β€” fine for routing), each set here stays undefined until its
+ * filter-options column has actually LOADED: the server skips validation for
+ * an undefined set, so an in-flight fetch or an errored column can never make
+ * a real score name look unknown and get its filter dropped.
+ */
+export function observedScoreNamesFromOptions(
+ observed: ObservedOptions | undefined,
+): ObservedScoreNames | undefined {
+ if (observed === undefined) return undefined;
+ const names = (column: string): string[] | undefined => {
+ const values = observed[column];
+ if (values === undefined) return undefined;
+ const out = values.map((o) => o.value);
+ if (
+ out.length > MAX_SCORE_NAMES_PER_TYPE ||
+ out.some((n) => n.length > MAX_SCORE_NAME_LENGTH)
+ ) {
+ return undefined;
+ }
+ return out;
+ };
+ return {
+ numeric: names("scores_avg"),
+ categorical: names("score_categories"),
+ traceNumeric: names("trace_scores_avg"),
+ traceCategorical: names("trace_score_categories"),
+ };
+}
+
function nameSetsEqual(
a: ReadonlySet<string> | undefined,
b: ReadonlySet<string> | undefined,
diff --git a/web/src/features/search-bar/server/parseFilterCompletion.ts b/web/src/features/search-bar/server/parseFilterCompletion.ts
index 36de7ad44f..b626b0fcf5 100644
--- a/web/src/features/search-bar/server/parseFilterCompletion.ts
+++ b/web/src/features/search-bar/server/parseFilterCompletion.ts
@@ -10,7 +10,9 @@ import {
singleFilter,
} from "@langfuse/shared";
+import { SCORE_COLUMNS } from "../lib/fields";
import { filterStateToQueryText } from "../lib/filter-state-to-query";
+import type { ObservedScoreNames } from "../lib/observed-options";
// Mirrors COMPATIBLE_FILTER_TYPES in
// packages/shared/src/server/queries/clickhouse-sql/filterTypeCompatibility.ts β€”
@@ -89,14 +91,92 @@ function parseFilterArray(completion: string): {
return { filters: [], rawCount: 0 };
}
+// Which ObservedScoreNames set holds the real names for each score column β€”
+// column implies both level (observation/trace) and type (numeric/categorical).
+const SCORE_NAME_SET_BY_COLUMN: Record<
+ string,
+ keyof ObservedScoreNames | undefined
+> = {
+ [SCORE_COLUMNS.observation.numeric]: "numeric",
+ [SCORE_COLUMNS.observation.categorical]: "categorical",
+ [SCORE_COLUMNS.trace.numeric]: "traceNumeric",
+ [SCORE_COLUMNS.trace.categorical]: "traceCategorical",
+};
+
+// Case/separator-insensitive form for the confident-correction match:
+// `my_score`, `My Score`, and `my-score` all normalize to `myscore`.
+function normalizeScoreName(name: string): string {
+ return name.toLowerCase().replace(/[\s_-]+/g, "");
+}
+
+/** The single real name whose normalized form matches `key`; null when none
+ * matches or more than one does (ambiguous β€” not a confident correction). */
+function uniqueNormalizedMatch(
+ names: readonly string[],
+ key: string,
+): string | null {
+ const target = normalizeScoreName(key);
+ let match: string | null = null;
+ for (const name of names) {
+ if (normalizeScoreName(name) !== target) continue;
+ if (match !== null && match !== name) return null;
+ match = name;
+ }
+ return match;
+}
+
+/**
+ * Guardrail: score filters address a score by NAME (`key`), and a misspelled
+ * name (`my_score` for the real `my-score`) passes every other check β€” Zod
+ * (`key` is any string), the contract map (column→type only), and the grammar
+ * round-trip (any key renders on a score column) β€” then applies as a dead
+ * filter that silently matches nothing. So check each score filter's key
+ * against the observed names for ITS column (which fixes both level and type):
+ * exact match keeps, a unique normalized match corrects the key in place, and
+ * anything else is dropped and reported in `unknownScoreNames`. A set the
+ * client did not send (column not loaded) is not enforced. No cross-type or
+ * cross-level rescue: the operator/value shape belongs to the column.
+ */
+function validateScoreNames(
+ filters: FilterState,
+ scoreNames: ObservedScoreNames | undefined,
+): { filters: FilterState; unknownScoreNames: string[] } {
+ if (scoreNames === undefined) return { filters, unknownScoreNames: [] };
+ const kept: FilterState = [];
+ const unknown: string[] = [];
+ for (const filter of filters) {
+ if (filter.type !== "numberObject" && filter.type !== "categoryOptions") {
+ kept.push(filter);
+ continue;
+ }
+ const setKey = SCORE_NAME_SET_BY_COLUMN[filter.column];
+ const names = setKey === undefined ? undefined : scoreNames[setKey];
+ if (names === undefined || names.includes(filter.key)) {
+ kept.push(filter);
+ continue;
+ }
+ const corrected = uniqueNormalizedMatch(names, filter.key);
+ if (corrected !== null) {
+ kept.push({ ...filter, key: corrected });
+ continue;
+ }
+ unknown.push(filter.key);
+ }
+ return { filters: kept, unknownScoreNames: [...new Set(unknown)] };
+}
+
export type GeneratedFilters = {
/** Filters that round-trip to bar grammar β€” safe to apply and show as pills. */
filters: FilterState;
/** The derived bar query text (for display / telemetry). */
queryText: string;
- /** How many model filters were dropped β€” malformed shape, hallucinated, or
- * non-v4 columns (i.e. emitted by the model but not applied). */
+ /** How many model filters were dropped β€” malformed shape, hallucinated
+ * columns/score names, or non-v4 columns (emitted but not applied). */
droppedCount: number;
+ /** Score names the model emitted that match no observed score of that
+ * column's type, exactly or via `_`/`-`/space/case normalization. Their
+ * clauses were dropped; surface these so the drop is never silent. */
+ unknownScoreNames: string[];
};
/**
@@ -105,20 +185,31 @@ export type GeneratedFilters = {
* dropped here, so a caller can never apply a filter the bar can't show as an
* editable pill.
*/
-export function parseGeneratedFilters(completion: string): GeneratedFilters {
+export function parseGeneratedFilters(
+ completion: string,
+ scoreNames?: ObservedScoreNames,
+): GeneratedFilters {
// `rawCount` is what the model emitted; `parsed` already excludes elements
// that failed `singleFilter`, so the drop count is measured against rawCount.
const { filters: parsed, rawCount } = parseFilterArray(completion);
// Guardrail 1: drop filters whose type the events contract would reject.
const compatible = parsed.filter(isEventsContractCompatible);
- // Guardrail 2: drop anything that doesn't round-trip to bar grammar (unknown /
+ // Guardrail 2: correct or drop score filters whose key names no real score β€”
+ // the one hallucination the round-trip below cannot catch (any key renders
+ // on a score column), yet it applies as a dead filter matching nothing.
+ const { filters: scoreChecked, unknownScoreNames } = validateScoreNames(
+ compatible,
+ scoreNames,
+ );
+ // Guardrail 3: drop anything that doesn't round-trip to bar grammar (unknown /
// non-representable columns land in skippedFilters).
- const { text, skippedFilters } = filterStateToQueryText(compatible);
+ const { text, skippedFilters } = filterStateToQueryText(scoreChecked);
const skipped = new Set(skippedFilters);
- const filters = compatible.filter((f) => !skipped.has(f));
+ const filters = scoreChecked.filter((f) => !skipped.has(f));
return {
filters,
queryText: text,
droppedCount: rawCount - filters.length,
+ unknownScoreNames,
};
}
diff --git a/web/src/features/search-bar/server/router.ts b/web/src/features/search-bar/server/router.ts
index 93498e37fa..7734f87df1 100644
--- a/web/src/features/search-bar/server/router.ts
+++ b/web/src/features/search-bar/server/router.ts
@@ -23,6 +23,10 @@ import {
import { env } from "@/src/env.mjs";
import { z } from "zod";
import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ MAX_SCORE_NAME_LENGTH,
+ MAX_SCORE_NAMES_PER_TYPE,
+} from "../lib/observed-options";
import { buildFilterSystemPrompt } from "./buildFilterPrompt";
import { parseGeneratedFilters } from "./parseFilterCompletion";
import {
@@ -31,6 +35,12 @@ import {
isLangfuseAITracingConfigured,
} from "@/src/features/ai-features/server/bedrockCompletion";
+// Caps shared with `observedScoreNamesFromOptions` (the client-side builder),
+// which sends a set as undefined instead of ever exceeding them.
+const scoreNameList = z
+ .array(z.string().max(MAX_SCORE_NAME_LENGTH))
+ .max(MAX_SCORE_NAMES_PER_TYPE);
+
const GenerateFilterInput = z.object({
projectId: z.string(),
prompt: z.string().min(1).max(2048),
@@ -39,6 +49,17 @@ const GenerateFilterInput = z.object({
/** Project data context (observed values, metadata keys, result count) built
* on the client from already-loaded filterOptions + visible rows. */
dataContext: z.string().max(16000).optional(),
+ /** Observed score names by column type (from filterOptions), used to
+ * validate/correct the score names the model returns. A set left undefined
+ * means that column hasn't loaded client-side β€” it is not enforced. */
+ scoreNames: z
+ .object({
+ numeric: scoreNameList.optional(),
+ categorical: scoreNameList.optional(),
+ traceNumeric: scoreNameList.optional(),
+ traceCategorical: scoreNameList.optional(),
+ })
+ .optional(),
});
export const searchBarRouter = createTRPCRouter({
@@ -160,8 +181,12 @@ export const searchBarRouter = createTRPCRouter({
// Parse the model output and keep only the filters that round-trip to
// bar grammar β€” a hallucinated/non-v4 column is dropped, never applied.
- const { filters, queryText, droppedCount } =
- parseGeneratedFilters(llmCompletion);
+ // Score names are validated against the observed sets (exact keeps, a
+ // unique `_`/`-`/space/case-normalized match corrects, anything else is
+ // dropped and reported) so a misspelled score name can never apply as a
+ // dead filter that silently matches nothing.
+ const { filters, queryText, droppedCount, unknownScoreNames } =
+ parseGeneratedFilters(llmCompletion, input.scoreNames);
if (droppedCount > 0) {
logger.warn(
@@ -169,11 +194,12 @@ export const searchBarRouter = createTRPCRouter({
{
projectId: input.projectId,
droppedCount,
+ unknownScoreNames,
},
);
}
- return { filters, queryText };
+ return { filters, queryText, unknownScoreNames };
} catch (error) {
// Already-shaped rejections (auth / precondition / not-found) are
// expected control flow, not backend faults β€” rethrow them without