Skip to content

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

perf(clickhouse): pre-filter traces in CTE for analytics integration joins (#13364)

Steffen Schmitzfbef5ab2f0e1
diff --git a/packages/shared/src/server/repositories/observations.ts b/packages/shared/src/server/repositories/observations.ts
index d16c163901..9771a7cd66 100644
--- a/packages/shared/src/server/repositories/observations.ts
+++ b/packages/shared/src/server/repositories/observations.ts
@@ -1875,10 +1875,31 @@ export const getGenerationsForAnalyticsIntegrations = async function* (
projectName: string,
minTimestamp: Date,
maxTimestamp: Date,
+ options: { useGraceHash?: boolean } = {},
) {
- const traceTable = "traces";
-
+ // Pre-filter traces in a CTE so the trace timestamp window prunes partitions
+ // directly, instead of living alongside the LEFT JOIN where the planner
+ // cannot push it down. LEFT JOIN keeps generations whose trace is missing or
+ // outside the 7-day window — they still ship to PostHog with NULL trace
+ // fields rather than being silently dropped.
const query = `
+ WITH selected_traces AS (
+ 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)} - ${OBSERVATIONS_TO_TRACE_INTERVAL}
+ AND t.timestamp <= {maxTimestamp: DateTime64(3)} + ${TRACE_TO_OBSERVATIONS_INTERVAL}
+ )
+
SELECT
o.name as name,
o.start_time as start_time,
@@ -1900,16 +1921,13 @@ export const getGenerationsForAnalyticsIntegrations = async function* (
t.user_id as trace_user_id,
t.release as trace_release,
t.tags as trace_tags,
- t.metadata['$posthog_session_id'] as posthog_session_id,
- t.metadata['$mixpanel_session_id'] as mixpanel_session_id
+ t.posthog_session_id as posthog_session_id,
+ t.mixpanel_session_id as mixpanel_session_id
FROM observations o FINAL
- LEFT JOIN ${traceTable} t FINAL ON o.trace_id = t.id AND o.project_id = t.project_id
+ LEFT JOIN selected_traces t ON o.trace_id = t.id AND o.project_id = t.project_id
WHERE o.project_id = {projectId: String}
- AND t.project_id = {projectId: String}
AND o.start_time >= {minTimestamp: DateTime64(3)}
AND o.start_time < {maxTimestamp: DateTime64(3)}
- AND t.timestamp >= {minTimestamp: DateTime64(3)} - INTERVAL 7 DAY
- AND t.timestamp <= {maxTimestamp: DateTime64(3)}
AND o.type = 'GENERATION'
`;
@@ -1928,10 +1946,14 @@ export const getGenerationsForAnalyticsIntegrations = async function* (
},
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
- clickhouse_settings: {
- join_algorithm: "grace_hash",
- grace_hash_join_initial_buckets: "32",
- },
+ ...(options.useGraceHash
+ ? {
+ clickhouse_settings: {
+ join_algorithm: "grace_hash",
+ grace_hash_join_initial_buckets: "32",
+ },
+ }
+ : {}),
},
});
diff --git a/packages/shared/src/server/repositories/scores.ts b/packages/shared/src/server/repositories/scores.ts
index e9815af4ff..0dd91631dd 100644
--- a/packages/shared/src/server/repositories/scores.ts
+++ b/packages/shared/src/server/repositories/scores.ts
@@ -2065,11 +2065,31 @@ export const getScoresForAnalyticsIntegrations = async function* (
projectName: string,
minTimestamp: Date,
maxTimestamp: Date,
+ options: { useGraceHash?: boolean } = {},
) {
- // Subtract 7d from minTimestamp to account for shift in query
- const traceTable = "traces";
+ // Pre-filter traces in a CTE 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. Subtract 7d from minTimestamp to keep scores
+ // whose trace was created before the score window started.
+ const query = `
+ WITH selected_traces AS (
+ 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)}
+ )
- const query = ` SELECT
+ SELECT
s.id as id,
s.timestamp as timestamp,
s.name as name,
@@ -2088,10 +2108,10 @@ export const getScoresForAnalyticsIntegrations = async function* (
t.release as trace_release,
t.tags as trace_tags,
s.metadata as metadata,
- t.metadata['$posthog_session_id'] as posthog_session_id,
- t.metadata['$mixpanel_session_id'] as mixpanel_session_id
+ t.posthog_session_id as posthog_session_id,
+ t.mixpanel_session_id as mixpanel_session_id
FROM scores s FINAL
- LEFT JOIN ${traceTable} t FINAL ON s.trace_id = t.id AND s.project_id = t.project_id
+ 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)}
@@ -2101,14 +2121,6 @@ export const getScoresForAnalyticsIntegrations = async function* (
OR s.session_id IS NOT NULL
OR s.dataset_run_id IS NOT NULL
)
- AND (
- t.project_id = '' -- use the default value for the string type to filter for absence
- OR (
- t.project_id = {projectId: String}
- AND t.timestamp >= {minTimestamp: DateTime64(3)} - INTERVAL 7 DAY
- AND t.timestamp <= {maxTimestamp: DateTime64(3)}
- )
- )
`;
const records = queryClickhouseStream<Record<string, unknown>>({
@@ -2127,10 +2139,14 @@ export const getScoresForAnalyticsIntegrations = async function* (
},
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
- clickhouse_settings: {
- join_algorithm: "grace_hash",
- grace_hash_join_initial_buckets: "32",
- },
+ ...(options.useGraceHash
+ ? {
+ clickhouse_settings: {
+ join_algorithm: "grace_hash",
+ grace_hash_join_initial_buckets: "32",
+ },
+ }
+ : {}),
},
});
diff --git a/packages/shared/src/server/repositories/traces.ts b/packages/shared/src/server/repositories/traces.ts
index d36dc22838..1f64b4ac62 100644
--- a/packages/shared/src/server/repositories/traces.ts
+++ b/packages/shared/src/server/repositories/traces.ts
@@ -1413,6 +1413,7 @@ export const getTracesForAnalyticsIntegrations = async function* (
projectName: string,
minTimestamp: Date,
maxTimestamp: Date,
+ options: { useGraceHash?: boolean } = {},
) {
// Determine which trace table to use based on experiment flag
const traceTable = "traces";
@@ -1468,10 +1469,14 @@ export const getTracesForAnalyticsIntegrations = async function* (
},
clickhouseConfigs: {
request_timeout: env.LANGFUSE_CLICKHOUSE_DATA_EXPORT_REQUEST_TIMEOUT_MS,
- clickhouse_settings: {
- join_algorithm: "grace_hash",
- grace_hash_join_initial_buckets: "32",
- },
+ ...(options.useGraceHash
+ ? {
+ clickhouse_settings: {
+ join_algorithm: "grace_hash",
+ grace_hash_join_initial_buckets: "32",
+ },
+ }
+ : {}),
},
});
diff --git a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
index c8cc11982c..bb85732dfd 100644
--- a/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
+++ b/worker/src/features/mixpanel/handleMixpanelIntegrationProjectJob.ts
@@ -26,6 +26,10 @@ type MixpanelExecutionConfig = {
maxTimestamp: Date;
decryptedMixpanelProjectToken: string;
mixpanelRegion: string;
+ // First attempt uses ClickHouse `auto` join algorithm. We only fall back to
+ // `grace_hash` (slower, but spills to disk) on retries so an OOM on the first
+ // attempt recovers without manual intervention while healthy syncs stay fast.
+ useGraceHash: boolean;
};
const processMixpanelTraces = async (config: MixpanelExecutionConfig) => {
@@ -34,6 +38,7 @@ const processMixpanelTraces = async (config: MixpanelExecutionConfig) => {
config.projectName,
config.minTimestamp,
config.maxTimestamp,
+ { useGraceHash: config.useGraceHash },
);
logger.info(
@@ -70,6 +75,7 @@ const processMixpanelGenerations = async (config: MixpanelExecutionConfig) => {
config.projectName,
config.minTimestamp,
config.maxTimestamp,
+ { useGraceHash: config.useGraceHash },
);
logger.info(
@@ -106,6 +112,7 @@ const processMixpanelScores = async (config: MixpanelExecutionConfig) => {
config.projectName,
config.minTimestamp,
config.maxTimestamp,
+ { useGraceHash: config.useGraceHash },
);
logger.info(
@@ -225,6 +232,7 @@ export const handleMixpanelIntegrationProjectJob = async (
mixpanelIntegration.encryptedMixpanelProjectToken,
),
mixpanelRegion: mixpanelIntegration.mixpanelRegion,
+ useGraceHash: job.attemptsMade > 0,
};
try {
diff --git a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
index 3fc4c151e2..0ed15abd83 100644
--- a/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
+++ b/worker/src/features/posthog/handlePostHogIntegrationProjectJob.ts
@@ -27,6 +27,10 @@ type PostHogExecutionConfig = {
maxTimestamp: Date;
decryptedPostHogApiKey: string;
postHogHost: string;
+ // First attempt uses ClickHouse `auto` join algorithm. We only fall back to
+ // `grace_hash` (slower, but spills to disk) on retries so an OOM on the first
+ // attempt recovers without manual intervention while healthy syncs stay fast.
+ useGraceHash: boolean;
};
const postHogSettings = {
@@ -39,6 +43,7 @@ const processPostHogTraces = async (config: PostHogExecutionConfig) => {
config.projectName,
config.minTimestamp,
config.maxTimestamp,
+ { useGraceHash: config.useGraceHash },
);
logger.info(
@@ -86,6 +91,7 @@ const processPostHogGenerations = async (config: PostHogExecutionConfig) => {
config.projectName,
config.minTimestamp,
config.maxTimestamp,
+ { useGraceHash: config.useGraceHash },
);
logger.info(
@@ -133,6 +139,7 @@ const processPostHogScores = async (config: PostHogExecutionConfig) => {
config.projectName,
config.minTimestamp,
config.maxTimestamp,
+ { useGraceHash: config.useGraceHash },
);
logger.info(
@@ -316,6 +323,7 @@ export const handlePostHogIntegrationProjectJob = async (
maxTimestamp,
decryptedPostHogApiKey: decrypt(postHogIntegration.encryptedPosthogApiKey),
postHogHost: postHogIntegration.posthogHostName,
+ useGraceHash: job.attemptsMade > 0,
};
try {