Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(filters): session filtering with old state (#9976)

Nimar2306ea565a5e
diff --git a/packages/shared/src/server/repositories/trace-sessions.ts b/packages/shared/src/server/repositories/trace-sessions.ts
index 742c6ffcc9..77fbb85862 100644
--- a/packages/shared/src/server/repositories/trace-sessions.ts
+++ b/packages/shared/src/server/repositories/trace-sessions.ts
@@ -9,7 +9,9 @@ export const getPublicSessionsFilter = async (
// Theoretically we should also filter the sessions by environment here. As this would return a huge list that's probably not feasible.
// I.e. we only perform the environment check on the ClickHouse queries.
- const sessionsBookmarkedFilter = filter?.find((f) => f.column === "⭐️");
+ const sessionsBookmarkedFilter = filter?.find(
+ (f) => f.column === "⭐️" || f.column === "bookmarked",
+ );
let additionalBookmarkFilter: z.infer<typeof singleFilter>[] = [];
if (sessionsBookmarkedFilter) {
@@ -65,7 +67,12 @@ export const getPublicSessionsFilter = async (
}
return filter
- ? [...filter.filter((f) => f.column !== "⭐️"), ...additionalBookmarkFilter]
+ ? [
+ ...filter.filter(
+ (f) => f.column !== "⭐️" && f.column !== "bookmarked",
+ ),
+ ...additionalBookmarkFilter,
+ ]
: [...additionalBookmarkFilter];
};
diff --git a/web/src/components/table/table-view-presets/validation.ts b/web/src/components/table/table-view-presets/validation.ts
index a1387aeb4c..3ce4e95647 100644
--- a/web/src/components/table/table-view-presets/validation.ts
+++ b/web/src/components/table/table-view-presets/validation.ts
@@ -4,6 +4,7 @@ import {
type ColumnDefinition,
type OrderByState,
} from "@langfuse/shared";
+import { normalizeFilterColumnNames } from "@/src/features/filters/lib/filter-transform";
/**
* Validates if an orderBy state references valid columns
@@ -44,27 +45,16 @@ export function validateFilters(
if (!filterColumnDefinition || filterColumnDefinition.length === 0)
return filters;
- // Validate and normalize filters
- return filters
- .map((filter) => {
- // Find matching column definition (by ID or name for backward compat)
- const matchingDef = filterColumnDefinition.find(
- (def) => def.id === filter.column || def.name === filter.column,
- );
-
- // Filter is invalid if no matching definition found
- if (!matchingDef) return null;
-
- // If filter uses old display name, normalize to ID
- if (filter.column !== matchingDef.id) {
- return {
- ...filter,
- column: matchingDef.id,
- };
- }
+ // Normalize display names to column IDs for backward compatibility
+ const normalized = normalizeFilterColumnNames(
+ filters,
+ filterColumnDefinition,
+ );
- // Filter already uses correct ID
- return filter;
- })
- .filter((f): f is NonNullable<typeof f> => f !== null);
+ // Validate that columns exist (remove invalid ones)
+ return normalized.filter((filter) => {
+ return filterColumnDefinition.some(
+ (def) => def.id === filter.column || def.name === filter.column,
+ );
+ });
}
diff --git a/web/src/features/filters/filter-integration.clienttest.ts b/web/src/features/filters/filter-integration.clienttest.ts
index ca0993b0cb..6487df04ec 100644
--- a/web/src/features/filters/filter-integration.clienttest.ts
+++ b/web/src/features/filters/filter-integration.clienttest.ts
@@ -18,6 +18,9 @@ import {
import { validateFilters } from "@/src/components/table/table-view-presets/validation";
import { traceFilterConfig } from "./config/traces-config";
import { observationFilterConfig } from "./config/observations-config";
+import { transformFiltersForBackend } from "./lib/filter-transform";
+import { sessionFilterConfig } from "./config/sessions-config";
+import { decodeAndNormalizeFilters } from "./hooks/useSidebarFilterState";
const mockColumnMap: ColumnToQueryKeyMap = {
name: "name",
@@ -567,3 +570,45 @@ describe("Config Validation of old saved views", () => {
expect(invalidFacets).toEqual([]);
});
});
+
+describe("Filter Flow: URL → Decode → Normalize → Transform", () => {
+ it("should preserve multiple string contains filters from URL", () => {
+ // environment contains "e" AND environment contains "a"
+ // These create valid SQL: WHERE env LIKE '%e%' AND env LIKE '%a%'
+ const urlFilter =
+ "environment;string;;contains;e,environment;string;;contains;a";
+
+ const normalized = decodeAndNormalizeFilters(
+ urlFilter,
+ sessionFilterConfig.columnToQueryKey,
+ sessionFilterConfig.columnDefinitions,
+ {},
+ );
+
+ const result = transformFiltersForBackend(normalized, {});
+
+ // Both filters preserved
+ expect(result).toHaveLength(2);
+ expect(result[0]?.value).toBe("e");
+ expect(result[1]?.value).toBe("a");
+ });
+
+ it("should handle backend column remapping from URL", () => {
+ // Observations/traces table: "tags" (frontend) → "traceTags" (ClickHouse backend)
+ const urlFilter = "tags;arrayOptions;;any of;tag1";
+
+ const normalized = decodeAndNormalizeFilters(
+ urlFilter,
+ { tags: "tags" },
+ traceFilterConfig.columnDefinitions,
+ {},
+ );
+
+ const result = transformFiltersForBackend(normalized, {
+ tags: "traceTags",
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0]?.column).toBe("traceTags");
+ });
+});
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
index edcaf8a418..1ca1cf57c5 100644
--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -4,15 +4,68 @@ import {
type FilterState,
singleFilter,
type SingleValueOption,
+ type ColumnDefinition,
} from "@langfuse/shared";
import {
computeSelectedValues,
encodeFiltersGeneric,
decodeFiltersGeneric,
+ type GenericFilterOptions,
+ type ColumnToQueryKeyMap,
} from "../lib/filter-query-encoding";
+import { normalizeFilterColumnNames } from "../lib/filter-transform";
import useSessionStorage from "@/src/components/useSessionStorage";
import type { FilterConfig } from "../lib/filter-config";
+/**
+ * Decodes filters from URL query string and normalizes display names to column IDs.
+ * This prevents duplicates when old URLs use display names and new filters use column IDs.
+ *
+ * @param filtersQuery - Encoded filter string from URL
+ * @param columnToQueryKey - Mapping of column IDs to query keys
+ * @param columnDefinitions - Column definitions for validation and normalization
+ * @param options - Available filter options
+ * @returns Normalized and validated FilterState
+ */
+export function decodeAndNormalizeFilters(
+ filtersQuery: string,
+ columnToQueryKey: ColumnToQueryKeyMap,
+ columnDefinitions: ColumnDefinition[],
+ options: GenericFilterOptions,
+): FilterState {
+ try {
+ const filters = decodeFiltersGeneric(
+ filtersQuery,
+ columnToQueryKey,
+ options,
+ (column) => {
+ const columnDef = columnDefinitions.find((col) => col.id === column);
+ return columnDef?.type || "stringOptions";
+ },
+ );
+
+ // Normalize display names to column IDs immediately after decoding
+ // This prevents duplicates when old URLs use display names (e.g., "Environment")
+ // and user adds new filters with column IDs (e.g., "environment")
+ const normalized = normalizeFilterColumnNames(filters, columnDefinitions);
+
+ // Validate normalized filters
+ const result: FilterState = [];
+ for (const filter of normalized) {
+ const validationResult = singleFilter.safeParse(filter);
+ if (validationResult.success) {
+ result.push(validationResult.data);
+ } else {
+ console.warn(`Invalid filter skipped:`, filter, validationResult.error);
+ }
+ }
+ return result;
+ } catch (error) {
+ console.error("Error decoding filters:", error);
+ return [];
+ }
+}
+
function computeNumericRange(
column: string,
filterState: FilterState,
@@ -227,38 +280,12 @@ export function useSidebarFilterState(
);
const filterState: FilterState = useMemo(() => {
- try {
- const filters = decodeFiltersGeneric(
- filtersQuery,
- config.columnToQueryKey,
- options,
- (column) => {
- const columnDef = config.columnDefinitions.find(
- (col) => col.id === column,
- );
- return columnDef?.type || "stringOptions";
- },
- );
-
- // Validate filters
- const result: FilterState = [];
- for (const filter of filters) {
- const validationResult = singleFilter.safeParse(filter);
- if (validationResult.success) {
- result.push(validationResult.data);
- } else {
- console.warn(
- `Invalid filter skipped:`,
- filter,
- validationResult.error,
- );
- }
- }
- return result;
- } catch (error) {
- console.error("Error decoding filters:", error);
- return [];
- }
+ return decodeAndNormalizeFilters(
+ filtersQuery,
+ config.columnToQueryKey,
+ config.columnDefinitions,
+ options,
+ );
}, [
filtersQuery,
config.columnToQueryKey,
diff --git a/web/src/features/filters/lib/filter-transform.ts b/web/src/features/filters/lib/filter-transform.ts
index a9932d19b3..775e31f4f1 100644
--- a/web/src/features/filters/lib/filter-transform.ts
+++ b/web/src/features/filters/lib/filter-transform.ts
@@ -8,53 +8,54 @@ import { type FilterState, type ColumnDefinition } from "@langfuse/shared";
export type ColumnToBackendKeyMap = Record<string, string>;
/**
- * Normalizes filter column names to IDs and transforms to backend-expected IDs
+ * Normalizes filter column names from display names to column IDs
+ * Handles backward compatibility where old URLs/saved views used display names ("Environment")
+ * and new system uses column IDs ("environment")
*
- * Performs two transformations:
- * 1. Name → ID normalization: "Environment" → "environment"
- * 2. Frontend ID → Backend ID remapping: "tags" → "traceTags" (for CH column mapping)
+ * @param filters - FilterState that may contain display names or column IDs
+ * @param columnDefinitions - Column definitions for lookup
+ * @returns FilterState with all column names normalized to IDs
+ */
+export function normalizeFilterColumnNames(
+ filters: FilterState,
+ columnDefinitions: ColumnDefinition[],
+): FilterState {
+ return filters.map((filter) => {
+ const colDef = columnDefinitions.find(
+ (c) => c.id === filter.column || c.name === filter.column,
+ );
+ if (colDef && colDef.id !== filter.column) {
+ return { ...filter, column: colDef.id };
+ }
+ return filter;
+ });
+}
+
+/**
+ * Transforms frontend filter column IDs to backend-expected column IDs
*
- * @param filters - FilterState from frontend (may have names or IDs)
- * @param columnMap - Mapping of frontend column ID -> backend column ID
- * @param columnDefinitions - Column definitions for name→id normalization
- * @returns Transformed FilterState with normalized and backend-mapped column IDs
+ * Note: Display name normalization ("Environment" → "environment") now happens earlier
+ * in useSidebarFilterState after URL decoding. This function only handles backend remapping.
+ *
+ * @param filters - FilterState from frontend (already has column IDs, not display names)
+ * @param columnMap - Mapping of frontend column ID -> backend column ID (e.g., "tags" → "traceTags")
+ * @param columnDefinitions - Not used anymore (kept for backward compatibility)
+ * @returns FilterState with backend-mapped column IDs
*/
export function transformFiltersForBackend(
filters: FilterState,
columnMap: ColumnToBackendKeyMap,
- columnDefinitions?: ColumnDefinition[],
+ _columnDefinitions?: ColumnDefinition[],
): FilterState {
return filters.map((filter) => {
- let normalizedColumn = filter.column;
-
- // Step 1: Normalize column name to ID (if columnDefinitions provided)
- // This handles filters created by PopoverFilterBuilder that use column.name instead of column.id
- if (columnDefinitions) {
- const colDef = columnDefinitions.find(
- (c) => c.id === filter.column || c.name === filter.column,
- );
- if (colDef && colDef.id !== filter.column) {
- normalizedColumn = colDef.id;
- }
- }
-
- // Step 2: Apply backend column remapping (e.g., "tags" → "traceTags")
- const backendColumnId = columnMap[normalizedColumn];
- if (backendColumnId && backendColumnId !== normalizedColumn) {
+ // Apply backend column remapping (e.g., "tags" → "traceTags" for ClickHouse)
+ const backendColumnId = columnMap[filter.column];
+ if (backendColumnId && backendColumnId !== filter.column) {
return {
...filter,
column: backendColumnId,
};
}
-
- // Return with normalized column if it changed
- if (normalizedColumn !== filter.column) {
- return {
- ...filter,
- column: normalizedColumn,
- };
- }
-
return filter;
});
}
diff --git a/web/src/hooks/use-environment-filter.tsx b/web/src/hooks/use-environment-filter.tsx
index e8c0ddb4a9..c99416e15a 100644
--- a/web/src/hooks/use-environment-filter.tsx
+++ b/web/src/hooks/use-environment-filter.tsx
@@ -13,13 +13,8 @@ export function convertSelectedEnvironmentsToFilter(
selectedEnvironments: string[],
) {
if (selectedEnvironments.length === 0) {
- // No environments selected = show nothing
- return environmentColumns.map((column) => ({
- type: "stringOptions" as const,
- column,
- operator: "any of" as const,
- value: ["__NEVER_MATCH_ANYTHING__"], // Impossible value to match
- }));
+ // No environments selected = no filter (show all)
+ return [];
}
return environmentColumns.map((column) => ({