Skip to content

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

chore: handle clickhouse errors gracefully and correct formatting for getTraceById timestamp (#4210)

Steffen Schmitz7ea0a368afe2
diff --git a/packages/shared/src/server/clickhouse/client.ts b/packages/shared/src/server/clickhouse/client.ts
index 2342e20cca..20df54c8d4 100644
--- a/packages/shared/src/server/clickhouse/client.ts
+++ b/packages/shared/src/server/clickhouse/client.ts
@@ -19,6 +19,6 @@ export const clickhouseClient = createClient({
*/
export const convertDateToClickhouseDateTime = (date: Date): string => {
- // 2024-11-06T20:37:00.000Z -> 2024-11-06 21:37:00
- return date.toISOString().slice(0, 19).replace("T", " ");
+ // 2024-11-06T20:37:00.123Z -> 2024-11-06 21:37:00.123
+ return date.toISOString().replace("T", " ").replace("Z", "");
};
diff --git a/packages/shared/src/server/repositories/dashboards.ts b/packages/shared/src/server/repositories/dashboards.ts
index 08358ed2e1..766847c13e 100644
--- a/packages/shared/src/server/repositories/dashboards.ts
+++ b/packages/shared/src/server/repositories/dashboards.ts
@@ -112,7 +112,7 @@ export const getScoreAggregate = async (
${hasTraceFilter ? "JOIN traces t FINAL ON t.id = s.trace_id AND t.project_id = s.project_id" : ""}
WHERE s.project_id = {projectId: String}
AND ${chFilterApplied.query}
- ${timeFilter && hasTraceFilter ? `AND t.timestamp >= {tracesTimestamp: DateTime} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
+ ${timeFilter && hasTraceFilter ? `AND t.timestamp >= {tracesTimestamp: DateTime64(3)} - ${SCORE_TO_TRACE_OBSERVATIONS_INTERVAL}` : ""}
GROUP BY s.name, s.source, s.data_type
ORDER BY count(*) DESC
`;
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index 7e24862762..ff39324077 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -372,7 +372,7 @@ const getObservationsTableInternal = async <T>(
LEFT JOIN scores_avg AS s_avg ON s_avg.trace_id = o.trace_id and s_avg.observation_id = o.id
WHERE ${appliedObservationsFilter.query}
AND o.type = 'GENERATION'
- ${timeFilter ? `AND t.timestamp > {tracesTimestampFilter: DateTime} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}
+ ${timeFilter ? `AND t.timestamp > {tracesTimestampFilter: DateTime64(3)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}` : ""}
${search.query}
${orderByToClickhouseSql(orderBy ?? null, observationsTableUiColumnDefinitions)}
${limit !== undefined && offset !== undefined ? `LIMIT ${limit} OFFSET ${offset}` : ""};`;
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index c14d64d04b..831e93cbdd 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -301,7 +301,7 @@ export const getTracesByIds = async (
FROM traces
WHERE id IN ({traceIds: Array(String)})
AND project_id = {projectId: String}
- ${timestamp ? `AND timestamp >= {timestamp: DateTime}` : ""}
+ ${timestamp ? `AND timestamp >= {timestamp: DateTime64(3)}` : ""}
ORDER BY event_ts DESC LIMIT 1 by id, project_id;`;
const records = await queryClickhouse<TraceRecordReadType>({
query,
@@ -320,19 +320,23 @@ export const getTraceByIdOrThrow = async (
projectId: string,
timestamp?: Date,
) => {
- const query = `SELECT *
- FROM traces
- WHERE id = {traceId: String}
- AND project_id = {projectId: String}
- ${timestamp ? `AND timestamp = {timestamp: DateTime64(3)}` : ""}
- ORDER BY event_ts DESC LIMIT 1 by id, project_id`;
+ const query = `
+ SELECT *
+ FROM traces
+ WHERE id = {traceId: String}
+ AND project_id = {projectId: String}
+ ${timestamp ? `AND timestamp = {timestamp: DateTime64(3)}` : ""}
+ ORDER BY event_ts DESC LIMIT 1 by id, project_id
+ `;
const records = await queryClickhouse<TraceRecordReadType>({
query,
params: {
traceId,
projectId,
- timestamp: timestamp ? timestamp.getTime() : null,
+ ...(timestamp
+ ? { timestamp: convertDateToClickhouseDateTime(timestamp) }
+ : {}),
},
});
@@ -622,7 +626,7 @@ const getSessionsTableGeneric = async <T>(props: FetchTracesTableProps) => {
anyLast(project_id) as project_id
FROM observations o FINAL
WHERE o.project_id = {projectId: String}
- ${traceTimestampFilter ? `AND o.start_time >= {observationsStartTime: DateTime} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
+ ${traceTimestampFilter ? `AND o.start_time >= {observationsStartTime: DateTime64(3)} - ${TRACE_TO_OBSERVATIONS_INTERVAL}` : ""}
GROUP BY o.trace_id
),
session_data AS (
diff --git a/web/src/server/utils/checkClickhouseAccess.ts b/web/src/server/utils/checkClickhouseAccess.ts
index 851e3d290b..6cc0ce597e 100644
--- a/web/src/server/utils/checkClickhouseAccess.ts
+++ b/web/src/server/utils/checkClickhouseAccess.ts
@@ -56,25 +56,33 @@ export const measureAndReturnApi = async <T, Y>(args: {
}
logger.debug("Read from postgres and clickhouse");
- const [[pgResult, pgDuration], [chResult, chDuration]] =
- await Promise.all([
- executionWrapper(input, pgExecution, currentSpan, "pg"),
- executionWrapper(input, clickhouseExecution, currentSpan, "ch"),
- ]);
+ try {
+ const [[pgResult, pgDuration], [chResult, chDuration]] =
+ await Promise.all([
+ executionWrapper(input, pgExecution, currentSpan, "pg"),
+ executionWrapper(input, clickhouseExecution, currentSpan, "ch"),
+ ]);
+ // Positive duration difference means clickhouse is faster
+ const durationDifference = pgDuration - chDuration;
+ currentSpan?.setAttribute(
+ "execution-time-difference",
+ durationDifference,
+ );
+ currentSpan?.setAttribute("pg-duration", pgDuration);
+ currentSpan?.setAttribute("ch-duration", chDuration);
- const durationDifference = Math.abs(pgDuration - chDuration);
- currentSpan?.setAttribute(
- "execution-time-difference",
- durationDifference,
- );
- currentSpan?.setAttribute("pg-duration", pgDuration);
- currentSpan?.setAttribute("ch-duration", chDuration);
-
- if (env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true") {
- logger.debug("Return data from clickhouse");
- return chResult;
+ return env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"
+ ? chResult
+ : pgResult;
+ } catch (e) {
+ logger.error(
+ "Error in clickhouse experiment wrapper. Retrying leading store.",
+ e,
+ );
+ return env.LANGFUSE_RETURN_FROM_CLICKHOUSE === "true"
+ ? clickhouseExecution(input)
+ : pgExecution(input);
}
- return pgResult;
},
);
};
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 1c1f28658f..2b980bc001 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -145,7 +145,7 @@ export class IngestionService {
table: TableName.Scores,
additionalFilters: {
whereCondition: timestamp
- ? " AND timestamp >= {timestamp: DateTime} "
+ ? " AND timestamp >= {timestamp: DateTime64(3)} "
: "",
params: { timestamp },
},
@@ -227,7 +227,7 @@ export class IngestionService {
table: TableName.Traces,
additionalFilters: {
whereCondition: timestamp
- ? " AND timestamp >= {timestamp: DateTime} "
+ ? " AND timestamp >= {timestamp: DateTime64(3)} "
: "",
params: { timestamp },
},
@@ -276,7 +276,7 @@ export class IngestionService {
entityId,
table: TableName.Observations,
additionalFilters: {
- whereCondition: `AND type = {type: String} ${startTime ? "AND start_time >= {startTime: DateTime} " : ""}`,
+ whereCondition: `AND type = {type: String} ${startTime ? "AND start_time >= {startTime: DateTime64(3)} " : ""}`,
params: {
type,
startTime,
diff --git a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
index c5269162b2..6efdefe89a 100644
--- a/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
+++ b/worker/src/services/IngestionService/tests/IngestionService.unit.test.ts
@@ -19,10 +19,10 @@ describe("IngestionService unit tests", () => {
});
it("correctly convert Date to Clickhouse DateTime", async () => {
- const date = new Date("2024-10-12T12:13:14.000Z");
+ const date = new Date("2024-10-12T12:13:14.123Z");
const clickhouseDateTime = convertDateToClickhouseDateTime(date);
- expect(clickhouseDateTime).toEqual("2024-10-12 12:13:14");
+ expect(clickhouseDateTime).toEqual("2024-10-12 12:13:14.123");
});
});