Skip to content

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

feat(filters): add boolean score filtering (#14674)

Tobias Wochingerfd3dc9e02080
diff --git a/fern/apis/server/definition/trace.yml b/fern/apis/server/definition/trace.yml
index ec62a17675..e242945b89 100644
--- a/fern/apis/server/definition/trace.yml
+++ b/fern/apis/server/definition/trace.yml
@@ -82,7 +82,7 @@ service:
```json
[
{
- "type": string, // Required. One of: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "boolean", "null"
+ "type": string, // Required. One of: "datetime", "string", "number", "stringOptions", "categoryOptions", "arrayOptions", "stringObject", "numberObject", "booleanObject", "boolean", "null"
"column": string, // Required. Column to filter on (see available columns below)
"operator": string, // Required. Operator based on type:
// - datetime: ">", "<", ">=", "<="
@@ -93,10 +93,11 @@ service:
// - number: "=", ">", "<", ">=", "<="
// - stringObject: "=", "contains", "does not contain", "starts with", "ends with"
// - numberObject: "=", ">", "<", ">=", "<="
+ // - booleanObject: "=", "<>"
// - boolean: "=", "<>"
// - null: "is null", "is not null"
"value": any, // Required (except for null type). Value to compare against. Type depends on filter type
- "key": string // Required only for stringObject, numberObject, and categoryOptions types when filtering on nested fields like metadata
+ "key": string // Required only for stringObject, numberObject, booleanObject, and categoryOptions types when filtering on nested fields like metadata or score names
}
]
```
@@ -139,6 +140,7 @@ service:
### Scores (requires join with scores table)
- `scores_avg` (number) - Average of numeric scores (alias: `scores`)
- `score_categories` (categoryOptions) - Categorical score values
+ - `score_booleans` (booleanObject) - Boolean score values. Use `key` for the score name and a boolean `value`, e.g. `{"type": "booleanObject", "column": "score_booleans", "key": "is_correct", "operator": "=", "value": true}`. The `<>` operator also matches traces without a score of that name.
## Filter Examples
```json
diff --git a/packages/shared/src/eventsTable.ts b/packages/shared/src/eventsTable.ts
index 27912485c6..b324ac5201 100644
--- a/packages/shared/src/eventsTable.ts
+++ b/packages/shared/src/eventsTable.ts
@@ -252,6 +252,13 @@ const eventsTableColsDefinition = [
options: [], // to be added at runtime
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "score_booleans",
+ type: "booleanObject",
+ internal: "score_booleans",
+ nullable: true,
+ },
{
name: "Trace Scores (numeric)",
id: "trace_scores_avg",
@@ -266,6 +273,13 @@ const eventsTableColsDefinition = [
options: [], // to be added at runtime
nullable: true,
},
+ {
+ name: "Trace Scores (boolean)",
+ id: "trace_score_booleans",
+ type: "booleanObject",
+ internal: "trace_score_booleans",
+ nullable: true,
+ },
{
name: "Comment Count",
id: "commentCount",
diff --git a/packages/shared/src/features/annotation/types.ts b/packages/shared/src/features/annotation/types.ts
index c5848f961e..2a9b78173d 100644
--- a/packages/shared/src/features/annotation/types.ts
+++ b/packages/shared/src/features/annotation/types.ts
@@ -1,11 +1,6 @@
import z from "zod";
import { StringNoHTML, StringNoHTMLNonEmpty } from "../../utils/zod";
-import {
- BooleanData,
- CategoricalData,
- TextData,
- NumericData,
-} from "../../domain";
+import { CategoricalData, TextData, NumericData } from "../../domain";
const ScoreTargetTrace = z.object({
type: z.literal("trace"),
@@ -45,6 +40,24 @@ const UpdateAnnotationScoreBase = CreateAnnotationScoreBase.extend({
id: z.string(),
});
+const AnnotationBooleanData = z.object({
+ stringValue: z.enum(["True", "False"]),
+ dataType: z.literal("BOOLEAN"),
+});
+
+// The router persists `value` and `stringValue` verbatim, and the two feed
+// different filter paths (scores_avg vs score_booleans) — derive `value` from
+// the label so a crafted request cannot store an inconsistent pair like
+// { stringValue: "True", value: 0 }.
+const deriveBooleanValue = <
+ T extends { dataType: string; stringValue?: string | null; value: number },
+>(
+ data: T,
+): T =>
+ data.dataType === "BOOLEAN"
+ ? { ...data, value: data.stringValue === "True" ? 1 : 0 }
+ : data;
+
/**
* CreateAnnotationScoreData is only used for annotation scores created via the UI.
* For langfuse score types please refer to `web/src/features/public-api/types/scores.ts`
@@ -53,10 +66,10 @@ export const CreateAnnotationScoreData = CreateAnnotationScoreBase.and(
z.discriminatedUnion("dataType", [
NumericData,
CategoricalData,
- BooleanData,
+ AnnotationBooleanData,
TextData,
]),
-);
+).transform(deriveBooleanValue);
export type CreateAnnotationScoreData = z.infer<
typeof CreateAnnotationScoreData
@@ -70,10 +83,10 @@ export const UpdateAnnotationScoreData = UpdateAnnotationScoreBase.and(
z.discriminatedUnion("dataType", [
NumericData,
CategoricalData,
- BooleanData,
+ AnnotationBooleanData,
TextData,
]),
-);
+).transform(deriveBooleanValue);
export type UpdateAnnotationScoreData = z.infer<
typeof UpdateAnnotationScoreData
diff --git a/packages/shared/src/interfaces/filters.ts b/packages/shared/src/interfaces/filters.ts
index 66c927ed3f..d84ab3743c 100644
--- a/packages/shared/src/interfaces/filters.ts
+++ b/packages/shared/src/interfaces/filters.ts
@@ -16,6 +16,7 @@ export const filterOperators = {
"ends with",
],
numberObject: ["=", ">", "<", ">=", "<="],
+ booleanObject: ["=", "<>"],
boolean: ["=", "<>"],
null: ["is null", "is not null"],
positionInTrace: ["="],
@@ -80,6 +81,13 @@ export const numberObjectFilter = z.object({
operator: z.enum(filterOperators.number),
value: z.number(),
});
+export const booleanObjectFilter = z.object({
+ type: z.literal("booleanObject"),
+ column: z.string(),
+ key: z.string(), // eg scores --> "is_hallucination"
+ operator: z.enum(filterOperators.booleanObject),
+ value: z.boolean(),
+});
export const booleanFilter = z.object({
type: z.literal("boolean"),
column: z.string(),
@@ -126,6 +134,7 @@ export const singleFilter = z.discriminatedUnion("type", [
arrayOptionsFilter,
stringObjectFilter,
numberObjectFilter,
+ booleanObjectFilter,
booleanFilter,
nullFilter,
positionInTraceFilter,
@@ -158,6 +167,7 @@ export const eventsTableSingleFilter = z.discriminatedUnion("type", [
arrayOptionsFilter,
eventsTableStringObjectFilter,
numberObjectFilter,
+ booleanObjectFilter,
booleanFilter,
nullFilter,
positionInTraceFilter,
diff --git a/packages/shared/src/observationsTable.ts b/packages/shared/src/observationsTable.ts
index 7d3d715b0d..477fac2367 100644
--- a/packages/shared/src/observationsTable.ts
+++ b/packages/shared/src/observationsTable.ts
@@ -198,6 +198,13 @@ export const observationsTableCols: ColumnDefinition[] = [
options: [], // to be added at runtime
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "score_booleans",
+ type: "booleanObject",
+ internal: "score_booleans",
+ nullable: true,
+ },
{
name: "Version",
id: "version",
@@ -281,6 +288,7 @@ export type ObservationOptions = {
environment: Array<SingleValueOption>;
scores_avg: Array<string>;
score_categories: Array<MultiValueOption>;
+ score_booleans: Array<string>;
promptName: Array<SingleValueOption>;
tags: Array<SingleValueOption>;
type: Array<SingleValueOption>;
@@ -313,6 +321,9 @@ export function observationsTableColsWithOptions(
if (col.id === "score_categories") {
return formatColumnOptions(col, options?.score_categories ?? []);
}
+ if (col.id === "score_booleans") {
+ return formatColumnOptions(col, options?.score_booleans ?? []);
+ }
if (col.id === "promptName") {
return formatColumnOptions(col, options?.promptName ?? []);
}
diff --git a/packages/shared/src/server/filterToPrisma.ts b/packages/shared/src/server/filterToPrisma.ts
index 3ba010fb4b..1f634b9728 100644
--- a/packages/shared/src/server/filterToPrisma.ts
+++ b/packages/shared/src/server/filterToPrisma.ts
@@ -113,6 +113,9 @@ export function tableColumnsToSqlFilter(
// LFE-4815: Support category options in postgres
logger.warn("Category options not supported in postgres yet");
throw new Error("Category options not supported in postgres yet");
+ case "booleanObject":
+ logger.warn("Boolean object filters not supported in postgres yet");
+ throw new Error("Boolean object filters not supported in postgres yet");
case "null":
valuePrisma = Prisma.sql``;
break;
diff --git a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts
index a5140484cd..0f7229f46b 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/clickhouse-filter.ts
@@ -580,6 +580,54 @@ export class NumberObjectFilter implements Filter {
}
}
+/**
+ * Encodes one boolean-score entry the way the `score_booleans` ClickHouse
+ * aggregation stores it (`scoreBooleansAggregation` in query-fragments.ts:
+ * `concat(name, ':', lowerUTF8(string_value))`). BooleanObjectFilter and
+ * InMemoryFilterService must build lookup targets through this helper so the
+ * two filter paths and the SQL producer cannot drift apart.
+ */
+export const encodeBooleanScoreEntry = (key: string, value: boolean): string =>
+ `${key}:${value ? "true" : "false"}`;
+
+export class BooleanObjectFilter implements Filter {
+ public clickhouseTable: string;
+ public field: string;
+ public key: string;
+ public value: boolean;
+ public operator: (typeof filterOperators)["booleanObject"][number];
+ public tablePrefix?: string;
+
+ constructor(opts: {
+ clickhouseTable: string;
+ field: string;
+ operator: (typeof filterOperators)["booleanObject"][number];
+ key: string;
+ value: boolean;
+ tablePrefix?: string;
+ }) {
+ this.clickhouseTable = opts.clickhouseTable;
+ this.field = opts.field;
+ this.value = opts.value;
+ this.operator = opts.operator;
+ this.tablePrefix = opts.tablePrefix;
+ this.key = opts.key;
+ }
+
+ apply(): ClickhouseFilter {
+ const uid = clickhouseCompliantRandomCharacters();
+ const varName = `booleanObjectFilter${uid}`;
+ const column = `${this.tablePrefix ? this.tablePrefix + "." : ""}${this.field}`;
+ const value = encodeBooleanScoreEntry(this.key, this.value);
+ const predicate = `has(${column}, {${varName}: String})`;
+
+ return {
+ query: this.operator === "<>" ? `NOT ${predicate}` : predicate,
+ params: { [varName]: value },
+ };
+ }
+}
+
export class BooleanFilter implements Filter {
public clickhouseTable: string;
public field: string;
diff --git a/packages/shared/src/server/queries/clickhouse-sql/factory.ts b/packages/shared/src/server/queries/clickhouse-sql/factory.ts
index 34c7fc8530..58533611a7 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/factory.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/factory.ts
@@ -18,6 +18,7 @@ import {
NumberFilter,
ArrayOptionsFilter,
BooleanFilter,
+ BooleanObjectFilter,
NumberObjectFilter,
StringObjectFilter,
NullFilter,
@@ -131,6 +132,15 @@ export const createFilterFromFilterState = (
value: frontEndFilter.value,
tablePrefix: column.queryPrefix,
});
+ case "booleanObject":
+ return new BooleanObjectFilter({
+ clickhouseTable: column.clickhouseTableName,
+ field: column.clickhouseSelect,
+ key: frontEndFilter.key,
+ operator: frontEndFilter.operator,
+ value: frontEndFilter.value,
+ tablePrefix: column.queryPrefix,
+ });
case "stringObject":
return new StringObjectFilter({
clickhouseTable: column.clickhouseTableName,
diff --git a/packages/shared/src/server/queries/clickhouse-sql/filterTypeCompatibility.ts b/packages/shared/src/server/queries/clickhouse-sql/filterTypeCompatibility.ts
index 9f085dd276..5c3f2a38eb 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/filterTypeCompatibility.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/filterTypeCompatibility.ts
@@ -15,6 +15,7 @@ export const COMPATIBLE_FILTER_TYPES: Partial<
boolean: ["boolean"],
stringObject: ["stringObject"],
numberObject: ["numberObject"],
+ booleanObject: ["booleanObject"],
categoryOptions: ["categoryOptions", "stringOptions"],
};
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 f1d875679a..5316073f9e 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/query-fragments.ts
@@ -68,6 +68,20 @@ export const eventsTracesAggregation = (
return builder;
};
+/**
+ * Aggregation expression producing a `score_booleans` array with entries
+ * encoded as `<name>:true|false` (lowercased via lowerUTF8). This is the
+ * producer half of a wire contract: `BooleanObjectFilter` and
+ * `InMemoryFilterService` build the same strings via `encodeBooleanScoreEntry`
+ * and do `has()` membership checks — every producer must use this fragment so
+ * the encoding cannot drift. groupUniqArrayIf (not groupArrayIf) because
+ * consumers only check existence, and dedup bounds the aggregation state to
+ * 2 × distinct boolean score names even when the surrounding GROUP BY keeps
+ * per-row columns like `id` or `comment`.
+ */
+export const scoreBooleansAggregation = (columnPrefix = ""): string =>
+ `groupUniqArrayIf(concat(${columnPrefix}name, ':', lowerUTF8(${columnPrefix}string_value)), ${columnPrefix}data_type = 'BOOLEAN' AND notEmpty(${columnPrefix}string_value))`;
+
interface BaseScoresParams {
projectId: string;
startTimeFrom?: string | null;
@@ -124,7 +138,9 @@ export const buildScoresAggregationCTE = (
${primaryKey},
${additionalOuterCols.length > 0 ? additionalOuterCols.join(",\n ") + "," : ""}
groupArrayIf(tuple(name, avg_value, data_type, string_value), data_type IN ('NUMERIC', 'BOOLEAN')) AS scores_avg,
- groupArrayIf(concat(name, ':', string_value), data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)) AS score_categories${params.includeTupleEncoding ? `,\n groupArrayIf(tuple(name, string_value, data_type), data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)) AS score_categories_tuples` : ""}
+ groupArrayIf(concat(name, ':', string_value), data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)) AS score_categories,
+ -- BOOLEAN scores also stay in scores_avg for legacy numeric filters; true/false filters need raw-value existence instead of avg(value).
+ ${scoreBooleansAggregation()} AS score_booleans${params.includeTupleEncoding ? `,\n groupArrayIf(tuple(name, string_value, data_type), data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)) AS score_categories_tuples` : ""}
FROM (
SELECT
${primaryKey},
@@ -324,7 +340,8 @@ export const eventsSessionScoresAggregation = (params: {
groupArrayIf(
concat(name, ':', string_value),
data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
- ) AS score_categories
+ ) AS score_categories,
+ ${scoreBooleansAggregation()} AS score_booleans
FROM (
SELECT
project_id,
@@ -355,6 +372,7 @@ export const eventsSessionScoresAggregation = (params: {
"score_session_id",
"scores_avg",
"score_categories",
+ "score_booleans",
],
};
};
diff --git a/packages/shared/src/server/queries/index.ts b/packages/shared/src/server/queries/index.ts
index 8f6ee93c4d..85a2d69c54 100644
--- a/packages/shared/src/server/queries/index.ts
+++ b/packages/shared/src/server/queries/index.ts
@@ -17,6 +17,7 @@ export {
NumberObjectFilter,
StringObjectFilter,
NullFilter,
+ encodeBooleanScoreEntry,
type ClickhouseOperator,
} from "./clickhouse-sql/clickhouse-filter";
export {
@@ -84,4 +85,5 @@ export {
eventsTraceMetadata,
eventsTracesAggregation,
eventsTracesScoresAggregation,
+ scoreBooleansAggregation,
} from "./clickhouse-sql/query-fragments";
diff --git a/packages/shared/src/server/repositories/dataset-run-items.ts b/packages/shared/src/server/repositories/dataset-run-items.ts
index 85895a677c..25f18607e7 100644
--- a/packages/shared/src/server/repositories/dataset-run-items.ts
+++ b/packages/shared/src/server/repositories/dataset-run-items.ts
@@ -1,4 +1,5 @@
import { DatasetRunItemDomain } from "../../domain/dataset-run-items";
+import { scoreBooleansAggregation } from "../queries/clickhouse-sql/query-fragments";
import { type OrderByState } from "../../interfaces/orderBy";
import { datasetRunItemsTableUiColumnDefinitions } from "../tableMappings";
import { datasetRunsTableUiColumnDefinitions } from "../../tableDefinitions/mapDatasetRunsTable";
@@ -99,6 +100,7 @@ export type DatasetRunsMetrics = {
avgLatency: number;
aggScoresAvg: Array<[string, number]>;
aggScoreCategories: string[];
+ aggScoreBooleans: string[];
};
type DatasetRunsRows = {
@@ -122,6 +124,7 @@ type DatasetRunsMetricsRecordType = {
total_cost: number;
agg_scores_avg: Array<[string, number]>;
agg_score_categories: string[];
+ agg_score_booleans: string[];
};
type DatasetRunsRowsRecordType = {
@@ -174,6 +177,7 @@ const convertDatasetRunsMetricsRecord = (
avgLatency: record.avg_latency_seconds ?? 0,
aggScoresAvg: record.agg_scores_avg ?? [],
aggScoreCategories: record.agg_score_categories ?? [],
+ aggScoreBooleans: record.agg_score_booleans ?? [],
};
};
@@ -272,7 +276,8 @@ const getDatasetRunsTableInternal = async <T>(
-- Score aggregations
sa.scores_avg as agg_scores_avg,
- sa.score_categories as agg_score_categories`;
+ sa.score_categories as agg_score_categories,
+ sa.score_booleans as agg_score_booleans`;
break;
case "count":
select = "count(DISTINCT drm.dataset_run_id) as count";
@@ -339,7 +344,8 @@ const getDatasetRunsTableInternal = async <T>(
groupArrayIf(
concat(s.name, ':', s.string_value),
s.data_type = 'CATEGORICAL' AND notEmpty(s.string_value)
- ) AS score_categories
+ ) AS score_categories,
+ ${scoreBooleansAggregation("s.")} AS score_booleans
FROM dataset_run_items_rmt dri
LEFT JOIN (
SELECT
@@ -648,7 +654,8 @@ const getQualifyingDatasetItems = async <T>(opts: {
groupArrayIf(
concat(s.name, ':', s.string_value),
s.data_type = 'CATEGORICAL' AND notEmpty(s.string_value)
- ) AS score_categories
+ ) AS score_categories,
+ ${scoreBooleansAggregation("s.")} AS score_booleans
FROM dataset_run_items_rmt dri
LEFT JOIN (
SELECT
@@ -829,7 +836,8 @@ const getDatasetRunItemsTableInternal = async <
groupArrayIf(
concat(s.name, ':', s.string_value),
s.data_type = 'CATEGORICAL' AND notEmpty(s.string_value)
- ) AS score_categories
+ ) AS score_categories,
+ ${scoreBooleansAggregation("s.")} AS score_booleans
FROM dataset_run_items_rmt dri
LEFT JOIN (
SELECT
diff --git a/packages/shared/src/server/repositories/events.ts b/packages/shared/src/server/repositories/events.ts
index bcb2d3c72b..ff06ed9a12 100644
--- a/packages/shared/src/server/repositories/events.ts
+++ b/packages/shared/src/server/repositories/events.ts
@@ -627,8 +627,10 @@ async function getObservationsFromEventsTableInternal<T>(
column === "scores" ||
column === "scores_avg" ||
column === "score_categories" ||
+ column === "score_booleans" ||
column === "scores (numeric)" ||
- column === "scores (categorical)"
+ column === "scores (categorical)" ||
+ column === "scores (boolean)"
);
});
const hasTraceScoresFilter = baseFilter.some((f) => {
@@ -636,8 +638,10 @@ async function getObservationsFromEventsTableInternal<T>(
return (
column === "trace_scores_avg" ||
column === "trace_score_categories" ||
+ column === "trace_score_booleans" ||
column === "trace scores (numeric)" ||
- column === "trace scores (categorical)"
+ column === "trace scores (categorical)" ||
+ column === "trace scores (boolean)"
);
});
const orderByEntries = orderByToEntries(
@@ -1791,7 +1795,10 @@ async function getTracesFromEventsTableForPublicApiInternal<T>(
// Check if filters specifically reference score aggregation columns
const hasScoreAggregationFilters = tracesFilter.some(
- (f) => f.field === "s.scores_avg" || f.field === "s.score_categories",
+ (f) =>
+ f.field === "s.scores_avg" ||
+ f.field === "s.score_categories" ||
+ f.field === "s.score_booleans",
);
// Build traces CTE using eventsTracesAggregation WITHOUT filters
@@ -1825,6 +1832,7 @@ async function getTracesFromEventsTableForPublicApiInternal<T>(
"score_ids",
"scores_avg",
"score_categories",
+ "score_booleans",
],
})
.leftJoin(
diff --git a/packages/shared/src/server/repositories/experiments.ts b/packages/shared/src/server/repositories/experiments.ts
index 8e72b7cc6f..2665056729 100644
--- a/packages/shared/src/server/repositories/experiments.ts
+++ b/packages/shared/src/server/repositories/experiments.ts
@@ -21,6 +21,7 @@ import {
eventsExperimentsAggregation,
eventsScoresAggregation,
eventsTracesScoresAggregation,
+ scoreBooleansAggregation,
} from "../queries/clickhouse-sql/query-fragments";
import { extractTimeFilter, queryClickhouse } from "../repositories";
import { parseClickhouseUTCDateTimeFormat } from "../repositories/clickhouse";
@@ -110,6 +111,7 @@ const experimentScoreCTE = (params: {
"s.experiment_id AS experiment_id",
`groupArrayIf(tuple(s.name, s.exp_avg, s.data_type, s.string_value), s.data_type IN ('NUMERIC', 'BOOLEAN')) AS ${prefix}_scores_avg`,
`groupArrayIf(concat(s.name, ':', s.string_value), s.data_type = 'CATEGORICAL' AND notEmpty(s.string_value)) AS ${prefix}_score_categories`,
+ `${scoreBooleansAggregation("s.")} AS ${prefix}_score_booleans`,
)
.groupBy("s.project_id", "s.experiment_id")
.having(params.filters.apply())
@@ -251,10 +253,16 @@ const getExperimentsFromEventsGeneric = async <T>(
// Detect score filter presence to conditionally include score CTEs
const hasTraceScoreFilter = scoreAggFilters.some((f) =>
- ["trace_scores_avg", "trace_score_categories"].includes(f.field),
+ [
+ "trace_scores_avg",
+ "trace_score_categories",
+ "trace_score_booleans",
+ ].includes(f.field),
);
const hasObsScoreFilter = scoreAggFilters.some((f) =>
- ["obs_scores_avg", "obs_score_categories"].includes(f.field),
+ ["obs_scores_avg", "obs_score_categories", "obs_score_booleans"].includes(
+ f.field,
+ ),
);
const experimentIds = experimentIdFilter?.values;
@@ -284,7 +292,11 @@ const getExperimentsFromEventsGeneric = async <T>(
schema: ["project_id", "experiment_id", "trace_id"],
},
filters: scoreAggFilters.filter((f) =>
- ["obs_scores_avg", "obs_score_categories"].includes(f.field),
+ [
+ "obs_scores_avg",
+ "obs_score_categories",
+ "obs_score_booleans",
+ ].includes(f.field),
),
level: "observation",
}),
@@ -306,7 +318,11 @@ const getExperimentsFromEventsGeneric = async <T>(
schema: ["project_id", "experiment_id", "trace_id"],
},
filters: scoreAggFilters.filter((f) =>
- ["trace_scores_avg", "trace_score_categories"].includes(f.field),
+ [
+ "trace_scores_avg",
+ "trace_score_categories",
+ "trace_score_booleans",
+ ].includes(f.field),
),
level: "trace",
}),
@@ -578,6 +594,7 @@ export type ScoreColumnDefinition = {
type ProcessedScoreFilterOptions = {
numeric: string[];
+ boolean: string[];
categorical: Array<{ label: string; values: string[] }>;
scoreColumns: ScoreColumnDefinition[];
};
@@ -586,6 +603,7 @@ const processScoreFilterOptionsResults = (
rows: ScoreFilterOptionsRow[],
): ProcessedScoreFilterOptions => {
const numeric = new Set<string>();
+ const boolean = new Set<string>();
const categorical = new Map<string, Set<string>>();
const scoreColumns: ScoreColumnDefinition[] = [];
@@ -599,6 +617,9 @@ const processScoreFilterOptionsResults = (
if (row.data_type === "NUMERIC" || row.data_type === "BOOLEAN") {
numeric.add(row.name);
+ }
+ if (row.data_type === "BOOLEAN") {
+ boolean.add(row.name);
} else if (row.data_type === "CATEGORICAL") {
const existingValues = categorical.get(row.name) ?? new Set<string>();
row.values.forEach((value) => existingValues.add(value));
@@ -608,6 +629,7 @@ const processScoreFilterOptionsResults = (
return {
numeric: Array.from(numeric),
+ boolean: Array.from(boolean),
categorical: Array.from(categorical.entries()).map(([label, values]) => ({
label,
values: Array.from(values),
@@ -618,6 +640,7 @@ const processScoreFilterOptionsResults = (
const emptyScoreFilterOptions = (): ProcessedScoreFilterOptions => ({
numeric: [],
+ boolean: [],
categorical: [],
scoreColumns: [],
});
@@ -683,9 +706,11 @@ export const getExperimentItemsFilterOptions = async (
): Promise<{
obs_scores_avg: string[];
obs_score_categories: Array<{ label: string; values: string[] }>;
+ obs_score_booleans: string[];
obs_score_columns: ScoreColumnDefinition[];
trace_scores_avg: string[];
trace_score_categories: Array<{ label: string; values: string[] }>;
+ trace_score_booleans: string[];
trace_score_columns: ScoreColumnDefinition[];
}> => {
const { observation, trace } =
@@ -694,9 +719,11 @@ export const getExperimentItemsFilterOptions = async (
return {
obs_scores_avg: observation.numeric,
obs_score_categories: observation.categorical,
+ obs_score_booleans: observation.boolean,
obs_score_columns: observation.scoreColumns,
trace_scores_avg: trace.numeric,
trace_score_categories: trace.categorical,
+ trace_score_booleans: trace.boolean,
trace_score_columns: trace.scoreColumns,
};
};
@@ -857,10 +884,16 @@ const buildQualificationPlan = (
const filters = filterByExperiment.flatMap((f) => f.filters);
const hasScoreFilters = filters.some((f) =>
- ["obs_scores_avg", "obs_score_categories"].includes(f.column),
+ ["obs_scores_avg", "obs_score_categories", "obs_score_booleans"].includes(
+ f.column,
+ ),
);
const hasTraceScoreFilters = filters.some((f) =>
- ["trace_scores_avg", "trace_score_categories"].includes(f.column),
+ [
+ "trace_scores_avg",
+ "trace_score_categories",
+ "trace_score_booleans",
+ ].includes(f.column),
);
const allExperimentIds = [
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index b4b29eefe8..96354de297 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -9,6 +9,7 @@ import {
upsertClickhouse,
} from "./clickhouse";
import { logger } from "../logger";
+import { scoreBooleansAggregation } from "../queries/clickhouse-sql/query-fragments";
import {
InternalServerError,
LangfuseNotFoundError,
@@ -759,7 +760,8 @@ const getObservationsTableInternal = async <T>(
groupArrayIf(
concat(name, ':', string_value),
data_type = 'CATEGORICAL' AND notEmpty(string_value)
- ) AS score_categories
+ ) AS score_categories,
+ ${scoreBooleansAggregation()} AS score_booleans
FROM (
SELECT
trace_id,
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index cbbd81c37e..e026316f62 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -1056,6 +1056,49 @@ export const getNumericScoresGroupedByName = async (
return rows;
};
+export const getBooleanScoresGroupedByName = async (
+ projectId: string,
+ filter?: FilterState,
+) => {
+ const chFilter = filter
+ ? createFilterFromFilterState(
+ filter,
+ scoresColumnsTableUiColumnDefinitions,
+ scoresTableCols,
+ )
+ : undefined;
+
+ const filterRes = chFilter ? new FilterList(chFilter).apply() : undefined;
+
+ const query = `
+ select
+ name as name
+ from scores s
+ WHERE s.project_id = {projectId: String}
+ AND s.data_type = 'BOOLEAN'
+ AND s.string_value IS NOT NULL
+ AND s.string_value != ''
+ ${filterRes?.query ? `AND ${filterRes.query}` : ""}
+ GROUP BY name
+ ORDER BY count() desc
+ LIMIT ${FILTER_OPTION_SCORE_NAME_LIMIT};
+ `;
+
+ const rows = await queryClickhouse<{
+ name: string;
+ }>({
+ query: query,
+ params: {
+ projectId: projectId,
+ ...(filterRes ? filterRes.params : {}),
+ },
+ tags: { projectId },
+ preferredClickhouseService: "ReadOnly",
+ });
+
+ return rows;
+};
+
export const getCategoricalScoresGroupedByName = async (
projectId: string,
filter?: FilterState,
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index db4b553086..413eb841d3 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -12,6 +12,7 @@ import {
getProjectIdDefaultFilter,
} from "../queries/clickhouse-sql/factory";
import { orderByToClickhouseSql } from "../queries";
+import { scoreBooleansAggregation } from "../queries/clickhouse-sql/query-fragments";
import { shouldSkipObservationsFinal } from "../queries/clickhouse-sql/query-options";
import { LISTABLE_SCORE_TYPES } from "../../domain/scores";
import { OrderByState } from "../../interfaces/orderBy";
@@ -1733,7 +1734,10 @@ async function buildTracesBaseQuery(
const filtersNeedScores = filter.some((f) => f.clickhouseTable === "scores");
const hasScoreAggregationFilters = filter.some(
- (f) => f.field === "s.scores_avg" || f.field === "s.score_categories",
+ (f) =>
+ f.field === "s.scores_avg" ||
+ f.field === "s.score_categories" ||
+ f.field === "s.score_booleans",
);
const ctes = [];
@@ -1783,7 +1787,8 @@ async function buildTracesBaseQuery(
project_id,
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
+ groupArrayIf(concat(name, ':', string_value), data_type = 'CATEGORICAL' AND notEmpty(string_value)) AS score_categories,
+ ${scoreBooleansAggregation()} AS score_booleans
FROM (
SELECT
project_id,
diff --git a/packages/shared/src/server/services/InMemoryFilterService.ts b/packages/shared/src/server/services/InMemoryFilterService.ts
index 792d5c1cff..268969e214 100644
--- a/packages/shared/src/server/services/InMemoryFilterService.ts
+++ b/packages/shared/src/server/services/InMemoryFilterService.ts
@@ -1,5 +1,6 @@
import { FilterCondition, FilterState } from "../../types";
import { logger } from "../logger";
+import { encodeBooleanScoreEntry } from "../queries/clickhouse-sql/clickhouse-filter";
export class InMemoryFilterService {
/**
@@ -102,6 +103,13 @@ export class InMemoryFilterService {
condition.value,
operator,
);
+ case "booleanObject":
+ return this.evaluateBooleanObjectFilter(
+ fieldValue,
+ condition.key,
+ condition.value,
+ operator,
+ );
case "null":
return this.evaluateNullFilter(fieldValue, operator);
case "positionInTrace":
@@ -368,6 +376,36 @@ export class InMemoryFilterService {
}
}
+ private static evaluateBooleanObjectFilter(
+ fieldValue: unknown,
+ key: string,
+ filterValue: boolean,
+ operator: string,
+ ): boolean {
+ // Same encoding as the score_booleans ClickHouse aggregation — callers
+ // must supply pre-lowercased `name:true|false` entries via their field
+ // mapper (raw score string_value is "True"/"False" and would not match).
+ const target = encodeBooleanScoreEntry(key, filterValue);
+ const hasValue = Array.isArray(fieldValue)
+ ? fieldValue.map(String).includes(target)
+ : false;
+
+ switch (operator) {
+ case "=":
+ return hasValue;
+ case "<>":
+ return !hasValue;
+ default:
+ logger.error("Unsupported booleanObject filter operator", {
+ operator,
+ filterValue,
+ fieldValue,
+ key,
+ });
+ return false;
+ }
+ }
+
private static evaluateNullFilter(
fieldValue: unknown,
operator: string,
diff --git a/packages/shared/src/server/services/sessions-ui-table-events-service.ts b/packages/shared/src/server/services/sessions-ui-table-events-service.ts
index 2c2a83ac69..e331bcfa67 100644
--- a/packages/shared/src/server/services/sessions-ui-table-events-service.ts
+++ b/packages/shared/src/server/services/sessions-ui-table-events-service.ts
@@ -37,6 +37,7 @@ type SessionEventsBaseReturnType = {
type SessionScoreFields = {
scores_avg?: Array<Array<[string, number]>>;
score_categories?: Array<Array<string>>;
+ score_booleans?: Array<Array<string>>;
};
export type SessionEventsDataReturnType = SessionEventsBaseReturnType &
@@ -286,7 +287,7 @@ const getSessionsTableFromEventsGeneric = async <T>(
"s.session_output_usage",
"s.session_total_usage",
)
- .select("sc.scores_avg", "sc.score_categories");
+ .select("sc.scores_avg", "sc.score_categories", "sc.score_booleans");
break;
default: {
const exhaustiveCheckDefault: never = select;
diff --git a/packages/shared/src/server/services/sessions-ui-table-service.ts b/packages/shared/src/server/services/sessions-ui-table-service.ts
index 1ea45d2128..8232ff2c4c 100644
--- a/packages/shared/src/server/services/sessions-ui-table-service.ts
+++ b/packages/shared/src/server/services/sessions-ui-table-service.ts
@@ -5,6 +5,7 @@ import { FilterState } from "../../types";
import { sessionsViewCols } from "../../tableDefinitions/sessionsView";
import { findUiColumnMapping } from "../../tableDefinitions";
import { convertDateToClickhouseDateTime } from "../clickhouse/client";
+import { scoreBooleansAggregation } from "../queries/clickhouse-sql/query-fragments";
import { measureAndReturn } from "../clickhouse/measureAndReturn";
import { DateTimeFilter, FilterList, orderByToClickhouseSql } from "../queries";
import {
@@ -27,6 +28,7 @@ export type SessionDataReturnType = {
trace_environment?: string;
scores_avg?: Array<Array<[string, number]>>;
score_categories?: Array<Array<string>>;
+ score_booleans?: Array<Array<string>>;
};
export type SessionWithMetricsReturnType = SessionDataReturnType & {
@@ -161,7 +163,8 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
session_output_usage,
session_total_usage,
scores_avg,
- score_categories`;
+ score_categories,
+ score_booleans`;
break;
default: {
const exhaustiveCheckDefault: never = select;
@@ -229,6 +232,7 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
"session_input_usage",
"scores_avg",
"score_categories",
+ "score_booleans",
].includes(f.field),
) ||
(orderBy &&
@@ -258,7 +262,8 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
groupArrayIf(
concat(name, ':', string_value),
data_type = 'CATEGORICAL' AND notEmpty(string_value)
- ) AS score_categories
+ ) AS score_categories,
+ ${scoreBooleansAggregation()} AS score_booleans
FROM (
SELECT
project_id,
@@ -277,7 +282,7 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
name,
data_type,
string_value
- ) tmp
+ ) tmp
GROUP BY
project_id, session_id
)`;
@@ -342,7 +347,8 @@ const getSessionsTableGeneric = async <T>(props: FetchSessionsTableProps) => {
${
select === "metrics" || requiresScoresJoin
? `groupUniqArrayArray(s.scores_avg) as scores_avg,
- groupUniqArrayArray(s.score_categories) as score_categories,`
+ groupUniqArrayArray(s.score_categories) as score_categories,
+ groupUniqArrayArray(s.score_booleans) as score_booleans,`
: ""
}
arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sumMap(o.sum_cost_details)))) as session_input_cost,
diff --git a/packages/shared/src/server/services/traces-ui-table-service.ts b/packages/shared/src/server/services/traces-ui-table-service.ts
index b862ca8ecb..bbf10d0f47 100644
--- a/packages/shared/src/server/services/traces-ui-table-service.ts
+++ b/packages/shared/src/server/services/traces-ui-table-service.ts
@@ -1,4 +1,5 @@
import { OrderByState } from "../../interfaces/orderBy";
+import { scoreBooleansAggregation } from "../queries/clickhouse-sql/query-fragments";
import { tracesTableUiColumnDefinitions } from "../tableMappings";
import { tracesTableCols } from "../../tableDefinitions/tracesTable";
import { findUiColumnMapping } from "../../tableDefinitions";
@@ -328,7 +329,8 @@ async function getTracesTableGeneric(props: FetchTracesTableProps) {
groupArrayIf(
concat(name, ':', string_value),
data_type = 'CATEGORICAL' AND notEmpty(string_value)
- ) AS score_categories
+ ) AS score_categories,
+ ${scoreBooleansAggregation()} AS score_booleans
FROM (
SELECT
project_id,
diff --git a/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts b/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts
index ef2d4e5e63..46074bb9e9 100644
--- a/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapDatasetRunItemsTable.ts
@@ -47,6 +47,12 @@ export const datasetRunItemsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "sa.score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "agg_score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "sa.score_booleans",
+ },
];
export const mapDatasetRunItemFilterColumn = (
diff --git a/packages/shared/src/server/tableMappings/mapEventsTable.ts b/packages/shared/src/server/tableMappings/mapEventsTable.ts
index b6e8c43e1f..13698b90a0 100644
--- a/packages/shared/src/server/tableMappings/mapEventsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapEventsTable.ts
@@ -337,6 +337,12 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "s.score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "s.score_booleans",
+ },
{
uiTableName: "Trace Scores (numeric)",
uiTableId: "trace_scores_avg",
@@ -349,6 +355,12 @@ export const eventsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "ts.score_categories",
},
+ {
+ uiTableName: "Trace Scores (boolean)",
+ uiTableId: "trace_score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "ts.score_booleans",
+ },
{
uiTableName: "Comment Count",
uiTableId: "commentCount",
diff --git a/packages/shared/src/server/tableMappings/mapExperimentItemsTable.ts b/packages/shared/src/server/tableMappings/mapExperimentItemsTable.ts
index 9bd849be73..aee0c02510 100644
--- a/packages/shared/src/server/tableMappings/mapExperimentItemsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapExperimentItemsTable.ts
@@ -13,6 +13,12 @@ export const experimentItemsTableNativeUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "s.score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "obs_score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "s.score_booleans",
+ },
{
uiTableName: "Trace Scores (numeric)",
uiTableId: "trace_scores_avg",
@@ -25,6 +31,12 @@ export const experimentItemsTableNativeUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "ts.score_categories",
},
+ {
+ uiTableName: "Trace Scores (boolean)",
+ uiTableId: "trace_score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "ts.score_booleans",
+ },
{
uiTableName: "Item Metadata",
uiTableId: "itemMetadata",
diff --git a/packages/shared/src/server/tableMappings/mapExperimentTable.ts b/packages/shared/src/server/tableMappings/mapExperimentTable.ts
index d07a041849..1ea89ce21d 100644
--- a/packages/shared/src/server/tableMappings/mapExperimentTable.ts
+++ b/packages/shared/src/server/tableMappings/mapExperimentTable.ts
@@ -69,6 +69,12 @@ export const experimentScoreAggCols: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "obs_score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "obs_score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "obs_score_booleans",
+ },
// Trace-level scores
{
uiTableName: "Trace Scores (numeric)",
@@ -82,6 +88,12 @@ export const experimentScoreAggCols: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "trace_score_categories",
},
+ {
+ uiTableName: "Trace Scores (boolean)",
+ uiTableId: "trace_score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "trace_score_booleans",
+ },
];
export const experimentOrderByCols: UiColumnMappings = [
diff --git a/packages/shared/src/server/tableMappings/mapObservationsTable.ts b/packages/shared/src/server/tableMappings/mapObservationsTable.ts
index 573f5b6421..88811063b3 100644
--- a/packages/shared/src/server/tableMappings/mapObservationsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapObservationsTable.ts
@@ -221,6 +221,12 @@ export const observationsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "s.score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "s.score_booleans",
+ },
{
uiTableName: "Version",
uiTableId: "version",
diff --git a/packages/shared/src/server/tableMappings/mapScoresColumnsTable.ts b/packages/shared/src/server/tableMappings/mapScoresColumnsTable.ts
index b0dbccfacc..1818e9912c 100644
--- a/packages/shared/src/server/tableMappings/mapScoresColumnsTable.ts
+++ b/packages/shared/src/server/tableMappings/mapScoresColumnsTable.ts
@@ -1,4 +1,5 @@
import { UiColumnMappings } from "../../tableDefinitions";
+import { SCORE_BOOLEAN_VALUE_SQL } from "./mapScoresTable";
export const scoresColumnsTableUiColumnDefinitions: UiColumnMappings = [
// scores native columns
@@ -20,6 +21,13 @@ export const scoresColumnsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: 's."dataset_run_id"',
},
+ {
+ uiTableName: "Boolean Value",
+ uiTableId: "booleanValue",
+ clickhouseTableName: "scores",
+ clickhouseSelect: SCORE_BOOLEAN_VALUE_SQL,
+ emptyEqualsNull: true,
+ },
{
uiTableName: "Observation ID",
uiTableId: "observationId",
diff --git a/packages/shared/src/server/tableMappings/mapScoresTable.ts b/packages/shared/src/server/tableMappings/mapScoresTable.ts
index 8e76d77e3b..3e81f5f15c 100644
--- a/packages/shared/src/server/tableMappings/mapScoresTable.ts
+++ b/packages/shared/src/server/tableMappings/mapScoresTable.ts
@@ -1,5 +1,11 @@
import { UiColumnMappings } from "../../tableDefinitions";
+// Lowercased boolean string_value ('true'/'false', '' for non-boolean rows) —
+// matches the lowercase options offered by the scores view's Boolean Value
+// facet. Shared with mapScoresColumnsTable so the two mappings cannot drift.
+export const SCORE_BOOLEAN_VALUE_SQL =
+ "if(s.data_type = 'BOOLEAN' AND notEmpty(s.string_value), lowerUTF8(s.string_value), '')";
+
export const scoresTableUiColumnDefinitions: UiColumnMappings = [
{
uiTableName: "ID",
@@ -57,6 +63,13 @@ export const scoresTableUiColumnDefinitions: UiColumnMappings = [
clickhouseSelect: "value",
queryPrefix: "s",
},
+ {
+ uiTableName: "Boolean Value",
+ uiTableId: "booleanValue",
+ clickhouseTableName: "scores",
+ clickhouseSelect: SCORE_BOOLEAN_VALUE_SQL,
+ emptyEqualsNull: true,
+ },
{
uiTableName: "Source",
uiTableId: "source",
diff --git a/packages/shared/src/server/tableMappings/mapSessionTable.ts b/packages/shared/src/server/tableMappings/mapSessionTable.ts
index a21a6901cf..63cfd476f9 100644
--- a/packages/shared/src/server/tableMappings/mapSessionTable.ts
+++ b/packages/shared/src/server/tableMappings/mapSessionTable.ts
@@ -150,4 +150,10 @@ export const sessionCols: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "score_booleans",
+ },
];
diff --git a/packages/shared/src/server/tableMappings/mapTracesTable.ts b/packages/shared/src/server/tableMappings/mapTracesTable.ts
index d3fe572fba..c4ffa228ce 100644
--- a/packages/shared/src/server/tableMappings/mapTracesTable.ts
+++ b/packages/shared/src/server/tableMappings/mapTracesTable.ts
@@ -187,6 +187,12 @@ export const tracesTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "scores",
clickhouseSelect: "s.score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "score_booleans",
+ clickhouseTableName: "scores",
+ clickhouseSelect: "s.score_booleans",
+ },
{
uiTableName: "Latency (s)",
uiTableId: "latency",
diff --git a/packages/shared/src/tableDefinitions/datasetRunItemsTable.ts b/packages/shared/src/tableDefinitions/datasetRunItemsTable.ts
index 01c6395016..3ef8802fea 100644
--- a/packages/shared/src/tableDefinitions/datasetRunItemsTable.ts
+++ b/packages/shared/src/tableDefinitions/datasetRunItemsTable.ts
@@ -17,11 +17,19 @@ export const datasetRunItemsTableCols: ColumnDefinition[] = [
options: [], // to be filled in at runtime
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "agg_score_booleans",
+ type: "booleanObject",
+ internal: "agg_score_booleans",
+ nullable: true,
+ },
];
export type DatasetRunItemsOptions = {
agg_scores_avg?: Array<string>;
agg_score_categories?: Array<MultiValueOption>;
+ agg_score_booleans?: Array<string>;
};
export function datasetRunItemsTableColsWithOptions(
@@ -35,6 +43,9 @@ export function datasetRunItemsTableColsWithOptions(
if (col.id === "agg_score_categories") {
return formatColumnOptions(col, options?.agg_score_categories ?? []);
}
+ if (col.id === "agg_score_booleans") {
+ return formatColumnOptions(col, options?.agg_score_booleans ?? []);
+ }
return col;
});
}
diff --git a/packages/shared/src/tableDefinitions/datasetRunsTable.ts b/packages/shared/src/tableDefinitions/datasetRunsTable.ts
index 924f7f08a9..6954fa74d8 100644
--- a/packages/shared/src/tableDefinitions/datasetRunsTable.ts
+++ b/packages/shared/src/tableDefinitions/datasetRunsTable.ts
@@ -20,6 +20,7 @@ type DatasetRunFilterColumnLiterals = ExtractLiterals<
const CLICKHOUSE_FILTER_COLUMNS: DatasetRunFilterColumnLiterals[] = [
"Scores (categorical)",
"Scores (numeric)",
+ "Scores (boolean)",
];
const CLICKHOUSE_FILTER_COLUMNS_SET = new Set(CLICKHOUSE_FILTER_COLUMNS);
@@ -52,11 +53,19 @@ export const datasetRunsTableCols: ColumnDefinition[] = [
options: [], // to be filled in at runtime
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "agg_score_booleans",
+ type: "booleanObject",
+ internal: "agg_score_booleans",
+ nullable: true,
+ },
];
export type DatasetRunsOptions = {
agg_scores_avg?: Array<string>;
agg_score_categories?: Array<MultiValueOption>;
+ agg_score_booleans?: Array<string>;
};
export function datasetRunsTableColsWithOptions(
@@ -70,6 +79,9 @@ export function datasetRunsTableColsWithOptions(
if (col.id === "agg_score_categories") {
return formatColumnOptions(col, options?.agg_score_categories ?? []);
}
+ if (col.id === "agg_score_booleans") {
+ return formatColumnOptions(col, options?.agg_score_booleans ?? []);
+ }
return col;
});
}
diff --git a/packages/shared/src/tableDefinitions/mapDatasetRunsTable.ts b/packages/shared/src/tableDefinitions/mapDatasetRunsTable.ts
index c043083394..418487e0f6 100644
--- a/packages/shared/src/tableDefinitions/mapDatasetRunsTable.ts
+++ b/packages/shared/src/tableDefinitions/mapDatasetRunsTable.ts
@@ -25,4 +25,10 @@ export const datasetRunsTableUiColumnDefinitions: UiColumnMappings = [
clickhouseTableName: "dataset_run_items_rmt",
clickhouseSelect: "sa.score_categories",
},
+ {
+ uiTableName: "Scores (boolean)",
+ uiTableId: "agg_score_booleans",
+ clickhouseTableName: "dataset_run_items_rmt",
+ clickhouseSelect: "sa.score_booleans",
+ },
];
diff --git a/packages/shared/src/tableDefinitions/scoresTable.ts b/packages/shared/src/tableDefinitions/scoresTable.ts
index 0a5bdc53ff..02d7341d41 100644
--- a/packages/shared/src/tableDefinitions/scoresTable.ts
+++ b/packages/shared/src/tableDefinitions/scoresTable.ts
@@ -63,6 +63,16 @@ export const scoresTableCols: ColumnDefinition[] = [
options: [],
},
{ name: "Value", id: "value", type: "number", internal: 's."value"' },
+ {
+ name: "Boolean Value",
+ id: "booleanValue",
+ type: "stringOptions",
+ // ClickHouse-only column: the SQL lives in the ClickHouse mappings
+ // (SCORE_BOOLEAN_VALUE_SQL in mapScoresTable) — `internal` is Postgres
+ // syntax and must not carry a ClickHouse expression.
+ internal: "",
+ options: [{ value: "true" }, { value: "false" }],
+ },
{
name: "String Value",
id: "stringValue",
diff --git a/packages/shared/src/tableDefinitions/sessionsView.ts b/packages/shared/src/tableDefinitions/sessionsView.ts
index 26ab0a913f..d815816c03 100644
--- a/packages/shared/src/tableDefinitions/sessionsView.ts
+++ b/packages/shared/src/tableDefinitions/sessionsView.ts
@@ -110,6 +110,13 @@ export const sessionsViewCols: ColumnDefinition[] = [
options: [], // to be added at runtime
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "score_booleans",
+ type: "booleanObject",
+ internal: "score_booleans",
+ nullable: true,
+ },
{
name: "Comment Count",
id: "commentCount",
@@ -130,6 +137,7 @@ export type SessionOptions = {
tags: Array<SingleValueOption>;
scores_avg?: Array<string>;
score_categories?: Array<MultiValueOption>;
+ score_booleans?: Array<string>;
};
export function sessionsTableColsWithOptions(
@@ -151,6 +159,9 @@ export function sessionsTableColsWithOptions(
if (col.id === "score_categories") {
return formatColumnOptions(col, options?.score_categories ?? []);
}
+ if (col.id === "score_booleans") {
+ return formatColumnOptions(col, options?.score_booleans ?? []);
+ }
return col;
});
}
diff --git a/packages/shared/src/tableDefinitions/tracesTable.ts b/packages/shared/src/tableDefinitions/tracesTable.ts
index dfe8c938fd..7278d70de9 100644
--- a/packages/shared/src/tableDefinitions/tracesTable.ts
+++ b/packages/shared/src/tableDefinitions/tracesTable.ts
@@ -159,6 +159,13 @@ export const tracesTableCols: ColumnDefinition[] = [
options: [], // to be filled in at runtime
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "score_booleans",
+ type: "booleanObject",
+ internal: "score_booleans",
+ nullable: true,
+ },
{
name: "Latency (s)",
id: "latency",
@@ -217,6 +224,7 @@ export const evalDatasetFormFilterCols: ColumnDefinition[] = datasetOnlyCols;
export type TraceOptions = {
scores_avg?: Array<string>;
score_categories?: Array<MultiValueOption>;
+ score_booleans?: Array<string>;
traceName?: Array<SingleValueOption>;
traceTags?: Array<SingleValueOption>;
environment?: Array<SingleValueOption>;
@@ -258,6 +266,9 @@ export function tracesTableColsWithOptions(
if (col.id === "score_categories") {
return formatColumnOptions(col, options?.score_categories ?? []);
}
+ if (col.id === "score_booleans") {
+ return formatColumnOptions(col, options?.score_booleans ?? []);
+ }
return col;
});
}
diff --git a/packages/shared/src/tableDefinitions/typeHelpers.ts b/packages/shared/src/tableDefinitions/typeHelpers.ts
index ad5e93ee84..8926d6e65a 100644
--- a/packages/shared/src/tableDefinitions/typeHelpers.ts
+++ b/packages/shared/src/tableDefinitions/typeHelpers.ts
@@ -7,12 +7,16 @@ export function formatColumnOptions<T extends ColumnDefinition>(
? MultiValueOption[]
: T extends { type: "stringOptions" | "arrayOptions" }
? SingleValueOption[]
- : T extends { type: "numberObject" | "stringObject" }
+ : T extends { type: "numberObject" | "stringObject" | "booleanObject" }
? string[]
: never,
): T {
- // For numberObject type, set keyOptions instead of options
- if (col.type === "numberObject" || col.type === "stringObject") {
+ // For keyed object filters, set keyOptions instead of options.
+ if (
+ col.type === "numberObject" ||
+ col.type === "stringObject" ||
+ col.type === "booleanObject"
+ ) {
return { ...col, keyOptions: newOptions };
}
diff --git a/packages/shared/src/tableDefinitions/types.ts b/packages/shared/src/tableDefinitions/types.ts
index 557fb3816c..d9387f4027 100644
--- a/packages/shared/src/tableDefinitions/types.ts
+++ b/packages/shared/src/tableDefinitions/types.ts
@@ -94,7 +94,7 @@ export type ColumnDefinition =
| {
name: string;
id: string;
- type: "stringObject" | "numberObject";
+ type: "stringObject" | "numberObject" | "booleanObject";
internal: string;
keyOptions?: Array<string>;
nullable?: boolean;
diff --git a/web/src/__tests__/server/dataset-service.servertest.ts b/web/src/__tests__/server/dataset-service.servertest.ts
index a64fd3c4dd..a9a055a370 100644
--- a/web/src/__tests__/server/dataset-service.servertest.ts
+++ b/web/src/__tests__/server/dataset-service.servertest.ts
@@ -710,6 +710,119 @@ describe("Fetch datasets for UI presentation", () => {
expect(precisionRuns[0].id).toEqual(highScoreRunId);
});
+ it("should filter dataset run items by boolean scores", async () => {
+ const datasetId = v4();
+ const scoreName = `passes_guardrail_${v4()}`;
+
+ await prisma.dataset.create({
+ data: {
+ id: datasetId,
+ name: v4(),
+ projectId: projectId,
+ },
+ });
+
+ const runId = v4();
+ await prisma.datasetRuns.create({
+ data: {
+ id: runId,
+ name: "boolean-score-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ });
+
+ // Three items: one trace scored True, one scored False, one unscored
+ const itemIdWithTrueScore = v4();
+ const itemIdWithFalseScore = v4();
+ const itemIdWithoutScore = v4();
+
+ await createManyDatasetItems({
+ projectId,
+ items: [
+ { id: itemIdWithTrueScore, datasetId, metadata: {} },
+ { id: itemIdWithFalseScore, datasetId, metadata: {} },
+ { id: itemIdWithoutScore, datasetId, metadata: {} },
+ ],
+ });
+
+ const traceIdWithTrueScore = v4();
+ const traceIdWithFalseScore = v4();
+ const traceIdWithoutScore = v4();
+
+ await createDatasetRunItemsCh([
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: runId,
+ trace_id: traceIdWithTrueScore,
+ project_id: projectId,
+ dataset_item_id: itemIdWithTrueScore,
+ dataset_id: datasetId,
+ dataset_run_name: "boolean-score-run",
+ }),
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: runId,
+ trace_id: traceIdWithFalseScore,
+ project_id: projectId,
+ dataset_item_id: itemIdWithFalseScore,
+ dataset_id: datasetId,
+ dataset_run_name: "boolean-score-run",
+ }),
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: runId,
+ trace_id: traceIdWithoutScore,
+ project_id: projectId,
+ dataset_item_id: itemIdWithoutScore,
+ dataset_id: datasetId,
+ dataset_run_name: "boolean-score-run",
+ }),
+ ]);
+
+ await createScoresCh([
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIdWithTrueScore,
+ project_id: projectId,
+ name: scoreName,
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIdWithFalseScore,
+ project_id: projectId,
+ name: scoreName,
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const runItems = await getDatasetRunItemsByDatasetIdCh({
+ projectId,
+ datasetId,
+ filter: [
+ {
+ type: "booleanObject" as const,
+ column: "agg_score_booleans",
+ key: scoreName,
+ operator: "=" as const,
+ value: true,
+ },
+ ],
+ limit: 10,
+ offset: 0,
+ });
+
+ expect(runItems).toHaveLength(1);
+ expect(runItems[0].traceId).toEqual(traceIdWithTrueScore);
+ expect(runItems[0].datasetItemId).toEqual(itemIdWithTrueScore);
+ });
+
it("should filter dataset runs by categorical scores", async () => {
const datasetId = v4();
@@ -930,6 +1043,105 @@ describe("Fetch datasets for UI presentation", () => {
expect(positiveSentimentRuns[0].id).toEqual(excellentRunId);
});
+ it("should filter dataset runs by boolean scores", async () => {
+ const datasetId = v4();
+
+ await prisma.dataset.create({
+ data: {
+ id: datasetId,
+ name: v4(),
+ projectId: projectId,
+ },
+ });
+
+ const passingRunId = v4();
+ const failingRunId = v4();
+ await prisma.datasetRuns.createMany({
+ data: [
+ {
+ id: passingRunId,
+ name: "passing-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ {
+ id: failingRunId,
+ name: "failing-run",
+ datasetId,
+ metadata: {},
+ projectId,
+ },
+ ],
+ });
+
+ const itemIds = [v4(), v4()];
+ const traceIds = [v4(), v4()];
+ await createManyDatasetItems({
+ projectId,
+ items: itemIds.map((id) => ({ id, datasetId, metadata: {} })),
+ });
+ await createDatasetRunItemsCh([
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: passingRunId,
+ trace_id: traceIds[0],
+ project_id: projectId,
+ dataset_item_id: itemIds[0],
+ dataset_id: datasetId,
+ dataset_run_name: "passing-run",
+ }),
+ createDatasetRunItem({
+ id: v4(),
+ dataset_run_id: failingRunId,
+ trace_id: traceIds[1],
+ project_id: projectId,
+ dataset_item_id: itemIds[1],
+ dataset_id: datasetId,
+ dataset_run_name: "failing-run",
+ }),
+ ]);
+
+ await createScoresCh([
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[0],
+ project_id: projectId,
+ name: "passes_guardrail",
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createTraceScore({
+ id: v4(),
+ trace_id: traceIds[1],
+ project_id: projectId,
+ name: "passes_guardrail",
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const passingRuns = await getDatasetRunsTableMetricsCh({
+ projectId: projectId,
+ datasetId: datasetId,
+ runIds: [passingRunId, failingRunId],
+ filter: [
+ {
+ type: "booleanObject" as const,
+ column: "agg_score_booleans",
+ key: "passes_guardrail",
+ operator: "=" as const,
+ value: true,
+ },
+ ],
+ });
+
+ expect(passingRuns).toHaveLength(1);
+ expect(passingRuns[0].id).toEqual(passingRunId);
+ });
+
it("should combine score filters with other filters", async () => {
const datasetId = v4();
diff --git a/web/src/__tests__/server/observations-trpc.servertest.ts b/web/src/__tests__/server/observations-trpc.servertest.ts
index 0f68ef49d8..e065dbee09 100644
--- a/web/src/__tests__/server/observations-trpc.servertest.ts
+++ b/web/src/__tests__/server/observations-trpc.servertest.ts
@@ -123,6 +123,78 @@ describe("traces trpc", () => {
expect(generations.generations).toBeDefined();
});
+ it("should filter generations by boolean scores", async () => {
+ const traceId = randomUUID();
+ const matchingGenerationId = randomUUID();
+ const otherGenerationId = randomUUID();
+ const scoreName = `passes_guardrail_${randomUUID()}`;
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: projectId,
+ name: "boolean-score-generation-trace",
+ });
+ const matchingGeneration = createObservation({
+ id: matchingGenerationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "boolean-score-generation-match",
+ });
+ const otherGeneration = createObservation({
+ id: otherGenerationId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "boolean-score-generation-other",
+ });
+
+ await createTracesCh([trace]);
+ await createObservationsCh([matchingGeneration, otherGeneration]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: matchingGenerationId,
+ name: scoreName,
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceId,
+ observation_id: otherGenerationId,
+ name: scoreName,
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const generations = await caller.generations.all({
+ projectId,
+ searchQuery: "",
+ searchType: [],
+ filter: [
+ {
+ column: "score_booleans",
+ key: scoreName,
+ operator: "=",
+ value: true,
+ type: "booleanObject",
+ },
+ ],
+ orderBy: null,
+ limit: 50,
+ page: 0,
+ });
+
+ expect(generations.generations.map((g) => g.id)).toEqual([
+ matchingGenerationId,
+ ]);
+ });
+
it("should search generations by input only", async () => {
const traceId = randomUUID();
const generationId = randomUUID();
diff --git a/web/src/__tests__/server/repositories/event-repository.servertest.ts b/web/src/__tests__/server/repositories/event-repository.servertest.ts
index 1282408eae..d7aab13067 100644
--- a/web/src/__tests__/server/repositories/event-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/event-repository.servertest.ts
@@ -592,6 +592,169 @@ describe("Clickhouse Events Repository Test", () => {
expect(count).toBeGreaterThanOrEqual(0);
});
+ it("filters observations by observation-level boolean scores", async () => {
+ const uniqueProjectId = randomUUID();
+ const traceId = randomUUID();
+ const matchingSpanId = randomUUID();
+ const otherSpanId = randomUUID();
+ const now = Date.now();
+
+ await createEventsCh([
+ createEvent({
+ id: matchingSpanId,
+ span_id: matchingSpanId,
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "boolean-score-match",
+ start_time: now * 1000,
+ }),
+ createEvent({
+ id: otherSpanId,
+ span_id: otherSpanId,
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "boolean-score-other",
+ start_time: now * 1000,
+ }),
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ observation_id: matchingSpanId,
+ name: "is_hallucination",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ timestamp: now,
+ event_ts: now,
+ created_at: now,
+ updated_at: now,
+ }),
+ createTraceScore({
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ observation_id: otherSpanId,
+ name: "is_hallucination",
+ data_type: "BOOLEAN",
+ value: 0,
+ string_value: "False",
+ timestamp: now,
+ event_ts: now,
+ created_at: now,
+ updated_at: now,
+ }),
+ ]);
+
+ const booleanFilter: FilterCondition = {
+ type: "booleanObject",
+ column: "score_booleans",
+ operator: "=",
+ key: "is_hallucination",
+ value: true,
+ };
+
+ await waitForExpect(async () => {
+ const observations = await getObservationsWithModelDataFromEventsTable({
+ projectId: uniqueProjectId,
+ filter: [booleanFilter],
+ limit: 100,
+ offset: 0,
+ });
+ const count = await getObservationsCountFromEventsTable({
+ projectId: uniqueProjectId,
+ filter: [booleanFilter],
+ });
+
+ expect(count).toBe(1);
+ expect(observations.map((o) => o.id)).toEqual([matchingSpanId]);
+ });
+ });
+
+ it("filters observations by trace-level boolean scores", async () => {
+ const uniqueProjectId = randomUUID();
+ const matchingTraceId = randomUUID();
+ const otherTraceId = randomUUID();
+ const matchingSpanId = randomUUID();
+ const otherSpanId = randomUUID();
+ const now = Date.now();
+
+ await createEventsCh([
+ createEvent({
+ id: matchingSpanId,
+ span_id: matchingSpanId,
+ project_id: uniqueProjectId,
+ trace_id: matchingTraceId,
+ type: "SPAN",
+ name: "trace-boolean-score-match",
+ start_time: now * 1000,
+ }),
+ createEvent({
+ id: otherSpanId,
+ span_id: otherSpanId,
+ project_id: uniqueProjectId,
+ trace_id: otherTraceId,
+ type: "SPAN",
+ name: "trace-boolean-score-other",
+ start_time: now * 1000,
+ }),
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: uniqueProjectId,
+ trace_id: matchingTraceId,
+ observation_id: null,
+ name: "passes_guardrail",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ timestamp: now,
+ event_ts: now,
+ created_at: now,
+ updated_at: now,
+ }),
+ createTraceScore({
+ project_id: uniqueProjectId,
+ trace_id: otherTraceId,
+ observation_id: null,
+ name: "passes_guardrail",
+ data_type: "BOOLEAN",
+ value: 0,
+ string_value: "False",
+ timestamp: now,
+ event_ts: now,
+ created_at: now,
+ updated_at: now,
+ }),
+ ]);
+
+ const booleanFilter: FilterCondition = {
+ type: "booleanObject",
+ column: "trace_score_booleans",
+ operator: "=",
+ key: "passes_guardrail",
+ value: true,
+ };
+
+ await waitForExpect(async () => {
+ const observations = await getObservationsWithModelDataFromEventsTable({
+ projectId: uniqueProjectId,
+ filter: [booleanFilter],
+ limit: 100,
+ offset: 0,
+ });
+ const count = await getObservationsCountFromEventsTable({
+ projectId: uniqueProjectId,
+ filter: [booleanFilter],
+ });
+
+ expect(count).toBe(1);
+ expect(observations.map((o) => o.id)).toEqual([matchingSpanId]);
+ });
+ });
+
it("should not throw when searchQuery is provided without filters", async () => {
const uniqueProjectId = randomUUID();
const traceId = randomUUID();
@@ -747,6 +910,18 @@ describe("Clickhouse Events Repository Test", () => {
created_at: now,
updated_at: now,
}),
+ createTraceScore({
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ name: "unrequested-filter-option-boolean",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ timestamp: now,
+ event_ts: now,
+ created_at: now,
+ updated_at: now,
+ }),
]);
await waitForExpect(async () => {
@@ -762,8 +937,74 @@ describe("Clickhouse Events Repository Test", () => {
expect(options.traceTags).toBeUndefined();
expect(options.scores_avg).toBeUndefined();
expect(options.score_categories).toBeUndefined();
+ expect(options.score_booleans).toBeUndefined();
expect(options.trace_scores_avg).toBeUndefined();
expect(options.trace_score_categories).toBeUndefined();
+ expect(options.trace_score_booleans).toBeUndefined();
+ });
+ });
+
+ it("loads requested boolean score filter option columns", async () => {
+ const uniqueProjectId = randomUUID();
+ const traceId = randomUUID();
+ const spanId = randomUUID();
+ const now = Date.now();
+
+ await createEventsCh([
+ createEvent({
+ id: spanId,
+ span_id: spanId,
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ type: "SPAN",
+ name: "requested-boolean-filter-option",
+ start_time: now * 1000,
+ }),
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ observation_id: spanId,
+ name: "requested-observation-boolean",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ timestamp: now,
+ event_ts: now,
+ created_at: now,
+ updated_at: now,
+ }),
+ createTraceScore({
+ project_id: uniqueProjectId,
+ trace_id: traceId,
+ observation_id: null,
+ name: "requested-trace-boolean",
+ data_type: "BOOLEAN",
+ value: 0,
+ string_value: "False",
+ timestamp: now,
+ event_ts: now,
+ created_at: now,
+ updated_at: now,
+ }),
+ ]);
+
+ await waitForExpect(async () => {
+ const options = await getEventFilterOptions({
+ projectId: uniqueProjectId,
+ columns: ["score_booleans", "trace_score_booleans"],
+ });
+
+ expect(options.score_booleans).toContain(
+ "requested-observation-boolean",
+ );
+ expect(options.trace_score_booleans).toContain(
+ "requested-trace-boolean",
+ );
+ expect(options.trace_score_booleans).not.toContain(
+ "requested-observation-boolean",
+ );
});
});
diff --git a/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts b/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts
index 3dd958b90e..29327489f7 100644
--- a/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/experiment-items-repository.servertest.ts
@@ -213,6 +213,168 @@ describe("Clickhouse Experiment Items Repository Test", () => {
expect(result[0].itemId).toBe(item1Id);
});
+ it("should filter items by trace-level boolean scores", async () => {
+ const baselineExpId = randomUUID();
+ const datasetId = randomUUID();
+ const item1Id = randomUUID();
+ const item2Id = randomUUID();
+ const item1TraceId = randomUUID();
+ const item2TraceId = randomUUID();
+ const item1RootId = randomUUID();
+ const item2RootId = randomUUID();
+
+ await createEventsCh([
+ createExperimentEvent({
+ project_id: projectId,
+ trace_id: item1TraceId,
+ span_id: item1RootId,
+ experimentId: baselineExpId,
+ experimentName: "baseline-exp",
+ datasetId,
+ itemId: item1Id,
+ experimentItemRootSpanId: item1RootId,
+ start_time: Date.now() * 1000,
+ }),
+ createExperimentEvent({
+ project_id: projectId,
+ trace_id: item2TraceId,
+ span_id: item2RootId,
+ experimentId: baselineExpId,
+ experimentName: "baseline-exp",
+ datasetId,
+ itemId: item2Id,
+ experimentItemRootSpanId: item2RootId,
+ start_time: Date.now() * 1000,
+ }),
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: item1TraceId,
+ observation_id: null,
+ name: "passes_guardrail",
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: item2TraceId,
+ observation_id: null,
+ name: "passes_guardrail",
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const result = await getExperimentItemsFromEvents({
+ projectId,
+ baseExperimentId: baselineExpId,
+ compExperimentIds: [],
+ filterByExperiment: [
+ {
+ experimentId: baselineExpId,
+ filters: [
+ {
+ column: "trace_score_booleans",
+ type: "booleanObject",
+ key: "passes_guardrail",
+ operator: "=",
+ value: true,
+ } as FilterCondition,
+ ],
+ },
+ ],
+ limit: 10,
+ offset: 0,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].itemId).toBe(item1Id);
+ });
+
+ it("should filter items by root observation boolean scores", async () => {
+ const baselineExpId = randomUUID();
+ const datasetId = randomUUID();
+ const item1Id = randomUUID();
+ const item2Id = randomUUID();
+ const item1TraceId = randomUUID();
+ const item2TraceId = randomUUID();
+ const item1RootId = randomUUID();
+ const item2RootId = randomUUID();
+
+ await createEventsCh([
+ createExperimentEvent({
+ project_id: projectId,
+ trace_id: item1TraceId,
+ span_id: item1RootId,
+ experimentId: baselineExpId,
+ experimentName: "baseline-exp",
+ datasetId,
+ itemId: item1Id,
+ experimentItemRootSpanId: item1RootId,
+ start_time: Date.now() * 1000,
+ }),
+ createExperimentEvent({
+ project_id: projectId,
+ trace_id: item2TraceId,
+ span_id: item2RootId,
+ experimentId: baselineExpId,
+ experimentName: "baseline-exp",
+ datasetId,
+ itemId: item2Id,
+ experimentItemRootSpanId: item2RootId,
+ start_time: Date.now() * 1000,
+ }),
+ ]);
+ await createScoresCh([
+ createRootObservationScore({
+ projectId,
+ traceId: item1TraceId,
+ rootObservationId: item1RootId,
+ scoreName: "root_passes_guardrail",
+ value: 1,
+ stringValue: "True",
+ dataType: "BOOLEAN",
+ }),
+ createRootObservationScore({
+ projectId,
+ traceId: item2TraceId,
+ rootObservationId: item2RootId,
+ scoreName: "root_passes_guardrail",
+ value: 0,
+ stringValue: "False",
+ dataType: "BOOLEAN",
+ }),
+ ]);
+
+ const result = await getExperimentItemsFromEvents({
+ projectId,
+ baseExperimentId: baselineExpId,
+ compExperimentIds: [],
+ filterByExperiment: [
+ {
+ experimentId: baselineExpId,
+ filters: [
+ {
+ column: "obs_score_booleans",
+ type: "booleanObject",
+ key: "root_passes_guardrail",
+ operator: "=",
+ value: true,
+ } as FilterCondition,
+ ],
+ },
+ ],
+ limit: 10,
+ offset: 0,
+ });
+
+ expect(result).toHaveLength(1);
+ expect(result[0].itemId).toBe(item1Id);
+ });
+
it("should NOT include non-root observation scores in filtering", async () => {
// GIVEN: Item with child observation score (not root)
const baselineExpId = randomUUID();
diff --git a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts b/web/src/__tests__/server/repositories/experiment-repository.servertest.ts
index f0725ecad3..3e64dc48bb 100644
--- a/web/src/__tests__/server/repositories/experiment-repository.servertest.ts
+++ b/web/src/__tests__/server/repositories/experiment-repository.servertest.ts
@@ -778,6 +778,88 @@ describe("Clickhouse Experiment Repository Test", () => {
expect(excludedExperiment).toBeUndefined(); // avg = 0.5 < 0.6
});
+ it("should filter experiments by boolean trace scores", async () => {
+ const experimentIdWithTrueScore = randomUUID();
+ const experimentIdWithFalseScore = randomUUID();
+ const experimentIdWithoutScore = randomUUID();
+ const datasetId = randomUUID();
+ const scoreName = `passes_guardrail_${randomUUID()}`;
+
+ const now = new Date().getTime();
+
+ const traceIdWithTrueScore = randomUUID();
+ const traceIdWithFalseScore = randomUUID();
+ const traceIdWithoutScore = randomUUID();
+
+ const makeExperimentEvent = (experimentId: string, traceId: string) => {
+ const rootSpanId = randomUUID();
+ return createEvent({
+ id: randomUUID(),
+ span_id: rootSpanId,
+ project_id: projectId,
+ trace_id: traceId,
+ type: "GENERATION",
+ name: "test-generation",
+ experiment_id: experimentId,
+ experiment_name: `boolean-score-filter-${experimentId}`,
+ experiment_metadata_names: [],
+ experiment_metadata_values: [],
+ experiment_dataset_id: datasetId,
+ experiment_item_id: randomUUID(),
+ experiment_item_version: null,
+ experiment_item_root_span_id: rootSpanId,
+ start_time: now * 1000,
+ });
+ };
+
+ await createEventsCh([
+ makeExperimentEvent(experimentIdWithTrueScore, traceIdWithTrueScore),
+ makeExperimentEvent(experimentIdWithFalseScore, traceIdWithFalseScore),
+ makeExperimentEvent(experimentIdWithoutScore, traceIdWithoutScore),
+ ]);
+
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceIdWithTrueScore,
+ observation_id: null,
+ name: scoreName,
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceIdWithFalseScore,
+ observation_id: null,
+ name: scoreName,
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const result = await getExperimentsFromEvents({
+ projectId,
+ filter: [
+ {
+ column: "trace_score_booleans",
+ type: "booleanObject",
+ key: scoreName,
+ operator: "=",
+ value: true,
+ },
+ ],
+ limit: 1000,
+ page: 0,
+ });
+
+ const resultIds = result.map((e) => e.id);
+ expect(resultIds).toContain(experimentIdWithTrueScore);
+ expect(resultIds).not.toContain(experimentIdWithFalseScore);
+ expect(resultIds).not.toContain(experimentIdWithoutScore);
+ });
+
it("should filter experiments by name with equals operator", async () => {
const experimentId1 = randomUUID();
const experimentName1 = "exact-match-name-" + randomUUID();
@@ -1162,9 +1244,11 @@ describe("Clickhouse Experiment Repository Test", () => {
expect(result).toEqual({
obs_scores_avg: [],
obs_score_categories: [],
+ obs_score_booleans: [],
obs_score_columns: [],
trace_scores_avg: [],
trace_score_categories: [],
+ trace_score_booleans: [],
trace_score_columns: [],
});
});
@@ -1178,9 +1262,11 @@ describe("Clickhouse Experiment Repository Test", () => {
expect(result).toEqual({
obs_scores_avg: [],
obs_score_categories: [],
+ obs_score_booleans: [],
obs_score_columns: [],
trace_scores_avg: [],
trace_score_categories: [],
+ trace_score_booleans: [],
trace_score_columns: [],
});
});
diff --git a/web/src/__tests__/server/scores-trpc.servertest.ts b/web/src/__tests__/server/scores-trpc.servertest.ts
index 8048cb4450..e8175acf74 100644
--- a/web/src/__tests__/server/scores-trpc.servertest.ts
+++ b/web/src/__tests__/server/scores-trpc.servertest.ts
@@ -1,5 +1,16 @@
-const mockAddScoreDelete = vi.fn();
-const mockAddBatchAction = vi.fn();
+const {
+ mockAddScoreDelete,
+ mockAddBatchAction,
+ mockGetEventsGroupedByTraceTags,
+ mockGetEventsGroupedByTraceName,
+ mockGetEventsGroupedByUserId,
+} = vi.hoisted(() => ({
+ mockAddScoreDelete: vi.fn(),
+ mockAddBatchAction: vi.fn(),
+ mockGetEventsGroupedByTraceTags: vi.fn(async () => []),
+ mockGetEventsGroupedByTraceName: vi.fn(async () => []),
+ mockGetEventsGroupedByUserId: vi.fn(async () => []),
+}));
vi.mock("@langfuse/shared/src/server", async () => {
const originalModule = await vi.importActual("@langfuse/shared/src/server");
@@ -15,6 +26,9 @@ vi.mock("@langfuse/shared/src/server", async () => {
add: mockAddBatchAction,
})),
},
+ getEventsGroupedByTraceTags: mockGetEventsGroupedByTraceTags,
+ getEventsGroupedByTraceName: mockGetEventsGroupedByTraceName,
+ getEventsGroupedByUserId: mockGetEventsGroupedByUserId,
};
});
@@ -48,6 +62,9 @@ describe("scores trpc", () => {
orgId = setup.orgId;
mockAddScoreDelete.mockClear();
mockAddBatchAction.mockClear();
+ mockGetEventsGroupedByTraceTags.mockClear();
+ mockGetEventsGroupedByTraceName.mockClear();
+ mockGetEventsGroupedByUserId.mockClear();
const session: Session = {
expires: "1",
@@ -86,6 +103,129 @@ describe("scores trpc", () => {
caller = appRouter.createCaller({ ...ctx, prisma });
});
+ describe("scores.all", () => {
+ it("does not match empty boolean representations when filtering boolean values", async () => {
+ const trueBooleanScore = createTraceScore({
+ project_id: projectId,
+ name: "boolean-score-true",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ });
+ const falseBooleanScore = createTraceScore({
+ project_id: projectId,
+ name: "boolean-score-false",
+ data_type: "BOOLEAN",
+ value: 0,
+ string_value: "False",
+ });
+ const emptyBooleanScore = createTraceScore({
+ project_id: projectId,
+ name: "boolean-score-empty",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "",
+ });
+ const numericScore = createTraceScore({
+ project_id: projectId,
+ name: "numeric-score",
+ data_type: "NUMERIC",
+ value: 0.7,
+ string_value: null,
+ });
+
+ await createScoresCh([
+ trueBooleanScore,
+ falseBooleanScore,
+ emptyBooleanScore,
+ numericScore,
+ ]);
+
+ const payload = {
+ projectId,
+ filter: [
+ {
+ column: "booleanValue",
+ type: "stringOptions",
+ operator: "none of",
+ value: ["false"],
+ },
+ ],
+ orderBy: { column: "timestamp", order: "DESC" },
+ page: 0,
+ limit: 50,
+ } as const;
+
+ const result = await caller.scores.all(payload);
+ const resultFromEvents = await caller.scores.allFromEvents(payload);
+
+ expect(result.scores.map((score) => score.id)).toEqual([
+ trueBooleanScore.id,
+ ]);
+ expect(resultFromEvents.scores.map((score) => score.id)).toEqual([
+ trueBooleanScore.id,
+ ]);
+ });
+ });
+
+ describe("scores.createAnnotationScore", () => {
+ it("rejects empty stringValue for boolean annotation scores", async () => {
+ const configId = randomUUID();
+ const scoreName = `boolean-annotation-score-${configId.slice(0, 8)}`;
+
+ await expect(
+ caller.scores.createAnnotationScore({
+ projectId,
+ name: scoreName,
+ value: 1,
+ stringValue: "",
+ dataType: "BOOLEAN",
+ scoreTarget: { type: "trace", traceId: randomUUID() },
+ configId,
+ environment: "default",
+ } as any),
+ ).rejects.toThrow();
+ });
+
+ it("accepts explicit boolean annotation stringValue labels", async () => {
+ const traceId = randomUUID();
+ const configId = randomUUID();
+ const scoreName = `boolean-annotation-score-${configId.slice(0, 8)}`;
+
+ await createTracesCh([
+ createTrace({
+ id: traceId,
+ project_id: projectId,
+ }),
+ ]);
+ await prisma.scoreConfig.create({
+ data: {
+ id: configId,
+ projectId,
+ name: scoreName,
+ dataType: ScoreConfigDataType.BOOLEAN,
+ categories: [
+ { label: "True", value: 1 },
+ { label: "False", value: 0 },
+ ],
+ },
+ });
+
+ const score = await caller.scores.createAnnotationScore({
+ projectId,
+ name: scoreName,
+ value: 1,
+ stringValue: "True",
+ dataType: "BOOLEAN",
+ scoreTarget: { type: "trace", traceId },
+ configId,
+ environment: "default",
+ });
+
+ expect(score.stringValue).toBe("True");
+ });
+ });
+
describe("scores.deleteMany", () => {
it("should delete scores by ids", async () => {
// Setup
@@ -259,6 +399,22 @@ describe("scores trpc", () => {
});
});
+ describe("scores.filterOptions", () => {
+ it("returns static boolean value options for both scores views", async () => {
+ await expect(
+ caller.scores.filterOptions({ projectId }),
+ ).resolves.toMatchObject({
+ booleanValue: [{ value: "true" }, { value: "false" }],
+ });
+
+ await expect(
+ caller.scores.filterOptionsFromEvents({ projectId }),
+ ).resolves.toMatchObject({
+ booleanValue: [{ value: "true" }, { value: "false" }],
+ });
+ });
+ });
+
describe("scoreConfigs.all", () => {
it("should paginate score configs deterministically when createdAt timestamps tie", async () => {
const sharedCreatedAt = new Date("2100-05-12T00:00:00.000Z");
diff --git a/web/src/__tests__/server/sessions-ui-table.servertest.ts b/web/src/__tests__/server/sessions-ui-table.servertest.ts
index 0365526a9f..6f6ae1d3a5 100644
--- a/web/src/__tests__/server/sessions-ui-table.servertest.ts
+++ b/web/src/__tests__/server/sessions-ui-table.servertest.ts
@@ -628,6 +628,65 @@ describe("trpc.sessions", () => {
expect(tableRows).toHaveLength(1);
expect(tableRows[0].session_id).toEqual(session_id_with_score);
});
+
+ it("should GET correct session data with boolean score filters", async () => {
+ const project_id = v4();
+ const trace_id_with_score = v4();
+ const session_id_with_score = v4();
+ const trace_id_without_score = v4();
+ const session_id_without_score = v4();
+
+ const filterState: FilterState = [
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "passes_guardrail",
+ operator: "=",
+ value: true,
+ },
+ ];
+
+ const trace_with_score = createTrace({
+ id: trace_id_with_score,
+ project_id,
+ session_id: session_id_with_score,
+ });
+ const trace_without_score = createTrace({
+ id: trace_id_without_score,
+ project_id,
+ session_id: session_id_without_score,
+ });
+ await seedSessionData([trace_with_score, trace_without_score]);
+
+ await createScoresCh([
+ createSessionScore({
+ project_id,
+ session_id: session_id_with_score,
+ name: "passes_guardrail",
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createSessionScore({
+ project_id,
+ session_id: session_id_without_score,
+ name: "passes_guardrail",
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const tableRows = await sessionsTable({
+ projectId: project_id,
+ filter: filterState,
+ limit: 10,
+ page: 0,
+ });
+
+ expect(tableRows).toHaveLength(1);
+ expect(tableRows[0].session_id).toEqual(session_id_with_score);
+ });
});
// The events tables only exist where the v4 preview is enabled (CI creates
@@ -712,6 +771,76 @@ maybeEventsTable("parity: sessions metrics from events vs legacy", () => {
);
});
+ it("should GET correct session data with boolean score filters from events", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+ const sessionIdWithTrueScore = v4();
+ const sessionIdWithFalseScore = v4();
+ const sessionIdWithoutScore = v4();
+
+ await prisma.traceSession.createMany({
+ data: [
+ { id: sessionIdWithTrueScore, projectId },
+ { id: sessionIdWithFalseScore, projectId },
+ { id: sessionIdWithoutScore, projectId },
+ ],
+ });
+
+ const traces = [
+ createTrace({
+ session_id: sessionIdWithTrueScore,
+ project_id: projectId,
+ }),
+ createTrace({
+ session_id: sessionIdWithFalseScore,
+ project_id: projectId,
+ }),
+ createTrace({ session_id: sessionIdWithoutScore, project_id: projectId }),
+ ];
+
+ await createTracesCh(traces);
+ await createEventsCh(buildMatchingEvents(traces, []));
+
+ await createScoresCh([
+ createSessionScore({
+ project_id: projectId,
+ session_id: sessionIdWithTrueScore,
+ name: "passes_guardrail",
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createSessionScore({
+ project_id: projectId,
+ session_id: sessionIdWithFalseScore,
+ name: "passes_guardrail",
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const filterState: FilterState = [
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "passes_guardrail",
+ operator: "=",
+ value: true,
+ },
+ ];
+
+ const tableRows = await getSessionsTableFromEvents({
+ projectId,
+ filter: filterState,
+ orderBy: null,
+ limit: 10,
+ page: 0,
+ });
+
+ expect(tableRows).toHaveLength(1);
+ expect(tableRows[0].session_id).toEqual(sessionIdWithTrueScore);
+ });
+
it("honours the same filter so only the targeted session is returned", async () => {
const { projectId } = await createOrgProjectAndApiKey();
const targetId = v4();
diff --git a/web/src/__tests__/server/traces-api.servertest.ts b/web/src/__tests__/server/traces-api.servertest.ts
index e88129a379..2e25310a02 100644
--- a/web/src/__tests__/server/traces-api.servertest.ts
+++ b/web/src/__tests__/server/traces-api.servertest.ts
@@ -2010,6 +2010,82 @@ describe("/api/public/traces API Endpoint", () => {
expect(traces.body.data.map((d) => d.id)).toEqual([traceWithScore1]);
expect(traces.body.meta.totalItems).toBe(1);
});
+
+ it("should filter by score_booleans without requesting scores field group", async () => {
+ const baseTimestamp = Date.now();
+ const traceWithTrueScore = randomUUID();
+ const traceWithFalseScore = randomUUID();
+
+ const trace1 = createTrace({
+ id: traceWithTrueScore,
+ name: "trace-boolean-score-true",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ });
+ const trace2 = createTrace({
+ id: traceWithFalseScore,
+ name: "trace-boolean-score-false",
+ project_id: projectId,
+ timestamp: baseTimestamp,
+ });
+
+ await Promise.all([
+ createTraceWithObservations(useEventsTable, trace1, []),
+ createTraceWithObservations(useEventsTable, trace2, []),
+ createScoresCh([
+ createTraceScore({
+ trace_id: traceWithTrueScore,
+ project_id: projectId,
+ name: "is_hallucination",
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ timestamp: baseTimestamp,
+ observation_id: null,
+ }),
+ createTraceScore({
+ trace_id: traceWithFalseScore,
+ project_id: projectId,
+ name: "is_hallucination",
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ timestamp: baseTimestamp,
+ observation_id: null,
+ }),
+ ]),
+ ]);
+
+ const filterParam = JSON.stringify([
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "is_hallucination",
+ operator: "=",
+ value: true,
+ },
+ {
+ type: "stringOptions",
+ column: "id",
+ operator: "any of",
+ value: [traceWithTrueScore, traceWithFalseScore],
+ },
+ ]);
+
+ const traces = await makeZodVerifiedAPICall(
+ GetTracesV1Response,
+ "GET",
+ buildUrl(`fields=core&filter=${encodeURIComponent(filterParam)}`),
+ undefined,
+ auth,
+ );
+
+ expect(traces.status).toBe(200);
+ expect(traces.body.data.map((d) => d.id)).toEqual([
+ traceWithTrueScore,
+ ]);
+ expect(traces.body.meta.totalItems).toBe(1);
+ });
});
};
diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.ts
index 4a246cff5b..a2bfae364b 100644
--- a/web/src/__tests__/server/traces-trpc.servertest.ts
+++ b/web/src/__tests__/server/traces-trpc.servertest.ts
@@ -6,6 +6,7 @@ import {
createTrace,
createTracesCh,
createTraceScore,
+ createSessionScore,
createScoresCh,
getTraceByIdFromTracesTable,
createEventsCh,
@@ -266,6 +267,114 @@ describe("traces trpc", () => {
expect(traces.traces.length).toBe(0);
});
+ it("should filter traces by boolean score with = and <> operators", async () => {
+ const scoreName = `bool_score_${randomUUID()}`;
+
+ const traceWithTrueScore = createTrace({ project_id: projectId });
+ const traceWithFalseScore = createTrace({ project_id: projectId });
+ const traceWithoutScore = createTrace({ project_id: projectId });
+ const traceIds = [
+ traceWithTrueScore.id,
+ traceWithFalseScore.id,
+ traceWithoutScore.id,
+ ];
+
+ await createTracesCh([
+ traceWithTrueScore,
+ traceWithFalseScore,
+ traceWithoutScore,
+ ]);
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceWithTrueScore.id,
+ name: scoreName,
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traceWithFalseScore.id,
+ name: scoreName,
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const baseFilter = [
+ {
+ column: "timestamp",
+ type: "datetime" as const,
+ operator: ">=" as const,
+ value: new Date(new Date().getTime() - 10_000).toISOString(),
+ },
+ {
+ column: "id",
+ type: "stringOptions" as const,
+ operator: "any of" as const,
+ value: traceIds,
+ },
+ ];
+
+ const equalsResult = await caller.traces.all({
+ projectId,
+ filter: [
+ ...baseFilter,
+ {
+ column: "Scores (boolean)",
+ type: "booleanObject",
+ key: scoreName,
+ operator: "=",
+ value: true,
+ },
+ ],
+ searchQuery: null,
+ searchType: ["id"],
+ page: 0,
+ limit: 50,
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
+ },
+ });
+
+ expect(equalsResult.traces.map((t) => t.id)).toEqual([
+ traceWithTrueScore.id,
+ ]);
+
+ // `<>` is the intended "none of / including unscored" semantics: NOT
+ // has() over an empty score_booleans array is true, so traces without
+ // any score of that name match too — consistent with categorical
+ // filters and InMemoryFilterService.
+ const notEqualsResult = await caller.traces.all({
+ projectId,
+ filter: [
+ ...baseFilter,
+ {
+ column: "Scores (boolean)",
+ type: "booleanObject",
+ key: scoreName,
+ operator: "<>",
+ value: true,
+ },
+ ],
+ searchQuery: null,
+ searchType: ["id"],
+ page: 0,
+ limit: 50,
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
+ },
+ });
+
+ expect(notEqualsResult.traces.map((t) => t.id).sort()).toEqual(
+ [traceWithFalseScore.id, traceWithoutScore.id].sort(),
+ );
+ });
+
it("should search traces by input only", async () => {
const trace = createTrace({
project_id: projectId,
@@ -528,34 +637,130 @@ describe("traces trpc", () => {
await createTracesCh([trace]);
await createObservationsCh([observation]);
- const observationScore = createTraceScore({
+ const observationScoreName = `observation_quality_${randomUUID()}`;
+ const sessionScoreName = `session_quality_${randomUUID()}`;
+ const scoreTimestamp = Date.now();
+
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: observationScoreName,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.7,
+ timestamp: scoreTimestamp,
+ }),
+ createSessionScore({
+ project_id: projectId,
+ name: sessionScoreName,
+ source: "API",
+ data_type: "NUMERIC",
+ value: 0.5,
+ timestamp: scoreTimestamp,
+ }),
+ ]);
+
+ const filterOptions = await caller.traces.filterOptions({
+ projectId,
+ timestampFilter: [
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: new Date(scoreTimestamp - 1_000),
+ },
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: "<=",
+ value: new Date(scoreTimestamp + 1_000),
+ },
+ ],
+ });
+
+ expect(filterOptions.scores_avg).toEqual(
+ expect.arrayContaining([observationScoreName]),
+ );
+ expect(filterOptions.scores_avg).not.toContain(sessionScoreName);
+ });
+
+ it("should include observation-only boolean score names for trace-scoped aggregates", async () => {
+ const trace = createTrace({
project_id: projectId,
- trace_id: trace.id,
- observation_id: observation.id,
- name: "observation_only_quality",
- source: "API",
- data_type: "NUMERIC",
- value: 0.7,
});
- const sessionScore = createTraceScore({
+ const observation = createObservation({
project_id: projectId,
- trace_id: null,
- session_id: randomUUID(),
- name: "session_only_quality",
- source: "API",
- data_type: "NUMERIC",
- value: 0.5,
+ trace_id: trace.id,
});
- await createScoresCh([observationScore, sessionScore]);
+ await createTracesCh([trace]);
+ await createObservationsCh([observation]);
+
+ const observationScoreName = `observation_bool_${randomUUID()}`;
+ const emptyObservationScoreName = `observation_bool_empty_${randomUUID()}`;
+ const sessionScoreName = `session_bool_${randomUUID()}`;
+ const scoreTimestamp = Date.now();
+
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: observationScoreName,
+ source: "API",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "True",
+ timestamp: scoreTimestamp,
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observation.id,
+ name: emptyObservationScoreName,
+ source: "API",
+ data_type: "BOOLEAN",
+ value: 1,
+ string_value: "",
+ timestamp: scoreTimestamp,
+ }),
+ createSessionScore({
+ project_id: projectId,
+ name: sessionScoreName,
+ source: "API",
+ data_type: "BOOLEAN",
+ value: 0,
+ string_value: "False",
+ timestamp: scoreTimestamp,
+ }),
+ ]);
const filterOptions = await caller.traces.filterOptions({
projectId,
+ timestampFilter: [
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: ">=",
+ value: new Date(scoreTimestamp - 1_000),
+ },
+ {
+ column: "timestamp",
+ type: "datetime",
+ operator: "<=",
+ value: new Date(scoreTimestamp + 1_000),
+ },
+ ],
});
- expect(filterOptions.scores_avg).toEqual(
- expect.arrayContaining(["observation_only_quality"]),
+ expect(filterOptions.score_booleans).toEqual(
+ expect.arrayContaining([observationScoreName]),
+ );
+ expect(filterOptions.score_booleans).not.toContain(
+ emptyObservationScoreName,
);
- expect(filterOptions.scores_avg).not.toContain("session_only_quality");
+ expect(filterOptions.score_booleans).not.toContain(sessionScoreName);
});
});
diff --git a/web/src/__tests__/server/unit/annotationBooleanScoreSchema.servertest.ts b/web/src/__tests__/server/unit/annotationBooleanScoreSchema.servertest.ts
new file mode 100644
index 0000000000..7b9888b0ec
--- /dev/null
+++ b/web/src/__tests__/server/unit/annotationBooleanScoreSchema.servertest.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ CreateAnnotationScoreData,
+ UpdateAnnotationScoreData,
+} from "@langfuse/shared";
+
+// Pins a deliberate decision in the BOOLEAN branch of the annotation score
+// schemas (packages/shared/src/features/annotation/types.ts): `value` is
+// derived from the label, so an inconsistent pair like
+// { stringValue: "True", value: 0 } cannot make the numeric (scores_avg)
+// and boolean (score_booleans) filter paths disagree on the same score.
+describe("annotation boolean score schema", () => {
+ const base = {
+ name: "is_correct",
+ projectId: "project-id",
+ scoreTarget: { type: "trace", traceId: "trace-id" },
+ configId: "config-id",
+ dataType: "BOOLEAN",
+ } as const;
+
+ it("derives value from the label on create", () => {
+ const parsed = CreateAnnotationScoreData.parse({
+ ...base,
+ stringValue: "False",
+ value: 1,
+ });
+
+ expect(parsed.stringValue).toBe("False");
+ expect(parsed.value).toBe(0);
+ });
+
+ it("derives value on update, overriding an inconsistent input value", () => {
+ const parsed = UpdateAnnotationScoreData.parse({
+ ...base,
+ id: "score-id",
+ stringValue: "True",
+ value: 0,
+ });
+
+ expect(parsed.stringValue).toBe("True");
+ expect(parsed.value).toBe(1);
+ });
+
+ it("rejects labels other than the exact config-enforced True/False", () => {
+ for (const stringValue of ["yes", "", "true", "false"]) {
+ expect(() =>
+ CreateAnnotationScoreData.parse({
+ ...base,
+ stringValue,
+ value: 1,
+ }),
+ ).toThrow();
+ }
+ });
+});
diff --git a/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
index 74f6b8788d..66785385c9 100644
--- a/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
+++ b/web/src/__tests__/server/unit/parseFilterCompletion.servertest.ts
@@ -89,9 +89,23 @@ describe("parseGeneratedFilters", () => {
operator: ">",
value: 0.8,
},
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "flag",
+ operator: "=",
+ value: true,
+ },
+ {
+ type: "booleanObject",
+ column: "trace_score_booleans",
+ key: "traceFlag",
+ operator: "<>",
+ value: false,
+ },
]);
const { filters, droppedCount } = parseGeneratedFilters(completion);
- expect(filters).toHaveLength(2);
+ expect(filters).toHaveLength(4);
expect(droppedCount).toBe(0);
});
diff --git a/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts b/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts
index 6490bc8cb8..410650b29c 100644
--- a/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts
+++ b/web/src/__tests__/server/unit/searchBarFilterPrompt.servertest.ts
@@ -69,8 +69,10 @@ describe("buildFilterSystemPrompt", () => {
expect(prompt).toContain("metadata");
expect(prompt).toContain(SCORE_COLUMNS.observation.numeric);
expect(prompt).toContain(SCORE_COLUMNS.observation.categorical);
+ expect(prompt).toContain(SCORE_COLUMNS.observation.boolean);
expect(prompt).toContain(SCORE_COLUMNS.trace.numeric);
expect(prompt).toContain(SCORE_COLUMNS.trace.categorical);
+ expect(prompt).toContain(SCORE_COLUMNS.trace.boolean);
});
it("omits the refine section without a current query", () => {
@@ -142,4 +144,26 @@ describe("metadata and score filters are representable", () => {
]);
expect(skippedFilters).toHaveLength(0);
});
+
+ it("boolean observation and trace scores", () => {
+ const { skippedFilters, text } = filterStateToQueryText([
+ {
+ type: "booleanObject",
+ column: SCORE_COLUMNS.observation.boolean,
+ key: "flag",
+ operator: "=",
+ value: true,
+ },
+ {
+ type: "booleanObject",
+ column: SCORE_COLUMNS.trace.boolean,
+ key: "traceFlag",
+ operator: "<>",
+ value: false,
+ },
+ ]);
+
+ expect(skippedFilters).toHaveLength(0);
+ expect(text).toBe("scores.flag:true -traceScores.traceFlag:false");
+ });
});
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index b945b861f4..3ca6ad129c 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -842,6 +842,25 @@ const LoadedSessionEventsPage: React.FC<{
return keyOptions ? { ...column, keyOptions } : column;
}
+ if (column.type === "booleanObject" && column.id === "score_booleans") {
+ const keyOptions = getStringFilterOptions(
+ typedFilterOptions.score_booleans,
+ );
+
+ return keyOptions ? { ...column, keyOptions } : column;
+ }
+
+ if (
+ column.type === "booleanObject" &&
+ column.id === "trace_score_booleans"
+ ) {
+ const keyOptions = getStringFilterOptions(
+ typedFilterOptions.trace_score_booleans,
+ );
+
+ return keyOptions ? { ...column, keyOptions } : column;
+ }
+
return column;
});
}, [typedFilterOptions, sessionEventsFilterConfig.columnDefinitions]);
diff --git a/web/src/components/table/data-table-controls.tsx b/web/src/components/table/data-table-controls.tsx
index 43ebaf7d05..e849c0377e 100644
--- a/web/src/components/table/data-table-controls.tsx
+++ b/web/src/components/table/data-table-controls.tsx
@@ -32,6 +32,7 @@ import type {
UIFilter,
KeyValueFilterEntry,
NumericKeyValueFilterEntry,
+ BooleanKeyValueFilterEntry,
StringKeyValueFilterEntry,
TextFilterEntry,
} from "@/src/features/filters/hooks/useSidebarFilterState";
@@ -374,6 +375,28 @@ export function DataTableControls({
);
}
+ if (filter.type === "booleanKeyValue") {
+ return (
+ <BooleanKeyValueFacet
+ key={filter.column}
+ filterKey={filter.column}
+ label={filter.label}
+ tooltip={filter.tooltip}
+ help={filter.help}
+ expanded={filter.expanded}
+ loading={filter.loading}
+ keyOptions={filter.keyOptions}
+ value={filter.value}
+ onChange={filter.onChange}
+ isActive={filter.isActive}
+ onReset={filter.onReset}
+ keyPlaceholder="Name"
+ isDisabled={filter.isDisabled}
+ disabledReason={filter.disabledReason}
+ />
+ );
+ }
+
if (filter.type === "stringKeyValue") {
return (
<StringKeyValueFacet
@@ -470,6 +493,13 @@ interface NumericKeyValueFacetProps extends BaseFacetProps {
keyPlaceholder?: string;
}
+interface BooleanKeyValueFacetProps extends BaseFacetProps {
+ keyOptions?: string[];
+ value: BooleanKeyValueFilterEntry[];
+ onChange: (filters: BooleanKeyValueFilterEntry[]) => void;
+ keyPlaceholder?: string;
+}
+
interface StringKeyValueFacetProps extends BaseFacetProps {
keyOptions?: string[];
value: StringKeyValueFilterEntry[];
@@ -1339,6 +1369,52 @@ export function NumericKeyValueFacet({
);
}
+export function BooleanKeyValueFacet({
+ label,
+ tooltip,
+ help,
+ filterKey,
+ filterKeyShort,
+ expanded: _expanded,
+ loading,
+ keyOptions,
+ value,
+ onChange,
+ isActive,
+ isDisabled,
+ disabledReason,
+ onReset,
+ keyPlaceholder,
+}: BooleanKeyValueFacetProps) {
+ return (
+ <FilterAccordionItem
+ label={label}
+ tooltip={tooltip}
+ help={help}
+ filterKey={filterKey}
+ filterKeyShort={filterKeyShort}
+ isActive={isActive}
+ isDisabled={isDisabled}
+ disabledReason={disabledReason}
+ onReset={onReset}
+ >
+ {loading ? (
+ <div className="text-muted-foreground px-4 py-2 text-sm">
+ Loading...
+ </div>
+ ) : (
+ <KeyValueFilterBuilder
+ mode="boolean"
+ keyOptions={keyOptions}
+ activeFilters={value}
+ onChange={onChange}
+ keyPlaceholder={keyPlaceholder}
+ />
+ )}
+ </FilterAccordionItem>
+ );
+}
+
export function StringKeyValueFacet({
label,
tooltip,
diff --git a/web/src/components/table/filtered-run-pills.tsx b/web/src/components/table/filtered-run-pills.tsx
index 8b7002895e..a10f260326 100644
--- a/web/src/components/table/filtered-run-pills.tsx
+++ b/web/src/components/table/filtered-run-pills.tsx
@@ -39,8 +39,8 @@ function operatorToText(operator: FilterCondition["operator"]): string {
function formatFilterForPill(filter: FilterCondition) {
const { operator, value } = filter;
- // Handle score filters (numberObject and categoryOptions with key)
- if (filter.type === "numberObject") {
+ // Handle score filters with key
+ if (filter.type === "numberObject" || filter.type === "booleanObject") {
const valueStr = Array.isArray(value) ? value.join(", ") : String(value);
return `${filter.key} ${operatorToText(operator)} ${valueStr}`;
}
diff --git a/web/src/components/table/key-value-filter-builder.tsx b/web/src/components/table/key-value-filter-builder.tsx
index ea515c34a5..068f4cbeed 100644
--- a/web/src/components/table/key-value-filter-builder.tsx
+++ b/web/src/components/table/key-value-filter-builder.tsx
@@ -27,6 +27,7 @@ import { cn } from "@/src/utils/tailwind";
import type {
KeyValueFilterEntry,
NumericKeyValueFilterEntry,
+ BooleanKeyValueFilterEntry,
StringKeyValueFilterEntry,
} from "@/src/features/filters/hooks/useSidebarFilterState";
@@ -46,6 +47,13 @@ type KeyValueFilterBuilderProps =
onChange: (filters: NumericKeyValueFilterEntry[]) => void;
keyPlaceholder?: string;
}
+ | {
+ mode: "boolean";
+ keyOptions?: string[];
+ activeFilters: BooleanKeyValueFilterEntry[];
+ onChange: (filters: BooleanKeyValueFilterEntry[]) => void;
+ keyPlaceholder?: string;
+ }
| {
mode: "string";
keyOptions?: string[];
@@ -69,6 +77,11 @@ const STRING_OPERATOR_LABELS = {
"does not contain": "does not contain",
} as const;
+const BOOLEAN_OPERATOR_LABELS = {
+ "=": "equals",
+ "<>": "does not equal",
+} as const;
+
export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
const {
mode,
@@ -88,6 +101,7 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
const [localFilters, setLocalFilters] = useState<
| KeyValueFilterEntry[]
| NumericKeyValueFilterEntry[]
+ | BooleanKeyValueFilterEntry[]
| StringKeyValueFilterEntry[]
>(() => (activeFilters.length > 0 ? activeFilters : []));
@@ -96,6 +110,7 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
updates:
| Partial<KeyValueFilterEntry>
| Partial<NumericKeyValueFilterEntry>
+ | Partial<BooleanKeyValueFilterEntry>
| Partial<StringKeyValueFilterEntry>,
) => {
// TypeScript can't narrow the union array type automatically, so we narrow explicitly based on mode
@@ -117,6 +132,15 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
} as NumericKeyValueFilterEntry;
setLocalFilters(newFilters);
(onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);
+ } else if (mode === "boolean") {
+ const filters = localFilters as BooleanKeyValueFilterEntry[];
+ const newFilters = [...filters];
+ newFilters[index] = {
+ ...newFilters[index],
+ ...updates,
+ } as BooleanKeyValueFilterEntry;
+ setLocalFilters(newFilters);
+ (onChange as (filters: BooleanKeyValueFilterEntry[]) => void)(newFilters);
} else {
const filters = localFilters as StringKeyValueFilterEntry[];
const newFilters = [...filters];
@@ -148,6 +172,15 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
const filters = localFilters as NumericKeyValueFilterEntry[];
const newFilters = [...filters, newFilter];
setLocalFilters(newFilters);
+ } else if (mode === "boolean") {
+ const newFilter: BooleanKeyValueFilterEntry = {
+ key: "",
+ operator: "=" as const,
+ value: "",
+ };
+ const filters = localFilters as BooleanKeyValueFilterEntry[];
+ const newFilters = [...filters, newFilter];
+ setLocalFilters(newFilters);
} else {
const newFilter: StringKeyValueFilterEntry = {
key: "",
@@ -171,6 +204,11 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
const newFilters = filters.filter((_, i) => i !== index);
setLocalFilters(newFilters);
(onChange as (filters: NumericKeyValueFilterEntry[]) => void)(newFilters);
+ } else if (mode === "boolean") {
+ const filters = localFilters as BooleanKeyValueFilterEntry[];
+ const newFilters = filters.filter((_, i) => i !== index);
+ setLocalFilters(newFilters);
+ (onChange as (filters: BooleanKeyValueFilterEntry[]) => void)(newFilters);
} else {
const filters = localFilters as StringKeyValueFilterEntry[];
const newFilters = filters.filter((_, i) => i !== index);
@@ -348,7 +386,7 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
<Input
type="number"
placeholder="Value"
- value={filter.value}
+ value={(filter as NumericKeyValueFilterEntry).value}
onChange={(e) =>
handleFilterChange(index, {
value:
@@ -358,6 +396,52 @@ export function KeyValueFilterBuilder(props: KeyValueFilterBuilderProps) {
disabled={!filter.key}
/>
</>
+ ) : mode === "boolean" ? (
+ <>
+ <Select
+ value={filter.operator}
+ onValueChange={(value) =>
+ handleFilterChange(index, {
+ operator: value as "=" | "<>",
+ })
+ }
+ >
+ <SelectTrigger>
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {Object.entries(BOOLEAN_OPERATOR_LABELS).map(
+ ([op, label]) => (
+ <SelectItem key={op} value={op}>
+ {label}
+ </SelectItem>
+ ),
+ )}
+ </SelectContent>
+ </Select>
+
+ <Select
+ value={
+ typeof filter.value === "boolean"
+ ? String(filter.value)
+ : undefined
+ }
+ onValueChange={(value) =>
+ handleFilterChange(index, {
+ value: value === "true",
+ })
+ }
+ disabled={!filter.key}
+ >
+ <SelectTrigger>
+ <SelectValue placeholder="Value" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="true">true</SelectItem>
+ <SelectItem value="false">false</SelectItem>
+ </SelectContent>
+ </Select>
+ </>
) : (
<>
{/* String operator select */}
diff --git a/web/src/components/table/use-cases/observations.tsx b/web/src/components/table/use-cases/observations.tsx
index 5f7ead46b9..1d1df4f8e0 100644
--- a/web/src/components/table/use-cases/observations.tsx
+++ b/web/src/components/table/use-cases/observations.tsx
@@ -417,6 +417,7 @@ export default function ObservationsTable({
) ?? undefined;
const scoresNumeric = filterOptions.data?.scores_avg ?? undefined;
+ const scoresBoolean = filterOptions.data?.score_booleans ?? undefined;
return {
environment:
@@ -479,6 +480,7 @@ export default function ObservationsTable({
totalCost: [],
score_categories: scoreCategories,
scores_avg: scoresNumeric,
+ score_booleans: scoresBoolean,
};
}, [environmentFilterOptions.data, filterOptions.data]);
diff --git a/web/src/components/table/use-cases/scores.tsx b/web/src/components/table/use-cases/scores.tsx
index 0fcd245054..6ebf0d1bf1 100644
--- a/web/src/components/table/use-cases/scores.tsx
+++ b/web/src/components/table/use-cases/scores.tsx
@@ -310,6 +310,7 @@ export default function ScoresTable({
value: sv.value,
count: sv.count !== undefined ? Number(sv.count) : undefined,
})) ?? undefined,
+ booleanValue: filterOptions.data?.booleanValue ?? undefined,
traceName:
filterOptions.data?.traceName?.map((tn) => ({
value: tn.value,
diff --git a/web/src/components/table/use-cases/sessions.tsx b/web/src/components/table/use-cases/sessions.tsx
index 0573ace8e7..a8c99de6d6 100644
--- a/web/src/components/table/use-cases/sessions.tsx
+++ b/web/src/components/table/use-cases/sessions.tsx
@@ -236,6 +236,7 @@ export default function SessionsTable({
) ?? undefined;
const scoresNumeric = filterOptions.data?.scores_avg ?? undefined;
+ const scoresBoolean = filterOptions.data?.score_booleans ?? undefined;
return {
bookmarked: ["Bookmarked", "Not bookmarked"],
@@ -256,6 +257,7 @@ export default function SessionsTable({
totalCost: [],
score_categories: scoreCategories,
scores_avg: scoresNumeric,
+ score_booleans: scoresBoolean,
};
}, [environmentOptions, filterOptions.data]);
diff --git a/web/src/components/table/use-cases/traces.tsx b/web/src/components/table/use-cases/traces.tsx
index fd97813214..805934c28f 100644
--- a/web/src/components/table/use-cases/traces.tsx
+++ b/web/src/components/table/use-cases/traces.tsx
@@ -316,6 +316,8 @@ export default function TracesTable({
const scoresNumeric =
traceFilterOptionsResponse.data?.scores_avg ?? undefined;
+ const scoresBoolean =
+ traceFilterOptionsResponse.data?.score_booleans ?? undefined;
return {
traceName:
@@ -350,6 +352,7 @@ export default function TracesTable({
totalCost: [],
score_categories: scoreCategories,
scores_avg: scoresNumeric,
+ score_booleans: scoresBoolean,
};
}, [environmentFilterOptions.data, traceFilterOptionsResponse.data]);
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index 495193fb86..0130c48b09 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -53,6 +53,7 @@ import {
getTraceScoresForDatasetRuns,
getDatasetRunItemsCountCh,
getNumericScoresGroupedByName,
+ getBooleanScoresGroupedByName,
getCategoricalScoresGroupedByName,
getDatasetRunsTableRowsCh,
getDatasetRunsTableCountCh,
@@ -758,20 +759,26 @@ export const datasetRouter = createTRPCRouter({
const { timestampFilter } = input;
- const [numericScoreNames, categoricalScoreNames] = await Promise.all([
- getNumericScoresGroupedByName(
- input.projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
- getCategoricalScoresGroupedByName(
- input.projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
- ]);
+ const [numericScoreNames, categoricalScoreNames, booleanScoreNames] =
+ await Promise.all([
+ getNumericScoresGroupedByName(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getCategoricalScoresGroupedByName(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getBooleanScoresGroupedByName(
+ input.projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ ]);
return {
agg_scores_avg: numericScoreNames.map((s) => s.name),
agg_score_categories: categoricalScoreNames,
+ agg_score_booleans: booleanScoreNames.map((s) => s.name),
};
}),
@@ -796,20 +803,26 @@ export const datasetRouter = createTRPCRouter({
const { projectId, timestampFilter } = input;
- const [numericScoreNames, categoricalScoreNames] = await Promise.all([
- getNumericScoresGroupedByName(
- projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
- getCategoricalScoresGroupedByName(
- projectId,
- timestampFilter ? [timestampFilter] : [],
- ),
- ]);
+ const [numericScoreNames, categoricalScoreNames, booleanScoreNames] =
+ await Promise.all([
+ getNumericScoresGroupedByName(
+ projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getCategoricalScoresGroupedByName(
+ projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ getBooleanScoresGroupedByName(
+ projectId,
+ timestampFilter ? [timestampFilter] : [],
+ ),
+ ]);
return {
agg_scores_avg: numericScoreNames.map((s) => s.name),
agg_score_categories: categoricalScoreNames,
+ agg_score_booleans: booleanScoreNames.map((s) => s.name),
};
}),
diff --git a/web/src/features/evals/hooks/useEvalConfigFilterOptions.ts b/web/src/features/evals/hooks/useEvalConfigFilterOptions.ts
index a2e4a395f9..7e929a4d76 100644
--- a/web/src/features/evals/hooks/useEvalConfigFilterOptions.ts
+++ b/web/src/features/evals/hooks/useEvalConfigFilterOptions.ts
@@ -76,6 +76,7 @@ export function useEvalConfigFilterOptions({
})),
scores_avg: traceFilterOptionsResponse.data.scores_avg,
score_categories: traceFilterOptionsResponse.data.score_categories,
+ score_booleans: traceFilterOptionsResponse.data.score_booleans,
traceTags: traceFilterOptionsResponse.data.tags?.map((t) => ({
value: t.value,
})),
diff --git a/web/src/features/events/config/filter-config.ts b/web/src/features/events/config/filter-config.ts
index 2dd84ec0ad..040c31e662 100644
--- a/web/src/features/events/config/filter-config.ts
+++ b/web/src/features/events/config/filter-config.ts
@@ -287,6 +287,11 @@ export const observationEventsFilterConfig: FilterConfig = {
column: "scores_avg",
label: "Numeric Scores",
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "score_booleans",
+ label: "Boolean Scores",
+ },
{
type: "keyValue" as const,
column: "trace_score_categories",
@@ -297,6 +302,11 @@ export const observationEventsFilterConfig: FilterConfig = {
column: "trace_scores_avg",
label: "Trace Numeric Scores",
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "trace_score_booleans",
+ label: "Trace Boolean Scores",
+ },
{
type: "numeric" as const,
column: "commentCount",
diff --git a/web/src/features/events/hooks/useEventsFilterOptions.ts b/web/src/features/events/hooks/useEventsFilterOptions.ts
index 9a2b8861f6..f18b11584c 100644
--- a/web/src/features/events/hooks/useEventsFilterOptions.ts
+++ b/web/src/features/events/hooks/useEventsFilterOptions.ts
@@ -41,8 +41,10 @@ const ALL_EVENT_FILTER_OPTION_COLUMNS = [
"calledToolNames",
"scores_avg",
"score_categories",
+ "score_booleans",
"trace_scores_avg",
"trace_score_categories",
+ "trace_score_booleans",
] as const satisfies readonly EventFilterOptionColumn[];
// Columns loaded eagerly on mount in lazy mode: the sidebar's default-expanded
@@ -50,7 +52,7 @@ const ALL_EVENT_FILTER_OPTION_COLUMNS = [
// suggestion fields (level/type/environment/name). The high-cardinality facets
// (userId/sessionId, model/prompt/experiment/tool) load only when opened or typed.
//
-// The four score-NAME columns are eager too. They are cheap (just the distinct
+// The six score-NAME columns are eager too. They are cheap (just the distinct
// score names + their categorical buckets, not per-row data) and drive the
// grammar's score-type routing: `scoreTypeContextFromObserved` must be populated
// before the bar lowers a `scores.<name>:5` token, or a categorical numeric-label
@@ -64,8 +66,10 @@ const EAGER_EVENT_FILTER_OPTION_COLUMNS = [
"isRootObservation",
"scores_avg",
"score_categories",
+ "score_booleans",
"trace_scores_avg",
"trace_score_categories",
+ "trace_score_booleans",
] as const satisfies readonly EventFilterOptionColumn[];
const EAGER_COLUMN_SET: ReadonlySet<string> = new Set(
@@ -292,8 +296,10 @@ export function useEventsFilterOptions({
totalCost: [],
score_categories: scoreCategories,
scores_avg: scoresNumeric,
+ score_booleans: rawData.score_booleans ?? undefined,
trace_score_categories: traceScoreCategories,
trace_scores_avg: traceScoresNumeric,
+ trace_score_booleans: rawData.trace_score_booleans ?? undefined,
};
}, [rawData]);
diff --git a/web/src/features/events/server/eventsService.ts b/web/src/features/events/server/eventsService.ts
index 9d7255755f..3026e08674 100644
--- a/web/src/features/events/server/eventsService.ts
+++ b/web/src/features/events/server/eventsService.ts
@@ -13,6 +13,7 @@ import {
getEventsFilterOptionValuesPage,
getEventsNumericStatsByFilterColumn,
getNumericScoresGroupedByName,
+ getBooleanScoresGroupedByName,
getScoresGroupedByNameSourceType,
getObservationsBatchIOFromEventsTable,
getScoresForObservations,
@@ -113,8 +114,10 @@ const EVENT_FILTER_OPTION_COLUMNS = [
const EVENT_SCORE_FILTER_OPTION_COLUMNS = [
"scores_avg",
"score_categories",
+ "score_booleans",
"trace_scores_avg",
"trace_score_categories",
+ "trace_score_booleans",
] as const;
export const EVENT_FILTER_OPTIONS_COLUMNS = [
@@ -534,18 +537,24 @@ export async function getEventFilterOptions(
);
const shouldLoadScoresAvg = requestedColumns.has("scores_avg");
const shouldLoadScoreCategories = requestedColumns.has("score_categories");
+ const shouldLoadScoreBooleans = requestedColumns.has("score_booleans");
const shouldLoadTraceScores = requestedColumns.has("trace_scores_avg");
const shouldLoadTraceScoreCategories = requestedColumns.has(
"trace_score_categories",
);
+ const shouldLoadTraceScoreBooleans = requestedColumns.has(
+ "trace_score_booleans",
+ );
// Observation-scoped and trace-scoped discovery are kept separate so each
// score column only offers names its filter/join can actually match.
const [
numericScoreNames,
+ booleanScoreNames,
categoricalScoreNames,
traceScoreColumns,
traceCategoricalScoreColumns,
+ traceBooleanScoreColumns,
eventFilterOptions,
] = await Promise.all([
shouldLoadScoresAvg
@@ -554,6 +563,12 @@ export async function getEventFilterOptions(
...traceTimestampFilters,
])
: Promise.resolve([]),
+ shouldLoadScoreBooleans
+ ? getBooleanScoresGroupedByName(projectId, [
+ ...OBSERVATION_SCORE_SCOPE_FILTER,
+ ...traceTimestampFilters,
+ ])
+ : Promise.resolve([]),
shouldLoadScoreCategories
? getCategoricalScoresGroupedByName(projectId, [
...OBSERVATION_SCORE_SCOPE_FILTER,
@@ -572,6 +587,12 @@ export async function getEventFilterOptions(
...traceTimestampFilters,
])
: Promise.resolve([]),
+ shouldLoadTraceScoreBooleans
+ ? getBooleanScoresGroupedByName(projectId, [
+ ...TRACE_SCORE_SCOPE_FILTER,
+ ...traceTimestampFilters,
+ ])
+ : Promise.resolve([]),
eventColumns.length > 0
? getEventsFilterOptionsForColumns({
projectId,
@@ -609,12 +630,22 @@ export async function getEventFilterOptions(
...(shouldLoadScoreCategories
? { score_categories: categoricalScoreNames }
: {}),
+ ...(shouldLoadScoreBooleans
+ ? { score_booleans: booleanScoreNames.map((score) => score.name) }
+ : {}),
...(shouldLoadTraceScores
? { trace_scores_avg: traceNumericScoreNames }
: {}),
...(shouldLoadTraceScoreCategories
? { trace_score_categories: traceCategoricalScoreColumns }
: {}),
+ ...(shouldLoadTraceScoreBooleans
+ ? {
+ trace_score_booleans: traceBooleanScoreColumns.map(
+ (score) => score.name,
+ ),
+ }
+ : {}),
};
}
diff --git a/web/src/features/experiments/components/table/ExperimentFilterPills.tsx b/web/src/features/experiments/components/table/ExperimentFilterPills.tsx
index 7f9960067d..3e637a9074 100644
--- a/web/src/features/experiments/components/table/ExperimentFilterPills.tsx
+++ b/web/src/features/experiments/components/table/ExperimentFilterPills.tsx
@@ -30,9 +30,11 @@ function operatorToText(operator: FilterCondition["operator"]): string {
function formatFilterForPill(filter: FilterCondition): string {
const { column, operator, value } = filter;
- // Handle object filters (numberObject, stringObject) with key
+ // Handle object filters with key
if (
- (filter.type === "numberObject" || filter.type === "stringObject") &&
+ (filter.type === "numberObject" ||
+ filter.type === "stringObject" ||
+ filter.type === "booleanObject") &&
"key" in filter
) {
const valueStr = Array.isArray(value) ? value.join(", ") : String(value);
diff --git a/web/src/features/experiments/components/table/filter-config.ts b/web/src/features/experiments/components/table/filter-config.ts
index bdf26e864c..55ecaff872 100644
--- a/web/src/features/experiments/components/table/filter-config.ts
+++ b/web/src/features/experiments/components/table/filter-config.ts
@@ -97,6 +97,13 @@ export const experimentsTableCols: ColumnDefinition[] = [
options: [],
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "obs_score_booleans",
+ type: "booleanObject",
+ internal: "obs_score_booleans",
+ nullable: true,
+ },
// Trace-level scores (ets.* alias in backend)
{
name: "Trace Scores (numeric)",
@@ -112,6 +119,13 @@ export const experimentsTableCols: ColumnDefinition[] = [
options: [],
nullable: true,
},
+ {
+ name: "Trace Scores (boolean)",
+ id: "trace_score_booleans",
+ type: "booleanObject",
+ internal: "trace_score_booleans",
+ nullable: true,
+ },
];
// Helper function to get column name from experimentsTableCols by ID
@@ -164,6 +178,11 @@ export const experimentsFilterConfig: FilterConfig = {
column: "obs_scores_avg",
label: getExperimentsColumnName("obs_scores_avg"),
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "obs_score_booleans",
+ label: getExperimentsColumnName("obs_score_booleans"),
+ },
// Trace-level scores
{
type: "keyValue" as const,
@@ -175,6 +194,11 @@ export const experimentsFilterConfig: FilterConfig = {
column: "trace_scores_avg",
label: getExperimentsColumnName("trace_scores_avg"),
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "trace_score_booleans",
+ label: getExperimentsColumnName("trace_score_booleans"),
+ },
],
};
diff --git a/web/src/features/experiments/config/experiment-items-filter-config.ts b/web/src/features/experiments/config/experiment-items-filter-config.ts
index 436e4a4267..5d262ecec0 100644
--- a/web/src/features/experiments/config/experiment-items-filter-config.ts
+++ b/web/src/features/experiments/config/experiment-items-filter-config.ts
@@ -76,6 +76,13 @@ export const experimentItemsTableCols: ColumnDefinition[] = [
options: [],
nullable: true,
},
+ {
+ name: "Scores (boolean)",
+ id: "obs_score_booleans",
+ type: "booleanObject",
+ internal: "obs_score_booleans",
+ nullable: true,
+ },
{
name: "Trace Scores (numeric)",
id: "trace_scores_avg",
@@ -90,6 +97,13 @@ export const experimentItemsTableCols: ColumnDefinition[] = [
options: [],
nullable: true,
},
+ {
+ name: "Trace Scores (boolean)",
+ id: "trace_score_booleans",
+ type: "booleanObject",
+ internal: "trace_score_booleans",
+ nullable: true,
+ },
{
name: "Item Metadata",
id: "itemMetadata",
@@ -147,6 +161,11 @@ export const experimentItemsFilterConfig: FilterConfig = {
column: "obs_scores_avg",
label: getExperimentItemsColumnName("obs_scores_avg"),
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "obs_score_booleans",
+ label: getExperimentItemsColumnName("obs_score_booleans"),
+ },
{
type: "keyValue" as const,
column: "trace_score_categories",
@@ -157,5 +176,10 @@ export const experimentItemsFilterConfig: FilterConfig = {
column: "trace_scores_avg",
label: getExperimentItemsColumnName("trace_scores_avg"),
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "trace_score_booleans",
+ label: getExperimentItemsColumnName("trace_score_booleans"),
+ },
],
};
diff --git a/web/src/features/experiments/hooks/useExperimentFilterOptions.ts b/web/src/features/experiments/hooks/useExperimentFilterOptions.ts
index a8c672a956..12e07d8012 100644
--- a/web/src/features/experiments/hooks/useExperimentFilterOptions.ts
+++ b/web/src/features/experiments/hooks/useExperimentFilterOptions.ts
@@ -56,11 +56,14 @@ export function useExperimentFilterOptions({
obs_score_categories: processScoreCategories(
filterOptions.data?.obs_score_categories,
),
+ obs_score_booleans: filterOptions.data?.obs_score_booleans ?? undefined,
// Trace-level score options
trace_scores_avg: filterOptions.data?.trace_scores_avg ?? undefined,
trace_score_categories: processScoreCategories(
filterOptions.data?.trace_score_categories,
),
+ trace_score_booleans:
+ filterOptions.data?.trace_score_booleans ?? undefined,
};
}, [datasets.data, filterOptions.data]);
diff --git a/web/src/features/experiments/hooks/useExperimentItemsFilterOptions.ts b/web/src/features/experiments/hooks/useExperimentItemsFilterOptions.ts
index 6025b8dc57..9b2d922f73 100644
--- a/web/src/features/experiments/hooks/useExperimentItemsFilterOptions.ts
+++ b/web/src/features/experiments/hooks/useExperimentItemsFilterOptions.ts
@@ -47,8 +47,10 @@ export const useExperimentItemsFilterOptions = ({
return {
obs_scores_avg: undefined,
obs_score_categories: undefined,
+ obs_score_booleans: undefined,
trace_scores_avg: undefined,
trace_score_categories: undefined,
+ trace_score_booleans: undefined,
} satisfies ExperimentItemScoreFilterOptions;
}
@@ -57,10 +59,12 @@ export const useExperimentItemsFilterOptions = ({
obs_score_categories: processCategoricalScoreOptions(
filterOptions.data.obs_score_categories,
),
+ obs_score_booleans: filterOptions.data.obs_score_booleans,
trace_scores_avg: filterOptions.data.trace_scores_avg,
trace_score_categories: processCategoricalScoreOptions(
filterOptions.data.trace_score_categories,
),
+ trace_score_booleans: filterOptions.data.trace_score_booleans,
} satisfies ExperimentItemScoreFilterOptions;
}, [filterOptions.data]);
diff --git a/web/src/features/experiments/server/router.ts b/web/src/features/experiments/server/router.ts
index 5765bf9fab..8d729d98a7 100644
--- a/web/src/features/experiments/server/router.ts
+++ b/web/src/features/experiments/server/router.ts
@@ -5,6 +5,7 @@ import {
createDatasetItemFilterState,
ExperimentCreateQueue,
getCategoricalScoresGroupedByName,
+ getBooleanScoresGroupedByName,
getDatasetItems,
getEventsGroupedByExperimentDatasetId,
getExperimentsCountFromEvents,
@@ -455,21 +456,29 @@ export const experimentsRouter = createTRPCRouter({
}))
: [];
- const [numericScoreNames, categoricalScoreNames, experimentDatasetIds] =
- await Promise.all([
- getNumericScoresGroupedByName(
- input.projectId,
- traceTimestampFilters ?? [],
- ),
- getCategoricalScoresGroupedByName(
- input.projectId,
- traceTimestampFilters ?? [],
- ),
- getEventsGroupedByExperimentDatasetId(
- input.projectId,
- input.startTimeFilter ?? [],
- ),
- ]);
+ const [
+ numericScoreNames,
+ categoricalScoreNames,
+ booleanScoreNames,
+ experimentDatasetIds,
+ ] = await Promise.all([
+ getNumericScoresGroupedByName(
+ input.projectId,
+ traceTimestampFilters ?? [],
+ ),
+ getCategoricalScoresGroupedByName(
+ input.projectId,
+ traceTimestampFilters ?? [],
+ ),
+ getBooleanScoresGroupedByName(
+ input.projectId,
+ traceTimestampFilters ?? [],
+ ),
+ getEventsGroupedByExperimentDatasetId(
+ input.projectId,
+ input.startTimeFilter ?? [],
+ ),
+ ]);
const experimentDatasetIdSet = new Set<string>();
for (const { experimentDatasetId } of experimentDatasetIds) {
@@ -481,14 +490,17 @@ export const experimentsRouter = createTRPCRouter({
// Return score options for both observation-level and trace-level filters
// The same score names are available at both levels
const numericScoreOptions = numericScoreNames.map((score) => score.name);
+ const booleanScoreOptions = booleanScoreNames.map((score) => score.name);
return {
// Observation-level score options (eos.*)
obs_scores_avg: numericScoreOptions,
obs_score_categories: categoricalScoreNames,
+ obs_score_booleans: booleanScoreOptions,
// Trace-level score options (ets.*)
trace_scores_avg: numericScoreOptions,
trace_score_categories: categoricalScoreNames,
+ trace_score_booleans: booleanScoreOptions,
experimentDatasetIds: Array.from(experimentDatasetIdSet),
};
}),
diff --git a/web/src/features/experiments/types/charts.ts b/web/src/features/experiments/types/charts.ts
index f6cb006575..7d954a6c26 100644
--- a/web/src/features/experiments/types/charts.ts
+++ b/web/src/features/experiments/types/charts.ts
@@ -19,15 +19,19 @@ export type MetricOption = {
export type ScoreFilterOptions = {
obs_scores_avg?: string[];
obs_score_categories?: Record<string, string[]>;
+ obs_score_booleans?: string[];
experiment_scores_avg?: string[];
experiment_score_categories?: Record<string, string[]>;
+ experiment_score_booleans?: string[];
};
export type ExperimentItemScoreFilterOptions = {
obs_scores_avg?: string[];
obs_score_categories?: Record<string, string[]>;
+ obs_score_booleans?: string[];
trace_scores_avg?: string[];
trace_score_categories?: Record<string, string[]>;
+ trace_score_booleans?: string[];
};
export type ScoreLevel = "obs" | "experiment";
diff --git a/web/src/features/filters/components/filter-builder.tsx b/web/src/features/filters/components/filter-builder.tsx
index 1ed7733f89..a5a1acb447 100644
--- a/web/src/features/filters/components/filter-builder.tsx
+++ b/web/src/features/filters/components/filter-builder.tsx
@@ -281,7 +281,9 @@ export function InlineFilterState({
)}
>
{filter.column}
- {filter.type === "stringObject" || filter.type === "numberObject"
+ {filter.type === "stringObject" ||
+ filter.type === "numberObject" ||
+ filter.type === "booleanObject"
? `.${filter.key}`
: ""}{" "}
{filter.operator}{" "}
@@ -295,7 +297,7 @@ export function InlineFilterState({
: filter.value.join(", ")
: filter.type === "number" || filter.type === "numberObject"
? filter.value
- : filter.type === "boolean"
+ : filter.type === "boolean" || filter.type === "booleanObject"
? `${filter.value}`
: filter.type === "null"
? ""
@@ -599,7 +601,8 @@ function FilterBuilderForm({
);
const keyOptions =
column?.type === "numberObject" ||
- column?.type === "stringObject"
+ column?.type === "stringObject" ||
+ column?.type === "booleanObject"
? column.keyOptions?.filter(
(o) => NonEmptyString.safeParse(o).success,
)
@@ -721,9 +724,11 @@ function FilterBuilderForm({
</Popover>
{filter.type &&
(filter.type === "numberObject" ||
- filter.type === "stringObject") &&
+ filter.type === "stringObject" ||
+ filter.type === "booleanObject") &&
(column?.type === "numberObject" ||
- column?.type === "stringObject") ? (
+ column?.type === "stringObject" ||
+ column?.type === "booleanObject") ? (
keyOptions?.length ? (
// Case 1: object with keyOptions - selector of the key of the object
<Select
@@ -954,7 +959,8 @@ function FilterBuilderForm({
columnsWithCustomSelect.includes(column.id)
}
/>
- ) : filter.type === "boolean" ? (
+ ) : filter.type === "boolean" ||
+ filter.type === "booleanObject" ? (
<Select
disabled={disabled}
onValueChange={(value) => {
diff --git a/web/src/features/filters/config/observations-config.ts b/web/src/features/filters/config/observations-config.ts
index e7c8fd0426..98133589a1 100644
--- a/web/src/features/filters/config/observations-config.ts
+++ b/web/src/features/filters/config/observations-config.ts
@@ -177,6 +177,11 @@ export const observationFilterConfig: FilterConfig = {
column: "scores_avg",
label: "Numeric Scores",
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "score_booleans",
+ label: "Boolean Scores",
+ },
{
type: "numeric" as const,
column: "commentCount",
diff --git a/web/src/features/filters/config/scores-config.ts b/web/src/features/filters/config/scores-config.ts
index 624f945cf6..ee052668e9 100644
--- a/web/src/features/filters/config/scores-config.ts
+++ b/web/src/features/filters/config/scores-config.ts
@@ -57,11 +57,18 @@ export const scoreFilterConfig: FilterConfig = {
column: "value",
label: "Numeric Value",
tooltip:
- "Filters scores by numeric value. Applies to NUMERIC and BOOLEAN data types. For CATEGORICAL scores, use the 'Categorical Value' filter below.",
+ "Filters scores by numeric value. For BOOLEAN scores, use the 'Boolean Value' filter below. For CATEGORICAL scores, use the 'Categorical Value' filter below.",
min: 0,
max: 1,
step: 0.01,
},
+ {
+ type: "categorical" as const,
+ column: "booleanValue",
+ label: "Boolean Value",
+ tooltip: "Filters BOOLEAN scores by true or false.",
+ disableTextFilter: true,
+ },
{
type: "categorical" as const,
column: "stringValue",
diff --git a/web/src/features/filters/config/sessions-config.ts b/web/src/features/filters/config/sessions-config.ts
index 676885c3b4..9f46f2cd16 100644
--- a/web/src/features/filters/config/sessions-config.ts
+++ b/web/src/features/filters/config/sessions-config.ts
@@ -118,6 +118,11 @@ export const sessionFilterConfig: FilterConfig = {
column: "scores_avg",
label: "Numeric Scores",
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "score_booleans",
+ label: "Boolean Scores",
+ },
{
type: "numeric" as const,
column: "commentCount",
diff --git a/web/src/features/filters/config/traces-config.ts b/web/src/features/filters/config/traces-config.ts
index 914cc7e872..beac5a7a0c 100644
--- a/web/src/features/filters/config/traces-config.ts
+++ b/web/src/features/filters/config/traces-config.ts
@@ -148,6 +148,11 @@ export const traceFilterConfig: FilterConfig = {
column: "scores_avg",
label: "Numeric Scores",
},
+ {
+ type: "booleanKeyValue" as const,
+ column: "score_booleans",
+ label: "Boolean Scores",
+ },
],
};
diff --git a/web/src/features/filters/hooks/useFilterState.ts b/web/src/features/filters/hooks/useFilterState.ts
index ac56fa2893..8e944ef925 100644
--- a/web/src/features/filters/hooks/useFilterState.ts
+++ b/web/src/features/filters/hooks/useFilterState.ts
@@ -50,6 +50,7 @@ const getCommaArrayParam = (table: TableName) => ({
const stringified = `${columnId};${f.type};${
f.type === "numberObject" ||
f.type === "stringObject" ||
+ f.type === "booleanObject" ||
f.type === "categoryOptions" ||
f.type === "positionInTrace"
? f.key
@@ -105,7 +106,7 @@ const getCommaArrayParam = (table: TableName) => ({
? splitOnUnescapedPipe(decodedValue).map(
unescapePipeInValue,
)
- : type === "boolean"
+ : type === "boolean" || type === "booleanObject"
? decodedValue === "true"
: decodedValue;
diff --git a/web/src/features/filters/hooks/useSidebarFilterState.tsx b/web/src/features/filters/hooks/useSidebarFilterState.tsx
index 714c8730d8..29f79348a7 100644
--- a/web/src/features/filters/hooks/useSidebarFilterState.tsx
+++ b/web/src/features/filters/hooks/useSidebarFilterState.tsx
@@ -220,6 +220,12 @@ export type NumericKeyValueFilterEntry = {
value: number | "";
};
+export type BooleanKeyValueFilterEntry = {
+ key: string;
+ operator: "=" | "<>";
+ value: boolean | "";
+};
+
// Represents one active string filter row in the string key-value facet UI
// Example: key="environment", operator="=", value="production"
export type StringKeyValueFilterEntry = {
@@ -243,6 +249,13 @@ export interface NumericKeyValueUIFilter extends BaseUIFilter {
onChange: (filters: NumericKeyValueFilterEntry[]) => void;
}
+export interface BooleanKeyValueUIFilter extends BaseUIFilter {
+ type: "booleanKeyValue";
+ value: BooleanKeyValueFilterEntry[]; // Array of active filter rows
+ keyOptions?: string[];
+ onChange: (filters: BooleanKeyValueFilterEntry[]) => void;
+}
+
export interface StringKeyValueUIFilter extends BaseUIFilter {
type: "stringKeyValue";
value: StringKeyValueFilterEntry[]; // Array of active filter rows
@@ -256,6 +269,7 @@ export type UIFilter =
| StringUIFilter
| KeyValueUIFilter
| NumericKeyValueUIFilter
+ | BooleanKeyValueUIFilter
| StringKeyValueUIFilter;
const EMPTY_MAP: Map<string, number> = new Map();
@@ -1392,11 +1406,36 @@ export function useSidebarFilterState(
const isActive = activeFilters.length > 0;
const disableState = getFacetDisabledState(facet);
- // Get available keys from options (should be array of score names)
+ // Get available keys from options (should be array of score names).
+ // Backend numeric score-name discovery keeps BOOLEAN names for
+ // legacy numeric filtering; the paired boolean facet (same column
+ // with the score_booleans suffix) owns those names in the UI, so
+ // subtract them from the offering here. Active filter keys are
+ // merged back in resolveKnownKeyOptions, so pre-existing numeric
+ // filters on boolean scores (old URLs/saved views) still render
+ // and stay editable.
+ const pairedBooleanKeys =
+ options[facet.column.replace(/scores_avg$/, "score_booleans")];
+ const booleanNames = new Set(
+ Array.isArray(pairedBooleanKeys)
+ ? pairedBooleanKeys.map((option) =>
+ typeof option === "string" ? option : option.value,
+ )
+ : [],
+ );
const availableKeys = options[facet.column];
+ const nonBooleanKeys =
+ Array.isArray(availableKeys) && booleanNames.size > 0
+ ? availableKeys.filter(
+ (option) =>
+ !booleanNames.has(
+ typeof option === "string" ? option : option.value,
+ ),
+ )
+ : availableKeys;
const keyOptions = resolveKnownKeyOptions(
facet.keyOptions,
- availableKeys,
+ nonBooleanKeys,
activeFilters.map((filter) => filter.key),
);
@@ -1450,6 +1489,81 @@ export function useSidebarFilterState(
};
}
+ // Handle booleanKeyValue filters
+ if (facet.type === "booleanKeyValue") {
+ const booleanFilters = filterState.filter(
+ (f) => f.column === facet.column && f.type === "booleanObject",
+ ) as Array<{
+ column: string;
+ type: "booleanObject";
+ operator: "=" | "<>";
+ key: string;
+ value: boolean;
+ }>;
+
+ const activeFilters: BooleanKeyValueFilterEntry[] =
+ booleanFilters.map((f) => ({
+ key: f.key,
+ operator: f.operator,
+ value: f.value,
+ }));
+
+ const isActive = activeFilters.length > 0;
+ const disableState = getFacetDisabledState(facet);
+ const availableKeys = options[facet.column];
+ const keyOptions = resolveKnownKeyOptions(
+ facet.keyOptions,
+ availableKeys,
+ activeFilters.map((filter) => filter.key),
+ );
+
+ return {
+ type: "booleanKeyValue",
+ column: facet.column,
+ label: facet.label,
+ tooltip: facet.tooltip,
+ help: facet.help,
+
+ value: activeFilters,
+ keyOptions,
+ loading: shouldShowLoading(facet.column),
+ expanded: expandedSet.has(facet.column),
+ isActive,
+ isDisabled: disableState.isDisabled,
+ disabledReason: disableState.reason,
+ onChange: (filters: BooleanKeyValueFilterEntry[]) => {
+ const withoutBoolean = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "booleanObject"),
+ );
+
+ const validFilters = filters.filter(
+ (entry) => entry.key && entry.value !== "",
+ );
+
+ const newFilters: FilterState = [
+ ...withoutBoolean,
+ ...validFilters.map((entry) => ({
+ column: facet.column,
+ type: "booleanObject" as const,
+ operator: entry.operator,
+ key: entry.key,
+ value: entry.value as boolean,
+ })),
+ ];
+
+ setFilterState(newFilters);
+ },
+ onReset: () => {
+ const newFilters = filterState.filter(
+ (f) =>
+ !(f.column === facet.column && f.type === "booleanObject"),
+ );
+ setFilterState(newFilters);
+ },
+ };
+ }
+
// Handle stringKeyValue filters
if (facet.type === "stringKeyValue") {
// Extract all stringObject filters for this column from filterState
diff --git a/web/src/features/filters/lib/filter-config.ts b/web/src/features/filters/lib/filter-config.ts
index 90d72160c4..476c98b44b 100644
--- a/web/src/features/filters/lib/filter-config.ts
+++ b/web/src/features/filters/lib/filter-config.ts
@@ -50,6 +50,11 @@ interface NumericKeyValueFacet extends BaseFacet {
keyOptions?: string[];
}
+interface BooleanKeyValueFacet extends BaseFacet {
+ type: "booleanKeyValue";
+ keyOptions?: string[];
+}
+
interface StringKeyValueFacet extends BaseFacet {
type: "stringKeyValue";
keyOptions?: string[];
@@ -62,6 +67,7 @@ export type Facet =
| StringFacet
| KeyValueFacet
| NumericKeyValueFacet
+ | BooleanKeyValueFacet
| StringKeyValueFacet;
export type FilterStateMigration = (filters: FilterState) => FilterState;
diff --git a/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts b/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts
index de263d492e..07db6d05aa 100644
--- a/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts
+++ b/web/src/features/filters/lib/filter-query-encoding-decoding.clienttest.ts
@@ -164,6 +164,21 @@ describe("Filter Query Encoding & Decoding (Legacy Format)", () => {
);
});
+ it("should encode booleanObject filter", () => {
+ const filters: FilterState = [
+ {
+ column: "score_booleans",
+ type: "booleanObject",
+ operator: "=",
+ key: "flag",
+ value: true,
+ },
+ ];
+ expect(encodeFilters(filters)).toBe(
+ "score_booleans;booleanObject;flag;=;true",
+ );
+ });
+
it("should encode stringObject filter", () => {
const filters: FilterState = [
{
@@ -356,6 +371,20 @@ describe("Filter Query Encoding & Decoding (Legacy Format)", () => {
]);
});
+ it("should decode booleanObject filter", () => {
+ const query = "score_booleans;booleanObject;flag;=;true";
+ const decoded = decodeFilters(query);
+ expect(decoded).toEqual([
+ {
+ column: "score_booleans",
+ type: "booleanObject",
+ operator: "=",
+ key: "flag",
+ value: true,
+ },
+ ]);
+ });
+
it("should decode stringObject filter", () => {
const query = "metadata;stringObject;environment;contains;production";
const decoded = decodeFilters(query);
diff --git a/web/src/features/filters/lib/filter-query-encoding.ts b/web/src/features/filters/lib/filter-query-encoding.ts
index 2d81f9ed37..155812ee82 100644
--- a/web/src/features/filters/lib/filter-query-encoding.ts
+++ b/web/src/features/filters/lib/filter-query-encoding.ts
@@ -95,6 +95,7 @@ export function encodeFiltersGeneric(filters: FilterState): string {
const key =
f.type === "numberObject" ||
f.type === "stringObject" ||
+ f.type === "booleanObject" ||
f.type === "categoryOptions" ||
f.type === "positionInTrace"
? (f as any).key || ""
@@ -179,7 +180,7 @@ export function decodeFiltersGeneric(query: string): FilterState {
: decodedValue === ""
? [""] // allow empty strings for stringOptions (i.e, filter for empty trace name)
: [decodedValue];
- } else if (type === "boolean") {
+ } else if (type === "boolean" || type === "booleanObject") {
parsedValue = decodedValue === "true";
} else {
parsedValue = decodedValue;
@@ -198,6 +199,7 @@ export function decodeFiltersGeneric(query: string): FilterState {
if (
type === "categoryOptions" ||
type === "numberObject" ||
+ type === "booleanObject" ||
type === "stringObject" ||
type === "positionInTrace"
) {
diff --git a/web/src/features/mcp/features/observations/tools/getObservationFilterSchema.ts b/web/src/features/mcp/features/observations/tools/getObservationFilterSchema.ts
index 34ac8ef2d1..a474c586b4 100644
--- a/web/src/features/mcp/features/observations/tools/getObservationFilterSchema.ts
+++ b/web/src/features/mcp/features/observations/tools/getObservationFilterSchema.ts
@@ -58,7 +58,8 @@ export const [
nullable: Boolean(column.nullable),
requiresKey:
column.type === "stringObject" ||
- column.type === "numberObject",
+ column.type === "numberObject" ||
+ column.type === "booleanObject",
},
];
}),
diff --git a/web/src/features/search-bar/lib/adapter.clienttest.ts b/web/src/features/search-bar/lib/adapter.clienttest.ts
index f491890dc7..8f6d2b6e6b 100644
--- a/web/src/features/search-bar/lib/adapter.clienttest.ts
+++ b/web/src/features/search-bar/lib/adapter.clienttest.ts
@@ -302,6 +302,150 @@ describe("astToFilterState", () => {
]);
});
+ it("routes known boolean scores to booleanObject filters", () => {
+ const scoreTypes = {
+ numericScoreNames: new Set<string>(),
+ categoricalScoreNames: new Set<string>(),
+ booleanScoreNames: new Set<string>(["flag"]),
+ traceNumericScoreNames: new Set<string>(),
+ traceCategoricalScoreNames: new Set<string>(),
+ traceBooleanScoreNames: new Set<string>(["traceFlag"]),
+ };
+ const lowerWith = (text: string) =>
+ astToFilterState(parse(text).ast, scoreTypes);
+
+ expect(lowerWith("scores.flag:true").filters).toEqual([
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "flag",
+ operator: "=",
+ value: true,
+ },
+ ]);
+ expect(lowerWith("-traceScores.traceFlag:false").filters).toEqual([
+ {
+ type: "booleanObject",
+ column: "trace_score_booleans",
+ key: "traceFlag",
+ operator: "<>",
+ value: false,
+ },
+ ]);
+ // Comparisons fall back to the legacy numeric column — see the
+ // "keeps legacy numeric filters" test below.
+ expect(lowerWith("scores.flag:>0").errors).toEqual([]);
+ expect(
+ lowerWith("scores.flag:(true OR false)").errors.length,
+ ).toBeGreaterThan(0);
+ });
+
+ it("routes boolean literals to booleanObject when legacy numeric options also include the score", () => {
+ const scoreTypes = {
+ numericScoreNames: new Set<string>(["flag"]),
+ categoricalScoreNames: new Set<string>(),
+ booleanScoreNames: new Set<string>(["flag"]),
+ traceNumericScoreNames: new Set<string>(["traceFlag"]),
+ traceCategoricalScoreNames: new Set<string>(),
+ traceBooleanScoreNames: new Set<string>(["traceFlag"]),
+ };
+
+ expect(
+ astToFilterState(parse("scores.flag:true").ast, scoreTypes).filters,
+ ).toEqual([
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "flag",
+ operator: "=",
+ value: true,
+ },
+ ]);
+ expect(
+ astToFilterState(parse("-traceScores.traceFlag:false").ast, scoreTypes)
+ .filters,
+ ).toEqual([
+ {
+ type: "booleanObject",
+ column: "trace_score_booleans",
+ key: "traceFlag",
+ operator: "<>",
+ value: false,
+ },
+ ]);
+ expect(
+ astToFilterState(parse("scores.flag:1").ast, scoreTypes).filters,
+ ).toEqual([
+ {
+ type: "numberObject",
+ column: "scores_avg",
+ key: "flag",
+ operator: "=",
+ value: 1,
+ },
+ ]);
+ });
+
+ it("keeps legacy numeric filters working on boolean-observed scores", () => {
+ // Boolean scores also aggregate numerically (0/1) into scores_avg. The
+ // sidebar's numeric facet and pre-boolean-filter URLs/saved views still
+ // produce numberObject filters on them; those must keep lowering
+ // numerically — rejecting them would lock the bar red on state a
+ // first-party surface created.
+ const scoreTypes = {
+ numericScoreNames: new Set<string>(),
+ categoricalScoreNames: new Set<string>(),
+ booleanScoreNames: new Set<string>(["flag"]),
+ traceNumericScoreNames: new Set<string>(),
+ traceCategoricalScoreNames: new Set<string>(),
+ traceBooleanScoreNames: new Set<string>(["traceFlag"]),
+ };
+ const lowerWith = (text: string) =>
+ astToFilterState(parse(text).ast, scoreTypes);
+
+ const comparison = lowerWith("scores.flag:>=0.5");
+ expect(comparison.errors).toEqual([]);
+ expect(comparison.filters).toEqual([
+ {
+ type: "numberObject",
+ column: "scores_avg",
+ key: "flag",
+ operator: ">=",
+ value: 0.5,
+ },
+ ]);
+ expect(lowerWith("scores.flag:1").filters).toEqual([
+ {
+ type: "numberObject",
+ column: "scores_avg",
+ key: "flag",
+ operator: "=",
+ value: 1,
+ },
+ ]);
+ expect(lowerWith("traceScores.traceFlag:<1").filters).toEqual([
+ {
+ type: "numberObject",
+ column: "trace_scores_avg",
+ key: "traceFlag",
+ operator: "<",
+ value: 1,
+ },
+ ]);
+ // Boolean literals still prefer the boolean column…
+ expect(lowerWith("scores.flag:true").filters).toEqual([
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "flag",
+ operator: "=",
+ value: true,
+ },
+ ]);
+ // …and anything neither numeric nor boolean keeps the boolean diagnostic.
+ expect(lowerWith("scores.flag:positive").errors.length).toBeGreaterThan(0);
+ });
+
it("treats := (exact) on a categorical score as a category match", () => {
// `:=positive` must behave like the bare `:positive` (any-of category),
// not be rejected as a comparison.
@@ -723,6 +867,40 @@ describe("filterStateToQueryText", () => {
);
});
+ it("reverse-renders booleanObject score filters without rewriting legacy numeric filters", () => {
+ const booleanFilter: FilterState = [
+ {
+ type: "booleanObject",
+ column: "score_booleans",
+ key: "Boolean Flag",
+ operator: "=",
+ value: true,
+ },
+ {
+ type: "booleanObject",
+ column: "trace_score_booleans",
+ key: "traceFlag",
+ operator: "<>",
+ value: false,
+ },
+ ];
+ expect(filterStateToQueryText(booleanFilter).text).toBe(
+ 'scores."Boolean Flag":true -traceScores.traceFlag:false',
+ );
+
+ expect(
+ filterStateToQueryText([
+ {
+ type: "numberObject",
+ column: "scores_avg",
+ key: "Boolean Flag",
+ operator: "=",
+ value: 1,
+ },
+ ]).text,
+ ).toBe('scores."Boolean Flag":1');
+ });
+
it("serializes metadata equality as the bare form, not :=value", () => {
// `metadata.region:eu` lowers to a stringObject `=` filter; serializing it
// back must produce the bare `metadata.region:eu` the user typed — the
diff --git a/web/src/features/search-bar/lib/adapter.ts b/web/src/features/search-bar/lib/adapter.ts
index 27796f9124..8c1ce4a183 100644
--- a/web/src/features/search-bar/lib/adapter.ts
+++ b/web/src/features/search-bar/lib/adapter.ts
@@ -58,15 +58,17 @@ export type AstToFilterStateResult = {
export type ScoreTypeContext = {
numericScoreNames?: ReadonlySet<string>;
categoricalScoreNames?: ReadonlySet<string>;
+ booleanScoreNames?: ReadonlySet<string>;
traceNumericScoreNames?: ReadonlySet<string>;
traceCategoricalScoreNames?: ReadonlySet<string>;
+ traceBooleanScoreNames?: ReadonlySet<string>;
};
export function resolveScoreType(
ctx: ScoreTypeContext | undefined,
level: "observation" | "trace",
name: string,
-): "numeric" | "categorical" | "both" | "unknown" {
+): "numeric" | "categorical" | "boolean" | "both" | "unknown" {
if (ctx === undefined) return "unknown";
const numeric =
level === "trace" ? ctx.traceNumericScoreNames : ctx.numericScoreNames;
@@ -74,14 +76,29 @@ export function resolveScoreType(
level === "trace"
? ctx.traceCategoricalScoreNames
: ctx.categoricalScoreNames;
+ const boolean =
+ level === "trace" ? ctx.traceBooleanScoreNames : ctx.booleanScoreNames;
const isNum = numeric?.has(name) ?? false;
const isCat = categorical?.has(name) ?? false;
- if (isNum && isCat) return "both";
+ const isBool = boolean?.has(name) ?? false;
+ const typeCount = Number(isNum) + Number(isCat) + Number(isBool);
+ if (typeCount > 1) return "both";
if (isNum) return "numeric";
if (isCat) return "categorical";
+ if (isBool) return "boolean";
return "unknown";
}
+function isObservedBooleanScore(
+ ctx: ScoreTypeContext | undefined,
+ level: "observation" | "trace",
+ name: string,
+): boolean {
+ const boolean =
+ level === "trace" ? ctx?.traceBooleanScoreNames : ctx?.booleanScoreNames;
+ return boolean?.has(name) ?? false;
+}
+
/**
* A top-level OR whose children are all same-field single-value `=` filters
* collapses to one any-of filter node. Null otherwise.
@@ -669,10 +686,67 @@ function lowerScores(
});
};
+ const lowerBooleanScore = (): void => {
+ if (isComparison(node.op)) {
+ errors.push(
+ `${path} is boolean — comparison operators only apply to numeric scores`,
+ );
+ return;
+ }
+ if (node.values.length > 1) {
+ errors.push(
+ `${path} expects a single boolean value — grouped boolean values are not supported`,
+ );
+ return;
+ }
+ const raw = node.values[0]?.toLowerCase();
+ if (raw !== "true" && raw !== "false") {
+ errors.push(`${path} is boolean — use true or false`);
+ return;
+ }
+ out.push({
+ type: "booleanObject",
+ column: columns.boolean,
+ key,
+ operator: negated ? "<>" : "=",
+ value: raw === "true",
+ });
+ };
+
// Route by observed score TYPE when we know it — a categorical score with
// numeric labels (e.g. a 1–5 rating) must hit the categorical column, not
// scores_avg, or it silently targets a column with no data.
const scoreType = resolveScoreType(scoreTypes, level, key);
+ const allBooleanLiterals = node.values.every((v) => {
+ const raw = v.toLowerCase();
+ return raw === "true" || raw === "false";
+ });
+ if (
+ isObservedBooleanScore(scoreTypes, level, key) &&
+ allBooleanLiterals &&
+ !isComparison(node.op)
+ ) {
+ lowerBooleanScore();
+ return;
+ }
+ if (scoreType === "boolean") {
+ // Legacy-read compat: boolean scores also aggregate numerically (0/1)
+ // into scores_avg, and pre-boolean-filter URLs/saved views still carry
+ // numberObject filters on them. Numeric-shaped input keeps lowering
+ // numerically so that state stays renderable/editable; everything else
+ // gets the boolean diagnostic (never the categorical fallback — a boolean
+ // name has no data in score_categories).
+ const allNumericValues = node.values.every((v) =>
+ Number.isFinite(Number(v)),
+ );
+ if (isComparison(node.op) || node.op === "exact" || allNumericValues) {
+ lowerNumeric();
+ return;
+ }
+ lowerBooleanScore();
+ return;
+ }
+
if (scoreType === "categorical") {
// Comparisons (> < >= <=) are meaningless on a category. But exact (`:=x`)
// and the bare `=` form are both just an exact category match, so they
@@ -694,7 +768,11 @@ function lowerScores(
}
// '=' default: numeric when known-numeric, else value-syntax fallback
- // (all-numeric → numeric) for unknown/both.
+ // (all-numeric → numeric) for unknown/both. Known context-miss caveat: a
+ // booleanObject filter whose score name is not in the observed sets (time
+ // range, name-limit cap, saved view) renders as `scores.X:true` and
+ // re-lowers here to categoryOptions — the same context dependence the
+ // categorical kind has always had; eager score-name loading keeps this rare.
const allNumeric = node.values.every((v) => Number.isFinite(Number(v)));
if (scoreType === "numeric" || allNumeric) {
lowerNumeric();
diff --git a/web/src/features/search-bar/lib/ai-context.ts b/web/src/features/search-bar/lib/ai-context.ts
index 8c97af752c..36ad873cc7 100644
--- a/web/src/features/search-bar/lib/ai-context.ts
+++ b/web/src/features/search-bar/lib/ai-context.ts
@@ -23,8 +23,10 @@ const VALUE_COLUMNS: Array<{ col: string; label: string }> = [
{ col: "promptName", label: "promptName" },
{ col: "scores_avg", label: "scores.<name> (numeric)" },
{ col: "score_categories", label: "scores.<name> (categorical)" },
+ { col: "score_booleans", label: "scores.<name> (boolean)" },
{ col: "trace_scores_avg", label: "traceScores.<name> (numeric)" },
{ col: "trace_score_categories", label: "traceScores.<name> (categorical)" },
+ { col: "trace_score_booleans", label: "traceScores.<name> (boolean)" },
];
// Filter-options columns the AI prompt grounds on (lazy mode: requested when
diff --git a/web/src/features/search-bar/lib/completions.clienttest.ts b/web/src/features/search-bar/lib/completions.clienttest.ts
index 2a381541c0..c3b990ae3f 100644
--- a/web/src/features/search-bar/lib/completions.clienttest.ts
+++ b/web/src/features/search-bar/lib/completions.clienttest.ts
@@ -10,7 +10,10 @@ import {
type CompletionOption,
type InputCompletionContext,
} from "@/src/features/search-bar/lib/completions";
-import type { ObservedOptions } from "@/src/features/search-bar/lib/observed-options";
+import {
+ toObservedOptions,
+ type ObservedOptions,
+} from "@/src/features/search-bar/lib/observed-options";
const OBSERVED: ObservedOptions = {
level: [
@@ -20,6 +23,7 @@ const OBSERVED: ObservedOptions = {
environment: [{ value: "production" }, { value: "dev" }],
scores_avg: [{ value: "accuracy" }],
score_categories: [{ value: "feedback" }],
+ score_booleans: [{ value: "flag" }],
"score_categories.feedback": [{ value: "positive" }, { value: "negative" }],
"metadata.region": [{ value: "eu" }, { value: "us" }],
};
@@ -254,19 +258,41 @@ describe("planInputCompletions", () => {
const labels = flattenOptions(p).map((o) => o.label);
expect(labels).toContain("scores.accuracy");
expect(labels).toContain("scores.feedback");
+ expect(labels).toContain("scores.flag");
+ });
+
+ it("shows overlapping boolean score names as boolean-only", () => {
+ const observed = toObservedOptions(
+ {
+ scores_avg: [{ value: "flag" }],
+ score_categories: [],
+ score_booleans: [{ value: "flag" }],
+ },
+ false,
+ );
+
+ const option = flattenOptions(plan("scores.", 7, { observed })).find(
+ (o) => o.label === "scores.flag",
+ );
+
+ expect(option).toMatchObject({
+ label: "scores.flag",
+ detail: "boolean score",
+ });
});
it("suggests trace-score names for every accepted alias incl. singular tracescore.", () => {
// The parser resolves tracescore./tracescores./trace_scores.; each must also
// produce the score-name dropdown, or that spelling parses but suggests
// nothing. (The singular form was previously missing from PATH_PREFIXES.)
- // Both trace score-name columns are requested + returned together, so model
- // the categorical one as loaded-but-empty (lazy mode keys loading on column
- // presence, not value count).
+ // All three trace score-name columns are requested + returned together, so
+ // model the categorical/boolean ones as loaded-but-empty (lazy mode keys
+ // loading on column presence, not value count).
const observed = {
...OBSERVED,
trace_scores_avg: [{ value: "nps" }],
trace_score_categories: [],
+ trace_score_booleans: [],
};
for (const prefix of ["tracescore.", "tracescores.", "trace_scores."]) {
const p = plan(prefix, prefix.length, { observed });
@@ -285,6 +311,14 @@ describe("planInputCompletions", () => {
]);
});
+ it("suggests boolean score values", () => {
+ const p = plan("scores.flag:", 12);
+ const values = flattenOptions(p)
+ .filter((o) => o.kind === "value")
+ .map((o) => o.label);
+ expect(values).toEqual(["true", "false"]);
+ });
+
it("suggests metadata values for known keys", () => {
const p = plan("metadata.region:", 16);
const values = flattenOptions(p).filter((o) => o.kind === "value");
@@ -615,12 +649,16 @@ describe("planInputCompletions", () => {
expect(p?.requestColumns).toBeUndefined();
});
- it("requests both score-name columns and shows loading on a score path", () => {
+ it("requests all score-name columns and shows loading on a score path", () => {
const p = plan("scores.", 7, {
observed: { level: [{ value: "ERROR" }] },
});
expect(p?.loading).toBe(true);
- expect(p?.requestColumns).toEqual(["scores_avg", "score_categories"]);
+ expect(p?.requestColumns).toEqual([
+ "scores_avg",
+ "score_categories",
+ "score_booleans",
+ ]);
});
it("requests trace score-name columns while typing a trace score value", () => {
@@ -631,6 +669,7 @@ describe("planInputCompletions", () => {
expect(p?.requestColumns).toEqual([
"trace_scores_avg",
"trace_score_categories",
+ "trace_score_booleans",
]);
});
@@ -647,7 +686,11 @@ describe("planInputCompletions", () => {
const score = plan("scores.", 7, {
observed: { level: [{ value: "ERROR" }] },
- erroredColumns: new Set(["scores_avg", "score_categories"]),
+ erroredColumns: new Set([
+ "scores_avg",
+ "score_categories",
+ "score_booleans",
+ ]),
});
expect(score?.loading).not.toBe(true);
expect(score?.requestColumns).toBeUndefined();
diff --git a/web/src/features/search-bar/lib/completions.ts b/web/src/features/search-bar/lib/completions.ts
index 7bc0dc9dc4..6daf87e1d1 100644
--- a/web/src/features/search-bar/lib/completions.ts
+++ b/web/src/features/search-bar/lib/completions.ts
@@ -21,6 +21,7 @@ import {
} from "./langQ";
import {
FIELDS,
+ SCORE_COLUMNS,
nullableFields,
resolveField,
type FieldDef,
@@ -483,9 +484,17 @@ function keyPathOptions(
};
}
const numericColumn =
- kind.level === "trace" ? "trace_scores_avg" : "scores_avg";
+ kind.level === "trace"
+ ? SCORE_COLUMNS.trace.numeric
+ : SCORE_COLUMNS.observation.numeric;
const categoricalColumn =
- kind.level === "trace" ? "trace_score_categories" : "score_categories";
+ kind.level === "trace"
+ ? SCORE_COLUMNS.trace.categorical
+ : SCORE_COLUMNS.observation.categorical;
+ const booleanColumn =
+ kind.level === "trace"
+ ? SCORE_COLUMNS.trace.boolean
+ : SCORE_COLUMNS.observation.boolean;
const seen = new Map<string, string>();
for (const o of observedValues(observed, numericColumn))
seen.set(o.value, "numeric score");
@@ -495,6 +504,14 @@ function keyPathOptions(
seen.has(o.value) ? "numeric + categorical score" : "categorical score",
);
}
+ for (const o of observedValues(observed, booleanColumn)) {
+ seen.set(
+ o.value,
+ seen.has(o.value)
+ ? `${seen.get(o.value)} + boolean score`
+ : "boolean score",
+ );
+ }
const options = [...seen.entries()].map(([name, detail]) => ({
id: `key:${kind.canonical}${name}`,
kind: "field" as const,
@@ -595,16 +612,28 @@ function valueStageSections(input: ValueStageInput): {
case "scores": {
const numericColumn =
- ref.level === "trace" ? "trace_scores_avg" : "scores_avg";
+ ref.level === "trace"
+ ? SCORE_COLUMNS.trace.numeric
+ : SCORE_COLUMNS.observation.numeric;
const categoricalColumn =
- ref.level === "trace" ? "trace_score_categories" : "score_categories";
- // Routing a `scores.<name>:` value needs both score-name columns; request
- // and show a loading row while either is still streaming in.
- if (columnPending(numericColumn) || columnPending(categoricalColumn)) {
+ ref.level === "trace"
+ ? SCORE_COLUMNS.trace.categorical
+ : SCORE_COLUMNS.observation.categorical;
+ const booleanColumn =
+ ref.level === "trace"
+ ? SCORE_COLUMNS.trace.boolean
+ : SCORE_COLUMNS.observation.boolean;
+ // Routing a `scores.<name>:` value needs all three score-name columns;
+ // request and show a loading row while any is still streaming in.
+ if (
+ columnPending(numericColumn) ||
+ columnPending(categoricalColumn) ||
+ columnPending(booleanColumn)
+ ) {
return {
sections: [],
loading: true,
- requestColumns: [numericColumn, categoricalColumn],
+ requestColumns: [numericColumn, categoricalColumn, booleanColumn],
};
}
// Quoted for the example shown in the compare-op tooltip — a spaced score
@@ -617,11 +646,31 @@ function valueStageSections(input: ValueStageInput): {
const isNumeric = observedValues(observed, numericColumn).some(
(o) => o.value === ref.key,
);
+ const isBoolean = observedValues(observed, booleanColumn).some(
+ (o) => o.value === ref.key,
+ );
const categories = observedValues(
observed,
`${categoricalColumn}.${ref.key}`,
);
const sections: CompletionSection[] = [];
+ if (isBoolean) {
+ const all = [
+ {
+ id: "value:true",
+ kind: "value" as const,
+ label: "true",
+ value: "true",
+ },
+ {
+ id: "value:false",
+ kind: "value" as const,
+ label: "false",
+ value: "false",
+ },
+ ];
+ sections.push(...section(SECTION_VALUES, valueOptions(all, typed)));
+ }
if (categories.length > 0) {
const all = categories.map((o) => ({
id: `value:${o.value}`,
@@ -632,7 +681,11 @@ function valueStageSections(input: ValueStageInput): {
}));
sections.push(...section(SECTION_VALUES, valueOptions(all, typed)));
}
- if ((isNumeric || categories.length === 0) && typed.length === 0) {
+ if (
+ !isBoolean &&
+ (isNumeric || categories.length === 0) &&
+ typed.length === 0
+ ) {
sections.push(
...section(
SECTION_COMPARE_OPS,
@@ -991,28 +1044,31 @@ export function planInputCompletions(
// Dot paths (metadata./scores./traceScores.) suggest observed keys.
const path = pathKindOf(keyPart);
if (path !== null) {
- // Score-name suggestions need both score-name columns; request and show a
- // loading row while they stream in (lazy mode). Metadata keys are not
- // server-enumerated — they come from the client-side observed-metadata
+ // Score-name suggestions need all three score-name columns; request and
+ // show a loading row while they stream in (lazy mode). Metadata keys are
+ // not server-enumerated — they come from the client-side observed-metadata
// map (lib/metadata-paths.ts) — so there is nothing to request there.
if (path.kind.canonical !== "metadata.") {
- const numericColumn =
- path.kind.level === "trace" ? "trace_scores_avg" : "scores_avg";
- const categoricalColumn =
+ const scoreColumns =
path.kind.level === "trace"
- ? "trace_score_categories"
- : "score_categories";
+ ? SCORE_COLUMNS.trace
+ : SCORE_COLUMNS.observation;
+ const scoreNameColumns = [
+ scoreColumns.numeric,
+ scoreColumns.categorical,
+ scoreColumns.boolean,
+ ];
const scorePending = (column: string): boolean =>
!ctx.erroredColumns?.has(column) &&
(ctx.observed === undefined || !(column in ctx.observed));
- if (scorePending(numericColumn) || scorePending(categoricalColumn)) {
+ if (scoreNameColumns.some(scorePending)) {
return {
stage: "field",
from: bodyStart,
to,
loading: true,
sections: [],
- requestColumns: [numericColumn, categoricalColumn],
+ requestColumns: scoreNameColumns,
};
}
}
diff --git a/web/src/features/search-bar/lib/fields.ts b/web/src/features/search-bar/lib/fields.ts
index 8033af8707..e7ce8044df 100644
--- a/web/src/features/search-bar/lib/fields.ts
+++ b/web/src/features/search-bar/lib/fields.ts
@@ -109,10 +109,15 @@ export const HAS_KEY = "has";
/** Langfuse score filter columns (filter by score NAME via key-value ops). */
export const SCORE_COLUMNS = {
- observation: { numeric: "scores_avg", categorical: "score_categories" },
+ observation: {
+ numeric: "scores_avg",
+ categorical: "score_categories",
+ boolean: "score_booleans",
+ },
trace: {
numeric: "trace_scores_avg",
categorical: "trace_score_categories",
+ boolean: "trace_score_booleans",
},
} as const;
diff --git a/web/src/features/search-bar/lib/filter-state-to-query.ts b/web/src/features/search-bar/lib/filter-state-to-query.ts
index b03b01bb21..d5ccd5c88e 100644
--- a/web/src/features/search-bar/lib/filter-state-to-query.ts
+++ b/web/src/features/search-bar/lib/filter-state-to-query.ts
@@ -54,13 +54,15 @@ function scorePathOf(column: string, key: string): string | null {
// (`scores."Rouge Score"`); resolveField unquotes it on the way back.
if (
column === SCORE_COLUMNS.observation.numeric ||
- column === SCORE_COLUMNS.observation.categorical
+ column === SCORE_COLUMNS.observation.categorical ||
+ column === SCORE_COLUMNS.observation.boolean
) {
return `scores.${quoteIfNeeded(key)}`;
}
if (
column === SCORE_COLUMNS.trace.numeric ||
- column === SCORE_COLUMNS.trace.categorical
+ column === SCORE_COLUMNS.trace.categorical ||
+ column === SCORE_COLUMNS.trace.boolean
) {
return `traceScores.${quoteIfNeeded(key)}`;
}
@@ -199,6 +201,12 @@ function lowerSingle(filter: FilterState[number]): ASTNode | null {
const op = filter.operator === "=" ? "=" : filter.operator;
return filterNode(path, op, [String(filter.value)]);
}
+ case "booleanObject": {
+ const path = scorePathOf(filter.column, filter.key);
+ if (path === null) return null;
+ const node = filterNode(path, "=", [String(filter.value)]);
+ return filter.operator === "<>" ? negate(node) : node;
+ }
case "categoryOptions": {
const path = scorePathOf(filter.column, filter.key);
if (path === null || filter.value.length === 0) return null;
@@ -433,6 +441,8 @@ function normalizeValuesFor(
return values; // text — verbatim
}
if (ref.type === "scores") {
+ if (resolveScoreType(scoreTypes, ref.level, ref.key) === "boolean")
+ return values.map((v) => v.toLowerCase());
// Numeric / unknown scores get Number-canonicalized by lowerNumeric; a
// known-CATEGORICAL score keeps its label verbatim (a numeric-looking label
// like "2.0" must NOT be rewritten to "2"). normalizeNumberString only
diff --git a/web/src/features/search-bar/lib/observed-options.ts b/web/src/features/search-bar/lib/observed-options.ts
index f571625202..d08a1fbe9d 100644
--- a/web/src/features/search-bar/lib/observed-options.ts
+++ b/web/src/features/search-bar/lib/observed-options.ts
@@ -10,6 +10,7 @@
// withMetadataPathOptions, which fills the `metadata` key)
import type { ScoreTypeContext } from "./adapter";
+import { SCORE_COLUMNS } from "./fields";
export type ObservedValue = {
value: string;
@@ -42,6 +43,34 @@ function toObservedValues(options: RawOption[]): ObservedValue[] {
return out;
}
+function removeObservedValues(
+ options: ObservedValue[] | undefined,
+ excluded: ReadonlySet<string>,
+): ObservedValue[] | undefined {
+ if (!options || excluded.size === 0) return options;
+ return options.filter((option) => !excluded.has(option.value));
+}
+
+function normalizeScoreColumns(
+ out: ObservedOptions,
+ columns: (typeof SCORE_COLUMNS)["observation" | "trace"],
+): void {
+ const booleanNames = new Set(
+ (out[columns.boolean] ?? []).map((option) => option.value),
+ );
+
+ // Backend score option discovery keeps BOOLEAN names in numeric options for
+ // legacy consumers. Keep backend compatibility but make the search bar treat
+ // those names as boolean-only.
+ out[columns.numeric] =
+ removeObservedValues(out[columns.numeric], booleanNames) ?? [];
+}
+
+function normalizeScoreTypes(out: ObservedOptions): void {
+ normalizeScoreColumns(out, SCORE_COLUMNS.observation);
+ normalizeScoreColumns(out, SCORE_COLUMNS.trace);
+}
+
/**
* Flatten the sidebar filter-options shape into observed-value lists keyed
* the way the completion planner looks them up. Returns undefined while the
@@ -68,6 +97,7 @@ export function toObservedOptions(
.map((v) => ({ value: v }));
}
}
+ normalizeScoreTypes(out);
return out;
}
@@ -85,8 +115,10 @@ export function scoreTypeContextFromObserved(
return {
numericScoreNames: names("scores_avg"),
categoricalScoreNames: names("score_categories"),
+ booleanScoreNames: names("score_booleans"),
traceNumericScoreNames: names("trace_scores_avg"),
traceCategoricalScoreNames: names("trace_score_categories"),
+ traceBooleanScoreNames: names("trace_score_booleans"),
};
}
@@ -117,7 +149,12 @@ export function scoreTypeContextEqual(
return (
nameSetsEqual(a?.numericScoreNames, b?.numericScoreNames) &&
nameSetsEqual(a?.categoricalScoreNames, b?.categoricalScoreNames) &&
+ nameSetsEqual(a?.booleanScoreNames, b?.booleanScoreNames) &&
nameSetsEqual(a?.traceNumericScoreNames, b?.traceNumericScoreNames) &&
- nameSetsEqual(a?.traceCategoricalScoreNames, b?.traceCategoricalScoreNames)
+ nameSetsEqual(
+ a?.traceCategoricalScoreNames,
+ b?.traceCategoricalScoreNames,
+ ) &&
+ nameSetsEqual(a?.traceBooleanScoreNames, b?.traceBooleanScoreNames)
);
}
diff --git a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
index a7b85f87a9..a9da714c84 100644
--- a/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
+++ b/web/src/features/search-bar/lib/searchBarInvariants.clienttest.ts
@@ -41,6 +41,17 @@ const eventsView: RegistryUnderTest = {
traceNumericScoreNames: new Set(["nps"]),
traceCategoricalScoreNames: new Set(),
},
+ // Boolean-observed scores: boolean literals route to booleanObject while
+ // numeric shapes keep the legacy scores_avg lowering (old URLs/saved
+ // views), so both must hold the invariants under the same context.
+ {
+ numericScoreNames: new Set(),
+ categoricalScoreNames: new Set(),
+ booleanScoreNames: new Set(["accuracy"]),
+ traceNumericScoreNames: new Set(),
+ traceCategoricalScoreNames: new Set(),
+ traceBooleanScoreNames: new Set(["nps"]),
+ },
],
fieldValues: ["x", "ERROR", "5", "0.8", "2026-06-01", "true", "a b", "gpt-4"],
// Adversarial free text — the tokens the parser reserves/quotes. The bare
diff --git a/web/src/features/search-bar/server/buildFilterPrompt.ts b/web/src/features/search-bar/server/buildFilterPrompt.ts
index a27f2ab7f4..abd0b9c43c 100644
--- a/web/src/features/search-bar/server/buildFilterPrompt.ts
+++ b/web/src/features/search-bar/server/buildFilterPrompt.ts
@@ -186,8 +186,9 @@ Filter by score NAME via the "key" field. Default to OBSERVATION-level scores
unless the request clearly means trace-level scores.
- Numeric score: {"type": "numberObject", "column": "${SCORE_COLUMNS.observation.numeric}" (observation) or "${SCORE_COLUMNS.trace.numeric}" (trace), "key": "<score name>", "operator": ">" | "<" | ">=" | "<=" | "=", "value": <number>}
- Categorical score: {"type": "categoryOptions", "column": "${SCORE_COLUMNS.observation.categorical}" (observation) or "${SCORE_COLUMNS.trace.categorical}" (trace), "key": "<score name>", "operator": "any of" | "none of", "value": ["<category>"]}
+- Boolean score: {"type": "booleanObject", "column": "${SCORE_COLUMNS.observation.boolean}" (observation) or "${SCORE_COLUMNS.trace.boolean}" (trace), "key": "<score name>", "operator": "=" | "<>", "value": true | false}
-NEVER use ${SCORE_COLUMNS.observation.numeric} / ${SCORE_COLUMNS.observation.categorical} / ${SCORE_COLUMNS.trace.numeric} / ${SCORE_COLUMNS.trace.categorical} as a plain column (no bare {"type":"number","column":"${SCORE_COLUMNS.observation.numeric}"} etc.) — they REQUIRE the keyed numberObject/categoryOptions shape above with the score name in "key". Only use a score name that appears in the observed data; do not invent one.
+NEVER use ${SCORE_COLUMNS.observation.numeric} / ${SCORE_COLUMNS.observation.categorical} / ${SCORE_COLUMNS.observation.boolean} / ${SCORE_COLUMNS.trace.numeric} / ${SCORE_COLUMNS.trace.categorical} / ${SCORE_COLUMNS.trace.boolean} as a plain column (no bare {"type":"number","column":"${SCORE_COLUMNS.observation.numeric}"} etc.) — they REQUIRE the keyed numberObject/categoryOptions/booleanObject shape above with the score name in "key". Only use a score name that appears in the observed data; do not invent one.
## Null checks
diff --git a/web/src/features/search-bar/server/parseFilterCompletion.ts b/web/src/features/search-bar/server/parseFilterCompletion.ts
index 4c12fd0a6b..36de7ad44f 100644
--- a/web/src/features/search-bar/server/parseFilterCompletion.ts
+++ b/web/src/features/search-bar/server/parseFilterCompletion.ts
@@ -26,6 +26,7 @@ const COMPATIBLE_FILTER_TYPES: Record<string, readonly string[]> = {
boolean: ["boolean"],
stringObject: ["stringObject"],
numberObject: ["numberObject"],
+ booleanObject: ["booleanObject"],
categoryOptions: ["categoryOptions", "stringOptions"],
};
diff --git a/web/src/server/api/definitions/scoresTable.ts b/web/src/server/api/definitions/scoresTable.ts
index 6a1d540be8..1549d13870 100644
--- a/web/src/server/api/definitions/scoresTable.ts
+++ b/web/src/server/api/definitions/scoresTable.ts
@@ -13,6 +13,7 @@ export type ScoreOptions = {
traceName: Array<SingleValueOption>;
userId: Array<SingleValueOption>;
stringValue: Array<SingleValueOption>;
+ booleanValue: Array<SingleValueOption>;
};
export function scoresTableColsWithOptions(
@@ -34,6 +35,9 @@ export function scoresTableColsWithOptions(
if (col.id === "stringValue") {
return formatColumnOptions(col, options?.stringValue ?? []);
}
+ if (col.id === "booleanValue") {
+ return formatColumnOptions(col, options?.booleanValue ?? []);
+ }
return col;
});
}
diff --git a/web/src/server/api/routers/generations/filterOptionsQuery.ts b/web/src/server/api/routers/generations/filterOptionsQuery.ts
index 8679a786de..5e133e88b7 100644
--- a/web/src/server/api/routers/generations/filterOptionsQuery.ts
+++ b/web/src/server/api/routers/generations/filterOptionsQuery.ts
@@ -8,6 +8,7 @@ import {
import { protectedProjectProcedure } from "@/src/server/api/trpc";
import {
getCategoricalScoresGroupedByName,
+ getBooleanScoresGroupedByName,
getObservationsGroupedByModel,
getObservationsGroupedByModelId,
getObservationsGroupedByName,
@@ -68,6 +69,7 @@ export const filterOptionsQuery = protectedProjectProcedure
const [
numericScoreNames,
categoricalScoreNames,
+ booleanScoreNames,
model,
name,
promptNames,
@@ -81,6 +83,7 @@ export const filterOptionsQuery = protectedProjectProcedure
getNumericScoresGroupedByName(input.projectId, traceTimestampFilters),
// categorical scores
getCategoricalScoresGroupedByName(input.projectId, traceTimestampFilters),
+ getBooleanScoresGroupedByName(input.projectId, traceTimestampFilters),
//model
getObservationsGroupedByModel(input.projectId, startTimeFilter ?? []),
//name
@@ -129,6 +132,7 @@ export const filterOptionsQuery = protectedProjectProcedure
})),
scores_avg: numericScoreNames.map((score) => score.name),
score_categories: categoricalScoreNames,
+ score_booleans: booleanScoreNames.map((score) => score.name),
promptName: promptNames
.filter((i) => i.promptName !== null)
.map((i) => ({
diff --git a/web/src/server/api/routers/scores.ts b/web/src/server/api/routers/scores.ts
index 7da2117f36..59bcc58416 100644
--- a/web/src/server/api/routers/scores.ts
+++ b/web/src/server/api/routers/scores.ts
@@ -100,6 +100,8 @@ type AllScoresFromEventsReturnType = Omit<ScoreDomain, "metadata"> & {
hasMetadata: boolean;
};
+const BOOLEAN_SCORE_VALUE_OPTIONS = [{ value: "true" }, { value: "false" }];
+
export const scoresRouter = createTRPCRouter({
/**
* Get all scores for a project, meant for internal use and *excludes metadata of scores*
@@ -366,6 +368,7 @@ export const scoresRouter = createTRPCRouter({
count: Number(u.count),
})),
stringValue: stringValues,
+ booleanValue: BOOLEAN_SCORE_VALUE_OPTIONS,
};
}),
filterOptions: protectedProjectProcedure
@@ -408,6 +411,7 @@ export const scoresRouter = createTRPCRouter({
})),
userId: userIds.map((u) => ({ value: u.user, count: u.count })),
stringValue: stringValues,
+ booleanValue: BOOLEAN_SCORE_VALUE_OPTIONS,
};
}),
deleteMany: protectedProjectProcedure
diff --git a/web/src/server/api/routers/sessions.ts b/web/src/server/api/routers/sessions.ts
index fc09812a18..ac9338b749 100644
--- a/web/src/server/api/routers/sessions.ts
+++ b/web/src/server/api/routers/sessions.ts
@@ -42,6 +42,7 @@ import {
hasAnySession,
getScoresForSessions,
getNumericScoresGroupedByName,
+ getBooleanScoresGroupedByName,
getCategoricalScoresGroupedByName,
tracesTableUiColumnDefinitions,
getEventsGroupedByUserId,
@@ -544,27 +545,33 @@ export const sessionRouter = createTRPCRouter({
}))
: [];
- const [userIds, tags, numericScoreNames, categoricalScoreNames] =
- await Promise.all([
- getTracesGroupedByUsers(
- input.projectId,
- filter,
- undefined,
- 1000,
- 0,
- columns,
- ),
- getTracesGroupedByTags({
- projectId: input.projectId,
- filter,
- columns,
- }),
- getNumericScoresGroupedByName(input.projectId, scoreTimestampFilter),
- getCategoricalScoresGroupedByName(
- input.projectId,
- scoreTimestampFilter,
- ),
- ]);
+ const [
+ userIds,
+ tags,
+ numericScoreNames,
+ categoricalScoreNames,
+ booleanScoreNames,
+ ] = await Promise.all([
+ getTracesGroupedByUsers(
+ input.projectId,
+ filter,
+ undefined,
+ 1000,
+ 0,
+ columns,
+ ),
+ getTracesGroupedByTags({
+ projectId: input.projectId,
+ filter,
+ columns,
+ }),
+ getNumericScoresGroupedByName(input.projectId, scoreTimestampFilter),
+ getCategoricalScoresGroupedByName(
+ input.projectId,
+ scoreTimestampFilter,
+ ),
+ getBooleanScoresGroupedByName(input.projectId, scoreTimestampFilter),
+ ]);
return {
userIds: userIds.map((row) => ({
@@ -575,6 +582,7 @@ export const sessionRouter = createTRPCRouter({
tags: tags,
scores_avg: numericScoreNames.map((s) => s.name),
score_categories: categoricalScoreNames,
+ score_booleans: booleanScoreNames.map((s) => s.name),
};
}),
filterOptionsFromEvents: protectedProjectProcedure
@@ -613,16 +621,22 @@ export const sessionRouter = createTRPCRouter({
}))
: [];
- const [userIds, tags, numericScoreNames, categoricalScoreNames] =
- await Promise.all([
- getEventsGroupedByUserId(input.projectId, eventsFilter),
- getEventsGroupedByTraceTags(input.projectId, eventsFilter),
- getNumericScoresGroupedByName(input.projectId, scoreTimestampFilter),
- getCategoricalScoresGroupedByName(
- input.projectId,
- scoreTimestampFilter,
- ),
- ]);
+ const [
+ userIds,
+ tags,
+ numericScoreNames,
+ categoricalScoreNames,
+ booleanScoreNames,
+ ] = await Promise.all([
+ getEventsGroupedByUserId(input.projectId, eventsFilter),
+ getEventsGroupedByTraceTags(input.projectId, eventsFilter),
+ getNumericScoresGroupedByName(input.projectId, scoreTimestampFilter),
+ getCategoricalScoresGroupedByName(
+ input.projectId,
+ scoreTimestampFilter,
+ ),
+ getBooleanScoresGroupedByName(input.projectId, scoreTimestampFilter),
+ ]);
return {
userIds: userIds.map((row) => ({
@@ -635,6 +649,7 @@ export const sessionRouter = createTRPCRouter({
})),
scores_avg: numericScoreNames.map((s) => s.name),
score_categories: categoricalScoreNames,
+ score_booleans: booleanScoreNames.map((s) => s.name),
};
}),
byIdWithScores: protectedGetSessionProcedure
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index 5fee0304bb..d5d15df22e 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -33,6 +33,7 @@ import {
getTracesTableCount,
getScoresForTraces,
getNumericScoresGroupedByName,
+ getBooleanScoresGroupedByName,
getTracesGroupedByName,
getTracesGroupedByTags,
getObservationsForTrace,
@@ -295,6 +296,7 @@ export const traceRouter = createTRPCRouter({
const [
numericScoreNames,
categoricalScoreNames,
+ booleanScoreNames,
traceNames,
tags,
userIds,
@@ -305,6 +307,7 @@ export const traceRouter = createTRPCRouter({
input.projectId,
traceScopedScoreFilters,
),
+ getBooleanScoresGroupedByName(input.projectId, traceScopedScoreFilters),
getTracesGroupedByName(
input.projectId,
tracesTableUiColumnDefinitions,
@@ -334,6 +337,7 @@ export const traceRouter = createTRPCRouter({
name: traceNames.map((n) => ({ value: n.name, count: n.count })),
scores_avg: numericScoreNames.map((s) => s.name),
score_categories: categoricalScoreNames,
+ score_booleans: booleanScoreNames.map((s) => s.name),
tags: tags,
users: userIds.map((u) => ({
value: u.user,
diff --git a/worker/src/__tests__/batchExport.test.ts b/worker/src/__tests__/batchExport.test.ts
index 3ee13d9b27..55dc6bfd3e 100644
--- a/worker/src/__tests__/batchExport.test.ts
+++ b/worker/src/__tests__/batchExport.test.ts
@@ -360,6 +360,146 @@ describe("batch export test suite", () => {
expect(mediumAccuracyRow?.accuracy).toEqual([0.75]);
});
+ it("should export observations filtered by boolean scores", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const trace = createTrace({
+ project_id: projectId,
+ id: randomUUID(),
+ });
+
+ await createTracesCh([trace]);
+
+ const observations = [
+ createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "flagged",
+ start_time: new Date("2024-01-01").getTime(),
+ }),
+ createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "not-flagged",
+ start_time: new Date("2024-01-02").getTime(),
+ }),
+ createObservation({
+ project_id: projectId,
+ trace_id: trace.id,
+ id: randomUUID(),
+ type: "GENERATION",
+ name: "unscored",
+ start_time: new Date("2024-01-03").getTime(),
+ }),
+ ];
+
+ await createObservationsCh(observations);
+
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observations[0].id,
+ name: "is_hallucination",
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: trace.id,
+ observation_id: observations[1].id,
+ name: "is_hallucination",
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ }),
+ ]);
+
+ const stream = await getObservationStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "booleanObject",
+ column: "Scores (boolean)",
+ key: "is_hallucination",
+ operator: "=",
+ value: true,
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].name).toBe("flagged");
+ });
+
+ it("should export traces filtered by boolean scores", async () => {
+ const { projectId } = await createOrgProjectAndApiKey();
+
+ const traces = [
+ createTrace({ project_id: projectId, id: randomUUID() }),
+ createTrace({ project_id: projectId, id: randomUUID() }),
+ createTrace({ project_id: projectId, id: randomUUID() }),
+ ];
+
+ await createTracesCh(traces);
+
+ await createScoresCh([
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traces[0].id,
+ name: "is_valid",
+ value: 1,
+ string_value: "True",
+ data_type: "BOOLEAN",
+ observation_id: null,
+ }),
+ createTraceScore({
+ project_id: projectId,
+ trace_id: traces[1].id,
+ name: "is_valid",
+ value: 0,
+ string_value: "False",
+ data_type: "BOOLEAN",
+ observation_id: null,
+ }),
+ ]);
+
+ const stream = await getTraceStream({
+ projectId: projectId,
+ cutoffCreatedAt: new Date(Date.now() + 1000 * 60 * 60 * 24),
+ filter: [
+ {
+ type: "booleanObject",
+ column: "Scores (boolean)",
+ key: "is_valid",
+ operator: "=",
+ value: true,
+ },
+ ],
+ });
+
+ const rows: any[] = [];
+
+ for await (const chunk of stream) {
+ rows.push(chunk);
+ }
+
+ expect(rows).toHaveLength(1);
+ expect(rows[0].id).toBe(traces[0].id);
+ });
+
it("should export sessions", async () => {
const { projectId } = await createOrgProjectAndApiKey();
diff --git a/worker/src/__tests__/evalService.filtering.test.ts b/worker/src/__tests__/evalService.filtering.test.ts
index 5ff7ab0bf4..82467e0153 100644
--- a/worker/src/__tests__/evalService.filtering.test.ts
+++ b/worker/src/__tests__/evalService.filtering.test.ts
@@ -658,7 +658,7 @@ describe("test eval filtering", () => {
expect(jobs[0].status.toString()).toBe("PENDING");
}, 10_000);
- test("cached trace preserves metadata for in-memory filter evaluation", async ({
+ test("cached trace preserves filterable fields for in-memory filter evaluation", async ({
expect,
projectId,
traceId1,
@@ -669,13 +669,14 @@ describe("test eval filtering", () => {
// Create a trace with metadata
await upsertTrace({
id: traceId1,
+ bookmarked: true,
metadata: { tier: "premium" },
});
// Create TWO job configs so configs.length > 1, triggering the cached trace path
// (getTraceById is called with excludeInputOutput: true)
await configureJob({
- scoreName: "score-with-metadata-filter",
+ scoreName: "score-with-metadata-and-boolean-filter",
filter: [
{
type: "stringObject",
@@ -683,7 +684,13 @@ describe("test eval filtering", () => {
value: "premium",
column: "metadata",
operator: "=",
- },
+ } satisfies z.infer<typeof singleFilter>,
+ {
+ type: "boolean",
+ value: true,
+ column: "bookmarked",
+ operator: "=",
+ } satisfies z.infer<typeof singleFilter>,
],
});
await configureJob({
@@ -698,7 +705,7 @@ describe("test eval filtering", () => {
});
const jobs = await getJobs();
- // Both configs should produce a job — the metadata filter should match
+ // Both configs should produce a job — both in-memory filters should match
expect(jobs.length).toBe(2);
}, 10_000);
diff --git a/worker/src/__tests__/inMemoryFilterService.test.ts b/worker/src/__tests__/inMemoryFilterService.test.ts
index 9ffa5fd668..fe2957c8b9 100644
--- a/worker/src/__tests__/inMemoryFilterService.test.ts
+++ b/worker/src/__tests__/inMemoryFilterService.test.ts
@@ -23,6 +23,7 @@ describe("InMemoryFilterService", () => {
precision: 0.87,
recall: 0.92,
},
+ scoreBooleans: ["flag:true", "other:false"],
categories: {
type: "classification",
model: "gpt-4",
@@ -61,6 +62,8 @@ describe("InMemoryFilterService", () => {
return data.metadata;
case "scores":
return data.scores;
+ case "scoreBooleans":
+ return data.scoreBooleans;
case "categories":
return data.categories;
case "cost":
@@ -891,6 +894,40 @@ describe("InMemoryFilterService", () => {
).toBe(false);
});
+ test("evaluates booleanObject filters correctly", () => {
+ expect(
+ InMemoryFilterService.evaluateFilter(
+ mockData,
+ [
+ {
+ column: "scoreBooleans",
+ type: "booleanObject",
+ key: "flag",
+ operator: "=",
+ value: true,
+ },
+ ],
+ fieldMapper,
+ ),
+ ).toBe(true);
+
+ expect(
+ InMemoryFilterService.evaluateFilter(
+ mockData,
+ [
+ {
+ column: "scoreBooleans",
+ type: "booleanObject",
+ key: "flag",
+ operator: "<>",
+ value: false,
+ },
+ ],
+ fieldMapper,
+ ),
+ ).toBe(true);
+ });
+
test("evaluates null filters correctly", () => {
const dataWithNulls = { ...mockData, release: null };
diff --git a/worker/src/features/database-read-stream/observation-stream.ts b/worker/src/features/database-read-stream/observation-stream.ts
index 221e651f51..6224c3fc6c 100644
--- a/worker/src/features/database-read-stream/observation-stream.ts
+++ b/worker/src/features/database-read-stream/observation-stream.ts
@@ -25,6 +25,7 @@ import {
shouldSkipObservationsFinal,
EventsQueryBuilder,
eventsScoresAggregation,
+ scoreBooleansAggregation,
} from "@langfuse/shared/src/server";
import { Readable } from "stream";
import { env } from "../../env";
@@ -170,7 +171,9 @@ export const getObservationStream = async (
groupArrayIf(
tuple(name, string_value, data_type),
data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
- ) AS score_categories_tuples
+ ) AS score_categories_tuples,
+ -- boolean score existence entries for booleanObject filters (has())
+ ${scoreBooleansAggregation()} AS score_booleans
FROM (
SELECT
trace_id,
diff --git a/worker/src/features/database-read-stream/trace-stream.ts b/worker/src/features/database-read-stream/trace-stream.ts
index 388415301f..011aa3fa13 100644
--- a/worker/src/features/database-read-stream/trace-stream.ts
+++ b/worker/src/features/database-read-stream/trace-stream.ts
@@ -13,6 +13,7 @@ import {
tracesTableUiColumnDefinitions,
clickhouseSearchCondition,
parseClickhouseUTCDateTimeFormat,
+ scoreBooleansAggregation,
StringFilter,
} from "@langfuse/shared/src/server";
import { Readable } from "stream";
@@ -135,7 +136,9 @@ export const getTraceStream = async (props: {
groupArrayIf(
tuple(name, string_value, data_type),
data_type IN ('CATEGORICAL', 'TEXT') AND notEmpty(string_value)
- ) AS score_categories_tuples
+ ) AS score_categories_tuples,
+ -- boolean score existence entries for booleanObject filters (has())
+ ${scoreBooleansAggregation()} AS score_booleans
FROM (
SELECT
project_id,