Skip to content

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

fix(api): include observations table join when advanced filters reference it (#10496)

Valery Meleshkin34d42bcee753
diff --git a/fern/apis/server/definition/observations.yml b/fern/apis/server/definition/observations.yml
index 9a1c432d22..568676f1ed 100644
--- a/fern/apis/server/definition/observations.yml
+++ b/fern/apis/server/definition/observations.yml
@@ -115,10 +115,6 @@ service:
### Structured Data
- `metadata` (stringObject/numberObject/categoryOptions) - Metadata key-value pairs. Use `key` parameter to filter on specific metadata keys.
- ### Scores (requires join with scores table)
- - `scores_avg` (number) - Average of numeric scores (alias: `scores`)
- - `score_categories` (categoryOptions) - Categorical score values
-
### Associated Trace Fields (requires join with traces table)
- `userId` (string) - User ID from associated trace
- `traceName` (string) - Name from associated trace
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 92129e0bcb..762a3b2e68 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
@@ -172,6 +172,17 @@ const EVENTS_AGGREGATION_FIELDS = {
bookmarked:
"argMaxIf(bookmarked, event_ts, parent_span_id = '') AS bookmarked",
public: "max(public) AS public",
+
+ // Observation-level aggregations for filtering support
+ usage_details: "sumMap(usage_details) as usage_details",
+ cost_details: "sumMap(cost_details) as cost_details",
+ aggregated_level:
+ "multiIf(arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR', arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING', arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT', 'DEBUG') AS aggregated_level",
+ warning_count: "countIf(level = 'WARNING') as warning_count",
+ error_count: "countIf(level = 'ERROR') as error_count",
+ default_count: "countIf(level = 'DEFAULT') as default_count",
+ debug_count: "countIf(level = 'DEBUG') as debug_count",
+
// Legacy fields for backward compatibility
tags: "array() AS tags",
release: "'' AS release",
diff --git a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
index 52e518bf55..364b11034b 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
@@ -32,19 +32,24 @@ export const eventsTracesAggregation = (
);
};
-interface EventsScoresAggregationParams {
+interface BaseScoresAggregationParams {
projectId: string;
startTimeFrom?: string | null;
+ level: "observation" | "trace";
+ hasScoreAggregationFilters?: boolean;
}
/**
- * Scores CTE for events table queries.
- * Aggregates numeric and categorical scores for observations.
+ * Unified score aggregation CTE builder for both observation-level and trace-level scores.
*
- * Returns a query and params object that can be passed directly to withCTE.
+ * @param level - 'observation' for observation scores, 'trace' for trace-level scores
+ * @param hasScoreAggregationFilters - When true, uses nested subquery for proper avg() computation
+ *
+ * Observation level: Aggregates scores by (trace_id, observation_id), always uses nested structure
+ * Trace level: Aggregates scores by (project_id, trace_id), filters observation_id IS NULL
*/
-export const eventsScoresAggregation = (
- params: EventsScoresAggregationParams,
+const buildScoresAggregationCTE = (
+ params: BaseScoresAggregationParams,
): { query: string; params: Record<string, any> } => {
const queryParams: Record<string, any> = {
projectId: params.projectId,
@@ -54,65 +59,98 @@ export const eventsScoresAggregation = (
queryParams.startTimeFrom = params.startTimeFrom;
}
+ const isTraceLevel = params.level === "trace";
+
+ // Observation level: trace_id + observation_id
+ // Trace level: project_id + trace_id
+ const primaryKey = isTraceLevel ? "project_id" : "observation_id";
+ const additionalInnerCols = isTraceLevel ? ["id"] : ["comment"];
+ const additionalOuterCols = isTraceLevel
+ ? ["groupUniqArray(id) as score_ids"]
+ : [];
+ const observationFilter = isTraceLevel ? "AND observation_id IS NULL" : "";
+ const orderBy = isTraceLevel ? "" : "ORDER BY trace_id";
+
const query = `
- SELECT
- trace_id,
- observation_id,
- -- For numeric scores, use tuples of (name, avg_value)
- groupArrayIf(
- tuple(name, avg_value),
- data_type IN ('NUMERIC', 'BOOLEAN')
- ) AS scores_avg,
- -- For categorical scores, use name:value format for improved query performance
- groupArrayIf(
- concat(name, ':', string_value),
- data_type = 'CATEGORICAL' AND notEmpty(string_value)
- ) AS score_categories
- FROM (
SELECT
trace_id,
- observation_id,
- name,
- avg(value) avg_value,
- string_value,
- data_type,
- comment
- FROM
- scores FINAL
- WHERE project_id = {projectId: String}
- ${params.startTimeFrom ? `AND timestamp >= {startTimeFrom: DateTime64(3)}` : ""}
- GROUP BY
- trace_id,
- observation_id,
- name,
- string_value,
- data_type,
- comment
- ORDER BY
- trace_id
+ ${primaryKey},
+ ${additionalOuterCols.length > 0 ? additionalOuterCols.join(",\n ") + "," : ""}
+ groupArrayIf(tuple(name, avg_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
+ groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories
+ FROM (
+ SELECT
+ ${primaryKey},
+ trace_id,
+ ${additionalInnerCols.join(",\n ")},
+ name,
+ data_type,
+ string_value,
+ avg(value) as avg_value
+ FROM scores FINAL
+ WHERE project_id = {projectId: String}
+ ${observationFilter}
+ ${params.startTimeFrom ? `AND timestamp >= {startTimeFrom: DateTime64(3)}` : ""}
+ GROUP BY
+ ${primaryKey},
+ trace_id,
+ ${additionalInnerCols.join(",\n ")},
+ name,
+ data_type,
+ string_value
+ ${orderBy}
) tmp
- GROUP BY
- trace_id,
- observation_id
- `.trim();
+ GROUP BY ${primaryKey}, trace_id
+ `.trim();
return { query, params: queryParams };
};
+interface EventsScoresAggregationParams {
+ projectId: string;
+ startTimeFrom?: string | null;
+}
+
+/**
+ * Scores CTE for events table queries.
+ * Aggregates numeric and categorical scores for observations.
+ *
+ * Returns a query and params object that can be passed directly to withCTE.
+ */
+export const eventsScoresAggregation = (
+ params: EventsScoresAggregationParams,
+): { query: string; params: Record<string, any> } => {
+ return buildScoresAggregationCTE({
+ ...params,
+ level: "observation",
+ });
+};
+
interface EventsTracesScoresAggregationParams {
projectId: string;
startTimeFrom?: string | null;
+ hasScoreAggregationFilters?: boolean;
}
/**
* Scores CTE for trace-level queries.
* Aggregates scores that belong to traces (not observations).
*
+ * When hasScoreAggregationFilters is true, uses nested subquery structure
+ * with pre-aggregation to enable proper array filtering on scores_avg/score_categories.
+ *
* Returns a query and params object that can be passed directly to withCTE.
*/
export const eventsTracesScoresAggregation = (
params: EventsTracesScoresAggregationParams,
): { query: string; params: Record<string, any> } => {
+ if (params.hasScoreAggregationFilters) {
+ return buildScoresAggregationCTE({
+ ...params,
+ level: "trace",
+ });
+ }
+
const queryParams: Record<string, any> = {
projectId: params.projectId,
};
@@ -121,6 +159,7 @@ export const eventsTracesScoresAggregation = (
queryParams.startTimeFrom = params.startTimeFrom;
}
+ // Flat structure (trace-level only, when no score filters present)
const query = `
SELECT
trace_id,
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index 7e4d66a4ca..ecc5df738e 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -157,7 +157,30 @@ const PUBLIC_API_TRACES_COLUMN_MAPPING = createPublicApiTracesColumnMapping(
"t",
);
-const TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS = tracesTableUiColumnDefinitions;
+// For events-based traces, observation fields are aggregated into the traces CTE (with 't' prefix),
+// not joined from a separate observations table (with 'o' prefix). We need to remap these.
+const TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS =
+ tracesTableUiColumnDefinitions.map((col) => {
+ // If this column references the observations table with 'o' prefix,
+ // remap it to use 't' prefix since observations are aggregated into traces CTE
+ if (col.clickhouseTableName === "observations") {
+ // Replace o. prefix with t. in clickhouseSelect (only when followed by identifier)
+ // Technically we do not need to deal with the prefix at all,
+ // since here these columns are always used inside a CTE.
+ const updatedSelect = col.clickhouseSelect.replace(
+ /\bo\.([a-z_])/g,
+ "t.$1",
+ );
+
+ return {
+ ...col,
+ clickhouseTableName: "traces", // Now it's in the traces CTE
+ queryPrefix: undefined,
+ clickhouseSelect: updatedSelect,
+ };
+ }
+ return col;
+ });
/**
* Order by columns for traces CTE (post-aggregation)
@@ -602,12 +625,19 @@ const getObservationsFromEventsTableForPublicApiInternal = async <T>(
eventsTableUiColumnDefinitions,
);
- // Determine if we need to join traces (for userId filter)
- const hasTraceFilter = Boolean(filterParams.userId);
+ // Remove score filters since observations don't support scores in response
+ const filteredObservationsFilter = observationsFilter.filter(
+ (f) => f.clickhouseTable !== "scores",
+ );
+
+ // Determine if we need to join traces (check both simple params and advanced filters)
+ const hasTraceFilter = filteredObservationsFilter.some(
+ (f) => f.clickhouseTable === "traces",
+ );
// Extract time filter using helper
- const startTimeFrom = extractTimeFilter(observationsFilter);
- const appliedFilter = observationsFilter.apply();
+ const startTimeFrom = extractTimeFilter(filteredObservationsFilter);
+ const appliedFilter = filteredObservationsFilter.apply();
// Build query using EventsQueryBuilder
const queryBuilder = new EventsQueryBuilder({ projectId });
@@ -754,6 +784,16 @@ const getTracesFromEventsTableForPublicApiInternal = async <T>(
const appliedFilter = tracesFilter.apply();
+ // Check if any filters reference the scores table
+ const filtersNeedScores = tracesFilter.some(
+ (f) => f.clickhouseTable === "scores",
+ );
+
+ // Check if filters specifically reference score aggregation columns
+ const hasScoreAggregationFilters = tracesFilter.some(
+ (f) => f.field === "s.scores_avg" || f.field === "s.score_categories",
+ );
+
// Build traces CTE using eventsTracesAggregation WITHOUT filters
// Filters must be applied AFTER aggregation to ensure filters on aggregated
// fields (like timestamp or version) are applied correctly
@@ -768,15 +808,22 @@ const getTracesFromEventsTableForPublicApiInternal = async <T>(
.from("traces", "t")
.where(appliedFilter);
- if (includeScores) {
+ if (includeScores || filtersNeedScores) {
const scoresCTE = eventsTracesScoresAggregation({
projectId,
startTimeFrom,
+ hasScoreAggregationFilters,
});
queryBuilder = queryBuilder
.withCTE("score_stats", {
...scoresCTE,
- schema: ["trace_id", "project_id", "score_ids"],
+ schema: [
+ "trace_id",
+ "project_id",
+ "score_ids",
+ "scores_avg",
+ "score_categories",
+ ],
})
.leftJoin(
"score_stats",
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index f01960c747..cec769a033 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2501,14 +2501,6 @@ paths:
keys.
- ### Scores (requires join with scores table)
-
- - `scores_avg` (number) - Average of numeric scores (alias:
- `scores`)
-
- - `score_categories` (categoryOptions) - Categorical score values
-
-
### Associated Trace Fields (requires join with traces table)
- `userId` (string) - User ID from associated trace
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index fd953ba658..aabac4778c 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1826,7 +1826,7 @@
{
"key": "filter",
"value": "",
- "description": "JSON string containing an array of filter conditions. When provided, this takes precedence over query parameter filters (userId, name, type, level, environment, fromStartTime, ...).\n\n## Filter Structure\nEach filter condition has the following structure:\n```json\n[\n {\n \"type\": string, // Required. One of: \"datetime\", \"string\", \"number\", \"stringOptions\", \"categoryOptions\", \"arrayOptions\", \"stringObject\", \"numberObject\", \"boolean\", \"null\"\n \"column\": string, // Required. Column to filter on (see available columns below)\n \"operator\": string, // Required. Operator based on type:\n // - datetime: \">\", \"<\", \">=\", \"<=\"\n // - string: \"=\", \"contains\", \"does not contain\", \"starts with\", \"ends with\"\n // - stringOptions: \"any of\", \"none of\"\n // - categoryOptions: \"any of\", \"none of\"\n // - arrayOptions: \"any of\", \"none of\", \"all of\"\n // - number: \"=\", \">\", \"<\", \">=\", \"<=\"\n // - stringObject: \"=\", \"contains\", \"does not contain\", \"starts with\", \"ends with\"\n // - numberObject: \"=\", \">\", \"<\", \">=\", \"<=\"\n // - boolean: \"=\", \"<>\"\n // - null: \"is null\", \"is not null\"\n \"value\": any, // Required (except for null type). Value to compare against. Type depends on filter type\n \"key\": string // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata\n }\n]\n```\n\n## Available Columns\n\n### Core Observation Fields\n- `id` (string) - Observation ID\n- `type` (string) - Observation type (SPAN, GENERATION, EVENT)\n- `name` (string) - Observation name\n- `traceId` (string) - Associated trace ID\n- `startTime` (datetime) - Observation start time\n- `endTime` (datetime) - Observation end time\n- `environment` (string) - Environment tag\n- `level` (string) - Log level (DEBUG, DEFAULT, WARNING, ERROR)\n- `statusMessage` (string) - Status message\n- `version` (string) - Version tag\n\n### Performance Metrics\n- `latency` (number) - Latency in seconds (calculated: end_time - start_time)\n- `timeToFirstToken` (number) - Time to first token in seconds\n- `tokensPerSecond` (number) - Output tokens per second\n\n### Token Usage\n- `inputTokens` (number) - Number of input tokens\n- `outputTokens` (number) - Number of output tokens\n- `totalTokens` (number) - Total tokens (alias: `tokens`)\n\n### Cost Metrics\n- `inputCost` (number) - Input cost in USD\n- `outputCost` (number) - Output cost in USD\n- `totalCost` (number) - Total cost in USD\n\n### Model Information\n- `model` (string) - Provided model name\n- `promptName` (string) - Associated prompt name\n- `promptVersion` (number) - Associated prompt version\n\n### Structured Data\n- `metadata` (stringObject/numberObject/categoryOptions) - Metadata key-value pairs. Use `key` parameter to filter on specific metadata keys.\n\n### Scores (requires join with scores table)\n- `scores_avg` (number) - Average of numeric scores (alias: `scores`)\n- `score_categories` (categoryOptions) - Categorical score values\n\n### Associated Trace Fields (requires join with traces table)\n- `userId` (string) - User ID from associated trace\n- `traceName` (string) - Name from associated trace\n- `traceEnvironment` (string) - Environment from associated trace\n- `traceTags` (arrayOptions) - Tags from associated trace\n\n## Filter Examples\n```json\n[\n {\n \"type\": \"string\",\n \"column\": \"type\",\n \"operator\": \"=\",\n \"value\": \"GENERATION\"\n },\n {\n \"type\": \"number\",\n \"column\": \"latency\",\n \"operator\": \">=\",\n \"value\": 2.5\n },\n {\n \"type\": \"stringObject\",\n \"column\": \"metadata\",\n \"key\": \"environment\",\n \"operator\": \"=\",\n \"value\": \"production\"\n }\n]\n```"
+ "description": "JSON string containing an array of filter conditions. When provided, this takes precedence over query parameter filters (userId, name, type, level, environment, fromStartTime, ...).\n\n## Filter Structure\nEach filter condition has the following structure:\n```json\n[\n {\n \"type\": string, // Required. One of: \"datetime\", \"string\", \"number\", \"stringOptions\", \"categoryOptions\", \"arrayOptions\", \"stringObject\", \"numberObject\", \"boolean\", \"null\"\n \"column\": string, // Required. Column to filter on (see available columns below)\n \"operator\": string, // Required. Operator based on type:\n // - datetime: \">\", \"<\", \">=\", \"<=\"\n // - string: \"=\", \"contains\", \"does not contain\", \"starts with\", \"ends with\"\n // - stringOptions: \"any of\", \"none of\"\n // - categoryOptions: \"any of\", \"none of\"\n // - arrayOptions: \"any of\", \"none of\", \"all of\"\n // - number: \"=\", \">\", \"<\", \">=\", \"<=\"\n // - stringObject: \"=\", \"contains\", \"does not contain\", \"starts with\", \"ends with\"\n // - numberObject: \"=\", \">\", \"<\", \">=\", \"<=\"\n // - boolean: \"=\", \"<>\"\n // - null: \"is null\", \"is not null\"\n \"value\": any, // Required (except for null type). Value to compare against. Type depends on filter type\n \"key\": string // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata\n }\n]\n```\n\n## Available Columns\n\n### Core Observation Fields\n- `id` (string) - Observation ID\n- `type` (string) - Observation type (SPAN, GENERATION, EVENT)\n- `name` (string) - Observation name\n- `traceId` (string) - Associated trace ID\n- `startTime` (datetime) - Observation start time\n- `endTime` (datetime) - Observation end time\n- `environment` (string) - Environment tag\n- `level` (string) - Log level (DEBUG, DEFAULT, WARNING, ERROR)\n- `statusMessage` (string) - Status message\n- `version` (string) - Version tag\n\n### Performance Metrics\n- `latency` (number) - Latency in seconds (calculated: end_time - start_time)\n- `timeToFirstToken` (number) - Time to first token in seconds\n- `tokensPerSecond` (number) - Output tokens per second\n\n### Token Usage\n- `inputTokens` (number) - Number of input tokens\n- `outputTokens` (number) - Number of output tokens\n- `totalTokens` (number) - Total tokens (alias: `tokens`)\n\n### Cost Metrics\n- `inputCost` (number) - Input cost in USD\n- `outputCost` (number) - Output cost in USD\n- `totalCost` (number) - Total cost in USD\n\n### Model Information\n- `model` (string) - Provided model name\n- `promptName` (string) - Associated prompt name\n- `promptVersion` (number) - Associated prompt version\n\n### Structured Data\n- `metadata` (stringObject/numberObject/categoryOptions) - Metadata key-value pairs. Use `key` parameter to filter on specific metadata keys.\n\n### Associated Trace Fields (requires join with traces table)\n- `userId` (string) - User ID from associated trace\n- `traceName` (string) - Name from associated trace\n- `traceEnvironment` (string) - Environment from associated trace\n- `traceTags` (arrayOptions) - Tags from associated trace\n\n## Filter Examples\n```json\n[\n {\n \"type\": \"string\",\n \"column\": \"type\",\n \"operator\": \"=\",\n \"value\": \"GENERATION\"\n },\n {\n \"type\": \"number\",\n \"column\": \"latency\",\n \"operator\": \">=\",\n \"value\": 2.5\n },\n {\n \"type\": \"stringObject\",\n \"column\": \"metadata\",\n \"key\": \"environment\",\n \"operator\": \"=\",\n \"value\": \"production\"\n }\n]\n```"
}
],
"variable": []
diff --git a/web/src/__tests__/async/observations-api.servertest.ts b/web/src/__tests__/async/observations-api.servertest.ts
index 48a9ecb221..33cb8fe88f 100644
--- a/web/src/__tests__/async/observations-api.servertest.ts
+++ b/web/src/__tests__/async/observations-api.servertest.ts
@@ -718,6 +718,163 @@ describe("/api/public/observations API Endpoint", () => {
expect(response.body.data.length).toBe(1);
});
+
+ it("should not crash when scores filter is used", async () => {
+ const traceId = randomUUID();
+ const timestamp = new Date();
+ const baseTimestamp = timestamp.getTime();
+ const timeValue = useEventsTable
+ ? baseTimestamp * 1000
+ : baseTimestamp;
+
+ const createdTrace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ });
+
+ const obs1Id = randomUUID();
+
+ await createAndInsertObservations(useEventsTable, createdTrace, [
+ {
+ id: obs1Id,
+ trace_id: traceId,
+ project_id: projectId,
+ name: "obs-with-high-score",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ },
+ ]);
+
+ const filterParam = JSON.stringify([
+ {
+ type: "number",
+ column: "scores_avg",
+ operator: ">=",
+ value: 1000.0,
+ },
+ ]);
+
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
+ "GET",
+ `/api/public/observations${queryParam}&traceId=${traceId}&type=GENERATION&filter=${encodeURIComponent(filterParam)}`,
+ );
+
+ expect(response.status).toBe(200);
+ // Score filter should be ignored, so some observations should be returned
+ expect(response.body.data.length).toBeGreaterThan(0);
+ });
+
+ it("should filter by userId (trace field)", async () => {
+ const trace1Id = randomUUID();
+ const trace2Id = randomUUID();
+ const timestamp = new Date();
+ const baseTimestamp = timestamp.getTime();
+ const timeValue = useEventsTable
+ ? baseTimestamp * 1000
+ : baseTimestamp;
+
+ // Create two traces with different userIds
+ const trace1 = createTrace({
+ id: trace1Id,
+ project_id: projectId,
+ timestamp: timeValue,
+ user_id: "user-A",
+ });
+
+ const trace2 = createTrace({
+ id: trace2Id,
+ project_id: projectId,
+ timestamp: timeValue,
+ user_id: "user-B",
+ });
+
+ if (useEventsTable) {
+ createEventsCh([
+ createEvent({
+ ...trace1,
+ span_id: trace1.id,
+ trace_id: trace1.id,
+ parent_span_id: "",
+ name: "trace1",
+ }),
+ createEvent({
+ ...trace2,
+ span_id: trace2.id,
+ trace_id: trace2.id,
+ parent_span_id: "",
+ name: "trace2",
+ }),
+ ]);
+ }
+
+ // Create observations for both traces
+ await createAndInsertObservations(useEventsTable, trace1, [
+ {
+ id: randomUUID(),
+ trace_id: trace1Id,
+ project_id: projectId,
+ name: "obs-trace1-a",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue,
+ },
+ {
+ id: randomUUID(),
+ trace_id: trace1Id,
+ project_id: projectId,
+ name: "obs-trace1-b",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue + 1000,
+ },
+ ]);
+
+ await createAndInsertObservations(useEventsTable, trace2, [
+ {
+ id: randomUUID(),
+ trace_id: trace2Id,
+ project_id: projectId,
+ name: "obs-trace2",
+ type: "GENERATION",
+ level: "DEFAULT",
+ start_time: timeValue + 2000,
+ },
+ ]);
+
+ const filterParam = JSON.stringify([
+ {
+ type: "string",
+ column: "userId",
+ operator: "=",
+ value: "user-A",
+ },
+ {
+ type: "stringOptions",
+ column: "traceId",
+ operator: "any of",
+ value: [trace1Id, trace2Id],
+ },
+ ]);
+
+ const response = await makeZodVerifiedAPICall(
+ GetObservationsV1Response,
+ "GET",
+ `/api/public/observations${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ );
+
+ expect(response.status).toBe(200);
+ // Should only return observations from trace1
+ const matchingObs = response.body.data.filter(
+ (obs) => obs.traceId === trace1Id || obs.traceId === trace2Id,
+ );
+ expect(matchingObs.length).toBeGreaterThanOrEqual(2); // events path picks up top level trace itself
+ expect(matchingObs.every((obs) => obs.traceId === trace1Id)).toBe(
+ true,
+ );
+ });
});
};
diff --git a/web/src/__tests__/async/traces-api.servertest.ts b/web/src/__tests__/async/traces-api.servertest.ts
index 45b083d014..f2c2f30747 100644
--- a/web/src/__tests__/async/traces-api.servertest.ts
+++ b/web/src/__tests__/async/traces-api.servertest.ts
@@ -1580,6 +1580,215 @@ describe("/api/public/traces API Endpoint", () => {
expect(matchingTrace2).toBeTruthy();
expect(matchingTrace2?.version).toBe("2.0");
});
+
+ it("should filter by latency without requesting metrics field group", async () => {
+ // Filtering by latency should work even without requesting the "metrics" field group
+ const baseTimestamp = Date.now();
+ const traceWithLatency1 = randomUUID();
+ const traceWithLatency2 = randomUUID();
+ const traceWithLatency3 = randomUUID();
+
+ // Create trace 1 with observations that result in ~0.5 second latency
+ const trace1 = createTrace({
+ id: traceWithLatency1,
+ name: "trace-latency-1",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ environment: "test-latency",
+ });
+
+ const observations1: ObservationEventData[] = [
+ {
+ trace_id: traceWithLatency1,
+ project_id: projectId,
+ name: "obs-1",
+ start_time: baseTimestamp,
+ end_time: baseTimestamp + 500, // 0.5 seconds
+ },
+ ];
+
+ // Create trace 2 with observations that result in ~1.5 second latency
+ const trace2 = createTrace({
+ id: traceWithLatency2,
+ name: "trace-latency-2",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ environment: "test-latency",
+ });
+
+ const observations2: ObservationEventData[] = [
+ {
+ trace_id: traceWithLatency2,
+ project_id: projectId,
+ name: "obs-2",
+ start_time: baseTimestamp,
+ end_time: baseTimestamp + 1500, // 1.5 seconds
+ },
+ ];
+
+ // Create trace 3 with observations that result in ~2.5 second latency
+ const trace3 = createTrace({
+ id: traceWithLatency3,
+ name: "trace-latency-3",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ environment: "test-latency",
+ });
+
+ const observations3: ObservationEventData[] = [
+ {
+ trace_id: traceWithLatency3,
+ project_id: projectId,
+ name: "obs-3",
+ start_time: baseTimestamp,
+ end_time: baseTimestamp + 2500, // 2.5 seconds
+ },
+ ];
+
+ await createTraceWithObservations(
+ useEventsTable,
+ trace1,
+ observations1,
+ );
+ await createTraceWithObservations(
+ useEventsTable,
+ trace2,
+ observations2,
+ );
+ await createTraceWithObservations(
+ useEventsTable,
+ trace3,
+ observations3,
+ );
+
+ // Simple wait to ensure data is available
+ await new Promise((resolve) => setTimeout(resolve, 100));
+
+ // Test filtering by latency range (>= 0 and <= 1.9 seconds)
+ // This should return trace1 and trace2, but not trace3
+ // Note: We're NOT requesting the "metrics" field group
+ const filterParam = JSON.stringify([
+ {
+ type: "number",
+ column: "latency",
+ operator: ">=",
+ value: 0,
+ },
+ {
+ type: "number",
+ column: "latency",
+ operator: "<=",
+ value: 1.9,
+ },
+ {
+ type: "stringOptions",
+ column: "id",
+ operator: "any of",
+ value: [traceWithLatency1, traceWithLatency2, traceWithLatency3],
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`fields=core&filter=${encodeURIComponent(filterParam)}`),
+ );
+
+ expect(traces.status).toBe(200);
+ const trace1Result = traces.body.data.find(
+ (t) => t.id === traceWithLatency1,
+ );
+ const trace2Result = traces.body.data.find(
+ (t) => t.id === traceWithLatency2,
+ );
+ const trace3Result = traces.body.data.find(
+ (t) => t.id === traceWithLatency3,
+ );
+
+ // Trace 1 (0.5s) and Trace 2 (1.5s) should be found
+ expect(trace1Result).toBeTruthy();
+ expect(trace2Result).toBeTruthy();
+ // Trace 3 (2.5s) should NOT be found
+ expect(trace3Result).toBeUndefined();
+
+ expect(traces.body.meta.totalItems).toBeGreaterThanOrEqual(2);
+ });
+
+ it("should filter by score_categories without requesting scores field group", async () => {
+ // Filtering by score fields should work even without requesting the "scores" field group
+ // This test verifies that score_stats CTE is created when filters reference scores table
+ const baseTimestamp = Date.now();
+ const traceWithScore1 = randomUUID();
+ const traceWithScore2 = randomUUID();
+
+ // Create trace 1 with categorical score "good"
+ const trace1 = createTrace({
+ id: traceWithScore1,
+ name: "trace-score-1",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ });
+
+ const score1 = createTraceScore({
+ trace_id: traceWithScore1,
+ project_id: projectId,
+ name: "quality",
+ string_value: "good",
+ data_type: "CATEGORICAL",
+ timestamp: baseTimestamp,
+ observation_id: null, // Must be null for trace-level scores
+ });
+
+ // Create trace 2 with categorical score "bad"
+ const trace2 = createTrace({
+ id: traceWithScore2,
+ name: "trace-score-2",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ });
+
+ const score2 = createTraceScore({
+ trace_id: traceWithScore2,
+ project_id: projectId,
+ name: "quality",
+ string_value: "bad",
+ data_type: "CATEGORICAL",
+ timestamp: baseTimestamp,
+ observation_id: null, // Must be null for trace-level scores
+ });
+
+ await createTraceWithObservations(useEventsTable, trace1, []);
+ await createTraceWithObservations(useEventsTable, trace2, []);
+ await createScoresCh([score1, score2]);
+
+ // Test filtering by score_categories (check for "good" score)
+ // This should return trace1 only
+ // Note: We're NOT requesting the "scores" field group
+ const filterParam = JSON.stringify([
+ {
+ type: "stringOptions",
+ column: "score_categories",
+ operator: "any of",
+ value: ["quality:good"],
+ },
+ {
+ type: "stringOptions",
+ column: "id",
+ operator: "any of",
+ value: [traceWithScore1, traceWithScore2],
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`fields=core&filter=${encodeURIComponent(filterParam)}`),
+ );
+
+ expect(traces.status).toBe(200);
+ expect(traces.body.data.map((d) => d.id)).toEqual([traceWithScore1]);
+ expect(traces.body.meta.totalItems).toBe(1);
+ });
});
};
@@ -1916,4 +2125,105 @@ describe("/api/public/traces API Endpoint", () => {
runTestSuite(true); // Events table
}
});
+
+ // Comprehensive filter column tests - verify all documented filter columns don't crash
+ describe("Filter Columns - Doesn't Fail Tests", () => {
+ const runFilterTests = (useEventsTable: boolean) => {
+ const suiteName = useEventsTable
+ ? "with events table"
+ : "with traces table";
+ const queryParam = useEventsTable ? "?useEventsTable=true&" : "?";
+
+ describe(suiteName, () => {
+ // Aggregated Metrics (from observations)
+ const metricsFilters = [
+ { column: "latency", type: "number", operator: ">=", value: 0 },
+ { column: "inputTokens", type: "number", operator: ">=", value: 0 },
+ { column: "outputTokens", type: "number", operator: ">=", value: 0 },
+ { column: "totalTokens", type: "number", operator: ">=", value: 0 },
+ { column: "inputCost", type: "number", operator: ">=", value: 0 },
+ { column: "outputCost", type: "number", operator: ">=", value: 0 },
+ { column: "totalCost", type: "number", operator: ">=", value: 0 },
+ ];
+
+ metricsFilters.forEach(({ column, type, operator, value }) => {
+ it(`should not fail when filtering by ${column}`, async () => {
+ const filterParam = JSON.stringify([
+ { type, column, operator, value },
+ ]);
+ const response = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ `/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ );
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ expect(response.body.meta).toBeDefined();
+ });
+ });
+
+ // Observation Level Aggregations
+ const observationAggFilters = [
+ { column: "level", type: "string", operator: "=", value: "ERROR" },
+ { column: "warningCount", type: "number", operator: ">=", value: 0 },
+ { column: "errorCount", type: "number", operator: ">=", value: 0 },
+ { column: "defaultCount", type: "number", operator: ">=", value: 0 },
+ { column: "debugCount", type: "number", operator: ">=", value: 0 },
+ ];
+
+ observationAggFilters.forEach(({ column, type, operator, value }) => {
+ it(`should not fail when filtering by ${column}`, async () => {
+ const filterParam = JSON.stringify([
+ { type, column, operator, value },
+ ]);
+ const response = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ `/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ );
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ expect(response.body.meta).toBeDefined();
+ });
+ });
+
+ // Scores (should not crash, filters are ignored per our fix)
+ const scoreFilters = [
+ {
+ column: "scores_avg",
+ type: "numberObject",
+ key: "quality",
+ operator: ">=",
+ value: 0.5,
+ },
+ {
+ column: "score_categories",
+ type: "stringOptions",
+ operator: "any of",
+ value: ["good", "bad"],
+ },
+ ];
+
+ scoreFilters.forEach((filterDef) => {
+ it(`should not fail when filtering by ${filterDef.column}`, async () => {
+ const filterParam = JSON.stringify([filterDef]);
+ const response = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ `/api/public/traces${queryParam}filter=${encodeURIComponent(filterParam)}`,
+ );
+ expect(response.status).toBe(200);
+ expect(response.body.data).toBeDefined();
+ expect(response.body.meta).toBeDefined();
+ });
+ });
+ });
+ };
+
+ // Run for both table implementations
+ runFilterTests(false);
+ if (env.LANGFUSE_ENABLE_EVENTS_TABLE_OBSERVATIONS === "true") {
+ runFilterTests(true);
+ }
+ });
});
diff --git a/web/src/features/public-api/server/observations.ts b/web/src/features/public-api/server/observations.ts
index 244f359a7c..cfe4e7e6c4 100644
--- a/web/src/features/public-api/server/observations.ts
+++ b/web/src/features/public-api/server/observations.ts
@@ -171,8 +171,13 @@ const generateFilter = (query: QueryType) => {
observationsTableUiColumnDefinitions,
);
+ // Remove score filters since observations don't support scores in response
+ const filteredChFilter = chFilter.filter(
+ (f) => f.clickhouseTable !== "scores",
+ );
+
// Add project filter
- chFilter.push(
+ filteredChFilter.push(
new StringFilter({
clickhouseTable: "observations",
field: "project_id",
@@ -180,5 +185,5 @@ const generateFilter = (query: QueryType) => {
value: query.projectId,
}),
);
- return chFilter;
+ return filteredChFilter;
};
diff --git a/web/src/features/public-api/server/traces.ts b/web/src/features/public-api/server/traces.ts
index 0861c0d49a..22990d80a4 100644
--- a/web/src/features/public-api/server/traces.ts
+++ b/web/src/features/public-api/server/traces.ts
@@ -40,27 +40,36 @@ export type TraceQueryType = {
useEventsTable?: boolean | null;
};
-export const generateTracesForPublicApi = async ({
- props,
- advancedFilters,
- orderBy,
-}: {
- props: TraceQueryType;
- advancedFilters?: FilterState;
- orderBy: OrderByState;
-}) => {
+function buildTracesBaseQuery(
+ props: TraceQueryType,
+ select:
+ | {
+ includeObservations: boolean;
+ includeIO: boolean;
+ includeMetrics: boolean;
+ includeScores: boolean;
+ count: false;
+ }
+ | {
+ includeObservations: false;
+ includeIO: false;
+ includeMetrics: false;
+ includeScores: false;
+ count: true;
+ },
+ advancedFilters?: FilterState,
+ orderBy?: OrderByState,
+): {
+ query: string;
+ params: Record<string, any>;
+ fromTimeFilter?: DateTimeFilter | undefined;
+} {
// ClickHouse query optimizations for List Traces API
const disableObservationsFinal =
env.LANGFUSE_API_CLICKHOUSE_DISABLE_OBSERVATIONS_FINAL === "true";
const propagateObservationsTimeBounds =
env.LANGFUSE_API_CLICKHOUSE_PROPAGATE_OBSERVATIONS_TIME_BOUNDS === "true";
- const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;
- const includeIO = requestedFields.includes("io");
- const includeScores = requestedFields.includes("scores");
- const includeObservations = requestedFields.includes("observations");
- const includeMetrics = requestedFields.includes("metrics");
-
let filter = deriveFilters(
props,
filterParams,
@@ -101,19 +110,47 @@ export const generateTracesForPublicApi = async ({
),
);
- // Build CTEs conditionally based on requested fields
+ // Check if any filters reference the observations or scores tables
+ const filtersNeedObservations = filter.some(
+ (f) => f.clickhouseTable === "observations",
+ );
+ const filtersNeedScores = filter.some((f) => f.clickhouseTable === "scores");
+
+ // Check if filters specifically reference score aggregation columns
+ const hasScoreAggregationFilters = filter.some(
+ (f) => f.field === "s.scores_avg" || f.field === "s.score_categories",
+ );
+
+ // Build CTEs conditionally based on requested fields OR filters
const ctes = [];
- if (includeObservations || includeMetrics) {
+ if (
+ select.includeObservations ||
+ select.includeMetrics ||
+ filtersNeedObservations
+ ) {
// Conditionally add FINAL based on env var and whether metrics are requested
- const shouldUseFinal = includeMetrics && !disableObservationsFinal;
+ const shouldUseFinal =
+ (select.includeMetrics || filtersNeedObservations) &&
+ !disableObservationsFinal;
+
+ // Include metrics in CTE if requested OR if filters need them
+ const includeMetricsInCTE =
+ select.includeMetrics || filtersNeedObservations;
ctes.push(`
observation_stats AS (
SELECT
trace_id,
project_id,
- ${includeMetrics ? "sum(total_cost) as total_cost, date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds, " : ""}
+ ${includeMetricsInCTE ? "sum(total_cost) as total_cost, date_diff('millisecond', least(min(start_time), min(end_time)), greatest(max(start_time), max(end_time))) as latency_milliseconds, " : ""}
+ sumMap(usage_details) as usage_details,
+ sumMap(cost_details) as cost_details,
+ multiIf(arrayExists(x -> x = 'ERROR', groupArray(level)), 'ERROR', arrayExists(x -> x = 'WARNING', groupArray(level)), 'WARNING', arrayExists(x -> x = 'DEFAULT', groupArray(level)), 'DEFAULT', 'DEBUG') AS aggregated_level,
+ countIf(level = 'WARNING') as warning_count,
+ countIf(level = 'ERROR') as error_count,
+ countIf(level = 'DEFAULT') as default_count,
+ countIf(level = 'DEBUG') as debug_count,
groupUniqArray(id) as observation_ids
FROM observations ${shouldUseFinal ? "FINAL" : ""}
WHERE project_id = {projectId: String}
@@ -125,13 +162,53 @@ export const generateTracesForPublicApi = async ({
)`);
}
- if (includeScores) {
- ctes.push(`
+ if (select.includeScores || filtersNeedScores) {
+ // Use nested structure with pre-aggregation when score filters are present
+ // This ensures proper avg() computation and enables array filtering
+ if (hasScoreAggregationFilters) {
+ ctes.push(`
score_stats AS (
SELECT
trace_id,
project_id,
- groupUniqArray(id) as score_ids
+ groupUniqArray(id) as score_ids,
+ groupArrayIf(tuple(name, avg_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
+ groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories
+ FROM (
+ SELECT
+ project_id,
+ trace_id,
+ id,
+ name,
+ data_type,
+ string_value,
+ avg(value) as avg_value
+ FROM scores FINAL
+ WHERE project_id = {projectId: String}
+ AND session_id IS NULL
+ AND dataset_run_id IS NULL
+ ${fromTimeFilter ? `AND timestamp >= {cteFromTimeFilter: DateTime64(3)}` : ""}
+ ${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
+ GROUP BY
+ project_id,
+ trace_id,
+ id,
+ name,
+ data_type,
+ string_value
+ ) tmp
+ GROUP BY project_id, trace_id
+ )`);
+ } else {
+ // Use flat structure when no score filters present (backward compatible, better performance)
+ ctes.push(`
+ score_stats AS (
+ SELECT
+ trace_id,
+ project_id,
+ groupUniqArray(id) as score_ids,
+ groupArrayIf(tuple(name, value), data_type IN ('NUMERIC', 'BOOLEAN')) as scores_avg,
+ groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL') as score_categories
FROM scores
WHERE project_id = {projectId: String}
AND session_id IS NULL
@@ -140,37 +217,125 @@ export const generateTracesForPublicApi = async ({
${environmentFilter.length() > 0 ? `AND ${appliedEnvironmentFilter.query}` : ""}
GROUP BY project_id, trace_id
)`);
+ }
}
const withClause = ctes.length > 0 ? `WITH ${ctes.join(", ")}` : "";
+ // If user provides an order we prefer it or fallback to timestamp as the default.
+ // In both cases we append a t.event_ts desc order to pick the latest event in case of duplicates
+ // if we want to use a skip index.
+ // This may still return stale information if the orderBy key was updated between traces or if a filter
+ // applies only to a stale value.
+ const chOrderBy =
+ (orderByToClickhouseSql(orderBy || [], orderByColumns) ||
+ "ORDER BY t.timestamp desc") +
+ (shouldUseSkipIndexes ? ", t.event_ts desc" : "");
+
+ const queryMiddle = `
+ FROM traces t ${shouldUseSkipIndexes ? "" : "FINAL"}
+ ${select.includeObservations || select.includeMetrics || filtersNeedObservations ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
+ ${select.includeScores || filtersNeedScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
+ WHERE t.project_id = {projectId: String}
+ ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
+ `;
+
+ const query = select.count
+ ? `${withClause}
+ SELECT count() as count
+ ${queryMiddle}
+ `
+ : `
+ ${withClause}
+
+ SELECT
+ -- Core fields (always included)
+ t.id as id,
+ CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath",
+ t.project_id as project_id,
+ t.timestamp as timestamp,
+ t.name as name,
+ t.environment as environment,
+ t.session_id as session_id,
+ t.user_id as user_id,
+ t.release as release,
+ t.version as version,
+ t.bookmarked as bookmarked,
+ t.public as public,
+ t.tags as tags,
+ t.created_at as created_at,
+ t.updated_at as updated_at
+ -- IO fields (conditional)
+ ${select.includeIO ? ", t.input as input, t.output as output, t.metadata as metadata" : ""}
+ -- Scores (conditional)
+ ${select.includeScores ? ", s.score_ids as scores" : ""}
+ -- Observations (conditional)
+ ${select.includeObservations ? ", o.observation_ids as observations" : ""}
+ -- Metrics (conditional)
+ ${select.includeMetrics ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost" : ""}
+ ${queryMiddle}
+ ${chOrderBy}
+ ${shouldUseSkipIndexes ? "LIMIT 1 by t.id, t.project_id" : ""}
+ ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
+ `;
+
+ const params = {
+ ...appliedEnvironmentFilter.params,
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ ...(props.limit !== undefined ? { limit: props.limit } : {}),
+ ...(props.page !== undefined
+ ? { offset: (props.page - 1) * props.limit }
+ : {}),
+ ...(fromTimeFilter
+ ? {
+ cteFromTimeFilter: convertDateToClickhouseDateTime(
+ fromTimeFilter.value,
+ ),
+ }
+ : {}),
+ ...(toTimeFilter && propagateObservationsTimeBounds
+ ? {
+ cteToTimeFilter: convertDateToClickhouseDateTime(toTimeFilter.value),
+ }
+ : {}),
+ };
+
+ return { query, params, fromTimeFilter };
+}
+
+export const generateTracesForPublicApi = async ({
+ props,
+ advancedFilters,
+ orderBy,
+}: {
+ props: TraceQueryType;
+ advancedFilters?: FilterState;
+ orderBy: OrderByState;
+}) => {
+ const requestedFields = props.fields ?? TRACE_FIELD_GROUPS;
+ const includeIO = requestedFields.includes("io");
+ const includeScores = requestedFields.includes("scores");
+ const includeObservations = requestedFields.includes("observations");
+ const includeMetrics = requestedFields.includes("metrics");
+
+ const { query, params, fromTimeFilter } = buildTracesBaseQuery(
+ props,
+ {
+ includeIO,
+ includeObservations,
+ includeMetrics,
+ includeScores,
+ count: false,
+ },
+ advancedFilters,
+ orderBy,
+ );
const result = await measureAndReturn({
operationName: "getTracesForPublicApi",
projectId: props.projectId,
input: {
- params: {
- ...appliedEnvironmentFilter.params,
- ...appliedFilter.params,
- projectId: props.projectId,
- ...(props.limit !== undefined ? { limit: props.limit } : {}),
- ...(props.page !== undefined
- ? { offset: (props.page - 1) * props.limit }
- : {}),
- ...(fromTimeFilter
- ? {
- cteFromTimeFilter: convertDateToClickhouseDateTime(
- fromTimeFilter.value,
- ),
- }
- : {}),
- ...(toTimeFilter && propagateObservationsTimeBounds
- ? {
- cteToTimeFilter: convertDateToClickhouseDateTime(
- toTimeFilter.value,
- ),
- }
- : {}),
- },
+ params,
tags: {
feature: "tracing",
type: "trace",
@@ -182,54 +347,6 @@ export const generateTracesForPublicApi = async ({
preferredClickhouseService: "ReadOnly",
},
fn: (input) => {
- // If user provides an order we prefer it or fallback to timestamp as the default.
- // In both cases we append a t.event_ts desc order to pick the latest event in case of duplicates
- // if we want to use a skip index.
- // This may still return stale information if the orderBy key was updated between traces or if a filter
- // applies only to a stale value.
- const chOrderBy =
- (orderByToClickhouseSql(orderBy || [], orderByColumns) ||
- "ORDER BY t.timestamp desc") +
- (shouldUseSkipIndexes ? ", t.event_ts desc" : "");
-
- const query = `
- ${withClause}
-
- SELECT
- -- Core fields (always included)
- t.id as id,
- CONCAT('/project/', t.project_id, '/traces/', t.id) as "htmlPath",
- t.project_id as project_id,
- t.timestamp as timestamp,
- t.name as name,
- t.environment as environment,
- t.session_id as session_id,
- t.user_id as user_id,
- t.release as release,
- t.version as version,
- t.bookmarked as bookmarked,
- t.public as public,
- t.tags as tags,
- t.created_at as created_at,
- t.updated_at as updated_at
- -- IO fields (conditional)
- ${includeIO ? ", t.input as input, t.output as output, t.metadata as metadata" : ""}
- -- Scores (conditional)
- ${includeScores ? ", s.score_ids as scores" : ""}
- -- Observations (conditional)
- ${includeObservations ? ", o.observation_ids as observations" : ""}
- -- Metrics (conditional)
- ${includeMetrics ? ", COALESCE(o.latency_milliseconds / 1000, 0) as latency, COALESCE(o.total_cost, 0) as totalCost" : ""}
- FROM traces t ${shouldUseSkipIndexes ? "" : "FINAL"}
- ${includeObservations || includeMetrics ? "LEFT JOIN observation_stats o ON t.id = o.trace_id AND t.project_id = o.project_id" : ""}
- ${includeScores ? "LEFT JOIN score_stats s ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
- WHERE t.project_id = {projectId: String}
- ${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
- ${chOrderBy}
- ${shouldUseSkipIndexes ? "LIMIT 1 by t.id, t.project_id" : ""}
- ${props.limit !== undefined && props.page !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
- `;
-
return queryClickhouse<
TraceRecordReadType & {
observations?: string[];
@@ -269,13 +386,32 @@ export const getTracesCountForPublicApi = async ({
);
const appliedFilter = filter.apply();
- const query = `
+ let query = `
SELECT count() as count
FROM __TRACE_TABLE__ t
WHERE project_id = {projectId: String}
${filter.length() > 0 ? `AND ${appliedFilter.query}` : ""}
`;
+ let params: Record<string, any> = {
+ ...appliedFilter.params,
+ projectId: props.projectId,
+ };
+
+ if (advancedFilters !== undefined && advancedFilters.length > 0) {
+ ({ query, params } = buildTracesBaseQuery(
+ props,
+ {
+ includeObservations: false,
+ includeIO: false,
+ includeMetrics: false,
+ includeScores: false,
+ count: true,
+ },
+ advancedFilters,
+ ));
+ }
+
const timestamp = props.fromTimestamp
? new Date(props.fromTimestamp)
: undefined;
@@ -284,7 +420,7 @@ export const getTracesCountForPublicApi = async ({
operationName: "getTracesCountForPublicApi",
projectId: props.projectId,
input: {
- params: { ...appliedFilter.params, projectId: props.projectId },
+ params,
tags: {
feature: "tracing",
type: "trace",