🪢 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(ingestion): add app root detection (#13718)
Hassieb Pakzad1fc22b4f1011
diff --git a/packages/shared/clickhouse/scripts/dev-tables.sh b/packages/shared/clickhouse/scripts/dev-tables.shindex c51850c760..59dd0a443f 100644--- a/packages/shared/clickhouse/scripts/dev-tables.sh+++ b/packages/shared/clickhouse/scripts/dev-tables.sh@@ -157,6 +157,7 @@ CREATE TABLE IF NOT EXISTS events_fulllevel LowCardinality(String),status_message String, -- Threat '' and null the same for searchcompletion_start_time Nullable(DateTime64(6)),+ is_app_root Bool DEFAULT false,-- Updateable propertiesbookmarked Bool DEFAULT false,@@ -304,6 +305,7 @@ CREATE TABLE IF NOT EXISTS events_corelevel LowCardinality(String),status_message String,completion_start_time Nullable(DateTime64(6)),+ is_app_root Bool DEFAULT false,-- Updateable propertiesbookmarked Bool DEFAULT false,@@ -429,6 +431,7 @@ SELECTlevel,status_message,completion_start_time,+ is_app_root,bookmarked,public,prompt_id,diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.tsindex edec4f84ae..c88647ee96 100644--- a/packages/shared/src/eventsTable.ts+++ b/packages/shared/src/eventsTable.ts@@ -1,5 +1,9 @@import { type ColumnDefinition } from "./tableDefinitions";+export const eventsTableHasParentObservationSql = "e.parent_span_id != ''";+export const eventsTableIsRootObservationSql =+ "(e.parent_span_id = '' OR e.is_app_root = true)";+type MutableDeep<T> = T extends readonly (infer U)[]? MutableDeep<U>[]: T extends object@@ -274,7 +278,13 @@ const eventsTableColsDefinition = [name: "Has Parent Observation",id: "hasParentObservation",type: "boolean",- internal: "e.parent_span_id != ''",+ internal: eventsTableHasParentObservationSql,+ },+ {+ name: "Is Root Observation",+ id: "isRootObservation",+ type: "boolean",+ internal: eventsTableIsRootObservationSql,},{name: "Experiment Dataset ID",diff --git a/packages/shared/src/server/llm/internalTraceEvents.ts b/packages/shared/src/server/llm/internalTraceEvents.tsindex 873b7234a4..567f2d33a5 100644--- a/packages/shared/src/server/llm/internalTraceEvents.ts+++ b/packages/shared/src/server/llm/internalTraceEvents.ts@@ -53,6 +53,7 @@ export type InternalTraceEventInput = {tags?: string[];bookmarked?: boolean;public?: boolean;+ isAppRoot?: boolean | null;userId?: string;sessionId?: string;level?: string;diff --git a/packages/shared/src/server/otel/OtelIngestionProcessor.ts b/packages/shared/src/server/otel/OtelIngestionProcessor.tsindex 05befda789..bb5e870ee7 100644--- a/packages/shared/src/server/otel/OtelIngestionProcessor.ts+++ b/packages/shared/src/server/otel/OtelIngestionProcessor.ts@@ -458,6 +458,7 @@ export class OtelIngestionProcessor {// Propertiestags: this.extractTags(spanAttributes),public: this.extractPublic(spanAttributes),+ isAppRoot: this.extractIsAppRoot(spanAttributes),traceName:spanAttributes?.[LangfuseOtelSpanAttributes.TRACE_NAME] ??null,@@ -943,6 +944,12 @@ export class OtelIngestionProcessor {return value === true || value === "true";}+ private extractIsAppRoot(attributes?: Record<string, unknown>): boolean {+ const value = attributes?.[LangfuseOtelSpanAttributes.IS_APP_ROOT];++ return value === true || value === "true";+ }+private createObservationEvent(params: CreateObservationEventParams,): IngestionEventType {diff --git a/packages/shared/src/server/otel/attributes.ts b/packages/shared/src/server/otel/attributes.tsindex bfe71d1688..43ee33163a 100644--- a/packages/shared/src/server/otel/attributes.ts+++ b/packages/shared/src/server/otel/attributes.ts@@ -33,6 +33,7 @@ export enum LangfuseOtelSpanAttributes {// InternalAS_ROOT = "langfuse.internal.as_root",+ IS_APP_ROOT = "langfuse.internal.is_app_root",// Compatibility - Map properties that were documented in https://langfuse.com/docs/opentelemetry/get-started#property-mapping,// but have a new assignmentdiff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.tsindex 36b8fb7895..b7b5f8fea9 100644--- a/packages/shared/src/server/repositories/definitions.ts+++ b/packages/shared/src/server/repositories/definitions.ts@@ -651,6 +651,7 @@ export const eventRecordBaseSchema = z.object({trace_name: z.string().nullish(),user_id: z.string().nullish(),session_id: z.string().nullish(),+ is_app_root: z.boolean().default(false),// User updatable flagstags: z.array(z.string()).default([]),diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.tsindex e65d759dc4..8b2dc09d20 100644--- a/packages/shared/src/server/repositories/events.ts+++ b/packages/shared/src/server/repositories/events.ts@@ -96,11 +96,15 @@ import {OrderByEntry,} from "../queries/clickhouse-sql/event-query-builder";import { type EventsObservationPublic } from "../queries/createGenerationsQuery";+import {+ eventsTableCols,+ eventsTableHasParentObservationSql,+ eventsTableIsRootObservationSql,+} from "../../eventsTable";import {findUiColumnMapping,type UiColumnMappings,} from "../../tableDefinitions";-import { eventsTableCols } from "../../eventsTable";import { tracesTableCols } from "../../tableDefinitions/tracesTable";import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";@@ -2504,8 +2508,7 @@ export const getEventsGroupedByExperimentName = async (};/**- * Get grouped hasParentObservation boolean from events table- * Used for filter options (counts for "Is Root Observation" facet)+ * Get grouped literal parent-pointer boolean from events table.*/export const getEventsGroupedByHasParentObservation = async (projectId: string,@@ -2524,9 +2527,8 @@ export const getEventsGroupedByHasParentObservation = async (const queryBuilder = new EventsAggQueryBuilder({projectId,- groupByColumn: "(e.parent_span_id != '')",- selectExpression:- "(e.parent_span_id != '') as hasParentObservation, count() as count",+ groupByColumn: eventsTableHasParentObservationSql,+ selectExpression: `${eventsTableHasParentObservationSql} as hasParentObservation, count() as count`,}).where(appliedEventsFilter).orderBy(opts?.orderBy ?? "ORDER BY hasParentObservation ASC")@@ -2547,6 +2549,48 @@ export const getEventsGroupedByHasParentObservation = async (});};+/**+ * Get grouped root observation boolean from events table.+ * Used for filter options for the "Is Root Observation" facet.+ */+export const getEventsGroupedByIsRootObservation = async (+ projectId: string,+ filter: FilterState,+) => {+ const eventsFilter = new FilterList(+ createFilterFromFilterState(+ filter,+ eventsTableUiColumnDefinitions,+ eventsTableCols,+ ),+ );++ const appliedEventsFilter = eventsFilter.apply();++ const queryBuilder = new EventsAggQueryBuilder({+ projectId,+ groupByColumn: eventsTableIsRootObservationSql,+ selectExpression: `${eventsTableIsRootObservationSql} as isRootObservation, count() as count`,+ })+ .where(appliedEventsFilter)+ .orderBy("ORDER BY isRootObservation ASC")+ .limit(2, 0);++ const { query, params } = queryBuilder.buildWithParams();++ return queryClickhouse<{ isRootObservation: boolean; count: number }>({+ query,+ params,+ tags: {+ feature: "tracing",+ type: "events",+ kind: "analytic",+ projectId,+ },+ preferredClickhouseService: "EventsReadOnly",+ });+};+/*** Get grouped available tool names from events table* Used for filter optionsdiff --git a/packages/shared/src/server/services/TableViewService/systemPresets.ts b/packages/shared/src/server/services/TableViewService/systemPresets.tsindex 5150f0e511..2cf1966c31 100644--- a/packages/shared/src/server/services/TableViewService/systemPresets.ts+++ b/packages/shared/src/server/services/TableViewService/systemPresets.ts@@ -52,10 +52,10 @@ const OBSERVATIONS_EVENTS_SYSTEM_TABLE_VIEW_PRESETS: SystemTableViewPreset[] = [tableName: TableViewPresetTableName.ObservationsEvents,filters: [{- column: "hasParentObservation",+ column: "isRootObservation",type: "boolean",operator: "=",- value: false,+ value: true,},],}),diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.tsindex 0203f4dd98..f9089bcb71 100644--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts@@ -2,6 +2,10 @@// The frontend only sends the column names to the backend. This needs to be changed in the future to send column IDs.import { UiColumnMappings } from "../../tableDefinitions";+import {+ eventsTableHasParentObservationSql,+ eventsTableIsRootObservationSql,+} from "../../eventsTable";export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [{@@ -232,7 +236,13 @@ export const eventsTableNativeUiColumnDefinitions: UiColumnMappings = [uiTableName: "Has Parent Observation",uiTableId: "hasParentObservation",clickhouseTableName: "events_proto",- clickhouseSelect: "e.parent_span_id != ''",+ clickhouseSelect: eventsTableHasParentObservationSql,+ },+ {+ uiTableName: "Is Root Observation",+ uiTableId: "isRootObservation",+ clickhouseTableName: "events_proto",+ clickhouseSelect: eventsTableIsRootObservationSql,},{uiTableName: "Parent Observation ID",diff --git a/packages/shared/src/server/test-utils/tracing-factory.ts b/packages/shared/src/server/test-utils/tracing-factory.tsindex bb04e023d6..421f3d20d9 100644--- a/packages/shared/src/server/test-utils/tracing-factory.ts+++ b/packages/shared/src/server/test-utils/tracing-factory.ts@@ -232,6 +232,7 @@ export const createEvent = (user_id: null,session_id: null,+ is_app_root: false,level: "DEFAULT",status_message: null,diff --git a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts b/web/src/__tests__/server/api/otel/otelMapping.servertest.tsindex 098039a33e..851df107b1 100644--- a/web/src/__tests__/server/api/otel/otelMapping.servertest.ts+++ b/web/src/__tests__/server/api/otel/otelMapping.servertest.ts@@ -1210,6 +1210,50 @@ describe("OTel Resource Span Mapping", () => {},};+ it.each([+ ["missing attribute", undefined, false],+ ["boolean true", { boolValue: true }, true],+ ["string true", { stringValue: "true" }, true],+ ["boolean false", { boolValue: false }, false],+ ["string false", { stringValue: "false" }, false],+ ])(+ "should extract isAppRoot from %s",+ (+ _name: string,+ otelAttributeValue: Record<string, unknown> | undefined,+ expectedIsAppRoot: boolean,+ ) => {+ const attributes = otelAttributeValue+ ? [+ {+ key: "langfuse.internal.is_app_root",+ value: otelAttributeValue,+ },+ ]+ : [];+ const resourceSpan = {+ scopeSpans: [+ {+ spans: [+ {+ ...defaultSpanProps,+ attributes,+ },+ ],+ },+ ],+ };++ const processor = new OtelIngestionProcessor({+ projectId: "test-project",+ });+ const eventInputs = processor.processToEvent([resourceSpan]);++ expect(eventInputs).toHaveLength(1);+ expect(eventInputs[0].isAppRoot).toBe(expectedIsAppRoot);+ },+ );+const aiSdkWeatherToolInputSchema = {type: "object",properties: {diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsxindex a53b71a3f2..c0863d608a 100644--- a/web/src/components/session/index.tsx+++ b/web/src/components/session/index.tsx@@ -632,9 +632,12 @@ export const SessionEventsPage: React.FC<{...observationEventsFilterConfig.columnDefinitions,positionInTraceColumn,],+ migrateFilterState: undefined,facets: observationEventsFilterConfig.facets.filter((facet) =>- facet.column !== "sessionId" && facet.column !== "environment",+ facet.column !== "sessionId" &&+ facet.column !== "isRootObservation" &&+ facet.column !== "environment",),};}, [positionInTraceColumn, sessionEventsTableName]);@@ -682,6 +685,7 @@ export const SessionEventsPage: React.FC<{(column) =>column.id !== "sessionId" &&column.id !== "hasParentObservation" &&+ column.id !== "isRootObservation" &&column.id !== "environment" &&column.id !== "traceId" &&column.id !== "traceName" &&@@ -753,6 +757,8 @@ export const SessionEventsPage: React.FC<{filter.column !== "sessionId" &&filter.column !== "Has Parent Observation" &&filter.column !== "hasParentObservation" &&+ filter.column !== "Is Root Observation" &&+ filter.column !== "isRootObservation" &&filter.column !== "environment" &&filter.column !== "traceId" &&filter.column !== "traceName" &&diff --git a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts b/web/src/components/table/table-view-presets/hooks/useTableViewManager.tsindex ddde8448e1..18c3ba6558 100644--- a/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts+++ b/web/src/components/table/table-view-presets/hooks/useTableViewManager.ts@@ -18,6 +18,7 @@ import isEqual from "lodash/isEqual";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { validateOrderBy, validateFilters } from "../validation";import { isSystemPresetId } from "../components/data-table-view-presets-drawer";+import type { FilterStateMigration } from "@/src/features/filters/lib/filter-config";interface TableStateUpdaters {setColumnOrder: (columnOrder: string[]) => void;@@ -36,6 +37,7 @@ interface UseTableStateProps {columns?: LangfuseColumnDef<any, any>[];filterColumnDefinition?: ColumnDefinition[];expandableFilterColumns?: string[];+ migrateFilterState?: FilterStateMigration;};currentFilterState?: FilterState;currentExpandedFilters?: string[];@@ -253,6 +255,7 @@ export function useTableViewManager({validFilters = validateFilters(viewData.filters,validationContext.filterColumnDefinition,+ validationContext.migrateFilterState,);}@@ -294,7 +297,7 @@ export function useTableViewManager({// Track expected filters to observe when state actually updates (for useEffect below)// If filters are already applied, don't set pending ref (will unlock immediately).// Also track pre-apply state so we can unlock when filters propagate but get- // canonicalized into an equivalent shape by downstream hooks.+ // migrated into an equivalent shape by downstream hooks.if (!filtersAlreadyApplied) {pendingFiltersRef.current = validFilters;pendingFiltersPreviousStateRef.current = currentFilterState ?? [];diff --git a/web/src/components/table/table-view-presets/validation.ts b/web/src/components/table/table-view-presets/validation.tsindex ceee4d0e37..77e1981b9d 100644--- a/web/src/components/table/table-view-presets/validation.ts+++ b/web/src/components/table/table-view-presets/validation.ts@@ -5,6 +5,7 @@ import {type OrderByState,} from "@langfuse/shared";import { normalizeFilterColumnNames } from "@/src/features/filters/lib/filter-transform";+import type { FilterStateMigration } from "@/src/features/filters/lib/filter-config";/*** Validates if an orderBy state references valid columns.@@ -63,6 +64,7 @@ export function validateOrderBy(export function validateFilters(filters: FilterState,filterColumnDefinition?: ColumnDefinition[],+ migrateFilterState?: FilterStateMigration,): FilterState {if (!filterColumnDefinition || filterColumnDefinition.length === 0)return filters;@@ -72,10 +74,13 @@ export function validateFilters(filters,filterColumnDefinition,);+ const migrated = migrateFilterState+ ? migrateFilterState(normalized)+ : normalized;// Validate that columns exist (remove invalid ones)// After normalization, filter.column is always a canonical ID- return normalized.filter((filter) => {+ return migrated.filter((filter) => {return filterColumnDefinition.some((def) => def.id === filter.column);});}diff --git a/web/src/features/events/components/EventsTable.tsx b/web/src/features/events/components/EventsTable.tsxindex 38e8eb4032..3331a679bf 100644--- a/web/src/features/events/components/EventsTable.tsx+++ b/web/src/features/events/components/EventsTable.tsx@@ -255,12 +255,12 @@ export default function ObservationsEventsTable({// RE-ENABLING THE VIEW MODE TOGGLE:// To re-enable, uncomment the code below AND the viewModeFilter, viewModeToggle,// auto-switch logic, and imports further down. However, note that the sidebar now- // has an "Is Root Observation" boolean facet that also controls `hasParentObservation`.+ // has an "Is Root Observation" boolean facet for `isRootObservation`.// Having BOTH active would create duplicate/conflicting filters. Pick one:// - Sidebar facet only (current): remove this commented code entirely// - Toolbar toggle only: uncomment this code, remove the boolean facet from- // web/src/features/events/config/filter-config.ts, and re-add- // `hasParentObservation` param to the useEventsFilterOptions call below+ // web/src/features/events/config/filter-config.ts, and scope filter options+ // by the active view mode// - Both: would need deduplication logic to prevent conflicting filters//// View mode toggle (Trace vs Observation)@@ -277,7 +277,7 @@ export default function ObservationsEventsTable({// string | null// >(`eventsAutoSwitchRange-${projectId}`, null);//- // const hasParentObservation = viewMode === "observation" ? undefined : false;+ // const isRootObservation = viewMode === "trace" ? true : undefined;//// const setViewMode = useCallback(// (mode: EventsViewMode) => {@@ -417,10 +417,10 @@ export default function ObservationsEventsTable({// viewMode === "trace"// ? [// {- // column: "hasParentObservation",+ // column: "isRootObservation",// type: "boolean",// operator: "=",- // value: false,+ // value: true,// },// ]// : [];@@ -1234,6 +1234,7 @@ export default function ObservationsEventsTable({expandableFilterColumns: eventsFilterConfig.facets.map((facet) => facet.column,),+ migrateFilterState: eventsFilterConfig.migrateFilterState,},currentFilterState: queryFilter.explicitFilterState,currentExpandedFilters: queryFilter.expanded,diff --git a/web/src/features/events/config/filter-config.ts b/web/src/features/events/config/filter-config.tsindex 285d0f681c..607c10df23 100644--- a/web/src/features/events/config/filter-config.ts+++ b/web/src/features/events/config/filter-config.ts@@ -1,4 +1,4 @@-import { eventsTableCols } from "@langfuse/shared";+import { eventsTableCols, type FilterState } from "@langfuse/shared";import {omitFilterFacets,type FilterConfig,@@ -23,6 +23,58 @@ export const OBSERVATION_EVENTS_COLUMN_TO_BACKEND_KEY: ColumnToBackendKeyMap = {// No mapping needed currently - events table column names align with UI};+const isBooleanEqualityOperator = (operator: string): operator is "=" | "<>" =>+ operator === "=" || operator === "<>";++export const migrateLegacyRootObservationFilters = (+ filters: FilterState,+): FilterState => {+ const hasRootObservationFilter = filters.some(+ (filter) =>+ filter.column === "isRootObservation" &&+ filter.type === "boolean" &&+ isBooleanEqualityOperator(filter.operator),+ );++ return filters.flatMap((filter) => {+ if (+ filter.column === "isRootObservation" &&+ filter.type === "boolean" &&+ isBooleanEqualityOperator(filter.operator)+ ) {+ return [+ {+ ...filter,+ operator: "=" as const,+ value: filter.operator === "<>" ? !filter.value : filter.value,+ },+ ];+ }++ if (+ (filter.column === "hasParentObservation" ||+ filter.column === "Has Parent Observation") &&+ filter.type === "boolean" &&+ isBooleanEqualityOperator(filter.operator)+ ) {+ if (hasRootObservationFilter) {+ return [];+ }++ return [+ {+ ...filter,+ column: "isRootObservation",+ operator: "=" as const,+ value: filter.operator === "=" ? !filter.value : filter.value,+ },+ ];+ }++ return [filter];+ });+};+export type ObservationEventsOmittableFilterColumn = "sessionId" | "userId";export const observationEventsFilterConfig: FilterConfig = {@@ -30,7 +82,9 @@ export const observationEventsFilterConfig: FilterConfig = {columnDefinitions: eventsTableCols,- defaultExpanded: ["environment", "name", "hasParentObservation", "type"],+ defaultExpanded: ["environment", "name", "isRootObservation", "type"],++ migrateFilterState: migrateLegacyRootObservationFilters,facets: [{@@ -46,11 +100,10 @@ export const observationEventsFilterConfig: FilterConfig = {},{type: "boolean" as const,- column: "hasParentObservation",+ column: "isRootObservation",label: "Is Root Observation",tooltip:- "A root observation is the top-level observation in a trace. It has no parent observation ID. Filter to 'True' to see only root-level observations.",- invertValue: true, // "True" = hasParentObservation=false (is root)+ "A root observation is top-level in a trace or marked as an app root by the SDK. Filter to 'True' to see root-level observations.",},{type: "categorical" as const,diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.tsindex 418f0b723b..1c095d815a 100644--- a/web/src/features/events/hooks/useEventsFilterOptions.ts+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts@@ -5,13 +5,13 @@ import { type FilterState, type TimeFilter } from "@langfuse/shared";type UseEventsFilterOptionsParams = {projectId: string;oldFilterState: FilterState;- hasParentObservation?: boolean;+ isRootObservation?: boolean;};export function useEventsFilterOptions({projectId,oldFilterState,- hasParentObservation,+ isRootObservation,}: UseEventsFilterOptionsParams) {// Extract start time filters for filter options queryconst startTimeFilters = useMemo(() => {@@ -28,7 +28,7 @@ export function useEventsFilterOptions({projectId,startTimeFilter:startTimeFilters.length > 0 ? startTimeFilters : undefined,- hasParentObservation,+ isRootObservation,},{trpc: {@@ -85,8 +85,7 @@ export function useEventsFilterOptions({experimentDatasetId: filterOptions.data?.experimentDatasetId ?? undefined,experimentId: filterOptions.data?.experimentId ?? undefined,experimentName: filterOptions.data?.experimentName ?? undefined,- hasParentObservation:- filterOptions.data?.hasParentObservation ?? undefined,+ isRootObservation: filterOptions.data?.isRootObservation ?? undefined,toolNames: filterOptions.data?.toolNames ?? undefined,calledToolNames: filterOptions.data?.calledToolNames ?? undefined,toolDefinitions: [],diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.tsindex d48387d37e..8cae74b6e8 100644--- a/web/src/features/events/server/eventsRouter.ts+++ b/web/src/features/events/server/eventsRouter.ts@@ -153,6 +153,7 @@ export const eventsRouter = createTRPCRouter({zodSchema.object({projectId: zodSchema.string(),startTimeFilter: zodSchema.array(timeFilter).optional(),+ isRootObservation: zodSchema.boolean().optional(),hasParentObservation: zodSchema.boolean().optional(),}),)@@ -167,7 +168,11 @@ export const eventsRouter = createTRPCRouter({return getEventFilterOptions({projectId: input.projectId,startTimeFilter: input.startTimeFilter,- hasParentObservation: input.hasParentObservation,+ isRootObservation:+ input.isRootObservation ??+ (input.hasParentObservation !== undefined+ ? !input.hasParentObservation+ : undefined), // backward compat for legacy hasParentObservation filterOption});},);diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.tsindex 928331b91e..831fc6900c 100644--- a/web/src/features/events/server/eventsService.ts+++ b/web/src/features/events/server/eventsService.ts@@ -24,6 +24,7 @@ import {getEventsGroupedByExperimentId,getEventsGroupedByExperimentName,getEventsGroupedByHasParentObservation,+ getEventsGroupedByIsRootObservation,getEventsGroupedByToolName,getEventsGroupedByCalledToolName,getNumericScoresGroupedByName,@@ -75,6 +76,7 @@ interface GetObservationsCountParams {interface GetObservationsFilterOptionsParams {projectId: string;startTimeFilter?: TimeFilter[];+ isRootObservation?: boolean;hasParentObservation?: boolean;observationType?: string;}@@ -247,11 +249,26 @@ const toFilterValueOptions = <const getEventFilterOptionsScope = (params: GetObservationsFilterOptionsParams,) => {- const { startTimeFilter, hasParentObservation, observationType } = params;-- // Build filter with optional hasParentObservation for scoping filter options+ const {+ startTimeFilter,+ isRootObservation,+ hasParentObservation,+ observationType,+ } = params;++ // Build filter with optional scoping for filter options.const eventsFilter: FilterState = [...(startTimeFilter ?? []),+ ...(isRootObservation !== undefined+ ? [+ {+ column: "isRootObservation" as const,+ type: "boolean" as const,+ operator: "=" as const,+ value: isRootObservation,+ },+ ]+ : []),...(hasParentObservation !== undefined? [{@@ -476,7 +493,7 @@ export async function getEventFilterOptions(experimentDatasetIds,experimentIds,experimentNames,- hasParentObservationResults,+ isRootObservationResults,toolNames,calledToolNames,] = await Promise.all([@@ -501,7 +518,7 @@ export async function getEventFilterOptions(getEventsGroupedByExperimentDatasetId(projectId, eventsFilter),getEventsGroupedByExperimentId(projectId, eventsFilter),getEventsGroupedByExperimentName(projectId, eventsFilter),- getEventsGroupedByHasParentObservation(projectId, eventsFilter),+ getEventsGroupedByIsRootObservation(projectId, eventsFilter),getEventsGroupedByToolName(projectId, eventsFilter),getEventsGroupedByCalledToolName(projectId, eventsFilter),]);@@ -550,9 +567,9 @@ export async function getEventFilterOptions(),experimentId: toFilterValueOptions(experimentIds, "experimentId"),experimentName: toFilterValueOptions(experimentNames, "experimentName"),- hasParentObservation: hasParentObservationResults.map((i) => ({+ isRootObservation: isRootObservationResults.map((i) => ({// ClickHouse returns UInt8 (0/1) for computed boolean; normalize to "true"/"false"- value: i.hasParentObservation ? "true" : "false",+ value: i.isRootObservation ? "true" : "false",count: i.count,})),toolNames: toolNamesdiff --git a/web/src/features/filters/filter-integration.clienttest.ts b/web/src/features/filters/filter-integration.clienttest.tsindex 90b2a2151d..963ac4e5ef 100644--- a/web/src/features/filters/filter-integration.clienttest.ts+++ b/web/src/features/filters/filter-integration.clienttest.ts@@ -642,6 +642,98 @@ describe("Filter Flow: URL → Decode → Normalize → Transform", () => {expect(normalized).toEqual([]);});++ it.each([+ ["column ID", "hasParentObservation", "=", false, true],+ ["display name", "Has Parent Observation", "=", false, true],+ ["column ID", "hasParentObservation", "<>", true, true],+ ["display name", "Has Parent Observation", "<>", true, true],+ ] as const)(+ "should redirect legacy %s root-observation URL filters to isRootObservation",+ (_label, column, operator, legacyValue, expectedValue) => {+ const legacyFilters: FilterState = [+ {+ column,+ type: "boolean",+ operator,+ value: legacyValue,+ },+ ];++ const normalized = decodeAndNormalizeFilters(+ encodeFiltersGeneric(legacyFilters),+ observationEventsFilterConfig.columnDefinitions,+ observationEventsFilterConfig.migrateFilterState,+ );++ expect(normalized).toEqual([+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: expectedValue,+ },+ ]);+ },+ );++ it("should migrate isRootObservation inequality URL filters for the sidebar", () => {+ const filters: FilterState = [+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "<>",+ value: false,+ },+ ];++ const normalized = decodeAndNormalizeFilters(+ encodeFiltersGeneric(filters),+ observationEventsFilterConfig.columnDefinitions,+ observationEventsFilterConfig.migrateFilterState,+ );++ expect(normalized).toEqual([+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: true,+ },+ ]);+ });++ it("should prefer isRootObservation URL filters over legacy duplicates", () => {+ const filters: FilterState = [+ {+ column: "hasParentObservation",+ type: "boolean",+ operator: "=",+ value: false,+ },+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: false,+ },+ ];++ const normalized = decodeAndNormalizeFilters(+ encodeFiltersGeneric(filters),+ observationEventsFilterConfig.columnDefinitions,+ observationEventsFilterConfig.migrateFilterState,+ );++ expect(normalized).toEqual([+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: false,+ },+ ]);+ });});describe("Saved view validation", () => {@@ -660,6 +752,42 @@ describe("Saved view validation", () => {).toEqual([]);});+ it.each([+ ["column ID", "hasParentObservation", false, true, "="],+ ["display name", "Has Parent Observation", false, true, "="],+ ["column ID", "hasParentObservation", true, false, "="],+ ["display name", "Has Parent Observation", true, false, "="],+ ["column ID", "hasParentObservation", true, true, "<>"],+ ["display name", "Has Parent Observation", true, true, "<>"],+ ] as const)(+ "should redirect legacy %s root-observation saved-view filters to isRootObservation",+ (_label, column, legacyValue, expectedValue, operator) => {+ const filters: FilterState = [+ {+ column,+ type: "boolean",+ operator,+ value: legacyValue,+ },+ ];++ expect(+ validateFilters(+ filters,+ observationEventsFilterConfig.columnDefinitions,+ observationEventsFilterConfig.migrateFilterState,+ ),+ ).toEqual([+ {+ column: "isRootObservation",+ type: "boolean",+ operator: "=",+ value: expectedValue,+ },+ ]);+ },+ );+it("should preserve the session detail positionInTrace presets when the session view defines the column", () => {const sessionEventColumns: ColumnDefinition[] = [...observationEventsFilterConfig.columnDefinitions,diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsxindex 49ed35238c..7efe78e094 100644--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx@@ -28,7 +28,7 @@ import {import { areStringSetsEqual } from "../lib/stringSetUtils";import { useKeyedSessionStorageState } from "./useKeyedSessionStorageState";import useSessionStorage from "@/src/components/useSessionStorage";-import type { FilterConfig } from "../lib/filter-config";+import type { FilterConfig, FilterStateMigration } from "../lib/filter-config";import type { PeekTableStateContextValue } from "@/src/components/table/peek/contexts/PeekTableStateContext";/**@@ -42,6 +42,7 @@ import type { PeekTableStateContextValue } from "@/src/components/table/peek/conexport function decodeAndNormalizeFilters(filtersQuery: string,columnDefinitions: ColumnDefinition[],+ migrateFilterState?: FilterStateMigration,): FilterState {try {const filters = decodeFiltersGeneric(filtersQuery);@@ -59,10 +60,13 @@ export function decodeAndNormalizeFilters(// 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);+ const migrated = migrateFilterState+ ? migrateFilterState(normalized)+ : normalized;// Validate normalized filtersconst result: FilterState = [];- for (const filter of normalized) {+ for (const filter of migrated) {const validationResult = singleFilter.safeParse(filter);if (validationResult.success) {const canonicalColumnId = knownColumns.get(@@ -516,9 +520,14 @@ export function useSidebarFilterState(return "";})();- return decodeAndNormalizeFilters(rawQuery, config.columnDefinitions);+ return decodeAndNormalizeFilters(+ rawQuery,+ config.columnDefinitions,+ config.migrateFilterState,+ );}, [config.columnDefinitions,+ config.migrateFilterState,stateLocationType,pendingFiltersQuery,urlFiltersQuery,diff --git a/web/src/features/filters/lib/filter-config.ts b/web/src/features/filters/lib/filter-config.tsindex 4a52c95939..919571a40e 100644--- a/web/src/features/filters/lib/filter-config.ts+++ b/web/src/features/filters/lib/filter-config.ts@@ -1,5 +1,5 @@import type React from "react";-import type { ColumnDefinition } from "@langfuse/shared";+import type { ColumnDefinition, FilterState } from "@langfuse/shared";interface BaseFacet {column: string;@@ -19,7 +19,7 @@ interface BooleanFacet extends BaseFacet {type: "boolean";trueLabel?: string;falseLabel?: string;- invertValue?: boolean; // When true, "True" label maps to filter value=false, used for parent_observation_id filter for is Root?+ invertValue?: boolean; // When true, "True" maps to filter value=false.}interface NumericFacet extends BaseFacet {@@ -58,12 +58,16 @@ export type Facet =| NumericKeyValueFacet| StringKeyValueFacet;+export type FilterStateMigration = (filters: FilterState) => FilterState;+export interface FilterConfig {tableName: string;columnDefinitions: ColumnDefinition[];defaultExpanded?: string[];defaultSidebarCollapsed?: boolean;facets: Facet[];+ /** Runs after display-name normalization and before filter validation. */+ migrateFilterState?: FilterStateMigration;}export function omitFilterFacets(diff --git a/worker/src/features/eventPropagation/handleExperimentBackfill.ts b/worker/src/features/eventPropagation/handleExperimentBackfill.tsindex 3605c7032e..ef3d6e87b3 100644--- a/worker/src/features/eventPropagation/handleExperimentBackfill.ts+++ b/worker/src/features/eventPropagation/handleExperimentBackfill.ts@@ -527,6 +527,7 @@ export function writeEnrichedSpans(spans: EnrichedSpan[]): void {tags: span.tags || [],bookmarked: span.bookmarked || false,public: span.public || false,+ is_app_root: false,trace_name: span.trace_name || undefined,user_id: span.user_id || undefined,diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.tsindex 507dccf54b..b78bd4e3c4 100644--- a/worker/src/services/IngestionService/index.ts+++ b/worker/src/services/IngestionService/index.ts@@ -285,6 +285,7 @@ export class IngestionService {tags: eventData.tags ?? [],bookmarked: eventData.bookmarked ?? false,public: eventData.public ?? false,+ is_app_root: eventData.isAppRoot ?? false,// Trace-level attributes: Name/User/sessiontrace_name: eventData.traceName,