πͺ’ 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
feat(search-bar): suggest observed metadata keys with types (LFE-10666) (#14771)
Nikita Kabardin479f82c2ff75
diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex f88002acdc..ffa81c3e92 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -106,6 +106,11 @@ import { useEventsSearchBar } from "@/src/features/search-bar/hooks/useEventsSeaimport { 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 { withMetadataPathOptions } from "@/src/features/search-bar/lib/metadata-paths";+import {+ useObservedMetadataPaths,+ useObservedMetadataRecorder,+} from "@/src/features/search-bar/hooks/useObservedMetadata";export type EventsTableRow = {// Identity fields@@ -497,9 +502,22 @@ export default function ObservationsEventsTable({[],);+ // Metadata key paths are not server-enumerated: merge the persisted+ // per-project map of paths observed on previously loaded rows (recorded+ // below, once the table data hook provides the rows) into the observed+ // options, so `metadata.` completes with real keys and their types.+ const observedMetadataPaths = useObservedMetadataPaths(+ projectId,+ searchBarMode,+ );+const observedOptions = useMemo(- () => toObservedOptions(filterOptions, isFilterOptionsPending),- [filterOptions, isFilterOptionsPending],+ () =>+ withMetadataPathOptions(+ toObservedOptions(filterOptions, isFilterOptionsPending),+ observedMetadataPaths,+ ),+ [filterOptions, isFilterOptionsPending, observedMetadataPaths],);const {@@ -609,6 +627,15 @@ export default function ObservationsEventsTable({// eslint-disable-next-line react-hooks/exhaustive-deps}, [observations.status, observations.rows]);+ // Record the visible rows' metadata paths into the persisted per-project+ // suggestions map (read above into observedMetadataPaths). Same sampling as+ // the AI context below; runs once per fetch (rows identity).+ useObservedMetadataRecorder({+ projectId,+ rows: observations.rows,+ enabled: searchBarMode,+ });+// Project data context for the AI filter prompt: observed values (from// filterOptions) + metadata keys sampled from the visible rows + the current// result count, so the model maps NL onto real columns/values rather thandiff --git a/web/src/features/search-bar/README.md b/web/src/features/search-bar/README.mdindex 3c2afe692a..b54e429498 100644--- a/web/src/features/search-bar/README.md+++ b/web/src/features/search-bar/README.md@@ -174,13 +174,18 @@ committedText ββresetToβββΆ store.draft ββ(type/pick/remove)ββplanner), `composer-segments.ts` (draft text β renderable token segments),`edits.ts` (span-local chip removal with AST-surgery fallback),`observed-options.ts` (filterOptions β per-column observed values),- `searchBarInvariants.ts` (pure, registry-shaped property-test harness β the- universal safety net reused per view; see Hardening).+ `metadata-paths.ts` (client-side metadata structure analysis; see "Metadata+ key suggestions"), `searchBarInvariants.ts` (pure, registry-shaped+ property-test harness β the universal safety net reused per view; see+ Hardening).- `store/searchBarStore.ts` β per-mount vanilla zustand store, **draft only**(`setDraft`/`resetTo`/`removeChipSpan`/`revealInvalid`). No committed copy,no commit workflow. Provided with the container's `commit` via`store/SearchBarStoreProvider.tsx` (`useSearchBarStore` selector,`useSearchBarCommit`).+- `store/observedMetadataStore.ts` β global zustand store persisted to+ localStorage: per-project map of observed metadata keys β types (the+ suggestions cache behind "Metadata key suggestions" below).- `hooks/useEventsSearchBar.ts` β the container/bridge. Derives `committedText`(memo), runs the one `resetTo` effect, and owns the `commit()` workflow(planCommit β write filter state + record recent). No URL param of its own;@@ -287,6 +292,52 @@ the wand only survives on non-bar/embedded surfaces and the v3 traces table).free text the user asked to remove. Without this, a stale `searchQuery` wouldsurvive and `resetTo` would re-derive the dropped text back into the bar.+## Metadata key suggestions (client-side observed map)++The API does not enumerate metadata keys, and backend metadata-structure+analysis is deferred (until CH26), so `metadata.` completions are fed+**client-side from rows the user has already loaded**:++- On each fetch, `hooks/useObservedMetadata.ts` samples the visible rows'+ metadata (same first-30 sampling as the AI-context path), records their+ **top-level keys** with the observed JSON value type+ (`lib/metadata-paths.ts`), and unions the result into+ `store/observedMetadataStore.ts` β persisted to localStorage, **per+ project** (one global `Record<projectId, β¦>` map, the globalDateRangeStore+ shape).+- `EventsTable` merges the project's map into the observed options where the+ completion planner already looked (`withMetadataPathOptions`): keys under+ `metadata` (`keyPathOptions`) and each key's observed values under+ `metadata.<key>` (the value stage). So typing `metadata.` suggests observed+ keys with the type as the option detail (`metadata.hej` Β· `number`), and+ `metadata.region:` offers the first few observed values (`eu`, `us`, β¦).+- **Values are first-observed distinct scalars, skip-don't-truncate.** Only+ string/number/boolean leaves are collected (object/array stored forms could+ not round-trip into a matching `=` filter), and a value longer than the cap+ is dropped entirely β a truncated suggestion would insert a filter that+ confidently matches nothing.+- **Top-level keys only, never flattened dot-paths.** Metadata is stored as a+ flat `Map(String, String)`: nested object values are JSON-encoded strings+ under their top-level key, and `StringObjectFilter` matches the LITERAL+ top-level key β a flattened `metadata.scope.name` suggestion would lower to+ key `scope.name` and match nothing (the metadata view's filter shortcut+ resolves the top-level key for the same reason). Dotted suggestions still+ appear whenever producers use dotted top-level keys (the OTel-attribute+ shape, `gen_ai.request.model`); object-valued keys are suggested with type+ `object` and their nested content matches via contains+ (`metadata.scope:*value*`).+- **Types are display-only.** Metadata filters always lower to `stringObject`+ (numeric metadata comparisons are rejected by `operatorIssue`); a key+ observed with more than one type β or only ever `null` β drops its hint+ instead of showing a wrong one (`mixed` is absorbing).+- **Bounded on every axis**: 30 sampled rows per fetch, key length β€ 100+ chars, β€ 200 keys per project (first-observed wins), β€ 5 values per key,+ value length β€ 60 chars, β€ 1024 values per project, β€ 20 projects+ (least-recently-updated evicted), plus a persist `version` key that resets+ the cache on schema change. A no-change merge skips the localStorage write.+- Accepted caveat: metadata the user has never loaded is never suggested (if+ they haven't seen it, they don't know it exists either).+## Extending to other views (the universality contract)The bar is intended to become the primary filter interface for **every**diff --git a/web/src/features/search-bar/hooks/useObservedMetadata.ts b/web/src/features/search-bar/hooks/useObservedMetadata.tsnew file mode 100644index 0000000000..3454037782--- /dev/null+++ b/web/src/features/search-bar/hooks/useObservedMetadata.ts@@ -0,0 +1,55 @@+// Bridge between the events table and the observed-metadata store: the+// recorder samples the currently visible rows' metadata into the persisted+// per-project key map (once per fetch β the rows identity only changes when+// new data lands), and the reader selects that project's map for merging into+// the bar's observed options (lib/metadata-paths.ts withMetadataPathOptions).+// Split in two because EventsTable derives its observed options before the+// table data hook runs, while the recorder needs the loaded rows.++import { useEffect } from "react";+import {+ collectMetadataPathTypes,+ METADATA_SAMPLE_ROWS,+ type StoredKeyInfo,+} from "../lib/metadata-paths";+import { useObservedMetadataStore } from "../store/observedMetadataStore";++/**+ * The project's persisted metadata keyβinfo map (type + sample values), or+ * undefined when disabled or nothing has been observed yet. Stable identity+ * between store writes.+ */+export function useObservedMetadataPaths(+ projectId: string,+ enabled: boolean,+): Record<string, StoredKeyInfo> | undefined {+ return useObservedMetadataStore((s) =>+ enabled ? s.byProject[projectId]?.paths : undefined,+ );+}++/**+ * Analyze the visible rows' metadata (JSON-encoded string or null, per+ * `MetadataDomainClient`) and union the observed top-level keys into the+ * project's persisted map. Samples the same first rows as the AI-context+ * path; the store skips the write when nothing changed, so re-running on+ * each fetch settles immediately.+ */+export function useObservedMetadataRecorder({+ projectId,+ rows,+ enabled,+}: {+ projectId: string;+ rows: ReadonlyArray<{ metadata?: unknown }> | undefined;+ enabled: boolean;+}): void {+ const recordPaths = useObservedMetadataStore((s) => s.actions.recordPaths);+ useEffect(() => {+ if (!enabled || rows === undefined || rows.length === 0) return;+ const collected = collectMetadataPathTypes(+ rows.slice(0, METADATA_SAMPLE_ROWS).map((r) => r.metadata),+ );+ if (collected.size > 0) recordPaths(projectId, collected);+ }, [enabled, rows, projectId, recordPaths]);+}diff --git a/web/src/features/search-bar/lib/completions.clienttest.ts b/web/src/features/search-bar/lib/completions.clienttest.tsindex aaf39b85fc..2a381541c0 100644--- a/web/src/features/search-bar/lib/completions.clienttest.ts+++ b/web/src/features/search-bar/lib/completions.clienttest.ts@@ -474,6 +474,32 @@ describe("planInputCompletions", () => {);});+ it("shows the observed type as the detail of a metadata key suggestion", () => {+ // Keys from the observed-metadata map carry a display-only type hint; a+ // key observed with multiple types (or only null) carries none. Dotted+ // keys (the OTel-attribute shape) are literal top-level keys.+ const observed = {+ ...OBSERVED,+ metadata: [+ { value: "hej", type: "number" },+ { value: "heyhey.abc", type: "string" },+ { value: "mixedKey" },+ ],+ };+ const opts = flattenOptions(plan("metadata.", 9, { observed }));+ const detailOf = (label: string) => {+ const o = opts.find((o) => o.label === label);+ return o && "detail" in o ? o.detail : undefined;+ };+ expect(detailOf("metadata.hej")).toBe("number");+ expect(detailOf("metadata.heyhey.abc")).toBe("string");+ expect(detailOf("metadata.mixedKey")).toBeUndefined();+ // Typing a key prefix ranks the matching key first and arms Enter.+ const prefixed = plan("metadata.heyhey", 15, { observed });+ expect(prefixed?.autoHighlight).toBe(true);+ expect(flattenOptions(prefixed)[0]?.label).toBe("metadata.heyhey.abc");+ });+it("keeps the key-path popover open while typing the quote for a spaced name", () => {// The documented syntax is `scores."Rouge Score"`; typing the leading quote// must keep ranking the (bare-labelled) options instead of closing thediff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.tsindex c1080406f1..7bc0dc9dc4 100644--- a/web/src/features/search-bar/lib/completions.ts+++ b/web/src/features/search-bar/lib/completions.ts@@ -471,7 +471,10 @@ function keyPathOptions(id: `key:metadata.${o.value}`,kind: "field" as const,label: `metadata.${o.value}`,- detail: o.count !== undefined ? String(o.count) : undefined,+ // The observed JSON type of the path (display-only β metadata filters+ // always lower to stringObject regardless). Paths seen with multiple+ // types carry no type hint; counts stay the fallback like other lists.+ detail: o.type ?? (o.count !== undefined ? String(o.count) : undefined),fieldId: keyText(o.value),}));return {@@ -990,7 +993,8 @@ export function planInputCompletions(if (path !== null) {// Score-name suggestions need both score-name columns; request and show a// loading row while they stream in (lazy mode). Metadata keys are not- // server-enumerated, so there is nothing to request there.+ // server-enumerated β they come from the client-side observed-metadata+ // map (lib/metadata-paths.ts) β so there is nothing to request there.if (path.kind.canonical !== "metadata.") {const numericColumn =path.kind.level === "trace" ? "trace_scores_avg" : "scores_avg";diff --git a/web/src/features/search-bar/lib/metadata-paths.clienttest.ts b/web/src/features/search-bar/lib/metadata-paths.clienttest.tsnew file mode 100644index 0000000000..ad42b0e82a--- /dev/null+++ b/web/src/features/search-bar/lib/metadata-paths.clienttest.ts@@ -0,0 +1,211 @@+import { describe, expect, it } from "vitest";++import {+ collectMetadataPathTypes,+ MAX_PATHS_PER_PROJECT,+ MAX_VALUES_PER_KEY,+ mergePathType,+ withMetadataPathOptions,+ type StoredKeyInfo,+} from "./metadata-paths";+import type { ObservedOptions } from "./observed-options";++describe("collectMetadataPathTypes", () => {+ it("records top-level keys with observed value types", () => {+ // The ticket's motivating example, as the JSON-encoded string rows carry.+ // `heyhey` is a nested branch: stored server-side as ONE Map key whose+ // value is a JSON string, so it is suggested as an "object" key β never+ // flattened to `heyhey.abc`, which would not be filterable.+ const collected = collectMetadataPathTypes([+ JSON.stringify({ hej: 123, heyhey: { abc: "hello" } }),+ ]);+ expect(collected.get("hej")?.type).toBe("number");+ expect(collected.get("heyhey")?.type).toBe("object");+ expect(collected.has("heyhey.abc")).toBe(false);+ expect(collected.size).toBe(2);+ });++ it("keeps dotted top-level keys as-is (the OTel attribute shape)", () => {+ const collected = collectMetadataPathTypes([+ JSON.stringify({ "gen_ai.request.model": "gpt-4o", "shape.depth": 3 }),+ ]);+ expect(collected.get("gen_ai.request.model")?.type).toBe("string");+ expect(collected.get("shape.depth")?.type).toBe("number");+ });++ it("types booleans and arrays", () => {+ const collected = collectMetadataPathTypes([+ JSON.stringify({ flag: true, tags: ["a", "b"] }),+ ]);+ expect(collected.get("flag")?.type).toBe("boolean");+ expect(collected.get("tags")?.type).toBe("array");+ });++ it("marks a key observed with two types across rows as mixed", () => {+ const collected = collectMetadataPathTypes([+ JSON.stringify({ a: 1 }),+ JSON.stringify({ a: "x" }),+ ]);+ expect(collected.get("a")?.type).toBe("mixed");+ });++ it("registers null-only keys without a type and upgrades them later", () => {+ const nullOnly = collectMetadataPathTypes([JSON.stringify({ a: null })]);+ expect(nullOnly.get("a")?.type).toBe("");+ const upgraded = collectMetadataPathTypes([+ JSON.stringify({ a: null }),+ JSON.stringify({ a: "x" }),+ ]);+ expect(upgraded.get("a")?.type).toBe("string");+ });++ it("collects distinct scalar values per key, stringified", () => {+ const collected = collectMetadataPathTypes([+ JSON.stringify({ region: "eu", turn: 3, flag: true }),+ JSON.stringify({ region: "us", turn: 3 }),+ JSON.stringify({ region: "eu" }),+ ]);+ expect(collected.get("region")?.values).toEqual(["eu", "us"]);+ expect(collected.get("turn")?.values).toEqual(["3"]);+ expect(collected.get("flag")?.values).toEqual(["true"]);+ });++ it("caps values per key at first-observed distinct", () => {+ const rows = Array.from({ length: MAX_VALUES_PER_KEY + 3 }, (_, i) =>+ JSON.stringify({ region: `region-${i}` }),+ );+ const collected = collectMetadataPathTypes(rows);+ expect(collected.get("region")?.values).toHaveLength(MAX_VALUES_PER_KEY);+ expect(collected.get("region")?.values?.[0]).toBe("region-0");+ });++ it("never collects values for object/array/null leaves or empty strings", () => {+ const collected = collectMetadataPathTypes([+ JSON.stringify({+ scope: { name: "x" },+ tags: ["a"],+ nothing: null,+ blank: "",+ }),+ ]);+ expect(collected.get("scope")?.values).toBeUndefined();+ expect(collected.get("tags")?.values).toBeUndefined();+ expect(collected.get("nothing")?.values).toBeUndefined();+ expect(collected.get("blank")?.values).toBeUndefined();+ });++ it("skips overlong values entirely instead of truncating them", () => {+ // A truncated value would insert a filter that matches nothing.+ const collected = collectMetadataPathTypes([+ JSON.stringify({ long: "x".repeat(200), short: "ok" }),+ ]);+ expect(collected.get("long")?.type).toBe("string");+ expect(collected.get("long")?.values).toBeUndefined();+ expect(collected.get("short")?.values).toEqual(["ok"]);+ });++ it("accepts already-parsed objects and skips unparsable/non-object rows", () => {+ const collected = collectMetadataPathTypes([+ { direct: 1 },+ "not json{",+ '"just a string"',+ "[1, 2]",+ null,+ undefined,+ 42,+ ]);+ expect([...collected.keys()]).toEqual(["direct"]);+ });++ it("caps the number of collected keys", () => {+ const wide = Object.fromEntries(+ Array.from({ length: MAX_PATHS_PER_PROJECT + 50 }, (_, i) => [+ `k${i}`,+ i,+ ]),+ );+ const collected = collectMetadataPathTypes([wide]);+ expect(collected.size).toBe(MAX_PATHS_PER_PROJECT);+ });++ it("still merges types for known keys once the cap is reached", () => {+ const wide = Object.fromEntries(+ Array.from({ length: MAX_PATHS_PER_PROJECT }, (_, i) => [`k${i}`, i]),+ );+ const collected = collectMetadataPathTypes([wide, { k0: "now a string" }]);+ expect(collected.size).toBe(MAX_PATHS_PER_PROJECT);+ expect(collected.get("k0")?.type).toBe("mixed");+ });++ it("skips empty, overlong, and __proto__ keys", () => {+ const collected = collectMetadataPathTypes([+ {+ "": 1,+ ["x".repeat(200)]: 2,+ ok: 3,+ },+ '{"__proto__": {"polluted": true}, "fine": 1}',+ ]);+ expect([...collected.keys()].sort()).toEqual(["fine", "ok"]);+ });+});++describe("mergePathType", () => {+ it("is mixed-absorbing and never demoted by null observations", () => {+ expect(mergePathType(undefined, "number")).toBe("number");+ expect(mergePathType("number", "number")).toBe("number");+ expect(mergePathType("number", "string")).toBe("mixed");+ expect(mergePathType("mixed", "number")).toBe("mixed");+ expect(mergePathType("mixed", "")).toBe("mixed");+ expect(mergePathType("number", "")).toBe("number");+ expect(mergePathType("", "string")).toBe("string");+ expect(mergePathType(undefined, null)).toBe("");+ });+});++describe("withMetadataPathOptions", () => {+ const observed: ObservedOptions = { level: [{ value: "ERROR" }] };++ it("keeps undefined observed undefined (loading semantics untouched)", () => {+ expect(+ withMetadataPathOptions(undefined, { a: { type: "string" } }),+ ).toBeUndefined();+ });++ it("returns the observed map unchanged without paths", () => {+ expect(withMetadataPathOptions(observed, undefined)).toBe(observed);+ expect(withMetadataPathOptions(observed, {})).toBe(observed);+ });++ it("merges sorted keys under `metadata`, omitting mixed/unknown types", () => {+ const paths: Record<string, StoredKeyInfo> = {+ "routing.queue": { type: "string" },+ hej: { type: "number" },+ scope: { type: "object" },+ both: { type: "mixed" },+ nullish: { type: "" },+ };+ const out = withMetadataPathOptions(observed, paths);+ expect(out?.level).toBe(observed.level);+ expect(out?.metadata).toEqual([+ { value: "both" },+ { value: "hej", type: "number" },+ { value: "nullish" },+ { value: "routing.queue", type: "string" },+ { value: "scope", type: "object" },+ ]);+ });++ it("exposes per-key values under `metadata.<key>` for the value stage", () => {+ const paths: Record<string, StoredKeyInfo> = {+ region: { type: "string", values: ["eu", "us"] },+ scope: { type: "object" },+ };+ const out = withMetadataPathOptions(observed, paths);+ expect(out?.["metadata.region"]).toEqual([+ { value: "eu" },+ { value: "us" },+ ]);+ expect(out?.["metadata.scope"]).toBeUndefined();+ });+});diff --git a/web/src/features/search-bar/lib/metadata-paths.ts b/web/src/features/search-bar/lib/metadata-paths.tsnew file mode 100644index 0000000000..e0f604f602--- /dev/null+++ b/web/src/features/search-bar/lib/metadata-paths.ts@@ -0,0 +1,183 @@+// Client-side metadata structure analysis feeding the bar's `metadata.<key>`+// key suggestions. The API does not enumerate metadata keys (see+// observed-options.ts) and backend structure analysis is deferred, so the map+// of observed keys is built OPPORTUNISTICALLY from rows the user has already+// loaded: each fetch samples the visible rows, records their TOP-LEVEL+// metadata keys with the observed JSON value type, and unions the result into+// the persisted per-project store (store/observedMetadataStore.ts). Accepted+// caveat: metadata the user has never loaded is never suggested.+//+// Top-level keys ONLY β deliberately not flattened into nested dot-paths.+// Metadata is stored as a flat Map(String, String): nested object values are+// JSON-encoded strings under their top-level key, and the stringObject filter+// matches the LITERAL top-level key ("we can only filter on the first level",+// StringObjectFilter in clickhouse-filter.ts; the metadata view's filter+// shortcut resolves the top-level key for the same reason β ValueCell.tsx).+// A flattened `metadata.scope.name` suggestion would lower to key+// "scope.name" and match nothing. Dot-paths still appear whenever producers+// use dotted top-level keys (the OTel-attribute shape, e.g.+// `gen_ai.request.model`) β those ARE literal keys and filter correctly.+// Object-valued keys are suggested with type "object"; their nested content+// is matched as a substring of the JSON-encoded branch (`metadata.scope:*v*`).+//+// Types are DISPLAY-ONLY hints: metadata filters always lower to+// `stringObject` (see fields.ts operatorIssue β numeric metadata comparisons+// are rejected), so a key observed with more than one type simply drops its+// hint rather than changing any filter behavior.++import type { ObservedOptions, ObservedValue } from "./observed-options";++export type MetadataLeafType =+ | "string"+ | "number"+ | "boolean"+ | "array"+ | "object";++/**+ * Stored per-key type: one observed value type, `"mixed"` once more than one+ * distinct type has been seen, or `""` while only null has been observed+ * (null registers the key but does not count as a type).+ */+export type StoredPathType = MetadataLeafType | "mixed" | "";++/** Persisted per-key record: display type + a few observed scalar values. */+export type StoredKeyInfo = {+ type: StoredPathType;+ /**+ * First-observed distinct SCALAR values (string/number/boolean, stringified)+ * feeding the value-stage dropdown. Object/array/null values and values+ * longer than MAX_VALUE_LENGTH are never collected β their stored form+ * could not round-trip into a matching `=` filter. Absent when none.+ */+ values?: string[];+};++// Bounds β metadata is user-shaped and unbounded, so every axis is capped:+// sampled rows per fetch, key string length, keys kept per project, values+// kept per key, and values kept per project in total (the store enforces the+// per-project caps on merge; entries beyond a cap are dropped, first-observed+// wins).+export const METADATA_SAMPLE_ROWS = 30;+export const MAX_PATHS_PER_PROJECT = 200;+export const MAX_VALUES_PER_KEY = 5;+// Hard per-project total. With today's caps the effective bound is the+// product 200 Γ 5 = 1000; this backstop binds only against drifted persisted+// state (older schema, tampered localStorage) or a future per-key cap raise.+export const MAX_VALUES_PER_PROJECT = 1024;+const MAX_PATH_LENGTH = 100;+// Values longer than this are SKIPPED, never truncated β a truncated value+// would insert a filter that confidently matches nothing.+const MAX_VALUE_LENGTH = 60;+// Skip parsing giant metadata blobs so the per-fetch analysis stays cheap.+const MAX_METADATA_JSON_LENGTH = 200_000;++function safeJsonParse(s: string): unknown {+ try {+ return JSON.parse(s);+ } catch {+ return undefined;+ }+}++function valueType(v: unknown): MetadataLeafType | null {+ if (Array.isArray(v)) return "array";+ const t = typeof v;+ if (t === "string" || t === "number" || t === "boolean") return t;+ if (t === "object" && v !== null) return "object";+ return null;+}++/**+ * Merge an already-stored key type with a newly observed one. `"mixed"` is+ * absorbing; null-only observations (`""`) never demote a known type.+ */+export function mergePathType(+ prev: StoredPathType | undefined,+ next: StoredPathType | null,+): StoredPathType {+ const observed = next ?? "";+ if (prev === undefined || prev === "") return observed;+ if (observed === "" || observed === prev) return prev;+ return "mixed";+}++/** Suggestible scalar value, stringified β or null when not suggestible. */+function scalarValue(v: unknown): string | null {+ const t = typeof v;+ if (t !== "string" && t !== "number" && t !== "boolean") return null;+ const s = String(v);+ return s.length > 0 && s.length <= MAX_VALUE_LENGTH ? s : null;+}++/**+ * Record the observed top-level metadata keys of sampled rows (JSON-encoded+ * strings per `MetadataDomainClient`, or already-parsed objects) with their+ * value types, merged across rows (`a:1` + `a:"x"` β `"mixed"`), plus the+ * first few distinct scalar values per key for the value-stage dropdown.+ */+export function collectMetadataPathTypes(+ sampleMetadata: readonly unknown[],+): Map<string, StoredKeyInfo> {+ const out = new Map<string, StoredKeyInfo>();+ for (const md of sampleMetadata) {+ if (typeof md === "string" && md.length > MAX_METADATA_JSON_LENGTH)+ continue;+ const parsed = typeof md === "string" ? safeJsonParse(md) : md;+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))+ continue;+ for (const [key, v] of Object.entries(parsed as Record<string, unknown>)) {+ // Empty keys are unfilterable; "__proto__" keys would turn the store's+ // plain-object key map into a prototype write.+ if (key.length === 0 || key === "__proto__") continue;+ if (key.length > MAX_PATH_LENGTH) continue;+ const existing = out.get(key);+ if (existing === undefined && out.size >= MAX_PATHS_PER_PROJECT) continue;+ const type = mergePathType(existing?.type, valueType(v));+ const value = scalarValue(v);+ let values = existing?.values;+ if (+ value !== null &&+ (values?.length ?? 0) < MAX_VALUES_PER_KEY &&+ !values?.includes(value)+ ) {+ values = [...(values ?? []), value];+ }+ out.set(key, values === undefined ? { type } : { type, values });+ }+ }+ return out;+}++/**+ * Merge the persisted per-project key map into the observed-options map where+ * the completion planner reads it: keys under `metadata` (keyPathOptions) and+ * each key's observed values under `metadata.<key>` (the value stage). Keys+ * are sorted so related dotted keys group together in the dropdown;+ * `"mixed"`/null-only keys carry no type hint. `undefined` observed (filter+ * options still loading) stays `undefined` so the planner's loading semantics+ * are untouched.+ */+export function withMetadataPathOptions(+ observed: ObservedOptions | undefined,+ paths: Record<string, StoredKeyInfo> | undefined,+): ObservedOptions | undefined {+ if (observed === undefined || paths === undefined) return observed;+ const entries = Object.entries(paths);+ if (entries.length === 0) return observed;+ const out: ObservedOptions = { ...observed };+ out.metadata = entries+ .sort(([a], [b]) => a.localeCompare(b))+ .map(+ ([path, { type }]): ObservedValue =>+ type === "" || type === "mixed"+ ? { value: path }+ : { value: path, type },+ );+ for (const [path, { values }] of entries) {+ if (values !== undefined && values.length > 0) {+ out[`metadata.${path}`] = values.map((v) => ({ value: v }));+ }+ }+ return out;+}diff --git a/web/src/features/search-bar/lib/observed-options.ts b/web/src/features/search-bar/lib/observed-options.tsindex 66185624ee..f571625202 100644--- a/web/src/features/search-bar/lib/observed-options.ts+++ b/web/src/features/search-bar/lib/observed-options.ts@@ -5,12 +5,18 @@// <columnId> β observed values (with counts when known)// scores_avg / trace_scores_avg β numeric score NAMES// score_categories[.<name>] β categorical score names / their values-// (metadata keys are not enumerated by the API today β metadata key paths-// complete from free typing only)+// (metadata key paths are not enumerated by the API β they are merged in+// client-side from the observed-metadata store; see lib/metadata-paths.ts+// withMetadataPathOptions, which fills the `metadata` key)import type { ScoreTypeContext } from "./adapter";-export type ObservedValue = { value: string; count?: number };+export type ObservedValue = {+ value: string;+ count?: number;+ /** Display-only type hint (observed metadata paths: "number", "string", β¦). */+ type?: string;+};export type ObservedOptions = Record<string, ObservedValue[]>;type RawOption = string | { value: string; count?: number };diff --git a/web/src/features/search-bar/store/observedMetadataStore.clienttest.ts b/web/src/features/search-bar/store/observedMetadataStore.clienttest.tsnew file mode 100644index 0000000000..5b89979ab6--- /dev/null+++ b/web/src/features/search-bar/store/observedMetadataStore.clienttest.ts@@ -0,0 +1,241 @@+import { describe, expect, it } from "vitest";++import {+ mergeIntoProject,+ useObservedMetadataStore,+} from "./observedMetadataStore";+import {+ MAX_PATHS_PER_PROJECT,+ MAX_VALUES_PER_KEY,+ MAX_VALUES_PER_PROJECT,+ type StoredKeyInfo,+} from "../lib/metadata-paths";++const paths = (entries: Record<string, StoredKeyInfo>) =>+ new Map(Object.entries(entries));++describe("mergeIntoProject", () => {+ it("creates a project entry and merges types on later observations", () => {+ const first = mergeIntoProject(+ {},+ "p1",+ paths({ a: { type: "number" } }),+ 1000,+ );+ expect(first?.p1).toEqual({+ paths: { a: { type: "number" } },+ updatedAt: 1000,+ });++ const second = mergeIntoProject(+ first!,+ "p1",+ paths({ a: { type: "string" }, b: { type: "boolean" } }),+ 2000,+ );+ expect(second?.p1.paths).toEqual({+ a: { type: "mixed" },+ b: { type: "boolean" },+ });+ expect(second?.p1.updatedAt).toBe(2000);+ });++ it("unions values per key up to the cap, first-observed wins", () => {+ const base = mergeIntoProject(+ {},+ "p1",+ paths({ region: { type: "string", values: ["eu", "us"] } }),+ 1000,+ )!;+ const merged = mergeIntoProject(+ base,+ "p1",+ paths({+ region: {+ type: "string",+ values: ["us", "apac", "mena", "latam", "antarctica"],+ },+ }),+ 2000,+ );+ // "us" deduped; new ones appended until MAX_VALUES_PER_KEY.+ expect(merged?.p1.paths.region?.values).toEqual([+ "eu",+ "us",+ "apac",+ "mena",+ "latam",+ ]);+ expect(merged?.p1.paths.region?.values).toHaveLength(MAX_VALUES_PER_KEY);+ });++ it("enforces the per-project total value cap as a backstop", () => {+ // Through normal input the total is bounded by keys Γ values-per-key+ // (200 Γ 5 = 1000 < 1024), so the backstop only binds against drifted+ // PERSISTED state β an older schema or tampered localStorage. Simulate+ // that: one key already holding far more values than today's per-key cap.+ const drifted = {+ p1: {+ paths: {+ bulk: {+ type: "string" as const,+ values: Array.from(+ { length: MAX_VALUES_PER_PROJECT - 2 },+ (_, i) => `v${i}`,+ ),+ },+ },+ updatedAt: 1000,+ },+ };+ const merged = mergeIntoProject(+ drifted,+ "p1",+ paths({ fresh: { type: "string", values: ["a", "b", "c", "d"] } }),+ 2000,+ );+ // Room for only 2 more values project-wide; the key itself registers.+ expect(merged?.p1.paths.fresh).toEqual({+ type: "string",+ values: ["a", "b"],+ });+ });++ it("returns null (no persist) when nothing changed recently", () => {+ const base = mergeIntoProject(+ {},+ "p1",+ paths({ a: { type: "number", values: ["1"] } }),+ 1000,+ )!;+ expect(+ mergeIntoProject(+ base,+ "p1",+ paths({ a: { type: "number", values: ["1"] } }),+ 2000,+ ),+ ).toBe(null);+ // Empty analysis never touches the store.+ expect(mergeIntoProject(base, "p1", new Map(), 2000)).toBe(null);+ });++ it("refreshes the LRU stamp of an unchanged-but-active project once stale", () => {+ const base = mergeIntoProject(+ {},+ "p1",+ paths({ a: { type: "number" } }),+ 1000,+ )!;+ const dayLater = 1000 + 25 * 60 * 60 * 1000;+ const touched = mergeIntoProject(+ base,+ "p1",+ paths({ a: { type: "number" } }),+ dayLater,+ );+ expect(touched?.p1.updatedAt).toBe(dayLater);+ expect(touched?.p1.paths).toBe(base.p1!.paths);+ });++ it("enforces the per-project key cap, keeping existing keys", () => {+ const full = Object.fromEntries(+ Array.from({ length: MAX_PATHS_PER_PROJECT }, (_, i) => [+ `k${i}`,+ { type: "string" } as StoredKeyInfo,+ ]),+ );+ const base = mergeIntoProject({}, "p1", paths(full), 1000)!;+ const merged = mergeIntoProject(+ base,+ "p1",+ paths({ overflow: { type: "number" }, k0: { type: "number" } }),+ 2000,+ );+ // The new key is dropped; the existing key still merges its type.+ expect(merged?.p1.paths.overflow).toBeUndefined();+ expect(merged?.p1.paths.k0?.type).toBe("mixed");+ expect(Object.keys(merged!.p1!.paths)).toHaveLength(MAX_PATHS_PER_PROJECT);+ });++ it("evicts the least-recently-updated projects beyond the cap", () => {+ let byProject = {};+ for (let i = 0; i < 21; i++) {+ byProject = mergeIntoProject(+ byProject,+ `p${i}`,+ paths({ a: { type: "string" } }),+ 1000 + i,+ )!;+ }+ expect(Object.keys(byProject)).toHaveLength(20);+ expect(byProject).not.toHaveProperty("p0");+ expect(byProject).toHaveProperty("p20");+ });++ it("types keys shadowing Object.prototype members correctly", () => {+ // `nextPaths["toString"]` must not read the inherited function as the+ // "existing" entry β that would skip the cap counter and pin the type to+ // "mixed" forever (review find: greptile/claude on PR #14771).+ const merged = mergeIntoProject(+ {},+ "p1",+ paths({+ toString: { type: "string", values: ["hello"] },+ constructor: { type: "number", values: ["1"] },+ hasOwnProperty: { type: "boolean" },+ }),+ 1000,+ );+ expect(merged?.p1.paths.toString).toEqual({+ type: "string",+ values: ["hello"],+ });+ expect(merged?.p1.paths.constructor).toEqual({+ type: "number",+ values: ["1"],+ });+ expect(merged?.p1.paths.hasOwnProperty).toEqual({ type: "boolean" });+ // Re-merging the same observation stays a no-op (types stable, no churn).+ expect(+ mergeIntoProject(+ merged!,+ "p1",+ paths({ toString: { type: "string", values: ["hello"] } }),+ 2000,+ ),+ ).toBe(null);+ });++ it("scopes paths per project (no cross-bleed)", () => {+ const one = mergeIntoProject(+ {},+ "p1",+ paths({ a: { type: "number" } }),+ 1000,+ )!;+ const two = mergeIntoProject(+ one,+ "p2",+ paths({ b: { type: "string" } }),+ 2000,+ )!;+ expect(two.p1?.paths).toEqual({ a: { type: "number" } });+ expect(two.p2?.paths).toEqual({ b: { type: "string" } });+ });+});++describe("useObservedMetadataStore", () => {+ it("records paths through the action and exposes them per project", () => {+ useObservedMetadataStore.setState({ byProject: {} });+ useObservedMetadataStore+ .getState()+ .actions.recordPaths(+ "proj",+ paths({ "routing.queue": { type: "string", values: ["billing"] } }),+ );+ expect(useObservedMetadataStore.getState().byProject.proj?.paths).toEqual({+ "routing.queue": { type: "string", values: ["billing"] },+ });+ });+});diff --git a/web/src/features/search-bar/store/observedMetadataStore.ts b/web/src/features/search-bar/store/observedMetadataStore.tsnew file mode 100644index 0000000000..56ba2d6c29--- /dev/null+++ b/web/src/features/search-bar/store/observedMetadataStore.ts@@ -0,0 +1,170 @@+// Persisted per-project map of observed metadata paths β types, feeding the+// search bar's `metadata.<path>` key suggestions (lib/metadata-paths.ts owns+// the analysis; hooks/useObservedMetadata.ts is the bridge).+//+// Same shape rationale as globalDateRangeStore: one global store holding a+// `Record<projectId, β¦>` map, so switching projects selects a different field+// instead of re-hydrating a per-project key (which could clobber another+// project's entry on an in-app switch). SSR gets a no-op storage.+//+// Growth is bounded on every axis (metadata is user-shaped and unbounded):+// keys per project and values per key/per project are capped on merge+// (MAX_PATHS_PER_PROJECT / MAX_VALUES_PER_KEY / MAX_VALUES_PER_PROJECT,+// drop-new when full), projects are capped with least-recently-updated+// eviction, and a merge that changes nothing skips the localStorage write+// entirely.++import { create } from "zustand";+import {+ createJSONStorage,+ persist,+ type StateStorage,+} from "zustand/middleware";+import {+ MAX_PATHS_PER_PROJECT,+ MAX_VALUES_PER_KEY,+ MAX_VALUES_PER_PROJECT,+ mergePathType,+ type StoredKeyInfo,+} from "../lib/metadata-paths";++export const OBSERVED_METADATA_STORAGE_KEY = "langfuse-observed-metadata";++const MAX_PROJECTS = 20;+// A merge that changes nothing still refreshes the LRU stamp when it is older+// than this, so an actively-viewed project with a long-stable map outlives a+// stale one β without a localStorage write on every fetch.+const LRU_TOUCH_INTERVAL_MS = 24 * 60 * 60 * 1000;++// No-op storage on the server; the real localStorage is used on the client.+const noopStorage: StateStorage = {+ getItem: () => null,+ setItem: () => {},+ removeItem: () => {},+};++type ProjectMetadataPaths = {+ /** Observed top-level key β stored type + sample values (see StoredKeyInfo). */+ paths: Record<string, StoredKeyInfo>;+ /** Last change (or daily activity refresh) β the project-eviction LRU key. */+ updatedAt: number;+};++type ObservedMetadataState = {+ byProject: Record<string, ProjectMetadataPaths>;+ actions: {+ /** Union newly observed paths into a project's map (see mergeIntoProject). */+ recordPaths: (+ projectId: string,+ collected: ReadonlyMap<string, StoredKeyInfo>,+ ) => void;+ };+};++/**+ * Pure merge: union `collected` into the project's path map β merging types+ * per key (mixed-absorbing) and unioning observed values (first-observed+ * wins) β enforcing the per-project key cap, the per-key and per-project+ * value caps, and the project-count cap (evict least-recently-updated).+ * Returns null when nothing needs persisting. Exported for tests.+ */+export function mergeIntoProject(+ byProject: Record<string, ProjectMetadataPaths>,+ projectId: string,+ collected: ReadonlyMap<string, StoredKeyInfo>,+ now: number,+): Record<string, ProjectMetadataPaths> | null {+ if (collected.size === 0) return null;+ const prev = byProject[projectId];+ const nextPaths: Record<string, StoredKeyInfo> = { ...(prev?.paths ?? {}) };+ let count = Object.keys(nextPaths).length;+ let totalValues = Object.values(nextPaths).reduce(+ (sum, info) => sum + (info.values?.length ?? 0),+ 0,+ );+ let changed = false;+ for (const [path, incoming] of collected) {+ // Own-property lookup: a key shadowing an Object.prototype member+ // ("toString", "constructor", β¦) must read as unseen, not as the+ // inherited function β which would bypass the cap counter and crash or+ // pin the type to "mixed" (`nextPaths["constructor"].values` resolves to+ // the static Object.values).+ const existing = Object.hasOwn(nextPaths, path)+ ? nextPaths[path]+ : undefined;+ if (existing === undefined) {+ if (count >= MAX_PATHS_PER_PROJECT) continue;+ count++;+ }+ const mergedType = mergePathType(existing?.type, incoming.type);+ let mergedValues = existing?.values;+ for (const v of incoming.values ?? []) {+ if ((mergedValues?.length ?? 0) >= MAX_VALUES_PER_KEY) break;+ if (totalValues >= MAX_VALUES_PER_PROJECT) break;+ if (mergedValues?.includes(v)) continue;+ mergedValues = [...(mergedValues ?? []), v];+ totalValues++;+ }+ if (+ existing === undefined ||+ existing.type !== mergedType ||+ mergedValues !== existing.values+ ) {+ nextPaths[path] =+ mergedValues === undefined+ ? { type: mergedType }+ : { type: mergedType, values: mergedValues };+ changed = true;+ }+ }+ // `prev` exists whenever nothing changed: an absent project entry always+ // changes on a non-empty `collected` (guarded above).+ if (!changed && now - prev!.updatedAt < LRU_TOUCH_INTERVAL_MS) return null;++ const next: Record<string, ProjectMetadataPaths> = {+ ...byProject,+ [projectId]: {+ paths: changed ? nextPaths : prev!.paths,+ updatedAt: now,+ },+ };+ const ids = Object.keys(next);+ if (ids.length > MAX_PROJECTS) {+ ids+ .sort((a, b) => next[a]!.updatedAt - next[b]!.updatedAt)+ .slice(0, ids.length - MAX_PROJECTS)+ .forEach((id) => delete next[id]);+ }+ return next;+}++export const useObservedMetadataStore = create<ObservedMetadataState>()(+ persist(+ (set, get) => ({+ byProject: {},+ actions: {+ recordPaths: (projectId, collected) => {+ const next = mergeIntoProject(+ get().byProject,+ projectId,+ collected,+ Date.now(),+ );+ if (next !== null) set({ byProject: next });+ },+ },+ }),+ {+ name: OBSERVED_METADATA_STORAGE_KEY,+ version: 2,+ // Hydrates from localStorage on the client; no-op during SSR.+ storage: createJSONStorage(() =>+ typeof window !== "undefined" ? window.localStorage : noopStorage,+ ),+ // Persist only data, never the actions object.+ partialize: (state) => ({ byProject: state.byProject }),+ // On any schema change, start fresh β the map is a rebuildable cache.+ migrate: () => ({ byProject: {} }),+ },+ ),+);