Skip to content

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

fix(tracing): reject searches without search types (#15273)

Valery Meleshkin2dc3885c901c
diff --git a/packages/shared/src/features/batchAction/types.ts b/packages/shared/src/features/batchAction/types.ts
index 1e96e7dbc6..a8a9bdc163 100644
--- a/packages/shared/src/features/batchAction/types.ts
+++ b/packages/shared/src/features/batchAction/types.ts
@@ -2,7 +2,11 @@ import z from "zod";
import { singleFilter } from "../../interfaces/filters";
import { orderBy } from "../../interfaces/orderBy";
import { BatchTableNames } from "../../interfaces/tableNames";
-import { TracingSearchType } from "../../interfaces/search";
+import {
+ hasValidTracingSearchTypes,
+ TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ TracingSearchType,
+} from "../../interfaces/search";
export enum BatchActionType {
Create = "create",
@@ -31,17 +35,22 @@ export enum ActionId {
const ActionIdSchema = z.enum(ActionId);
-export const BatchActionQuerySchema = z.object({
- filter: z.array(singleFilter).nullable(),
- orderBy,
- searchQuery: z.string().optional(),
- searchType: z.array(TracingSearchType).optional(),
- pathPrefix: z.string().optional(),
- // Routes worker reads to the events table instead of the legacy tables.
- // The v4 events view declares it and the server validates the declaration;
- // otherwise createBatchActionJob snapshots the user's v4 beta flag.
- useEventsTable: z.boolean().optional(),
-});
+export const BatchActionQuerySchema = z
+ .object({
+ filter: z.array(singleFilter).nullable(),
+ orderBy,
+ searchQuery: z.string().optional(),
+ searchType: z.array(TracingSearchType).optional(),
+ pathPrefix: z.string().optional(),
+ // Routes worker reads to the events table instead of the legacy tables.
+ // The v4 events view declares it and the server validates the declaration;
+ // otherwise createBatchActionJob snapshots the user's v4 beta flag.
+ useEventsTable: z.boolean().optional(),
+ })
+ .refine(hasValidTracingSearchTypes, {
+ message: TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ path: ["searchType"],
+ });
export type BatchActionQuery = z.infer<typeof BatchActionQuerySchema>;
diff --git a/packages/shared/src/features/batchExport/types.ts b/packages/shared/src/features/batchExport/types.ts
index 3971a79600..09012304bb 100644
--- a/packages/shared/src/features/batchExport/types.ts
+++ b/packages/shared/src/features/batchExport/types.ts
@@ -5,7 +5,11 @@ import { BatchExport } from "@prisma/client";
import { singleFilter } from "../../interfaces/filters";
import { orderBy } from "../../interfaces/orderBy";
import { BatchTableNames } from "../../interfaces/tableNames";
-import { TracingSearchType } from "../../interfaces/search";
+import {
+ hasValidTracingSearchTypes,
+ TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ TracingSearchType,
+} from "../../interfaces/search";
export enum BatchExportStatus {
QUEUED = "QUEUED",
@@ -65,6 +69,14 @@ export const BatchExportQuerySchema = z
// BatchExportQueryType is shared with the batch-action read stream (which
// handles every table), so a narrowed type breaks the worker typecheck.
.superRefine((query, ctx) => {
+ if (!hasValidTracingSearchTypes(query)) {
+ ctx.addIssue({
+ code: "custom",
+ path: ["searchType"],
+ message: TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ });
+ }
+
if (query.tableName === BatchTableNames.Datasets) {
ctx.addIssue({
code: "custom",
diff --git a/packages/shared/src/interfaces/search.ts b/packages/shared/src/interfaces/search.ts
index f7206fa436..89835a8cb0 100644
--- a/packages/shared/src/interfaces/search.ts
+++ b/packages/shared/src/interfaces/search.ts
@@ -4,3 +4,14 @@ export const TracingSearchType = z.enum(["id", "content", "input", "output"]);
// id: for searching smaller columns like IDs, types, and other metadata
// content: for searching input/output text of functions traced via OpenTelemetry
export type TracingSearchType = z.infer<typeof TracingSearchType>;
+
+export const TRACING_SEARCH_TYPE_REQUIRED_MESSAGE =
+ "At least one search type is required when searching tracing data";
+
+export const hasValidTracingSearchTypes = ({
+ searchQuery,
+ searchType,
+}: {
+ searchQuery?: string | null;
+ searchType?: TracingSearchType[] | null;
+}) => !searchQuery || !searchType || searchType.length > 0;
diff --git a/packages/shared/src/server/queries/clickhouse-sql/search.ts b/packages/shared/src/server/queries/clickhouse-sql/search.ts
index 13a888312a..3df9d6b455 100644
--- a/packages/shared/src/server/queries/clickhouse-sql/search.ts
+++ b/packages/shared/src/server/queries/clickhouse-sql/search.ts
@@ -1,4 +1,9 @@
-import { TracingSearchType } from "../../../interfaces/search";
+import { InvalidRequestError } from "../../../errors";
+import {
+ hasValidTracingSearchTypes,
+ TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ type TracingSearchType,
+} from "../../../interfaces/search";
import { ftsTextTokenConjunct } from "./fts";
const regexIndefiniteCharacters = "%";
@@ -49,6 +54,10 @@ export const clickhouseSearchCondition = ({
searchColumns,
useEventsTablePath = false,
}: ClickhouseSearchConditionOptions) => {
+ if (!hasValidTracingSearchTypes({ searchQuery: query, searchType })) {
+ throw new InvalidRequestError(TRACING_SEARCH_TYPE_REQUIRED_MESSAGE);
+ }
+
const prefix = tablePrefix ? `${tablePrefix}.` : "";
const ilikeWithPrefilter = (col: string, param = "{searchString: String}") =>
diff --git a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts
index 2c32c6f819..a0ce401747 100644
--- a/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts
+++ b/web/src/__tests__/server/clickhouseSearchCondition.servertest.ts
@@ -1,5 +1,5 @@
import { env } from "@/src/env.mjs";
-import { type TracingSearchType } from "@langfuse/shared";
+import { InvalidRequestError, type TracingSearchType } from "@langfuse/shared";
import {
clickhouseSearchCondition,
createEvent,
@@ -67,6 +67,24 @@ const matchingIds = async (opts: {
};
describe("clickhouseSearchCondition", () => {
+ it("rejects a search query without any search types", () => {
+ expect(() =>
+ clickhouseSearchCondition({
+ query: "alpha",
+ searchType: [],
+ }),
+ ).toThrow(InvalidRequestError);
+ });
+
+ it("allows an empty search type list when there is no search query", () => {
+ expect(
+ clickhouseSearchCondition({
+ query: undefined,
+ searchType: [],
+ }),
+ ).toMatchObject({ query: "", params: {} });
+ });
+
it.each([
{ query: undefined, searchType: ["content"], expected: false },
{ query: "alpha", searchType: undefined, expected: false },
diff --git a/web/src/__tests__/server/traces-trpc.servertest.ts b/web/src/__tests__/server/traces-trpc.servertest.ts
index 8694404091..bb58c77621 100644
--- a/web/src/__tests__/server/traces-trpc.servertest.ts
+++ b/web/src/__tests__/server/traces-trpc.servertest.ts
@@ -81,6 +81,51 @@ describe("traces trpc", () => {
});
describe("traces.all", () => {
+ it("rejects a search query without any search types", async () => {
+ await expect(
+ caller.traces.all({
+ projectId,
+ filter: null,
+ searchQuery: "trace-id",
+ searchType: [],
+ page: 0,
+ limit: 50,
+ orderBy: {
+ column: "timestamp",
+ order: "DESC",
+ },
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
+ it("rejects a legacy observation search without any search types", async () => {
+ await expect(
+ caller.generations.all({
+ projectId,
+ filter: [],
+ searchQuery: "observation-id",
+ searchType: [],
+ page: 0,
+ limit: 50,
+ orderBy: null,
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
+ it("rejects a v4 event search without any search types", async () => {
+ await expect(
+ caller.events.all({
+ projectId,
+ filter: [],
+ searchQuery: "event-id",
+ searchType: [],
+ page: 0,
+ limit: 50,
+ orderBy: null,
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
it("ignores legacy full-text-only search when legacy IO search is disabled", async () => {
mutableEnv.LANGFUSE_DISABLE_LEGACY_TRACING_IO_SEARCH = "true";
const tag = `legacy-io-search-disabled-${randomUUID()}`;
diff --git a/web/src/__tests__/server/unit/tracing-search-validation.servertest.ts b/web/src/__tests__/server/unit/tracing-search-validation.servertest.ts
new file mode 100644
index 0000000000..4be197f9ed
--- /dev/null
+++ b/web/src/__tests__/server/unit/tracing-search-validation.servertest.ts
@@ -0,0 +1,73 @@
+import {
+ BatchActionQuerySchema,
+ BatchExportQuerySchema,
+ BatchTableNames,
+} from "@langfuse/shared";
+import { GenerationTableOptions } from "@/src/server/api/routers/generations/utils/GenerationTableOptions";
+import { EventsTableOptions } from "@/src/features/events/server/types";
+
+describe("tracing search validation", () => {
+ const invalidSearch = {
+ searchQuery: "alpha",
+ searchType: [],
+ };
+
+ it.each([
+ {
+ name: "legacy observation table",
+ schema: GenerationTableOptions,
+ input: {
+ projectId: "project-id",
+ filter: [],
+ orderBy: null,
+ ...invalidSearch,
+ },
+ },
+ {
+ name: "v4 events table",
+ schema: EventsTableOptions,
+ input: {
+ projectId: "project-id",
+ filter: [],
+ orderBy: null,
+ ...invalidSearch,
+ },
+ },
+ {
+ name: "batch action",
+ schema: BatchActionQuerySchema,
+ input: {
+ filter: null,
+ orderBy: null,
+ ...invalidSearch,
+ },
+ },
+ {
+ name: "batch export",
+ schema: BatchExportQuerySchema,
+ input: {
+ tableName: BatchTableNames.Traces,
+ filter: null,
+ orderBy: null,
+ ...invalidSearch,
+ },
+ },
+ ])("rejects an empty search type list for $name", ({ schema, input }) => {
+ expect(schema.safeParse(input).success).toBe(false);
+ });
+
+ it.each([GenerationTableOptions, EventsTableOptions])(
+ "allows an empty search type list when the query is empty",
+ (schema) => {
+ expect(
+ schema.safeParse({
+ projectId: "project-id",
+ filter: [],
+ orderBy: null,
+ searchQuery: "",
+ searchType: [],
+ }).success,
+ ).toBe(true);
+ },
+ );
+});
diff --git a/web/src/features/events/server/eventsRouter.ts b/web/src/features/events/server/eventsRouter.ts
index 1ce5d02038..f25826258e 100644
--- a/web/src/features/events/server/eventsRouter.ts
+++ b/web/src/features/events/server/eventsRouter.ts
@@ -41,7 +41,7 @@ import {
} from "@/src/features/trace-graph-view/types";
import type * as opentelemetry from "@opentelemetry/api";
-const GetAllEventsInput = EventsTableOptions.extend({
+const GetAllEventsInput = EventsTableOptions.safeExtend({
...paginationZod,
});
diff --git a/web/src/features/events/server/types.ts b/web/src/features/events/server/types.ts
index e267a2fa8d..0c85fb13aa 100644
--- a/web/src/features/events/server/types.ts
+++ b/web/src/features/events/server/types.ts
@@ -1,10 +1,21 @@
import { z } from "zod";
-import { singleFilter, TracingSearchType, orderBy } from "@langfuse/shared";
+import {
+ hasValidTracingSearchTypes,
+ singleFilter,
+ TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ TracingSearchType,
+ orderBy,
+} from "@langfuse/shared";
-export const EventsTableOptions = z.object({
- projectId: z.string(), // Required for protectedProjectProcedure
- filter: z.array(singleFilter),
- searchQuery: z.string().nullable(),
- searchType: z.array(TracingSearchType),
- orderBy: orderBy,
-});
+export const EventsTableOptions = z
+ .object({
+ projectId: z.string(), // Required for protectedProjectProcedure
+ filter: z.array(singleFilter),
+ searchQuery: z.string().nullable(),
+ searchType: z.array(TracingSearchType),
+ orderBy: orderBy,
+ })
+ .refine(hasValidTracingSearchTypes, {
+ message: TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ path: ["searchType"],
+ });
diff --git a/web/src/server/api/routers/generations/getAllQueries.ts b/web/src/server/api/routers/generations/getAllQueries.ts
index acc1d570e1..d53afb95a6 100644
--- a/web/src/server/api/routers/generations/getAllQueries.ts
+++ b/web/src/server/api/routers/generations/getAllQueries.ts
@@ -7,7 +7,7 @@ import { getObservationsTableCount } from "@langfuse/shared/src/server";
import { applyCommentFilters } from "@langfuse/shared/src/server";
import { sanitizeLegacyTracingSearch } from "@/src/features/traces/server/legacyIoSearch";
-const GetAllGenerationsInput = GenerationTableOptions.extend({
+const GetAllGenerationsInput = GenerationTableOptions.safeExtend({
...paginationZod,
});
diff --git a/web/src/server/api/routers/generations/utils/GenerationTableOptions.ts b/web/src/server/api/routers/generations/utils/GenerationTableOptions.ts
index 01b523e56c..76b85773f4 100644
--- a/web/src/server/api/routers/generations/utils/GenerationTableOptions.ts
+++ b/web/src/server/api/routers/generations/utils/GenerationTableOptions.ts
@@ -1,11 +1,21 @@
import { z } from "zod";
-import { singleFilter, TracingSearchType } from "@langfuse/shared";
+import {
+ hasValidTracingSearchTypes,
+ singleFilter,
+ TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ TracingSearchType,
+} from "@langfuse/shared";
import { orderBy } from "@langfuse/shared";
-export const GenerationTableOptions = z.object({
- projectId: z.string(), // Required for protectedProjectProcedure
- filter: z.array(singleFilter),
- searchQuery: z.string().nullable(),
- searchType: z.array(TracingSearchType),
- orderBy: orderBy,
-});
+export const GenerationTableOptions = z
+ .object({
+ projectId: z.string(), // Required for protectedProjectProcedure
+ filter: z.array(singleFilter),
+ searchQuery: z.string().nullable(),
+ searchType: z.array(TracingSearchType),
+ orderBy: orderBy,
+ })
+ .refine(hasValidTracingSearchTypes, {
+ message: TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ path: ["searchType"],
+ });
diff --git a/web/src/server/api/routers/traces.ts b/web/src/server/api/routers/traces.ts
index d5d15df22e..acd7a24880 100644
--- a/web/src/server/api/routers/traces.ts
+++ b/web/src/server/api/routers/traces.ts
@@ -21,6 +21,8 @@ import {
singleFilter,
timeFilter,
type Observation,
+ hasValidTracingSearchTypes,
+ TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
TracingSearchType,
type ScoreDomain,
ScoreDataTypeArray,
@@ -69,14 +71,19 @@ import {
import { scoreFilters } from "@/src/features/scores/lib/scoreColumns";
import partition from "lodash/partition";
-const TraceCountOptions = z.object({
- projectId: z.string(), // Required for protectedProjectProcedure
- searchQuery: z.string().nullable(),
- searchType: z.array(TracingSearchType),
- filter: z.array(singleFilter).nullable(),
- orderBy: orderBy,
-});
-const TraceFilterOptions = TraceCountOptions.extend({
+const TraceCountOptions = z
+ .object({
+ projectId: z.string(), // Required for protectedProjectProcedure
+ searchQuery: z.string().nullable(),
+ searchType: z.array(TracingSearchType),
+ filter: z.array(singleFilter).nullable(),
+ orderBy: orderBy,
+ })
+ .refine(hasValidTracingSearchTypes, {
+ message: TRACING_SEARCH_TYPE_REQUIRED_MESSAGE,
+ path: ["searchType"],
+ });
+const TraceFilterOptions = TraceCountOptions.safeExtend({
...paginationZod,
});
type TraceFilterOptions = z.infer<typeof TraceFilterOptions>;