Skip to content

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

fix(api): expose logical root observations (#15567)

Valery Meleshkin09d6e6fdd33d
diff --git a/fern/apis/server/definition/commons.yml b/fern/apis/server/definition/commons.yml
index e5abdf04c3..4ddd41cb2e 100644
--- a/fern/apis/server/definition/commons.yml
+++ b/fern/apis/server/definition/commons.yml
@@ -247,12 +247,19 @@ types:
docs: The project ID this observation belongs to
parentObservationId:
type: nullable<string>
- docs: The parent observation ID
+ docs: |
+ The physical parent observation ID, if present.
+ Observations marked as app roots by the SDK may retain a non-null parent ID.
type:
type: string
docs: The type of the observation (e.g. GENERATION, SPAN, EVENT)
# Basic fields (field group: basic)
+ isRootObservation:
+ type: optional<boolean>
+ docs: |
+ Whether this observation is a logical root.
+ This is true for observations without a physical parent and observations marked as app roots by the SDK.
name:
type: optional<nullable<string>>
docs: The name of the observation
diff --git a/fern/apis/server/definition/observations.yml b/fern/apis/server/definition/observations.yml
index 3934c71b26..e8a105753d 100644
--- a/fern/apis/server/definition/observations.yml
+++ b/fern/apis/server/definition/observations.yml
@@ -17,7 +17,7 @@ service:
## Field Selection
Use the `fields` parameter to control which observation fields are returned:
- `core` - Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type
- - `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId
+ - `basic` - name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId, isRootObservation
- `time` - completionStartTime, createdAt, updatedAt
- `io` - input, output
- `metadata` - metadata (truncated to 200 chars by default, use `expandMetadata` to get full values)
@@ -72,7 +72,17 @@ service:
level:
type: optional<commons.ObservationLevel>
docs: Optional filter for observations with a specific level (e.g. "DEBUG", "DEFAULT", "WARNING", "ERROR").
- parentObservationId: optional<string>
+ parentObservationId:
+ type: optional<string>
+ docs: |
+ Filter by the physical parent observation ID.
+ An empty value matches only observations without a physical parent. Use `isRootObservation` to include observations marked as app roots by the SDK, which may retain a non-null `parentObservationId`.
+ isRootObservation:
+ type: optional<boolean>
+ docs: |
+ Filter by whether an observation is a logical root.
+ Root observations include observations without a physical parent and observations marked as app roots by the SDK.
+ An app-root observation may have `isRootObservation=true` and a non-null `parentObservationId`.
environment:
type: optional<string>
allow-multiple: true
@@ -130,6 +140,7 @@ service:
- `version` (string) - Version tag
- `userId` (string) - User ID
- `sessionId` (string) - Session ID
+ - `isRootObservation` (boolean) - Whether the observation is a logical root. Observations marked as app roots by the SDK may retain a non-null parentObservationId.
### Trace-Related Fields
- `traceName` (string) - Name of the parent trace
@@ -190,6 +201,12 @@ service:
"column": "output",
"operator": "matches",
"value": "needle"
+ },
+ {
+ "type": "boolean",
+ "column": "isRootObservation",
+ "operator": "=",
+ "value": true
}
]
```
diff --git a/packages/shared/src/domain/observation-field-groups.ts b/packages/shared/src/domain/observation-field-groups.ts
index 6a3641a8e8..076ed91e41 100644
--- a/packages/shared/src/domain/observation-field-groups.ts
+++ b/packages/shared/src/domain/observation-field-groups.ts
@@ -33,7 +33,7 @@
export const OBSERVATION_FIELD_GROUPS_PUBLIC_API = [
"core", // Always included: id, traceId, startTime, endTime, projectId, parentObservationId, type
- "basic", // name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId
+ "basic", // name, level, statusMessage, version, environment, bookmarked, public, userId, sessionId, isRootObservation
"time", // completionStartTime, createdAt, updatedAt
"io", // input, output
"metadata", // metadata
diff --git a/packages/shared/src/domain/observations.ts b/packages/shared/src/domain/observations.ts
index 58a88dd5d4..64536ebb8e 100644
--- a/packages/shared/src/domain/observations.ts
+++ b/packages/shared/src/domain/observations.ts
@@ -116,6 +116,7 @@ export type ObservationCoreFields = Pick<
export const EventsObservationSchema = ObservationSchema.extend({
userId: z.string().nullable(),
sessionId: z.string().nullable(),
+ isRootObservation: z.boolean().optional(),
traceName: z.string().nullable(),
release: z.string().nullable().optional(),
tags: z.array(z.string()).nullable().optional(),
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
index aec8e22457..395b8b0762 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.test.ts
@@ -7,6 +7,22 @@ import {
EventsSessionAggregationQueryBuilder,
} from "./event-query-builder";
+describe("EventsQueryBuilder public API v2 field groups", () => {
+ it.each([
+ ["basic", true],
+ ["core", false],
+ ] as const)(
+ "projects semantic root status for %s: %s",
+ (fieldSet, selected) => {
+ const query = new EventsQueryBuilder({ projectId: "test-project" })
+ .selectFieldSet(fieldSet)
+ .buildWithParams().query;
+
+ expect(query.includes('"is_root_observation"')).toBe(selected);
+ },
+ );
+});
+
describe("EventsAggregationQueryBuilder", () => {
it("counts distinct non-synthetic observations per trace", () => {
const { query } = new EventsAggregationQueryBuilder({
diff --git a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
index e561dab66f..e120967d0b 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/event-query-builder.ts
@@ -1,7 +1,8 @@
import {
OBSERVATION_FIELD_GROUPS_PUBLIC_API,
- ObservationFieldGroupPublicApi,
+ type ObservationFieldGroupPublicApi,
} from "../../../domain/observation-field-groups";
+import { eventsTableIsRootObservationSql } from "../../../eventsTable";
import { OBSERVATIONS_TO_TRACE_INTERVAL } from "../../repositories/constants";
import { FilterList, StringFilter } from "./clickhouse-filter";
@@ -117,6 +118,7 @@ const EVENTS_FIELDS = {
environment: 'e.environment as "environment"',
type: "e.type as type",
parentObservationId: 'e.parent_span_id as "parent_observation_id"',
+ isRootObservation: `toBool(${eventsTableIsRootObservationSql}) as "is_root_observation"`,
name: "e.name as name",
level: "e.level as level",
statusMessage: 'e.status_message as "status_message"',
@@ -380,6 +382,7 @@ const FIELD_SETS = {
"public",
"userId",
"sessionId",
+ "isRootObservation",
],
time: ["completionStartTime", "createdAt", "updatedAt"],
model: ["providedModelName", "internalModelId", "modelParameters"],
diff --git a/packages/shared/src/server/queries/public-api-filter-builder.ts b/packages/shared/src/server/queries/public-api-filter-builder.ts
index c10a6127a8..af0dddf21e 100644
--- a/packages/shared/src/server/queries/public-api-filter-builder.ts
+++ b/packages/shared/src/server/queries/public-api-filter-builder.ts
@@ -1,3 +1,4 @@
+import { eventsTableIsRootObservationSql } from "../../eventsTable";
import { filterOperators } from "../../interfaces/filters";
import {
FilterList,
@@ -7,6 +8,7 @@ import {
CategoryOptionsFilter,
StringFilter,
NumberFilter,
+ BooleanFilter,
type ClickhouseOperator,
} from "./clickhouse-sql/clickhouse-filter";
import { z } from "zod";
@@ -192,6 +194,16 @@ export function createPublicApiObservationsColumnMapping(
clickhouseTable: tableName,
clickhousePrefix: tablePrefix,
},
+ ...(tableName === "events_proto"
+ ? [
+ {
+ id: "isRootObservation",
+ clickhouseSelect: eventsTableIsRootObservationSql,
+ filterType: "BooleanFilter",
+ clickhouseTable: tableName,
+ },
+ ]
+ : []),
{
id: "fromStartTime",
clickhouseSelect: "start_time",
@@ -342,6 +354,17 @@ export function convertApiProvidedFilterToClickhouseFilter(
}
break;
}
+ case "BooleanFilter":
+ if (typeof value === "boolean") {
+ filterInstance = new BooleanFilter({
+ clickhouseTable: columnMapping.clickhouseTable,
+ field: columnMapping.clickhouseSelect,
+ operator: "=",
+ value,
+ tablePrefix: columnMapping.clickhousePrefix,
+ });
+ }
+ break;
}
filterInstance && filterList.push(filterInstance);
diff --git a/packages/shared/src/server/repositories/definitions.ts b/packages/shared/src/server/repositories/definitions.ts
index 99d8cd684c..552d2c2e5e 100644
--- a/packages/shared/src/server/repositories/definitions.ts
+++ b/packages/shared/src/server/repositories/definitions.ts
@@ -118,6 +118,7 @@ export const eventsObservationRecordReadSchema =
observationRecordReadSchema.extend({
user_id: z.string().nullish(),
session_id: z.string().nullish(),
+ is_root_observation: z.boolean().optional(),
trace_name: z.string().nullish(),
release: z.string().nullish(),
tags: z.array(z.string()).optional(),
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 7a5fe16b28..f5f09f149d 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -94,7 +94,6 @@ import {
import type { AnalyticsObservationEvent } from "../analytics-integrations/types";
import {
getObservationByIdFromObservationsTable,
- ObservationsTableQueryResult,
ObservationTableQuery,
} from "./observations";
import { convertEventsObservation } from "./observations_converters";
@@ -168,10 +167,10 @@ const applyBatchIOStringRendering = (
| null;
};
-type ObservationsTableQueryResultWitouhtTraceFields = Omit<
- ObservationsTableQueryResult,
- "trace_tags" | "trace_name" | "trace_user_id"
->;
+type EventsObservationQueryResult = EventsObservationRecordReadType & {
+ latency?: string;
+ time_to_first_token?: string;
+};
/**
* Extra row fields present when the query ran with an `ioSizeCap`
@@ -216,19 +215,19 @@ export type ObservationIOSizeFields = {
* @param requestedFields - Field groups for V2 API (null = V1 API, returns complete observations)
*/
async function enrichObservationsWithModelData(
- observationRecords: Array<ObservationsTableQueryResultWitouhtTraceFields>,
+ observationRecords: Array<EventsObservationQueryResult>,
projectId: string,
parseIoAsJson: boolean,
requestedFields: ObservationFieldGroupPublicApi[],
): Promise<Array<EventsObservationPublic>>;
async function enrichObservationsWithModelData(
- observationRecords: Array<ObservationsTableQueryResultWitouhtTraceFields>,
+ observationRecords: Array<EventsObservationQueryResult>,
projectId: string,
parseIoAsJson: boolean,
requestedFields: null,
): Promise<Array<EventsObservation & ObservationPriceFields>>;
async function enrichObservationsWithModelData(
- observationRecords: Array<ObservationsTableQueryResultWitouhtTraceFields>,
+ observationRecords: Array<EventsObservationQueryResult>,
projectId: string,
parseIoAsJson: boolean,
requestedFields: ObservationFieldGroupPublicApi[] | null,
@@ -446,18 +445,16 @@ export const getObservationsForTraceFromEventsTable = async (params: {
}
const records =
- await getObservationsFromEventsTableInternal<ObservationsTableQueryResultWitouhtTraceFields>(
- {
- projectId,
- filter,
- orderBy: { column: "startTime", order: "ASC" },
- limit: MAX_OBSERVATIONS_PER_TRACE + 1,
- offset: 0,
- select: "rows",
- selectIOAndMetadata,
- selectToolData,
- },
- );
+ await getObservationsFromEventsTableInternal<EventsObservationQueryResult>({
+ projectId,
+ filter,
+ orderBy: { column: "startTime", order: "ASC" },
+ limit: MAX_OBSERVATIONS_PER_TRACE + 1,
+ offset: 0,
+ select: "rows",
+ selectIOAndMetadata,
+ selectToolData,
+ });
const totalCount = records.length;
@@ -519,7 +516,7 @@ export async function getObservationsWithModelDataFromEventsTable(
opts: ObservationTableQuery,
): Promise<FullEventsObservations> {
const observationRecords = await getObservationsFromEventsTableInternal<
- ObservationsTableQueryResultWitouhtTraceFields & Partial<IOSizeCapRowFields>
+ EventsObservationQueryResult & Partial<IOSizeCapRowFields>
>({
...opts,
select: "rows",
@@ -1302,6 +1299,7 @@ type PublicApiObservationsQuery = {
type?: string;
level?: string;
parentObservationId?: string;
+ isRootObservation?: boolean;
fromStartTime?: string;
toStartTime?: string;
version?: string;
@@ -1585,7 +1583,7 @@ export const getObservationsFromEventsTableForPublicApi = async (
});
const observationRecords =
- await getObservationsRowsFromBuilder<ObservationsTableQueryResultWitouhtTraceFields>(
+ await getObservationsRowsFromBuilder<EventsObservationQueryResult>(
projectId,
queryBuilder,
);
@@ -1611,9 +1609,7 @@ export const getObservationsFromEventsTableForPublicApi = async (
* This avoids expensive full-table scans on events_full.
*/
export const getObservationsV2FromEventsTableForPublicApi = async (
- opts: PublicApiObservationsQuery & {
- fields: ObservationFieldGroupPublicApi[];
- },
+ opts: PublicApiObservationsQuery,
options: BuildObservationsQueryComponentsOptions = {},
): Promise<Array<EventsObservationPublic>> => {
const { projectId, expandMetadataKeys } = opts;
@@ -1686,7 +1682,7 @@ export const getObservationsV2FromEventsTableForPublicApi = async (
}
const records =
- await getObservationsRowsFromBuilder<ObservationsTableQueryResultWitouhtTraceFields>(
+ await getObservationsRowsFromBuilder<EventsObservationQueryResult>(
projectId,
builder,
);
@@ -1695,7 +1691,7 @@ export const getObservationsV2FromEventsTableForPublicApi = async (
records,
projectId,
false, // V2 API: IO fields are always returned as raw strings
- opts.fields, // V2 API: field groups specified, return partial observations
+ requestedFields,
);
};
diff --git a/packages/shared/src/server/repositories/observations_converters.ts b/packages/shared/src/server/repositories/observations_converters.ts
index f6bee7a6c5..cf37aa5ce5 100644
--- a/packages/shared/src/server/repositories/observations_converters.ts
+++ b/packages/shared/src/server/repositories/observations_converters.ts
@@ -415,6 +415,9 @@ export function convertEventsObservation(
...baseObservation,
userId: record.user_id ?? null,
sessionId: record.session_id ?? null,
+ ...(record.is_root_observation !== undefined && {
+ isRootObservation: record.is_root_observation,
+ }),
traceName: record.trace_name ?? null,
release: record.release ?? null,
tags: record.tags ?? null,
@@ -432,6 +435,9 @@ export function convertEventsObservation(
...baseObservation,
...(record.user_id !== undefined && { userId: record.user_id }),
...(record.session_id !== undefined && { sessionId: record.session_id }),
+ ...(record.is_root_observation !== undefined && {
+ isRootObservation: record.is_root_observation,
+ }),
...(record.trace_name !== undefined && { traceName: record.trace_name }),
...(record.release !== undefined && { release: record.release }),
...(record.tags !== undefined && { tags: record.tags }),
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index d99eec119d..567d26588e 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2107,7 +2107,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/ObservationsView'
+ $ref: '#/components/schemas/ObservationsViewSingle'
'400':
description: ''
content:
@@ -3281,7 +3281,7 @@ paths:
parentObservationId, type
- `basic` - name, level, statusMessage, version, environment,
- bookmarked, public, userId, sessionId
+ bookmarked, public, userId, sessionId, isRootObservation
- `time` - completionStartTime, createdAt, updatedAt
@@ -3406,10 +3406,30 @@ paths:
nullable: true
- name: parentObservationId
in: query
+ description: >-
+ Filter by the physical parent observation ID.
+
+ An empty value matches only observations without a physical parent.
+ Use `isRootObservation` to include observations marked as app roots
+ by the SDK, which may retain a non-null `parentObservationId`.
required: false
schema:
type: string
nullable: true
+ - name: isRootObservation
+ in: query
+ description: >-
+ Filter by whether an observation is a logical root.
+
+ Root observations include observations without a physical parent and
+ observations marked as app roots by the SDK.
+
+ An app-root observation may have `isRootObservation=true` and a
+ non-null `parentObservationId`.
+ required: false
+ schema:
+ type: boolean
+ nullable: true
- name: environment
in: query
description: >-
@@ -3514,6 +3534,10 @@ paths:
- `sessionId` (string) - Session ID
+ - `isRootObservation` (boolean) - Whether the observation is a
+ logical root. Observations marked as app roots by the SDK may retain
+ a non-null parentObservationId.
+
### Trace-Related Fields
@@ -3617,6 +3641,12 @@ paths:
"column": "output",
"operator": "matches",
"value": "needle"
+ },
+ {
+ "type": "boolean",
+ "column": "isRootObservation",
+ "operator": "=",
+ "value": true
}
]
@@ -7635,8 +7665,10 @@ paths:
List evaluation rules in the authenticated project.
- Each item describes one live evaluation rule and its effective runtime
- status.
+ This includes legacy `trace` and `dataset` rules so they can be
+ inspected and migrated to v4 rules. Legacy rules are read-only through
+ this API; create, update, and delete continue to support only
+ `observation` and `experiment` rules.
operationId: unstable_evaluationRules_list
tags:
- UnstableEvaluationRules
@@ -7707,7 +7739,9 @@ paths:
Use this endpoint to inspect the current evaluator, target, mapping,
- filters, and effective runtime status.
+ filters, execution timing, and effective runtime status. Legacy `trace`
+ and `dataset` rules are returned for migration and are read-only through
+ this API.
operationId: unstable_evaluationRules_get
tags:
- UnstableEvaluationRules
@@ -7726,7 +7760,7 @@ paths:
content:
application/json:
schema:
- $ref: '#/components/schemas/unstableEvaluationRule'
+ $ref: '#/components/schemas/unstableReadableEvaluationRule'
'400':
description: ''
content:
@@ -8936,6 +8970,37 @@ components:
required:
- data
- meta
+ Deprecation:
+ title: Deprecation
+ type: object
+ description: >-
+ Migration signal returned by deprecated endpoints. Optional fields are
+ omitted when they have no value.
+ properties:
+ message:
+ type: string
+ description: >-
+ Human- and agent-readable summary of the deprecation and its
+ replacement.
+ replacement:
+ type: string
+ nullable: true
+ description: >-
+ The replacement endpoint, e.g. "GET /api/public/v2/observations".
+ Omitted when the endpoint is being removed without a direct
+ replacement.
+ docsUrl:
+ type: string
+ nullable: true
+ description: Link to the migration documentation (markdown), when available.
+ sunsetAt:
+ type: string
+ nullable: true
+ description: >-
+ ISO date after which the endpoint may stop working, when a removal
+ date is committed.
+ required:
+ - message
Trace:
title: Trace
type: object
@@ -9061,6 +9126,9 @@ components:
items:
$ref: '#/components/schemas/ScoreV1'
description: List of scores
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- htmlPath
- observations
@@ -9094,6 +9162,9 @@ components:
type: array
items:
$ref: '#/components/schemas/Trace'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- traces
allOf:
@@ -9287,6 +9358,15 @@ components:
- timeToFirstToken
allOf:
- $ref: '#/components/schemas/Observation'
+ ObservationsViewSingle:
+ title: ObservationsViewSingle
+ type: object
+ properties:
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
+ allOf:
+ - $ref: '#/components/schemas/ObservationsView'
ObservationV2:
title: ObservationV2
type: object
@@ -9318,10 +9398,22 @@ components:
parentObservationId:
type: string
nullable: true
- description: The parent observation ID
+ description: >-
+ The physical parent observation ID, if present.
+
+ Observations marked as app roots by the SDK may retain a non-null
+ parent ID.
type:
type: string
description: The type of the observation (e.g. GENERATION, SPAN, EVENT)
+ isRootObservation:
+ type: boolean
+ nullable: true
+ description: >-
+ Whether this observation is a logical root.
+
+ This is true for observations without a physical parent and
+ observations marked as app roots by the SDK.
name:
type: string
nullable: true
@@ -9994,6 +10086,10 @@ components:
- $ref: '#/components/schemas/TextScore'
required:
- dataType
+ properties:
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
CreateScoreValue:
title: CreateScoreValue
oneOf:
@@ -10262,6 +10358,9 @@ components:
type: array
items:
$ref: '#/components/schemas/DatasetRunItem'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- datasetRunItems
allOf:
@@ -10920,6 +11019,9 @@ components:
$ref: '#/components/schemas/DatasetRunItem'
meta:
$ref: '#/components/schemas/utilsMetaResponse'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- data
- meta
@@ -10970,6 +11072,9 @@ components:
$ref: '#/components/schemas/DatasetRun'
meta:
$ref: '#/components/schemas/utilsMetaResponse'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- data
- meta
@@ -11924,6 +12029,9 @@ components:
Format varies based on the query parameters.
Histograms will return an array with [lower, upper, height] tuples.
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- data
legacyObservations:
@@ -11949,6 +12057,9 @@ components:
$ref: '#/components/schemas/ObservationsView'
meta:
$ref: '#/components/schemas/utilsMetaResponse'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- data
- meta
@@ -14042,6 +14153,9 @@ components:
$ref: '#/components/schemas/GetScoresResponseData'
meta:
$ref: '#/components/schemas/utilsMetaResponse'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- data
- meta
@@ -14055,6 +14169,9 @@ components:
$ref: '#/components/schemas/Session'
meta:
$ref: '#/components/schemas/utilsMetaResponse'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- data
- meta
@@ -14068,6 +14185,9 @@ components:
$ref: '#/components/schemas/TraceWithDetails'
meta:
$ref: '#/components/schemas/utilsMetaResponse'
+ _deprecation:
+ $ref: '#/components/schemas/Deprecation'
+ nullable: true
required:
- data
- meta
@@ -15743,8 +15863,8 @@ components:
required:
- message
- code
- unstableEvaluationRule:
- title: unstableEvaluationRule
+ unstableEvaluationRuleBase:
+ title: unstableEvaluationRuleBase
type: object
description: >-
Live evaluation rule for incoming data.
@@ -15793,9 +15913,6 @@ components:
If you create a newer project version with the same evaluator name
later, existing evaluation rules are moved to it automatically.
- target:
- $ref: '#/components/schemas/unstableEvaluationRuleTarget'
- description: Target object type that should trigger scoring.
enabled:
type: boolean
description: Desired enabled state configured by the client.
@@ -15821,20 +15938,6 @@ components:
Must be greater than `0` and less than or equal to `1`.
- `1` means evaluate every matching target.
- `0.25` means evaluate approximately 25% of matching targets.
- filter:
- type: array
- items:
- $ref: '#/components/schemas/unstableEvaluationRuleFilter'
- description: >-
- List of filter conditions used to decide whether a target should be
- evaluated.
- mapping:
- type: array
- items:
- $ref: '#/components/schemas/unstableEvaluationRuleMapping'
- description: >-
- Variable mappings used to populate evaluator runtime variables from
- the live target object.
createdAt:
type: string
format: date-time
@@ -15847,16 +15950,94 @@ components:
- id
- name
- evaluator
- - target
- enabled
- status
- pausedReason
- pausedMessage
- sampling
- - filter
- - mapping
- createdAt
- updatedAt
+ unstableEvaluationRule:
+ title: unstableEvaluationRule
+ type: object
+ properties:
+ target:
+ $ref: '#/components/schemas/unstableEvaluationRuleTarget'
+ description: Target object type that should trigger scoring.
+ filter:
+ type: array
+ items:
+ $ref: '#/components/schemas/unstableEvaluationRuleFilter'
+ description: >-
+ List of filter conditions used to decide whether a target should be
+ evaluated.
+ mapping:
+ type: array
+ items:
+ $ref: '#/components/schemas/unstableEvaluationRuleMapping'
+ description: >-
+ Variable mappings used to populate evaluator runtime variables from
+ the live target object.
+ required:
+ - target
+ - filter
+ - mapping
+ allOf:
+ - $ref: '#/components/schemas/unstableEvaluationRuleBase'
+ unstableLegacyEvaluationRule:
+ title: unstableLegacyEvaluationRule
+ type: object
+ description: >-
+ Legacy trace- or dataset-level evaluation rule returned by list and get
+ for migration.
+
+
+ This resource is read-only through the unstable public API. Its mapping
+ preserves the trace, dataset item, or named observation that each
+ evaluator variable previously read from. Its filters use the persisted
+ legacy filter format so migration clients can read the configuration
+ without losing information.
+ properties:
+ target:
+ $ref: '#/components/schemas/unstableLegacyEvaluationRuleTarget'
+ delay:
+ type: integer
+ description: Delay in milliseconds before the legacy evaluation job runs.
+ timeScope:
+ type: array
+ items:
+ $ref: '#/components/schemas/unstableEvaluationRuleTimeScope'
+ description: >-
+ Whether the legacy rule evaluates newly ingested data, existing
+ data, or both.
+ filter:
+ type: array
+ items:
+ $ref: '#/components/schemas/unstableEvaluationRuleFilter'
+ description: Stored filters used by the legacy trace or dataset rule.
+ mapping:
+ type: array
+ items:
+ $ref: '#/components/schemas/unstableLegacyEvaluationRuleMapping'
+ description: >-
+ Stored variable mappings, including the trace, dataset item, or
+ named observation selected for each variable.
+ required:
+ - target
+ - delay
+ - timeScope
+ - filter
+ - mapping
+ allOf:
+ - $ref: '#/components/schemas/unstableEvaluationRuleBase'
+ unstableReadableEvaluationRule:
+ title: unstableReadableEvaluationRule
+ oneOf:
+ - $ref: '#/components/schemas/unstableEvaluationRule'
+ - $ref: '#/components/schemas/unstableLegacyEvaluationRule'
+ description: >-
+ Evaluation rule returned by list and get, including read-only legacy
+ trace and dataset rules.
unstableEvaluationRules:
title: unstableEvaluationRules
type: object
@@ -15865,7 +16046,7 @@ components:
data:
type: array
items:
- $ref: '#/components/schemas/unstableEvaluationRule'
+ $ref: '#/components/schemas/unstableReadableEvaluationRule'
description: Evaluation rules in the current page.
meta:
$ref: '#/components/schemas/utilsMetaResponse'
@@ -16178,6 +16359,67 @@ components:
type: string
enum:
- llm_as_judge
+ unstableEvaluationRuleTimeScope:
+ title: unstableEvaluationRuleTimeScope
+ type: string
+ enum:
+ - NEW
+ - EXISTING
+ unstableLegacyEvaluationRuleTarget:
+ title: unstableLegacyEvaluationRuleTarget
+ type: string
+ enum:
+ - trace
+ - dataset
+ unstableLegacyEvaluationRuleMapping:
+ title: unstableLegacyEvaluationRuleMapping
+ type: object
+ description: >-
+ Maps one evaluator variable to a trace, dataset item, or field on a
+ named observation in a legacy rule.
+ properties:
+ variable:
+ type: string
+ description: Evaluator prompt variable populated by this mapping.
+ langfuseObject:
+ $ref: '#/components/schemas/unstableLegacyEvaluationObject'
+ description: >-
+ Trace, dataset item, or observation type from which the value is
+ read.
+ objectName:
+ type: string
+ nullable: true
+ description: >-
+ Observation name to match, or `null` when `langfuseObject` is
+ `trace` or `dataset_item`.
+ source:
+ type: string
+ description: Stored field selected from the trace, dataset item, or observation.
+ jsonPath:
+ type: string
+ nullable: true
+ description: Optional JSONPath selector applied to the selected field.
+ required:
+ - variable
+ - langfuseObject
+ - objectName
+ - source
+ unstableLegacyEvaluationObject:
+ title: unstableLegacyEvaluationObject
+ type: string
+ enum:
+ - trace
+ - span
+ - generation
+ - event
+ - agent
+ - tool
+ - chain
+ - retriever
+ - evaluator
+ - embedding
+ - guardrail
+ - dataset_item
unstableEvaluationRuleEvaluator:
title: unstableEvaluationRuleEvaluator
type: object
diff --git a/web/src/__tests__/server/observations-api-v2.servertest.ts b/web/src/__tests__/server/observations-api-v2.servertest.ts
index f19b6d57f2..7958c678c1 100644
--- a/web/src/__tests__/server/observations-api-v2.servertest.ts
+++ b/web/src/__tests__/server/observations-api-v2.servertest.ts
@@ -202,6 +202,38 @@ describe("/api/public/v2/observations API Endpoint", () => {
expect(JSON.stringify(response.body)).toContain("parseIoAsJson");
});
+ it("returns core and basic fields when fields is omitted", async () => {
+ const traceId = randomUUID();
+ const observationId = randomUUID();
+
+ await createEventsCh([
+ createEvent({
+ id: observationId,
+ span_id: observationId,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "default-fields-observation",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: Date.now() * 1000,
+ }),
+ ]);
+
+ const response = await getObservations(
+ `/api/public/v2/observations?traceId=${traceId}`,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.data).toContainEqual(
+ expect.objectContaining({
+ id: observationId,
+ name: "default-fields-observation",
+ level: "DEFAULT",
+ isRootObservation: true,
+ }),
+ );
+ });
+
it("should respect limit parameter with default of 50", async () => {
const timestamp = Date.now() * 1000;
const observations = Array.from({ length: 6 }, (_, index) => {
@@ -268,6 +300,79 @@ describe("/api/public/v2/observations API Endpoint", () => {
expect(obs?.level).toBe("WARNING");
});
+ it("should filter semantic roots while preserving their physical parent", async () => {
+ const traceId = randomUUID();
+ const physicalRootId = randomUUID();
+ const appRootId = randomUUID();
+ const childId = randomUUID();
+ const externalParentId = randomUUID();
+ const timeValue = Date.now() * 1000;
+
+ await createEventsCh(
+ (
+ [
+ [physicalRootId, "", false],
+ [appRootId, externalParentId, true],
+ [childId, physicalRootId, false],
+ ] as const
+ ).map(([id, parentSpanId, isAppRoot], offset) =>
+ createEvent({
+ id,
+ span_id: id,
+ parent_span_id: parentSpanId,
+ is_app_root: isAppRoot,
+ trace_id: traceId,
+ project_id: projectId,
+ type: "SPAN",
+ level: "DEFAULT",
+ start_time: timeValue + offset,
+ }),
+ ),
+ );
+
+ const fetchTopology = async (filter: string) =>
+ Object.fromEntries(
+ (
+ await getObservations(
+ `/api/public/v2/observations?fields=basic&traceId=${traceId}&${filter}`,
+ )
+ ).body.data.map(({ id, isRootObservation, parentObservationId }) => [
+ id,
+ [isRootObservation, parentObservationId],
+ ]),
+ );
+ const structuredFilter = encodeURIComponent(
+ JSON.stringify([
+ {
+ type: "boolean",
+ column: "isRootObservation",
+ operator: "=",
+ value: true,
+ },
+ ]),
+ );
+ const expectedRoots = {
+ [physicalRootId]: [true, null],
+ [appRootId]: [true, externalParentId],
+ };
+
+ expect(
+ await Promise.all(
+ [
+ "isRootObservation=true",
+ `filter=${structuredFilter}`,
+ "parentObservationId=",
+ "isRootObservation=false",
+ ].map(fetchTopology),
+ ),
+ ).toEqual([
+ expectedRoots,
+ expectedRoots,
+ { [physicalRootId]: [true, null] },
+ { [childId]: [false, physicalRootId] },
+ ]);
+ });
+
it("should filter by multiple environment query params (any-of semantics)", async () => {
const traceId = randomUUID();
const envA = `env-a-${randomUUID()}`;
@@ -1063,6 +1168,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
"public",
"userId",
"sessionId",
+ "isRootObservation",
// time
"completionStartTime",
"createdAt",
@@ -1176,6 +1282,7 @@ describe("/api/public/v2/observations API Endpoint", () => {
"public",
"userId",
"sessionId",
+ "isRootObservation",
],
time: ["completionStartTime", "createdAt", "updatedAt"],
io: ["input", "output"],
diff --git a/web/src/features/mcp/features/observations/schema.ts b/web/src/features/mcp/features/observations/schema.ts
index 4ee2858c9b..2b0000be34 100644
--- a/web/src/features/mcp/features/observations/schema.ts
+++ b/web/src/features/mcp/features/observations/schema.ts
@@ -20,8 +20,10 @@ type ObservationMcpFieldDefinition = ObservationMcpFieldMetadata & {
group: ObservationFieldGroupPublicApi;
};
-type ObservationMcpField =
- (typeof OBSERVATION_FIELD_GROUP_FIELD_NAMES)[ObservationFieldGroupPublicApi][number];
+type ObservationMcpField = Exclude<
+ (typeof OBSERVATION_FIELD_GROUP_FIELD_NAMES)[ObservationFieldGroupPublicApi][number],
+ "isRootObservation"
+>;
type ObservationMcpFieldType =
| "array"
@@ -35,6 +37,8 @@ type ObservationMcpFieldType =
const OBSERVATION_MCP_FIELDS = OBSERVATION_FIELD_GROUPS_PUBLIC_API.flatMap(
(group) => OBSERVATION_FIELD_GROUP_FIELD_NAMES[group],
+).filter(
+ (field): field is ObservationMcpField => field !== "isRootObservation",
);
const OBSERVATION_MCP_FIELD_SET = new Set<string>(OBSERVATION_MCP_FIELDS);
@@ -98,11 +102,15 @@ export type { ObservationMcpField };
export const OBSERVATION_MCP_FIELD_DEFINITIONS: ObservationMcpFieldDefinition[] =
OBSERVATION_FIELD_GROUPS_PUBLIC_API.flatMap((group) =>
- OBSERVATION_FIELD_GROUP_FIELD_NAMES[group].map((field) => ({
- field,
- group,
- ...OBSERVATION_MCP_FIELD_METADATA[field],
- })),
+ OBSERVATION_FIELD_GROUP_FIELD_NAMES[group]
+ .filter((field): field is ObservationMcpField =>
+ OBSERVATION_MCP_FIELD_SET.has(field),
+ )
+ .map((field) => ({
+ field,
+ group,
+ ...OBSERVATION_MCP_FIELD_METADATA[field],
+ })),
);
export const OBSERVATION_MCP_DEFAULT_FIELDS = OBSERVATION_MCP_FIELDS.filter(
diff --git a/web/src/features/public-api/types/observations.ts b/web/src/features/public-api/types/observations.ts
index da899c7939..0a56b30921 100644
--- a/web/src/features/public-api/types/observations.ts
+++ b/web/src/features/public-api/types/observations.ts
@@ -179,6 +179,9 @@ export const transformDbToApiObservation = (
bookmarked,
public: _public,
+
+ // Exclude the V2-only logical root flag from V1 responses.
+ isRootObservation: _isRootObservation,
...rest
} = observation as EventsObservation &
ObservationPriceFields & {
@@ -337,6 +340,10 @@ export const GetObservationsV2Query = z.object({
traceId: z.string().nullish(),
version: z.string().nullish(),
parentObservationId: z.string().nullish(),
+ isRootObservation: z
+ .enum(["true", "false"])
+ .transform((value) => value === "true")
+ .optional(),
environment: z.union([z.array(z.string()), z.string()]).nullish(),
fromStartTime: stringDateTime.optional(),
toStartTime: stringDateTime.optional(),
@@ -360,6 +367,7 @@ const APIObservationV2 = z
type: z.string(),
// Basic fields (field group: basic)
+ isRootObservation: z.boolean().optional(),
name: z.string().nullable().optional(),
level: z.enum(["DEBUG", "DEFAULT", "WARNING", "ERROR"]).optional(),
statusMessage: z.string().nullable().optional(),
diff --git a/web/src/pages/api/public/v2/observations/index.ts b/web/src/pages/api/public/v2/observations/index.ts
index f5359310b7..c61881621d 100644
--- a/web/src/pages/api/public/v2/observations/index.ts
+++ b/web/src/pages/api/public/v2/observations/index.ts
@@ -39,6 +39,7 @@ export default withMiddlewares({
type: query.type ?? undefined,
environment: query.environment ?? undefined,
parentObservationId: query.parentObservationId ?? undefined,
+ isRootObservation: query.isRootObservation,
fromStartTime: query.fromStartTime ?? undefined,
toStartTime: query.toStartTime ?? undefined,
version: query.version ?? undefined,
@@ -49,10 +50,8 @@ export default withMiddlewares({
};
// Fetch observations from events table with field groups applied at query time
- const items = await getObservationsV2FromEventsTableForPublicApi({
- ...filterProps,
- fields: filterProps.fields ?? [], // V2 requires fields array
- });
+ const items =
+ await getObservationsV2FromEventsTableForPublicApi(filterProps);
// Determine if there are more results (we fetched limit+1)
const hasMore = items.length > query.limit;
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index 0c334ed62e..72b8fc816b 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -4955,6 +4955,7 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
"release",
"trace_name",
"parent_observation_id",
+ "is_root_observation",
"bookmarked",
"public",
"created_at",
@@ -4990,6 +4991,7 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
// --- Boolean columns ---
expect(row.bookmarked).toBe(true);
expect(row.public).toBe(true);
+ expect(row.is_root_observation).toBe(true);
// --- Numeric columns ---
expect(row.prompt_version).toBe(1);
@@ -5111,6 +5113,7 @@ maybeDescribe("getEventsForBlobStorageExport", () => {
"release",
"trace_name",
"parent_observation_id",
+ "is_root_observation",
"bookmarked",
"public",
"created_at",