Skip to content

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

chore: improve clickhouse schema (#3638)

Max Deichmann6200a9844fe8
diff --git a/packages/shared/clickhouse/migrations/0001_traces.up.sql b/packages/shared/clickhouse/migrations/0001_traces.up.sql
index 31864a6a37..86ea51e7eb 100644
--- a/packages/shared/clickhouse/migrations/0001_traces.up.sql
+++ b/packages/shared/clickhouse/migrations/0001_traces.up.sql
@@ -15,12 +15,13 @@ CREATE TABLE traces (
`session_id` Nullable(String),
`created_at` DateTime64(3) DEFAULT now(),
`updated_at` DateTime64(3) DEFAULT now(),
+ event_ts DateTime64(3),
INDEX idx_id id TYPE bloom_filter(0.001) GRANULARITY 1,
INDEX idx_res_metadata_key mapKeys(metadata) TYPE bloom_filter(0.01) GRANULARITY 1,
INDEX idx_res_metadata_value mapValues(metadata) TYPE bloom_filter(0.01) GRANULARITY 1
) ENGINE = ReplacingMergeTree Partition by toYYYYMM(timestamp)
ORDER BY (
project_id,
- toUnixTimestamp(timestamp),
+ toDate(timestamp),
id
- );
\ No newline at end of file
+ );
diff --git a/packages/shared/clickhouse/migrations/0002_observations.up.sql b/packages/shared/clickhouse/migrations/0002_observations.up.sql
index 159957a41f..ae97410fd6 100644
--- a/packages/shared/clickhouse/migrations/0002_observations.up.sql
+++ b/packages/shared/clickhouse/migrations/0002_observations.up.sql
@@ -35,6 +35,7 @@ CREATE TABLE observations (
`prompt_version` Nullable(UInt16),
`created_at` DateTime64(3) DEFAULT now(),
`updated_at` DateTime64(3) DEFAULT now(),
+ event_ts DateTime64(3),
INDEX idx_id id TYPE bloom_filter() GRANULARITY 1,
INDEX idx_trace_id trace_id TYPE bloom_filter() GRANULARITY 1,
INDEX idx_project_id project_id TYPE bloom_filter() GRANULARITY 1,
@@ -44,7 +45,7 @@ CREATE TABLE observations (
ORDER BY (
project_id,
`type`,
- trace_id,
- toUnixTimestamp(start_time),
+ toDate(start_time),
id
- );
\ No newline at end of file
+ );
+
diff --git a/packages/shared/clickhouse/migrations/0003_scores.up.sql b/packages/shared/clickhouse/migrations/0003_scores.up.sql
index 8de0cf8812..c4105ce4a9 100644
--- a/packages/shared/clickhouse/migrations/0003_scores.up.sql
+++ b/packages/shared/clickhouse/migrations/0003_scores.up.sql
@@ -14,12 +14,13 @@ CREATE TABLE scores (
`string_value` Nullable(String),
`created_at` DateTime64(3) DEFAULT now(),
`updated_at` DateTime64(3) DEFAULT now(),
+ event_ts DateTime64(3),
INDEX idx_id id TYPE bloom_filter(0.001) GRANULARITY 1,
- INDEX idx_project_id trace_id TYPE bloom_filter(0.001) GRANULARITY 1
+ INDEX idx_project_trace_observation (project_id, trace_id, observation_id) TYPE bloom_filter(0.001) GRANULARITY 1
) ENGINE = ReplacingMergeTree Partition by toYYYYMM(timestamp)
ORDER BY (
project_id,
- trace_id,
- toUnixTimestamp(timestamp),
+ toDate(timestamp),
+ name,
id
- );
\ No newline at end of file
+ )
diff --git a/packages/shared/clickhouse/migrations/0004_observations_wide.down.sql b/packages/shared/clickhouse/migrations/0004_observations_wide.down.sql
new file mode 100644
index 0000000000..2f2eacfaf7
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/0004_observations_wide.down.sql
@@ -0,0 +1,3 @@
+DROP TABLE IF EXISTS mv_observations_to_observations_wide;
+DROP TABLE IF EXISTS mv_traces_to_observations_wide;
+DROP TABLE IF EXISTS observations_wide;
diff --git a/packages/shared/clickhouse/migrations/0004_observations_wide.up.sql b/packages/shared/clickhouse/migrations/0004_observations_wide.up.sql
new file mode 100644
index 0000000000..513aba727c
--- /dev/null
+++ b/packages/shared/clickhouse/migrations/0004_observations_wide.up.sql
@@ -0,0 +1,175 @@
+CREATE TABLE observations_wide
+(
+ `id` String,
+ trace_id Nullable(String),
+ `name` Nullable(String),
+ `project_id` String,
+ `user_id` Nullable(String),
+ `metadata` Map(String, String),
+ `release` Nullable(String),
+ `version` Nullable(String),
+ `public` Bool,
+ `bookmarked` Bool,
+ `tags` Array(String),
+ `input` Nullable(String),
+ `output` Nullable(String),
+ `session_id` Nullable(String),
+ `created_at` DateTime64(3),
+ `updated_at` DateTime64(3),
+ event_ts DateTime64(3),
+ `type` LowCardinality(String),
+ `parent_observation_id` Nullable(String),
+ `start_time` DateTime64(3),
+ `end_time` Nullable(DateTime64(3)),
+ `level` LowCardinality(String),
+ `status_message` Nullable(String),
+ `provided_model_name` Nullable(String),
+ `internal_model_id` Nullable(String),
+ `model_parameters` Nullable(String),
+ `provided_input_usage_units` Nullable(Decimal64(12)),
+ `provided_output_usage_units` Nullable(Decimal64(12)),
+ `provided_total_usage_units` Nullable(Decimal64(12)),
+ `input_usage_units` Nullable(Decimal64(12)),
+ `output_usage_units` Nullable(Decimal64(12)),
+ `total_usage_units` Nullable(Decimal64(12)),
+ `unit` Nullable(String),
+ `provided_input_cost` Nullable(Decimal64(12)),
+ `provided_output_cost` Nullable(Decimal64(12)),
+ `provided_total_cost` Nullable(Decimal64(12)),
+ `input_cost` Nullable(Decimal64(12)),
+ `output_cost` Nullable(Decimal64(12)),
+ `total_cost` Nullable(Decimal64(12)),
+ `completion_start_time` Nullable(DateTime64(3)),
+ `prompt_id` Nullable(String),
+ `prompt_name` Nullable(String),
+ `prompt_version` Nullable(UInt16),
+ trace_timestamp DateTime64(3),
+ trace_name String,
+ trace_user_id Nullable(String),
+ trace_metadata Map(String, String),
+ trace_release Nullable(String),
+ trace_version Nullable(String),
+ trace_public Bool,
+ trace_bookmarked Bool,
+ trace_tags Array(String),
+ trace_input Nullable(String),
+ trace_output Nullable(String),
+ trace_session_id Nullable(String),
+ trace_event_ts DateTime64(3)
+) ENGINE = ReplacingMergeTree Partition by toYYYYMM(start_time)
+ORDER BY (
+ project_id,
+ `type`,
+ toDate(start_time),
+ id
+ );
+
+CREATE MATERIALIZED VIEW mv_traces_to_observations_wide TO observations_wide AS
+SELECT
+ argMax(t.`name`, o.event_ts) as trace_name,
+ argMax(t.timestamp, o.event_ts) as trace_timestamp,
+ argMax(t.user_id, o.event_ts) as trace_user_id,
+ argMax(t.metadata, o.event_ts) as trace_metadata,
+ argMax(t.release, o.event_ts) as trace_release,
+ argMax(t.version, o.event_ts) as trace_version,
+ argMax(t.project_id, o.event_ts) as trace_project_id,
+ argMax(t.public, o.event_ts) as trace_public,
+ argMax(t.bookmarked, o.event_ts) as trace_bookmarked,
+ argMax(t.tags, o.event_ts) as trace_tags,
+ argMax(t.input, o.event_ts) as trace_input,
+ argMax(t.output, o.event_ts) as trace_output,
+ argMax(t.session_id, o.event_ts) as trace_session_id,
+ argMax(t.event_ts, o.event_ts) as trace_event_ts,
+ o.id as id,
+ argMax(o.trace_id, o.event_ts) as trace_id,
+ argMax(o.name, o.event_ts) as `name`,
+ o.project_id as project_id,
+ argMax(o.metadata, o.event_ts) as metadata,
+ argMax(o.type, o.event_ts) as type,
+ argMax(o.parent_observation_id, o.event_ts) as parent_observation_id,
+ argMax(o.start_time, o.event_ts) as start_time,
+ argMax(o.end_time, o.event_ts) as end_time,
+ argMax(o.level, o.event_ts) as level,
+ argMax(o.status_message, o.event_ts) as status_message,
+ argMax(o.provided_model_name, o.event_ts) as provided_model_name,
+ argMax(o.internal_model_id, o.event_ts) as internal_model_id,
+ argMax(o.model_parameters, o.event_ts) as model_parameters,
+ argMax(o.provided_input_usage_units, o.event_ts) as provided_input_usage_units,
+ argMax(o.provided_output_usage_units, o.event_ts) as provided_output_usage_units,
+ argMax(o.provided_total_usage_units, o.event_ts) as provided_total_usage_units,
+ argMax(o.input_usage_units, o.event_ts) as input_usage_units,
+ argMax(o.output_usage_units, o.event_ts) as output_usage_units,
+ argMax(o.total_usage_units, o.event_ts) as total_usage_units,
+ argMax(o.unit, o.event_ts) as unit,
+ argMax(o.provided_input_cost, o.event_ts) as provided_input_cost,
+ argMax(o.provided_output_cost, o.event_ts) as provided_output_cost,
+ argMax(o.provided_total_cost, o.event_ts) as provided_total_cost,
+ argMax(o.input_cost, o.event_ts) as input_cost,
+ argMax(o.output_cost, o.event_ts) as output_cost,
+ argMax(o.total_cost, o.event_ts) as total_cost,
+ argMax(o.completion_start_time, o.event_ts) as completion_start_time,
+ argMax(o.prompt_id, o.event_ts) as prompt_id,
+ argMax(o.prompt_name, o.event_ts) as prompt_name,
+ argMax(o.prompt_version, o.event_ts) as prompt_version,
+ argMax(o.created_at, o.event_ts) as created_at,
+ argMax(o.updated_at, o.event_ts) as updated_at,
+ argMax(o.event_ts, o.event_ts) as event_ts
+FROM traces t
+INNER JOIN observations o ON t.id = o.trace_id
+GROUP BY o.id, o.project_id;
+
+CREATE MATERIALIZED VIEW mv_observations_to_observations_wide TO observations_wide AS
+SELECT
+ argMax(t.timestamp, o.event_ts) as trace_timestamp,
+ argMax(t.name, o.event_ts) as trace_name,
+ argMax(t.user_id, o.event_ts) as trace_user_id,
+ argMax(t.metadata, o.event_ts) as trace_metadata,
+ argMax(t.release, o.event_ts) as trace_release,
+ argMax(t.version, o.event_ts) as trace_version,
+ argMax(t.project_id, o.event_ts) as trace_project_id,
+ argMax(t.public, o.event_ts) as trace_public,
+ argMax(t.bookmarked, o.event_ts) as trace_bookmarked,
+ argMax(t.tags, o.event_ts) as trace_tags,
+ argMax(t.input, o.event_ts) as trace_input,
+ argMax(t.output, o.event_ts) as trace_output,
+ argMax(t.session_id, o.event_ts) as trace_session_id,
+ argMax(t.event_ts, o.event_ts) as trace_event_ts,
+ o.id as id,
+ argMax(o.trace_id, o.event_ts) as trace_id,
+ argMax(o.name, o.event_ts) as name,
+ o.project_id as project_id,
+ argMax(o.metadata, o.event_ts) as metadata,
+ argMax(o.type, o.event_ts) as type,
+ argMax(o.parent_observation_id, o.event_ts) as parent_observation_id,
+ argMax(o.start_time, o.event_ts) as start_time,
+ argMax(o.end_time, o.event_ts) as end_time,
+ argMax(o.level, o.event_ts) as level,
+ argMax(o.status_message, o.event_ts) as status_message,
+ argMax(o.provided_model_name, o.event_ts) as provided_model_name,
+ argMax(o.internal_model_id, o.event_ts) as internal_model_id,
+ argMax(o.model_parameters, o.event_ts) as model_parameters,
+ argMax(o.provided_input_usage_units, o.event_ts) as provided_input_usage_units,
+ argMax(o.provided_output_usage_units, o.event_ts) as provided_output_usage_units,
+ argMax(o.provided_total_usage_units, o.event_ts) as provided_total_usage_units,
+ argMax(o.input_usage_units, o.event_ts) as input_usage_units,
+ argMax(o.output_usage_units, o.event_ts) as output_usage_units,
+ argMax(o.total_usage_units, o.event_ts) as total_usage_units,
+ argMax(o.unit, o.event_ts) as unit,
+ argMax(o.provided_input_cost, o.event_ts) as provided_input_cost,
+ argMax(o.provided_output_cost, o.event_ts) as provided_output_cost,
+ argMax(o.provided_total_cost, o.event_ts) as provided_total_cost,
+ argMax(o.input_cost, o.event_ts) as input_cost,
+ argMax(o.output_cost, o.event_ts) as output_cost,
+ argMax(o.total_cost, o.event_ts) as total_cost,
+ argMax(o.completion_start_time, o.event_ts) as completion_start_time,
+ argMax(o.prompt_id, o.event_ts) as prompt_id,
+ argMax(o.prompt_name, o.event_ts) as prompt_name,
+ argMax(o.prompt_version, o.event_ts) as prompt_version,
+ argMax(o.created_at, o.event_ts) as created_at,
+ argMax(o.updated_at, o.event_ts) as updated_at,
+ argMax(o.event_ts, o.event_ts) as event_ts
+FROM observations o
+LEFT OUTER JOIN traces t ON t.id = o.trace_id
+GROUP BY o.id, o.project_id;
+
+
diff --git a/packages/shared/clickhouse/scripts/seed.ts b/packages/shared/clickhouse/scripts/seed.ts
new file mode 100644
index 0000000000..f8576458d3
--- /dev/null
+++ b/packages/shared/clickhouse/scripts/seed.ts
@@ -0,0 +1,134 @@
+import { clickhouseClient } from "@langfuse/shared/src/server";
+import { prisma } from "../../src/db";
+import { redis } from "@langfuse/shared/src/server";
+
+export const prepareClickhouse = async (projectIds: string[]) => {
+ for (const projectId of projectIds) {
+ console.log(`Preparing Clickhouse for project ${projectId}...`);
+ const tracesQuery = `
+ INSERT INTO traces
+ SELECT toString(floor(randUniform(0, 10000))) AS id,
+ '2024-07-31 09:47:59.270' AS timestamp,
+ concat('name_', toString(rand() % 100)) AS name,
+ concat('user_id_', toString(randUniform(0, 100))) AS user_id,
+ map('key', 'value') AS metadata,
+ concat('release_', toString(randUniform(0, 100))) AS release,
+ concat('version_', toString(randUniform(0, 100))) AS version,
+ '${projectId}' AS project_id,
+ if(rand() < 0.8, true, false) as public,
+ if(rand() < 0.8, true, false) as bookmarked,
+ array('tag1', 'tag2') as tags,
+ repeat('input', toInt64(randExponential(1 / 100))) AS input,
+ repeat('output', toInt64(randExponential(1 / 100))) AS output,
+ concat('session_', toString(rand() % 100)) AS session_id,
+ timestamp AS created_at,
+ timestamp AS updated_at,
+ timestamp AS event_ts
+ FROM numbers(10000);
+ `;
+
+ const observationsQuery = `
+ INSERT INTO observations
+ SELECT toString(floor(randUniform(0, 70000))) AS id,
+ toString(floor(randUniform(0, 10000))) AS trace_id,
+ '${projectId}' AS project_id,
+ 'GENERATION' AS type,
+ toString(rand()) AS parent_observation_id,
+ '2024-07-31 09:47:59.270' AS start_time,
+ addSeconds(start_time, floor(randExponential(1 / 10))) AS end_time,
+ concat('name', toString(rand() % 100)) AS name,
+ map('key', 'value') AS metadata,
+ 'level' AS level,
+ 'status_message' AS status_message,
+ 'version' AS version,
+ repeat('input', toInt64(randExponential(1 / 100))) AS input,
+ repeat('output', toInt64(randExponential(1 / 100))) AS output,
+ if(
+ number % 2 = 0,
+ 'claude-3-haiku-20240307',
+ 'gpt-4'
+ ) as provided_model_name,
+ toString(floor(randUniform(0, 1000000000))) as internal_model_id,
+ 'model_parameters' AS model_parameters,
+ 1000 AS provided_input_usage_units,
+ 1000 AS provided_output_usage_units,
+ 1000 AS provided_total_usage_units,
+ 1000 AS input_usage_units,
+ 1000 AS output_usage_units,
+ 1000 AS total_usage_units,
+ 1000 AS provided_input_cost,
+ 1000 AS provided_output_cost,
+ 1000 AS provided_total_cost,
+ 'unit' AS unit,
+ 1000 AS input_cost,
+ 1000 AS output_cost,
+ 1000 AS total_cost,
+ start_time AS completion_start_time,
+ toString(rand()) AS prompt_id,
+ toString(rand()) AS prompt_name,
+ 1000 AS prompt_version,
+ start_time AS created_at,
+ start_time AS updated_at,
+ start_time AS event_ts
+ FROM numbers(10000);
+ `;
+
+ const scoresQuery = `
+ INSERT INTO scores
+ SELECT toString(floor(randUniform(0, 100))) AS id,
+ now() - randUniform(0, 100) AS timestamp,
+ '${projectId}' AS project_id,
+ toString(floor(randUniform(0, 1000))) AS trace_id,
+ if(
+ rand() > 0.9,
+ toString(floor(randUniform(0, 1000))),
+ NULL
+ ) AS observation_id,
+ concat('name_', toString(rand() % 100)) AS name,
+ randUniform(0, 100) as value,
+ 'API' as source,
+ 'comment' as comment,
+ toString(rand() % 100) as author_user_id,
+ toString(rand() % 100) as config_id,
+ toString(rand() % 100) as data_type,
+ toString(rand() % 100) as string_value,
+ timestamp AS created_at,
+ timestamp AS updated_at,
+ timestamp AS event_ts
+ FROM numbers(10000);
+ `;
+
+ const queries = [tracesQuery, scoresQuery, observationsQuery];
+
+ await Promise.all(
+ queries.map((query) =>
+ clickhouseClient.command({
+ query,
+ clickhouse_settings: {
+ wait_end_of_query: 1,
+ },
+ })
+ )
+ );
+ }
+};
+
+async function main() {
+ try {
+ const projectIds = [
+ "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",
+ "239ad00f-562f-411d-af14-831c75ddd875",
+ ]; // Example project IDs
+ await prepareClickhouse(projectIds);
+ console.log("Clickhouse preparation completed successfully.");
+ } catch (error) {
+ console.error("Error during Clickhouse preparation:", error);
+ } finally {
+ await clickhouseClient.close();
+ await prisma.$disconnect();
+ redis?.disconnect();
+ console.log("Disconnected from Clickhouse.");
+ }
+}
+
+main();
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 616db2dac5..7f44489f71 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -47,7 +47,8 @@
"ch:up": "bash clickhouse/scripts/up.sh",
"ch:down": "bash clickhouse/scripts/down.sh",
"ch:drop": "bash clickhouse/scripts/drop.sh",
- "ch:reset": "pnpm run ch:down && pnpm run ch:up"
+ "ch:reset": "pnpm run ch:down && pnpm run ch:up && pnpm run ch:seed",
+ "ch:seed": "dotenv -e ../../.env -- tsx clickhouse/scripts/seed.ts"
},
"prisma": {
"seed": "ts-node -r tsconfig-paths/register -r dotenv/config --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"
@@ -106,6 +107,7 @@
"prisma-kysely": "^1.8.0",
"ts-node": "^10.9.2",
"tsc-watch": "^6.2.0",
+ "tsx": "^4.19.1",
"typescript": "^5.4.5",
"vitest": "^2.1.2"
},
diff --git a/packages/shared/src/server/definitions.ts b/packages/shared/src/server/definitions.ts
index bfb273d375..cab3829d3a 100644
--- a/packages/shared/src/server/definitions.ts
+++ b/packages/shared/src/server/definitions.ts
@@ -50,6 +50,7 @@ export const observationRecordReadSchema = observationRecordBaseSchema.extend({
start_time: clickhouseStringDateSchema,
end_time: clickhouseStringDateSchema.nullish(),
completion_start_time: clickhouseStringDateSchema.nullish(),
+ event_ts: clickhouseStringDateSchema,
});
export type ObservationRecordReadType = z.infer<
typeof observationRecordReadSchema
@@ -62,6 +63,7 @@ export const observationRecordInsertSchema = observationRecordBaseSchema.extend(
start_time: z.number(),
end_time: z.number().nullish(),
completion_start_time: z.number().nullish(),
+ event_ts: z.number(),
}
);
export type ObservationRecordInsertType = z.infer<
@@ -89,6 +91,7 @@ export const traceRecordReadSchema = traceRecordBaseSchema.extend({
timestamp: clickhouseStringDateSchema,
created_at: clickhouseStringDateSchema,
updated_at: clickhouseStringDateSchema,
+ event_ts: clickhouseStringDateSchema,
});
export type TraceRecordReadType = z.infer<typeof traceRecordReadSchema>;
@@ -96,6 +99,7 @@ export const traceRecordInsertSchema = traceRecordBaseSchema.extend({
timestamp: z.number(),
created_at: z.number(),
updated_at: z.number(),
+ event_ts: z.number(),
});
export type TraceRecordInsertType = z.infer<typeof traceRecordInsertSchema>;
@@ -119,6 +123,7 @@ export const scoreRecordReadSchema = scoreRecordBaseSchema.extend({
created_at: clickhouseStringDateSchema,
updated_at: clickhouseStringDateSchema,
timestamp: clickhouseStringDateSchema,
+ event_ts: clickhouseStringDateSchema,
});
export type ScoreRecordReadType = z.infer<typeof scoreRecordReadSchema>;
@@ -126,6 +131,7 @@ export const scoreRecordInsertSchema = scoreRecordBaseSchema.extend({
created_at: z.number(),
updated_at: z.number(),
timestamp: z.number(),
+ event_ts: z.number(),
});
export type ScoreRecordInsertType = z.infer<typeof scoreRecordInsertSchema>;
@@ -137,6 +143,7 @@ export const convertTraceReadToInsert = (
created_at: new Date(record.created_at).getTime(),
updated_at: new Date(record.created_at).getTime(),
timestamp: new Date(record.timestamp).getTime(),
+ event_ts: new Date(record.event_ts).getTime(),
};
};
@@ -152,6 +159,7 @@ export const convertObservationReadToInsert = (
completion_start_time: record.completion_start_time
? new Date(record.completion_start_time).getTime()
: undefined,
+ event_ts: new Date(record.event_ts).getTime(),
};
};
@@ -163,5 +171,6 @@ export const convertScoreReadToInsert = (
created_at: new Date(record.created_at).getTime(),
updated_at: new Date(record.updated_at).getTime(),
timestamp: new Date(record.timestamp).getTime(),
+ event_ts: new Date(record.event_ts).getTime(),
};
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index c3582d4b4d..6f47c5472c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -282,6 +282,9 @@ importers:
tsc-watch:
specifier: ^6.2.0
version: 6.2.0([email protected])
+ tsx:
+ specifier: ^4.19.1
+ version: 4.19.1
typescript:
specifier: ^5.4.5
version: 5.4.5
diff --git a/worker/src/services/IngestionService/index.ts b/worker/src/services/IngestionService/index.ts
index 34ba233353..c4311499a0 100644
--- a/worker/src/services/IngestionService/index.ts
+++ b/worker/src/services/IngestionService/index.ts
@@ -68,7 +68,7 @@ export class IngestionService {
private redis: Redis,
prisma: PrismaClient,
private clickHouseWriter: ClickhouseWriter,
- private clickhouseClient: ClickhouseClientType,
+ private clickhouseClient: ClickhouseClientType
) {
this.promptService = new PromptService(prisma, redis);
}
@@ -77,10 +77,10 @@ export class IngestionService {
eventType: ClickhouseEntityType,
projectId: string,
eventBodyId: string,
- events: IngestionEventType[],
+ events: IngestionEventType[]
): Promise<void> {
logger.info(
- `Merging ingestion ${eventType} event for project ${projectId} and event ${eventBodyId}`,
+ `Merging ingestion ${eventType} event for project ${projectId} and event ${eventBodyId}`
);
switch (eventType) {
@@ -139,6 +139,7 @@ export class IngestionService {
string_value: validatedScore.stringValue,
created_at: Date.now(),
updated_at: Date.now(),
+ event_ts: new Date(scoreEvent.timestamp).getTime(),
};
});
@@ -152,7 +153,7 @@ export class IngestionService {
if (!clickhouseScoreRecord && !this.hasCreateEvent(scoreEventList)) {
throw new Error(
- `No create event or existing record found for score with id ${entityId} in project ${projectId}`,
+ `No create event or existing record found for score with id ${entityId} in project ${projectId}`
);
}
@@ -190,7 +191,7 @@ export class IngestionService {
if (!clickhouseTraceRecord && !this.hasCreateEvent(traceEventList)) {
throw new Error(
- `No create event or existing record found for trace with id ${entityId} in project ${projectId}`,
+ `No create event or existing record found for trace with id ${entityId} in project ${projectId}`
);
}
@@ -232,7 +233,7 @@ export class IngestionService {
!this.hasCreateEvent(observationEventList)
) {
throw new Error(
- `No create event or existing record found for observation with id ${entityId} in project ${projectId}`,
+ `No create event or existing record found for observation with id ${entityId} in project ${projectId}`
);
}
@@ -255,6 +256,7 @@ export class IngestionService {
tags: [],
bookmarked: false,
public: false,
+ event_ts: Date.now(),
};
this.clickHouseWriter.addToQueue(TableName.Traces, wrapperTraceRecord);
@@ -263,7 +265,7 @@ export class IngestionService {
this.clickHouseWriter.addToQueue(
TableName.Observations,
- finalObservationRecord,
+ finalObservationRecord
);
}
@@ -279,7 +281,7 @@ export class IngestionService {
const mergedRecord = this.mergeRecords(
recordsToMerge,
- immutableEntityKeys[TableName.Scores],
+ immutableEntityKeys[TableName.Scores]
);
return scoreRecordInsertSchema.parse(mergedRecord);
@@ -297,7 +299,7 @@ export class IngestionService {
const mergedRecord = this.mergeRecords(
recordsToMerge,
- immutableEntityKeys[TableName.Traces],
+ immutableEntityKeys[TableName.Traces]
);
return traceRecordInsertSchema.parse(mergedRecord);
@@ -317,7 +319,7 @@ export class IngestionService {
const mergedRecord = this.mergeRecords(
recordsToMerge,
- immutableEntityKeys[TableName.Observations],
+ immutableEntityKeys[TableName.Observations]
);
const parsedObservationRecord =
@@ -341,7 +343,7 @@ export class IngestionService {
private mergeRecords<T extends InsertRecord>(
records: T[],
- immutableEntityKeys: string[],
+ immutableEntityKeys: string[]
): unknown {
if (records.length === 0) {
throw new Error("No records to merge");
@@ -377,7 +379,7 @@ export class IngestionService {
private async getPrompt(
projectId: string,
- observationEventList: ObservationEvent[],
+ observationEventList: ObservationEvent[]
): Promise<ObservationPrompt | null> {
const lastObservationWithPromptInfo = observationEventList
.slice()
@@ -398,7 +400,7 @@ export class IngestionService {
}
private hasPromptInformation(
- event: ObservationEvent,
+ event: ObservationEvent
): event is ObservationEvent & {
body: { promptName: string; promptVersion: number };
} {
@@ -440,7 +442,7 @@ export class IngestionService {
const tokenCosts = IngestionService.calculateTokenCosts(
internalModel,
observationRecord,
- tokenCounts,
+ tokenCounts
);
return {
@@ -453,7 +455,7 @@ export class IngestionService {
private getTokenCounts(
observationRecord: ObservationRecordInsertType,
- model: Model | null | undefined,
+ model: Model | null | undefined
): Pick<
ObservationRecordInsertType,
"input_usage_units" | "output_usage_units" | "total_usage_units"
@@ -500,7 +502,7 @@ export class IngestionService {
input_usage_units?: number | null;
output_usage_units?: number | null;
total_usage_units?: number | null;
- },
+ }
): {
input_cost: number | null | undefined;
output_cost: number | null | undefined;
@@ -592,7 +594,7 @@ export class IngestionService {
: table === TableName.Scores
? convertScoreReadToInsert(recordParser[table].parse(result[0]))
: convertObservationReadToInsert(
- recordParser[table].parse(result[0]),
+ recordParser[table].parse(result[0])
);
});
}
@@ -610,7 +612,7 @@ export class IngestionService {
// in the default implementation, we set timestamps server side if not provided.
// we need to insert timestamps here and change the SDKs to send timestamps client side.
timestamp: this.getMillisecondTimestamp(
- trace.body.timestamp ?? trace.timestamp,
+ trace.body.timestamp ?? trace.timestamp
),
name: trace.body.name,
user_id: trace.body.userId,
@@ -628,6 +630,7 @@ export class IngestionService {
session_id: trace.body.sessionId,
created_at: Date.now(),
updated_at: Date.now(),
+ event_ts: new Date(trace.timestamp).getTime(),
};
return traceRecord;
@@ -693,7 +696,7 @@ export class IngestionService {
type: observationType,
name: obs.body.name,
start_time: this.getMillisecondTimestamp(
- obs.body.startTime ?? obs.timestamp,
+ obs.body.startTime ?? obs.timestamp
),
end_time:
"endTime" in obs.body && obs.body.endTime
@@ -735,6 +738,7 @@ export class IngestionService {
prompt_version: prompt?.version,
created_at: Date.now(),
updated_at: Date.now(),
+ event_ts: new Date(obs.timestamp).getTime(),
};
return observationRecord;
@@ -742,7 +746,7 @@ export class IngestionService {
}
private stringify(
- obj: string | object | number | boolean | undefined | null,
+ obj: string | object | number | boolean | undefined | null
): string | undefined {
if (obj == null) return; // return undefined on undefined or null
@@ -754,10 +758,10 @@ export class IngestionService {
}
private hasCreateEvent(
- eventList: ObservationEvent[] | ScoreEventType[] | TraceEventType[],
+ eventList: ObservationEvent[] | ScoreEventType[] | TraceEventType[]
): boolean {
return eventList.some((event) =>
- event.type.toLowerCase().includes("create"),
+ event.type.toLowerCase().includes("create")
);
}
}