Skip to content

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

139 KB
Raw Blame
/* eslint-disable no-nested-ternary, @typescript-eslint/no-use-before-define */
import { prisma } from "../../db";
import {
  TupleParam,
  type ClickHouseClientConfigOptions,
  type ClickHouseSettings,
} from "@clickhouse/client";
import {
  sql,
  type AliasableExpression,
  type AliasedExpression,
  type Expression,
  type ExpressionBuilder,
  type QueryCreator,
} from "kysely";
import type {
  EventsObservation,
  ObservationType,
} from "../../domain/observations";
import type { MetadataDomain } from "../../domain/traces";
import { env } from "../../env";
import { InternalServerError } from "../../errors/InternalServerError";
import { InvalidRequestError } from "../../errors/InvalidRequestError";
import { LangfuseNotFoundError } from "../../errors/NotFoundError";
import {
  convertDateToClickhouseDateTime,
  PreferredClickhouseService,
} from "../clickhouse/client";
import { instrumentAsync, recordDistribution } from "../instrumentation";
import { logger } from "../logger";
import { AI_GATEWAY_SERVICE_NAME } from "../../features/ai-gateway/constants";
import { compileClickhouseQuery } from "../query-ast/compile";
import { getClickhouseKysely } from "../query-ast/dialect";
import type { ClickHouseDatabase } from "../query-ast/schema";
import { promptGenerationEvents } from "./prompt-events";
import {
  arrayMap,
  byteLength,
  count,
  dateDiff,
  softDeleteAfterLimit,
  startsWith,
  leftUTF8,
  limitBy,
  latestNonEmpty,
  literal,
  mapValue,
  medianExact,
  metadataMap,
  sumMapValuesWhereKeyContains,
  toDate,
  toJSONString,
  toStartOfMinute,
  tupleIn,
  uniq,
  xxHash32,
} from "../query-ast/extensions";
import {
  convertClickhouseToDomain,
  convertClickhouseTracesListToDomain,
} from "./traces_converters";
import {
  getLastTraceTimestampsByProjectsFromTracesTable,
  getTraceByIdFromTracesTable,
  getTracesIdentifierForSessionFromTracesTable,
  hasAnyTrace,
  persistProjectHasTracesFlag,
  readProjectHasTracesFlag,
} from "./traces";
import {
  type Filter,
  FilterList,
  filtersRequireEventsFull,
} from "../queries/clickhouse-sql/clickhouse-filter";

import {
  type FullEventsObservation,
  FullEventsObservations,
  ObservationPriceFields,
  type EventsObservationPublic,
} from "../queries/createGenerationsQuery";

import { buildEventsObservationRowSelection } from "../queries/clickhouse-sql/events-observation-row-selection";
import { extractTimeFilter } from "../queries/clickhouse-sql/filter-utils";
import {
  orderByToClickhouseSql,
  orderByToEntries,
} from "../queries/clickhouse-sql/orderby-factory";
import {
  createPublicApiObservationsColumnMapping,
  createPublicApiTracesColumnMapping,
  deriveFilters,
  type ApiColumnMapping,
} from "../queries/public-api-filter-builder";
import {
  isFtsAcceleratedIoOperator,
  isFtsEventsTable,
  isFtsTextField,
} from "../queries/clickhouse-sql/fts";

import { createFilterFromFilterState } from "../queries/clickhouse-sql/factory";
import { DateTimeFilter } from "../queries/clickhouse-sql/clickhouse-filter";
import { isTimeFilter } from "../queries/clickhouse-sql/filter-utils";
import {
  planScoreFilterPushdown,
  resolveScoreDataRequirement,
} from "../queries/clickhouse-sql/score-filter-pushdown";
import type { EventsTableFilterState, FilterState } from "../../types";
import type { TracingSearchType } from "../../interfaces/search";
import {
  eventsTracesAggregation,
  eventsTracesScoresAggregation,
} from "../queries/clickhouse-sql/query-fragments";
import {
  eventsTableNativeUiColumnDefinitions,
  eventsTableUiColumnDefinitions,
} from "../tableMappings/mapEventsTable";
import { tracesTableUiColumnDefinitions } from "../tableMappings/mapTracesTable";
import {
  applyInputOutputRendering,
  DEFAULT_RENDERING_PROPS,
  RenderingProps,
} from "../utils/rendering";
import {
  OBSERVATION_FIELD_GROUPS_PUBLIC_API,
  OBSERVATION_FIELD_GROUPS_FULL,
  type ObservationFieldGroupPublicApi,
  type ObservationFieldGroupFull,
} from "../../domain/observation-field-groups";
import {
  commandClickhouse,
  parseClickhouseUTCDateTimeFormat,
  queryClickhouse,
  queryClickhouseStream,
  queryClickhouseStreamRawText,
  queryClickhouseExecRaw,
  BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
  ClickHouseResourceError,
  ClickHouseQueryAbortedError,
  queryClickhouseWithProgress,
  isProgressRow,
  isRow,
  isException,
} from "./clickhouse";
import {
  EventsObservationRecordReadType,
  TraceRecordReadType,
} from "./definitions";
import {
  INTERNAL_INGESTION_SDK_NAMES,
  UNKNOWN_INGESTION_SDK_VALUE,
} from "../ingestion/ingestionAttribution";
import type { AnalyticsObservationEvent } from "../analytics-integrations/types";
import {
  getObservationByIdFromObservationsTable,
  ObservationTableQuery,
} from "./observations";
import { convertEventsObservation } from "./observations_converters";
import {
  eventsMetadataValue,
  eventsMetricsSecondsSelects,
  eventsRowFieldSelects,
  eventsTraceName,
  observationByIdSelects,
  sessionAggregationSelects,
  TRACE_AGGREGATION_FIELDS,
  traceAggregationSelects,
  type SessionEventsField,
  type SessionEventsMetricsRow,
} from "./events-selects";
import {
  EventsQueryBuilder,
  CTEQueryBuilder,
  EventsAggQueryBuilder,
  buildEventsFullTableSplitQuery,
  type QueryWithParams,
  normalizeSessionCounts,
  type SessionEventsFields,
  OrderByEntry,
} from "../queries/clickhouse-sql/event-query-builder";
import { eventsFieldSetKeys } from "./events-field-sets";
import {
  buildEventsFilterOptionColumnQuery,
  buildEventsFilterOptionsForColumnsQuery,
  buildEventsExactFilterOptionsForColumnsQuery,
  buildEventsMetadataValuesQuery,
  EVENTS_FILTER_OPTION_SAMPLE_ROWS,
  EVENTS_FILTER_OPTION_TOP_N,
  type EventFilterOptionRow,
  type EventFilterOptionColumn,
  type EventFilterOptionScope,
} from "../queries/clickhouse-sql/event-filter-options";

import {
  eventsTableCols,
  normalizeEventsTraceName,
  type NumericEventsTableColumnId,
} from "../../eventsTable";
import { OBSERVATIONS_TO_TRACE_INTERVAL_DAYS } from "./constants";
import type { TraceDeleteBatchActionCursor } from "../../features/batchAction/types";
import {
  findUiColumnMapping,
  type UiColumnMappings,
} from "../../tableDefinitions/types";

import { tracesTableCols } from "../../tableDefinitions/tracesTable";
import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
import { escapeSqlLikePattern } from "../utils/sqlLike";
import type {
  SkillsAvailable,
  SkillsResourceLoaded,
} from "../../features/skills/trace";

/** Trace aggregates a session's trace identifiers read: no input/output, so `events` routes to `events_core`. */
const SESSION_TRACE_FIELDS = [
  "id",
  "project_id",
  "name",
  "timestamp",
  "environment",
  "session_id",
  "user_id",
] as const;

const OBSERVATIONS_DEFAULT_FROM_MS = Date.parse("2020-01-01T00:00:00Z");
const OBSERVATIONS_SCAN_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
const OBSERVATIONS_SCAN_BUDGET_MS = 45_000;
const OBSERVATIONS_QUERY_ROW_TARGET = 5_000_000;
const OBSERVATIONS_QUERY_OVERHEAD_MS = 3_000;
const OBSERVATIONS_MS_PER_GB = 1_500;

/** xxHash32('CUR00254FG5s') = 0; with id '', the tuple excludes all boundary rows. */
const OBSERVATIONS_TIME_CURSOR_TRACE_ID = "CUR00254FG5s";

/** The `input`/`output` pair an I/O select reads from one relation. */
type IoColumns = { input: string; output: string };

export type EventBatchIOStringOutput = {
  id: string;
  traceId: string;
  input: string | null;
  output: string | null;
  metadata: MetadataDomain;
};

export type EventBatchIOSkillFields = {
  skillsAvailable: SkillsAvailable;
  skillsResourceLoaded: SkillsResourceLoaded;
};

/** Raw ClickHouse storage shape: name-less JSON strings, names in the parallel toolCallNames array. */
export type EventBatchIOToolCallFields = {
  toolCalls: string[];
  toolCallNames: string[];
};

export type EventBatchIOWithExperimentOutput = EventBatchIOStringOutput & {
  experimentItemExpectedOutput: string | null;
  experimentItemMetadata: MetadataDomain;
};

export type EventBatchIOResult<
  TIncludeExperiment extends boolean,
  TIncludeToolCalls extends boolean,
  TIncludeSkills extends boolean = false,
> = (TIncludeExperiment extends true
  ? EventBatchIOWithExperimentOutput
  : EventBatchIOStringOutput) &
  (TIncludeToolCalls extends true ? EventBatchIOToolCallFields : object) &
  (TIncludeSkills extends true ? EventBatchIOSkillFields : object);

const BATCH_IO_STRING_RENDERING_PROPS: RenderingProps = {
  // Batch I/O truncation is handled in SQL via leftUTF8 for performance.
  truncated: false,
  shouldJsonParse: false,
};

const applyBatchIOStringRendering = (
  io: string | null | undefined,
): string | null => {
  return applyInputOutputRendering(io, BATCH_IO_STRING_RENDERING_PROPS) as
    | string
    | null;
};

type EventsObservationQueryResult = EventsObservationRecordReadType & {
  latency?: string;
  time_to_first_token?: string;
};

/**
 * Extra row fields present when the query ran with an `ioSizeCap`
 * (EventsQueryBuilder.selectIOWithSizeCap). ClickHouse returns UInt64 as
 * string and the exists-flag as 0/1.
 */
type IOSizeCapRowFields = {
  input_length: string;
  output_length: string;
  metadata_truncated: 0 | 1;
  metadata_length: string;
};

/**
 * Caller-facing truncation summary attached to observations fetched with an
 * `ioSizeCap`: true field lengths (UTF-8 code points) plus flags telling a
 * preview head apart from full content.
 */
export type ObservationIOSizeFields = {
  inputLength: number;
  outputLength: number;
  inputTruncated: boolean;
  outputTruncated: boolean;
  metadataTruncated: boolean;
  /** Shipped (capped) metadata weight in chars — for response budgeting. */
  metadataLength: number;
};

/**
 * Internal helper: enrich observations with model pricing data
 * Uses events-specific converter to include userId and sessionId
 * Supports both V1 (complete observations) and V2 (partial observations with field groups)
 *
 * CONTRACT: a 1:1 order-preserving map over observationRecords — never
 * filter, deduplicate, or reorder here. The ioSizeCap path in
 * getObservationsWithModelDataFromEventsTable zips row-extra columns back on
 * by index and asserts the row count.
 *
 * @param observationRecords - Raw observation records from ClickHouse
 * @param projectId - Project ID for model lookup
 * @param parseIoAsJson - Whether to parse input/output as JSON
 * @param requestedFields - Field groups for V2 API (null = V1 API, returns complete observations)
 */
async function enrichObservationsWithModelData(
  observationRecords: Array<EventsObservationQueryResult>,
  projectId: string,
  parseIoAsJson: boolean,
  requestedFields: ObservationFieldGroupPublicApi[],
): Promise<Array<EventsObservationPublic>>;
async function enrichObservationsWithModelData(
  observationRecords: Array<EventsObservationQueryResult>,
  projectId: string,
  parseIoAsJson: boolean,
  requestedFields: null,
): Promise<Array<EventsObservation & ObservationPriceFields>>;
async function enrichObservationsWithModelData(
  observationRecords: Array<EventsObservationQueryResult>,
  projectId: string,
  parseIoAsJson: boolean,
  requestedFields: ObservationFieldGroupPublicApi[] | null,
): Promise<
  Array<(EventsObservation & ObservationPriceFields) | EventsObservationPublic>
> {
  // Determine if this is V1 (complete) or V2 (partial) API
  const isV2 = Array.isArray(requestedFields);

  // Determine if model enrichment is needed
  // V1 API: always enrich
  // V2 API: only enrich if "model" field group is requested
  const shouldEnrichModel = !isV2 || requestedFields.includes("model");

  // Fetch model data if needed
  const models = shouldEnrichModel
    ? await (async () => {
        const uniqueModels: string[] = Array.from(
          new Set(
            observationRecords
              .map((r) => r.internal_model_id)
              .filter((r): r is string => Boolean(r)),
          ),
        );

        return uniqueModels.length > 0
          ? await prisma.model.findMany({
              where: {
                id: {
                  in: uniqueModels,
                },
                OR: [{ projectId: projectId }, { projectId: null }],
              },
              include: {
                Price: {
                  where: { pricingTier: { isDefault: true } },
                },
              },
            })
          : [];
      })()
    : [];

  return observationRecords.map((o) => {
    const model = shouldEnrichModel
      ? models.find((m) => m.id === o.internal_model_id)
      : null;

    const renderingProps = {
      shouldJsonParse: parseIoAsJson,
      truncated: false,
    };

    // Branch based on API version to use correct overload
    const converted = isV2
      ? convertEventsObservation(o, renderingProps, false)
      : convertEventsObservation(o, renderingProps, true);

    const enriched = {
      ...converted,
      // Use ClickHouse-calculated latency/timeToFirstToken if available, otherwise use what converter calculated
      latency:
        o.latency !== undefined
          ? o.latency
            ? Number(o.latency) / 1000
            : null
          : (converted.latency ?? null),
      timeToFirstToken:
        o.time_to_first_token !== undefined
          ? o.time_to_first_token
            ? Number(o.time_to_first_token) / 1000
            : null
          : (converted.timeToFirstToken ?? null),
      // Add model pricing fields (null if not fetched)
      modelId: model?.id ?? null,
      inputPrice:
        model?.Price?.find((m) => m.usageType === "input")?.price ?? null,
      outputPrice:
        model?.Price?.find((m) => m.usageType === "output")?.price ?? null,
      totalPrice:
        model?.Price?.find((m) => m.usageType === "total")?.price ?? null,
    };

    return enriched;
  });
}

/**
 * CONTRACT: a 1:1 order-preserving map — never filter, deduplicate, or
 * reorder here. The ioSizeCap path in
 * getObservationsWithModelDataFromEventsTable zips row-extra columns back on
 * by index and asserts the row count.
 */
async function enrichObservationsWithTraceFields(
  observationRecords: Array<EventsObservation & ObservationPriceFields>,
): Promise<FullEventsObservations> {
  return observationRecords.map((observation) => {
    // Remove raw tags field as this is re-mapped to traceTags
    const { tags: _tags, ...observationWithoutRawTags } = observation;
    return {
      ...observationWithoutRawTags,
      traceTags: observation.tags ?? [],
      traceTimestamp: null,
      toolDefinitions: observation.toolDefinitions ?? null,
      toolCalls: observation.toolCalls ?? null,
      // Compute counts from actual data for events table
      toolDefinitionsCount: observation.toolDefinitions
        ? Object.keys(observation.toolDefinitions).length
        : null,
      toolCallsCount: observation.toolCalls
        ? observation.toolCalls.length
        : null,
    };
  });
}

/**
 * Column mapping for public API filters on events table (observations)
 */
const PUBLIC_API_EVENTS_COLUMN_MAPPING: ApiColumnMapping[] =
  createPublicApiObservationsColumnMapping(
    "events_proto",
    "e",
    "parent_span_id",
  );

/**
 * Column mappings for traces aggregated from events table
 */
const PUBLIC_API_TRACES_COLUMN_MAPPING = createPublicApiTracesColumnMapping(
  "traces",
  "t",
);

// For events-based traces, observation fields are aggregated into the traces CTE (with 't' prefix),
// not joined from a separate observations table (with 'o' prefix). We need to remap these.
const TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS =
  tracesTableUiColumnDefinitions.map((col) => {
    // If this column references the observations table with 'o' prefix,
    // remap it to use 't' prefix since observations are aggregated into traces CTE
    if (col.clickhouseTableName === "observations") {
      // Replace o. prefix with t. in clickhouseSelect (only when followed by identifier)
      // Technically we do not need to deal with the prefix at all,
      // since here these columns are always used inside a CTE.
      const updatedSelect = col.clickhouseSelect.replace(
        /\bo\.([a-z_])/g,
        "t.$1",
      );

      return {
        ...col,
        clickhouseTableName: "traces", // Now it's in the traces CTE
        queryPrefix: undefined,
        clickhouseSelect: updatedSelect,
      };
    }
    return col;
  });

/**
 * Order by columns for traces CTE (post-aggregation)
 */
const allowedOrderByIds = [
  "timestamp",
  "name",
  "userId",
  "sessionId",
  "environment",
  "version",
  "release",
];
const TRACES_ORDER_BY_COLUMNS = TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS.filter(
  (col) => allowedOrderByIds.includes(col.uiTableId),
).map((col) => ({
  ...col,
  // Adjust column names that change after aggregation (start_time -> timestamp)
  clickhouseSelect:
    col.uiTableId === "timestamp" ? "timestamp" : col.clickhouseSelect,
  queryPrefix: "t", // Use 't' prefix because we're selecting from traces CTE
}));

// TODO: introduce pagination
export const MAX_OBSERVATIONS_PER_TRACE =
  env.LANGFUSE_MAX_OBSERVATIONS_PER_TRACE;

export const getObservationsForTraceFromEventsTable = async (params: {
  projectId: string;
  traceId: string;
  timestamp?: Date;
  selectIOAndMetadata?: boolean;
  selectMetadata?: boolean;
  selectToolData?: boolean;
  /** Restrict to these observation types. All types when omitted. */
  types?: ObservationType[];
  filter?: FilterState;
  /** Rows read at most; `totalCount` exceeds it when the trace has more. */
  limit?: number;
}): Promise<{ observations: FullEventsObservations; totalCount: number }> => {
  const {
    projectId,
    traceId,
    timestamp,
    selectIOAndMetadata = false,
    selectMetadata = false,
    selectToolData = false,
    types,
    limit = MAX_OBSERVATIONS_PER_TRACE,
  } = params;

  const filter: FilterState = [
    ...(params.filter ?? []),
    {
      column: "traceId",
      operator: "=" as const,
      value: traceId,
      type: "string" as const,
    },
  ];

  if (timestamp) {
    filter.push({
      column: "startTime",
      operator: ">=" as const,
      // Equivalent to TRACE_TO_OBSERVATIONS_INTERVAL (INTERVAL 1 HOUR)
      value: new Date(timestamp.getTime() - 60 * 60 * 1000),
      type: "datetime" as const,
    });
  }

  if (types) {
    filter.push({
      column: "type",
      operator: "any of" as const,
      value: types,
      type: "stringOptions" as const,
    });
  }

  const records =
    await getObservationsFromEventsTableInternal<EventsObservationQueryResult>({
      projectId,
      filter,
      orderBy: { column: "startTime", order: "ASC" },
      limit: limit + 1,
      offset: 0,
      select: "rows",
      selectIOAndMetadata,
      selectMetadata,
      selectToolData,
    });

  const totalCount = records.length;

  const withModelData = await enrichObservationsWithModelData(
    records.slice(0, limit),
    projectId,
    false,
    null,
  );
  const observations = await enrichObservationsWithTraceFields(withModelData);

  return { observations, totalCount };
};

export const getObservationsCountFromEventsTable = async (
  opts: ObservationTableQuery,
) => {
  const count = await getObservationsFromEventsTableInternal<{
    count: string;
  }>({
    ...opts,
    select: "count",
  });

  return Number(count[0].count);
};

/**
 * Row count plus approximate distinct trace count over the same filtered set,
 * computed in a single ClickHouse pass. Powers the events-table select-all
 * batch-delete confirmation ("N items spanning M unique traces").
 */
export const getObservationsCountsFromEventsTable = async (
  opts: ObservationTableQuery,
): Promise<{ totalCount: number; uniqueTraceCount: number }> => {
  const counts = await getObservationsFromEventsTableInternal<{
    count: string;
    unique_trace_count: string;
  }>({
    ...opts,
    select: "count-with-unique-traces",
  });

  return {
    totalCount: Number(counts[0].count),
    uniqueTraceCount: Number(counts[0].unique_trace_count),
  };
};

export async function getObservationsWithModelDataFromEventsTable(
  opts: ObservationTableQuery & {
    ioSizeCap: NonNullable<ObservationTableQuery["ioSizeCap"]>;
  },
): Promise<Array<FullEventsObservation & ObservationIOSizeFields>>;
export async function getObservationsWithModelDataFromEventsTable(
  opts: ObservationTableQuery,
): Promise<FullEventsObservations>;
export async function getObservationsWithModelDataFromEventsTable(
  opts: ObservationTableQuery,
): Promise<FullEventsObservations> {
  const observationRecords = await getObservationsFromEventsTableInternal<
    EventsObservationQueryResult & Partial<IOSizeCapRowFields>
  >({
    ...opts,
    select: "rows",
  });

  const withModelData: Array<EventsObservation & ObservationPriceFields> =
    await enrichObservationsWithModelData(
      observationRecords,
      opts.projectId,
      false,
      null, // V1 path: always enrich all fields
    );

  const enriched = await enrichObservationsWithTraceFields(withModelData);

  if (!opts.ioSizeCap) return enriched;

  // Zip the size fields back on BY ROW ORDER: both enrichers above are 1:1
  // order-preserving maps over the records (a documented contract on each).
  // Never zip by id — un-merged ReplacingMergeTree versions of one span
  // return multiple rows sharing an id, and an id-keyed lookup would attach
  // one version's lengths to another version's payload.
  if (enriched.length !== observationRecords.length) {
    throw new Error(
      "getObservationsWithModelDataFromEventsTable: enrichment changed the row count; the ioSizeCap zip requires 1:1 order-preserving enrichers",
    );
  }
  const { inlineChars } = opts.ioSizeCap;
  return enriched.map((observation, index) => {
    const record = observationRecords[index];
    const inputLength = Number(record.input_length ?? 0);
    const outputLength = Number(record.output_length ?? 0);
    return {
      ...observation,
      inputLength,
      outputLength,
      inputTruncated: inputLength > inlineChars,
      outputTruncated: outputLength > inlineChars,
      metadataTruncated: Boolean(Number(record.metadata_truncated ?? 0)),
      metadataLength: Number(record.metadata_length ?? 0),
    };
  });
}

export const getObservationMetricsForPromptsFromEvents = async (
  projectId: string,
  promptIds: string[],
  {
    fromTimestamp,
    toTimestamp,
  }: { fromTimestamp?: Date; toTimestamp?: Date } = {},
) => {
  const builder = getClickhouseKysely()
    .with("prompt_events", () =>
      promptGenerationEvents(
        promptIds,
        [
          "e.project_id as project_id",
          "e.prompt_id as prompt_id",
          "e.prompt_version as prompt_version",
          "e.trace_id as trace_id",
          "e.span_id as span_id",
          "e.start_time as start_time",
          "e.end_time as end_time",
          "e.usage_details as usage_details",
          "e.cost_details as cost_details",
        ],
        { fromTimestamp, toTimestamp },
      ),
    )
    .selectFrom("prompt_events as e")
    .select((eb) => [
      count().as("count"),
      "e.prompt_id as prompt_id",
      "e.prompt_version as prompt_version",
      eb.fn.min("e.start_time").as("first_observation"),
      eb.fn.max("e.start_time").as("last_observation"),
      medianExact(
        sumMapValuesWhereKeyContains(
          eb.ref("e.usage_details"),
          literal("input"),
        ),
      ).as("median_input_usage"),
      medianExact(
        sumMapValuesWhereKeyContains(
          eb.ref("e.usage_details"),
          literal("output"),
        ),
      ).as("median_output_usage"),
      medianExact(mapValue(eb.ref("e.cost_details"), literal("total"))).as(
        "median_total_cost",
      ),
      medianExact(
        dateDiff("millisecond", eb.ref("e.start_time"), eb.ref("e.end_time")),
      ).as("median_latency_ms"),
    ])
    .groupBy(["e.prompt_id", "e.prompt_version"])
    .orderBy("e.prompt_version", "desc");
  const { sql: query, params } = compileClickhouseQuery(builder, projectId);
  const rows = await queryClickhouse<{
    count: string;
    prompt_id: string;
    prompt_version: number;
    first_observation: string;
    last_observation: string;
    median_input_usage: string;
    median_output_usage: string;
    median_total_cost: string;
    median_latency_ms: string;
  }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => ({
    count: Number(row.count),
    promptId: row.prompt_id,
    promptVersion: row.prompt_version,
    firstObservation: parseClickhouseUTCDateTimeFormat(row.first_observation),
    lastObservation: parseClickhouseUTCDateTimeFormat(row.last_observation),
    medianInputUsage: Number(row.median_input_usage),
    medianOutputUsage: Number(row.median_output_usage),
    medianTotalCost: Number(row.median_total_cost),
    medianLatencyMs: Number(row.median_latency_ms),
  }));
};

export const getObservationsWithPromptNameFromEvents = async (
  projectId: string,
  promptNames: string[],
  {
    fromTimestamp,
    toTimestamp,
  }: { fromTimestamp?: Date; toTimestamp?: Date } = {},
) => {
  const builder = getClickhouseKysely()
    .selectFrom("events")
    .select((eb) => [uniq(eb.ref("span_id")).as("count"), "prompt_name"])
    .where("prompt_name", "in", promptNames)
    .where("prompt_name", "!=", literal(""))
    .$if(fromTimestamp != null, (qb) =>
      qb.where("start_time", ">=", fromTimestamp!),
    )
    .$if(toTimestamp != null, (qb) =>
      qb.where("start_time", "<=", toTimestamp!),
    )
    .groupBy("prompt_name");
  const { sql: query, params } = compileClickhouseQuery(builder, projectId);
  const rows = await queryClickhouse<{ count: string; prompt_name: string }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => ({
    count: Number(row.count),
    promptName: row.prompt_name,
  }));
};

export const getTraceDeleteCursorPageFromEvents = async (props: {
  projectId: string;
  filter: FilterState;
  cutoffCreatedAt: Date;
  cursor?: TraceDeleteBatchActionCursor | null;
  searchQuery?: string;
  searchType?: TracingSearchType[];
  limit: number;
  clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;
}): Promise<TraceDeleteBatchActionCursor[]> => {
  // Trace-delete cursoring intentionally reuses observation pagination where
  // span_id is the final tuple element, while this scanner deduplicates by
  // trace_id. If a deleted multi-span trace is still visible on a lagging
  // replica, a later span for the same trace can be emitted again. That is
  // acceptable because trace deletion is idempotent and only retries the same
  // trace id; the processor keeps its durable in-flight traceIds boundary.
  const rows = await getObservationsFromEventsTableInternal<{
    id: string;
    trace_id: string;
    start_time: string;
  }>({
    projectId: props.projectId,
    filter: [
      ...props.filter,
      {
        column: "startTime",
        operator: "<" as const,
        value: props.cutoffCreatedAt,
        type: "datetime" as const,
      },
    ],
    searchQuery: props.searchQuery,
    searchType: props.searchType,
    limit: props.limit,
    cursor: props.cursor?.id
      ? {
          lastStartTimeTo: new Date(props.cursor.timestamp),
          lastTraceId: props.cursor.traceId,
          lastId: props.cursor.id,
        }
      : undefined,
    clickhouseConfigs: props.clickhouseConfigs,
    // This scanner runs interleaved with DELETE mutations. Use the writable
    // pool so the next page is read from the same side as the mutation path
    // instead of a potentially lagging EventsReadOnly replica.
    preferredClickhouseService: "ReadWrite",
    select: "trace-delete-cursor",
  });

  return rows.map((row) => ({
    id: row.id,
    traceId: row.trace_id,
    timestamp: parseClickhouseUTCDateTimeFormat(row.start_time).toISOString(),
  }));
};

async function getObservationsFromEventsTableInternal<T>(
  opts: ObservationTableQuery & {
    selectMetadata?: boolean;
    select:
      | "count"
      | "count-with-unique-traces"
      | "rows"
      | "trace-delete-cursor";
    selectToolData?: boolean;
    preferredClickhouseService?: PreferredClickhouseService;
  },
): Promise<Array<T>> {
  const {
    projectId,
    filter,
    selectIOAndMetadata,
    selectMetadata,
    selectToolData = true,
    renderingProps = DEFAULT_RENDERING_PROPS,
    limit,
    offset,
    orderBy,
    clickhouseConfigs,
    preferredClickhouseService,
  } = opts;

  // Extract positionInTrace filter and build baseFilter without it
  const positionFilter = filter.find((f) => f.type === "positionInTrace");
  const baseFilter: typeof filter = [
    ...filter.filter((f) => f.type !== "positionInTrace"),
  ];

  const orderByEntries = orderByToEntries(
    [orderBy ?? null],
    eventsTableUiColumnDefinitions,
  );

  // Build filter list from baseFilter (without positionInTrace)
  // Build query using EventsQueryBuilder
  const { queryBuilder, search } = buildEventsObservationRowSelection({
    projectId,
    filter: baseFilter,
    searchQuery: opts.searchQuery,
    searchType: opts.searchType,
    orderBy,
  });

  if (opts.select === "count") {
    queryBuilder.selectFieldSet("count");
  } else if (opts.select === "count-with-unique-traces") {
    queryBuilder.selectFieldSet("countWithUniqueTraces");
  } else if (opts.select === "trace-delete-cursor") {
    queryBuilder.selectRaw(
      "e.span_id AS id",
      "e.trace_id AS trace_id",
      "e.start_time AS start_time",
    );
  } else {
    queryBuilder.selectFieldSet(
      selectToolData ? "base" : "baseWithoutTools",
      "calculated",
    );
    if (selectIOAndMetadata) {
      if (opts.ioSizeCap) {
        queryBuilder.selectIOWithSizeCap(
          opts.ioSizeCap.inlineChars,
          opts.ioSizeCap.previewChars,
        );
      } else {
        queryBuilder.selectIO(
          renderingProps.truncated,
          env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT,
        );
      }
    }
    if (selectIOAndMetadata || selectMetadata) {
      queryBuilder.selectFieldSet("metadata");
    }
  }

  const isTraceDeleteCursorSelect = opts.select === "trace-delete-cursor";
  const isCursorPagination =
    isTraceDeleteCursorSelect || Boolean(opts.cursorPagination);

  // Handle positionInTrace via CTE with ROW_NUMBER()
  // All modes use the same pattern: rank observations per trace, pick rn = N.
  // `root` remains only for backward compatibility and maps to `first`.
  // root/first/nthFromStart → ORDER BY start_time ASC
  // last/nthFromEnd         → ORDER BY start_time DESC
  if (positionFilter && "key" in positionFilter) {
    const key = positionFilter.key;
    const isFromEnd = key === "last" || key === "nthFromEnd";
    const direction = isFromEnd ? "DESC" : "ASC";
    const position = (() => {
      if (key === "last" || key === "first" || key === "root") {
        return 1;
      }
      if (typeof positionFilter.value === "number") {
        return positionFilter.value;
      }
      return 1;
    })();

    // Build observation-only filter for CTE (no s.* or t.* references)
    const nativeFilter = new FilterList(
      createFilterFromFilterState(
        baseFilter,
        eventsTableNativeUiColumnDefinitions,
      ),
    );
    const appliedNativeFilter = nativeFilter.apply();
    const qualifyingObsBuilder = new EventsQueryBuilder({ projectId })
      .selectRaw(
        "e.span_id",
        `ROW_NUMBER() OVER (PARTITION BY e.trace_id ORDER BY e.start_time ${direction}, e.event_ts ${direction}, e.span_id ${direction}) as _rn`,
      )
      .when(
        search.requiresEventsFull || filtersRequireEventsFull(nativeFilter),
        (b) => b.forceFullTable(),
      )
      .where(appliedNativeFilter)
      .where(search);

    queryBuilder.withCTE(
      "qualifying_obs",
      qualifyingObsBuilder.buildWithParams(),
    );

    queryBuilder.whereRaw(
      "e.span_id IN (SELECT span_id FROM qualifying_obs WHERE _rn = {_posRn: UInt32})",
      { _posRn: Math.max(1, position) },
    );
  }

  queryBuilder
    .when(isCursorPagination, (b) =>
      applyObservationsCursorFilter(opts.cursor, b),
    )
    .when(isCursorPagination, (b) => {
      const cursorOrderedBuilder = b.orderByColumns([
        ...orderByForObservationsQuery("e"),
        ...(opts.dedupeBySpanId
          ? [{ column: "e.event_ts", direction: "DESC" as const }]
          : []),
      ]);

      if (isTraceDeleteCursorSelect) {
        return cursorOrderedBuilder.limitBy("e.trace_id", "e.project_id");
      }
      if (opts.dedupeBySpanId) {
        return cursorOrderedBuilder.limitBy("e.span_id", "e.project_id");
      }
      return cursorOrderedBuilder;
    })
    .when(
      !isCursorPagination &&
        (orderByEntries.length > 0 || Boolean(opts.dedupeBySpanId)),
      (b) =>
        b.orderByColumns(
          opts.dedupeBySpanId
            ? // event_ts DESC within the caller's order so LIMIT 1 BY keeps
              // the newest version of each span.
              [
                ...orderByEntries,
                { column: "e.event_ts", direction: "DESC" as const },
              ]
            : orderByEntries,
        ),
    )
    .when(!isCursorPagination && Boolean(opts.dedupeBySpanId), (b) =>
      b.limitBy("e.span_id", "e.project_id"),
    )
    .limit(limit, isCursorPagination ? undefined : offset);

  const { query, params } = queryBuilder.buildWithParams();

  return queryClickhouse<T>({
    query,
    params,
    tags: { projectId },
    clickhouseConfigs,
    preferredClickhouseService: preferredClickhouseService ?? "EventsReadOnly",
    // Buffering reads ahead on every stream; wasted once LIMIT is filled.
    clickhouseSettings: { read_in_order_use_buffering: 0 },
  });
}

export const getObservationByIdFromEventsTable = async ({
  id,
  projectId,
  fetchWithInputOutput = false,
  startTime,
  startTimeLowerBound,
  type,
  traceId,
  renderingProps = DEFAULT_RENDERING_PROPS,
  preferredClickhouseService,
}: {
  id: string;
  projectId: string;
  fetchWithInputOutput?: boolean;
  startTime?: Date;
  startTimeLowerBound?: Date;
  type?: ObservationType;
  traceId?: string;
  renderingProps?: RenderingProps;
  preferredClickhouseService?: PreferredClickhouseService;
}) => {
  const records = await getObservationByIdFromEventsTableInternal({
    id,
    projectId,
    fetchWithInputOutput,
    startTime,
    startTimeLowerBound,
    type,
    traceId,
    renderingProps,
    preferredClickhouseService: preferredClickhouseService ?? "EventsReadOnly",
  });
  const mapped = records.map((record) => {
    // Remove raw tags field as this is re-mapped to traceTags
    const { tags, ...converted } = convertEventsObservation(
      record,
      renderingProps,
      true,
    );

    return {
      ...converted,
      traceTags: tags ?? [],
    };
  });

  mapped.forEach((observation) => {
    recordDistribution(
      "langfuse.query_by_id_age",
      new Date().getTime() - observation.startTime.getTime(),
      {
        table: "events",
      },
    );
  });
  if (mapped.length === 0) {
    throw new LangfuseNotFoundError(`Observation with id ${id} not found`);
  }

  if (mapped.length > 1) {
    logger.error(
      `Multiple observations found for id ${id} and project ${projectId}`,
    );
    throw new InternalServerError(
      `Multiple observations found for id ${id} and project ${projectId}`,
    );
  }
  return mapped.shift();
};

async function getObservationByIdFromEventsTableInternal({
  id,
  projectId,
  fetchWithInputOutput = false,
  startTime,
  startTimeLowerBound,
  type,
  traceId,
  renderingProps = DEFAULT_RENDERING_PROPS,
  preferredClickhouseService,
}: {
  id: string;
  projectId: string;
  fetchWithInputOutput?: boolean;
  startTime?: Date;
  startTimeLowerBound?: Date;
  type?: ObservationType;
  traceId?: string;
  renderingProps?: RenderingProps;
  preferredClickhouseService?: PreferredClickhouseService;
}) {
  // Minute-resolution start_time matches the events_full primary key
  // (project_id, toStartOfMinute(start_time), ...) so the lookup can prune.
  // The lower bound subtracts the observation-to-trace skew interval because
  // an observation may start slightly before its anchor (e.g. the parent
  // trace).
  const db = getClickhouseKysely();
  const needsFullTable =
    fetchWithInputOutput && renderingProps.truncated !== true;

  // A soft-deleted latest version reads as not found, not as an older version.
  const builder = (
    needsFullTable
      ? db.selectFrom("events as e")
      : db.selectFrom("events_truncated as e")
  )
    .$call(softDeleteAfterLimit())
    .select(observationByIdSelects)
    .$if(fetchWithInputOutput, (qb) =>
      qb.select((eb) => observationIoSelects(eb, renderingProps.truncated)),
    )
    .where("span_id", "=", id)
    .$if(startTime != null, (qb) =>
      qb.where((eb) =>
        eb(
          toStartOfMinute(eb.ref("start_time")),
          "=",
          toStartOfMinute(startTime!),
        ),
      ),
    )
    .$if(startTimeLowerBound != null, (qb) =>
      qb.where(
        "start_time",
        ">=",
        observationsToTraceLowerBound(startTimeLowerBound!),
      ),
    )
    .$if(type != null, (qb) => qb.where("type", "=", type!))
    .$if(traceId != null, (qb) => qb.where("trace_id", "=", traceId!))
    .orderBy("start_time", "desc")
    .orderBy("event_ts", "desc")
    .limit(literal(1));

  const { sql: query, params } = compileClickhouseQuery(builder, projectId);

  return await queryClickhouse<EventsObservationRecordReadType>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService,
  });
}

/** `input`/`output`, capped to the server-side char limit on a truncated read. */
function observationIoSelects(
  eb: ExpressionBuilder<{ e: IoColumns }, "e">,
  truncated: boolean | undefined,
) {
  if (!truncated) return ["e.input", "e.output"] as const;
  const charLimit = env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT;
  return [
    leftUTF8(eb.ref("e.input"), charLimit).as("input"),
    leftUTF8(eb.ref("e.output"), charLimit).as("output"),
  ];
}

/**
 * Get a trace by ID from the events table.
 * Compatible with getTraceById but queries the events table instead.
 *
 * Avoid using the `excludeInputOutput` and `excludeMetadata` fields as they
 * are only for backwards compatibility with the existing `getTraceById` interface.
 */
export const getTraceByIdFromEventsTable = async ({
  traceId,
  projectId,
  timestamp,
  fromTimestamp,
  renderingProps = DEFAULT_RENDERING_PROPS,
  preferredClickhouseService,
  excludeInputOutput = false,
  excludeMetadata = false,
}: {
  traceId: string;
  projectId: string;
  timestamp?: Date;
  fromTimestamp?: Date;
  renderingProps?: RenderingProps;
  preferredClickhouseService?: PreferredClickhouseService;
  /** When true, sets input/output columns to empty in the query to reduce database load */
  excludeInputOutput?: boolean;
  /** When true, sets metadata column to empty in the query to reduce database load */
  excludeMetadata?: boolean;
}) => {
  const db = getClickhouseKysely();
  const truncated = renderingProps.truncated === true;

  const tracesCte = (qb: QueryCreator<ClickHouseDatabase>) =>
    qb
      .selectFrom(truncated ? "events_truncated as e" : "events as e")
      .select((eb) => traceAggregationSelects(TRACE_AGGREGATION_FIELDS)(eb))
      .where("trace_id", "in", [traceId])
      .$if(fromTimestamp != null, (inner) =>
        inner.where(
          "start_time",
          ">=",
          observationsToTraceLowerBound(fromTimestamp!),
        ),
      )
      .groupBy(["trace_id", "project_id"])
      .orderBy("timestamp", "desc");

  const metadataSelect = excludeMetadata
    ? sql`map()`.as("metadata")
    : "t.metadata";

  const builder = db
    .with("event_traces", tracesCte)
    .selectFrom("event_traces as t")
    .select((eb) => [
      "t.id",
      "t.name",
      "t.user_id",
      "t.release",
      "t.version",
      "t.project_id",
      "t.environment",
      "t.public",
      "t.bookmarked",
      "t.tags",
      "t.session_id",
      "t.timestamp",
      "t.created_at",
      "t.updated_at",
      metadataSelect,
      literal(0).as("is_deleted"),
      ...traceIoSelects(eb, excludeInputOutput, truncated),
    ])
    .$if(timestamp != null, (qb) =>
      qb.where((eb) =>
        eb(toDate(eb.ref("t.timestamp")), "=", toDate(timestamp!)),
      ),
    )
    .orderBy("t.timestamp", "desc")
    .limit(literal(1));

  const { sql: query, params } = compileClickhouseQuery(builder, projectId);

  const records = await queryClickhouse<TraceRecordReadType>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: preferredClickhouseService ?? "EventsReadOnly",
  });

  const res = records.map((record) =>
    convertClickhouseToDomain(record, renderingProps),
  );

  res.forEach((trace) => {
    recordDistribution(
      "langfuse.query_by_id_age",
      new Date().getTime() - trace.timestamp.getTime(),
      {
        table: "events",
      },
    );
  });

  return res.shift();
};

/** Earliest start_time an observation of a trace anchored at `anchor` can have. */
function observationsToTraceLowerBound(anchor: Date): Date {
  return new Date(
    anchor.getTime() -
      OBSERVATIONS_TO_TRACE_INTERVAL_DAYS * 24 * 60 * 60 * 1000,
  );
}

/** `input`/`output` of the trace CTE `t`: empty, capped on a truncated read, or full. */
function traceIoSelects(
  eb: ExpressionBuilder<{ t: IoColumns }, "t">,
  excludeInputOutput: boolean,
  truncated: boolean,
) {
  if (excludeInputOutput)
    return [literal("").as("input"), literal("").as("output")];
  if (truncated) {
    const charLimit = env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT;
    return [
      leftUTF8(eb.ref("t.input"), charLimit).as("input"),
      leftUTF8(eb.ref("t.output"), charLimit).as("output"),
    ];
  }
  return ["t.input", "t.output"] as const;
}

/**
 * Routing wrapper for "trace by id" reads.
 *
 * If data is only written into the events tables, we look there and go to
 * traces otherwise.
 *
 * @deprecated Please prefer `getTraceByIdFromEventsTable` for new use-cases.
 * This should be exclusively used for backwards compatibility if the write mode
 * is events_only.
 */
export const getTraceById = async (
  params: Parameters<typeof getTraceByIdFromTracesTable>[0],
) => {
  if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {
    return getTraceByIdFromTracesTable(params);
  }
  return getTraceByIdFromEventsTable(params);
};

/**
 * Routing wrapper for "observation by id" reads.
 *
 * If data is only written into the events tables, we look there and go to the
 * legacy observations table otherwise.
 *
 * @deprecated Please prefer `getObservationByIdFromEventsTable` for new
 * use-cases. This should be exclusively used for backwards compatibility if the
 * write mode is events_only.
 */
export const getObservationById = async (
  params: Parameters<typeof getObservationByIdFromObservationsTable>[0],
) => {
  if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {
    return getObservationByIdFromObservationsTable(params);
  }
  return getObservationByIdFromEventsTable(params);
};

/**
 * Routing wrapper for "trace identifiers for session" reads.
 *
 * If data is only written into the events tables, we look there and go to the
 * legacy traces table otherwise.
 *
 * @deprecated Please prefer `getTracesIdentifierForSessionFromEvents` for new
 * use-cases. This should be exclusively used for backwards compatibility if the
 * write mode is events_only.
 */
export const getTracesIdentifierForSession = async (
  projectId: string,
  sessionId: string,
) => {
  if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {
    return getTracesIdentifierForSessionFromTracesTable(projectId, sessionId);
  }
  return getTracesIdentifierForSessionFromEvents(projectId, sessionId);
};

/**
 * Check if any tracing data exists in the events table.
 */
export const hasAnyTraceFromEventsTable = async (
  projectId: string,
): Promise<boolean> => {
  const { sql: query, params } = compileHasAnyFromEventsTable({
    projectId,
    kind: "trace",
  });

  const rows = await queryClickhouse<{ one: number }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
    clickhouseSettings: {
      max_threads: 1,
    },
  });

  return rows.length > 0;
};

type HasAnyEventsKind = "trace" | "user" | "session";

function compileHasAnyFromEventsTable(opts: {
  projectId: string;
  kind: HasAnyEventsKind;
}) {
  const db = getClickhouseKysely();

  const query = db
    .selectFrom("events")
    .select(literal(1).as("one"))
    .$if(opts.kind === "user", (qb) =>
      qb.where("user_id", "is not", null).where("user_id", "!=", literal("")),
    )
    .$if(opts.kind === "session", (qb) =>
      qb
        .where("session_id", "is not", null)
        .where("session_id", "!=", literal("")),
    )
    .limit(literal(1));

  return compileClickhouseQuery(query, opts.projectId);
}

/**
 * Routing wrapper for the tracing onboarding gate ("has this project ingested
 * any tracing data yet?").
 *
 * If data is only written into the events tables, we look there and go to the
 * legacy traces table otherwise. Both paths share the project's `hasTraces`
 * flag as a read-through cache, so steady-state checks skip ClickHouse.
 */
export const hasAnyTracingData = async (projectId: string) => {
  if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {
    return hasAnyTrace(projectId);
  }

  if (await readProjectHasTracesFlag(projectId)) {
    return true;
  }

  const result = await hasAnyTraceFromEventsTable(projectId);
  if (result) {
    await persistProjectHasTracesFlag(projectId);
  }
  return result;
};

/**
 * Last event start_time per project from the events table, capped to the last
 * 30 days (matches the traces-table variant's window).
 */
export const getLastTraceTimestampsByProjectsFromEventsTable = async ({
  projectIds,
}: {
  projectIds: string[];
}) => {
  if (projectIds.length === 0) return [];

  // Spans several projects, so it cannot go through compileClickhouseQuery,
  // whose tenancy scope is always a single project.
  const query = `
    SELECT
      project_id,
      max(start_time) as last_trace_at
    FROM events_core
    WHERE project_id IN ({projectIds: Array(String)})
    AND start_time >= now() - INTERVAL 30 DAY
    AND is_deleted = 0
    GROUP BY project_id
  `;

  const rows = await queryClickhouse<{
    project_id: string;
    last_trace_at: string;
  }>({
    query,
    params: { projectIds },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => ({
    projectId: row.project_id,
    lastTraceAt: parseClickhouseUTCDateTimeFormat(row.last_trace_at),
  }));
};

/**
 * Routing wrapper for "last trace timestamp per project" reads.
 *
 * If data is only written into the events tables, we look there and go to the
 * legacy traces table otherwise.
 */
export const getLastTraceTimestampsByProjects = async (
  params: Parameters<typeof getLastTraceTimestampsByProjectsFromTracesTable>[0],
) => {
  if (env.LANGFUSE_MIGRATION_V4_WRITE_MODE !== "events_only") {
    return getLastTraceTimestampsByProjectsFromTracesTable(params);
  }
  return getLastTraceTimestampsByProjectsFromEventsTable(params);
};

/**
 * Trace and observation counts per project for events_core rows created in
 * `[start, end)`. Ingestion-API traces carry a synthetic `t-<traceId>` root
 * row, which counts towards the trace but not as an observation. A trace with
 * rows created in several intervals counts once in each. The AI gateway writes
 * one generation per request, so `gatewayRequests` counts its rows; ingestion
 * keeps the gateway service name only on gateway-authenticated uploads.
 */
export const getTracingCountsByProjectInCreationIntervalFromEventsTable =
  async ({
    start,
    end,
    projectIds,
  }: {
    start: Date;
    end: Date;
    projectIds?: string[];
  }) => {
    // Spans several projects, so it cannot go through compileClickhouseQuery,
    // whose tenancy scope is always a single project.
    const query = `
      SELECT
        project_id,
        uniq(trace_id) as traces,
        countIf(span_id != concat('t-', trace_id)) as observations,
        countIf(service_name = {gatewayServiceName: String}) as gateway_requests
      FROM events_core
      WHERE created_at >= {start: DateTime64(3)}
      AND created_at < {end: DateTime64(3)}
      AND is_deleted = 0
      ${projectIds ? "AND project_id IN ({projectIds: Array(String)})" : ""}
      GROUP BY project_id
    `;

    const rows = await queryClickhouse<{
      project_id: string;
      traces: string;
      observations: string;
      gateway_requests: string;
    }>({
      query,
      params: {
        start: convertDateToClickhouseDateTime(start),
        end: convertDateToClickhouseDateTime(end),
        gatewayServiceName: AI_GATEWAY_SERVICE_NAME,
        ...(projectIds ? { projectIds } : {}),
      },
      clickhouseConfigs: {
        request_timeout: 300000, // 5 minutes timeout
      },
      preferredClickhouseService: "EventsReadOnly",
    });

    return rows.map((row) => ({
      projectId: row.project_id,
      traces: Number(row.traces),
      observations: Number(row.observations),
      gatewayRequests: Number(row.gateway_requests),
    }));
  };

type PublicApiObservationsQuery = {
  projectId: string;
  page: number;
  limit: number;
  traceId?: string;
  userId?: string;
  sessionId?: string;
  name?: string;
  type?: string;
  level?: string;
  parentObservationId?: string;
  isRootObservation?: boolean;
  fromStartTime?: string;
  toStartTime?: string;
  version?: string;
  environment?: string | string[];
  advancedFilters?: EventsTableFilterState;
  parseIoAsJson?: boolean;
  cursor?: {
    lastStartTimeTo: Date;
    lastTraceId: string;
    lastId: string;
  };
  fields?: ObservationFieldGroupPublicApi[] | null;
  /**
   * Metadata keys to expand (return full non-truncated values).
   * - null/undefined: use truncated metadata (default behavior)
   * - string[]: expand specified keys (or all keys if empty array)
   */
  expandMetadataKeys?: string[] | null;
};

type BuildObservationsQueryComponentsOptions = {
  allowUnindexedIoFilters?: boolean;
  clickhouseSettings?: ClickHouseSettings;
};

const EVENTS_IO_FILTER_TYPE_ERROR =
  "Input/output filters only support filter type `string`.";

const validateInputOutputFilterTypes = (
  filterState: EventsTableFilterState | undefined,
  columnDefinitions: UiColumnMappings,
) => {
  for (const filter of filterState ?? []) {
    const column = findUiColumnMapping(columnDefinitions, filter.column);

    if (
      column &&
      isFtsEventsTable(column.clickhouseTableName) &&
      isFtsTextField(column.clickhouseSelect) &&
      filter.type !== "string"
    ) {
      throw new InvalidRequestError(EVENTS_IO_FILTER_TYPE_ERROR);
    }
  }
};

const isInputOutputFilter = (filter: Filter): boolean =>
  isFtsTextField(filter.field);

const validateIndexedInputOutputFilters = (filter: FilterList) => {
  const hasIoFilter = filter.some(isInputOutputFilter);
  if (!hasIoFilter) {
    return;
  }

  const hasRequiredIoFilter = filter.some(
    (f) => isInputOutputFilter(f) && isFtsAcceleratedIoOperator(f.operator),
  );
  if (!hasRequiredIoFilter) {
    throw new InvalidRequestError(
      "Input/output filters require at least one `matches` or `=` operator.",
    );
  }
};

/**
 * Build observation query components: an EventsQueryBuilder (with JOINs and filters but
 * without CTEs) and any external CTEs that should be composed at the outer level.
 *
 * This enables CTE-based split queries where external CTEs (e.g. traces) are hoisted
 * to the outer WITH clause rather than embedded in the EventsQueryBuilder.
 */
function buildObservationsQueryComponents(
  opts: PublicApiObservationsQuery,
  columnDefinitions: UiColumnMappings = eventsTableNativeUiColumnDefinitions,
  options: BuildObservationsQueryComponentsOptions = {},
): {
  queryBuilder: EventsQueryBuilder;
  externalCTEs: Array<{
    name: string;
    queryWithParams: { query: string; params: Record<string, any> };
  }>;
  filtersNeedFullTable: boolean;
  observationsFilter: FilterList;
} {
  const { projectId, advancedFilters, ...filterParams } = opts;

  if (!options.allowUnindexedIoFilters) {
    validateInputOutputFilterTypes(advancedFilters, columnDefinitions);
  }

  // Convert and merge simple and advanced filters
  const observationsFilter = deriveFilters(
    { ...filterParams, projectId },
    PUBLIC_API_EVENTS_COLUMN_MAPPING,
    advancedFilters,
    columnDefinitions,
    eventsTableCols,
  );

  if (!options.allowUnindexedIoFilters) {
    validateIndexedInputOutputFilters(observationsFilter);
  }

  // Determine if we need to join traces (check both simple params and advanced filters)
  const hasTraceFilter = observationsFilter.some(
    (f) => f.clickhouseTable === "traces",
  );
  const filtersNeedFullTable = filtersRequireEventsFull(observationsFilter);

  const startTimeFrom = extractTimeFilter(observationsFilter);
  const appliedFilter = observationsFilter.apply();

  // Build external CTEs
  const externalCTEs: Array<{
    name: string;
    queryWithParams: { query: string; params: Record<string, any> };
  }> = [];
  if (hasTraceFilter) {
    externalCTEs.push({
      name: "traces",
      queryWithParams: eventsTracesAggregation({
        projectId,
        startTimeFrom,
      }).buildWithParams(),
    });
  }

  // Build query with joins and filters (no CTEs)
  const queryBuilder = new EventsQueryBuilder({ projectId })
    .when(filtersNeedFullTable, (b) => b.forceFullTable())
    .when(hasTraceFilter, (b) =>
      b.leftJoin(
        "traces t",
        "ON t.id = e.trace_id AND t.project_id = e.project_id",
      ),
    )
    .where(appliedFilter);

  return {
    queryBuilder,
    externalCTEs,
    filtersNeedFullTable,
    observationsFilter,
  };
}

function buildObservationsQueryBase(
  opts: PublicApiObservationsQuery,
  columnDefinitions: UiColumnMappings = eventsTableNativeUiColumnDefinitions,
): EventsQueryBuilder {
  const { queryBuilder, externalCTEs } = buildObservationsQueryComponents(
    opts,
    columnDefinitions,
    { allowUnindexedIoFilters: true },
  );
  for (const cte of externalCTEs) {
    queryBuilder.withCTE(cte.name, cte.queryWithParams);
  }
  return queryBuilder;
}

function orderByForObservationsQuery(
  prefix = "e",
  span_id = "span_id",
): OrderByEntry[] {
  // Order by to cursor ordering.
  // project_id and potentially other prefixes are injected in the query builder when necessary
  return [
    { column: `${prefix}.start_time`, direction: "DESC" as const },
    { column: `xxHash32(${prefix}.trace_id)`, direction: "DESC" as const },
    { column: `${prefix}.${span_id}`, direction: "DESC" as const },
  ];
}

function applyOrderByForObservationsQuery(
  queryBuilder: EventsQueryBuilder,
): EventsQueryBuilder {
  return queryBuilder.orderByColumns(orderByForObservationsQuery("e"));
}

function applyOffsetPagination(
  opts: PublicApiObservationsQuery,
  queryBuilder: EventsQueryBuilder,
): EventsQueryBuilder {
  // Apply offset pagination for page-based requests
  const offset = (opts.page - 1) * opts.limit;
  return queryBuilder.limit(opts.limit, offset);
}

function applyObservationsCursorFilter(
  cursor: PublicApiObservationsQuery["cursor"] | undefined,
  queryBuilder: EventsQueryBuilder,
): EventsQueryBuilder {
  // The cursor carries start_time at millisecond precision (JS Date round-trip),
  // while the column is DateTime64(6). This is lossless only because every
  // ingestion path writes ms-aligned start_time values (OTel nanos are floored
  // to ms). If ingestion ever preserves sub-millisecond precision, this bound
  // floors to the boundary row's millisecond and permanently skips rows at page
  // boundaries — carry the raw ClickHouse string through the cursor instead (LFE-10405).
  return queryBuilder.when(Boolean(cursor), (b) => {
    const currentCursor = cursor;
    if (!currentCursor) {
      return b;
    }

    return b.whereRaw(
      "e.start_time <= {lastStartTime: DateTime64(6)} AND (e.start_time, xxHash32(e.trace_id), e.span_id) < ({lastStartTime: DateTime64(6)}, xxHash32({lastTraceId: String}), {lastId: String})",
      {
        lastStartTime: convertDateToClickhouseDateTime(
          currentCursor.lastStartTimeTo,
        ),
        lastTraceId: currentCursor.lastTraceId,
        lastId: currentCursor.lastId,
      },
    );
  });
}

function applyCursorPagination(
  opts: PublicApiObservationsQuery,
  queryBuilder: EventsQueryBuilder,
): EventsQueryBuilder {
  queryBuilder = applyObservationsCursorFilter(opts.cursor, queryBuilder);

  // Always apply limit (fetch limit+1 to detect if there are more results)
  return queryBuilder.limit(opts.limit + 1, undefined);
}

async function getObservationsRowsFromBuilder<T>(
  projectId: string,
  queryBuilder: QueryWithParams,
  extraTags: Record<string, string> = {},
  clickhouseSettings?: ClickHouseSettings,
): Promise<Array<T>> {
  const { query, params } = queryBuilder.buildWithParams();

  return await queryClickhouse<T>({
    query,
    params,
    tags: { projectId, ...extraTags },
    preferredClickhouseService: "EventsReadOnly",
    clickhouseSettings: {
      // Buffering reads ahead on every stream; wasted once LIMIT is filled.
      read_in_order_use_buffering: 0,
      ...clickhouseSettings,
    },
  });
}

/**
 * Internal function to get count of observations from events table for public API.
 */
async function getObservationsCountFromEventsTableForPublicApiInternal(
  opts: PublicApiObservationsQuery,
): Promise<Array<{ count: string }>> {
  const { projectId } = opts;

  // Build query with filters and common CTEs
  const queryBuilder = buildObservationsQueryBase(opts);

  // Select count field set
  queryBuilder.selectFieldSet("count");

  const { query, params } = queryBuilder.buildWithParams();

  const result = await queryClickhouse<{ count: string }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return result;
}

/**
 * V1 API: Get observations list from events table for public API
 * Returns complete observations with all fields for transformDbToApiObservation
 */
export const getObservationsFromEventsTableForPublicApi = async (
  opts: Omit<PublicApiObservationsQuery, "fields">,
): Promise<Array<EventsObservation & ObservationPriceFields>> => {
  const { projectId } = opts;

  // Build query with filters and common CTEs
  const queryBuilder = applyOffsetPagination(
    opts,
    applyOrderByForObservationsQuery(buildObservationsQueryBase(opts)),
  );

  OBSERVATION_FIELD_GROUPS_PUBLIC_API.forEach((fieldGroup) => {
    queryBuilder.selectFieldSet(fieldGroup);
  });

  const observationRecords =
    await getObservationsRowsFromBuilder<EventsObservationQueryResult>(
      projectId,
      queryBuilder,
    );

  const observations = await enrichObservationsWithModelData(
    observationRecords,
    opts.projectId,
    opts.parseIoAsJson ?? true, // V1 API: default to parsing JSON (backwards compatibility)
    null, // V1 API: no field groups, return complete observations
  );

  return observations;
};

export const getObservationsV2FromEventsTableForPublicApi = async (
  opts: PublicApiObservationsQuery,
  options: BuildObservationsQueryComponentsOptions = {},
): Promise<Array<EventsObservationPublic>> => {
  const builder = buildObservationsV2Query(opts, options);

  const records =
    await getObservationsRowsFromBuilder<EventsObservationQueryResult>(
      opts.projectId,
      builder,
      {},
      options.clickhouseSettings,
    );

  return await enrichObservationsWithModelData(
    records,
    opts.projectId,
    false, // V2 API: IO fields are always returned as raw strings
    opts.fields ?? ["core", "basic"],
  );
};

/** Assemble a page from completed windows, including empty continuations. */
export const getObservationsV2PageFromEventsTableForPublicApi = async (
  opts: PublicApiObservationsQuery,
): Promise<{
  items: EventsObservationPublic[];
  cursor: PublicApiObservationsQuery["cursor"];
}> =>
  instrumentAsync({ name: "observations-v2-scan" }, async (span) => {
    if (opts.limit === 0) return { items: [], cursor: undefined };
    const scan = createObservationsScan(opts.projectId);
    try {
      const bounds = extractObservationsStartTimeBounds(opts);
      const from = bounds.from ?? OBSERVATIONS_DEFAULT_FROM_MS;
      if (bounds.to !== undefined && from > bounds.to) {
        return { items: [], cursor: undefined };
      }
      const page = await scanObservationWindows(opts, from, bounds.to, scan);
      span.setAttribute("observations.scan.windows", page.windows);
      return {
        items: await enrichObservationsWithModelData(
          page.records.slice(0, opts.limit),
          opts.projectId,
          false,
          opts.fields ?? ["core", "basic"],
        ),
        cursor: page.cursor,
      };
    } finally {
      span.setAttributes(scan.getAttributes());
    }
  });

function extractObservationsStartTimeBounds(opts: PublicApiObservationsQuery) {
  const { observationsFilter } = buildObservationsQueryComponents(opts);
  let from: number | undefined;
  let to = opts.cursor?.lastStartTimeTo.getTime();
  observationsFilter.forEach((filter) => {
    if (!isTimeFilter(filter)) return;
    const value = filter.value.getTime();
    if (filter.operator === ">" || filter.operator === ">=") {
      from = Math.max(from ?? value, value);
    } else if (filter.operator === "<" || filter.operator === "<=") {
      to = Math.min(to ?? value, value);
    }
  });
  return { from, to };
}

async function scanObservationWindows(
  opts: PublicApiObservationsQuery,
  from: number,
  to: number | undefined,
  scan: ObservationsScan,
) {
  let records: EventsObservationQueryResult[] = [];
  let cursor: PublicApiObservationsQuery["cursor"];
  let windows = 0;
  let window: { durationMs: number; estimatedMs?: number } | undefined = {
    durationMs: OBSERVATIONS_SCAN_WINDOW_MS,
  };
  // An omitted upper bound stays open on the first query for future timestamps.
  let upper = to ?? Math.max(Date.now(), from);
  while (window !== undefined) {
    const windowStarted = performance.now();
    const lower = Math.max(from, upper - window.durationMs);
    const result = await queryObservationWindow(
      opts,
      records.length,
      {
        from: new Date(lower),
        to: to === undefined ? undefined : new Date(upper),
        inclusiveTo: windows === 0,
        estimatedMs: window.estimatedMs,
      },
      scan,
      windows,
    );
    if (result === undefined) break;
    windows++;
    records = records.concat(result.rows);
    if (records.length > opts.limit) {
      cursor = observationRowCursor(records[opts.limit - 1]);
      break;
    }
    if (lower === from) {
      cursor = undefined;
      break;
    }
    cursor = observationTimeCursor(lower);
    window = planNextObservationsWindow(
      upper - lower,
      lower - from,
      result,
      performance.now() - windowStarted,
      scan.remainingMs(),
    );
    upper = lower;
    to = lower;
  }
  return { records, cursor, windows };
}

async function queryObservationWindow(
  opts: PublicApiObservationsQuery,
  collected: number,
  window: {
    from: Date;
    to?: Date;
    inclusiveTo: boolean;
    estimatedMs?: number;
  },
  scan: ObservationsScan,
  completedWindows: number,
) {
  return instrumentAsync(
    { name: "observations-v2-scan-window" },
    async (span) => {
      const started = performance.now();
      if (window.estimatedMs !== undefined) {
        span.setAttribute("observations.scan.estimated_ms", window.estimatedMs);
      }
      try {
        const result = await scan.query<EventsObservationQueryResult>(
          buildObservationsV2Query(
            { ...opts, limit: opts.limit - collected },
            {},
            window,
          ),
        );
        span.setAttribute("observations.scan.completed", true);
        span.setAttribute("observations.scan.read_bytes", result.readBytes);
        if (result.readRows !== undefined)
          span.setAttribute("observations.scan.read_rows", result.readRows);
        return result;
      } catch (error) {
        // Only completed windows may advance the cursor on timeout.
        if (
          completedWindows > 0 &&
          error instanceof ClickHouseResourceError &&
          error.errorType === "TIMEOUT"
        ) {
          return undefined;
        }
        throw error;
      } finally {
        span.setAttribute(
          "observations.scan.elapsed_ms",
          performance.now() - started,
        );
      }
    },
  );
}

function observationRowCursor(last: EventsObservationQueryResult) {
  return {
    lastStartTimeTo: parseClickhouseUTCDateTimeFormat(last.start_time),
    lastTraceId: last.trace_id ?? "",
    lastId: last.id,
  };
}

function observationTimeCursor(lower: number) {
  return {
    lastStartTimeTo: new Date(lower),
    lastTraceId: OBSERVATIONS_TIME_CURSOR_TRACE_ID,
    lastId: "",
  };
}

function planNextObservationsWindow(
  windowMs: number,
  remainingRangeMs: number,
  last: { readRows: number | undefined; readBytes: number },
  elapsedMs: number,
  remainingMs: number,
) {
  if (remainingMs <= 0) return undefined;

  // Client wall time includes retries and stream consumption; GB is decimal.
  const costMs = Math.max(
    elapsedMs,
    (last.readBytes / 1e9) * OBSERVATIONS_MS_PER_GB,
  );
  const availableMs = remainingMs - OBSERVATIONS_QUERY_OVERHEAD_MS;
  // Near the deadline, do not shrink the interval just to reserve overhead.
  let timeMultiplier = 1;
  if (availableMs > 0) {
    timeMultiplier = costMs > 0 ? availableMs / costMs : Infinity;
  }
  const rowMultiplier =
    last.readRows !== undefined && last.readRows > 0
      ? OBSERVATIONS_QUERY_ROW_TARGET / last.readRows
      : Infinity;
  // Missing statistics or empty scans cannot justify unrestricted growth.
  let growthLimit = Infinity;
  if (last.readRows === undefined) growthLimit = 1;
  else if (last.readRows === 0 && last.readBytes === 0) growthLimit = 4;

  const durationMs = Math.min(
    remainingRangeMs,
    Math.max(
      1,
      Math.floor(
        windowMs * Math.min(timeMultiplier, rowMultiplier, growthLimit),
      ),
    ),
  );
  return {
    durationMs,
    estimatedMs:
      OBSERVATIONS_QUERY_OVERHEAD_MS + (durationMs / windowMs) * costMs,
  };
}

/** Own the deadline and cumulative work counters for all queries in one page. */
function createObservationsScan(projectId: string) {
  const started = performance.now();
  const abortSignal = AbortSignal.timeout(OBSERVATIONS_SCAN_BUDGET_MS);
  let readRows = 0;
  let readBytes = 0;
  const remainingMs = () =>
    OBSERVATIONS_SCAN_BUDGET_MS - (performance.now() - started);
  const query = async <T>(builder: QueryWithParams) => {
    let queryRows: number | undefined;
    let queryBytes = 0;
    try {
      const rows = await runObservationsScanQuery<T>(
        builder,
        projectId,
        abortSignal,
        remainingMs(),
        (scanned, bytes) => {
          // Streaming progress is cumulative, including work from retried attempts.
          readRows += scanned - (queryRows ?? 0);
          readBytes += bytes - queryBytes;
          queryRows = scanned;
          queryBytes = bytes;
        },
      );
      // Completed empty streams omit zero progress; nonzero reads flush on completion.
      return {
        rows,
        readRows: queryRows ?? (rows.length === 0 ? 0 : undefined),
        readBytes: queryBytes,
      };
    } catch (error) {
      if (error instanceof ClickHouseQueryAbortedError) {
        throw new ClickHouseResourceError("TIMEOUT", error);
      }
      throw error;
    }
  };
  return {
    query,
    remainingMs,
    getAttributes: () => ({
      "observations.scan.read_rows": readRows,
      "observations.scan.read_bytes": readBytes,
      "observations.scan.elapsed_ms": performance.now() - started,
    }),
  };
}

async function runObservationsScanQuery<T>(
  builder: QueryWithParams,
  projectId: string,
  abortSignal: AbortSignal,
  remainingMs: number,
  onProgress: (readRows: number, readBytes: number) => void,
): Promise<T[]> {
  const rows: T[] = [];
  for await (const item of queryClickhouseWithProgress<T>({
    ...builder.buildWithParams(),
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
    abortSignal,
    clickhouseConfigs: { request_timeout: OBSERVATIONS_SCAN_BUDGET_MS },
    clickhouseSettings: {
      read_in_order_use_buffering: 0,
      max_execution_time: Math.max(0.001, remainingMs / 1000),
      timeout_overflow_mode: "throw",
      timeout_before_checking_execution_speed: 0,
      cancel_http_readonly_queries_on_client_close: 1,
    },
  })) {
    if (isRow<T>(item)) rows.push(item.row);
    if (isProgressRow(item))
      onProgress(
        Number(item.progress.read_rows),
        Number(item.progress.read_bytes),
      );
    if (isException(item))
      throw ClickHouseResourceError.wrapIfResourceError(
        new Error(item.exception),
      );
  }
  return rows;
}

/**
 * V2 API: Get observations list from events table for public API
 * Returns partial observations based on requested field groups
 * Field filtering happens at query time in ClickHouse
 *
 * When IO or expanded metadata is requested, uses a CTE-based split query:
 * - base CTE: filters/orders/limits on events_core (fast, truncated)
 * - io CTE: fetches full IO/metadata from events_full for matched rows only
 * This avoids expensive full-table scans on events_full.
 */
function buildObservationsV2Query(
  opts: PublicApiObservationsQuery,
  options: BuildObservationsQueryComponentsOptions = {},
  window?: { from: Date; to?: Date; inclusiveTo: boolean },
): QueryWithParams {
  const { projectId, expandMetadataKeys } = opts;

  // Determine which field groups to include
  const requestedFields = opts.fields ?? ["core", "basic"];

  const needsIO = requestedFields.includes("io");
  const needsExpandedMetadata =
    requestedFields.includes("metadata") &&
    expandMetadataKeys != null &&
    expandMetadataKeys.length > 0;
  const needsIOCTE = needsIO || needsExpandedMetadata;

  // Shared: build base query with field sets, ordering, pagination
  const {
    queryBuilder: baseBuilder,
    externalCTEs,
    filtersNeedFullTable,
  } = buildObservationsQueryComponents(
    opts,
    eventsTableNativeUiColumnDefinitions,
    options,
  );

  // Apply scan bounds after merging user filters so structured filters cannot
  // override them. The same bounded base feeds the full-payload lookup.
  if (window) {
    for (const [value, operator] of [
      [window.from, ">="],
      [window.to, window.inclusiveTo ? "<=" : "<"],
    ] as const) {
      if (!value) continue;
      baseBuilder.where(
        new DateTimeFilter({
          clickhouseTable: "events_core",
          field: "start_time",
          tablePrefix: "e",
          operator,
          value,
        }).apply(),
      );
    }
  }

  // The io lane only pays off when base reads the cheap truncated table
  // (events_core) and the split defers the heavy input/output/metadata columns
  // to a page-size lookup on events_full. When a filter touches input/output,
  // `filtersNeedFullTable` already forces base onto events_full to evaluate that
  // filter, so there is nothing left to defer — the split just re-scans
  // events_full several times (base is referenced from the io lane and the final
  // join, and ClickHouse inlines CTEs). Read io/metadata inline on base instead.
  const useSplit = needsIOCTE && !filtersNeedFullTable;

  // Metadata goes to the io CTE only when we actually split; on the simple path
  // base already reads events_full (forced by the filter) so metadata is
  // untruncated there.
  const metadataFromIoCte = useSplit && requestedFields.includes("metadata");

  // Shared steps: ordering and pagination apply to every path and are
  // independent of which columns each path projects.
  applyOrderByForObservationsQuery(baseBuilder);
  applyCursorPagination(opts, baseBuilder);

  const queryPath: "simple" | "cte-join" = useSplit ? "cte-join" : "simple";

  // Field groups projected on the base builder. In the split, `io` (and
  // `metadata`) is fetched by the io CTE instead; selecting it on events_core
  // would return truncated values. On the simple path base is on events_full
  // whenever io/metadata is requested (filter-forced), so it is selected inline.
  const selectBaseFieldSets = () => {
    baseBuilder.selectFieldSet("core");
    const excludeFromBase = new Set<string>(["core"]);
    if (useSplit) {
      excludeFromBase.add("io");
      if (metadataFromIoCte) excludeFromBase.add("metadata");
    }
    requestedFields
      .filter((fg) => !excludeFromBase.has(fg))
      .forEach((fg) => baseBuilder.selectFieldSet(fg));
  };

  let builder: QueryWithParams;
  switch (queryPath) {
    case "simple":
      // Everything from events_core; CTEs attach directly to the builder.
      selectBaseFieldSets();
      for (const cte of externalCTEs) {
        baseBuilder.withCTE(cte.name, cte.queryWithParams);
      }
      builder = baseBuilder;
      break;
    case "cte-join":
      // Scalar groups from events_core, IO/metadata joined from events_full.
      selectBaseFieldSets();
      builder = buildEventsFullTableSplitQuery({
        projectId,
        baseBuilder,
        includeIO: needsIO,
        includeMetadata: metadataFromIoCte,
        externalCTEs,
      }).orderByColumns(orderByForObservationsQuery("b", "id"));
      break;
  }

  return builder;
}

type ObservationsScan = ReturnType<typeof createObservationsScan>;

/**
 * Get count of observations from events table for public API.
 */
export const getObservationsCountFromEventsTableForPublicApi = async (
  opts: PublicApiObservationsQuery,
): Promise<number> => {
  const countResult =
    await getObservationsCountFromEventsTableForPublicApiInternal(opts);
  return Number(countResult[0].count);
};

type PublicApiTracesQuery = {
  projectId: string;
  page: number;
  limit: number;
  userId?: string;
  name?: string;
  tags?: string | string[];
  sessionId?: string;
  version?: string;
  release?: string;
  environment?: string | string[];
  fromTimestamp?: string;
  toTimestamp?: string;
  fields?: string[];
  advancedFilters?: FilterState;
  orderBy?: { column: string; order: "ASC" | "DESC" } | null;
};

/**
 * Internal implementation for public API traces queries.
 * Uses eventsTracesAggregation to create a traces CTE that
 * behaves similarly to the old traces table.
 */
async function getTracesFromEventsTableForPublicApiInternal<T>(
  opts: PublicApiTracesQuery & { select: "rows" | "count" },
): Promise<Array<T>> {
  const {
    projectId,
    page,
    limit,
    advancedFilters,
    fields,
    orderBy,
    ...filterParams
  } = opts;

  // Determine which field groups are requested
  const includeIO = Boolean(fields?.includes("io"));
  const includeScores = Boolean(fields?.includes("scores"));
  const includeObservations = Boolean(fields?.includes("observations"));
  const includeMetrics = Boolean(fields?.includes("metrics"));

  // Convert and merge simple and advanced filters
  const tracesFilter = deriveFilters(
    { ...filterParams, projectId, page, limit },
    PUBLIC_API_TRACES_COLUMN_MAPPING,
    advancedFilters,
    TRACES_FROM_EVENTS_UI_COLUMN_DEFINITIONS,
    tracesTableCols,
  );

  // Extract time filter for cut-off point in eventsTracesAggregation
  // After aggregation, the time column is "timestamp" (not "start_time")
  const startTimeFrom = extractTimeFilter(tracesFilter, "traces", "timestamp");

  const appliedFilter = tracesFilter.apply();

  // Check if any filters reference the scores table
  const filtersNeedScores = tracesFilter.some(
    (f) => f.clickhouseTable === "scores",
  );

  // Check if filters specifically reference score aggregation columns
  const hasScoreAggregationFilters = tracesFilter.some(
    (f) =>
      f.field === "s.scores_avg" ||
      f.field === "s.score_categories" ||
      f.field === "s.score_booleans",
  );
  const scoreRowsFilter = planScoreFilterPushdown({
    filters: tracesFilter,
    scoreDataRequirement: resolveScoreDataRequirement({
      selectsScoreData: opts.select === "rows" && includeScores,
    }),
  });

  // Build traces CTE using eventsTracesAggregation WITHOUT filters
  // Filters must be applied AFTER aggregation to ensure filters on aggregated
  // fields (like timestamp or version) are applied correctly
  // Use events_full when I/O is requested (truncated: false), otherwise events_core
  const tracesBuilder = eventsTracesAggregation({
    projectId,
    startTimeFrom,
    truncated: !includeIO,
  });

  // Build the final query using CTEQueryBuilder
  let queryBuilder = new CTEQueryBuilder()
    .withCTEFromBuilder("traces", tracesBuilder)
    .from("traces", "t")
    .where(appliedFilter);

  if (includeScores || filtersNeedScores) {
    const scoresCTE = eventsTracesScoresAggregation({
      projectId,
      startTimeFrom,
      hasScoreAggregationFilters,
      scoreRowsFilter,
    });
    queryBuilder = queryBuilder
      .withCTE("score_stats", {
        ...scoresCTE,
        schema: [
          "trace_id",
          "project_id",
          "score_ids",
          "scores_avg",
          "score_categories",
          "score_booleans",
        ],
      })
      .leftJoin(
        "score_stats",
        "s",
        "ON s.trace_id = t.id AND s.project_id = t.project_id",
      );
  }

  // Select fields based on query type and field groups
  if (opts.select === "count") {
    queryBuilder.select("count() as count");
  } else {
    // Build select list
    queryBuilder = queryBuilder.selectColumns(
      "t.id",
      "t.project_id",
      "t.timestamp",
      "t.name",
      "t.environment",
      "t.session_id",
      "t.user_id",
      "t.version",
      "t.created_at",
      "t.updated_at",
      "t.tags",
      "t.bookmarked",
      "t.public",
      "t.release",
    );

    queryBuilder.select(
      "CONCAT('/project/', t.project_id, '/traces/', t.id) as htmlPath",
    );

    // Conditionally include other field groups
    if (includeIO) {
      queryBuilder = queryBuilder.selectColumns(
        "t.input",
        "t.output",
        "t.metadata",
      );
    }
    if (includeScores) {
      queryBuilder.select("s.score_ids as scores");
    }
    if (includeObservations) {
      queryBuilder.select("t.observation_ids as observations");
    }
    if (includeMetrics) {
      queryBuilder.select(
        "t.total_cost as totalCost",
        "COALESCE(t.latency_milliseconds / 1000, 0) as latency",
      );
    }

    const chOrderBy =
      orderByToClickhouseSql(
        orderBy ? [orderBy] : [],
        TRACES_ORDER_BY_COLUMNS,
      ) || "ORDER BY t.project_id DESC, t.timestamp DESC";

    queryBuilder.orderBy(chOrderBy).limit(limit, (page - 1) * limit);
  }

  const { query, params } = queryBuilder.buildWithParams();

  const result = await queryClickhouse<T>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return result;
}

/**
 * Get traces list from events table for public API.
 * Aggregates events by trace_id to rebuild traces with observation metrics.
 */
export const getTracesFromEventsTableForPublicApi = async (
  opts: PublicApiTracesQuery,
): Promise<Array<any>> => {
  const requestedFields = opts.fields ?? [
    "core",
    "io",
    "scores",
    "observations",
    "metrics",
  ];
  const includeScores = requestedFields.includes("scores");
  const includeObservations = requestedFields.includes("observations");
  const includeMetrics = requestedFields.includes("metrics");

  const result = await getTracesFromEventsTableForPublicApiInternal<any>({
    ...opts,
    select: "rows",
  });

  // Convert ClickHouse format to domain format and handle field groups
  return convertClickhouseTracesListToDomain(result, {
    scores: includeScores,
    observations: includeObservations,
    metrics: includeMetrics,
  });
};

/**
 * Get count of traces from events table for public API.
 * Uses same aggregation as list query to ensure consistent filtering.
 */
export const getTracesCountFromEventsTableForPublicApi = async (
  opts: PublicApiTracesQuery,
): Promise<number> => {
  const countResult = await getTracesFromEventsTableForPublicApiInternal<{
    count: string;
  }>({
    ...opts,
    select: "count",
  });
  return Number(countResult[0].count);
};

const updateableEventKeys = ["bookmarked", "public"] as const;

type UpdateableEventFields = {
  [K in (typeof updateableEventKeys)[number]]?: boolean;
};

/**
 * Update events in ClickHouse based on selector and updates provided.
 * Selector can filter by spanIds, traceIds, and rootOnly flag.
 * Both spanIds / traceIds are used only when defined and non-empty.
 * E.g. `{ traceIds: [...] }` will only filter by traceIds, while
 * `{ spanIds: [...], traceIds: [...] }` will filter by both.
 *
 * Updates both events_full and events_core tables.
 */
export const updateEvents = async (
  projectId: string,
  selector: { spanIds?: string[]; traceIds?: string[]; rootOnly?: boolean },
  updates: UpdateableEventFields,
): Promise<void> => {
  const setClauses: string[] = [];
  for (const key of updateableEventKeys) {
    if (updates[key] !== undefined) {
      setClauses.push(`${key} = {${key}: Bool}`);
    }
  }
  if (setClauses.length === 0) {
    // Nothing to update
    return;
  }

  const whereClause = `
    WHERE project_id = {projectId: String}
    ${selector.spanIds ? "AND span_id IN ({spanIds: Array(String)})" : ""}
    ${selector.traceIds ? "AND trace_id IN ({traceIds: Array(String)})" : ""}
    ${selector.rootOnly === true ? "AND parent_span_id = ''" : ""}
  `;

  const params = {
    projectId,
    spanIds: selector.spanIds ?? [],
    traceIds: selector.traceIds ?? [],
    ...updates,
  };

  const useLightweightUpdate = env.CLICKHOUSE_USE_LIGHTWEIGHT_UPDATE === "true";

  const updateOpts = (table: string) => ({
    query: useLightweightUpdate
      ? `UPDATE ${table} SET ${setClauses.join(", ")} ${whereClause}`
      : `ALTER TABLE ${table} UPDATE ${setClauses.join(", ")} ${whereClause}`,
    params,
    tags: { projectId },
  });

  await Promise.all([
    commandClickhouse(updateOpts("events_full")),
    commandClickhouse(updateOpts("events_core")),
  ]);
};

type GroupedEventsFilterOptions = {
  limit?: number;
  scope?: EventFilterOptionScope;
};

type BuiltEventsFilterOptionColumnQuery = NonNullable<
  ReturnType<typeof buildEventsFilterOptionColumnQuery>
>;
type BuiltEventsFilterOptionsForColumnsQuery = NonNullable<
  ReturnType<typeof buildEventsFilterOptionsForColumnsQuery>
>;
type BuiltEventsExactFilterOptionsForColumnsQuery = NonNullable<
  ReturnType<typeof buildEventsExactFilterOptionsForColumnsQuery>
>;

const queryEventsFilterOptionRows = async (
  projectId: string,
  queryWithParams:
    | BuiltEventsFilterOptionColumnQuery
    | BuiltEventsFilterOptionsForColumnsQuery
    | BuiltEventsExactFilterOptionsForColumnsQuery,
  clickhouseSettings?: ClickHouseSettings,
) => {
  return queryClickhouse<EventFilterOptionRow>({
    query: queryWithParams.query,
    params: queryWithParams.params,
    tags: { projectId },
    clickhouseSettings,
    preferredClickhouseService: "EventsReadOnly",
  });
};

const queryEventsFilterOptionsForColumns = async (params: {
  projectId: string;
  filter: FilterState;
  columns: readonly EventFilterOptionColumn[];
  limit: number;
  scope?: EventFilterOptionScope;
  includeApproxCount?: boolean;
}) => {
  const queryWithParams = buildEventsFilterOptionsForColumnsQuery({
    projectId: params.projectId,
    filter: params.filter,
    columns: params.columns,
    limit: params.limit,
    scope: params.scope,
    includeApproxCount: params.includeApproxCount,
    sampleRows: EVENTS_FILTER_OPTION_SAMPLE_ROWS,
  });

  if (!queryWithParams) {
    return [];
  }

  return queryEventsFilterOptionRows(params.projectId, queryWithParams);
};

const queryEventsFilterOptionColumn = async (params: {
  projectId: string;
  filter: FilterState;
  column: EventFilterOptionColumn;
  limit: number;
  offset?: number;
  scope?: EventFilterOptionScope;
  sampleRows?: number;
  clickhouseSettings?: ClickHouseSettings;
}) => {
  const queryWithParams = buildEventsFilterOptionColumnQuery({
    projectId: params.projectId,
    filter: params.filter,
    column: params.column,
    limit: params.limit,
    offset: params.offset,
    scope: params.scope,
    sampleRows: params.sampleRows,
  });

  if (!queryWithParams) {
    return [];
  }

  return queryEventsFilterOptionRows(
    params.projectId,
    queryWithParams,
    params.clickhouseSettings,
  );
};

export const getEventsFilterOptionsForColumns = async (params: {
  projectId: string;
  filter: FilterState;
  columns: readonly EventFilterOptionColumn[];
  topN?: number;
  scope?: EventFilterOptionScope;
  includeApproxCount?: boolean;
}) =>
  queryEventsFilterOptionsForColumns({
    ...params,
    limit: params.topN ?? EVENTS_FILTER_OPTION_TOP_N,
  });

/** Exact per-column facets in one events_core scan: sumMap/countIf aggregate state fanned out with arrayJoin (no GROUP BY / UNION ALL). */
export const getEventsExactFilterOptionsForColumns = async (params: {
  projectId: string;
  filter: FilterState;
  columns: readonly EventFilterOptionColumn[];
  topN?: number;
  scope?: EventFilterOptionScope;
}) => {
  const queryWithParams = buildEventsExactFilterOptionsForColumnsQuery({
    projectId: params.projectId,
    filter: params.filter,
    columns: params.columns,
    limit: params.topN ?? EVENTS_FILTER_OPTION_TOP_N,
    scope: params.scope,
    sampleRows: EVENTS_FILTER_OPTION_SAMPLE_ROWS,
  });

  if (!queryWithParams) {
    return [];
  }

  return queryEventsFilterOptionRows(params.projectId, queryWithParams);
};

// Unsampled: the cursor contract lets MCP agents page the true distinct set.
export const getEventsFilterOptionValuesPage = async (params: {
  projectId: string;
  filter: FilterState;
  column: EventFilterOptionColumn;
  limit: number;
  offset: number;
  clickhouseSettings?: ClickHouseSettings;
}) =>
  queryEventsFilterOptionColumn({
    projectId: params.projectId,
    filter: params.filter,
    column: params.column,
    limit: params.limit,
    offset: params.offset,
    clickhouseSettings: params.clickhouseSettings,
  });

/** EventsMetadataOptionRow is one metadata key or value with its event count. */
export type EventsMetadataOptionRow = { value: string; count: number };

/** getEventsMetadataValues returns the top-N distinct values for one metadata key on the events table. */
export const getEventsMetadataValues = async (params: {
  projectId: string;
  filter: FilterState;
  key: string;
  topN?: number;
}): Promise<EventsMetadataOptionRow[]> => {
  const queryWithParams = buildEventsMetadataValuesQuery({
    projectId: params.projectId,
    filter: params.filter,
    key: params.key,
    limit: params.topN ?? EVENTS_FILTER_OPTION_TOP_N,
    sampleRows: EVENTS_FILTER_OPTION_SAMPLE_ROWS,
  });

  if (!queryWithParams) {
    return [];
  }

  return queryClickhouse<EventsMetadataOptionRow>({
    query: queryWithParams.query,
    params: queryWithParams.params,
    tags: { projectId: params.projectId },
    preferredClickhouseService: "EventsReadOnly",
  });
};

const getSingleEventsFilterOptionColumn = async (
  projectId: string,
  filter: FilterState,
  column: EventFilterOptionColumn,
  opts?: GroupedEventsFilterOptions,
) =>
  queryEventsFilterOptionColumn({
    projectId,
    filter,
    column,
    limit: opts?.limit ?? EVENTS_FILTER_OPTION_TOP_N,
    scope: opts?.scope,
    sampleRows: EVENTS_FILTER_OPTION_SAMPLE_ROWS,
  });

export const getEventsGroupedByTraceTags = async (
  projectId: string,
  filter: FilterState,
  opts?: GroupedEventsFilterOptions,
) => {
  const rows = await getSingleEventsFilterOptionColumn(
    projectId,
    filter,
    "traceTags",
    opts,
  );
  return rows.map((row) => ({ tag: row.value }));
};

export const getEventsGroupedByUserId = async (
  projectId: string,
  filter: FilterState,
  opts?: GroupedEventsFilterOptions,
) => {
  const rows = await getSingleEventsFilterOptionColumn(
    projectId,
    filter,
    "userId",
    opts,
  );
  return rows.map((row) => ({ userId: row.value, count: row.count }));
};

// Unsampled: a sampled max() under-reports, hiding real outliers from MCP agents.
export const getEventsNumericStatsByFilterColumn = async (
  projectId: string,
  filter: FilterState,
  columnId: Exclude<
    NumericEventsTableColumnId,
    "inputTokens" | "outputTokens" | "inputCost" | "outputCost"
  >,
  clickhouseSettings?: ClickHouseSettings,
) => {
  const column = eventsTableCols.find((col) => col.id === columnId);

  if (!column || column.type !== "number") {
    throw new Error(`Column ${columnId} is not supported for numeric stats`);
  }

  const eventsFilter = new FilterList(
    createFilterFromFilterState(
      filter,
      eventsTableUiColumnDefinitions,
      eventsTableCols,
    ),
  );

  const valueExpression = column.internal;
  const appliedEventsFilter = eventsFilter.apply();

  const queryBuilder = new EventsAggQueryBuilder({
    projectId,
    groupByColumn: "tuple()",
    selectExpression: `min(${valueExpression}) as min, max(${valueExpression}) as max, avg(${valueExpression}) as avg, count(${valueExpression}) as count`,
  })
    .where(appliedEventsFilter)
    .whereRaw(`isNotNull(${valueExpression})`);

  const { query, params } = queryBuilder.buildWithParams();

  const res = await queryClickhouse<{
    min: number | null;
    max: number | null;
    avg: number | null;
    count: number;
  }>({
    query,
    params,
    tags: { projectId },
    clickhouseSettings,
    preferredClickhouseService: "EventsReadOnly",
  });
  const range = res[0];

  if (
    !range ||
    range.min === null ||
    range.max === null ||
    range.avg === null
  ) {
    return null;
  }

  return range;
};

export const getEventsGroupedByExperimentDatasetId = async (
  projectId: string,
  filter: FilterState,
) => {
  const rows = await getSingleEventsFilterOptionColumn(
    projectId,
    filter,
    "experimentDatasetId",
  );
  return rows.map((row) => ({
    experimentDatasetId: row.value,
    count: row.count,
  }));
};

/**
 * Delete events by trace IDs
 * Used when traces are deleted to cascade the deletion to the events table
 */
export const deleteEventsByTraceIds = async (
  projectId: string,
  traceIds: string[],
) => {
  // Preflight query uses events_core (faster)
  const preflight = await queryClickhouse<{
    min_ts: string;
    max_ts: string;
    cnt: string;
  }>({
    query: `
      SELECT
        min(start_time) - INTERVAL 1 HOUR as min_ts,
        max(start_time) + INTERVAL 1 HOUR as max_ts,
        count(*) as cnt
      FROM events_core
      WHERE project_id = {projectId: String} AND trace_id IN ({traceIds: Array(String)})
    `,
    params: { projectId, traceIds },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
    },
    tags: { projectId },
  });

  const count = Number(preflight[0]?.cnt ?? 0);
  if (count === 0) {
    logger.info(
      `deleteEventsByTraceIds: no rows found for project ${projectId}, skipping DELETE`,
    );
    return;
  }

  const deleteParams = {
    projectId,
    traceIds,
    minTs: preflight[0].min_ts,
    maxTs: preflight[0].max_ts,
  };
  const deleteQuery = (table: string) => `
    DELETE FROM ${table}
    WHERE project_id = {projectId: String}
    AND trace_id IN ({traceIds: Array(String)})
    AND start_time >= {minTs: String}::DateTime64(3)
    AND start_time <= {maxTs: String}::DateTime64(3)
  `;
  const deleteOpts = (table: string) => ({
    query: deleteQuery(table),
    params: deleteParams,
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
    },
    tags: { projectId },
  });

  // Delete from all tables in parallel
  await Promise.all([
    commandClickhouse(deleteOpts("events_full")),
    commandClickhouse(deleteOpts("events_core")),
  ]);
};

/**
 * This method is used by deleteEventsByProjectId and therefore
 * should NOT be using EventsReadOnly to prevent lagging replicas
 * from changing the outcome.
 */
export const hasAnyEvent = async (projectId: string) => {
  const query = `
    SELECT 1
    FROM events_core
    WHERE project_id = {projectId: String}
    LIMIT 1
  `;

  const rows = await queryClickhouse<{ 1: number }>({
    query,
    params: { projectId },
    tags: { projectId },
  });

  return rows.length > 0;
};

/**
 * Delete all events for a project
 * Used when an entire project is deleted
 */
export const deleteEventsByProjectId = async (
  projectId: string,
): Promise<boolean> => {
  const hasData = await hasAnyEvent(projectId);
  if (!hasData) {
    return false;
  }

  // Delete from both tables in parallel
  const deleteOpts = (table: string) => ({
    query: `DELETE FROM ${table} WHERE project_id = {projectId: String}`,
    params: { projectId },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
    },
    tags: { projectId },
    clickhouseSettings: { send_logs_level: "trace" as const },
  });

  await Promise.all([
    commandClickhouse(deleteOpts("events_full")),
    commandClickhouse(deleteOpts("events_core")),
  ]);

  return true;
};

export async function getAgentGraphDataFromEventsTable(params: {
  projectId: string;
  traceId: string;
  minStartTime: Date;
  maxStartTime: Date;
}) {
  const { projectId, traceId, minStartTime, maxStartTime } = params;

  const db = getClickhouseKysely();

  const builder = db
    .selectFrom("events_truncated as e")
    .select((eb) => {
      const metadata = metadataMap(
        eb.ref("e.metadata_names"),
        eb.ref("e.metadata_values"),
      );
      return [
        "e.span_id as id",
        "e.parent_span_id as parent_observation_id",
        "e.type as type",
        "e.name as name",
        "e.start_time as start_time",
        "e.end_time as end_time",
        mapValue<string>(metadata, literal("langgraph_node")).as("node"),
        mapValue<string>(metadata, literal("langgraph_step")).as("step"),
      ];
    })
    .where("e.trace_id", "=", traceId)
    .where("e.start_time", ">=", minStartTime)
    .where("e.start_time", "<=", maxStartTime);

  const { sql: query, params: queryParams } = compileClickhouseQuery(
    builder,
    projectId,
  );

  return queryClickhouse({
    query,
    params: queryParams,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });
}

/**
 * This method is used by deleteEventsByProjectId and therefore
 * should NOT be using EventsReadOnly to prevent lagging replicas
 * from changing the outcome.
 */
export const hasAnyEventOlderThan = async (
  projectId: string,
  beforeDate: Date,
) => {
  const query = `
    SELECT 1
    FROM events_core
    WHERE project_id = {projectId: String}
    AND start_time < {cutoffDate: DateTime64(3)}
    LIMIT 1
  `;

  const rows = await queryClickhouse<{ 1: number }>({
    query,
    params: {
      projectId,
      cutoffDate: convertDateToClickhouseDateTime(beforeDate),
    },
    tags: { projectId },
  });

  return rows.length > 0;
};

/**
 * Delete events older than a cutoff date
 * Used for data retention cleanup
 */
export const deleteEventsOlderThanDays = async (
  projectId: string,
  beforeDate: Date,
): Promise<boolean> => {
  const hasData = await hasAnyEventOlderThan(projectId, beforeDate);
  if (!hasData) {
    return false;
  }

  const deleteOpts = (table: string) => ({
    query: `
      DELETE FROM ${table}
      WHERE project_id = {projectId: String}
      AND start_time < {cutoffDate: DateTime64(3)}
    `,
    params: {
      projectId,
      cutoffDate: convertDateToClickhouseDateTime(beforeDate),
    },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
    },
    tags: { projectId },
  });

  await Promise.all([
    commandClickhouse(deleteOpts("events_full")),
    commandClickhouse(deleteOpts("events_core")),
  ]);

  return true;
};

export const getObservationsBatchIOFromEventsTable = async <
  TIncludeExperiment extends boolean = false,
  TIncludeToolCalls extends boolean = false,
  TIncludeSkills extends boolean = false,
>(opts: {
  projectId: string;
  observations: Array<{
    id: string;
    traceId: string;
  }>;
  minStartTime: Date;
  maxStartTime: Date;
  truncated?: boolean; // Default true for performance, false for full data
  /**
   * Chars of I/O and of each metadata value to ship on a full read. Lets a
   * caller that needs more than events_core's pre-truncated I/O still bound
   * the payload. Ignored for truncated reads (events_core caps far tighter).
   */
  ioCharLimit?: number;
  /** Restricts every requested observation to an already-authorized session. */
  sessionId?: string;
  includeExperimentFields?: TIncludeExperiment;
  /** Opt-in: tool-call arrays can be large; only eval consumers need them. */
  includeToolCallFields?: TIncludeToolCalls;
  includeSkillFields?: TIncludeSkills;
}): Promise<
  Array<
    EventBatchIOResult<TIncludeExperiment, TIncludeToolCalls, TIncludeSkills>
  >
> => {
  if (opts.observations.length === 0) {
    return [];
  }

  const truncated = opts.truncated ?? true;
  // Interpolated into SQL, so coerce to a positive integer here rather than
  // trusting the caller's number.
  const fullReadCharLimit =
    !truncated && opts.ioCharLimit !== undefined
      ? Math.max(1, Math.trunc(opts.ioCharLimit))
      : undefined;

  const observationIds = opts.observations.map((o) => o.id);
  const traceIds = Array.from(new Set(opts.observations.map((o) => o.traceId)));
  const observationTuples = opts.observations.map(
    (observation) => new TupleParam([observation.traceId, observation.id]),
  );

  // Use provided timestamp range with buffer for efficient filtering
  const minTimestamp = new Date(opts.minStartTime.getTime() - 1000); // -1 second buffer
  const maxTimestamp = new Date(opts.maxStartTime.getTime() + 1000); // +1 second buffer

  const charLimit = truncated
    ? env.LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT
    : fullReadCharLimit;
  const capIo = (expression: AliasableExpression<string>) =>
    charLimit ? leftUTF8(expression, charLimit) : expression;
  // events_core already stores these pre-truncated, so only a full read needs
  // capping — an explicit limit has to bound every large field, not just I/O.
  const capOnFullRead = (expression: AliasableExpression<string>) =>
    fullReadCharLimit ? leftUTF8(expression, fullReadCharLimit) : expression;
  const capEachOnFullRead = (values: Expression<string[]>) =>
    fullReadCharLimit
      ? arrayMap<string, string>(
          (value) => leftUTF8(value, fullReadCharLimit),
          values,
        )
      : values;

  // Keep the individual filters for primary-key pruning and the tuple filter
  // for exact trace/observation matching.
  const builder = getClickhouseKysely()
    .selectFrom(truncated ? "events_truncated as e" : "events as e")
    .select((eb) => [
      "e.span_id as id",
      "e.trace_id as trace_id",
      capIo(eb.ref("e.input")).as("input"),
      capIo(eb.ref("e.output")).as("output"),
    ])
    .$if(opts.includeExperimentFields === true, (qb) =>
      qb.select((eb) => [
        capOnFullRead(eb.ref("e.experiment_item_expected_output")).as(
          "experiment_item_expected_output",
        ),
        metadataMap(
          eb.ref("e.experiment_item_metadata_names"),
          capEachOnFullRead(eb.ref("e.experiment_item_metadata_values")),
        ).as("experiment_item_metadata"),
      ]),
    )
    .$if(opts.includeSkillFields === true, (qb) =>
      qb.select([
        "e.skills_available as skills_available",
        "e.skills_resource_loaded as skills_resource_loaded",
      ]),
    )
    .$if(opts.includeToolCallFields === true, (qb) =>
      qb.select([
        "e.tool_calls as tool_calls",
        "e.tool_call_names as tool_call_names",
      ]),
    )
    .select((eb) =>
      metadataMap(
        eb.ref("e.metadata_names"),
        capEachOnFullRead(eb.ref("e.metadata_values")),
      ).as("metadata"),
    )
    .where("e.span_id", "in", observationIds)
    .where("e.trace_id", "in", traceIds)
    .where((eb) =>
      tupleIn(eb.refTuple("e.trace_id", "e.span_id"), observationTuples),
    )
    .$if(opts.sessionId !== undefined, (qb) =>
      qb.where("e.trace_id", "in", (eb) =>
        eb
          .selectFrom("events")
          .select("trace_id")
          .where("trace_id", "in", traceIds)
          .groupBy("trace_id")
          .having((eb) =>
            eb(
              latestNonEmpty(eb.ref("session_id"), eb.ref("event_ts")),
              "=",
              opts.sessionId!,
            ),
          ),
      ),
    )
    .where("e.start_time", ">=", minTimestamp)
    .where("e.start_time", "<=", maxTimestamp);
  const { sql: query, params } = compileClickhouseQuery(
    builder,
    opts.projectId,
  );

  const results = await queryClickhouse<{
    id: string;
    trace_id: string;
    input: string | null;
    output: string | null;
    metadata: Record<string, string>;
    skills_available?: SkillsAvailable;
    skills_resource_loaded?: SkillsResourceLoaded;
    tool_calls?: string[];
    tool_call_names?: string[];
    experiment_item_expected_output?: string | null;
    experiment_item_metadata?: Record<string, string>;
  }>({
    query,
    params,
    tags: { projectId: opts.projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return results.map((r) => ({
    id: r.id,
    traceId: r.trace_id,
    input: applyBatchIOStringRendering(r.input),
    output: applyBatchIOStringRendering(r.output),
    metadata:
      r.metadata !== undefined ? parseMetadataCHRecordToDomain(r.metadata) : {},
    ...(opts.includeSkillFields
      ? {
          skillsAvailable: r.skills_available ?? [],
          skillsResourceLoaded: r.skills_resource_loaded ?? [],
        }
      : {}),
    ...(opts.includeToolCallFields
      ? {
          toolCalls: r.tool_calls ?? [],
          toolCallNames: r.tool_call_names ?? [],
        }
      : {}),
    ...(opts.includeExperimentFields
      ? {
          experimentItemExpectedOutput: r.experiment_item_expected_output,
          experimentItemMetadata:
            r.experiment_item_metadata !== undefined
              ? parseMetadataCHRecordToDomain(r.experiment_item_metadata)
              : {},
        }
      : {}),
  })) as Array<
    EventBatchIOResult<TIncludeExperiment, TIncludeToolCalls, TIncludeSkills>
  >;
};

/**
 * The single observation IO fields the stream/length helpers below can serve.
 * `input`/`output` are raw `String` columns streamed as-is — note they may be a
 * bare, unquoted string (not JSON) for plain-text prompts/completions, so the
 * route serves them as opaque bytes, not `application/json`. `metadata` is
 * reconstructed from the `metadata_names`/`metadata_values` `Map(String,String)`
 * columns, so **every metadata value is emitted JSON-string-encoded** (a nested
 * object comes out as an escaped string). Consumers must unwrap one level, exactly
 * as the existing metadata read path does (`parseMetadataCHRecordToDomain`).
 */
export const OBSERVATION_IO_STREAM_FIELDS = [
  "input",
  "output",
  "metadata",
] as const;

export type ObservationIoStreamField =
  (typeof OBSERVATION_IO_STREAM_FIELDS)[number];

interface ObservationIOReadOpts {
  projectId: string;
  traceId: string;
  observationId: string;
  field: ObservationIoStreamField;
  /** The observation's startTime; bounds the read for primary-key pruning. */
  startTime: Date;
}

// The ±1s window around `startTime` only prunes the primary key
// (project_id, toStartOfMinute(start_time), xxHash32(trace_id)); it is a
// performance hint, never an authorization control.
//
// The field expression is chosen from the validated `field` enum — never
// string-interpolated user input. The length pre-query and the byte stream share
// this builder so they can never drift; a mismatch would make the route's
// Content-Length integrity check wrong. A soft-deleted latest version reads as
// no row.
function compileObservationIOFieldRead<A extends string>(
  opts: ObservationIOReadOpts,
  select: (field: AliasableExpression<string>) => AliasedExpression<unknown, A>,
) {
  const query = getClickhouseKysely()
    .selectFrom("events as e")
    .$call(softDeleteAfterLimit())
    .select((eb) =>
      select(
        opts.field === "metadata"
          ? toJSONString(
              metadataMap(
                eb.ref("e.metadata_names"),
                eb.ref("e.metadata_values"),
              ),
            )
          : eb.ref(`e.${opts.field}`),
      ),
    )
    .where("e.trace_id", "=", opts.traceId)
    .where("e.span_id", "=", opts.observationId)
    .where("e.start_time", ">=", new Date(opts.startTime.getTime() - 1000))
    .where("e.start_time", "<=", new Date(opts.startTime.getTime() + 1000))
    .orderBy("e.event_ts", "desc")
    .limit(literal(1));

  return compileClickhouseQuery(query, opts.projectId);
}

/**
 * Byte length of one observation IO field — a cheap pre-query the streaming
 * route runs BEFORE committing headers. It does two jobs the raw stream can't:
 *  - distinguishes "not found" (no row → `null` → the route 404s) from "present
 *    but empty" (row with 0 → empty 200), so a stale/skewed `startTime` yields a
 *    diagnosable 404 rather than a misleading empty body; and
 *  - gives the exact byte count for a `Content-Length` header, so a mid-stream
 *    ClickHouse failure (truncated body) is detectable at the HTTP layer on ANY
 *    ClickHouse version — independent of the `x-clickhouse-exception-tag` header
 *    that raw-passthrough failure detection needs (≥25.11 only).
 * Uses the SAME field expression + WHERE as the stream, so the length matches the
 * bytes streamed. `length()` on a ClickHouse `String` is its byte count.
 */
export const getObservationIOFieldByteLengthFromEventsTable = async (
  opts: ObservationIOReadOpts,
): Promise<number | null> => {
  const { sql: query, params } = compileObservationIOFieldRead(opts, (field) =>
    byteLength(field).as("len"),
  );
  const rows = await queryClickhouse<{ len: string }>({
    query,
    params,
    tags: { projectId: opts.projectId, route: "observation-io-stream-length" },
    preferredClickhouseService: "EventsReadOnly",
  });
  const first = rows[0];
  return first ? Number(first.len) : null;
};

/**
 * Stream ONE observation's single IO field (input | output | metadata) straight
 * from ClickHouse to the caller as raw bytes, WITHOUT materializing the whole
 * value in the Node process. Uses `FORMAT RawBLOB`, so ClickHouse emits exactly
 * the field's bytes (no JSONEachRow envelope) and {@link queryClickhouseExecRaw}
 * hands back the live HTTP body as a `Readable` for the caller to pipe onward.
 * This is the transport primitive behind the lazy/streaming large-JSON viewer
 * (LFE-11081): the browser can fetch a multi-hundred-MB field as a byte stream
 * instead of forcing the server to buffer + JSON-serialize it in one shot.
 *
 * SECURITY: strictly tenant-scoped. The read is pinned to a single
 * (project_id, trace_id, span_id) via parameterized predicates, so it can only
 * ever return bytes for that one observation inside that one project — a wrong
 * projectId yields zero rows (zero bytes). `field` is NOT interpolated user
 * input: it selects from a fixed, closed set of SQL expressions. Callers MUST
 * still authorize the (projectId, traceId) pair before calling — this function
 * performs data isolation, not request authorization.
 */
export const streamObservationIOFieldFromEventsTable = (
  opts: ObservationIOReadOpts,
) => {
  const { sql: query, params } = compileObservationIOFieldRead(opts, (field) =>
    field.as("field"),
  );

  // FORMAT RawBLOB emits the selected String column's bytes with no escaping or
  // delimiters; with LIMIT 1 that is exactly this observation's field value.
  return queryClickhouseExecRaw({
    query,
    format: "RawBLOB",
    params,
    tags: {
      projectId: opts.projectId,
      route: "observation-io-stream",
    },
    preferredClickhouseService: "EventsReadOnly",
  });
};

/**
 * Full raw I/O + metadata for ONE observation, scoped to a session (the
 * session-detail download fallback for payloads too large to render inline,
 * LFE-10958). Callers are session-authorized (public sessions included), so
 * the session_id predicate is part of the authorization: the query itself
 * guarantees the observation belongs to that session — never widen it.
 */
export const getObservationFullIOForSessionFromEventsTable = async (opts: {
  projectId: string;
  sessionId: string;
  traceId: string;
  observationId: string;
  /** The observation's startTime; bounds the read for primary-key pruning. */
  startTime: Date;
}): Promise<{
  id: string;
  input: string | null;
  output: string | null;
  metadata: MetadataDomain;
} | null> => {
  // ±1s around start_time prunes on the primary key
  // (project_id, toStartOfMinute(start_time), xxHash32(trace_id)).
  const minTimestamp = new Date(opts.startTime.getTime() - 1000);
  const maxTimestamp = new Date(opts.startTime.getTime() + 1000);

  const db = getClickhouseKysely();
  // A soft-deleted latest version reads as not found.
  const builder = db
    .selectFrom("events as e")
    .$call(softDeleteAfterLimit())
    .select((eb) => [
      "e.span_id as id",
      "e.input as input",
      "e.output as output",
      metadataMap(eb.ref("e.metadata_names"), eb.ref("e.metadata_values")).as(
        "metadata",
      ),
    ])
    .where("e.session_id", "=", opts.sessionId)
    .where((eb) =>
      eb(xxHash32(eb.ref("e.trace_id")), "=", xxHash32(eb.val(opts.traceId))),
    )
    .where("e.trace_id", "=", opts.traceId)
    .where("e.span_id", "=", opts.observationId)
    .where("e.start_time", ">=", minTimestamp)
    .where("e.start_time", "<=", maxTimestamp)
    .orderBy("e.event_ts", "desc")
    .limit(literal(1));
  const { sql: query, params } = compileClickhouseQuery(
    builder,
    opts.projectId,
  );

  const rows = await queryClickhouse<{
    id: string;
    input: string | null;
    output: string | null;
    metadata: Record<string, string>;
  }>({
    query,
    params,
    tags: { projectId: opts.projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  const row = rows[0];
  if (!row) return null;

  return {
    id: row.id,
    input: applyBatchIOStringRendering(row.input),
    output: applyBatchIOStringRendering(row.output),
    metadata:
      row.metadata !== undefined
        ? parseMetadataCHRecordToDomain(row.metadata)
        : {},
  };
};

/**
 * Discouraged: Avoid using this function for new code.
 *
 * This function exists solely to support the annotation queue items lookup,
 * which needs to resolve parent trace IDs for observation-type queue items.
 * It is problematic for performance as it lacks time filtering, requiring
 * ClickHouse to scan a broad range of data.
 * We aim to refactor the annotation queue data model to eliminate this
 * dependency in a future iteration.
 */
export const getObservationsTraceIdsFromEventsTable = async (opts: {
  projectId: string;
  observationIds: string[];
}) => {
  const { projectId, observationIds } = opts;

  const db = getClickhouseKysely();

  const builder = db
    .selectFrom("events as e")
    .select(["e.trace_id as trace_id", "e.span_id as span_id"])
    .where("e.span_id", "in", observationIds);

  const { sql: query, params: queryParams } = compileClickhouseQuery(
    builder,
    projectId,
  );

  const result = await queryClickhouse<{
    trace_id: string;
    span_id: string;
  }>({
    query,
    params: queryParams,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return result.map((row) => ({
    id: row.span_id,
    traceId: row.trace_id,
  }));
};

/**
 * Column mappings for user queries from events table.
 * Includes a "Timestamp" mapping that points to start_time for compatibility
 * with the Users page filter state (which uses "Timestamp" from traces table).
 */
const usersFromEventsTableColumnDefinitions: UiColumnMappings = [
  ...eventsTableUiColumnDefinitions,
  {
    uiTableName: "Timestamp",
    uiTableId: "timestamp",
    clickhouseTableName: "events_proto",
    clickhouseSelect: 'e."start_time"',
  },
];

/**
 * Get users with trace counts from events table with pagination
 * Similar to getTracesGroupedByUsers but queries the events table
 */
export const getUsersFromEventsTable = async (
  projectId: string,
  filter: FilterState,
  searchQuery?: string,
  limit?: number,
  offset?: number,
) => {
  const eventsFilter = new FilterList(
    createFilterFromFilterState(filter, usersFromEventsTableColumnDefinitions),
  );
  const appliedEventsFilter = eventsFilter.apply();

  const queryBuilder = new EventsAggQueryBuilder({
    projectId,
    groupByColumn: "e.user_id",
    selectExpression: "e.user_id as user, uniq(e.trace_id) as count",
  })
    .where(appliedEventsFilter)
    .whereRaw("e.user_id IS NOT NULL AND length(e.user_id) > 0")
    .whereRaw("e.is_deleted = 0")
    .when(Boolean(searchQuery), (b) =>
      b.whereRaw("e.user_id ILIKE {searchQuery: String}", {
        searchQuery: `%${escapeSqlLikePattern(searchQuery ?? "")}%`,
      }),
    )
    .orderBy("ORDER BY count DESC")
    .limit(limit, offset);

  const { query, params } = queryBuilder.buildWithParams();

  return queryClickhouse<{ user: string; count: string }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });
};

/**
 * Get total user count from events table
 */
export const getUsersCountFromEventsTable = async (
  projectId: string,
  filter: FilterState,
  searchQuery?: string,
): Promise<{ totalCount: string }[]> => {
  const eventsFilter = new FilterList(
    createFilterFromFilterState(filter, usersFromEventsTableColumnDefinitions),
  );
  const appliedEventsFilter = eventsFilter.apply();

  const searchCondition = searchQuery
    ? `AND e.user_id ILIKE {searchQuery: String}`
    : "";

  const query = `
    SELECT uniq(e.user_id) AS totalCount
    FROM events_core e
    WHERE e.project_id = {projectId: String}
    AND e.user_id IS NOT NULL
    AND e.user_id != ''
    AND e.is_deleted = 0
    ${appliedEventsFilter.query ? `AND ${appliedEventsFilter.query}` : ""}
    ${searchCondition}
  `;

  return queryClickhouse<{ totalCount: string }>({
    query,
    params: {
      projectId,
      ...appliedEventsFilter.params,
      ...(searchQuery
        ? { searchQuery: `%${escapeSqlLikePattern(searchQuery)}%` }
        : {}),
    },
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });
};

/**
 * Get user metrics from events table
 * Key difference from getUserMetrics in traces.ts:
 * - Uses min(e.start_time)/max(e.start_time) for first/last event (all observations)
 * - Legacy uses min(t.timestamp)/max(t.timestamp) (only trace timestamps)
 */
export const getUserMetricsFromEventsTable = async (
  projectId: string,
  userIds: string[],
  filter: FilterState,
) => {
  if (userIds.length === 0) {
    return [];
  }

  const eventsFilter = new FilterList(
    createFilterFromFilterState(filter, usersFromEventsTableColumnDefinitions),
  );
  const appliedEventsFilter = eventsFilter.apply();

  const statsBuilder = new EventsAggQueryBuilder({
    projectId,
    groupByColumn: "e.user_id",
    selectExpression: `
      e.user_id as user_id,
      anyLast(e.environment) as environment,
      count(DISTINCT e.span_id) as obs_count,
      count(DISTINCT e.trace_id) as trace_count,
      sumMap(e.usage_details) as sum_usage_details,
      sum(e.total_cost) as sum_total_cost,
      min(e.start_time) as min_timestamp,
      max(e.start_time) as max_timestamp
    `,
  })
    .whereRaw("e.user_id IN ({userIds: Array(String)})", { userIds })
    // not required if called from tRPC (user_id is always defined), left in for safety only
    .whereRaw("e.user_id IS NOT NULL AND length(e.user_id) > 0")
    .whereRaw("e.is_deleted = 0")
    .where(appliedEventsFilter);

  const { query: statsQuery, params: statsParams } =
    statsBuilder.buildWithParams();

  const query = `
    WITH stats AS (${statsQuery})
    SELECT
      user_id,
      environment,
      obs_count,
      trace_count,
      sum_total_cost,
      min_timestamp,
      max_timestamp,
      arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'input') > 0, sum_usage_details))) as input_usage,
      arraySum(mapValues(mapFilter(x -> positionCaseInsensitive(x.1, 'output') > 0, sum_usage_details))) as output_usage,
      sum_usage_details['total'] as total_usage
    FROM stats
  `;

  const rows = await queryClickhouse<{
    user_id: string;
    environment: string;
    max_timestamp: string;
    min_timestamp: string;
    input_usage: string;
    output_usage: string;
    total_usage: string;
    obs_count: string;
    trace_count: string;
    sum_total_cost: string;
  }>({
    query,
    params: statsParams,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => ({
    userId: row.user_id,
    environment: row.environment,
    maxTimestamp: parseClickhouseUTCDateTimeFormat(row.max_timestamp),
    minTimestamp: parseClickhouseUTCDateTimeFormat(row.min_timestamp),
    inputUsage: Number(row.input_usage),
    outputUsage: Number(row.output_usage),
    totalUsage: Number(row.total_usage),
    observationCount: Number(row.obs_count),
    traceCount: Number(row.trace_count),
    totalCost: Number(row.sum_total_cost),
  }));
};

/**
 * Check if any user exists in events table
 * Uses hasAnyEvent pattern but filters for user_id
 */
export const hasAnyUserFromEventsTable = async (
  projectId: string,
): Promise<boolean> => {
  const { sql: query, params } = compileHasAnyFromEventsTable({
    projectId,
    kind: "user",
  });

  const rows = await queryClickhouse<{ one: number }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.length > 0;
};

/**
 * Query for the events blob export. Full I/O reads events_full; everything
 * else reads events_core. `convertLatencyToSecondsInSql` can be set by the paths
 * that skip the JS row enrichment (raw passthrough, Parquet), so they select
 * latency and time to first token in seconds instead of milliseconds.
 */
const buildEventsForBlobStorageExportQuery = (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  fieldGroups: ObservationFieldGroupFull[],
  convertLatencyToSecondsInSql: boolean,
) => {
  // core is always required (provides id, trace_id, start/end_time used for cursor and deduplication)
  const effectiveGroups = fieldGroups.includes("core")
    ? fieldGroups
    : (["core", ...fieldGroups] as ObservationFieldGroupFull[]);
  const includeIO = effectiveGroups.includes("io");
  const metricsInSeconds =
    convertLatencyToSecondsInSql && effectiveGroups.includes("metrics");
  const fieldSets = effectiveGroups.flatMap((group) => {
    if (group === "io" || (group === "metrics" && metricsInSeconds)) return [];
    // "model_export" is the field set name for the "model" group
    return group === "model" ? ["model_export" as const] : [group];
  });

  const builder = getClickhouseKysely()
    .selectFrom(includeIO ? "events as e" : "events_truncated as e")
    .select(eventsRowFieldSelects(eventsFieldSetKeys(...fieldSets)))
    .$if(includeIO, (qb) => qb.select(["e.input", "e.output"]))
    .$if(metricsInSeconds, (qb) => qb.select(eventsMetricsSecondsSelects))
    .where("e.start_time", ">=", minTimestamp)
    .where("e.start_time", "<", maxTimestamp)
    .$call(
      limitBy({
        count: 1,
        columns: (eb) => [eb.ref("e.span_id"), eb.ref("e.project_id")],
      }),
    );

  const { sql: query, params } = compileClickhouseQuery(builder, projectId);

  return {
    query,
    params,
    // Tagged explicitly: worker baggage isn't active during the deferred stream send.
    tags: { projectId, surface: "worker", route: "blob_export" },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
    },
    preferredClickhouseService: "EventsReadOnly" as const,
  };
};

export const getEventsForBlobStorageExport = function (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],
) {
  return queryClickhouseStream<Record<string, unknown>>(
    buildEventsForBlobStorageExportQuery(
      projectId,
      minTimestamp,
      maxTimestamp,
      fieldGroups,
      false, // standard path converts latency ms→s in JS
    ),
  );
};

// Raw-passthrough variant (LFE-10402): yields each row's unparsed JSONEachRow
// text, skipping the per-row parse/enrich/serialize cycle. When
// `convertLatencyToSeconds` is set, latency/ttft are divided by 1000 in SQL
// (matching what the JS path would have done); otherwise they stay in ms (legacy
// integrations). Price columns are NOT added.
export const getEventsForBlobStorageExportRaw = function (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],
  convertLatencyToSeconds = false,
) {
  return queryClickhouseStreamRawText(
    buildEventsForBlobStorageExportQuery(
      projectId,
      minTimestamp,
      maxTimestamp,
      fieldGroups,
      convertLatencyToSeconds,
    ),
  );
};

// LFE-10463: FORMAT Parquet export — reuses the field-group-aware builder and
// streams raw binary bytes to upload. No JS enrichment, so latency ms→s must run
// in SQL (`convertLatencyToSeconds`) and price columns are NOT added.
export const getEventsForBlobStorageExportParquet = function (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  fieldGroups: ObservationFieldGroupFull[] = [...OBSERVATION_FIELD_GROUPS_FULL],
  convertLatencyToSeconds = false,
) {
  return queryClickhouseExecRaw({
    ...buildEventsForBlobStorageExportQuery(
      projectId,
      minTimestamp,
      maxTimestamp,
      fieldGroups,
      convertLatencyToSeconds,
    ),
    format: "Parquet",
    clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
  });
};

/**
 * Streams events from ClickHouse for analytics integrations (PostHog, Mixpanel).
 * All fields come directly from the events table (which has denormalized trace-level data).
 */
export const getEventsForAnalyticsIntegrations = async function* (
  projectId: string,
  projectName: string,
  minTimestamp: Date,
  maxTimestamp: Date,
) {
  const builder = getClickhouseKysely()
    .selectFrom("events_truncated as e")
    // Use export field set for most fields (id, traceId, name, type, level, version,
    // environment, userId, sessionId, tags, release, traceName, totalCost, latency, etc.)
    .select(eventsRowFieldSelects(eventsFieldSetKeys("export")))
    // Add analytics-specific computed fields
    .select((eb) => [
      // Token counts from usage/cost details
      mapValue(eb.ref("e.usage_details"), literal("input")).as("input_tokens"),
      mapValue(eb.ref("e.usage_details"), literal("output")).as(
        "output_tokens",
      ),
      mapValue(eb.ref("e.usage_details"), literal("total")).as("total_tokens"),
      // Analytics integration session IDs from metadata (constructed from array columns)
      eventsMetadataValue(eb, literal("$posthog_session_id")).as(
        "posthog_session_id",
      ),
      eventsMetadataValue(eb, literal("$mixpanel_session_id")).as(
        "mixpanel_session_id",
      ),
    ])
    .where("e.start_time", ">=", minTimestamp)
    .where("e.start_time", "<", maxTimestamp)
    .$call(
      limitBy({
        count: 1,
        columns: (eb) => [eb.ref("e.span_id"), eb.ref("e.project_id")],
      }),
    );

  const { sql: query, params } = compileClickhouseQuery(builder, projectId);

  const records = queryClickhouseStream<Record<string, unknown>>({
    query,
    params,
    // Tagged explicitly: worker baggage isn't active during the deferred stream send.
    tags: { projectId, surface: "worker", route: "analytics_integration" },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
    },
    preferredClickhouseService: "EventsReadOnly",
  });

  const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
  for await (const record of records) {
    yield {
      timestamp: record.start_time,
      langfuse_observation_name: record.name,
      // The row type here is Record<string, unknown>; the column is a String
      // projection ('' when the event has no trace name).
      langfuse_trace_name: normalizeEventsTraceName(
        record.trace_name as string | null | undefined,
      ),
      langfuse_trace_id: record.trace_id,
      langfuse_url: `${baseUrl}/project/${projectId}/traces/${encodeURIComponent(record.trace_id as string)}?observation=${encodeURIComponent(record.id as string)}`,
      langfuse_user_url: record.user_id
        ? `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.user_id as string)}`
        : undefined,
      langfuse_id: record.id,
      langfuse_cost_usd: record.total_cost,
      langfuse_input_units: record.input_tokens,
      langfuse_output_units: record.output_tokens,
      langfuse_total_units: record.total_tokens,
      langfuse_session_id: record.session_id,
      langfuse_project_id: projectId,
      langfuse_project_name: projectName,
      langfuse_user_id: record.user_id || null,
      langfuse_latency: record.latency,
      langfuse_time_to_first_token: record.time_to_first_token,
      langfuse_release: record.release,
      langfuse_version: record.version,
      langfuse_model: record.provided_model_name,
      langfuse_level: record.level,
      langfuse_type: record.type,
      langfuse_tags: record.tags,
      langfuse_environment: record.environment,
      langfuse_event_version: "1.0.0",
      posthog_session_id: record.posthog_session_id ?? null,
      mixpanel_session_id: record.mixpanel_session_id ?? null,
    } satisfies AnalyticsObservationEvent;
  }
};

/*
 * Check if any session exists in events table
 * Filters for non-empty session_id
 */
export const hasAnySessionFromEventsTable = async (
  projectId: string,
): Promise<boolean> => {
  const { sql: query, params } = compileHasAnyFromEventsTable({
    projectId,
    kind: "session",
  });

  const rows = await queryClickhouse<{ one: number }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.length > 0;
};

/**
 * Fetch trace metadata (name, user_id, tags) for a list of trace IDs.
 * Used by the scores table to enrich score rows with trace-level data.
 */
export const getTraceMetadataByIdsFromEvents = async (props: {
  projectId: string;
  traceIds: string[];
  clickhouseConfigs?: ClickHouseClientConfigOptions;
}) => {
  if (props.traceIds.length === 0) return [];

  const db = getClickhouseKysely();

  const builder = db
    .selectFrom("events as e")
    .select((eb) => [
      "e.trace_id as id",
      eventsTraceName(eb).as("name"),
      "e.user_id as user_id",
      "e.tags as tags",
    ])
    .where((eb) => eb(eventsTraceName(eb), "is not", null))
    .where("e.trace_id", "in", props.traceIds)
    .$call(limitBy({ count: 1, columns: (eb) => [eb.ref("e.trace_id")] }));

  const { sql: query, params } = compileClickhouseQuery(
    builder,
    props.projectId,
  );

  return queryClickhouse<{
    id: string;
    name: string;
    user_id: string;
    tags: string[];
  }>({
    query,
    params,
    tags: { projectId: props.projectId },
    clickhouseConfigs: props.clickhouseConfigs,
    preferredClickhouseService: "EventsReadOnly",
  });
};

const evalExecutionIdentifierColumn = (identifier: "evaluator" | "rule") =>
  identifier === "evaluator" ? "e.evaluator_id" : "e.evaluation_rule_id";

const evaluatorTestEventCondition =
  "e.evaluator_execution_is_test OR startsWith(e.trace_name, 'Test evaluator')";

const traceCostsByIdentifier = (params: {
  projectId: string;
  identifiers: Array<{
    identifier: "evaluator" | "rule";
    alias: string;
  }>;
  additionalSelect?: string[];
}) =>
  new EventsAggQueryBuilder({
    projectId: params.projectId,
    groupByColumn: "e.trace_id",
    selectExpression: [
      "e.trace_id as trace_id",
      ...params.identifiers.map(({ identifier, alias }) => {
        const identifierColumn = evalExecutionIdentifierColumn(identifier);
        return `anyIf(${identifierColumn}, notEmpty(${identifierColumn})) as ${alias}`;
      }),
      "sum(e.total_cost) as trace_total_cost",
      ...(params.additionalSelect ?? []),
    ].join(", "),
  })
    .whereRaw("e.start_time > now() - INTERVAL 7 DAY")
    .whereRaw("e.is_deleted = 0");

const costMetricFields = {
  avgCost: {
    select: "avg(tc.trace_total_cost) as avg_cost",
    column: "avg_cost",
  },
  totalCost: {
    select: "sum(tc.trace_total_cost) as total_cost",
    column: "total_cost",
  },
  executionCount: {
    select: "count(*) as execution_count",
    column: "execution_count",
  },
} as const;

const getCostMetricsByIdentifierIds = async <
  const TFields extends readonly (keyof typeof costMetricFields)[],
>(params: {
  projectId: string;
  identifierIds: string[];
  fields: TFields;
  identifier: "evaluator" | "rule";
}) => {
  if (params.identifierIds.length === 0) return [];

  const traceCostsBuilder = traceCostsByIdentifier({
    projectId: params.projectId,
    identifiers: [{ identifier: params.identifier, alias: "identifier_id" }],
    additionalSelect: [
      `countIf(${evaluatorTestEventCondition}) as test_event_count`,
    ],
  })
    .havingRaw("identifier_id IN ({identifierIds: Array(String)})", {
      identifierIds: params.identifierIds,
    })
    .havingRaw("test_event_count = 0");

  const traceCosts = traceCostsBuilder.buildWithParams();
  const queryBuilder = new CTEQueryBuilder()
    .withCTE("trace_costs", {
      ...traceCosts,
      schema: ["trace_id", "identifier_id", "trace_total_cost"] as const,
    })
    .from("trace_costs", "tc")
    .select(
      "tc.identifier_id as identifier_id",
      ...params.fields.map((field) => costMetricFields[field].select),
    )
    .groupBy("tc.identifier_id");

  const { query, params: queryParams } = queryBuilder.buildWithParams();
  const rows = await queryClickhouse<Record<string, string>>({
    query,
    params: queryParams,
    tags: { projectId: params.projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => {
    const metrics = Object.fromEntries(
      params.fields.map((field) => [
        field,
        Number(row[costMetricFields[field].column]),
      ]),
    ) as Record<TFields[number], number>;

    return { identifierId: row.identifier_id, ...metrics };
  });
};

export const getAvgCostByEvaluatorIds = async (
  projectId: string,
  evaluatorIds: string[],
) => {
  const metrics = await getCostMetricsByIdentifierIds({
    projectId,
    identifierIds: evaluatorIds,
    fields: ["avgCost", "executionCount"],
    identifier: "evaluator",
  });
  return metrics.map(({ identifierId, ...costs }) => ({
    evaluatorId: identifierId,
    ...costs,
  }));
};

export const getTotalCostByRule = async (
  projectId: string,
  ruleIds: string[],
) => {
  const metrics = await getCostMetricsByIdentifierIds({
    projectId,
    identifierIds: ruleIds,
    fields: ["totalCost"],
    identifier: "rule",
  });
  return metrics.map(({ identifierId, totalCost }) => ({
    ruleId: identifierId,
    totalCost,
  }));
};

export const getTotalCostByEvaluatorIds = async (
  projectId: string,
  evaluatorIds: string[],
) => {
  const metrics = await getCostMetricsByIdentifierIds({
    projectId,
    identifierIds: evaluatorIds,
    fields: ["totalCost"],
    identifier: "evaluator",
  });
  return metrics.map(({ identifierId, totalCost }) => ({
    evaluatorId: identifierId,
    totalCost,
  }));
};

/** Returns the latest cost-bearing evaluator trace from the last seven days. */
export const getLatestEvaluatorRunCost = async (
  projectId: string,
  evaluatorId: string,
) => {
  const builder = traceCostsByIdentifier({
    projectId,
    identifiers: [
      {
        identifier: "evaluator",
        alias: "evaluator_id",
      },
    ],
    additionalSelect: [
      "max(e.start_time) as timestamp",
      "countIf(e.type = 'GENERATION') as generation_count",
    ],
  })
    .havingRaw("evaluator_id = {evaluatorId: String}", { evaluatorId })
    .havingRaw("generation_count > 0")
    .orderBy("ORDER BY timestamp DESC, trace_id DESC")
    .limit(1);

  const { query, params } = builder.buildWithParams();
  const rows = await queryClickhouse<{ trace_total_cost: string }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows[0] ? Number(rows[0].trace_total_cost) : null;
};

const EVALUATOR_HEALTH_RECENT_EXECUTIONS = 50;

/**
 * Counts execution traces by outcome, excluding tests. Only each evaluator's
 * most recent executions from the last seven days count, so an evaluator that
 * recovered from an earlier outage reports its current health.
 */
export const getEvaluatorExecutionSummaries = async (
  projectId: string,
  evaluatorIds: string[],
) => {
  if (evaluatorIds.length === 0) return [];

  const builder = new EventsAggQueryBuilder({
    projectId,
    groupByColumn: "e.trace_id, e.evaluator_id",
    selectExpression: [
      "e.trace_id as trace_id",
      "e.evaluator_id as evaluator_id",
      "min(e.start_time) as started_at",
      "countIf(e.level = 'ERROR') > 0 as failed",
    ].join(", "),
  })
    .whereRaw("e.start_time > now() - INTERVAL 7 DAY")
    .whereRaw("e.evaluator_id IN ({evaluatorIds: Array(String)})", {
      evaluatorIds,
    })
    .havingRaw(`countIf(${evaluatorTestEventCondition}) = 0`);

  // Aggregate the per-trace outcomes, rather than counting individual observations.
  const { query, params } = builder.buildWithParams();
  const rows = await queryClickhouse<{
    evaluator_id: string;
    total: string;
    failed_count: string;
  }>({
    // groupArraySorted keeps a bounded top-N per evaluator instead of sorting
    // every execution of the week; trace_id makes ties deterministic.
    query: `SELECT evaluator_id, length(recent) as total,
        arrayCount(x -> x.3, recent) as failed_count
      FROM (
        SELECT evaluator_id,
          groupArraySorted({recentExecutions: UInt32})(
            (-toUnixTimestamp64Micro(started_at), trace_id, failed)
          ) as recent
        FROM (${query})
        GROUP BY evaluator_id
      )`,
    params: { ...params, recentExecutions: EVALUATOR_HEALTH_RECENT_EXECUTIONS },
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => ({
    evaluatorId: row.evaluator_id,
    total: Number(row.total),
    failed: Number(row.failed_count),
  }));
};

export const getSessionMetricsFromEvents = async <
  F extends SessionEventsField,
>(props: {
  projectId: string;
  sessionIds: string[];
  fields: SessionEventsFields<F>;
  queryFromTimestamp?: Date;
}) => {
  if (props.sessionIds.length === 0) return [];

  const { projectId, sessionIds, fields, queryFromTimestamp } = props;
  const builder = getClickhouseKysely()
    .selectFrom("events as e")
    .select(sessionAggregationSelects(fields))
    .where("session_id", "in", sessionIds)
    .$if(queryFromTimestamp != null, (qb) =>
      qb.where(
        "start_time",
        ">=",
        observationsToTraceLowerBound(queryFromTimestamp!),
      ),
    )
    .where("session_id", "!=", literal(""))
    .groupBy("session_id")
    .limit(sessionIds.length);
  const { sql: query, params } = compileClickhouseQuery(builder, projectId);

  const rows = await queryClickhouse<Pick<SessionEventsMetricsRow, F>>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map(normalizeSessionCounts);
};

/**
 * SDK metadata detection result.
 * isOtel is always present, other fields are optional (only when non-empty).
 */
export type SdkMetadata = {
  isOtel: boolean;
  name?: string;
  version?: string;
  language?: string;
};

/**
 * Infers SDK details from the most recent OTel-compatible event in the past
 * 7 days:
 * - isOtel: event arrived via OTel-compatible ingestion (`source` column;
 *   includes Langfuse SDK v3+, raw OTel exporters, and backfilled OTel rows)
 * - name/version: ingestion attribution headers persisted at write time
 *   (`ingestion_sdk_name`/`ingestion_sdk_version`; 'unknown' for non-Langfuse
 *   clients, which then return no name/version)
 * - language: `telemetry_sdk_language` resource attribute column
 *
 * Projects with no OTel events in the past 7 days return isOtel: false
 * (acceptable for inactive projects and pre-OTel v2 SDKs).
 */
export async function getLatestSdkVersionInfoFromEvents(params: {
  projectId: string;
}): Promise<SdkMetadata> {
  const { projectId } = params;

  const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
  const builder = getClickhouseKysely()
    .selectFrom("events as e")
    .select((eb) => [
      "e.ingestion_sdk_name as ingestion_sdk_name",
      "e.ingestion_sdk_version as ingestion_sdk_version",
      "e.telemetry_sdk_language as telemetry_sdk_language",
      eb.fn.min("e.start_time").as("first_seen"),
      eb.fn.max("e.start_time").as("last_seen"),
      count().as("event_count"),
    ])
    .where("e.start_time", ">=", sevenDaysAgo)
    .where((eb) =>
      eb(toDate(eb.ref("e.start_time")), ">=", toDate(sevenDaysAgo)),
    )
    .where((eb) => startsWith(eb.ref("e.source"), literal("otel")))
    .where(
      "e.ingestion_sdk_name",
      "not in",
      INTERNAL_INGESTION_SDK_NAMES.map((n) => literal(n)),
    )
    .groupBy([
      "e.ingestion_sdk_name",
      "e.ingestion_sdk_version",
      "e.telemetry_sdk_language",
    ])
    .orderBy("last_seen", "desc");
  const { sql: query, params: queryParams } = compileClickhouseQuery(
    builder,
    projectId,
  );
  const result = await queryClickhouse<{
    ingestion_sdk_name: string;
    ingestion_sdk_version: string;
    telemetry_sdk_language: string;
    first_seen: string;
    last_seen: string;
    event_count: string;
  }>({
    query,
    params: queryParams,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  if (result.length === 0) {
    return { isOtel: false };
  }
  const row = result[0];

  // Attribution headers are only sent by Langfuse SDKs; raw OTel clients
  // (e.g. Vercel AI SDK) carry the 'unknown' sentinel and yield no name/version
  const hasAttribution =
    row.ingestion_sdk_name &&
    row.ingestion_sdk_name !== UNKNOWN_INGESTION_SDK_VALUE;
  const version = (() => {
    if (hasAttribution) {
      if (row.ingestion_sdk_version !== UNKNOWN_INGESTION_SDK_VALUE) {
        return row.ingestion_sdk_version;
      }
      return "";
    }
    return undefined;
  })();

  return {
    isOtel: true,
    ...(hasAttribution && { name: row.ingestion_sdk_name }),
    ...(version && { version }),
    ...(row.telemetry_sdk_language && {
      language: row.telemetry_sdk_language,
    }),
  };
}

export const getTracesIdentifierForSessionFromEvents = async (
  projectId: string,
  sessionId: string,
) => {
  /** tracesCte aggregates traces with a span in the session, keeping those whose aggregated session_id equals sessionId */
  const tracesCte = (qb: QueryCreator<ClickHouseDatabase>) =>
    qb
      .selectFrom("events as e")
      .select((eb) => traceAggregationSelects(SESSION_TRACE_FIELDS)(eb))
      .where("e.trace_id", "in", (eb) =>
        eb
          .selectFrom("events")
          .select("trace_id")
          .distinct()
          .where("session_id", "=", sessionId),
      )
      .groupBy(["trace_id", "project_id"])
      .having("session_id", "=", sessionId);

  /** builder emits `select t.id, t.user_id, … from event_traces t order by t.timestamp limit 1 by t.id, t.project_id` */
  const builder = getClickhouseKysely()
    .with("event_traces", tracesCte)
    .selectFrom("event_traces as t")
    .select([
      "t.id",
      "t.user_id",
      "t.name",
      "t.timestamp",
      "t.project_id",
      "t.environment",
    ])
    .orderBy("t.timestamp", "asc")
    .$call(
      limitBy({
        count: 1,
        columns: (eb) => [eb.ref("t.id"), eb.ref("t.project_id")],
      }),
    );

  const { sql: query, params } = compileClickhouseQuery(builder, projectId);

  const rows = await queryClickhouse<{
    id: string;
    user_id: string;
    name: string;
    timestamp: string;
    environment: string;
  }>({
    query,
    params,
    tags: { projectId },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => ({
    id: row.id,
    userId: row.user_id,
    name: row.name,
    timestamp: parseClickhouseUTCDateTimeFormat(row.timestamp),
    environment: row.environment,
  }));
};