Skip to content

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

109 KB
Raw Blame
/* eslint-disable no-nested-ternary, @typescript-eslint/no-use-before-define */
import { z } from "zod";
import {
  ScoreDataTypeType,
  ScoreDomain,
  ScoreSourceType,
  AGGREGATABLE_SCORE_TYPES,
  AggregatableScoreDataType,
  ScoreByDataType,
  LISTABLE_SCORE_TYPES,
  ListableScoreDataType,
  ScoreDataTypeEnum,
} from "../../domain/scores";
import {
  SCORE_EXPORT_CORE_FIELDS,
  SCORE_EXPORT_FIELD_GROUPS,
  SCORE_EXPORT_GROUP_FIELDS,
  type ScoreExportFieldGroup,
} from "../../domain/export-field-groups";
import { InvalidRequestError } from "../../errors/InvalidRequestError";
import { InternalServerError } from "../../errors/InternalServerError";
import {
  eventsTableIsRootObservationSql,
  eventsTableTraceNameSql,
  eventsTableTraceNameAggregationSql,
} from "../../eventsTable";
import type { APIScoreV3 } from "../../features/scores/interfaces/api/v3/schemas";
import type { ScoreFieldGroupV3 } from "../../features/scores/interfaces/api/v3/endpoints";
import { filterAndValidateV3GetScoreList } from "../../features/scores/interfaces/api/v3/validation";
import {
  commandClickhouse,
  type ClickhouseQueryOpts,
  queryClickhouse,
  queryClickhouseStream,
  queryClickhouseExecRaw,
  BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
  upsertClickhouse,
  parseClickhouseUTCDateTimeFormat,
  clickhouseCompliantRandomCharacters,
} from "./clickhouse";
import {
  FilterList,
  StringOptionsFilter,
  DateTimeFilter,
  NumberFilter,
} from "../queries/clickhouse-sql/clickhouse-filter";
import { orderByToClickhouseSql } from "../queries/clickhouse-sql/orderby-factory";
import { scoreOnlyFiltersAreSeekEligible } from "../queries/clickhouse-sql/score-seek-eligibility";
import { FilterCondition, FilterState, TimeFilter } from "../../types";
import {
  createFilterFromFilterState,
  getProjectIdDefaultFilter,
} from "../queries/clickhouse-sql/factory";
import { OrderByState } from "../../interfaces/orderBy";
import { dashboardColumnDefinitions } from "../../tableDefinitions/mapDashboards";
import {
  scoresTableUiColumnDefinitions,
  scoresTableUiColumnDefinitionsFromEvents,
} from "../tableMappings/mapScoresTable";
import {
  convertScoreAggregation,
  convertClickhouseScoreToDomain,
  ScoreAggregation,
} from "./scores_converters";
import { SCORE_TO_TRACE_OBSERVATIONS_INTERVAL } from "./constants";
import {
  convertDateToClickhouseDateTime,
  PreferredClickhouseService,
} from "../clickhouse/client";
import { ScoreRecordReadType } from "./definitions";
import { env } from "../../env";
import { _handleGetScoreById, _handleGetScoresByIds } from "./scores-utils";
import { parseMetadataCHRecordToDomain } from "../utils/metadata_conversion";
import type { AnalyticsScoreEvent } from "../analytics-integrations/types";
import { ClickHouseClientConfigOptions } from "@clickhouse/client";
import { recordDistribution } from "../instrumentation";
import { logger } from "../logger";
import { prisma } from "../../db";
import { scoresColumnsTableUiColumnDefinitions } from "../tableMappings/mapScoresColumnsTable";
import {
  eventsTraceMetadata,
  eventsExperimentTraceIds,
} from "../queries/clickhouse-sql/query-fragments";
import { compileClickhouseQuery } from "../query-ast/compile";
import { shouldSkipScoresDedup } from "../queries/clickhouse-sql/query-options";
import { getClickhouseKysely } from "../query-ast/dialect";
import {
  limitBy,
  literal,
  mapKeys,
  notEmpty,
  useFinal,
} from "../query-ast/extensions";
import { scoresTableCols } from "../../tableDefinitions/scoresTable";
import { promptGenerationEvents } from "./prompt-events";
import {
  findUiColumnMapping,
  matchesUiColumnMapping,
} from "../../tableDefinitions/types";

const FILTER_OPTION_SCORE_NAME_LIMIT = 200;
const FILTER_OPTION_CATEGORICAL_VALUE_LIMIT = 20;

export const searchExistingAnnotationScore = async (
  projectId: string,
  observationId: string | null,
  traceId: string | null,
  sessionId: string | null,
  name: string | undefined,
  configId: string | undefined,
  dataType: ScoreDataTypeType,
) => {
  if (!name && !configId) {
    throw new Error("Either name or configId (or both) must be provided.");
  }

  const query = `
    SELECT *
    FROM scores s
    WHERE s.project_id = {projectId: String}
    AND s.source = 'ANNOTATION'
    AND s.data_type = {dataType: String}
    ${traceId ? `AND s.trace_id = {traceId: String}` : "AND isNull(s.trace_id)"}
    ${observationId ? `AND s.observation_id = {observationId: String}` : "AND isNull(s.observation_id)"}
    ${sessionId ? `AND s.session_id = {sessionId: String}` : "AND isNull(s.session_id)"}
    AND (
      FALSE
      ${name ? `OR s.name = {name: String}` : ""}
      ${configId ? `OR s.config_id = {configId: String}` : ""}
    )
    ORDER BY s.event_ts DESC
    ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
    LIMIT 1
  `;

  const rows = await queryClickhouse<ScoreRecordReadType>({
    query,
    params: {
      projectId,
      name,
      configId,
      traceId,
      observationId,
      sessionId,
      dataType,
    },
    tags: { projectId },
  });
  return rows.map((row) => convertClickhouseScoreToDomain(row)).shift();
};

export const getScoreById = async ({
  projectId,
  scoreId,
  source,
  preferredClickhouseService,
}: {
  projectId: string;
  scoreId: string;
  source?: ScoreSourceType;
  preferredClickhouseService?: PreferredClickhouseService;
}): Promise<ScoreDomain | undefined> => {
  return _handleGetScoreById({
    projectId,
    scoreId,
    source,
    scoreScope: "all",
    preferredClickhouseService,
  });
};

export const getScoresByIds = async (
  projectId: string,
  scoreId: string[],
  source?: ScoreSourceType,
  preferredClickhouseService?: PreferredClickhouseService,
): Promise<ScoreDomain[]> => {
  return _handleGetScoresByIds({
    projectId,
    scoreId,
    source,
    scoreScope: "all",
    dataTypes: LISTABLE_SCORE_TYPES,
    preferredClickhouseService,
  });
};

/**
 * Accepts a score in a Clickhouse-ready format.
 * id, project_id, name, and timestamp must always be provided.
 */
export const upsertScore = async (score: Partial<ScoreRecordReadType>) => {
  if (!["id", "project_id", "name", "timestamp"].every((key) => key in score)) {
    throw new Error("Identifier fields must be provided to upsert Score.");
  }
  await upsertClickhouse({
    table: "scores",
    records: [score as ScoreRecordReadType],
    eventBodyMapper: convertClickhouseScoreToDomain,
    tags: { projectId: score.project_id ?? "" },
  });
};

export type GetScoresForTracesProps<
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
> = {
  projectId: string;
  traceIds: string[];
  level?: "trace" | "observation" | "all";
  timestamp?: Date;
  limit?: number;
  offset?: number;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  excludeMetadata?: ExcludeMetadata;
  includeHasMetadata?: IncludeHasMetadata;
  preferredClickhouseService?: PreferredClickhouseService;
};

type GetScoresForSessionsProps<
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
> = {
  projectId: string;
  sessionIds: string[];
  limit?: number;
  offset?: number;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  excludeMetadata?: ExcludeMetadata;
  includeHasMetadata?: IncludeHasMetadata;
};

type GetScoresForExperimentsProps<
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
> = {
  projectId: string;
  runIds: string[];
  limit?: number;
  offset?: number;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  excludeMetadata?: ExcludeMetadata;
  includeHasMetadata?: IncludeHasMetadata;
};

const formatMetadataSelect = (
  excludeMetadata: boolean,
  includeHasMetadata: boolean,
) => {
  return [
    !excludeMetadata
      ? "* EXCEPT (evaluator_id, evaluation_rule_id)"
      : "* EXCEPT (metadata, evaluator_id, evaluation_rule_id)",
    includeHasMetadata
      ? "length(mapKeys(s.metadata)) > 0 AS has_metadata"
      : null,
  ]
    .filter((s) => s != null)
    .join(", ");
};

export const getScoresForSessions = async <
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
>(
  props: GetScoresForSessionsProps<ExcludeMetadata, IncludeHasMetadata>,
) => {
  const {
    projectId,
    sessionIds,
    limit,
    offset,
    clickhouseConfigs,
    excludeMetadata = false,
    includeHasMetadata = false,
  } = props;

  const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);

  const query = `
      select
        ${select}
      from scores s
      WHERE s.project_id = {projectId: String}
      AND s.session_id IN ({sessionIds: Array(String)})
      AND s.data_type IN ({dataTypes: Array(String)})
      ORDER BY s.event_ts DESC
      ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
      ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
    `;

  const rows = await queryClickhouse<ScoreRecordReadType>({
    query: query,
    params: {
      projectId,
      sessionIds,
      limit,
      offset,
      dataTypes: LISTABLE_SCORE_TYPES,
    },
    tags: { projectId },
    clickhouseConfigs,
    preferredClickhouseService: "ReadOnly",
  });

  const includeMetadataPayload = !excludeMetadata;
  return rows.map((row) =>
    convertClickhouseScoreToDomain(row, includeMetadataPayload),
  );
};

export const getScoresForExperiments = async <
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
>(
  props: GetScoresForExperimentsProps<ExcludeMetadata, IncludeHasMetadata>,
) => {
  const {
    projectId,
    runIds,
    limit,
    offset,
    clickhouseConfigs,
    excludeMetadata = false,
    includeHasMetadata = false,
  } = props;

  const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);

  const query = `
      select
        ${select}
      from scores s
      WHERE s.project_id = {projectId: String}
      AND s.dataset_run_id IN ({runIds: Array(String)})
      AND s.data_type IN ({dataTypes: Array(String)})
      ORDER BY s.event_ts DESC
      ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
      ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
    `;

  const rows = await queryClickhouse<ScoreRecordReadType>({
    query: query,
    params: {
      projectId,
      runIds,
      dataTypes: AGGREGATABLE_SCORE_TYPES,
      limit,
      offset,
    },
    tags: { projectId },
    clickhouseConfigs,
    preferredClickhouseService: "ReadOnly",
  });

  const includeMetadataPayload = !excludeMetadata;
  return rows.map((row) =>
    convertClickhouseScoreToDomain<ExcludeMetadata, AggregatableScoreDataType>(
      row,
      includeMetadataPayload,
    ),
  );
};

export const getTraceScoresForDatasetRuns = async (
  projectId: string,
  datasetRunIds: string[],
): Promise<Array<{ dataset_run_id: string } & any>> => {
  if (datasetRunIds.length === 0) return [];

  const query = `
    SELECT
      s.id as id,
      s.timestamp as timestamp,
      s.project_id as project_id,
      s.environment as environment,
      s.trace_id as trace_id,
      s.session_id as session_id,
      s.observation_id as observation_id,
      s.dataset_run_id as dataset_run_id,
      s.name as name,
      s.value as value,
      s.source as source,
      s.comment as comment,
      s.author_user_id as author_user_id,
      s.config_id as config_id,
      s.data_type as data_type,
      s.string_value as string_value,
      s.queue_id as queue_id,
      s.execution_trace_id as execution_trace_id,
      s.created_at as created_at,
      s.updated_at as updated_at,
      s.event_ts as event_ts,
      s.is_deleted as is_deleted,
      length(mapKeys(s.metadata)) > 0 AS has_metadata,
      dri.dataset_run_id as run_id
    FROM dataset_run_items_rmt dri
    JOIN scores s ${shouldSkipScoresDedup(projectId) ? "" : "FINAL"} ON dri.trace_id = s.trace_id
      AND dri.project_id = s.project_id
    WHERE dri.project_id = {projectId: String}
      AND dri.dataset_run_id IN {datasetRunIds: Array(String)}
      AND s.project_id = {projectId: String}
      AND s.data_type IN ({dataTypes: Array(String)})
    ORDER BY s.event_ts DESC
    LIMIT 1 BY s.id, s.project_id, dri.dataset_run_id
  `;

  const rows = await queryClickhouse<
    Omit<ScoreRecordReadType, "metadata"> & {
      has_metadata: 0 | 1;
      run_id: string;
    }
  >({
    query,
    params: {
      projectId,
      datasetRunIds,
      dataTypes: AGGREGATABLE_SCORE_TYPES,
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

  const includeMetadataPayload = false;
  return rows.map((row) => ({
    ...convertClickhouseScoreToDomain(
      { ...row, metadata: {} },
      includeMetadataPayload,
    ),
    datasetRunId: row.run_id,
    hasMetadata: !!row.has_metadata,
  }));
};

const experimentItemEventsQuery = (experimentIds: string[]) =>
  getClickhouseKysely()
    .selectFrom("events as e")
    .select(["e.project_id", "e.experiment_id", "e.trace_id"])
    .where("e.experiment_id", "in", experimentIds)
    .where("e.experiment_id", "!=", literal(""));

const scoresForExperimentItemsQuery = (
  experimentIds: string[],
  skipDedup: boolean,
) =>
  getClickhouseKysely()
    .selectFrom(experimentItemEventsQuery(experimentIds).as("e"))
    .innerJoin("scores as s", (join) =>
      join
        .onRef("e.trace_id", "=", "s.trace_id")
        .onRef("e.project_id", "=", "s.project_id"),
    )
    .$if(!skipDedup, useFinal(["scores"]))
    .select((eb) => [
      "s.id as id",
      "s.timestamp as timestamp",
      "s.project_id as project_id",
      "s.environment as environment",
      "s.trace_id as trace_id",
      "s.session_id as session_id",
      "s.observation_id as observation_id",
      "s.dataset_run_id as dataset_run_id",
      "s.name as name",
      "s.value as value",
      "s.source as source",
      "s.comment as comment",
      "s.author_user_id as author_user_id",
      "s.config_id as config_id",
      "s.data_type as data_type",
      "s.string_value as string_value",
      "s.queue_id as queue_id",
      "s.execution_trace_id as execution_trace_id",
      "s.created_at as created_at",
      "s.updated_at as updated_at",
      "s.event_ts as event_ts",
      "s.is_deleted as is_deleted",
      notEmpty(mapKeys(eb.ref("s.metadata"))).as("has_metadata"),
      "e.experiment_id as experiment_id",
    ])
    .where(
      "s.data_type",
      "in",
      AGGREGATABLE_SCORE_TYPES.map((t) => literal(t)),
    )
    .orderBy("s.event_ts", "desc")
    .$call(
      limitBy({
        count: 1,
        columns: (eb) => [
          eb.ref("s.id"),
          eb.ref("s.project_id"),
          eb.ref("e.experiment_id"),
        ],
      }),
    );

export const getScoresForExperimentItems = async (
  projectId: string,
  experimentIds: string[],
): Promise<
  Array<
    ScoreByDataType<AggregatableScoreDataType> & {
      experimentId: string;
      hasMetadata: boolean;
    }
  >
> => {
  if (experimentIds.length === 0) return [];

  const compiled = compileClickhouseQuery(
    scoresForExperimentItemsQuery(
      experimentIds,
      shouldSkipScoresDedup(projectId),
    ),
    projectId,
  );

  const rows = await queryClickhouse<
    Omit<ScoreRecordReadType, "metadata"> & {
      has_metadata: 0 | 1;
      experiment_id: string;
    }
  >({
    query: compiled.sql,
    params: compiled.params,
    tags: { projectId, route: "scores.getScoresForExperimentItems" },
    preferredClickhouseService: "EventsReadOnly",
  });

  const includeMetadataPayload = false;
  return rows.map((row) => ({
    ...convertClickhouseScoreToDomain<false, AggregatableScoreDataType>(
      { ...row, metadata: {} },
      includeMetadataPayload,
    ),
    experimentId: row.experiment_id,
    hasMetadata: !!row.has_metadata,
  }));
};

const getScoresForTracesInternal = async <
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
  DataTypes extends readonly ScoreDataTypeType[],
>(
  props: GetScoresForTracesProps<ExcludeMetadata, IncludeHasMetadata> & {
    dataTypes?: DataTypes;
  },
) => {
  const {
    projectId,
    traceIds,
    level = "all",
    timestamp,
    dataTypes,
    limit,
    offset,
    clickhouseConfigs,
    excludeMetadata = false,
    includeHasMetadata = false,
    preferredClickhouseService,
  } = props;

  const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);
  const levelFilter = (() => {
    if (level === "trace") {
      return "AND s.observation_id IS NULL";
    }
    if (level === "observation") {
      return "AND s.observation_id IS NOT NULL";
    }
    return "";
  })();

  const query = `
      select
        ${select}
      from scores s
      WHERE s.project_id = {projectId: String}
      AND s.trace_id IN ({traceIds: Array(String)})
      ${dataTypes ? `AND s.data_type IN ({dataTypes: Array(String)})` : ""}
      ${timestamp ? `AND s.timestamp >= {traceTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
      ${levelFilter}
      ORDER BY s.event_ts DESC
      ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
      ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
    `;

  const rows = await queryClickhouse<
    ScoreRecordReadType & {
      metadata: ExcludeMetadata extends true
        ? never
        : ScoreRecordReadType["metadata"];
      // has_metadata is 0 or 1 from ClickHouse, later converted to a boolean
      has_metadata: IncludeHasMetadata extends true ? 0 | 1 : never;
    }
  >({
    query: query,
    params: {
      projectId,
      traceIds,
      limit,
      offset,
      ...(dataTypes ? { dataTypes: dataTypes.map((d) => d.toString()) } : {}),
      ...(timestamp
        ? { traceTimestamp: convertDateToClickhouseDateTime(timestamp) }
        : {}),
    },
    tags: { projectId },
    clickhouseConfigs,
    preferredClickhouseService: preferredClickhouseService ?? "ReadOnly",
  });

  const includeMetadataPayload = !excludeMetadata;
  return rows.map((row) => {
    const score = convertClickhouseScoreToDomain(
      {
        ...row,
        metadata: excludeMetadata ? {} : row.metadata,
      },
      includeMetadataPayload,
    );

    recordDistribution(
      "langfuse.query_by_id_age",
      new Date().getTime() - score.timestamp.getTime(),
      {
        table: "scores",
      },
    );

    if (includeHasMetadata) {
      Object.assign(score, { hasMetadata: !!row.has_metadata });
    }

    return score;
  });
};

// Used in multiple places, including the public API, hence the non-default exclusion of metadata via excludeMetadata flag
export const getScoresForTraces = async <
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
>(
  props: GetScoresForTracesProps<ExcludeMetadata, IncludeHasMetadata>,
) => {
  return getScoresForTracesInternal({
    ...props,
    dataTypes: LISTABLE_SCORE_TYPES,
  });
};

export const getScoresAndCorrectionsForTraces = async <
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
>(
  props: GetScoresForTracesProps<ExcludeMetadata, IncludeHasMetadata>,
) => {
  return getScoresForTracesInternal({
    ...props,
  });
};

export type GetScoresForObservationsProps<
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
> = {
  projectId: string;
  observationIds: string[];
  /**
   * When provided, adds `AND s.timestamp >= minTimestamp - SCORE_TO_TRACE_OBSERVATIONS_INTERVAL`
   * to the query so ClickHouse can prune monthly partitions and avoid full-table scans.
   * Pass the minimum startTime of the observations whose scores you are fetching.
   */
  minTimestamp?: Date;
  limit?: number;
  offset?: number;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  excludeMetadata?: ExcludeMetadata;
  includeHasMetadata?: IncludeHasMetadata;
  preferredClickhouseService?: PreferredClickhouseService;
};

// Currently only used from the observations table, hence the exclusion of metadata without excludeMetadata flag
export const getScoresForObservations = async <
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
>(
  props: GetScoresForObservationsProps<ExcludeMetadata, IncludeHasMetadata>,
) => {
  const {
    projectId,
    observationIds,
    minTimestamp,
    limit,
    offset,
    clickhouseConfigs,
    excludeMetadata = false,
    includeHasMetadata = false,
    preferredClickhouseService,
  } = props;

  const select = formatMetadataSelect(excludeMetadata, includeHasMetadata);

  const query = `
      select
        ${select}
      from scores s
      WHERE s.project_id = {projectId: String}
      AND s.observation_id IN ({observationIds: Array(String)})
      AND s.data_type IN ({dataTypes: Array(String)})
      ${minTimestamp ? `AND s.timestamp >= {minTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
      ORDER BY s.event_ts DESC
      ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
      ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
    `;

  const rows = await queryClickhouse<
    ScoreRecordReadType & {
      metadata: ExcludeMetadata extends true
        ? never
        : ScoreRecordReadType["metadata"];
      // has_metadata is 0 or 1 from ClickHouse, later converted to a boolean
      has_metadata: IncludeHasMetadata extends true ? 0 | 1 : never;
    }
  >({
    query: query,
    params: {
      projectId: projectId,
      observationIds: observationIds,
      dataTypes: LISTABLE_SCORE_TYPES,
      limit: limit,
      offset: offset,
      ...(minTimestamp
        ? { minTimestamp: convertDateToClickhouseDateTime(minTimestamp) }
        : {}),
    },
    tags: { projectId },
    clickhouseConfigs,
    preferredClickhouseService,
  });

  const includeMetadataPayload = !excludeMetadata;
  return rows.map((row) => ({
    ...convertClickhouseScoreToDomain(
      {
        ...row,
        metadata: excludeMetadata ? {} : row.metadata,
      },
      includeMetadataPayload,
    ),
    hasMetadata: (includeHasMetadata
      ? !!row.has_metadata
      : undefined) as IncludeHasMetadata extends true ? boolean : never,
  }));
};

const uniqueNonEmptyStrings = (values: string[]) =>
  [...new Set(values)].filter(Boolean);

const scoreRecordReadColumns = [
  "id",
  "project_id",
  "trace_id",
  "session_id",
  "observation_id",
  "dataset_run_id",
  "environment",
  "name",
  "value",
  "source",
  "comment",
  "metadata",
  "author_user_id",
  "config_id",
  "data_type",
  "string_value",
  "long_string_value",
  "queue_id",
  "execution_trace_id",
  "is_deleted",
  "created_at",
  "updated_at",
  "timestamp",
  "event_ts",
];

const commaSeparatedSelect = (columns: string[]) => columns.join(", ");

const scoreRecordReadSelect = commaSeparatedSelect(
  scoreRecordReadColumns.map((column) => `s.${column}`),
);

export async function queryScoreRecordsForExperimentItems({
  projectId,
  traceIds,
  observationIds,
  min,
  toTimestamp,
  scoreLimit,
}: {
  projectId: string;
  traceIds: string[];
  observationIds: string[];
  min: Date; // applied verbatim, no offset widening — callers pre-widen
  toTimestamp?: Date; // applied verbatim, no offset widening
  scoreLimit: number;
}) {
  const uniqueTraceIds = uniqueNonEmptyStrings(traceIds);
  const uniqueObservationIds = uniqueNonEmptyStrings(observationIds);

  if (uniqueTraceIds.length === 0 && uniqueObservationIds.length === 0) {
    return [];
  }

  const input = {
    params: {
      projectId,
      traceIds: uniqueTraceIds,
      observationIds: uniqueObservationIds,
      minStartTime: convertDateToClickhouseDateTime(min),
      ...(toTimestamp
        ? { maxStartTime: convertDateToClickhouseDateTime(toTimestamp) }
        : {}),
      scoreLimit,
      dataTypes: LISTABLE_SCORE_TYPES.map((type) => type.toString()),
    },
    tags: {
      projectId,
      operation_name: "queryScoreRecordsForExperimentItems",
    },
  };
  return await queryClickhouse<ScoreRecordReadType>({
    query: `
      SELECT
        ${scoreRecordReadSelect}
      FROM (
        SELECT
          ${scoreRecordReadSelect}
        FROM scores s
        WHERE s.project_id = {projectId: String}
          AND s.timestamp >= {minStartTime: DateTime64(3)}
          ${toTimestamp ? "AND s.timestamp < {maxStartTime: DateTime64(3)}" : ""}
          AND s.data_type IN ({dataTypes: Array(String)})
          AND (
            s.observation_id IN ({observationIds: Array(String)})
            OR (
              s.trace_id IN ({traceIds: Array(String)})
              AND (s.observation_id IS NULL OR s.observation_id = '')
              AND s.session_id IS NULL
              AND s.dataset_run_id IS NULL
            )
          )
        ORDER BY s.event_ts DESC
        ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id"}
      ) s
      ORDER BY s.event_ts DESC
      LIMIT {scoreLimit: UInt32} BY s.trace_id
    `,
    params: input.params,
    tags: input.tags,
    preferredClickhouseService: "ReadOnly",
  });
}

export async function queryScoreRecordsForExperiments({
  projectId,
  experimentIds,
  fromTimestamp,
  toTimestamp,
  scoreLimit,
}: {
  projectId: string;
  experimentIds: string[];
  fromTimestamp: Date; // applied verbatim, no offset widening — callers pre-widen
  toTimestamp?: Date; // applied verbatim, no offset widening
  scoreLimit: number;
}) {
  const uniqueExperimentIds = uniqueNonEmptyStrings(experimentIds);

  if (uniqueExperimentIds.length === 0) {
    return [];
  }

  const input = {
    params: {
      projectId,
      experimentIds: uniqueExperimentIds,
      startTimeFrom: convertDateToClickhouseDateTime(fromTimestamp),
      ...(toTimestamp
        ? { startTimeTo: convertDateToClickhouseDateTime(toTimestamp) }
        : {}),
      scoreLimit,
      dataTypes: LISTABLE_SCORE_TYPES.map((type) => type.toString()),
    },
    tags: {
      projectId,
      operation_name: "queryScoreRecordsForExperiments",
    },
  };
  return await queryClickhouse<ScoreRecordReadType>({
    query: `
      SELECT
        ${scoreRecordReadSelect}
      FROM (
        SELECT
          ${scoreRecordReadSelect}
        FROM scores s
        WHERE s.project_id = {projectId: String}
          AND s.timestamp >= {startTimeFrom: DateTime64(3)}
          ${toTimestamp ? "AND s.timestamp < {startTimeTo: DateTime64(3)}" : ""}
          AND s.dataset_run_id IN ({experimentIds: Array(String)})
          AND s.data_type IN ({dataTypes: Array(String)})
          AND s.trace_id IS NULL
          AND s.observation_id IS NULL
          AND s.session_id IS NULL
        ORDER BY s.event_ts DESC
        ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id"}
      ) s
      ORDER BY s.dataset_run_id ASC, s.event_ts DESC
      LIMIT {scoreLimit: UInt32} BY s.dataset_run_id
    `,
    params: input.params,
    tags: input.tags,
    preferredClickhouseService: "ReadOnly",
  });
}

/**
 * Event/experiment column mappings for building WHERE filters inside the events CTE.
 * Maps to actual events_proto columns with the "e" prefix used by EventsQueryBuilder.
 */
const scoresEventsFilterMapping = [
  {
    uiTableName: "Experiment IDs",
    uiTableId: "experimentIds",
    clickhouseTableName: "events_proto",
    clickhouseSelect: "experiment_id",
    queryPrefix: "e",
  },
];

export const getScoresGroupedByNameSourceType = async ({
  projectId,
  filter,
  fromTimestamp,
  toTimestamp,
}: {
  projectId: string;
  filter: FilterCondition[];
  fromTimestamp?: Date;
  toTimestamp?: Date;
}) => {
  const scoresFilter = new FilterList();
  scoresFilter.push(
    ...createFilterFromFilterState(
      filter,
      scoresColumnsTableUiColumnDefinitions,
      scoresTableCols,
    ),
  );

  // Separate scores-only filters from event/experiment filters
  const nonEventFilters = scoresFilter.filter(
    (f) => !f.clickhouseTable.startsWith("events_"),
  );

  const scoresFilterRes = nonEventFilters.apply();

  // Only join dataset run items if there is a dataset run items filter
  const performDatasetRunItemsJoin = scoresFilter.some(
    (f) => f.clickhouseTable === "dataset_run_items_rmt",
  );

  // Extract event-level filter entries from the frontend filter state
  const eventFilterState = filter.filter((filterEntry) =>
    scoresEventsFilterMapping.some((col) =>
      matchesUiColumnMapping(col, filterEntry.column),
    ),
  );

  let eventsCTE = "";
  let eventsCTEParams: Record<string, unknown> = {};
  const hasEventsFilters = eventFilterState.length > 0;

  let eventsFilterRes;
  if (hasEventsFilters) {
    const eventsBuilder = eventsExperimentTraceIds(projectId);

    // Create filters from the event filter state using the proper column mappings
    const cteEventFilters = new FilterList(
      createFilterFromFilterState(eventFilterState, scoresEventsFilterMapping),
    );
    eventsFilterRes = cteEventFilters.apply();
    if (eventsFilterRes.query) {
      eventsBuilder.where(eventsFilterRes);
    }

    const { query: cteQuery, params: cteParams } =
      eventsBuilder.buildWithParams();
    eventsCTE = `WITH experiment_events AS (${cteQuery})`;
    Object.assign(eventsCTEParams, cteParams);
  }

  // We mainly use queries like this to retrieve filter options.
  // Therefore, we can skip final as some inaccuracy in count is acceptable.

  const query = `
    ${eventsCTE}
    SELECT
      s.name as name,
      s.source as source,
      s.data_type as data_type
    FROM scores s
    ${performDatasetRunItemsJoin ? `JOIN dataset_run_items_rmt dri ON s.trace_id = dri.trace_id AND s.project_id = dri.project_id` : ""}
    WHERE s.project_id = {projectId: String}
    ${hasEventsFilters ? `AND (s.project_id, s.trace_id) IN (SELECT project_id, trace_id FROM experiment_events)` : ""}
    ${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
    ${fromTimestamp ? `AND s.timestamp >= {fromTimestamp: DateTime64(3)}` : ""}
    ${toTimestamp ? `AND s.timestamp <= {toTimestamp: DateTime64(3)}` : ""}
    AND s.data_type IN ({dataTypes: Array(String)})
    GROUP BY name, source, data_type
    ORDER BY count() desc
    LIMIT ${FILTER_OPTION_SCORE_NAME_LIMIT};
  `;

  const rows = await queryClickhouse<{
    name: string;
    source: string;
    data_type: string;
  }>({
    query: query,
    params: {
      projectId: projectId,
      dataTypes: LISTABLE_SCORE_TYPES,
      ...(fromTimestamp
        ? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }
        : {}),
      ...(toTimestamp
        ? { toTimestamp: convertDateToClickhouseDateTime(toTimestamp) }
        : {}),
      ...(scoresFilterRes ? scoresFilterRes.params : {}),
      ...(eventsFilterRes ? eventsFilterRes.params : {}),
      ...eventsCTEParams,
    },
    tags: { projectId },
    preferredClickhouseService: hasEventsFilters
      ? "EventsReadOnly"
      : "ReadOnly",
  });

  return rows.map((row) => ({
    name: row.name,
    source: row.source as ScoreSourceType,
    dataType: row.data_type as ListableScoreDataType,
  }));
};

export const getNumericScoresGroupedByName = async (
  projectId: string,
  filter?: FilterState,
) => {
  // Despite the historical name of some callers, this accepts any score-table
  // compatible filter. Trace tables use this to scope discovery to scores that
  // roll up into trace aggregates, not just direct trace-level scores.
  const chFilter = filter
    ? createFilterFromFilterState(
        filter,
        scoresColumnsTableUiColumnDefinitions,
        scoresTableCols,
      )
    : undefined;

  const filterRes = chFilter ? new FilterList(chFilter).apply() : undefined;

  // We mainly use queries like this to retrieve filter options.
  // Therefore, we can skip final as some inaccuracy in count is acceptable.
  const query = `
      select
        name as name
      from scores s
      WHERE s.project_id = {projectId: String}
      AND has(['NUMERIC', 'BOOLEAN'], s.data_type)
      ${filterRes?.query ? `AND ${filterRes.query}` : ""}
      GROUP BY name
      ORDER BY count() desc
      LIMIT ${FILTER_OPTION_SCORE_NAME_LIMIT};
    `;

  const rows = await queryClickhouse<{
    name: string;
  }>({
    query: query,
    params: {
      projectId: projectId,
      ...(filterRes ? filterRes.params : {}),
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

  return rows;
};

export const getBooleanScoresGroupedByName = async (
  projectId: string,
  filter?: FilterState,
) => {
  const chFilter = filter
    ? createFilterFromFilterState(
        filter,
        scoresColumnsTableUiColumnDefinitions,
        scoresTableCols,
      )
    : undefined;

  const filterRes = chFilter ? new FilterList(chFilter).apply() : undefined;

  const query = `
      select
        name as name
      from scores s
      WHERE s.project_id = {projectId: String}
      AND s.data_type = 'BOOLEAN'
      AND s.string_value IS NOT NULL
      AND s.string_value != ''
      ${filterRes?.query ? `AND ${filterRes.query}` : ""}
      GROUP BY name
      ORDER BY count() desc
      LIMIT ${FILTER_OPTION_SCORE_NAME_LIMIT};
    `;

  const rows = await queryClickhouse<{
    name: string;
  }>({
    query: query,
    params: {
      projectId: projectId,
      ...(filterRes ? filterRes.params : {}),
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

  return rows;
};

export const getCategoricalScoresGroupedByName = async (
  projectId: string,
  filter?: FilterState,
) => {
  // Mirrors `getNumericScoresGroupedByName`: callers can provide any score
  // scope filters, not just timestamp predicates.
  const chFilter = filter
    ? createFilterFromFilterState(
        filter,
        scoresColumnsTableUiColumnDefinitions,
        scoresTableCols,
      )
    : undefined;

  const filterRes = chFilter ? new FilterList(chFilter).apply() : undefined;

  const query = `
    SELECT
      name AS label,
      groupUniqArray(${FILTER_OPTION_CATEGORICAL_VALUE_LIMIT})(string_value) AS values
    FROM scores s
    WHERE s.project_id = {projectId: String}
    AND s.data_type = 'CATEGORICAL'
    ${filterRes?.query ? `AND ${filterRes.query}` : ""}
    GROUP BY name
    ORDER BY count() DESC
    LIMIT ${FILTER_OPTION_SCORE_NAME_LIMIT};
  `;

  const rows = await queryClickhouse<{
    label: string;
    values: string[];
  }>({
    query: query,
    params: {
      projectId: projectId,
      ...(filterRes ? filterRes.params : {}),
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

  // Get score names from ClickHouse results to query score configs
  const scoreNames = rows.map((row) => row.label);

  // Query score_configs table for categorical configurations
  const scoreConfigs =
    scoreNames.length > 0
      ? await prisma.scoreConfig.findMany({
          where: {
            projectId: projectId,
            name: {
              in: scoreNames,
            },
            dataType: "CATEGORICAL",
            isArchived: false,
          },
          select: {
            name: true,
            categories: true,
          },
        })
      : [];

  // Create a map of score configs for easy lookup
  const configMap = new Map(
    scoreConfigs.map((config) => [config.name, config.categories]),
  );

  // Enhance the results with all possible category values from score configs
  return rows.map((row) => {
    const configCategories = configMap.get(row.label);

    if (configCategories && Array.isArray(configCategories)) {
      // Extract all possible category labels from the score config
      const allPossibleValues = (
        configCategories as Array<{ label: string; value: number }>
      ).map((category) => category.label);

      // Merge actual values from ClickHouse with all possible values from config
      // Use Set to ensure uniqueness
      const mergedValues = Array.from(
        new Set([...row.values, ...allPossibleValues]),
      ).slice(0, FILTER_OPTION_CATEGORICAL_VALUE_LIMIT);

      return {
        ...row,
        values: mergedValues,
      };
    }

    // If no config found, return original values
    return row;
  });
};

export const getScoresUiCount = async (props: {
  projectId: string;
  filter: FilterState;
  orderBy: OrderByState;
  limit?: number;
  offset?: number;
}) => {
  const rows = await getScoresUiGeneric<{ count: string }>({
    select: "count",
    excludeMetadata: true,
    ...props,
    preferredClickhouseService: "ReadOnly",
  });

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

export type ScoreUiTableRow = ScoreDomain & {
  traceName: string | null;
  traceUserId: string | null;
  traceTags: Array<string> | null;
};

export async function getScoresUiTable<
  ExcludeMetadata extends boolean,
  IncludeHasMetadata extends boolean,
>(props: {
  projectId: string;
  filter: FilterState;
  orderBy: OrderByState;
  limit?: number;
  offset?: number;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  excludeMetadata?: ExcludeMetadata;
  includeHasMetadataFlag?: IncludeHasMetadata;
  preferredClickhouseService?: PreferredClickhouseService;
}) {
  const {
    excludeMetadata = false,
    includeHasMetadataFlag = false,
    clickhouseConfigs,
    preferredClickhouseService,
    ...rest
  } = props;

  const rows = await getScoresUiGeneric<{
    id: string;
    project_id: string;
    environment: string;
    name: string;
    value: number;
    string_value: string | null;
    timestamp: string;
    source: string;
    data_type: string;
    comment: string | null;
    trace_id: string | null;
    session_id: string | null;
    dataset_run_id: string | null;
    metadata: ExcludeMetadata extends true ? never : Record<string, string>;
    observation_id: string | null;
    author_user_id: string | null;
    user_id: string | null;
    trace_name: string | null;
    trace_tags: Array<string> | null;
    job_configuration_id: string | null;
    author_user_image: string | null;
    author_user_name: string | null;
    config_id: string | null;
    queue_id: string | null;
    execution_trace_id: string | null;
    ingestion_api_key: string;
    ingestion_sdk_name: string;
    ingestion_sdk_version: string;
    is_deleted: number;
    event_ts: string;
    created_at: string;
    updated_at: string;
    // has_metadata is 0 or 1 from ClickHouse, later converted to a boolean
    has_metadata: IncludeHasMetadata extends true ? 0 | 1 : never;
  }>({
    select: "rows",
    excludeMetadata,
    includeHasMetadataFlag,
    clickhouseConfigs,
    preferredClickhouseService,
    ...rest,
  });

  const includeMetadataPayload = !excludeMetadata;
  return rows.map((row) => {
    const score = convertClickhouseScoreToDomain(
      {
        ...row,
        metadata: excludeMetadata ? {} : row.metadata,
        // Long string value is never required for scores UI table, so we always return an empty string
        long_string_value: "",
      },
      includeMetadataPayload,
    );
    return {
      ...score,
      traceUserId: row.user_id,
      traceName: row.trace_name,
      traceTags: row.trace_tags,
      hasMetadata: (includeHasMetadataFlag
        ? !!row.has_metadata
        : undefined) as IncludeHasMetadata extends true ? boolean : never,
    };
  });
}

const getScoresUiGeneric = async <T>(props: {
  select: "count" | "rows";
  projectId: string;
  filter: FilterState;
  orderBy: OrderByState;
  limit?: number;
  offset?: number;
  tags?: Record<string, string>;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  excludeMetadata?: boolean;
  includeHasMetadataFlag?: boolean;
  preferredClickhouseService?: PreferredClickhouseService;
}): Promise<T[]> => {
  const {
    projectId,
    filter,
    orderBy,
    limit,
    offset,
    clickhouseConfigs,
    preferredClickhouseService,
    excludeMetadata = false,
    includeHasMetadataFlag = false,
  } = props;

  const select =
    props.select === "count"
      ? "count(*) as count"
      : `
        s.id,
        s.project_id,
        s.environment,
        s.name,
        s.value,
        s.string_value,
        s.timestamp,
        s.source,
        s.data_type,
        s.comment,
        ${excludeMetadata ? "" : "s.metadata,"}
        s.trace_id,
        s.session_id,
        s.dataset_run_id,
        s.observation_id,
        s.author_user_id,
        t.user_id,
        t.name,
        t.tags,
        s.created_at,
        s.updated_at,
        s.source,
        s.config_id,
        s.queue_id,
        s.execution_trace_id,
        s.ingestion_api_key,
        s.ingestion_sdk_name,
        s.ingestion_sdk_version,
        s.is_deleted,
        s.event_ts,
        t.user_id,
        t.name as trace_name,
        t.tags as trace_tags
        ${includeHasMetadataFlag ? ",length(mapKeys(s.metadata)) > 0 AS has_metadata" : ""}
      `;

  const { scoresFilter } = getProjectIdDefaultFilter(projectId, {
    tracesPrefix: "t",
  });
  scoresFilter.push(
    ...createFilterFromFilterState(
      filter,
      scoresTableUiColumnDefinitions,
      scoresTableCols,
    ),
  );
  const scoresFilterRes = scoresFilter.apply();

  const orderByClause = orderByToClickhouseSql(
    orderBy ?? null,
    scoresTableUiColumnDefinitions,
  );

  // Only join traces for rows or if there is a trace filter on counts
  const performTracesJoin =
    props.select === "rows" ||
    scoresFilter.some((f) => f.clickhouseTable === "traces");

  const query = `
      SELECT
          ${select}
      FROM scores s ${shouldSkipScoresDedup(projectId) ? "" : "FINAL"}
      ${performTracesJoin ? "LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id" : ""}
      WHERE s.project_id = {projectId: String}
      AND s.data_type IN ({dataTypes: Array(String)})
      ${scoresFilterRes?.query ? `AND ${scoresFilterRes.query}` : ""}
      ${props.select === "rows" ? withIdTiebreaker(orderByClause, orderBy) : orderByClause}
      ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}
    `;

  const input = {
    params: {
      projectId: projectId,
      dataTypes: LISTABLE_SCORE_TYPES,
      ...(scoresFilterRes ? scoresFilterRes.params : {}),
      limit: limit,
      offset: offset,
    },
    tags: { ...(props.tags ?? {}), projectId },
  };
  return queryClickhouse<T>({
    query,
    params: input.params,
    tags: input.tags,
    clickhouseConfigs,
    preferredClickhouseService,
  });
};

/**
 * Trace column mapping for building WHERE filters inside the flat events CTE.
 * References actual events_core columns with the "e" prefix used by
 * EventsQueryBuilder.
 */
const scoresTraceFilterEventsMapping = [
  {
    uiTableName: "Trace Name",
    uiTableId: "traceName",
    clickhouseTableName: "traces",
    clickhouseSelect: eventsTableTraceNameSql,
  },
  {
    uiTableName: "User ID",
    uiTableId: "userId",
    clickhouseTableName: "traces",
    clickhouseSelect: "user_id",
    queryPrefix: "e",
  },
  {
    uiTableName: "Trace Tags",
    uiTableId: "trace_tags",
    clickhouseTableName: "traces",
    clickhouseSelect: "tags",
    queryPrefix: "e",
  },
];

// Score columns the count path reconstructs to their latest version via
// argMax(col, event_ts), replacing FINAL. id / project_id / name are the
// grouping keys and so are selected directly, not here.
const SCORE_COUNT_DEDUP_COLUMNS = [
  "timestamp",
  "environment",
  "trace_id",
  "observation_id",
  "session_id",
  "evaluator_id",
  "evaluation_rule_id",
  "value",
  "source",
  "comment",
  "author_user_id",
  "data_type",
  "string_value",
  "metadata",
] as const;

/**
 * Coarse toDate(timestamp) prune for a dedup subquery's pre-dedup scan (count
 * and rows paths share it).
 *
 * The exact timestamp bound must NOT filter raw rows before dedup (a score's
 * timestamp is mutable across versions, so it could drop the latest one); it is
 * re-applied post-dedup in the outer WHERE. This prune only skips partitions /
 * granules, keeping or dropping whole day-buckets, so the latest version always
 * survives to the dedup. Operators are relaxed (> / < to >= / <=) and both
 * sides wrapped in toDate() so boundary-day rows are never lost.
 */
const buildScoresDatePrune = (
  filter: FilterState,
): { query: string; params: Record<string, unknown> } => {
  const timestampColumn = scoresTableUiColumnDefinitionsFromEvents.find(
    (c) => c.uiTableId === "timestamp",
  );
  if (!timestampColumn) return { query: "", params: {} };

  const timestampFilters = createFilterFromFilterState(
    filter.filter((f) => matchesUiColumnMapping(timestampColumn, f.column)),
    scoresTableUiColumnDefinitionsFromEvents,
    scoresTableCols,
  ).filter((f): f is DateTimeFilter => f instanceof DateTimeFilter);

  const params: Record<string, unknown> = {};
  const clauses = timestampFilters.map((f) => {
    const dateOp = f.operator.startsWith(">") ? ">=" : "<=";
    const varName = `scoresInnerDatePrune${clickhouseCompliantRandomCharacters()}`;
    const column = `${f.tablePrefix ? `${f.tablePrefix}.` : ""}${f.field}`;
    params[varName] = convertDateToClickhouseDateTime(new Date(f.value));
    return `toDate(${column}) ${dateOp} toDate({${varName}: DateTime64(3, 'UTC')})`;
  });

  return { query: clauses.join(" AND "), params };
};

/**
 * v4 variant: scores query using a flat events CTE instead of the physical
 * traces table. Trace-level filters and sort use a "traces" CTE built by
 * EventsQueryBuilder, joined as alias "e".
 * Does NOT select trace metadata (that comes via metricsFromEvents).
 */
const getScoresUiGenericFromEvents = async <T>(props: {
  select: "count" | "rows";
  projectId: string;
  filter: FilterState;
  orderBy: OrderByState;
  limit?: number;
  offset?: number;
  tags?: Record<string, string>;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  excludeMetadata?: boolean;
  includeHasMetadataFlag?: boolean;
}): Promise<T[]> => {
  const {
    projectId,
    filter,
    orderBy,
    limit,
    offset,
    clickhouseConfigs,
    excludeMetadata = false,
    includeHasMetadataFlag = false,
  } = props;

  // tracesPrefix value is unused here — only scoresFilter is destructured,
  // and trace-level filtering is handled via the CTE below.
  const { scoresFilter } = getProjectIdDefaultFilter(projectId, {
    tracesPrefix: "t",
  });
  scoresFilter.push(
    ...createFilterFromFilterState(
      filter,
      scoresTableUiColumnDefinitionsFromEvents,
      scoresTableCols,
    ),
  );

  const scoreOnlyFilters = scoresFilter.filter(
    (f) => f.clickhouseTable !== "traces",
  );
  const scoreOnlyFilterRes = scoreOnlyFilters.apply();

  // Coarse pre-dedup prune shared by the count and rows subqueries; see
  // buildScoresDatePrune.
  const { query: innerDatePruneQuery, params: innerDatePruneParams } =
    buildScoresDatePrune(filter);

  // Trace-level filter entries from the frontend filter state
  const traceFilterState = filter.filter((filterEntry) =>
    scoresTraceFilterEventsMapping.some((col) =>
      matchesUiColumnMapping(col, filterEntry.column),
    ),
  );

  const matchedOrderByColumn = orderBy
    ? findUiColumnMapping(
        scoresTableUiColumnDefinitionsFromEvents,
        orderBy.column,
      )
    : null;
  const orderByColumn =
    matchedOrderByColumn?.clickhouseTableName === "traces"
      ? matchedOrderByColumn
      : null;

  const needsTracesCTE = traceFilterState.length > 0 || !!orderByColumn;

  // Build traces CTE using flat EventsQueryBuilder when needed
  let tracesCTEClause = "";
  const tracesCTEParams: Record<string, unknown> = {};

  if (needsTracesCTE) {
    const tracesEventsBuilder = eventsTraceMetadata(projectId);

    if (traceFilterState.length > 0) {
      const cteTraceFilters = new FilterList(
        createFilterFromFilterState(
          traceFilterState,
          scoresTraceFilterEventsMapping,
          scoresTableCols,
        ),
      );
      const cteTraceFilterRes = cteTraceFilters.apply();
      if (cteTraceFilterRes.query) {
        tracesEventsBuilder.where(cteTraceFilterRes);
      }
    }

    const { query: cteQuery, params: cteParams } =
      tracesEventsBuilder.buildWithParams();
    tracesCTEClause = `WITH traces AS (${cteQuery})`;
    Object.assign(tracesCTEParams, cteParams);
  }

  // Inner join when trace filters are active (exclude scores without matching traces)
  // Left join when only sorting (keep all scores)
  // The traces CTE is unique per trace (LIMIT 1 BY), so the inner join cannot
  // fan out. It must not be ANY: an inner ANY JOIN also dedups the left side,
  // keeping only one score per trace.
  const eventsJoin = (() => {
    if (needsTracesCTE) {
      if (traceFilterState.length > 0) {
        return `INNER JOIN traces e ON s.trace_id = e.id`;
      }
      return `LEFT ANY JOIN traces e ON s.trace_id = e.id`;
    }
    return "";
  })();

  // id and name are aliased because the traces CTE (joined as `e`) also exposes
  // id and name: without the alias ClickHouse qualifies the output columns as
  // s.id / s.name to disambiguate, and the row mapper reads bare id / name.
  const rowSelect = `
        s.id AS id,
        s.project_id,
        s.environment,
        s.name AS name,
        s.value,
        s.string_value,
        s.timestamp,
        s.source,
        s.data_type,
        s.comment,
        s.evaluator_id,
        ${excludeMetadata ? "" : "s.metadata,"}
        s.trace_id,
        s.session_id,
        s.dataset_run_id,
        s.observation_id,
        s.author_user_id,
        s.created_at,
        s.updated_at,
        s.config_id,
        s.queue_id,
        s.execution_trace_id,
        s.ingestion_api_key,
        s.ingestion_sdk_name,
        s.ingestion_sdk_version,
        s.is_deleted,
        s.event_ts
        ${includeHasMetadataFlag ? ",length(mapKeys(s.metadata)) > 0 AS has_metadata" : ""}
      `;

  // ── Selective seek ────────────────────────────────────────────────────────
  // A highly selective score-only filter (single trace/observation/id, or a
  // name) otherwise reconstructs the whole project before the outer WHERE
  // discards almost everything. When at least one score-only conjunct is
  // index-prunable (see scoreOnlyFiltersAreSeekEligible), first collect the
  // matching dedup keys via the bloom / primary indexes, then reconstruct only
  // those keys.
  //
  // The seek carries the *entire* score-only predicate, not just the prunable
  // conjuncts: it stays a superset collection (proof below), the index prunes
  // granules via the eligible conjuncts, and the remaining conjuncts shrink the
  // key set within surviving granules.
  //
  // Correctness: if a key's deduped-latest satisfies predicate P, its latest raw
  // row satisfies P (the latest *is* a raw row), so `SELECT DISTINCT … WHERE P`
  // over raw rows collects it — `{latest matches P} ⊆ {some raw row matches P}`
  // for any P (negation, null, range included). False positives (a key seeked
  // via an older matching version whose latest no longer matches) are removed by
  // re-applying P in the outer WHERE post-dedup. The seek's projection is the
  // dedup key only, all immutable within a group, so the resulting tuple IN
  // touches only dedup-key columns and is safe pre-dedup.
  const skipDedup = shouldSkipScoresDedup(projectId);
  // The seek only narrows the dedup reconstruction; a plain scan has none.
  const seekEligible =
    !skipDedup && scoreOnlyFiltersAreSeekEligible(scoreOnlyFilters);
  const seekSubquery = seekEligible
    ? `
        SELECT DISTINCT s.project_id, toDate(s.timestamp), s.name, s.id
        FROM scores s
        WHERE s.project_id = {projectId: String}
        ${innerDatePruneQuery ? `AND ${innerDatePruneQuery}` : ""}
        ${scoreOnlyFilterRes?.query ? `AND ${scoreOnlyFilterRes.query}` : ""}`
    : "";

  // Pre-dedup inner scan: project scope + coarse date prune only. Mutable-column
  // filters run post-dedup in the outer WHERE (see the dedup rule below). When
  // the seek fired, the tuple IN restricts the reconstruct scan to seeked keys;
  // it references only dedup-key columns, so it is safe pre-dedup.
  const innerScanWhere = `
        WHERE s.project_id = {projectId: String}
        ${innerDatePruneQuery ? `AND ${innerDatePruneQuery}` : ""}
        ${seekSubquery ? `AND (s.project_id, toDate(s.timestamp), s.name, s.id) IN (${seekSubquery}\n        )` : ""}`;

  // Post-dedup outer filters, shared by the count and rows paths.
  const outerWhereClause = `
      WHERE s.data_type IN ({dataTypes: Array(String)})
      ${scoreOnlyFilterRes?.query ? `AND ${scoreOnlyFilterRes.query}` : ""}`;

  // ── Dedup without FINAL ───────────────────────────────────────────────────
  // Reads dedup the ReplacingMergeTree by reconstructing each score's latest
  // version instead of FINAL. The count path collapses columns with one argMax
  // GROUP BY pass. The rows path needs every (incl. wide Map/String) column, so
  // it INNER JOINs scores back to a GROUP BY subquery holding each key's
  // max(event_ts), matching on the full sorting key + that event_ts. Only the
  // latest version has event_ts = max, so the join *is* the dedup: every joined
  // row is a latest version.
  //
  // Rule: filter AFTER dedup, never before. value / comment / timestamp /
  // trace_id are mutable across versions, so filtering raw rows can surface a
  // stale version (filter value>0.5 on v1=0.9→v2=0.1 keeps v1; FINAL keeps none).
  // Filtering the join output honours this — filters only ever see latest
  // versions. The GROUP BY that finds max(event_ts) carries only project scope +
  // a coarse toDate prune (innerDatePruneQuery) + the seek (when eligible), so
  // whole buckets are kept/dropped, the latest is never lost pre-dedup, and the
  // seek scans once.
  //
  // Filters run INSIDE the dedup subquery (with the join) so ClickHouse prunes
  // the wide scan by the real predicates before assembling the full join. The
  // LIMIT 1 BY there collapses the only remaining duplicates: two raw rows
  // sharing a key's max event_ts. That tie is two versions with equal version
  // timestamps, where FINAL itself keeps an arbitrary row (its answer flips with
  // insert order), so an arbitrary tie pick is FINAL-consistent.
  //
  // The trace join, ORDER BY, and LIMIT/OFFSET run OUTSIDE the subquery, at one
  // level, so pagination follows the requested sort (and a traces-column sort can
  // reference the joined `e`).
  const orderByClause = withIdTiebreaker(
    orderByToClickhouseSql(
      orderBy ?? null,
      scoresTableUiColumnDefinitionsFromEvents,
    ),
    orderBy,
  );
  // The table sorts by day, not by timestamp. Putting the day first keeps the
  // order but lets ClickHouse read the newest days first and stop after the
  // page. Only the plain scan reads the table directly, so only it benefits.
  const sortsByScoreTimestamp =
    matchedOrderByColumn?.clickhouseTableName === "scores" &&
    matchedOrderByColumn.clickhouseSelect === "timestamp";
  const sortKeyOrderByClause =
    sortsByScoreTimestamp && orderBy
      ? orderByClause.replace(
          /^ORDER BY /,
          `ORDER BY toDate(s.timestamp) ${orderBy.order}, `,
        )
      : orderByClause;
  const orderAndPage = (clause: string) => `
      ${clause}
      ${limit !== undefined && offset !== undefined ? `limit {limit: Int32} offset {offset: Int32}` : ""}`;

  // Projects whose scores are never updated have one row per key, so they
  // read the table directly instead of reconstructing the latest version.
  const plainScanQuery = () => `
      ${tracesCTEClause}
      SELECT
          ${props.select === "count" ? "count(*) AS count" : rowSelect}
      FROM (
        SELECT s.*
        FROM scores s
        ${innerScanWhere}
      ) s
      ${eventsJoin}
      ${outerWhereClause}
      ${props.select === "count" ? "" : orderAndPage(sortKeyOrderByClause)}
    `;

  const dedupCountQuery = () => `
      ${tracesCTEClause}
      SELECT count(*) AS count
      FROM (
        SELECT
          s.id,
          s.project_id,
          s.name,
          ${SCORE_COUNT_DEDUP_COLUMNS.map(
            (c) => `argMax(s.${c}, s.event_ts) AS ${c}`,
          ).join(",\n          ")}
        FROM scores s
        ${innerScanWhere}
        GROUP BY s.project_id, toDate(s.timestamp), s.name, s.id
      ) s
      ${eventsJoin}
      ${outerWhereClause}
    `;

  const dedupRowsQuery = () => `
      ${tracesCTEClause}
      SELECT
          ${rowSelect}
      FROM (
        SELECT s.*
        FROM scores s
        INNER JOIN (
          SELECT
            s.project_id AS latest_project_id,
            toDate(s.timestamp) AS latest_date,
            s.name AS latest_name,
            s.id AS latest_id,
            max(s.event_ts) AS latest_event_ts
          FROM scores s
          ${innerScanWhere}
          GROUP BY s.project_id, toDate(s.timestamp), s.name, s.id
        ) latest
          ON s.project_id = latest.latest_project_id
          AND toDate(s.timestamp) = latest.latest_date
          AND s.name = latest.latest_name
          AND s.id = latest.latest_id
          AND s.event_ts = latest.latest_event_ts
        ${outerWhereClause}
        LIMIT 1 BY s.project_id, toDate(s.timestamp), s.name, s.id
      ) s
      ${eventsJoin}
      ${orderAndPage(orderByClause)}
    `;

  const query = (() => {
    if (skipDedup) return plainScanQuery();
    if (props.select === "count") return dedupCountQuery();
    return dedupRowsQuery();
  })();

  const input = {
    params: {
      projectId,
      dataTypes: LISTABLE_SCORE_TYPES,
      ...(scoreOnlyFilterRes ? scoreOnlyFilterRes.params : {}),
      ...innerDatePruneParams,
      ...tracesCTEParams,
      limit,
      offset,
    },
    tags: { ...(props.tags ?? {}), projectId },
  };
  return queryClickhouse<T>({
    query,
    params: input.params,
    tags: input.tags,
    clickhouseConfigs,
    preferredClickhouseService: needsTracesCTE ? "EventsReadOnly" : "ReadOnly",
  });
};

/** Appends s.id in the primary sort direction so LIMIT/OFFSET pages are deterministic on ties */
const withIdTiebreaker = (orderByClause: string, orderBy: OrderByState) =>
  orderByClause && orderBy
    ? `${orderByClause}, s.id ${orderBy.order}`
    : orderByClause;

export const getScoresUiCountFromEvents = async (props: {
  projectId: string;
  filter: FilterState;
  orderBy: OrderByState;
  limit?: number;
  offset?: number;
}) => {
  const rows = await getScoresUiGenericFromEvents<{ count: string }>({
    select: "count",
    excludeMetadata: true,
    ...props,
  });

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

export type ScoreUiTableRowFromEvents = Omit<ScoreDomain, "metadata"> & {
  hasMetadata: boolean;
  evaluatorId: string | null;
};

export async function getScoresUiTableFromEvents(props: {
  projectId: string;
  filter: FilterState;
  orderBy: OrderByState;
  limit?: number;
  offset?: number;
  clickhouseConfigs?: ClickHouseClientConfigOptions;
  // Defaults to true: the scores UI table only needs the hasMetadata flag.
  // Batch exports pass false to include the full metadata payload.
  excludeMetadata?: boolean;
}) {
  const { clickhouseConfigs, excludeMetadata = true, ...rest } = props;

  const rows = await getScoresUiGenericFromEvents<{
    id: string;
    project_id: string;
    environment: string;
    name: string;
    value: number;
    string_value: string | null;
    timestamp: string;
    source: string;
    data_type: string;
    comment: string | null;
    trace_id: string | null;
    session_id: string | null;
    dataset_run_id: string | null;
    metadata?: Record<string, string>;
    observation_id: string | null;
    author_user_id: string | null;
    config_id: string | null;
    queue_id: string | null;
    execution_trace_id: string | null;
    ingestion_api_key: string;
    ingestion_sdk_name: string;
    ingestion_sdk_version: string;
    is_deleted: number;
    event_ts: string;
    created_at: string;
    updated_at: string;
    evaluator_id: string;
    has_metadata: 0 | 1;
  }>({
    select: "rows",
    excludeMetadata,
    includeHasMetadataFlag: true,
    clickhouseConfigs,
    ...rest,
  });

  return rows.map((row) => {
    const score = convertClickhouseScoreToDomain(
      {
        ...row,
        metadata: excludeMetadata ? {} : (row.metadata ?? {}),
        long_string_value: "",
      },
      !excludeMetadata,
    );
    return {
      ...score,
      hasMetadata: !!row.has_metadata,
      evaluatorId: row.evaluator_id || null,
    };
  });
}

export const getScoreNames = async (
  projectId: string,
  timestampFilter: FilterState,
) => {
  const chFilter = new FilterList(
    createFilterFromFilterState(
      timestampFilter,
      scoresTableUiColumnDefinitions,
      scoresTableCols,
    ),
  );
  const timestampFilterRes = chFilter.apply();

  // We mainly use queries like this to retrieve filter options.
  // Therefore, we can skip final as some inaccuracy in count is acceptable.
  const query = `
      select
        name,
        count(*) as count
      from scores s
      WHERE s.project_id = {projectId: String}
      ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
      AND s.data_type IN ({dataTypes: Array(String)})
      GROUP BY name
      ORDER BY count() desc
      LIMIT 1000;
    `;

  const rows = await queryClickhouse<{
    name: string;
    count: string;
  }>({
    query: query,
    params: {
      projectId: projectId,
      ...(timestampFilterRes ? timestampFilterRes.params : {}),
      dataTypes: LISTABLE_SCORE_TYPES,
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

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

export const getScoreStringValues = async (
  projectId: string,
  timestampFilter: FilterState,
) => {
  const chFilter = new FilterList(
    createFilterFromFilterState(
      timestampFilter,
      scoresTableUiColumnDefinitions,
      scoresTableCols,
    ),
  );
  const timestampFilterRes = chFilter.apply();

  // exclude TEXT scores as they are arbitrary by nature and hence have high cardinality
  // which in turn can lead to performance issues
  const query = `
      select
        string_value,
        count(*) as count
      from scores s
      WHERE s.project_id = {projectId: String}
      AND string_value IS NOT NULL
      AND string_value != ''
      AND s.data_type != 'TEXT'
      ${timestampFilterRes?.query ? `AND ${timestampFilterRes.query}` : ""}
      GROUP BY string_value
      ORDER BY count() desc
      LIMIT 1000;
    `;

  const rows = await queryClickhouse<{
    string_value: string;
    count: string;
  }>({
    query: query,
    params: {
      projectId: projectId,
      ...(timestampFilterRes ? timestampFilterRes.params : {}),
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

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

export const deleteScores = async (projectId: string, scoreIds: string[]) => {
  const query = `
    DELETE FROM scores
    WHERE project_id = {projectId: String}
    AND id in ({scoreIds: Array(String)});
  `;
  await commandClickhouse({
    query: query,
    params: {
      projectId,
      scoreIds,
    },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
    },
    tags: { projectId },
  });
};

export const deleteScoresByTraceIds = async (
  projectId: string,
  traceIds: string[],
) => {
  const query = `
    DELETE FROM scores
    WHERE project_id = {projectId: String}
    AND trace_id IN ({traceIds: Array(String)});
  `;
  await commandClickhouse({
    query: query,
    params: {
      projectId,
      traceIds,
    },
    clickhouseConfigs: {
      request_timeout: 120_000, // 2 minutes
    },
    tags: { projectId },
  });
};

export const deleteScoresByProjectId = async (
  projectId: string,
): Promise<boolean> => {
  const hasData = await hasAnyScore(projectId);
  if (!hasData) {
    return false;
  }

  const query = `
    DELETE FROM scores
    WHERE project_id = {projectId: String};
  `;
  const tags = { projectId };

  await commandClickhouse({
    query,
    params: { projectId },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
    },
    tags,
  });

  return true;
};

export const hasAnyScoreOlderThan = async (
  projectId: string,
  beforeDate: Date,
) => {
  const query = `
    SELECT 1
    FROM scores
    WHERE project_id = {projectId: String}
    AND timestamp < {cutoffDate: DateTime64(3)}
    LIMIT 1
  `;

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

  return rows.length > 0;
};

export const deleteScoresOlderThanDays = async (
  projectId: string,
  beforeDate: Date,
): Promise<boolean> => {
  const hasData = await hasAnyScoreOlderThan(projectId, beforeDate);
  if (!hasData) {
    return false;
  }

  const query = `
    DELETE FROM scores
    WHERE project_id = {projectId: String}
    AND timestamp < {cutoffDate: DateTime64(3)};
  `;
  await commandClickhouse({
    query: query,
    params: {
      projectId,
      cutoffDate: convertDateToClickhouseDateTime(beforeDate),
    },
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DELETION_TIMEOUT_MS,
    },
    tags: { projectId },
  });

  return true;
};

export const getNumericScoreHistogram = async (
  projectId: string,
  filter: FilterState,
  limit: number,
) => {
  const chFilter = new FilterList(
    createFilterFromFilterState(filter, dashboardColumnDefinitions),
  );
  const chFilterRes = chFilter.apply();

  const traceFilter = chFilter.find((f) => f.clickhouseTable === "traces");

  const query = `
    select s.value
    from scores s
    ${traceFilter ? `LEFT JOIN traces t ON s.trace_id = t.id AND t.project_id = s.project_id` : ""}
    WHERE s.project_id = {projectId: String}
    ${traceFilter ? `AND t.project_id = {projectId: String}` : ""}
    ${chFilterRes?.query ? `AND ${chFilterRes.query}` : ""}
    ORDER BY s.event_ts DESC
    ${shouldSkipScoresDedup(projectId) && !traceFilter ? "" : "LIMIT 1 BY s.id, s.project_id"}
    ${limit !== undefined ? `limit {limit: Int32}` : ""}
  `;

  const input = {
    params: {
      projectId,
      limit,
      ...(chFilterRes ? chFilterRes.params : {}),
    },
    tags: { projectId },
  };
  return queryClickhouse<{ value: number }>({
    query,
    params: input.params,
    tags: input.tags,
    preferredClickhouseService: "ReadOnly",
  });
};

export const getAggregatedScoresForPrompts = async (
  projectId: string,
  promptIds: string[],
  fetchScoreRelation: "observation" | "trace",
  {
    fromTimestamp,
    toTimestamp,
  }: { fromTimestamp?: Date; toTimestamp?: Date } = {},
) => {
  const query = `
    SELECT
      prompt_id,
      s.id,
      s.name,
      s.string_value,
      s.value,
      s.source,
      s.data_type,
      s.comment,
      s.timestamp,
      length(mapKeys(s.metadata)) > 0 AS has_metadata
    FROM scores s ${shouldSkipScoresDedup(projectId) ? "" : "FINAL"} LEFT JOIN observations o FINAL
      ON o.trace_id = s.trace_id
      AND o.project_id = s.project_id
      ${fetchScoreRelation === "observation" ? "AND o.id = s.observation_id" : ""}
    WHERE o.project_id = {projectId: String}
    AND s.project_id = {projectId: String}
    AND o.prompt_id IN ({promptIds: Array(String)})
    AND o.type = 'GENERATION'
    ${fromTimestamp ? "AND o.start_time >= {fromTimestamp: DateTime64(3)}" : ""}
    ${toTimestamp ? "AND o.start_time <= {toTimestamp: DateTime64(3)}" : ""}
    AND s.name IS NOT NULL
    ${fetchScoreRelation === "trace" ? "AND s.observation_id IS NULL" : ""}
    AND s.data_type IN ({dataTypes: Array(String)})
  `;

  const rows = await queryClickhouse<
    ScoreAggregation & {
      prompt_id: string;
      // has_metadata is 0 or 1 from ClickHouse, later converted to a boolean
      has_metadata: 0 | 1;
    }
  >({
    query,
    params: {
      projectId,
      promptIds,
      dataTypes: LISTABLE_SCORE_TYPES,
      ...(fromTimestamp
        ? { fromTimestamp: convertDateToClickhouseDateTime(fromTimestamp) }
        : {}),
      ...(toTimestamp
        ? { toTimestamp: convertDateToClickhouseDateTime(toTimestamp) }
        : {}),
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

  return rows.map((row) => ({
    ...convertScoreAggregation<ListableScoreDataType>(row),
    promptId: row.prompt_id,
    hasMetadata: !!row.has_metadata,
  }));
};

const aggregatedScoresForPromptsFromEventsQuery = (
  promptIds: string[],
  fetchScoreRelation: "observation" | "trace",
  timeWindow: { fromTimestamp?: Date; toTimestamp?: Date } = {},
  skipDedup = false,
) =>
  getClickhouseKysely()
    .with("prompt_events", () =>
      promptGenerationEvents(
        promptIds,
        [
          "e.project_id as project_id",
          "e.prompt_id as prompt_id",
          "e.trace_id as trace_id",
          "e.span_id as span_id",
        ],
        timeWindow,
      ),
    )
    .selectFrom("scores as s")
    .$if(!skipDedup, useFinal(["scores"]))
    .innerJoin("prompt_events as e", (join) => {
      const base = join
        .onRef("s.project_id", "=", "e.project_id")
        .onRef("s.trace_id", "=", "e.trace_id");
      return fetchScoreRelation === "observation"
        ? base.onRef("s.observation_id", "=", "e.span_id")
        : base;
    })
    .select((eb) => [
      "e.prompt_id as prompt_id",
      "s.id as id",
      "s.name as name",
      "s.string_value as string_value",
      "s.value as value",
      "s.source as source",
      "s.data_type as data_type",
      "s.comment as comment",
      "s.timestamp as timestamp",
      notEmpty(mapKeys(eb.ref("s.metadata"))).as("has_metadata"),
    ])
    .where("s.name", "is not", null)
    .where(
      "s.data_type",
      "in",
      LISTABLE_SCORE_TYPES.map((t) => literal(t)),
    )
    .$if(fetchScoreRelation === "trace", (qb) =>
      qb
        .where("s.observation_id", "is", null)
        .where("s.trace_id", "in", (eb) =>
          eb.selectFrom("prompt_events").select("trace_id"),
        ),
    )
    .$if(fetchScoreRelation === "observation", (qb) =>
      qb
        .where("s.observation_id", "is not", null)
        .where(({ eb, refTuple, selectFrom }) =>
          eb(
            refTuple("s.trace_id", "s.observation_id"),
            "in",
            selectFrom("prompt_events")
              .select(["trace_id", "span_id"])
              .$asTuple("trace_id", "span_id"),
          ),
        ),
    )
    .groupBy([
      "e.prompt_id",
      "s.id",
      "s.name",
      "s.string_value",
      "s.value",
      "s.source",
      "s.data_type",
      "s.comment",
      "s.timestamp",
      "s.metadata",
    ]);

export const buildAggregatedScoresForPromptsFromEventsQuery = (
  projectId: string,
  promptIds: string[],
  fetchScoreRelation: "observation" | "trace",
  timeWindow: { fromTimestamp?: Date; toTimestamp?: Date } = {},
) => {
  const compiled = compileClickhouseQuery(
    aggregatedScoresForPromptsFromEventsQuery(
      promptIds,
      fetchScoreRelation,
      timeWindow,
      shouldSkipScoresDedup(projectId),
    ),
    projectId,
  );
  return { query: compiled.sql, params: compiled.params };
};

export const getAggregatedScoresForPromptsFromEvents = async (
  projectId: string,
  promptIds: string[],
  fetchScoreRelation: "observation" | "trace",
  timeWindow: { fromTimestamp?: Date; toTimestamp?: Date } = {},
) => {
  const { query, params } = buildAggregatedScoresForPromptsFromEventsQuery(
    projectId,
    promptIds,
    fetchScoreRelation,
    timeWindow,
  );

  const rows = await queryClickhouse<
    ScoreAggregation & {
      prompt_id: string;
      has_metadata: 0 | 1;
    }
  >({
    query,
    params,
    tags: {
      projectId,
      route: "scores.getAggregatedScoresForPromptsFromEvents",
    },
    preferredClickhouseService: "EventsReadOnly",
  });

  return rows.map((row) => ({
    ...convertScoreAggregation<ListableScoreDataType>(row),
    promptId: row.prompt_id,
    hasMetadata: !!row.has_metadata,
  }));
};

export const getScoreCountsByProjectInCreationInterval = async ({
  start,
  end,
  projectId,
  projectIds,
}: {
  start: Date;
  end: Date;
  projectId?: string;
  projectIds?: string[];
}) => {
  const query = `
    SELECT
      project_id,
      count(*) as count
    FROM scores
    WHERE created_at >= {start: DateTime64(3)}
    AND created_at < {end: DateTime64(3)}
    ${projectId ? "AND project_id = {projectId: String}" : ""}
    ${projectIds ? "AND project_id IN ({projectIds: Array(String)})" : ""}
    AND data_type IN ({dataTypes: Array(String)})
    GROUP BY project_id
  `;

  const rows = await queryClickhouse<{ project_id: string; count: string }>({
    query,
    params: {
      start: convertDateToClickhouseDateTime(start),
      end: convertDateToClickhouseDateTime(end),
      dataTypes: LISTABLE_SCORE_TYPES,
      ...(projectId ? { projectId } : {}),
      ...(projectIds ? { projectIds } : {}),
    },
    clickhouseConfigs: {
      request_timeout: 300000, // 5 minutes timeout
    },
  });

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

export const getScoreCountOfProjectsSinceCreationDate = async ({
  projectIds,
  start,
}: {
  projectIds: string[];
  start: Date;
}) => {
  const query = `
    SELECT
      count(*) as count
    FROM scores
    WHERE project_id IN ({projectIds: Array(String)})
    AND created_at >= {start: DateTime64(3)}
  `;

  const rows = await queryClickhouse<{ count: string }>({
    query,
    params: {
      projectIds,
      start: convertDateToClickhouseDateTime(start),
    },
  });

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

/**
 * Reuses an already-planned ClickHouse lower bound when available. Callers
 * without one can retain their view-specific timestamp-filter predicate.
 */
type DistinctScoreNamesTimestampSource =
  | {
      filter: FilterState;
      isTimestampFilter: (filter: FilterCondition) => filter is TimeFilter;
      startTimeFrom?: never;
    }
  | {
      startTimeFrom: string | null;
      filter?: never;
      isTimestampFilter?: never;
    };

const getDistinctScoreNamesStartTimeFrom = (
  source: DistinctScoreNamesTimestampSource,
): string | null => {
  if ("startTimeFrom" in source) {
    return source.startTimeFrom ?? null;
  }

  const scoreTimestampFilter = source.filter.find(
    (filterItem): filterItem is TimeFilter =>
      source.isTimestampFilter(filterItem) &&
      (filterItem.operator === ">=" || filterItem.operator === ">"),
  );

  return scoreTimestampFilter
    ? convertDateToClickhouseDateTime(scoreTimestampFilter.value)
    : null;
};

export const getDistinctScoreNames = async (
  p: {
    projectId: string;
    cutoffCreatedAt: Date;
    clickhouseConfigs?: ClickHouseClientConfigOptions | undefined;
    preferredClickhouseService?: PreferredClickhouseService;
  } & DistinctScoreNamesTimestampSource,
) => {
  const {
    projectId,
    cutoffCreatedAt,
    clickhouseConfigs,
    preferredClickhouseService,
  } = p;
  const startTimeFrom = getDistinctScoreNamesStartTimeFrom(p);

  const query = `    SELECT DISTINCT
      name
    FROM scores s
    WHERE s.project_id = {projectId: String}
    AND s.created_at <= {cutoffCreatedAt: DateTime64(3)}
    ${startTimeFrom ? `AND s.timestamp >= {filterTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
    AND s.data_type IN ({dataTypes: Array(String)})
  `;

  const rows = await queryClickhouse<{ name: string }>({
    query,
    params: {
      projectId,
      cutoffCreatedAt: convertDateToClickhouseDateTime(cutoffCreatedAt),
      dataTypes: LISTABLE_SCORE_TYPES,
      ...(startTimeFrom
        ? {
            filterTimestamp: startTimeFrom,
          }
        : {}),
    },
    tags: { projectId },
    clickhouseConfigs,
    preferredClickhouseService,
  });

  return rows.map((row) => row.name);
};

// Shared query for both the standard (parsed) and Parquet (`exec` binary)
// score export paths. Opt-in field group columns are appended after the base
// columns so the base column order stays stable.
const buildScoresForBlobStorageExportQuery = (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  fieldGroups: ScoreExportFieldGroup[],
) => {
  const columns: string[] = [
    ...SCORE_EXPORT_CORE_FIELDS,
    ...SCORE_EXPORT_FIELD_GROUPS.filter((group) =>
      fieldGroups.includes(group),
    ).flatMap((group) => SCORE_EXPORT_GROUP_FIELDS[group]),
  ];
  const query = `
    SELECT
      ${columns.join(",\n      ")}
    FROM scores ${shouldSkipScoresDedup(projectId) ? "" : "FINAL"}
    WHERE project_id = {projectId: String}
    AND timestamp >= {minTimestamp: DateTime64(3)}
    AND timestamp < {maxTimestamp: DateTime64(3)}
    AND data_type IN ({dataTypes: Array(String)})
  `;

  return {
    query,
    params: {
      projectId,
      minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
      maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
      dataTypes: LISTABLE_SCORE_TYPES,
    },
    // 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: "ReadOnly" as const,
  };
};

export const getScoresForBlobStorageExport = function (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  fieldGroups: ScoreExportFieldGroup[] = [],
) {
  return queryClickhouseStream<Record<string, unknown>>(
    buildScoresForBlobStorageExportQuery(
      projectId,
      minTimestamp,
      maxTimestamp,
      fieldGroups,
    ),
  );
};

// LFE-10463: ClickHouse-native `FORMAT Parquet` export of scores. Reuses the
// standard query SQL and streams the raw binary body straight to upload.
export const getScoresForBlobStorageExportParquet = function (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  fieldGroups: ScoreExportFieldGroup[] = [],
) {
  return queryClickhouseExecRaw({
    ...buildScoresForBlobStorageExportQuery(
      projectId,
      minTimestamp,
      maxTimestamp,
      fieldGroups,
    ),
    format: "Parquet",
    clickhouseSettings: BLOB_EXPORT_PARQUET_CLICKHOUSE_SETTINGS,
  });
};

/**
 * Trace-attribute CTE for analytics-integration score exports. Pre-filters
 * traces so the trace timestamp window prunes partitions directly, instead of
 * living in an OR clause after the LEFT JOIN where the planner cannot push it
 * down. Subtracts 7d from minTimestamp to keep scores whose trace was created
 * before the score window started.
 *
 * Schema contract with the consuming query in
 * getScoresForAnalyticsIntegrations: project_id, id, name, session_id,
 * user_id, release, tags, posthog_session_id, mixpanel_session_id.
 */
const buildAnalyticsScoreTraceAttributesCte = (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
): { query: string; params: Record<string, unknown> } => ({
  query: `
      SELECT
        t.project_id as project_id,
        t.id as id,
        t.name as name,
        t.session_id as session_id,
        t.user_id as user_id,
        t.release as release,
        t.tags as tags,
        t.metadata['$posthog_session_id'] as posthog_session_id,
        t.metadata['$mixpanel_session_id'] as mixpanel_session_id
      FROM traces t FINAL
      WHERE t.project_id = {projectId: String}
      AND t.timestamp >= {minTimestamp: DateTime64(3)} - INTERVAL 7 DAY
      AND t.timestamp <= {maxTimestamp: DateTime64(3)}`,
  params: {
    projectId,
    minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
    maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
  },
});

// Same schema rebuilt from events_core for deployments that no longer write
// the legacy traces table (write mode events_only). The 7d start_time
// lookback mirrors the legacy CTE so delayed scores stay enriched.
//
// Hand-written rather than eventsTracesAggregation: aggregating only
// semantic-root rows keeps the GROUP BY state ~one row per trace (the
// full-span aggregation OOMed the largest tenants). The trace name is
// the latest non-empty trace_name, else the latest root-observation name; the
// remaining field expressions keep
// the parity fixes byte-verified against prod dual-write data in the
// LFE-14383 benchmark (tracked in LFE-11009).
const buildAnalyticsScoreTraceAttributesFromEventsCte = (
  projectId: string,
  minTimestamp: Date,
  maxTimestamp: Date,
): { query: string; params: Record<string, unknown> } => ({
  query: `
      SELECT
        e.project_id as project_id,
        e.trace_id as id,
        coalesce(${eventsTableTraceNameAggregationSql}, '') as name,
        nullIf(argMaxIf(e.session_id, e.event_ts, e.session_id <> ''), '') as session_id,
        nullIf(argMaxIf(e.user_id, e.event_ts, e.user_id <> ''), '') as user_id,
        nullIf(argMax(e.release, e.event_ts), '') as release,
        arraySort(groupUniqArrayArrayIf(e.tags, notEmpty(e.tags))) as tags,
        argMax(e.metadata_values[indexOf(e.metadata_names, '$posthog_session_id')], e.event_ts) as posthog_session_id,
        argMax(e.metadata_values[indexOf(e.metadata_names, '$mixpanel_session_id')], e.event_ts) as mixpanel_session_id
      FROM events_core e
      WHERE e.project_id = {projectId: String}
      AND e.start_time >= {minTimestamp: DateTime64(3)} - INTERVAL 7 DAY
      AND e.start_time <= {maxTimestamp: DateTime64(3)}
      AND e.is_deleted = 0
      AND ${eventsTableIsRootObservationSql}
      GROUP BY e.project_id, e.trace_id`,
  params: {
    projectId,
    minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
    maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
  },
});

export const getScoresForAnalyticsIntegrations = async function* (
  projectId: string,
  projectName: string,
  minTimestamp: Date,
  maxTimestamp: Date,
  options: {
    useGraceHash?: boolean;
    /** Pass "events" when the deployment no longer writes the traces table. */
    traceAttributesSource?: "traces" | "events";
  } = {},
) {
  const traceAttributesSource = options.traceAttributesSource ?? "traces";
  const selectedTraces =
    traceAttributesSource === "events"
      ? buildAnalyticsScoreTraceAttributesFromEventsCte(
          projectId,
          minTimestamp,
          maxTimestamp,
        )
      : buildAnalyticsScoreTraceAttributesCte(
          projectId,
          minTimestamp,
          maxTimestamp,
        );

  const query = `
    WITH selected_traces AS (${selectedTraces.query}
    )

    SELECT
      s.id as id,
      s.timestamp as timestamp,
      s.name as name,
      s.value as value,
      s.string_value as string_value,
      s.data_type as data_type,
      s.comment as comment,
      s.environment as environment,
      s.trace_id as score_trace_id,
      s.session_id as score_session_id,
      s.dataset_run_id as score_dataset_run_id,
      t.id as trace_id,
      t.name as trace_name,
      t.session_id as trace_session_id,
      t.user_id as trace_user_id,
      t.release as trace_release,
      t.tags as trace_tags,
      s.metadata as metadata,
      t.posthog_session_id as posthog_session_id,
      t.mixpanel_session_id as mixpanel_session_id
    FROM scores s ${shouldSkipScoresDedup(projectId) ? "" : "FINAL"}
    LEFT JOIN selected_traces t ON s.trace_id = t.id AND s.project_id = t.project_id
    WHERE s.project_id = {projectId: String}
    AND s.timestamp >= {minTimestamp: DateTime64(3)}
    AND s.timestamp < {maxTimestamp: DateTime64(3)}
    AND s.data_type IN ({dataTypes: Array(String)})
    AND (
      s.trace_id IS NOT NULL
      OR s.session_id IS NOT NULL
      OR s.dataset_run_id IS NOT NULL
    )
  `;

  const records = queryClickhouseStream<Record<string, unknown>>({
    query,
    params: {
      projectId,
      minTimestamp: convertDateToClickhouseDateTime(minTimestamp),
      maxTimestamp: convertDateToClickhouseDateTime(maxTimestamp),
      dataTypes: LISTABLE_SCORE_TYPES,
    },
    // Tagged explicitly: worker baggage isn't active during the deferred stream send.
    tags: { projectId, surface: "worker", route: "analytics_integration" },
    ...(traceAttributesSource === "events"
      ? { preferredClickhouseService: "EventsReadOnly" as const }
      : {}),
    clickhouseConfigs: {
      request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
      ...(options.useGraceHash
        ? {
            clickhouse_settings: {
              join_algorithm: "grace_hash",
              grace_hash_join_initial_buckets: "32",
            },
          }
        : {}),
    },
  });

  const baseUrl = env.NEXTAUTH_URL?.replace("/api/auth", "");
  for await (const record of records) {
    // Determine the effective session_id based on score attachment
    const effectiveSessionId =
      record.score_session_id || record.trace_session_id;

    // Determine the effective trace_id (could be null for session-only or dataset-run-only scores)
    const effectiveTraceId = record.score_trace_id || null;

    yield {
      timestamp: record.timestamp,
      langfuse_score_name: record.name,
      langfuse_score_value: record.value,
      langfuse_score_comment: record.comment,
      langfuse_score_metadata: record.metadata,
      langfuse_score_string_value: record.string_value,
      langfuse_score_data_type: record.data_type,
      langfuse_trace_name: record.trace_name,
      langfuse_trace_id: effectiveTraceId,
      langfuse_user_url: record.trace_user_id
        ? `${baseUrl}/project/${projectId}/users/${encodeURIComponent(record.trace_user_id as string)}`
        : undefined,
      langfuse_id: record.id,
      langfuse_session_id: effectiveSessionId,
      langfuse_project_id: projectId,
      langfuse_project_name: projectName,
      langfuse_user_id: record.trace_user_id || null,
      langfuse_release: record.trace_release,
      langfuse_tags: record.trace_tags,
      langfuse_environment: record.environment,
      langfuse_event_version: "1.0.0",
      langfuse_score_entity_type: record.score_trace_id
        ? "trace"
        : record.score_session_id
          ? "session"
          : record.score_dataset_run_id
            ? "dataset_run"
            : "unknown",
      langfuse_dataset_run_id: record.score_dataset_run_id,
      posthog_session_id: record.posthog_session_id ?? null,
      mixpanel_session_id: record.mixpanel_session_id ?? null,
    } satisfies AnalyticsScoreEvent;
  }
};

export const hasAnyScore = async (
  projectId: string,
  preferredClickhouseService?: PreferredClickhouseService,
) => {
  const query = `    SELECT 1
    FROM scores
    WHERE project_id = {projectId: String}
    LIMIT 1
  `;

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

  return rows.length > 0;
};

export const getScoreMetadataById = async (
  projectId: string,
  id: string,
  source?: ScoreSourceType,
) => {
  const query = `    SELECT
      metadata
    FROM scores s
    WHERE s.project_id = {projectId: String}
    AND s.id = {id: String}
    ${source ? `AND s.source = {source: String}` : ""}
    ORDER BY s.event_ts DESC
    ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
    LIMIT 1
  `;

  const rows = await queryClickhouse<Pick<ScoreRecordReadType, "metadata">>({
    query,
    params: {
      projectId,
      id,
      ...(source !== undefined ? { source } : {}),
    },
    tags: { projectId },
    preferredClickhouseService: "ReadOnly",
  });

  return rows
    .map((row) =>
      parseMetadataCHRecordToDomain(row.metadata as Record<string, string>),
    )
    .shift();
};

/**
 * Get score counts grouped by project and day within a date range.
 *
 * Returns one row per project per day with the count of scores created on that day.
 * Uses half-open interval [startDate, endDate) for filtering based on timestamp.
 *
 * @param startDate - Start of date range (inclusive)
 * @param endDate - End of date range (exclusive)
 * @returns Array of { count, projectId, date } objects
 *
 * @example
 * // Get score counts for March 1-2, 2024
 * const counts = await getScoreCountsByProjectAndDay({
 *   startDate: new Date('2024-03-01T00:00:00Z'),
 *   endDate: new Date('2024-03-03T00:00:00Z')
 * });
 *
 * Note: Skips using FINAL (double counting risk) for faster and cheaper
 * queries against clickhouse. Generous 4x overcompensation before blocking allows
 * for usage aggregation to be meaningful.
 *
 */
export const getScoreCountsByProjectAndDay = async ({
  startDate,
  endDate,
}: {
  startDate: Date;
  endDate: Date;
}) => {
  const query = `
    SELECT
      count(*) as count,
      project_id,
      toDate(timestamp) as date
    FROM scores
    WHERE timestamp >= {startDate: DateTime64(3)}
    AND timestamp < {endDate: DateTime64(3)}
    AND data_type IN ({dataTypes: Array(String)})
    GROUP BY project_id, toDate(timestamp)
  `;

  const rows = await queryClickhouse<{
    count: string;
    project_id: string;
    date: string;
  }>({
    query,
    params: {
      startDate: convertDateToClickhouseDateTime(startDate),
      endDate: convertDateToClickhouseDateTime(endDate),
      dataTypes: LISTABLE_SCORE_TYPES,
    },
    clickhouseConfigs: { request_timeout: 120_000 },
  });

  return rows.map((row) => ({
    count: Number(row.count),
    projectId: row.project_id,
    date: row.date,
  }));
};

// ─── Cursor helpers (v3 pagination) ───────────────────────────────────────────

export const ScoresCursorV3 = z.discriminatedUnion("v", [
  z.object({
    v: z.literal(1),
    lastTimestamp: z.coerce.date(),
    lastId: z.string(),
  }),
]);
export type ScoresCursorV3Type = z.infer<typeof ScoresCursorV3>;

export const EncodedScoresCursorV3 = z
  .string()
  .transform((val) => {
    try {
      const decoded = Buffer.from(val, "base64url").toString("utf-8");
      return JSON.parse(decoded);
    } catch (_e) {
      throw new InvalidRequestError("Invalid cursor format");
    }
  })
  .pipe(ScoresCursorV3);

export const encodeCursorV3 = (cursor: ScoresCursorV3Type): string =>
  Buffer.from(
    JSON.stringify({
      v: cursor.v,
      lastTimestamp: cursor.lastTimestamp.toISOString(),
      lastId: cursor.lastId,
    }),
  ).toString("base64url");

// ─── v1/v2 public-API score query helpers ─────────────────────────────────────

export type ScoreQueryType = {
  page: number;
  limit: number;
  projectId: string;
  traceId?: string;
  userId?: string;
  name?: string;
  source?: string;
  fromTimestamp?: string;
  toTimestamp?: string;
  value?: number;
  scoreId?: string;
  configId?: string;
  sessionId?: string;
  datasetRunId?: string;
  queueId?: string;
  traceTags?: string | string[];
  operator?: string;
  scoreIds?: string[];
  observationId?: string[];
  dataType?: string;
  environment?: string | string[];
  fields?: string[] | null;
  advancedFilters?: FilterState;
};

export const _handleGenerateScoresForPublicApi = async ({
  projectId,
  scoresFilter,
  tracesFilter,
  scoreScope,
  includeTrace,
  needsTraceJoin,
  pagination,
  apiVersion,
}: {
  projectId: string;
  scoresFilter: FilterList;
  tracesFilter: FilterList;
  scoreScope: "traces_only" | "all";
  includeTrace: boolean;
  needsTraceJoin: boolean;
  pagination?: { limit: number; page: number };
  apiVersion?: "v1" | "v2";
}) => {
  const appliedScoresFilter = scoresFilter.apply();
  const appliedTracesFilter = tracesFilter.apply();

  const query = `
      SELECT
          ${needsTraceJoin ? "t.user_id as user_id, t.tags as tags, t.environment as trace_environment, t.session_id as trace_session_id," : ""}
          s.id as id,
          s.project_id as project_id,
          s.timestamp as timestamp,
          s.environment as environment,
          s.name as name,
          s.value as value,
          s.string_value as string_value,
          s.long_string_value as long_string_value,
          s.author_user_id as author_user_id,
          s.created_at as created_at,
          s.updated_at as updated_at,
          s.source as source,
          s.comment as comment,
          s.metadata as metadata,
          s.data_type as data_type,
          s.config_id as config_id,
          s.queue_id as queue_id,
          s.execution_trace_id as execution_trace_id,
          s.trace_id as trace_id,
          s.observation_id as observation_id,
          s.session_id as session_id,
          s.dataset_run_id as dataset_run_id
      FROM
          scores s
          ${needsTraceJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}
      WHERE
          s.project_id = {projectId: String}
          AND (
            ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}
            (s.trace_id IS NOT NULL AND (${needsTraceJoin ? "t.id, t.project_id" : "s.trace_id, s.project_id"}) IN (
              SELECT
                ${needsTraceJoin ? "trace_id, project_id" : "s.trace_id, s.project_id"}
              FROM
                scores s
              WHERE
                s.project_id = {projectId: String}
                ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
                ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
              ORDER BY
                s.timestamp desc
              ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
                ))
          )
          ${scoreScope === "traces_only" ? "AND s.session_id IS NULL AND s.dataset_run_id IS NULL" : ""}
          ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
          ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}
      ${
        // The traces join is not deduplicated, so LIMIT 1 BY also collapses
        // one score row per unmerged trace version. Without it the scan reads
        // the table directly; the day first keeps the order but lets ClickHouse
        // read the newest days first and stop after the page.
        shouldSkipScoresDedup(projectId) && !needsTraceJoin
          ? "ORDER BY toDate(s.timestamp) desc, s.timestamp desc, s.event_ts desc"
          : "ORDER BY s.timestamp desc, s.event_ts desc\n      LIMIT 1 BY s.id, s.project_id"
      }
      ${pagination !== undefined ? `LIMIT {limit: Int32} OFFSET {offset: Int32}` : ""}
      `;

  const input = {
    params: {
      ...appliedScoresFilter.params,
      ...appliedTracesFilter.params,
      projectId,
      ...(pagination !== undefined
        ? {
            limit: pagination.limit,
            offset: (pagination.page - 1) * pagination.limit,
          }
        : {}),
    },
    tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },
  };
  const records = await queryClickhouse<
    ScoreRecordReadType & {
      tags?: string[];
      user_id?: string;
      trace_environment?: string;
      trace_session_id?: string | null;
    }
  >({
    query: query.replace("__TRACE_TABLE__", "traces"),
    params: input.params,
    tags: input.tags,
    preferredClickhouseService: "ReadOnly",
  });

  return records.map((record) => {
    const domainScore = convertClickhouseScoreToDomain(record);
    return {
      ...domainScore,
      trace:
        includeTrace && record.trace_id !== null
          ? {
              userId: record.user_id,
              tags: record.tags,
              environment: record.trace_environment,
              sessionId: record.trace_session_id,
            }
          : null,
    };
  });
};

export const _handleGetScoresCountForPublicApi = async ({
  projectId,
  scoresFilter,
  tracesFilter,
  scoreScope,
  needsTraceJoin,
  apiVersion,
}: {
  projectId: string;
  scoresFilter: FilterList;
  tracesFilter: FilterList;
  scoreScope: "traces_only" | "all";
  includeTrace: boolean;
  needsTraceJoin: boolean;
  apiVersion?: "v1" | "v2";
}) => {
  const appliedScoresFilter = scoresFilter.apply();
  const appliedTracesFilter = tracesFilter.apply();

  const query = `
      SELECT
        count() as count
      FROM
        scores s
          ${needsTraceJoin ? "LEFT JOIN __TRACE_TABLE__ t ON s.trace_id = t.id AND s.project_id = t.project_id" : ""}
      WHERE
        s.project_id = {projectId: String}
      AND (
        ${scoreScope === "traces_only" ? "" : "s.trace_id IS NULL OR "}
        (s.trace_id IS NOT NULL AND (${needsTraceJoin ? "t.id, t.project_id" : "s.trace_id, s.project_id"}) IN (
          SELECT
            ${needsTraceJoin ? "trace_id, project_id" : "s.trace_id, s.project_id"}
          FROM
            scores s
          WHERE
            s.project_id = {projectId: String}
            ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
            ${scoreScope === "traces_only" ? "AND s.session_id IS NULL" : ""}
          ORDER BY
            s.timestamp desc
          ${shouldSkipScoresDedup(projectId) ? "" : "LIMIT 1 BY s.id, s.project_id"}
        ))
      )
      ${appliedScoresFilter.query ? `AND ${appliedScoresFilter.query}` : ""}
      ${tracesFilter.length() > 0 ? `AND ${appliedTracesFilter.query}` : ""}
      `;

  const input = {
    params: {
      ...appliedScoresFilter.params,
      ...appliedTracesFilter.params,
      projectId,
    },
    tags: { projectId, ...(apiVersion ? { api_version: apiVersion } : {}) },
  };
  const records = await queryClickhouse<{ count: string }>({
    query: query.replace("__TRACE_TABLE__", "traces"),
    params: input.params,
    tags: input.tags,
    preferredClickhouseService: "ReadOnly",
  });
  return records.map((record) => Number(record.count)).shift();
};

// ─── v3 public-API score query helpers ────────────────────────────────────────

type ListFilterParams = {
  id?: string[];
  name?: string[];
  source?: string[];
  dataType?: string[];
  environment?: string[];
  configId?: string[];
  queueId?: string[];
  authorUserId?: string[];
  value?: string[];
  valueMin?: number;
  valueMax?: number;
  traceId?: string[];
  sessionId?: string[];
  observationId?: string[];
  experimentId?: string[];
  fromTimestamp?: Date;
  toTimestamp?: Date;
};

const CORE_COLUMNS_V3 = [
  "s.id as id",
  "s.project_id as project_id",
  "s.timestamp as timestamp",
  "s.environment as environment",
  "s.name as name",
  "s.value as value",
  "s.string_value as string_value",
  "s.long_string_value as long_string_value",
  "s.source as source",
  "s.data_type as data_type",
  "s.created_at as created_at",
  "s.updated_at as updated_at",
  "s.execution_trace_id as execution_trace_id",
];
const DETAILS_COLUMNS_V3 = [
  "s.comment as comment",
  "s.metadata as metadata",
  "s.config_id as config_id",
];
const SUBJECT_COLUMNS_V3 = [
  "s.trace_id as trace_id",
  "s.observation_id as observation_id",
  "s.session_id as session_id",
  "s.dataset_run_id as dataset_run_id",
];
const ANNOTATION_COLUMNS_V3 = [
  "s.author_user_id as author_user_id",
  "s.queue_id as queue_id",
];

export const buildSelectColumns = (fields: ScoreFieldGroupV3[]): string => {
  const selected = [...CORE_COLUMNS_V3];
  if (fields.includes("details")) selected.push(...DETAILS_COLUMNS_V3);
  if (fields.includes("subject")) selected.push(...SUBJECT_COLUMNS_V3);
  if (fields.includes("annotation")) selected.push(...ANNOTATION_COLUMNS_V3);
  return selected.join(",\n    ");
};

export function transformBooleanValueForFilter(v: "true" | "false"): number {
  if (v === "true") return 1;
  if (v === "false") return 0;
  throw new InternalServerError(
    `transformBooleanValueForFilter received unexpected value: ${v}`,
  );
}

function buildDynamicFilters(params: ListFilterParams): {
  query: string;
  params: Record<string, unknown>;
} {
  const filterList = new FilterList();

  type StringOptionFilterKey = Extract<
    keyof ListFilterParams,
    | "id"
    | "name"
    | "source"
    | "dataType"
    | "environment"
    | "configId"
    | "queueId"
    | "authorUserId"
    | "traceId"
    | "sessionId"
    | "observationId"
    | "experimentId"
  >;

  const STRING_OPTIONS_FILTERS: ReadonlyArray<{
    key: StringOptionFilterKey;
    field: string;
  }> = [
    { key: "id", field: "id" },
    { key: "name", field: "name" },
    { key: "source", field: "source" },
    { key: "dataType", field: "data_type" },
    { key: "environment", field: "environment" },
    { key: "configId", field: "config_id" },
    { key: "queueId", field: "queue_id" },
    { key: "authorUserId", field: "author_user_id" },
    { key: "traceId", field: "trace_id" },
    { key: "sessionId", field: "session_id" },
    { key: "observationId", field: "observation_id" },
    { key: "experimentId", field: "dataset_run_id" },
  ];

  for (const { key, field } of STRING_OPTIONS_FILTERS) {
    const values = params[key];
    if (values?.length) {
      filterList.push(
        new StringOptionsFilter({
          clickhouseTable: "scores",
          field,
          operator: "any of",
          values,
          tablePrefix: "s",
        }),
      );
    }
  }
  if (params.fromTimestamp !== undefined)
    filterList.push(
      new DateTimeFilter({
        clickhouseTable: "scores",
        field: "timestamp",
        operator: ">=",
        value: params.fromTimestamp,
        tablePrefix: "s",
      }),
    );
  if (params.toTimestamp !== undefined)
    filterList.push(
      new DateTimeFilter({
        clickhouseTable: "scores",
        field: "timestamp",
        operator: "<",
        value: params.toTimestamp,
        tablePrefix: "s",
      }),
    );
  if (params.valueMin !== undefined)
    filterList.push(
      new NumberFilter({
        clickhouseTable: "scores",
        field: "value",
        operator: ">=",
        value: params.valueMin,
        tablePrefix: "s",
        clickhouseTypeOverwrite: "Float64",
      }),
    );
  if (params.valueMax !== undefined)
    filterList.push(
      new NumberFilter({
        clickhouseTable: "scores",
        field: "value",
        operator: "<=",
        value: params.valueMax,
        tablePrefix: "s",
        clickhouseTypeOverwrite: "Float64",
      }),
    );

  const compiled = filterList.apply();

  const extraClauses: string[] = [];
  const extraParams: Record<string, unknown> = {};

  if (params.value?.length && params.dataType?.length === 1) {
    const dt = params.dataType[0] as ScoreDataTypeType;
    const uid = clickhouseCompliantRandomCharacters();
    const varName = `valueFilter${uid}`;

    switch (dt) {
      case ScoreDataTypeEnum.NUMERIC: {
        extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);
        extraParams[varName] = params.value.map((v) => {
          const n = Number(v);
          if (!Number.isFinite(n)) {
            throw new InternalServerError(
              `NUMERIC value filter received non-finite value: ${v}`,
            );
          }
          return n;
        });
        break;
      }
      case ScoreDataTypeEnum.BOOLEAN: {
        extraClauses.push(`s.value IN ({${varName}: Array(Float64)})`);
        extraParams[varName] = params.value.map((v) =>
          transformBooleanValueForFilter(v as "true" | "false"),
        );
        break;
      }
      case ScoreDataTypeEnum.CATEGORICAL: {
        extraClauses.push(`s.string_value IN ({${varName}: Array(String)})`);
        extraParams[varName] = params.value;
        break;
      }
      case ScoreDataTypeEnum.TEXT:
      case ScoreDataTypeEnum.CORRECTION:
        throw new InternalServerError(
          `value filter with dataType=${dt} should have been rejected by handler validation`,
        );
      default: {
        const _exhaustiveCheck: never = dt;
        throw new InternalServerError(
          `value filter received unknown dataType: ${_exhaustiveCheck as string}`,
        );
      }
    }
  }

  const allClauses = [compiled.query, ...extraClauses]
    .filter(Boolean)
    .join(" AND ");

  return { query: allClauses, params: { ...compiled.params, ...extraParams } };
}

const buildV3ListQuery = (
  withCursor: boolean,
  fields: ScoreFieldGroupV3[],
  filterClause: string,
  skipDedup: boolean,
) => `
  SELECT
    ${buildSelectColumns(fields)}
  FROM scores s
  WHERE s.project_id = {projectId: String}
  ${
    // The simple timestamp bound is redundant with the tuple comparison but
    // required for index pruning: ClickHouse does not decompose tuple
    // comparisons, so only the simple bound activates the partition key and
    // the (project_id, toDate(timestamp)) primary-key prefix.
    withCursor
      ? "AND (s.timestamp, s.id) < ({lastTimestamp: DateTime64(3)}, {lastId: String}) AND s.timestamp <= {lastTimestamp: DateTime64(3)}"
      : ""
  }
  ${filterClause ? `AND ${filterClause}` : ""}
  ${
    // Without dedup the scan reads the table directly; the day first keeps the
    // order but lets ClickHouse read the newest days first and stop after the page.
    skipDedup
      ? "ORDER BY toDate(s.timestamp) DESC, s.timestamp DESC, s.id DESC, s.event_ts DESC"
      : "ORDER BY s.timestamp DESC, s.id DESC, s.event_ts DESC\n  LIMIT 1 BY s.id, s.project_id"
  }
  LIMIT {limit: Int32}
`;

export function polymorphicValueForV3(score: {
  dataType: ScoreDataTypeType;
  value: number;
  stringValue?: string | null;
  longStringValue?: string | null;
}): number | boolean | string {
  switch (score.dataType) {
    case ScoreDataTypeEnum.NUMERIC:
      return score.value;
    case ScoreDataTypeEnum.BOOLEAN:
      return score.value === 1;
    case ScoreDataTypeEnum.CATEGORICAL:
    case ScoreDataTypeEnum.TEXT:
      if (score.stringValue == null) {
        throw new InternalServerError(
          `Score with dataType ${score.dataType} is missing its stringValue`,
        );
      }
      return score.stringValue;
    case ScoreDataTypeEnum.CORRECTION:
      if (score.longStringValue == null) {
        throw new InternalServerError(
          "Score with dataType CORRECTION is missing its longStringValue",
        );
      }
      return score.longStringValue;
    default: {
      const _exhaustiveCheck: never = score.dataType;
      throw new InternalServerError(
        `Score has unknown dataType: ${_exhaustiveCheck as string}`,
      );
    }
  }
}

function deriveSubjectForV3(
  score: ScoreDomain,
):
  | { kind: "observation"; id: string; traceId?: string }
  | { kind: "trace" | "session" | "experiment"; id: string } {
  if (score.datasetRunId) {
    return { kind: "experiment", id: score.datasetRunId };
  }
  if (score.observationId) {
    return {
      kind: "observation",
      id: score.observationId,
      ...(score.traceId ? { traceId: score.traceId } : {}),
    };
  }
  if (score.sessionId) {
    return { kind: "session", id: score.sessionId };
  }
  if (!score.traceId) {
    throw new InternalServerError(
      `Score ${score.id} has kind=trace but missing traceId`,
    );
  }
  return { kind: "trace", id: score.traceId };
}

export function scoreDomainToV3(
  score: ScoreDomain,
  fields: ScoreFieldGroupV3[],
): APIScoreV3 {
  return {
    id: score.id,
    projectId: score.projectId,
    name: score.name,
    dataType: score.dataType,
    value: polymorphicValueForV3({
      dataType: score.dataType,
      value: score.value,
      stringValue: score.stringValue as string | null | undefined,
      longStringValue: score.longStringValue as string | null | undefined,
    }),
    source: score.source,
    timestamp: score.timestamp,
    environment: score.environment,
    createdAt: score.createdAt,
    updatedAt: score.updatedAt,
    ...(fields.includes("details")
      ? {
          comment: score.comment,
          configId: score.configId,
          metadata: score.metadata,
        }
      : {}),
    ...(fields.includes("annotation")
      ? {
          authorUserId: score.authorUserId,
          queueId: score.queueId,
        }
      : {}),
    ...(fields.includes("subject")
      ? { subject: deriveSubjectForV3(score) }
      : {}),
  } as APIScoreV3;
}

export async function listScoresV3ForPublicApi(
  params: {
    projectId: string;
    limit: number;
    cursor?: ScoresCursorV3Type;
    fields: ScoreFieldGroupV3[];
  } & ListFilterParams,
  options?: Pick<ClickhouseQueryOpts, "clickhouseSettings">,
): Promise<{ data: APIScoreV3[]; cursor?: string }> {
  const { query: filterClause, params: filterParams } =
    buildDynamicFilters(params);

  const input = {
    params: {
      projectId: params.projectId,
      limit: params.limit + 1,
      ...(params.cursor && {
        lastTimestamp: convertDateToClickhouseDateTime(
          params.cursor.lastTimestamp,
        ),
        lastId: params.cursor.lastId,
      }),
      ...filterParams,
    },
    tags: { projectId: params.projectId },
  };
  const records = await queryClickhouse<ScoreRecordReadType>({
    query: buildV3ListQuery(
      Boolean(params.cursor),
      params.fields,
      filterClause,
      shouldSkipScoresDedup(params.projectId),
    ),
    params: input.params,
    tags: input.tags,
    clickhouseSettings: options?.clickhouseSettings,
    preferredClickhouseService: "ReadOnly",
  });

  const hasMore = records.length > params.limit;
  const pageRecords = hasMore ? records.slice(0, params.limit) : records;

  let nextCursor: string | undefined;
  if (hasMore && pageRecords.length > 0) {
    const last = pageRecords[pageRecords.length - 1];
    nextCursor = encodeCursorV3({
      v: 1,
      lastTimestamp: parseClickhouseUTCDateTimeFormat(String(last.timestamp)),
      lastId: last.id,
    });
  }

  const items: APIScoreV3[] = [];
  for (const row of pageRecords) {
    try {
      items.push(
        scoreDomainToV3(convertClickhouseScoreToDomain(row), params.fields),
      );
    } catch (error) {
      logger.error("v3 score row dropped from response: conversion error", {
        error,
        scoreId: row.id,
        projectId: params.projectId,
      });
    }
  }
  return {
    data: filterAndValidateV3GetScoreList(items, (error) => {
      logger.error(
        "v3 score row dropped from response: schema validation error",
        {
          issues: error.issues,
          projectId: params.projectId,
        },
      );
    }),
    cursor: nextCursor,
  };
}