Skip to content

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

feat(seeder): agent-first seed CLI — doctor, complex trees/sessions/bulk, v4 mirroring (#14104)

Nikita Kabardinadb0695245a0
diff --git a/.agents/AGENTS.md b/.agents/AGENTS.md
index d59b92050f..ab84ae67a4 100644
--- a/.agents/AGENTS.md
+++ b/.agents/AGENTS.md
@@ -8,9 +8,15 @@ evaluating, and debugging AI applications.
- Read the minimal local context required for the task.
- Keep changes scoped and avoid unrelated refactors.
- For bug fixes, write the failing test first, confirm it fails, then fix the
- bug.
+ bug. If the bug depends on a data shape, pause and ask: can
+ `pnpm run seed` prefill that shape locally? If not, consider extending a
+ seeder scenario so the bug stays cheaply reproducible
+ (`packages/shared/scripts/seeder/AGENTS.md`), or note why a seed cannot
+ express it.
- For user-visible frontend changes in `web/**`, review the affected flow in a
- real browser before signoff.
+ real browser before signoff. Prefill the data the flow needs with the seed
+ CLI (`pnpm run seed -- list` shows scenarios; runs print UI deep links) —
+ never with ad-hoc scripts or raw ClickHouse inserts.
- For documentation screenshots in Markdown, avoid fixed `height` on `<img>`
tags; prefer Markdown images or width-only HTML so previews preserve aspect
ratio.
diff --git a/.agents/skills/frontend-browser-review/SKILL.md b/.agents/skills/frontend-browser-review/SKILL.md
index 6c8cbddbd8..805e480d47 100644
--- a/.agents/skills/frontend-browser-review/SKILL.md
+++ b/.agents/skills/frontend-browser-review/SKILL.md
@@ -25,13 +25,29 @@ Use this skill when a change affects what users see or do in the browser.
- Bug fixes where the failure mode is visible in the browser
- Final signoff for user-visible frontend work
+## Prefill Test Data First
+
+Most flows are only reviewable against meaningful data. Before opening the
+browser, seed what the flow needs with the seed CLI (see the
+`seed-test-data` skill for the need→command table):
+
+- `pnpm run seed -- trace-tree --observations 5000 --v4` — complex
+ observation trees (v3 + v4 events)
+- `pnpm run seed -- long-session --traces 300` — heavy session views
+- `pnpm run seed -- many-traces --count 100000` — list/filter performance
+- `pnpm run seed -- doctor` — when the stack misbehaves
+
+Every run prints UI deep links — open those instead of navigating manually.
+Do not hand-write seed scripts or raw ClickHouse inserts.
+
## Review Loop
1. Start the app with `pnpm run dev:web` unless an existing local server is
already running.
2. Install Chromium with `pnpm run playwright:install` if Playwright has not
been set up on the machine yet.
-3. Open the primary changed flow with the Playwright MCP server.
+3. Open the primary changed flow with the Playwright MCP server, using the
+ deep links printed by the seed CLI when the flow needs seeded data.
4. Exercise the main happy path affected by the change.
5. Check for obvious visual regressions:
- broken layout or spacing
diff --git a/.agents/skills/seed-test-data/SKILL.md b/.agents/skills/seed-test-data/SKILL.md
new file mode 100644
index 0000000000..ab2e473a5b
--- /dev/null
+++ b/.agents/skills/seed-test-data/SKILL.md
@@ -0,0 +1,67 @@
+---
+name: seed-test-data
+description: |
+ Seed local Langfuse test data with one command: large/branching observation
+ trees (v3 and v4 events), long sessions, bulk traces for list performance.
+ Use whenever a task needs ClickHouse/Postgres test data — e.g. "seed a
+ complex trace", "make a tough session", "fill the trace list", "test v4
+ events UI", or when debugging trace/session/list rendering or performance.
+ Never write ad-hoc seed scripts or raw ClickHouse inserts.
+---
+
+# Seed Test Data
+
+One-shot deterministic test data for local Langfuse. The CLI handles env
+loading, preflight checks, ClickHouse/Postgres writes, readback verification,
+and prints UI deep links plus a machine-readable JSON summary (last stdout
+line).
+
+## If anything fails, run doctor first
+
+```bash
+pnpm run seed -- doctor
+```
+
+Prints PASS/WARN/FAIL per dependency (Postgres, migrations, project,
+ClickHouse, v4 dev tables, Redis, MinIO, web app) with the exact fix command
+for every failure. Do not debug Docker/ClickHouse manually before running
+this.
+
+## Need → command
+
+| I need... | Command |
+| --- | --- |
+| A very complex observation tree (v3) | `pnpm run seed -- trace-tree --observations 5000 --depth 12 --breadth 500` |
+| The same tree readable in the v4 events UI | add `--v4` (writes `events_full`; `events_core` fills via MV) |
+| A super tough session (v3 legacy session view) | `pnpm run seed -- long-session --traces 300 --observations-per-trace 8` |
+| Many traces for list/filter performance | `pnpm run seed -- many-traces --count 100000 --days 14` |
+| Huge/malformed/unicode payloads | `pnpm run seed -- trace-tree --payload-bytes 1000000 --payload-style malformed` (styles: json, text, malformed, unicode) |
+| See all scenarios and flags | `pnpm run seed -- list --json` |
+| Predict without writing | add `--dry-run` |
+
+## Contract
+
+- Last stdout line is a JSON summary: `traceIds`, `sessionIds`, `counts`,
+ `verified` (ClickHouse readback), `links` (UI deep links). Use `--json` to
+ suppress progress logs. Non-zero exit = data did not land; the error
+ includes a `fix:` line.
+- Deterministic: same `--seed` (default 42) and flags → same ids (ids never
+ contain dates), with timestamps anchored to the current UTC day. Re-running
+ within the same day overwrites in place; a later-day re-run updates the
+ same ids with re-anchored timestamps (the previous day's rows persist
+ under their old dates until then). Independent copies come only from
+ `--id-prefix`.
+- Default project is the seeded `7a88fb47-b4e2-43b8-a06c-a5ce950dc53a`
+ (login `[email protected]` / `password`); override with `--project`.
+- Open the printed `links` in the browser to verify visually. The v4
+ events-backed UI is the per-user "Fast (Preview)" sidebar toggle, or
+ `LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only` server-side.
+
+## Extending
+
+Add a scenario in `packages/shared/scripts/seeder/scenarios/`: a plain
+function using the deterministic `Rng` (never `Math.random`), register it in
+`scenarios/index.ts`, and update the table in
+`packages/shared/scripts/seeder/AGENTS.md` and this skill. Scenario names,
+flags, and JSON keys are additive-only contracts. Design rationale:
+`packages/shared/scripts/seeder/README.md`.
diff --git a/.agents/skills/seed-test-data/agents/openai.yaml b/.agents/skills/seed-test-data/agents/openai.yaml
new file mode 100644
index 0000000000..7e33438de8
--- /dev/null
+++ b/.agents/skills/seed-test-data/agents/openai.yaml
@@ -0,0 +1,4 @@
+interface:
+ display_name: "Seed Test Data"
+ short_description: "One-command Langfuse test data seeding"
+ default_prompt: "Use $seed-test-data to seed the local Langfuse data this task needs (complex traces, long sessions, bulk traces, v4 events)."
diff --git a/package.json b/package.json
index 2cd75ec95b..4afb30bc0c 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"db:seed": "turbo run db:seed",
"db:seed:examples": "turbo run db:seed:examples",
"nuke": "bash ./scripts/nuke.sh",
+ "seed": "pnpm --filter=shared run seed:scenario",
"dx": "pnpm i && pnpm run infra:dev:prune && pnpm run infra:dev:up --pull always && pnpm --filter=shared run db:reset:test && pnpm --filter=shared run db:reset && pnpm --filter=shared run ch:reset && pnpm --filter=shared run db:seed:examples && pnpm run dev",
"dx-f": "pnpm i && pnpm run infra:dev:prune && pnpm run infra:dev:up --pull always && pnpm --filter=shared run db:reset:test && pnpm --filter=shared run db:reset -f && SKIP_CONFIRM=1 pnpm --filter=shared run ch:reset && pnpm --filter=shared run db:seed:examples && pnpm run dev",
"dx:skip-infra": "pnpm i && pnpm --filter=shared run db:reset:test && pnpm --filter=shared run db:reset && pnpm --filter=shared run ch:reset && pnpm --filter=shared run db:seed:examples && pnpm run dev",
diff --git a/packages/shared/package.json b/packages/shared/package.json
index fe577088c3..a2c4075b7b 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -87,7 +87,8 @@
"ch:dev-tables": "bash clickhouse/scripts/dev-tables.sh",
"ch:reset": "pnpm run ch:down && pnpm run ch:up && pnpm run ch:seed && pnpm run ch:dev-tables",
"ch:seed": "dotenv -e ../../.env -- ts-node -r dotenv/config --compiler-options '{\"module\":\"CommonJS\"}' scripts/seeder/seed-clickhouse.ts",
- "load:setup": "dotenv -e ../../.env -- tsx scripts/seeder/load-seed-clickhouse.ts"
+ "load:setup": "dotenv -e ../../.env -- tsx scripts/seeder/load-seed-clickhouse.ts",
+ "seed:scenario": "dotenv -e ../../.env -- tsx scripts/seeder/cli.ts"
},
"prisma": {
"seed": "ts-node -r dotenv/config --compiler-options {\"module\":\"CommonJS\"} scripts/seeder/seed-postgres.ts"
diff --git a/packages/shared/scripts/seeder/AGENTS.md b/packages/shared/scripts/seeder/AGENTS.md
new file mode 100644
index 0000000000..6bd855ecbe
--- /dev/null
+++ b/packages/shared/scripts/seeder/AGENTS.md
@@ -0,0 +1,52 @@
+# Seeder — Agent Guide
+
+If you need local test data (traces, observation trees, sessions, bulk rows,
+v4 events), use the seed CLI. Do not write ad-hoc ts-node scripts or raw
+ClickHouse inserts — the CLI handles env loading, preflight, batching,
+verification, and deep links.
+
+```bash
+pnpm run seed -- doctor # check the stack; prints the fix per failure
+pnpm run seed -- list # scenarios and flags (--json for machines)
+pnpm run seed -- trace-tree --observations 5000 --breadth 500 --v4
+pnpm run seed -- long-session --traces 300 --observations-per-trace 8
+pnpm run seed -- many-traces --count 100000 --days 14
+```
+
+The last stdout line of a run is a JSON summary with `traceIds`,
+`sessionIds`, `counts`, `verified` (ClickHouse readback), and `links` (UI
+deep links). `--dry-run` predicts counts without writing; `--json` suppresses
+progress output. Full usage and the need→command table live in the
+`seed-test-data` skill (`.agents/skills/seed-test-data/SKILL.md`).
+
+## Layout
+
+- `cli.ts` — entry point (`pnpm run seed`, i.e. shared `seed:scenario`)
+- `doctor.ts` — stack checks with remediation commands; scenarios run a fast
+ preflight subset before writing
+- `scenarios/` — one file per scenario plus shared `rng.ts`, `payload.ts`,
+ `event-mirror.ts` (v3 observation → v4 `events_full` row), `verify.ts`
+- `seed-postgres.ts`, `seed-clickhouse.ts`, `utils/` — the pre-existing
+ `pnpm run dx` seed path (unchanged by the CLI)
+- `README.md` — design rationale, contract, and roadmap
+
+## Rules for changes
+
+- Scenario names, flag names, and JSON summary keys are a public contract for
+ agents and scripts: evolve additively, never rename or remove.
+- Scenarios must be deterministic: take randomness from `Rng` (seeded via
+ `--seed`), derive ids from `--id-prefix`, and never call `Math.random`.
+- Any value that lands in a ClickHouse ORDER BY key (timestamps; observation
+ `type` on v3; `start_time` on events) must NOT come from the sequential
+ rng stream or wall clock: use `utcDayStartMs()` for time anchors and the
+ stateless `jitter(seed, index, max)` for per-row variation. Stream-position
+ randomness re-keys rows whenever an unrelated flag (e.g. payload size)
+ changes how much rng earlier code consumed, silently duplicating rows on
+ re-run; `uniqExact` readbacks cannot see it.
+- Every scenario verifies its writes with a ClickHouse readback and fails
+ loudly on mismatch.
+- New scenarios: add `scenarios/<name>.ts`, register in `scenarios/index.ts`,
+ update the skill and this file, and run
+ `pnpm exec eslint scripts/seeder --fix` plus `pnpm run typecheck` in
+ `packages/shared`.
+- No customer data, no secrets, no fixtures that require model provider keys.
diff --git a/packages/shared/scripts/seeder/README.md b/packages/shared/scripts/seeder/README.md
new file mode 100644
index 0000000000..75d413d414
--- /dev/null
+++ b/packages/shared/scripts/seeder/README.md
@@ -0,0 +1,155 @@
+# Langfuse Seed CLI
+
+One command to put any local test state into Langfuse — for developers and
+for coding agents.
+
+```bash
+pnpm run seed -- doctor # check the stack, get the exact fix per failure
+pnpm run seed -- list # scenarios and flags (--json for machines)
+pnpm run seed -- trace-tree --observations 5000 --breadth 1000 --v4
+pnpm run seed -- long-session --traces 300 --observations-per-trace 8
+pnpm run seed -- many-traces --count 100000 --days 14
+```
+
+Every run preflights the stack, writes directly to ClickHouse (plus the
+Postgres rows the UI needs), verifies its writes with exact readbacks, and
+prints UI deep links plus a machine-readable JSON summary as the last stdout
+line. This file is the design explainer; the command reference for agents
+lives in [AGENTS.md](./AGENTS.md) and the `seed-test-data` skill.
+
+## Why this exists
+
+Two consumers need local seed data and both were underserved:
+
+1. **Coding agents.** "Test the trace list with real data" used to end in
+ ad-hoc ts-node scripts and Docker/ClickHouse debugging loops. Now
+ `doctor` diagnoses the whole stack with a remediation command per
+ failure, and the `seed-test-data` skill routes agents to a one-liner.
+2. **Developers.** The default dx seed produces data the frontend shrugs
+ at. These scenarios produce the shapes that actually break products:
+ thousand-child fan-outs, 60-level chains, megabyte malformed payloads,
+ unicode, monster sessions, 100k-trace lists.
+
+The core design: every scenario is a plain function `(params) =>
+SeedSummary` with two faces — the CLI for agents, and (future) direct
+programmatic calls from the dx seed chain.
+
+## Scenarios
+
+| Scenario | Covers | Key flags |
+| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
+| `trace-tree` | one trace with a large, branching observation tree: all ten observation kinds always present, guaranteed depth backbone, hub node with many children, errors/retries/missing end times | `--observations`, `--depth`, `--breadth`, `--payload-bytes`, `--payload-style json\|text\|malformed\|unicode`, `--v4` |
+| `long-session` | one session with many traces for session-detail and virtualization work; creates the Postgres `trace_sessions` row the session page requires | `--traces`, `--observations-per-trace`, `--payload-bytes`, `--minutes`, `--session-id`, `--v4` |
+| `many-traces` | trace-list and filter performance via `numbers()` bulk SQL; parent/score/prompt/session links all resolve | `--count`, `--days`, `--observations-per-trace`, `--scores-per-trace`, `--rich-payloads` |
+
+Common flags: `--project` (defaults to the seeded example project),
+`--environment`, `--seed`, `--id-prefix`, `--dry-run` (instant, arithmetic
+counts, writes nothing), `--json` (machine mode: pure-JSON stdout).
+
+Scenarios compose: e.g. a session where one trace has zero observations is
+two `long-session` runs sharing a `--session-id` with different
+`--id-prefix` values.
+
+## The contract (additive-only)
+
+Scenario names, flag names, JSON summary keys, and exit-code semantics are a
+public contract for agents and scripts — evolve them additively, never
+rename or remove.
+
+- The last stdout line is a JSON summary: `traceIds`, `sessionIds`,
+ `counts`, `verified` (exact `uniqExact` ClickHouse readbacks — every key
+ is asserted, shortfalls exit non-zero), `links`, `durationMs`.
+- Every error prints `error:` and `fix:` lines, never a stack trace —
+ including a missing `.env` (the CLI is a thin bootstrap in `cli.ts` that
+ prechecks env vars before importing `src/server`, whose env schema would
+ otherwise throw at import).
+- Determinism: same `--seed` and flags produce byte-identical data. Ids
+ never contain dates; timestamps anchor to the current UTC day, so
+ same-day re-runs overwrite in place and later-day re-runs re-anchor the
+ same ids. Independent copies come only from `--id-prefix`.
+
+## Data integrity guarantees
+
+Seeded data behaves like production data:
+
+- parents start before and end after their children (waterfall containment,
+ in scenarios and in the bulk SQL)
+- `completion_start_time` (TTFT) falls inside the generation's duration
+- scores reference observations and sessions of their own trace; each score
+ name maps to exactly one data_type; BOOLEAN string values are
+ `True`/`False` (production casing)
+- generations link to real Postgres prompts (the trace-detail prompt badge
+ resolves) or carry NULLs — never fabricated ids
+- session/user pools are `--id-prefix`-scoped, with their `trace_sessions`
+ rows created
+
+## ClickHouse determinism rules (the hard-won part)
+
+ReplacingMergeTree dedups by the full ORDER BY tuple, so **any value that
+lands in an ORDER BY key must not come from the sequential rng stream or
+the wall clock** — otherwise re-runs silently duplicate rows and
+`uniqExact` readbacks cannot see it. Concretely:
+
+- time anchors come from `utcDayStartMs()` (UTC midnight, computed in TS —
+ ClickHouse's `today()` is server-timezone)
+- per-row variation comes from the stateless `jitter(seed, index, max)`
+ (scenarios) or salted `xxHash32(number)` columns (bulk SQL); wrap hash
+ inputs in `toUInt64` — xxHash32 hashes the binary representation, and a
+ type-narrowing modulo silently changes the hash of the same value
+- the sequential `Rng` stream is fine for anything NOT in an ORDER BY key
+ (names, payload contents, usage numbers)
+
+Relevant ORDER BY keys: v3 observations sort on `type`; all v3 tables sort
+on `toDate(...)`-style time keys; `events_full` sorts on microsecond
+`start_time`.
+
+## v3 + v4
+
+`--v4` mirrors every observation into `events_full` following the canonical
+mapping in `clickhouse/scripts/dev-tables.sh`: one synthetic trace span per
+trace (`span_id = 't-<traceId>'`, `parent_span_id = ''`) carries the
+trace-level fields the v4 aggregations read, and root observations hang off
+it. `events_core` fills via the materialized view. Facts that matter:
+
+- `events_full` has no `id` column; `span_id` is the row identifier
+- the v4 read path is the per-user "Fast (Preview)" sidebar toggle or
+ `LANGFUSE_MIGRATION_V4_WRITE_MODE=events_only` server-side; the trace URL
+ is identical in both modes
+- `many-traces` is deliberately v3-only — its traces correctly show "not
+ found" in events-only mode
+
+## Relationship to `pnpm run dx`
+
+The dx flow is unchanged: the CLI is additive and no presets are wired in.
+The shared bulk builders that dx's `ch:seed` step uses received the same
+integrity fixes (resolvable parents/prompts/scores, deterministic re-runs),
+so dx-seeded bulk data is strictly better-shaped than before, at the same
+cost.
+
+## Layout
+
+- `cli.ts` — env-precheck bootstrap; `cli-main.ts` — the actual CLI
+- `doctor.ts` — stack checks (Postgres, migrations, project, ClickHouse +
+ tables + memory pressure, Redis, MinIO, web app), each with a fix command
+- `scenarios/` — one file per scenario plus `rng.ts` (Rng/jitter/anchor),
+ `payload.ts`, `event-mirror.ts` (v3→v4 mapping), `verify.ts` (readbacks)
+- `seed-postgres.ts`, `seed-clickhouse.ts`, `utils/` — the pre-existing dx
+ seed path (the bulk builders in `utils/clickhouse-builder.ts` are shared)
+
+## What's next (deliberately not built yet)
+
+- **API writer**: build the same logical data as public ingestion batches
+ against `LANGFUSE_BASE_URL` + keys, with batch limits and `--wait`
+ readback — the same command would then emulate realistic ingestion
+ against local web+worker or staging.
+- **dx presets**: a `scenarios/presets.ts` invoked from the examples seed,
+ selected via `LANGFUSE_SEED_PRESET`, to give default dx data more variety
+ without flags or interactivity.
+- More scenarios as needs surface: score zoo (blocked on the insert
+ schema's non-nullable `value` for TEXT scores), annotation queue items,
+ dataset experiment loops, media edge cases, deliberate orphan shapes
+ behind explicit flags.
+
+The original design discussion (registry/profiles/budgets alternatives,
+bug-history research) lives in git history: `4b77c8ef7` (first RFC draft)
+and this file's own history as `seeder-2-0-rfc.md`.
diff --git a/packages/shared/scripts/seeder/cli-main.ts b/packages/shared/scripts/seeder/cli-main.ts
new file mode 100644
index 0000000000..57a9558896
--- /dev/null
+++ b/packages/shared/scripts/seeder/cli-main.ts
@@ -0,0 +1,321 @@
+/**
+ * Langfuse seed CLI — one-shot local test data for humans and coding agents.
+ *
+ * Usage:
+ * pnpm run seed -- doctor [--json]
+ * pnpm run seed -- list [--json]
+ * pnpm run seed -- <scenario> [flags]
+ *
+ * Scenario names, flag names, and JSON output keys are a stable, additive-only
+ * contract. See ./README.md and ./AGENTS.md.
+ */
+import { parseArgs } from "node:util";
+import { prisma } from "../../src/db";
+import { logger, redis } from "../../src/server";
+import { preflight, runDoctor } from "./doctor";
+import { scenarios } from "./scenarios";
+import { ScenarioContext, ScenarioFlag, SeedError } from "./scenarios/types";
+
+const DEFAULT_PROJECT_ID = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+
+const COMMON_FLAGS: ScenarioFlag[] = [
+ {
+ flag: "project",
+ type: "string",
+ default: DEFAULT_PROJECT_ID,
+ description: "target project id (default: seed project)",
+ },
+ {
+ flag: "environment",
+ type: "string",
+ default: "default",
+ description: "langfuse environment written on rows",
+ },
+ {
+ flag: "seed",
+ type: "number",
+ default: 42,
+ description: "RNG seed — identical seed and flags produce identical data",
+ },
+ {
+ flag: "id-prefix",
+ type: "string",
+ default: "",
+ description: "prefix for generated ids (default: <scenario>-s<seed>)",
+ },
+ {
+ flag: "dry-run",
+ type: "boolean",
+ default: false,
+ description: "print planned counts and links, write nothing",
+ },
+ {
+ flag: "json",
+ type: "boolean",
+ default: false,
+ description: "machine mode: only the final JSON summary on stdout",
+ },
+];
+
+// CLI script, not a turbo task — reads the dev env directly.
+// eslint-disable-next-line turbo/no-undeclared-env-vars
+const baseUrl = (process.env.NEXTAUTH_URL ?? "http://localhost:3000").replace(
+ /\/$/,
+ "",
+);
+
+const usage = (): string => {
+ const lines = [
+ "Langfuse seed CLI — one-shot local test data.",
+ "",
+ "Usage:",
+ " pnpm run seed -- doctor [--json] [--project <id>] check the local stack, print fixes",
+ " pnpm run seed -- list [--json] list scenarios and flags",
+ " pnpm run seed -- <scenario> [flags] seed one scenario",
+ "",
+ "Scenarios:",
+ ];
+ for (const scenario of Object.values(scenarios)) {
+ lines.push(
+ ` ${scenario.name.padEnd(14)} ${scenario.description.split(":")[0]}`,
+ );
+ }
+ lines.push("");
+ lines.push("Common flags:");
+ for (const flag of COMMON_FLAGS) {
+ lines.push(` --${flag.flag.padEnd(12)} ${flag.description}`);
+ }
+ lines.push("");
+ lines.push("Examples:");
+ lines.push(
+ " pnpm run seed -- trace-tree --observations 5000 --breadth 500 --v4",
+ );
+ lines.push(
+ " pnpm run seed -- long-session --traces 300 --observations-per-trace 8",
+ );
+ lines.push(" pnpm run seed -- many-traces --count 100000 --days 14");
+ return lines.join("\n");
+};
+
+const buildParseOptions = (flags: ScenarioFlag[]) => {
+ const options: Record<string, { type: "string" | "boolean" }> = {};
+ for (const flag of flags) {
+ options[flag.flag] = {
+ type: flag.type === "boolean" ? "boolean" : "string",
+ };
+ }
+ return options;
+};
+
+const coerceValues = (
+ flags: ScenarioFlag[],
+ values: Record<string, string | boolean | undefined>,
+): Record<string, string | number | boolean> => {
+ const params: Record<string, string | number | boolean> = {};
+ for (const flag of flags) {
+ const raw = values[flag.flag];
+ if (raw === undefined) {
+ params[flag.flag] = flag.default;
+ continue;
+ }
+ if (flag.type === "number") {
+ const parsed = Number(raw);
+ if (raw === "" || !Number.isFinite(parsed) || !Number.isInteger(parsed)) {
+ throw new SeedError(
+ `--${flag.flag} expects an integer, got "${raw}"`,
+ `pass an integer, e.g. --${flag.flag} ${String(flag.default)}`,
+ );
+ }
+ params[flag.flag] = parsed;
+ } else {
+ params[flag.flag] = raw;
+ }
+ }
+ return params;
+};
+
+const printDoctor = (
+ result: Awaited<ReturnType<typeof runDoctor>>,
+ json: boolean,
+): void => {
+ if (json) {
+ console.log(JSON.stringify(result));
+ return;
+ }
+ for (const check of result.checks) {
+ const icon =
+ check.status === "pass"
+ ? "PASS"
+ : check.status === "warn"
+ ? "WARN"
+ : "FAIL";
+ console.log(`${icon} ${check.name.padEnd(22)} ${check.detail}`);
+ if (check.fix && check.status !== "pass") {
+ console.log(` fix: ${check.fix}`);
+ }
+ }
+ console.log(
+ result.ok
+ ? "\nStack is ready for seeding."
+ : "\nFix the FAIL items above, then re-run: pnpm run seed -- doctor",
+ );
+};
+
+const main = async (): Promise<number> => {
+ // winston's console transport writes to stdout; --json promises a pure
+ // stdout (only the final summary line), so silence it in machine mode.
+ if (process.argv.includes("--json")) {
+ logger.transports.forEach((transport) => {
+ transport.silent = true;
+ });
+ }
+
+ // pnpm forwards the "--" separator itself; strip leading occurrences.
+ let argv = process.argv.slice(2);
+ while (argv[0] === "--") argv = argv.slice(1);
+ const command = argv[0];
+
+ if (
+ !command ||
+ command === "help" ||
+ command === "--help" ||
+ command === "-h"
+ ) {
+ console.log(usage());
+ return 0;
+ }
+
+ if (command === "doctor") {
+ let values: { json?: boolean; project?: string };
+ try {
+ values = parseArgs({
+ args: argv.slice(1),
+ options: { json: { type: "boolean" }, project: { type: "string" } },
+ }).values;
+ } catch (error) {
+ throw new SeedError(
+ (error as Error).message,
+ "supported usage: doctor [--json] [--project <id>]",
+ );
+ }
+ const result = await runDoctor(
+ baseUrl,
+ values.project ?? DEFAULT_PROJECT_ID,
+ );
+ printDoctor(result, values.json === true);
+ return result.ok ? 0 : 1;
+ }
+
+ if (command === "list") {
+ let values: { json?: boolean };
+ try {
+ values = parseArgs({
+ args: argv.slice(1),
+ options: { json: { type: "boolean" } },
+ }).values;
+ } catch (error) {
+ throw new SeedError(
+ (error as Error).message,
+ "supported usage: list [--json]",
+ );
+ }
+ const listed = Object.values(scenarios).map((scenario) => ({
+ name: scenario.name,
+ description: scenario.description,
+ supportsV4: scenario.supportsV4,
+ flags: [...scenario.flags, ...COMMON_FLAGS],
+ }));
+ if (values.json) {
+ console.log(JSON.stringify({ scenarios: listed }));
+ } else {
+ for (const scenario of listed) {
+ console.log(`${scenario.name}\n ${scenario.description}`);
+ for (const flag of scenario.flags) {
+ console.log(
+ ` --${flag.flag.padEnd(24)} default: ${String(flag.default) || '""'} ${flag.description}`,
+ );
+ }
+ console.log("");
+ }
+ }
+ return 0;
+ }
+
+ const scenario = Object.hasOwn(scenarios, command)
+ ? scenarios[command]
+ : undefined;
+ if (!scenario) {
+ throw new SeedError(
+ `unknown scenario "${command}" — available: ${Object.keys(scenarios).join(", ")}, doctor, list`,
+ "run `pnpm run seed -- list` to see scenarios and flags",
+ );
+ }
+
+ const allFlags = [...scenario.flags, ...COMMON_FLAGS];
+ let params: Record<string, string | number | boolean>;
+ try {
+ const { values } = parseArgs({
+ args: argv.slice(1),
+ options: buildParseOptions(allFlags),
+ });
+ params = coerceValues(allFlags, values);
+ } catch (error) {
+ if (error instanceof SeedError) throw error;
+ throw new SeedError(
+ (error as Error).message,
+ "run `pnpm run seed -- list` to see supported flags",
+ );
+ }
+
+ const jsonOnly = params["json"] === true;
+ const seed = params["seed"] as number;
+ const ctx: ScenarioContext = {
+ projectId: params["project"] as string,
+ environment: params["environment"] as string,
+ seed,
+ idPrefix: (params["id-prefix"] as string) || `${scenario.name}-s${seed}`,
+ dryRun: params["dry-run"] === true,
+ baseUrl,
+ log: (message) => {
+ if (!jsonOnly) console.error(`[seed:${scenario.name}] ${message}`);
+ },
+ };
+
+ if (!ctx.dryRun) {
+ await preflight({
+ projectId: ctx.projectId,
+ needV4: scenario.supportsV4 && params["v4"] === true,
+ log: ctx.log,
+ });
+ }
+
+ const summary = await scenario.run(ctx, params);
+ console.log(JSON.stringify(summary));
+ if (!jsonOnly) {
+ console.error(
+ `[seed:${scenario.name}] ${summary.dryRun ? "dry-run" : "done"} in ${summary.durationMs}ms`,
+ );
+ for (const link of summary.links) {
+ console.error(`[seed:${scenario.name}] open: ${link}`);
+ }
+ }
+ return 0;
+};
+
+export const run = async (): Promise<void> => {
+ try {
+ const code = await main();
+ process.exitCode = code;
+ } catch (error) {
+ if (error instanceof SeedError) {
+ console.error(`error: ${error.message}`);
+ if (error.fix) console.error(`fix: ${error.fix}`);
+ } else {
+ console.error(error);
+ }
+ process.exitCode = 1;
+ } finally {
+ await prisma.$disconnect().catch(() => {});
+ redis?.disconnect();
+ }
+};
diff --git a/packages/shared/scripts/seeder/cli.ts b/packages/shared/scripts/seeder/cli.ts
new file mode 100644
index 0000000000..6f9c6ac7bd
--- /dev/null
+++ b/packages/shared/scripts/seeder/cli.ts
@@ -0,0 +1,56 @@
+/**
+ * Bootstrap for the Langfuse seed CLI.
+ *
+ * Deliberately imports nothing from src/: importing the server barrel parses
+ * the shared env schema at module load, which crashes with a raw ZodError
+ * when the repo-root .env is missing — exactly the fresh-clone situation
+ * where the CLI must instead print the fix. This file prechecks the env,
+ * then dynamically loads ./cli-main which contains the actual CLI.
+ */
+const ENV_FIX = "cp .env.dev.example .env (then review required values)";
+
+// Vars without defaults in the shared env schema; absence makes the
+// src/server import itself throw before any CLI code can run.
+const REQUIRED_ENV_VARS = [
+ "DATABASE_URL",
+ "CLICKHOUSE_URL",
+ "CLICKHOUSE_USER",
+ "CLICKHOUSE_PASSWORD",
+];
+
+// === undefined, not falsy: empty strings are valid for some of these
+// (e.g. passwordless local ClickHouse) and pass the zod schema; only
+// absence makes the src/server import throw. Malformed present values are
+// handled by the import catch below.
+const missing = REQUIRED_ENV_VARS.filter(
+ (name) => process.env[name] === undefined,
+);
+if (missing.length > 0) {
+ console.error(
+ `error: missing env vars: ${missing.join(", ")} — is the repo-root .env present?`,
+ );
+ console.error(`fix: ${ENV_FIX}`);
+ process.exitCode = 1;
+} else {
+ // winston's console transport writes to stdout and src/server logs during
+ // import; --json promises only the JSON summary on stdout, so raise the
+ // level before anything loads (cli-main silences transports as a backstop).
+
+ if (process.argv.includes("--json")) {
+ // unconditional: a user-set info/debug level would otherwise pollute the
+ // JSON-only stdout contract during the dynamic import below
+ // eslint-disable-next-line turbo/no-undeclared-env-vars
+ process.env.LANGFUSE_LOG_LEVEL = "error";
+ }
+ import("./cli-main.js")
+ .then((cliMain) => cliMain.run())
+ .catch((error: unknown) => {
+ // Residual env-schema failures (malformed values) and any other
+ // import-time crash still get an actionable line instead of nothing.
+ const message =
+ error instanceof Error ? error.message : String(error ?? "unknown");
+ console.error(`error: failed to start the seed CLI: ${message}`);
+ console.error(`fix: ${ENV_FIX}`);
+ process.exitCode = 1;
+ });
+}
diff --git a/packages/shared/scripts/seeder/doctor.ts b/packages/shared/scripts/seeder/doctor.ts
new file mode 100644
index 0000000000..7179b5a1d7
--- /dev/null
+++ b/packages/shared/scripts/seeder/doctor.ts
@@ -0,0 +1,427 @@
+import { prisma } from "../../src/db";
+import { clickhouseClient, redis } from "../../src/server";
+import { SeedError } from "./scenarios/types";
+
+export type CheckStatus = "pass" | "warn" | "fail";
+
+export type CheckResult = {
+ name: string;
+ status: CheckStatus;
+ detail: string;
+ fix?: string;
+};
+
+const FIX = {
+ envFile: "cp .env.dev.example .env (then review required values)",
+ infraUp: "pnpm run infra:dev:up",
+ chMigrate: "pnpm --filter=shared run ch:up",
+ chDevTables: "pnpm --filter=shared run ch:dev-tables",
+ dbMigrate: "pnpm --filter=shared run db:migrate",
+ dbSeed:
+ "pnpm --filter=shared run db:seed (creates the default seed projects)",
+ devWeb: "pnpm run dev:web",
+};
+
+const withTimeout = async <T>(promise: Promise<T>, ms: number): Promise<T> => {
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ return await Promise.race([
+ promise,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`timed out after ${ms}ms`)),
+ ms,
+ );
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+};
+
+const checkEnvFile = (): CheckResult => {
+ // Keep in sync with REQUIRED_ENV_VARS in ../cli.ts (the bootstrap checks
+ // them before importing src/server, whose env schema would otherwise throw).
+ // === undefined, not falsy — empty strings are valid for some of these
+ // (matches the bootstrap precheck in ../cli.ts)
+ const missing = [
+ "DATABASE_URL",
+ "CLICKHOUSE_URL",
+ "CLICKHOUSE_USER",
+ "CLICKHOUSE_PASSWORD",
+ ].filter((name) => process.env[name] === undefined);
+ return missing.length === 0
+ ? { name: "env", status: "pass", detail: "required env vars present" }
+ : {
+ name: "env",
+ status: "fail",
+ detail: `missing env vars: ${missing.join(", ")} — is the repo-root .env present?`,
+ fix: FIX.envFile,
+ };
+};
+
+const checkPostgres = async (): Promise<CheckResult> => {
+ try {
+ await withTimeout(prisma.$queryRaw`SELECT 1`, 4000);
+ return { name: "postgres", status: "pass", detail: "reachable" };
+ } catch (error) {
+ return {
+ name: "postgres",
+ status: "fail",
+ detail: `cannot reach Postgres: ${(error as Error).message}`,
+ fix: FIX.infraUp,
+ };
+ }
+};
+
+const checkMigrations = async (): Promise<CheckResult> => {
+ try {
+ const rows = await withTimeout(
+ prisma.$queryRaw<
+ { count: bigint }[]
+ >`SELECT count(*)::bigint AS count FROM _prisma_migrations WHERE finished_at IS NOT NULL`,
+ 4000,
+ );
+ const applied = Number(rows[0]?.count ?? 0);
+ return applied > 0
+ ? {
+ name: "postgres-migrations",
+ status: "pass",
+ detail: `${applied} migrations applied`,
+ }
+ : {
+ name: "postgres-migrations",
+ status: "fail",
+ detail: "no applied migrations found",
+ fix: FIX.dbMigrate,
+ };
+ } catch (error) {
+ return {
+ name: "postgres-migrations",
+ status: "fail",
+ detail: `cannot read _prisma_migrations: ${(error as Error).message}`,
+ fix: FIX.dbMigrate,
+ };
+ }
+};
+
+const checkProject = async (projectId: string): Promise<CheckResult> => {
+ try {
+ const project = await withTimeout(
+ prisma.project.findUnique({ where: { id: projectId } }),
+ 4000,
+ );
+ return project
+ ? {
+ name: "project",
+ status: "pass",
+ detail: `project ${projectId} exists`,
+ }
+ : {
+ name: "project",
+ status: "fail",
+ detail: `project ${projectId} not found in Postgres`,
+ fix: `${FIX.dbSeed} — or pass an existing project via --project <id>`,
+ };
+ } catch (error) {
+ // checkPostgres already proves connectivity, so a failure here is most
+ // likely a missing table (Prisma P2021 — migrations not applied); only
+ // P1xxx codes indicate connection-level problems.
+ const prismaCode = (error as { code?: string }).code ?? "";
+ return {
+ name: "project",
+ status: "fail",
+ detail: (error as Error).message,
+ fix: prismaCode.startsWith("P1") ? FIX.infraUp : FIX.dbMigrate,
+ };
+ }
+};
+
+const fetchClickhouseTables = async (): Promise<Set<string>> => {
+ const result = await withTimeout(
+ clickhouseClient().query({
+ query: `SELECT name FROM system.tables WHERE database = currentDatabase() AND name IN ('traces', 'observations', 'scores', 'events_full', 'events_core')`,
+ format: "JSONEachRow",
+ }),
+ 4000,
+ );
+ const rows = await result.json<{ name: string }>();
+ return new Set(rows.map((row) => row.name));
+};
+
+const checkClickhouse = async (): Promise<{
+ connectivity: CheckResult;
+ legacyTables: CheckResult;
+ v4Tables: CheckResult;
+}> => {
+ let tables: Set<string>;
+ try {
+ tables = await fetchClickhouseTables();
+ } catch (error) {
+ const fail: CheckResult = {
+ name: "clickhouse",
+ status: "fail",
+ detail: `cannot reach ClickHouse: ${(error as Error).message}`,
+ fix: FIX.infraUp,
+ };
+ return {
+ connectivity: fail,
+ legacyTables: {
+ name: "clickhouse-tables",
+ status: "fail",
+ detail: "skipped (no connection)",
+ // migration commands need a reachable ClickHouse; fix the root cause
+ fix: FIX.infraUp,
+ },
+ v4Tables: {
+ name: "clickhouse-v4-tables",
+ status: "warn",
+ detail: "skipped (no connection)",
+ fix: FIX.infraUp,
+ },
+ };
+ }
+
+ const legacyMissing = ["traces", "observations", "scores"].filter(
+ (table) => !tables.has(table),
+ );
+ const v4Missing = ["events_full", "events_core"].filter(
+ (table) => !tables.has(table),
+ );
+
+ return {
+ connectivity: { name: "clickhouse", status: "pass", detail: "reachable" },
+ legacyTables:
+ legacyMissing.length === 0
+ ? {
+ name: "clickhouse-tables",
+ status: "pass",
+ detail: "traces/observations/scores present",
+ }
+ : {
+ name: "clickhouse-tables",
+ status: "fail",
+ detail: `missing tables: ${legacyMissing.join(", ")} — migrations not applied`,
+ fix: FIX.chMigrate,
+ },
+ v4Tables:
+ v4Missing.length === 0
+ ? {
+ name: "clickhouse-v4-tables",
+ status: "pass",
+ detail: "events_full/events_core present",
+ }
+ : {
+ name: "clickhouse-v4-tables",
+ status: "warn",
+ detail: `missing v4 dev tables: ${v4Missing.join(", ")} — --v4 scenarios unavailable`,
+ fix: FIX.chDevTables,
+ },
+ };
+};
+
+const checkClickhouseMemory = async (): Promise<CheckResult> => {
+ try {
+ const result = await withTimeout(
+ clickhouseClient().query({
+ query: `SELECT
+ anyIf(value, metric = 'MemoryResident') AS resident,
+ greatest(anyIf(value, metric = 'CGroupMemoryTotal'), anyIf(value, metric = 'OSMemoryTotal')) AS total
+ FROM system.asynchronous_metrics
+ WHERE metric IN ('MemoryResident', 'CGroupMemoryTotal', 'OSMemoryTotal')`,
+ format: "JSONEachRow",
+ }),
+ 4000,
+ );
+ const rows = await result.json<{ resident: number; total: number }>();
+ const resident = Number(rows[0]?.resident ?? 0);
+ const total = Number(rows[0]?.total ?? 0);
+ if (total <= 0) {
+ return {
+ name: "clickhouse-memory",
+ status: "pass",
+ detail: "memory metrics unavailable (skipped)",
+ };
+ }
+ const ratio = resident / total;
+ const summary = `${(resident / 1024 ** 3).toFixed(1)} GiB of ${(total / 1024 ** 3).toFixed(1)} GiB`;
+ // Long-running local servers accumulate memory and large seeds then die
+ // with MEMORY_LIMIT_EXCEEDED even though connectivity checks pass.
+ return ratio < 0.7
+ ? { name: "clickhouse-memory", status: "pass", detail: summary }
+ : {
+ name: "clickhouse-memory",
+ status: "warn",
+ detail: `${summary} — large seeds may hit MEMORY_LIMIT_EXCEEDED`,
+ fix: "docker restart langfuse-clickhouse (frees memory; data persists on the volume)",
+ };
+ } catch {
+ return {
+ name: "clickhouse-memory",
+ status: "pass",
+ detail: "memory metrics unavailable (skipped)",
+ };
+ }
+};
+
+const checkRedis = async (): Promise<CheckResult> => {
+ if (!redis) {
+ return {
+ name: "redis",
+ status: "warn",
+ detail:
+ "redis client not configured (only needed for ingestion/worker paths)",
+ fix: FIX.infraUp,
+ };
+ }
+ try {
+ await withTimeout(redis.ping(), 2500);
+ return { name: "redis", status: "pass", detail: "reachable" };
+ } catch (error) {
+ return {
+ name: "redis",
+ status: "warn",
+ detail: `cannot reach Redis: ${(error as Error).message}`,
+ fix: FIX.infraUp,
+ };
+ }
+};
+
+const checkHttp = async (
+ name: string,
+ url: string,
+ fix: string,
+ detailOnPass: string,
+): Promise<CheckResult> => {
+ try {
+ const response = await fetch(url, { signal: AbortSignal.timeout(3000) });
+ if (!response.ok) {
+ return {
+ name,
+ status: "warn",
+ detail: `${url} returned HTTP ${response.status}`,
+ fix,
+ };
+ }
+ return { name, status: "pass", detail: detailOnPass };
+ } catch {
+ return { name, status: "warn", detail: `no response from ${url}`, fix };
+ }
+};
+
+const checkMinio = async (): Promise<CheckResult> => {
+ // CLI script, not a turbo task — probes the dev env directly.
+ // eslint-disable-next-line turbo/no-undeclared-env-vars
+ const endpoint = process.env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT;
+ if (!endpoint) {
+ return {
+ name: "blob-storage",
+ status: "warn",
+ detail:
+ "LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT not set (only needed for media/event uploads)",
+ fix: "set LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT in .env (e.g. http://localhost:9090) if media/event upload tests are needed",
+ };
+ }
+ return checkHttp(
+ "blob-storage",
+ `${endpoint.replace(/\/$/, "")}/minio/health/live`,
+ FIX.infraUp,
+ `reachable at ${endpoint}`,
+ );
+};
+
+export const runDoctor = async (
+ baseUrl: string,
+ projectId: string,
+): Promise<{ ok: boolean; checks: CheckResult[] }> => {
+ const env = checkEnvFile();
+ if (env.status === "fail") {
+ return { ok: false, checks: [env] };
+ }
+
+ const [
+ postgres,
+ migrations,
+ project,
+ clickhouse,
+ clickhouseMemory,
+ redisCheck,
+ minio,
+ web,
+ ] = await Promise.all([
+ checkPostgres(),
+ checkMigrations(),
+ checkProject(projectId),
+ checkClickhouse(),
+ checkClickhouseMemory(),
+ checkRedis(),
+ checkMinio(),
+ checkHttp(
+ "web-app",
+ `${baseUrl}/api/public/health`,
+ FIX.devWeb,
+ `responding at ${baseUrl} (deep links will work)`,
+ ),
+ ]);
+
+ const checks = [
+ env,
+ postgres,
+ migrations,
+ project,
+ clickhouse.connectivity,
+ clickhouse.legacyTables,
+ clickhouse.v4Tables,
+ clickhouseMemory,
+ redisCheck,
+ minio,
+ web,
+ ];
+ return { ok: checks.every((check) => check.status !== "fail"), checks };
+};
+
+/**
+ * Fast subset of doctor that scenario runs execute first, so a broken stack
+ * fails in seconds with the exact fix instead of a stack trace mid-insert.
+ */
+export const preflight = async (opts: {
+ projectId: string;
+ needV4: boolean;
+ log: (message: string) => void;
+}): Promise<void> => {
+ const env = checkEnvFile();
+ if (env.status === "fail") {
+ throw new SeedError(env.detail, env.fix);
+ }
+
+ const [postgres, project, clickhouse] = await Promise.all([
+ checkPostgres(),
+ checkProject(opts.projectId),
+ checkClickhouse(),
+ ]);
+
+ const required: CheckResult[] = [
+ postgres,
+ project,
+ clickhouse.connectivity,
+ clickhouse.legacyTables,
+ ];
+ if (opts.needV4) {
+ required.push({
+ ...clickhouse.v4Tables,
+ status:
+ clickhouse.v4Tables.status === "warn"
+ ? "fail"
+ : clickhouse.v4Tables.status,
+ });
+ }
+
+ const failed = required.find((check) => check.status === "fail");
+ if (failed) {
+ throw new SeedError(
+ `preflight failed [${failed.name}]: ${failed.detail}`,
+ failed.fix,
+ );
+ }
+ opts.log("preflight ok (postgres, project, clickhouse)");
+};
diff --git a/packages/shared/scripts/seeder/scenarios/event-mirror.ts b/packages/shared/scripts/seeder/scenarios/event-mirror.ts
new file mode 100644
index 0000000000..9dfbddc26a
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/event-mirror.ts
@@ -0,0 +1,140 @@
+import {
+ createEvent,
+ EventRecordInsertType,
+ ObservationRecordInsertType,
+ TraceRecordInsertType,
+} from "../../../src/server";
+
+const toMicros = (ms: number | null | undefined): number | null =>
+ ms === null || ms === undefined ? null : ms * 1000;
+
+const utf8Bytes = (value: unknown): number =>
+ typeof value === "string" ? Buffer.byteLength(value, "utf8") : 0;
+
+const sortedMetadata = (metadata: Record<string, string>) => {
+ const names = Object.keys(metadata).sort();
+ return { names, values: names.map((name) => metadata[name]) };
+};
+
+/**
+ * Mirrors v3 rows into v4 events_full following the canonical v3 -> v4
+ * mapping in clickhouse/scripts/dev-tables.sh: one synthetic trace span per
+ * trace (span_id = `t-<traceId>`, parent_span_id = '') carries the trace's
+ * name/input/output/metadata — v4 trace-level queries aggregate with
+ * `argMaxIf(..., parent_span_id = '')` — and every observation row points at
+ * a real parent, with roots re-parented onto the synthetic span. events_core
+ * fills automatically via the events_core_mv materialized view.
+ */
+export const traceToEvent = (
+ trace: TraceRecordInsertType,
+): EventRecordInsertType => {
+ const { names, values } = sortedMetadata(
+ (trace.metadata ?? {}) as Record<string, string>,
+ );
+
+ return createEvent({
+ project_id: trace.project_id,
+ trace_id: trace.id,
+ span_id: `t-${trace.id}`,
+ id: `t-${trace.id}`,
+ parent_span_id: "",
+ is_app_root: false,
+ name: trace.name ?? "",
+ trace_name: trace.name ?? "",
+ type: "SPAN",
+ environment: trace.environment ?? "default",
+ level: "DEFAULT",
+ status_message: null,
+ version: trace.version ?? null,
+ release: trace.release ?? null,
+ tags: trace.tags ?? [],
+ user_id: trace.user_id ?? null,
+ session_id: trace.session_id ?? null,
+ public: trace.public ?? false,
+ bookmarked: trace.bookmarked ?? false,
+ input: typeof trace.input === "string" ? trace.input : "",
+ output: typeof trace.output === "string" ? trace.output : "",
+ provided_model_name: null,
+ model_id: null,
+ model_parameters: "{}",
+ provided_usage_details: {},
+ usage_details: {},
+ provided_cost_details: {},
+ cost_details: {},
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ metadata_names: names,
+ metadata_values: values,
+ start_time: toMicros(trace.timestamp) ?? Date.now() * 1000,
+ end_time: null,
+ completion_start_time: null,
+ created_at: toMicros(trace.created_at) ?? Date.now() * 1000,
+ updated_at: toMicros(trace.updated_at) ?? Date.now() * 1000,
+ event_ts: toMicros(trace.event_ts) ?? Date.now() * 1000,
+ event_bytes: utf8Bytes(trace.input) + utf8Bytes(trace.output),
+ source: "API",
+ });
+};
+
+export const observationToEvent = (
+ observation: ObservationRecordInsertType,
+ trace: TraceRecordInsertType,
+): EventRecordInsertType => {
+ const isRoot = !observation.parent_observation_id;
+ // The backfill merges trace metadata into observation events
+ // (mapConcat(o.metadata, t.metadata)); mirror that with the observation
+ // taking precedence on key collisions.
+ const { names, values } = sortedMetadata({
+ ...((trace.metadata ?? {}) as Record<string, string>),
+ ...((observation.metadata ?? {}) as Record<string, string>),
+ });
+
+ return createEvent({
+ project_id: observation.project_id,
+ trace_id: observation.trace_id ?? trace.id,
+ span_id: observation.id,
+ id: observation.id,
+ // parent_span_id = '' is reserved for the synthetic trace span; root
+ // observations hang off it instead (see traceToEvent above).
+ parent_span_id: observation.parent_observation_id ?? `t-${trace.id}`,
+ is_app_root: false,
+ name: observation.name ?? "",
+ trace_name: trace.name ?? "",
+ public: trace.public ?? false,
+ bookmarked: (trace.bookmarked ?? false) && isRoot,
+ type: observation.type,
+ environment: observation.environment ?? "default",
+ level: observation.level ?? "DEFAULT",
+ status_message: observation.status_message ?? null,
+ // backfill: coalesce(o.version, t.version) — keeps the trace-level
+ // release !== version shape visible on observation events
+ version: observation.version ?? trace.version ?? null,
+ release: trace.release ?? null,
+ tags: trace.tags ?? [],
+ user_id: trace.user_id ?? null,
+ session_id: trace.session_id ?? null,
+ input: typeof observation.input === "string" ? observation.input : "",
+ output: typeof observation.output === "string" ? observation.output : "",
+ provided_model_name: observation.provided_model_name ?? null,
+ model_id: observation.internal_model_id ?? null,
+ model_parameters: observation.model_parameters ?? "{}",
+ provided_usage_details: observation.provided_usage_details ?? {},
+ usage_details: observation.usage_details ?? {},
+ provided_cost_details: observation.provided_cost_details ?? {},
+ cost_details: observation.cost_details ?? {},
+ prompt_id: observation.prompt_id ?? null,
+ prompt_name: observation.prompt_name ?? null,
+ prompt_version: observation.prompt_version ?? null,
+ metadata_names: names,
+ metadata_values: values,
+ start_time: toMicros(observation.start_time) ?? Date.now() * 1000,
+ end_time: toMicros(observation.end_time),
+ completion_start_time: toMicros(observation.completion_start_time),
+ created_at: toMicros(observation.created_at) ?? Date.now() * 1000,
+ updated_at: toMicros(observation.updated_at) ?? Date.now() * 1000,
+ event_ts: toMicros(observation.event_ts) ?? Date.now() * 1000,
+ event_bytes: utf8Bytes(observation.input) + utf8Bytes(observation.output),
+ source: "API",
+ });
+};
diff --git a/packages/shared/scripts/seeder/scenarios/index.ts b/packages/shared/scripts/seeder/scenarios/index.ts
new file mode 100644
index 0000000000..f49cd6e4c0
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/index.ts
@@ -0,0 +1,15 @@
+import { longSessionScenario } from "./long-session";
+import { manyTracesScenario } from "./many-traces";
+import { traceTreeScenario } from "./trace-tree";
+import { ScenarioDefinition } from "./types";
+
+/**
+ * Scenario registry. Names are part of the CLI contract — additive only.
+ */
+export const scenarios: Record<string, ScenarioDefinition> = {
+ "trace-tree": traceTreeScenario,
+ "long-session": longSessionScenario,
+ "many-traces": manyTracesScenario,
+};
+
+export * from "./types";
diff --git a/packages/shared/scripts/seeder/scenarios/long-session.ts b/packages/shared/scripts/seeder/scenarios/long-session.ts
new file mode 100644
index 0000000000..c807dbc019
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/long-session.ts
@@ -0,0 +1,499 @@
+import { prisma } from "../../../src/db";
+import {
+ createTrace,
+ createObservation,
+ createTraceScore,
+ createSessionScore,
+ createTracesCh,
+ createObservationsCh,
+ createScoresCh,
+ createEventsCh,
+ EventRecordInsertType,
+ ObservationRecordInsertType,
+ ScoreRecordInsertType,
+ TraceRecordInsertType,
+} from "../../../src/server";
+import { observationToEvent, traceToEvent } from "./event-mirror";
+import { buildPayload, PayloadStyle } from "./payload";
+import { jitter, Rng, utcDayStartMs } from "./rng";
+import {
+ chunk,
+ ScenarioContext,
+ ScenarioDefinition,
+ SeedError,
+ SeedSummary,
+} from "./types";
+import { countRows, sessionLink, traceLink } from "./verify";
+
+const TRACE_NAMES = [
+ "answer-support-question",
+ "summarize-thread",
+ "classify-intent",
+ "draft-reply",
+ "lookup-order",
+ "escalate-to-human",
+];
+
+const run = async (
+ ctx: ScenarioContext,
+ params: Record<string, string | number | boolean>,
+): Promise<SeedSummary> => {
+ const startedAt = Date.now();
+ const traceCount = params["traces"] as number;
+ const observationsPerTrace = params["observations-per-trace"] as number;
+ const payloadBytes = params["payload-bytes"] as number;
+ const windowMinutes = params["minutes"] as number;
+ const withV4 = params["v4"] as boolean;
+ const sessionId =
+ (params["session-id"] as string) || `${ctx.idPrefix}-session`;
+
+ if (traceCount < 1) {
+ throw new SeedError(
+ `--traces must be >= 1, got ${traceCount}`,
+ "pass a positive integer, e.g. --traces 120",
+ );
+ }
+ if (observationsPerTrace < 0) {
+ throw new SeedError(
+ `--observations-per-trace must be >= 0, got ${observationsPerTrace}`,
+ "pass 0 for traces without observations, or a positive integer",
+ );
+ }
+ if (windowMinutes < 1) {
+ throw new SeedError(
+ `--minutes must be >= 1, got ${windowMinutes}`,
+ "negative windows would place traces in the future, hidden by UI time filters",
+ );
+ }
+ if (payloadBytes < 0 || payloadBytes > 50_000_000) {
+ throw new SeedError(
+ `--payload-bytes must be between 0 and 50000000 (50 MB), got ${payloadBytes}`,
+ "larger payloads exceed V8 string limits during generation",
+ );
+ }
+
+ if (ctx.dryRun) {
+ // counts are derivable from the flags — skip payload/array generation
+ const firstTraceTimestamp =
+ utcDayStartMs() - windowMinutes * 60 * 1000 + jitter(ctx.seed, 0, 500);
+ return {
+ scenario: "long-session",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: Array.from(
+ { length: Math.min(traceCount, 5) },
+ (_, i) => `${ctx.idPrefix}-t${i}`,
+ ),
+ sessionIds: [sessionId],
+ counts: {
+ sessions: 1,
+ traces: traceCount,
+ observations: traceCount * observationsPerTrace,
+ scores: Math.ceil(traceCount / 3) + Math.ceil(traceCount / 5) + 1,
+ events: withV4 ? traceCount + traceCount * observationsPerTrace : 0,
+ },
+ verified: {},
+ links: [
+ sessionLink(ctx, sessionId),
+ traceLink(ctx, `${ctx.idPrefix}-t0`, firstTraceTimestamp),
+ ],
+ dryRun: true,
+ durationMs: Date.now() - startedAt,
+ };
+ }
+
+ const rng = new Rng(ctx.seed);
+ const sessionStart = utcDayStartMs() - windowMinutes * 60 * 1000;
+ const stepMs = (windowMinutes * 60 * 1000) / Math.max(traceCount, 1);
+ const users = Array.from(
+ { length: 8 },
+ (_, i) => `user-${ctx.idPrefix}-${i}`,
+ );
+
+ const traces: TraceRecordInsertType[] = [];
+ const observations: ObservationRecordInsertType[] = [];
+ const scores: ScoreRecordInsertType[] = [];
+ const events: EventRecordInsertType[] = [];
+
+ for (let t = 0; t < traceCount; t++) {
+ const traceId = `${ctx.idPrefix}-t${t}`;
+ // jitter() not rng: these timestamps land in ClickHouse ORDER BY keys
+ // (events_full start_time); stream-position randomness would re-key rows
+ // when unrelated flags change between re-runs with the same id prefix.
+ const timestamp =
+ sessionStart + Math.floor(t * stepMs) + jitter(ctx.seed, t, 500);
+ const isHuge = t > 0 && t % 17 === 0;
+ const style: PayloadStyle =
+ t % 7 === 3 ? "unicode" : rng.bool(0.6) ? "json" : "text";
+ const name =
+ t % 9 === 4
+ ? `${rng.pick(TRACE_NAMES)}-with-a-very-long-descriptive-name-${"y".repeat(120)}`
+ : t % 7 === 3
+ ? `多言語サポート ${rng.pick(TRACE_NAMES)}`
+ : rng.pick(TRACE_NAMES);
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ session_id: sessionId,
+ timestamp,
+ name,
+ user_id: rng.pick(users),
+ // release !== version on some traces (a v4 regression shape)
+ release: "v1.2.3",
+ version: t % 11 === 5 ? "v1.2.4" : "v1.2.3",
+ tags: ["seed", "long-session"],
+ public: false,
+ bookmarked: false,
+ metadata: {
+ scenario: "long-session",
+ turn: String(t),
+ },
+ input: buildPayload(
+ style,
+ isHuge ? 100_000 : rng.int(Math.min(300, payloadBytes), payloadBytes),
+ rng,
+ ),
+ output: buildPayload(
+ style,
+ rng.int(Math.min(200, payloadBytes), payloadBytes),
+ rng,
+ ),
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ });
+ traces.push(trace);
+
+ const rootObservationIndex = observations.length;
+ let maxChildEndTime = 0;
+ for (let o = 0; o < observationsPerTrace; o++) {
+ const observationId = `${traceId}-o${o}`;
+ const isRoot = o === 0;
+ // jitter() not rng for isGeneration/type: observation `type` is the
+ // 2nd v3 observations ORDER BY column, and stream-position randomness
+ // (shifted by --payload-bytes) would re-key rows on re-run.
+ const isGeneration =
+ o === 1 || (o > 1 && jitter(ctx.seed, t * 311 + o, 9) < 3);
+ const startTime =
+ timestamp + o * 350 + jitter(ctx.seed, t * 131 + o, 100);
+ const endTime =
+ startTime + (isGeneration ? rng.int(700, 3500) : rng.int(10, 300));
+ if (!isRoot) maxChildEndTime = Math.max(maxChildEndTime, endTime);
+ const hasError = t % 13 === 6 && isGeneration;
+ const usageInput = rng.int(100, 4000);
+ const usageOutput = rng.int(50, 2000);
+
+ observations.push(
+ createObservation({
+ id: observationId,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ type: isRoot
+ ? "AGENT"
+ : isGeneration
+ ? "GENERATION"
+ : (["TOOL", "SPAN", "EVENT"] as const)[
+ jitter(ctx.seed, t * 977 + o, 2)
+ ],
+ parent_observation_id: isRoot ? null : `${traceId}-o0`,
+ name: isRoot
+ ? "session-turn"
+ : isGeneration
+ ? "gpt-4o-completion"
+ : rng.pick(["fetch-context", "log-event", "format-reply"]),
+ start_time: startTime,
+ end_time: endTime,
+ completion_start_time: isGeneration
+ ? startTime + rng.int(90, 350)
+ : null,
+ level: hasError ? "ERROR" : "DEFAULT",
+ status_message: hasError ? "Model timeout, retried once" : null,
+ version: null,
+ input: isGeneration
+ ? JSON.stringify({
+ messages: [
+ {
+ role: "user",
+ content: buildPayload("text", rng.int(100, 800), rng),
+ },
+ ],
+ })
+ : null,
+ output: isGeneration
+ ? buildPayload("text", rng.int(100, 600), rng)
+ : null,
+ metadata: { scenario: "long-session", turn: String(t) },
+ provided_model_name: isGeneration ? "gpt-4o" : null,
+ internal_model_id: null,
+ model_parameters: isGeneration
+ ? JSON.stringify({ temperature: 0.7 })
+ : "{}",
+ provided_usage_details: isGeneration
+ ? {
+ input: usageInput,
+ output: usageOutput,
+ total: usageInput + usageOutput,
+ }
+ : {},
+ usage_details: isGeneration
+ ? {
+ input: usageInput,
+ output: usageOutput,
+ total: usageInput + usageOutput,
+ }
+ : {},
+ provided_cost_details: isGeneration
+ ? { input: usageInput * 2e-6, output: usageOutput * 6e-6 }
+ : {},
+ cost_details: isGeneration
+ ? {
+ input: usageInput * 2e-6,
+ output: usageOutput * 6e-6,
+ total: usageInput * 2e-6 + usageOutput * 6e-6,
+ }
+ : {},
+ total_cost: isGeneration
+ ? usageInput * 2e-6 + usageOutput * 6e-6
+ : null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ }),
+ );
+ }
+
+ // The root "session-turn" span must cover its children, otherwise the
+ // waterfall shows children running after their parent already ended.
+ if (observationsPerTrace > 1) {
+ observations[rootObservationIndex].end_time = maxChildEndTime + 25;
+ }
+
+ if (t % 3 === 0) {
+ scores.push(
+ createTraceScore({
+ id: `${traceId}-score-helpfulness`,
+ project_id: ctx.projectId,
+ trace_id: traceId,
+ environment: ctx.environment,
+ name: "helpfulness",
+ value: Math.round(rng.next() * 100) / 100,
+ data_type: "NUMERIC",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp,
+ }),
+ );
+ }
+ if (t % 5 === 0) {
+ scores.push(
+ createTraceScore({
+ id: `${traceId}-score-intent`,
+ project_id: ctx.projectId,
+ trace_id: traceId,
+ environment: ctx.environment,
+ name: "intent",
+ value: 1,
+ string_value: rng.pick(["billing", "refund", "technical", "other"]),
+ data_type: "CATEGORICAL",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp,
+ }),
+ );
+ }
+ }
+
+ scores.push(
+ createSessionScore({
+ id: `${ctx.idPrefix}-session-quality`,
+ project_id: ctx.projectId,
+ session_id: sessionId,
+ environment: ctx.environment,
+ name: "session-quality",
+ value: Math.round(rng.next() * 100) / 100,
+ data_type: "NUMERIC",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp: sessionStart,
+ }),
+ );
+
+ if (withV4) {
+ const tracesById = new Map(traces.map((tr) => [tr.id, tr]));
+ for (const trace of traces) {
+ events.push(traceToEvent(trace));
+ }
+ for (const obs of observations) {
+ const trace = obs.trace_id ? tracesById.get(obs.trace_id) : undefined;
+ if (trace) events.push(observationToEvent(obs, trace));
+ }
+ }
+
+ const counts: Record<string, number> = {
+ sessions: 1,
+ traces: traces.length,
+ observations: observations.length,
+ scores: scores.length,
+ events: events.length,
+ };
+
+ const links = [
+ sessionLink(ctx, sessionId),
+ traceLink(ctx, traces[0].id, traces[0].timestamp as number),
+ ];
+
+ // The session detail page 404s without the Postgres trace_sessions row.
+ await prisma.traceSession.upsert({
+ where: { id_projectId: { id: sessionId, projectId: ctx.projectId } },
+ update: {},
+ create: {
+ id: sessionId,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ createdAt: new Date(sessionStart),
+ },
+ });
+
+ ctx.log(
+ `writing 1 session, ${traces.length} traces, ${observations.length} observations, ${scores.length} scores${withV4 ? `, ${events.length} events` : ""}`,
+ );
+ for (const batch of chunk(traces, 1000)) {
+ await createTracesCh(batch);
+ }
+ for (const batch of chunk(observations, 1000)) {
+ await createObservationsCh(batch);
+ }
+ await createScoresCh(scores);
+ for (const batch of chunk(events, 500)) {
+ await createEventsCh(batch);
+ }
+
+ // uniqExact(id): count() would see pre-merge ReplacingMergeTree duplicates
+ // after re-runs with the same id prefix.
+ const verified: Record<string, number> = {
+ traces: await countRows(
+ "traces",
+ `project_id = {projectId: String} AND session_id = {sessionId: String}`,
+ { projectId: ctx.projectId, sessionId },
+ "uniqExact(id)",
+ ),
+ observations: await countRows(
+ "observations",
+ `project_id = {projectId: String} AND trace_id IN {traceIds: Array(String)}`,
+ { projectId: ctx.projectId, traceIds: traces.map((tr) => tr.id) },
+ "uniqExact(id)",
+ ),
+ scores: await countRows(
+ "scores",
+ `project_id = {projectId: String} AND (trace_id IN {traceIds: Array(String)} OR session_id = {sessionId: String})`,
+ {
+ projectId: ctx.projectId,
+ traceIds: traces.map((tr) => tr.id),
+ sessionId,
+ },
+ "uniqExact(id)",
+ ),
+ };
+ if (withV4) {
+ verified.events = await countRows(
+ "events_full",
+ `project_id = {projectId: String} AND session_id = {sessionId: String}`,
+ { projectId: ctx.projectId, sessionId },
+ "uniqExact(span_id)",
+ );
+ }
+
+ if (verified.traces < traces.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${traces.length} session traces, found ${verified.traces}`,
+ );
+ }
+ if (verified.observations < observations.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${observations.length} observations, found ${verified.observations}`,
+ );
+ }
+ if (verified.scores < scores.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${scores.length} scores, found ${verified.scores}`,
+ );
+ }
+ if (withV4 && verified.events < events.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${events.length} events_full rows, found ${verified.events}`,
+ );
+ }
+
+ return {
+ scenario: "long-session",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: traces.slice(0, 5).map((t) => t.id),
+ sessionIds: [sessionId],
+ counts,
+ verified,
+ links,
+ dryRun: false,
+ durationMs: Date.now() - startedAt,
+ };
+};
+
+export const longSessionScenario: ScenarioDefinition = {
+ name: "long-session",
+ description:
+ "One session with many traces for session-detail and virtualization work: mixed payload sizes (incl. 100KB outliers), long and unicode trace names, generation usage/cost, trace + session scores. Creates the required Postgres trace_sessions row.",
+ supportsV4: true,
+ flags: [
+ {
+ flag: "traces",
+ type: "number",
+ default: 120,
+ description: "traces in the session",
+ },
+ {
+ flag: "observations-per-trace",
+ type: "number",
+ default: 6,
+ description: "observations per trace",
+ },
+ {
+ flag: "payload-bytes",
+ type: "number",
+ default: 2_000,
+ description:
+ "approx max bytes for regular trace payloads (generation granularity is ~one paragraph/object, so very small values overshoot)",
+ },
+ {
+ flag: "minutes",
+ type: "number",
+ default: 180,
+ description: "session time window ending at UTC midnight of today",
+ },
+ {
+ flag: "session-id",
+ type: "string",
+ default: "",
+ description: "override the generated session id",
+ },
+ {
+ flag: "v4",
+ type: "boolean",
+ default: false,
+ description: "also mirror traces into v4 events tables",
+ },
+ ],
+ run,
+};
diff --git a/packages/shared/scripts/seeder/scenarios/many-traces.ts b/packages/shared/scripts/seeder/scenarios/many-traces.ts
new file mode 100644
index 0000000000..098ed02f3f
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/many-traces.ts
@@ -0,0 +1,280 @@
+import { readFileSync } from "fs";
+import path from "path";
+import { prisma } from "../../../src/db";
+import { clickhouseClient } from "../../../src/server";
+import { ClickHouseQueryBuilder } from "../utils/clickhouse-builder";
+import {
+ ScenarioContext,
+ ScenarioDefinition,
+ SeedError,
+ SeedSummary,
+} from "./types";
+import { utcDayStartMs } from "./rng";
+import { countRows, escapeLike, tracesListLink } from "./verify";
+
+/**
+ * Loads the bundled large fixtures, sliced exactly like SeederOrchestrator so
+ * the inline INSERT ... SELECT FROM numbers() SQL stays under ClickHouse's
+ * max_query_size.
+ */
+const loadFileContent = () => {
+ const utilsDir = path.join(__dirname, "../utils");
+ const nestedJson = JSON.parse(
+ readFileSync(path.join(utilsDir, "nested_json.json"), "utf-8"),
+ );
+ const chatMlJson = JSON.parse(
+ readFileSync(path.join(utilsDir, "chat_ml_json.json"), "utf-8"),
+ );
+ return {
+ heavyMarkdown: readFileSync(path.join(utilsDir, "markdown.txt"), "utf-8"),
+ nestedJson: {
+ ...nestedJson,
+ products: nestedJson.products?.slice(0, 3) ?? [],
+ },
+ chatMlJson: {
+ ...chatMlJson,
+ messages: chatMlJson.messages?.slice(0, 4) ?? [],
+ },
+ };
+};
+
+const run = async (
+ ctx: ScenarioContext,
+ params: Record<string, string | number | boolean>,
+): Promise<SeedSummary> => {
+ const startedAt = Date.now();
+ const count = params["count"] as number;
+ const days = params["days"] as number;
+ const observationsPerTrace = params["observations-per-trace"] as number;
+ const scoresPerTrace = params["scores-per-trace"] as number;
+ const richPayloads = params["rich-payloads"] as boolean;
+
+ if (count < 1) {
+ throw new SeedError(
+ `--count must be >= 1, got ${count}`,
+ "pass a positive integer, e.g. --count 10000",
+ );
+ }
+ if (observationsPerTrace < 0 || scoresPerTrace < 0) {
+ throw new SeedError(
+ `--observations-per-trace and --scores-per-trace must be >= 0, got ${observationsPerTrace} / ${scoresPerTrace}`,
+ "pass 0 to seed traces without observations/scores, or a positive integer",
+ );
+ }
+ if (days < 0) {
+ throw new SeedError(
+ `--days must be >= 0, got ${days}`,
+ "negative windows would place traces in the future, hidden by UI time filters",
+ );
+ }
+
+ const builder = new ClickHouseQueryBuilder();
+ const fileContent = richPayloads ? loadFileContent() : undefined;
+ const counts: Record<string, number> = {
+ traces: count,
+ observations: count * observationsPerTrace,
+ scores: count * scoresPerTrace,
+ };
+ const links = [tracesListLink(ctx)];
+
+ if (ctx.dryRun) {
+ return {
+ scenario: "many-traces",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: [],
+ sessionIds: Array.from(
+ { length: 5 },
+ (_, i) => `${ctx.idPrefix}-session_${i}`,
+ ),
+ counts,
+ verified: {},
+ links,
+ dryRun: true,
+ durationMs: Date.now() - startedAt,
+ };
+ }
+
+ // Ids are `{id-prefix}-trace-bulk-{n}-{projectId-suffix}`: re-runs with the
+ // same prefix and count overwrite, a different --id-prefix adds an
+ // independent copy.
+ ctx.log(
+ `bulk-inserting ${count} traces, ${counts.observations} observations, ${counts.scores} scores over ${days} day(s)`,
+ );
+ // One shared anchor so the three INSERT statements cannot straddle a UTC
+ // midnight and anchor observations/scores to a different day than traces.
+ const bulkOpts = {
+ numberOfDays: days,
+ idPrefix: ctx.idPrefix,
+ anchorSeconds: Math.floor(utcDayStartMs() / 1000),
+ seed: ctx.seed,
+ };
+ // Link ~10% of generations to REAL prompts — fabricated prompt ids would
+ // silently break the trace-detail prompt badge. No prompts -> NULL columns.
+ const prompts = await prisma.prompt.findMany({
+ where: { projectId: ctx.projectId },
+ select: { id: true, name: true, version: true },
+ orderBy: { createdAt: "asc" },
+ take: 10,
+ });
+ const queries = [
+ builder.buildBulkTracesInsert(
+ ctx.projectId,
+ count,
+ ctx.environment,
+ fileContent,
+ bulkOpts,
+ ),
+ ];
+ if (observationsPerTrace > 0) {
+ queries.push(
+ builder.buildBulkObservationsInsert(
+ ctx.projectId,
+ count,
+ observationsPerTrace,
+ ctx.environment,
+ fileContent,
+ { ...bulkOpts, prompts },
+ ),
+ );
+ }
+ if (scoresPerTrace > 0) {
+ queries.push(
+ builder.buildBulkScoresInsert(
+ ctx.projectId,
+ count,
+ scoresPerTrace,
+ ctx.environment,
+ {
+ ...bulkOpts,
+ observationsPerTrace,
+ },
+ ),
+ );
+ }
+ // The bulk SQL references {id-prefix}-session_0..99 on ~30% of traces; the
+ // session detail page 404s without the Postgres trace_sessions rows
+ // (same contract long-session handles for its own session).
+ await prisma.traceSession.createMany({
+ data: Array.from({ length: 100 }, (_, i) => ({
+ id: `${ctx.idPrefix}-session_${i}`,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ })),
+ skipDuplicates: true,
+ });
+
+ for (const query of queries) {
+ await clickhouseClient().command({
+ query,
+ clickhouse_settings: { wait_end_of_query: 1 },
+ });
+ }
+
+ const idSuffix = escapeLike(ctx.projectId.slice(-8));
+ const verified: Record<string, number> = {
+ traces: await countRows(
+ "traces",
+ `project_id = {projectId: String} AND id LIKE {prefix: String}`,
+ {
+ projectId: ctx.projectId,
+ prefix: `${escapeLike(ctx.idPrefix)}-trace-bulk-%-${idSuffix}`,
+ },
+ "uniqExact(id)",
+ ),
+ observations: await countRows(
+ "observations",
+ `project_id = {projectId: String} AND id LIKE {prefix: String}`,
+ {
+ projectId: ctx.projectId,
+ prefix: `${escapeLike(ctx.idPrefix)}-obs-bulk-%-${idSuffix}`,
+ },
+ "uniqExact(id)",
+ ),
+ scores: await countRows(
+ "scores",
+ `project_id = {projectId: String} AND id LIKE {prefix: String}`,
+ {
+ projectId: ctx.projectId,
+ prefix: `${escapeLike(ctx.idPrefix)}-score-bulk-%-${idSuffix}`,
+ },
+ "uniqExact(id)",
+ ),
+ };
+
+ if (verified.traces < count) {
+ throw new SeedError(
+ `Readback mismatch: expected at least ${count} bulk traces, found ${verified.traces}`,
+ );
+ }
+ if (verified.observations < counts.observations) {
+ throw new SeedError(
+ `Readback mismatch: expected ${counts.observations} bulk observations, found ${verified.observations}`,
+ );
+ }
+ if (verified.scores < counts.scores) {
+ throw new SeedError(
+ `Readback mismatch: expected ${counts.scores} bulk scores, found ${verified.scores}`,
+ );
+ }
+
+ return {
+ scenario: "many-traces",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: [],
+ sessionIds: Array.from(
+ { length: 5 },
+ (_, i) => `${ctx.idPrefix}-session_${i}`,
+ ),
+ counts,
+ verified,
+ links,
+ dryRun: false,
+ durationMs: Date.now() - startedAt,
+ };
+};
+
+export const manyTracesScenario: ScenarioDefinition = {
+ name: "many-traces",
+ description:
+ "Bulk traces/observations/scores for trace-list and filter performance work: ClickHouse numbers() SQL, fast even for 100k+ traces, deterministic ids so re-runs do not duplicate.",
+ supportsV4: false,
+ flags: [
+ {
+ flag: "count",
+ type: "number",
+ default: 10_000,
+ description: "number of traces",
+ },
+ {
+ flag: "days",
+ type: "number",
+ default: 3,
+ description: "spread timestamps over the past N days",
+ },
+ {
+ flag: "observations-per-trace",
+ type: "number",
+ default: 5,
+ description: "observations per trace",
+ },
+ {
+ flag: "scores-per-trace",
+ type: "number",
+ default: 2,
+ description: "scores per trace",
+ },
+ {
+ flag: "rich-payloads",
+ type: "boolean",
+ default: false,
+ description: "embed bundled markdown/JSON fixtures as payloads",
+ },
+ ],
+ run,
+};
diff --git a/packages/shared/scripts/seeder/scenarios/payload.ts b/packages/shared/scripts/seeder/scenarios/payload.ts
new file mode 100644
index 0000000000..c2f95335c5
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/payload.ts
@@ -0,0 +1,128 @@
+import { Rng } from "./rng";
+
+export type PayloadStyle = "json" | "text" | "malformed" | "unicode";
+
+export const PAYLOAD_STYLES: PayloadStyle[] = [
+ "json",
+ "text",
+ "malformed",
+ "unicode",
+];
+
+const WORDS = [
+ "retrieval",
+ "latency",
+ "guardrail",
+ "embedding",
+ "fallback",
+ "router",
+ "checkout",
+ "invoice",
+ "escalation",
+ "refund",
+ "summarize",
+ "classify",
+ "rerank",
+ "citation",
+ "groundedness",
+];
+
+const UNICODE_SNIPPETS = [
+ "翻訳されたユーザー入力テキスト",
+ "مرحبا بالعالم، هذا اختبار",
+ "Résumé détaillé — données confirmées",
+ "Привет, мир! Тестовые данные",
+ "🤖🔍📊 emoji-heavy content 🚀✅❌",
+ "𝔘𝔫𝔦𝔠𝔬𝔡𝔢 𝕞𝕒𝕥𝕙 𝖘𝖙𝖞𝖑𝖊𝖉",
+ 'escaped-looking: \\u00e9\\u4e2d\\ud83d\\ude00 and raw "quotes"',
+ "combining: ééé́ ZWJ: 👩‍💻",
+];
+
+const sentence = (rng: Rng, words: number): string => {
+ const parts: string[] = [];
+ for (let i = 0; i < words; i++) parts.push(rng.pick(WORDS));
+ return parts.join(" ");
+};
+
+const buildJsonPayload = (rng: Rng, targetBytes: number): string => {
+ const root: Record<string, unknown> = {
+ schemaVersion: 2,
+ request: {
+ query: sentence(rng, 8),
+ filters: { region: rng.pick(["eu", "us", "apac"]), beta: rng.bool() },
+ },
+ items: [] as unknown[],
+ };
+ const items = root.items as unknown[];
+ let size = JSON.stringify(root).length;
+ let index = 0;
+ while (size < targetBytes) {
+ const item = {
+ index,
+ id: `item-${index}-${rng.int(1000, 9999)}`,
+ score: Math.round(rng.next() * 1000) / 1000,
+ status: rng.pick(["ok", "retried", "failed", "skipped"]),
+ tags: [rng.pick(WORDS), rng.pick(WORDS)],
+ nested: {
+ depth1: {
+ depth2: {
+ note: sentence(rng, rng.int(4, 12)),
+ stringifiedJson: JSON.stringify({
+ inner: sentence(rng, 3),
+ n: index,
+ }),
+ },
+ },
+ },
+ };
+ items.push(item);
+ size += JSON.stringify(item).length + 1;
+ index++;
+ }
+ return JSON.stringify(root);
+};
+
+const buildTextPayload = (rng: Rng, targetBytes: number): string => {
+ const paragraphs: string[] = [];
+ let size = 0;
+ while (size < targetBytes) {
+ const paragraph = `## ${sentence(rng, 3)}\n\n${sentence(rng, rng.int(30, 80))}.`;
+ paragraphs.push(paragraph);
+ size += paragraph.length + 2;
+ }
+ return paragraphs.join("\n\n");
+};
+
+const buildUnicodePayload = (rng: Rng, targetBytes: number): string => {
+ const parts: string[] = [];
+ let size = 0;
+ while (size < targetBytes) {
+ const part = `${rng.pick(UNICODE_SNIPPETS)} ${sentence(rng, 4)}`;
+ parts.push(part);
+ size += Buffer.byteLength(part) + 1;
+ }
+ return parts.join("\n");
+};
+
+/**
+ * Builds a payload string of approximately targetBytes. "malformed" returns
+ * intentionally invalid JSON (truncated, unclosed) for JSON-viewer edge cases.
+ */
+export const buildPayload = (
+ style: PayloadStyle,
+ targetBytes: number,
+ rng: Rng,
+): string => {
+ switch (style) {
+ case "json":
+ return buildJsonPayload(rng, targetBytes);
+ case "text":
+ return buildTextPayload(rng, targetBytes);
+ case "unicode":
+ return buildUnicodePayload(rng, targetBytes);
+ case "malformed": {
+ const valid = buildJsonPayload(rng, targetBytes);
+ return `${valid.slice(0, Math.floor(valid.length * 0.9))},"unclosed":"tr`;
+ }
+ }
+};
diff --git a/packages/shared/scripts/seeder/scenarios/rng.ts b/packages/shared/scripts/seeder/scenarios/rng.ts
new file mode 100644
index 0000000000..434d41b70d
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/rng.ts
@@ -0,0 +1,60 @@
+/**
+ * Midnight UTC of the current day. Scenario timestamps anchor here (instead
+ * of Date.now()) so same-day re-runs produce identical ORDER BY tuples and
+ * ReplacingMergeTree overwrites instead of duplicating — events_full sorts
+ * on microsecond start_time, v3 tables on toDate(timestamp). Data still
+ * lands inside recent UI time windows; a re-run on a later day writes a
+ * fresh dated copy.
+ */
+export const utcDayStartMs = (): number =>
+ Math.floor(Date.now() / 86_400_000) * 86_400_000;
+
+/**
+ * Stateless per-index jitter for values that land in ClickHouse ORDER BY
+ * keys (e.g. event start_time). Unlike Rng, the result depends only on
+ * (seed, index) — not on how much of the rng stream earlier code consumed —
+ * so changing unrelated flags (payload size, observation count) does not
+ * re-key existing rows on re-run.
+ */
+export const jitter = (seed: number, index: number, max: number): number => {
+ let x = (seed ^ Math.imul(index + 1, 0x9e3779b9)) >>> 0;
+ x = Math.imul(x ^ (x >>> 16), 0x45d9f3b) >>> 0;
+ x = Math.imul(x ^ (x >>> 16), 0x45d9f3b) >>> 0;
+ x = (x ^ (x >>> 16)) >>> 0;
+ return x % (max + 1);
+};
+
+/**
+ * Deterministic PRNG (mulberry32) so scenarios produce identical data for
+ * identical --seed values. Never use Math.random in scenario code.
+ */
+export class Rng {
+ private state: number;
+
+ constructor(seed: number) {
+ this.state = seed >>> 0;
+ }
+
+ /** float in [0, 1) */
+ next(): number {
+ this.state = (this.state + 0x6d2b79f5) >>> 0;
+ let t = this.state;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ }
+
+ /** integer in [min, max] inclusive; callers must ensure min <= max —
+ * an inverted range would yield values ABOVE max */
+ int(min: number, max: number): number {
+ return min + Math.floor(this.next() * (max - min + 1));
+ }
+
+ pick<T>(items: readonly T[]): T {
+ return items[this.int(0, items.length - 1)];
+ }
+
+ bool(probability = 0.5): boolean {
+ return this.next() < probability;
+ }
+}
diff --git a/packages/shared/scripts/seeder/scenarios/trace-tree.ts b/packages/shared/scripts/seeder/scenarios/trace-tree.ts
new file mode 100644
index 0000000000..7ddd3df273
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/trace-tree.ts
@@ -0,0 +1,597 @@
+import {
+ createTrace,
+ createObservation,
+ createTraceScore,
+ createTracesCh,
+ createObservationsCh,
+ createScoresCh,
+ createEventsCh,
+ ObservationRecordInsertType,
+ ScoreRecordInsertType,
+} from "../../../src/server";
+import { ObservationType } from "../../../src/domain";
+import { observationToEvent, traceToEvent } from "./event-mirror";
+import { buildPayload, PayloadStyle, PAYLOAD_STYLES } from "./payload";
+import { jitter, Rng, utcDayStartMs } from "./rng";
+import {
+ chunk,
+ ScenarioContext,
+ ScenarioDefinition,
+ SeedError,
+ SeedSummary,
+} from "./types";
+import { countRows, traceLink } from "./verify";
+
+const ALL_KINDS: ObservationType[] = [
+ "AGENT",
+ "CHAIN",
+ "RETRIEVER",
+ "EMBEDDING",
+ "TOOL",
+ "GENERATION",
+ "EVALUATOR",
+ "GUARDRAIL",
+ "SPAN",
+ "EVENT",
+];
+
+const NAME_BY_KIND: Record<string, string[]> = {
+ AGENT: ["router-agent", "support-agent", "planner-agent"],
+ CHAIN: ["rag-chain", "summarize-chain"],
+ RETRIEVER: ["docs-retriever", "kb-retriever"],
+ EMBEDDING: ["query-embedding", "chunk-embedding"],
+ TOOL: ["search-products", "fetch-invoice", "issue-refund", "http-request"],
+ GENERATION: ["gpt-4o-completion", "claude-completion", "draft-answer"],
+ EVALUATOR: ["relevance-evaluator", "toxicity-evaluator"],
+ GUARDRAIL: ["pii-guardrail", "jailbreak-guardrail"],
+ SPAN: ["preprocess", "postprocess", "parse-response"],
+ EVENT: ["cache-hit", "rate-limit", "user-feedback"],
+};
+
+type TreeNode = {
+ index: number;
+ parentIndex: number | null;
+ depth: number;
+ kind: ObservationType;
+};
+
+/**
+ * Deterministic tree shape: a backbone chain guarantees the requested depth,
+ * one "hub" node gets `breadth` direct children (the many-children-under-one-
+ * parent shape), and remaining nodes attach with a bias toward the hub.
+ */
+const buildTreeShape = (
+ count: number,
+ depth: number,
+ breadth: number,
+ kinds: ObservationType[],
+ seed: number,
+): TreeNode[] => {
+ const nodes: TreeNode[] = [];
+ // jitter() not rng for kinds: observation `type` is the 2nd v3 ORDER BY
+ // column, and stream-position randomness would re-key rows when flags
+ // that shift rng consumption change between same-prefix re-runs.
+ const kindAt = (index: number): ObservationType =>
+ index < kinds.length
+ ? kinds[index]
+ : jitter(seed, index * 5 + 3, 9) < 4
+ ? "GENERATION"
+ : kinds[jitter(seed, index * 5 + 4, kinds.length - 1)];
+
+ for (let i = 0; i < count; i++) {
+ if (i === 0) {
+ nodes.push({ index: 0, parentIndex: null, depth: 0, kind: kinds[0] });
+ continue;
+ }
+ let parentIndex: number;
+ if (i < depth) {
+ parentIndex = i - 1; // backbone chain → guaranteed depth
+ } else if (i < depth + breadth) {
+ parentIndex = Math.min(2, depth - 1); // hub fan-out
+ } else {
+ // jitter() not rng: parentIndex cascades into start_time (an
+ // events_full ORDER BY key) via startOffsets, so stream-position
+ // randomness would re-key rows across same-prefix re-runs.
+ parentIndex =
+ jitter(seed, i * 17 + 1, 4) < 1
+ ? Math.min(2, depth - 1)
+ : jitter(seed, i * 17 + 2, i - 1);
+ }
+ nodes.push({
+ index: i,
+ parentIndex,
+ depth: nodes[parentIndex].depth + 1,
+ kind: kindAt(i),
+ });
+ }
+ return nodes;
+};
+
+const run = async (
+ ctx: ScenarioContext,
+ params: Record<string, string | number | boolean>,
+): Promise<SeedSummary> => {
+ const startedAt = Date.now();
+ const observationCount = params["observations"] as number;
+ const requestedDepth = params["depth"] as number;
+ const breadth = params["breadth"] as number;
+ // depth deeper than the observation count is geometrically impossible;
+ // clamping it down is helpful, not a silent rewrite of intent (the
+ // validator below enforces the >= 2 lower bound on the requested value)
+ const depth = Math.min(requestedDepth, observationCount);
+ const payloadBytes = params["payload-bytes"] as number;
+ const payloadStyle = params["payload-style"] as PayloadStyle;
+ const withV4 = params["v4"] as boolean;
+
+ if (!PAYLOAD_STYLES.includes(payloadStyle)) {
+ throw new SeedError(
+ `Unknown --payload-style "${payloadStyle}"`,
+ `pass one of: ${PAYLOAD_STYLES.join(", ")}`,
+ );
+ }
+ if (requestedDepth < 2) {
+ throw new SeedError(
+ `--depth must be >= 2, got ${requestedDepth}`,
+ "pass at least 2 (root plus one level), e.g. --depth 8",
+ );
+ }
+ if (breadth < 1) {
+ throw new SeedError(
+ `--breadth must be >= 1, got ${breadth}`,
+ "pass a positive integer, e.g. --breadth 30",
+ );
+ }
+ if (observationCount < 1) {
+ throw new SeedError(
+ `--observations must be >= 1, got ${observationCount}`,
+ "pass a positive integer, e.g. --observations 200",
+ );
+ }
+ if (payloadBytes < 0 || payloadBytes > 50_000_000) {
+ throw new SeedError(
+ `--payload-bytes must be between 0 and 50000000 (50 MB), got ${payloadBytes}`,
+ "larger payloads exceed V8 string limits during generation",
+ );
+ }
+
+ const rng = new Rng(ctx.seed);
+ const traceId = `${ctx.idPrefix}-trace`;
+ const traceTimestamp = utcDayStartMs();
+
+ if (ctx.dryRun) {
+ // counts are derivable from the flags — skip payload/array generation
+ return {
+ scenario: "trace-tree",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: [traceId],
+ sessionIds: [],
+ counts: {
+ traces: 1,
+ observations: observationCount,
+ scores: 3 + (observationCount >= 7 ? 1 : 0),
+ events: withV4 ? observationCount + 1 : 0,
+ },
+ verified: {},
+ links: [traceLink(ctx, traceId, traceTimestamp)],
+ dryRun: true,
+ durationMs: Date.now() - startedAt,
+ };
+ }
+
+ const shape = buildTreeShape(
+ observationCount,
+ depth,
+ breadth,
+ ALL_KINDS,
+ ctx.seed,
+ );
+
+ const rootInput = buildPayload(payloadStyle, payloadBytes, rng);
+ const rootOutput = buildPayload(
+ payloadStyle,
+ Math.ceil(payloadBytes / 2),
+ rng,
+ );
+
+ const trace = createTrace({
+ id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ name: `seed-trace-tree (${observationCount} obs)`,
+ timestamp: traceTimestamp,
+ user_id: `user-${ctx.idPrefix}`,
+ session_id: null,
+ release: "seed-1.0.0",
+ version: "seed-v2",
+ tags: ["seed", "trace-tree", payloadStyle],
+ public: false,
+ bookmarked: false,
+ metadata: {
+ scenario: "trace-tree",
+ seed: String(ctx.seed),
+ "shape.depth": String(depth),
+ "shape.breadth": String(breadth),
+ },
+ input: rootInput,
+ output: rootOutput,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ });
+
+ // Timeline offsets, all jitter()-derived (never the sequential rng stream
+ // or wall clock — start_time is an events_full ORDER BY key, and stream
+ // randomness would re-key rows when unrelated flags change on re-run).
+ // Top-down: a child starts shortly after its OWN PARENT starts, so the
+ // waterfall shows no orphaned gaps. Bottom-up: a parent's end covers its
+ // children. parentIndex < index makes both single passes safe.
+ const startOffsets = new Array<number>(shape.length).fill(0);
+ for (const node of shape) {
+ startOffsets[node.index] =
+ node.parentIndex === null
+ ? 0
+ : startOffsets[node.parentIndex] +
+ 10 +
+ jitter(ctx.seed, node.index, 80);
+ }
+ const endOffsets = new Array<number>(shape.length).fill(0);
+ for (let i = shape.length - 1; i >= 0; i--) {
+ const node = shape[i];
+ const ownDuration =
+ node.kind === "GENERATION"
+ ? 600 + jitter(ctx.seed, i * 3 + 1, 3400)
+ : 5 + jitter(ctx.seed, i * 3 + 2, 395);
+ // endOffsets[i] holds the max end of already-processed children here
+ const end = Math.max(startOffsets[i] + ownDuration, endOffsets[i] + 5);
+ endOffsets[i] = end;
+ if (node.parentIndex !== null) {
+ endOffsets[node.parentIndex] = Math.max(
+ endOffsets[node.parentIndex],
+ end,
+ );
+ }
+ }
+
+ let retryNodeUsed = false;
+ const observations: ObservationRecordInsertType[] = shape.map((node) => {
+ const isGeneration = node.kind === "GENERATION";
+ const startTime = traceTimestamp + startOffsets[node.index];
+ const missingEndTime = node.index > 0 && node.index % 19 === 0;
+ const isError = node.index % 29 === 7;
+ const isFailedToolRetryPair =
+ !retryNodeUsed && node.kind === "TOOL" && node.index > depth;
+ if (isFailedToolRetryPair) retryNodeUsed = true;
+
+ const longName = node.index % 37 === 11;
+ const baseName = rng.pick(NAME_BY_KIND[node.kind]);
+ const name = longName
+ ? `${baseName}-with-an-extremely-long-name-${"x".repeat(140)}`
+ : isFailedToolRetryPair
+ ? `${baseName}-retry`
+ : baseName;
+
+ const payloadForNode = (): string | null => {
+ if (node.index === 0) return rootInput;
+ if (node.index === Math.floor(observationCount / 2)) {
+ return buildPayload("malformed", Math.min(payloadBytes, 20_000), rng);
+ }
+ if (isGeneration) {
+ return JSON.stringify({
+ messages: [
+ { role: "system", content: "You are a helpful support agent." },
+ {
+ role: "user",
+ content: buildPayload("text", rng.int(200, 1200), rng),
+ },
+ ],
+ });
+ }
+ return rng.bool(0.4)
+ ? buildPayload("json", rng.int(150, 2000), rng)
+ : null;
+ };
+
+ const usageInput = rng.int(50, 3000);
+ const usageOutput = rng.int(20, 1500);
+
+ return createObservation({
+ id: `${ctx.idPrefix}-obs-${node.index}`,
+ trace_id: traceId,
+ project_id: ctx.projectId,
+ environment: ctx.environment,
+ type: node.kind,
+ parent_observation_id:
+ node.parentIndex === null
+ ? null
+ : `${ctx.idPrefix}-obs-${node.parentIndex}`,
+ name,
+ start_time: startTime,
+ end_time: missingEndTime ? null : traceTimestamp + endOffsets[node.index],
+ completion_start_time: isGeneration ? startTime + rng.int(80, 400) : null,
+ level:
+ isError || isFailedToolRetryPair
+ ? "ERROR"
+ : node.index % 13 === 5
+ ? "WARNING"
+ : "DEFAULT",
+ status_message:
+ isError || isFailedToolRetryPair
+ ? node.kind === "TOOL"
+ ? "Tool execution failed: upstream timeout after 30s"
+ : "Execution failed: upstream timeout after 30s"
+ : null,
+ version: null,
+ input: payloadForNode(),
+ output:
+ node.index === 0
+ ? rootOutput
+ : isGeneration
+ ? buildPayload("text", rng.int(150, 900), rng)
+ : null,
+ metadata: {
+ scenario: "trace-tree",
+ "node.depth": String(node.depth),
+ ...(isFailedToolRetryPair ? { "retry.count": "2" } : {}),
+ },
+ provided_model_name: isGeneration ? "gpt-4o" : null,
+ internal_model_id: null,
+ model_parameters: isGeneration
+ ? JSON.stringify({ temperature: 0.2, max_tokens: 1024 })
+ : "{}",
+ provided_usage_details: isGeneration
+ ? {
+ input: usageInput,
+ output: usageOutput,
+ total: usageInput + usageOutput,
+ }
+ : {},
+ usage_details: isGeneration
+ ? {
+ input: usageInput,
+ output: usageOutput,
+ total: usageInput + usageOutput,
+ }
+ : {},
+ provided_cost_details: isGeneration
+ ? { input: usageInput * 2e-6, output: usageOutput * 6e-6 }
+ : {},
+ cost_details: isGeneration
+ ? {
+ input: usageInput * 2e-6,
+ output: usageOutput * 6e-6,
+ total: usageInput * 2e-6 + usageOutput * 6e-6,
+ }
+ : {},
+ total_cost: isGeneration ? usageInput * 2e-6 + usageOutput * 6e-6 : null,
+ prompt_id: null,
+ prompt_name: null,
+ prompt_version: null,
+ created_at: Date.now(),
+ updated_at: Date.now(),
+ event_ts: Date.now(),
+ });
+ });
+
+ const evaluatorNode = observations.find((o) => o.type === "EVALUATOR");
+ const scores: ScoreRecordInsertType[] = [
+ createTraceScore({
+ id: `${ctx.idPrefix}-score-quality`,
+ project_id: ctx.projectId,
+ trace_id: traceId,
+ environment: ctx.environment,
+ name: "quality",
+ value: Math.round(rng.next() * 100) / 100,
+ data_type: "NUMERIC",
+ source: "API",
+ comment: "seeded numeric score",
+ metadata: {},
+ timestamp: traceTimestamp,
+ }),
+ createTraceScore({
+ id: `${ctx.idPrefix}-score-sentiment`,
+ project_id: ctx.projectId,
+ trace_id: traceId,
+ environment: ctx.environment,
+ name: "sentiment",
+ value: 1,
+ string_value: rng.pick(["positive", "neutral", "negative"]),
+ data_type: "CATEGORICAL",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp: traceTimestamp,
+ }),
+ createTraceScore({
+ id: `${ctx.idPrefix}-score-success`,
+ project_id: ctx.projectId,
+ trace_id: traceId,
+ environment: ctx.environment,
+ name: "success",
+ value: rng.bool(0.7) ? 1 : 0,
+ string_value: undefined,
+ data_type: "BOOLEAN",
+ source: "API",
+ comment: null,
+ metadata: {},
+ timestamp: traceTimestamp,
+ }),
+ ...(evaluatorNode
+ ? [
+ createTraceScore({
+ id: `${ctx.idPrefix}-score-relevance`,
+ project_id: ctx.projectId,
+ trace_id: traceId,
+ observation_id: evaluatorNode.id,
+ environment: ctx.environment,
+ name: "relevance",
+ value: Math.round(rng.next() * 100) / 100,
+ data_type: "NUMERIC",
+ source: "EVAL",
+ comment: null,
+ metadata: {},
+ timestamp: traceTimestamp,
+ }),
+ ]
+ : []),
+ ];
+
+ // BOOLEAN scores need a string_value mirroring the numeric value
+ const successScore = scores.find((s) => s.name === "success");
+ if (successScore) {
+ successScore.string_value = successScore.value === 1 ? "True" : "False";
+ }
+
+ const events = withV4
+ ? [
+ traceToEvent(trace),
+ ...observations.map((obs) => observationToEvent(obs, trace)),
+ ]
+ : [];
+
+ const counts: Record<string, number> = {
+ traces: 1,
+ observations: observations.length,
+ scores: scores.length,
+ events: events.length,
+ };
+
+ ctx.log(
+ `writing 1 trace, ${observations.length} observations, ${scores.length} scores${withV4 ? `, ${events.length} events` : ""}`,
+ );
+ await createTracesCh([trace]);
+ for (const batch of chunk(observations, 1000)) {
+ await createObservationsCh(batch);
+ }
+ await createScoresCh(scores);
+ for (const batch of chunk(events, 500)) {
+ await createEventsCh(batch);
+ }
+
+ // uniqExact(id): count() would see pre-merge ReplacingMergeTree duplicates
+ // after re-runs with the same id prefix.
+ const verified: Record<string, number> = {
+ traces: await countRows(
+ "traces",
+ `project_id = {projectId: String} AND id = {traceId: String}`,
+ { projectId: ctx.projectId, traceId },
+ "uniqExact(id)",
+ ),
+ observations: await countRows(
+ "observations",
+ `project_id = {projectId: String} AND trace_id = {traceId: String}`,
+ { projectId: ctx.projectId, traceId },
+ "uniqExact(id)",
+ ),
+ observationKinds: await countRows(
+ "observations",
+ `project_id = {projectId: String} AND trace_id = {traceId: String}`,
+ { projectId: ctx.projectId, traceId },
+ "uniqExact(type)",
+ ),
+ scores: await countRows(
+ "scores",
+ `project_id = {projectId: String} AND trace_id = {traceId: String}`,
+ { projectId: ctx.projectId, traceId },
+ "uniqExact(id)",
+ ),
+ };
+ if (withV4) {
+ verified.events = await countRows(
+ "events_full",
+ `project_id = {projectId: String} AND trace_id = {traceId: String}`,
+ { projectId: ctx.projectId, traceId },
+ "uniqExact(span_id)",
+ );
+ }
+
+ if (verified.traces < 1) {
+ throw new SeedError(
+ `Readback mismatch: trace ${traceId} not found after insert`,
+ );
+ }
+ if (verified.observations < observations.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${observations.length} observations, found ${verified.observations}`,
+ );
+ }
+ const expectedKinds = Math.min(observations.length, ALL_KINDS.length);
+ if (verified.observationKinds < expectedKinds) {
+ throw new SeedError(
+ `Readback mismatch: expected ${expectedKinds} distinct observation kinds, found ${verified.observationKinds}`,
+ );
+ }
+ if (verified.scores < scores.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${scores.length} scores, found ${verified.scores}`,
+ );
+ }
+ if (withV4 && verified.events < events.length) {
+ throw new SeedError(
+ `Readback mismatch: expected ${events.length} events_full rows, found ${verified.events}`,
+ );
+ }
+
+ return {
+ scenario: "trace-tree",
+ target: "clickhouse",
+ params,
+ projectId: ctx.projectId,
+ environment: ctx.environment,
+ traceIds: [traceId],
+ sessionIds: [],
+ counts,
+ verified,
+ links: [traceLink(ctx, traceId, traceTimestamp)],
+ dryRun: false,
+ durationMs: Date.now() - startedAt,
+ };
+};
+
+export const traceTreeScenario: ScenarioDefinition = {
+ name: "trace-tree",
+ description:
+ "One trace with a large, branching observation tree: all observation kinds, guaranteed depth, a hub node with many children, errors/retries/missing end times, configurable payload size and style.",
+ supportsV4: true,
+ flags: [
+ {
+ flag: "observations",
+ type: "number",
+ default: 200,
+ description: "total observations in the tree",
+ },
+ {
+ flag: "depth",
+ type: "number",
+ default: 8,
+ description: "guaranteed tree depth (backbone chain)",
+ },
+ {
+ flag: "breadth",
+ type: "number",
+ default: 30,
+ description: "children under the hub node",
+ },
+ {
+ flag: "payload-bytes",
+ type: "number",
+ default: 25_000,
+ description: "approx bytes for the root input payload (max 50 MB)",
+ },
+ {
+ flag: "payload-style",
+ type: "string",
+ default: "json",
+ description: "json | text | malformed | unicode",
+ },
+ {
+ flag: "v4",
+ type: "boolean",
+ default: false,
+ description: "also mirror the tree into v4 events_full/events_core",
+ },
+ ],
+ run,
+};
diff --git a/packages/shared/scripts/seeder/scenarios/types.ts b/packages/shared/scripts/seeder/scenarios/types.ts
new file mode 100644
index 0000000000..8538ea2a31
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/types.ts
@@ -0,0 +1,75 @@
+/**
+ * Shared contracts for seeder scenarios.
+ *
+ * Scenario names, flag names, and SeedSummary JSON keys are a public,
+ * additive-only contract consumed by agents and scripts. Do not rename or
+ * remove fields; add new ones instead. See ../README.md.
+ */
+
+export type ScenarioFlagType = "string" | "number" | "boolean";
+
+export type ScenarioFlag = {
+ /** kebab-case CLI flag name, e.g. "observations-per-trace" */
+ flag: string;
+ type: ScenarioFlagType;
+ default: string | number | boolean;
+ description: string;
+};
+
+export type SeedSummary = {
+ scenario: string;
+ target: "clickhouse";
+ params: Record<string, string | number | boolean>;
+ projectId: string;
+ environment: string;
+ traceIds: string[];
+ sessionIds: string[];
+ /** rows written per logical entity, e.g. { traces: 1, observations: 5000 } */
+ counts: Record<string, number>;
+ /** post-write readback counts from ClickHouse; mismatches fail the run */
+ verified: Record<string, number>;
+ /** UI deep links to inspect the seeded state */
+ links: string[];
+ dryRun: boolean;
+ durationMs: number;
+};
+
+export type ScenarioContext = {
+ projectId: string;
+ environment: string;
+ seed: number;
+ idPrefix: string;
+ dryRun: boolean;
+ baseUrl: string;
+ log: (message: string) => void;
+};
+
+export type ScenarioDefinition = {
+ name: string;
+ description: string;
+ flags: ScenarioFlag[];
+ /** true if the scenario supports mirroring rows into v4 events tables */
+ supportsV4: boolean;
+ run: (
+ ctx: ScenarioContext,
+ params: Record<string, string | number | boolean>,
+ ) => Promise<SeedSummary>;
+};
+
+export class SeedError extends Error {
+ public readonly fix?: string;
+
+ constructor(message: string, fix?: string) {
+ super(message);
+ this.name = "SeedError";
+ this.fix = fix;
+ }
+}
+
+export const chunk = <T>(items: T[], size: number): T[][] => {
+ const result: T[][] = [];
+ for (let i = 0; i < items.length; i += size) {
+ result.push(items.slice(i, i + size));
+ }
+ return result;
+};
diff --git a/packages/shared/scripts/seeder/scenarios/verify.ts b/packages/shared/scripts/seeder/scenarios/verify.ts
new file mode 100644
index 0000000000..8e30f3e896
--- /dev/null
+++ b/packages/shared/scripts/seeder/scenarios/verify.ts
@@ -0,0 +1,38 @@
+import { clickhouseClient } from "../../../src/server";
+import { ScenarioContext } from "./types";
+
+/**
+ * Cheap post-write readback. Not a verification framework — just enough for
+ * the CLI to fail loudly when rows did not land.
+ */
+export const countRows = async (
+ table: string,
+ whereSql: string,
+ params: Record<string, string | number | string[]>,
+ countExpr = "count()",
+): Promise<number> => {
+ const result = await clickhouseClient().query({
+ query: `SELECT ${countExpr} AS c FROM ${table} WHERE ${whereSql}`,
+ query_params: params,
+ format: "JSONEachRow",
+ });
+ const rows = await result.json<{ c: string | number }>();
+ return Number(rows[0]?.c ?? 0);
+};
+
+/** Escapes LIKE-special characters so id prefixes match literally. */
+export const escapeLike = (value: string): string =>
+ value.replace(/\\/g, "\\\\").replace(/[%_]/g, (match) => `\\${match}`);
+
+export const traceLink = (
+ ctx: ScenarioContext,
+ traceId: string,
+ timestampMs: number,
+): string =>
+ `${ctx.baseUrl}/project/${ctx.projectId}/traces/${encodeURIComponent(traceId)}?timestamp=${encodeURIComponent(new Date(timestampMs).toISOString())}`;
+
+export const sessionLink = (ctx: ScenarioContext, sessionId: string): string =>
+ `${ctx.baseUrl}/project/${ctx.projectId}/sessions/${encodeURIComponent(sessionId)}`;
+
+export const tracesListLink = (ctx: ScenarioContext): string =>
+ `${ctx.baseUrl}/project/${ctx.projectId}/traces`;
diff --git a/packages/shared/scripts/seeder/utils/clickhouse-builder.ts b/packages/shared/scripts/seeder/utils/clickhouse-builder.ts
index 5a4ad75b68..c35b69b8a1 100644
--- a/packages/shared/scripts/seeder/utils/clickhouse-builder.ts
+++ b/packages/shared/scripts/seeder/utils/clickhouse-builder.ts
@@ -5,7 +5,6 @@ import {
DatasetRunItemRecordInsertType,
createDatasetRunItemsCh,
} from "../../../src/server";
-import { SEED_TEXT_PROMPTS } from "./postgres-seed-constants";
import {
createTracesCh,
createObservationsCh,
@@ -21,7 +20,10 @@ import { InsertResult } from "@clickhouse/client";
*/
export class ClickHouseQueryBuilder {
private escapeString(str: string): string {
- return str.replace(/'/g, "''");
+ // Backslashes first: ClickHouse treats them as escape sequences inside
+ // single-quoted literals, so unescaped ones corrupt the stored value or
+ // break the statement (e.g. a JSON fixture's \" or an --id-prefix 'a\').
+ return str.replace(/\\/g, "\\\\").replace(/'/g, "''");
}
private buildNestedMetadataMapSql(
@@ -88,7 +90,12 @@ export class ClickHouseQueryBuilder {
count: number,
environment: string = "default",
fileContent?: { heavyMarkdown: string; nestedJson: any; chatMlJson: any },
- opts: { numberOfDays: number } = { numberOfDays: 1 },
+ opts: {
+ numberOfDays: number;
+ idPrefix?: string;
+ anchorSeconds?: number;
+ seed?: number;
+ } = { numberOfDays: 1 },
): string {
// Escape file content if provided
const escapedHeavyMarkdown = fileContent
@@ -100,34 +107,58 @@ export class ClickHouseQueryBuilder {
const escapedChatMl = fileContent
? this.escapeString(JSON.stringify(fileContent.chatMlJson))
: '{"messages": []}';
+ const idPrefix = opts.idPrefix
+ ? `${this.escapeString(opts.idPrefix)}-`
+ : "";
+ const escapedProjectId = this.escapeString(projectId);
+ const escapedEnvironment = this.escapeString(environment);
+ const idSuffix = this.escapeString(projectId.slice(-8));
+ const spreadSeconds = opts.numberOfDays * 86400;
+ const anchorSeconds =
+ opts.anchorSeconds ?? Math.floor(Date.now() / 86_400_000) * 86_400;
+ const seedSalt = (opts.seed ?? 0) >>> 0;
+ // Timestamps derive from `number` and anchor to midnight UTC (computed
+ // in TS, independent of the ClickHouse server timezone) so same-day
+ // re-runs produce identical ORDER BY tuples (toDate(timestamp) is a
+ // sorting key) and ReplacingMergeTree dedups instead of duplicating.
+ // NOTE: the INSERT relies on positional column order — keep the SELECT
+ // list in sync with the table schema when migrations add columns.
return `
INSERT INTO traces
- SELECT
- concat('trace-bulk-', toString(number), '-${projectId.slice(-8)}') AS id,
- toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS timestamp,
+ SELECT
+ concat('${idPrefix}trace-bulk-', toString(number), '-${idSuffix}') AS id,
+ toDateTime(${anchorSeconds} - intDiv(number * ${spreadSeconds}, ${Math.max(count, 1)})) AS timestamp,
concat('trace-', toString(number % 10)) AS name,
- if(randUniform(0, 1) < 0.3, concat('user_', toString(rand() % 1000)), NULL) AS user_id,
+ if(h1 % 10 < 3, concat('${idPrefix}user_', toString(h1 % 1000)), NULL) AS user_id,
${this.buildNestedMetadataMapSql(["'generated'", "'bulk'"])} AS metadata,
NULL AS release,
NULL AS version,
- '${projectId}' AS project_id,
- '${environment}' AS environment,
- if(rand() < 0.8, true, false) AS public,
- if(rand() < 0.1, true, false) AS bookmarked,
+ '${escapedProjectId}' AS project_id,
+ '${escapedEnvironment}' AS environment,
+ if(h2 % 10 = 0, true, false) AS public,
+ if(h2 % 20 = 1, true, false) AS bookmarked,
array() AS tags,
- if(randUniform(0, 1) < 0.3, '${escapedHeavyMarkdown}',
+ if(h3 % 10 < 3, '${escapedHeavyMarkdown}',
'${escapedChatMl}'
) AS input,
- if(randUniform(0, 1) < 0.2, '${escapedNestedJson}',
+ if(h3 % 10 >= 8, '${escapedNestedJson}',
'${escapedChatMl}'
) AS output,
- if(randUniform(0, 1) < 0.3, concat('session_', toString(rand() % 100)), NULL) AS session_id,
+ if(h1 % 100 < 30, concat('${idPrefix}session_', toString(h2 % 100)), NULL) AS session_id,
now() AS created_at,
now() AS updated_at,
now() AS event_ts,
0 AS is_deleted
- FROM numbers(${count});
+ FROM
+ (
+ SELECT
+ number,
+ xxHash32(toUInt64(number * 4 + ${seedSalt})) AS h1,
+ xxHash32(toUInt64(number * 4 + 1 + ${seedSalt})) AS h2,
+ xxHash32(toUInt64(number * 4 + 2 + ${seedSalt})) AS h3
+ FROM numbers(${count})
+ );
`;
}
@@ -141,9 +172,28 @@ export class ClickHouseQueryBuilder {
observationsPerTrace: number = 5,
environment: string = "default",
fileContent?: { heavyMarkdown: string; nestedJson: any; chatMlJson: any },
- opts: { numberOfDays: number } = { numberOfDays: 1 },
+ opts: {
+ numberOfDays: number;
+ idPrefix?: string;
+ anchorSeconds?: number;
+ seed?: number;
+ /** real Postgres prompt rows to link ~10% of generations to; omitted
+ * -> prompt columns stay NULL (fabricated ids break the PromptBadge) */
+ prompts?: { id: string; name: string; version: number }[];
+ } = { numberOfDays: 1 },
): string {
const totalObservations = tracesCount * observationsPerTrace;
+ const idPrefix = opts.idPrefix
+ ? `${this.escapeString(opts.idPrefix)}-`
+ : "";
+ const escapedProjectId = this.escapeString(projectId);
+ const escapedEnvironment = this.escapeString(environment);
+ const idSuffix = this.escapeString(projectId.slice(-8));
+ const spreadSeconds = opts.numberOfDays * 86400;
+ const anchorSeconds =
+ opts.anchorSeconds ?? Math.floor(Date.now() / 86_400_000) * 86_400;
+ const seedSalt = (opts.seed ?? 0) >>> 0;
+ const prompts = opts.prompts ?? [];
// Escape file content if provided
const escapedHeavyMarkdown = fileContent
@@ -156,21 +206,26 @@ export class ClickHouseQueryBuilder {
? this.escapeString(JSON.stringify(fileContent.chatMlJson))
: '{"messages": []}';
+ // start_time anchors to the OWN TRACE's timestamp formula (same divisor
+ // as buildBulkTracesInsert) plus a forward per-depth offset, so parents
+ // precede children and observations cluster at their trace's date.
return `
INSERT INTO observations
- SELECT
- concat('obs-bulk-', toString(number), '-${projectId.slice(-8)}') AS id,
- concat('trace-bulk-', toString(number % ${tracesCount}), '-${projectId.slice(-8)}') AS trace_id,
- '${projectId}' AS project_id,
- '${environment}' AS environment,
- if(randUniform(0, 1) < 0.47, 'GENERATION', if(randUniform(0, 1) < 0.94, 'SPAN', 'EVENT')) AS type,
- if(number % 6 = 0, NULL, toString(number - 1)) AS parent_observation_id,
- toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS start_time,
- addMilliseconds(start_time,
- case
- when type = 'GENERATION' then floor(randUniform(5, 30))
- when type = 'SPAN' then floor(randUniform(1, 50))
- else floor(randUniform(1, 10))
+ SELECT
+ concat('${idPrefix}obs-bulk-', toString(number), '-${idSuffix}') AS id,
+ concat('${idPrefix}trace-bulk-', toString(number % ${tracesCount}), '-${idSuffix}') AS trace_id,
+ '${escapedProjectId}' AS project_id,
+ '${escapedEnvironment}' AS environment,
+ multiIf(h1 % 100 < 47, 'GENERATION', h1 % 100 < 94, 'SPAN', 'EVENT') AS type,
+ if(number < ${tracesCount}, NULL, concat('${idPrefix}obs-bulk-', toString(number - ${tracesCount}), '-${idSuffix}')) AS parent_observation_id,
+ toDateTime(${anchorSeconds} - intDiv((number % ${Math.max(tracesCount, 1)}) * ${spreadSeconds}, ${Math.max(tracesCount, 1)}) + intDiv(number, ${Math.max(tracesCount, 1)}) * 60) AS start_time,
+ addMilliseconds(
+ toDateTime(${anchorSeconds} - intDiv((number % ${Math.max(tracesCount, 1)}) * ${spreadSeconds}, ${Math.max(tracesCount, 1)}) + ${Math.max(observationsPerTrace - 1, 0)} * 60),
+ (${Math.max(observationsPerTrace - 1, 0)} - intDiv(number, ${Math.max(tracesCount, 1)})) * 4000 +
+ case
+ when type = 'GENERATION' then 600 + h2 % 3400
+ when type = 'SPAN' then 1 + h2 % 50
+ else 1 + h2 % 10
end) AS end_time,
case
when type = 'GENERATION' then concat('generation-', toString(number % 10))
@@ -178,36 +233,48 @@ export class ClickHouseQueryBuilder {
else concat('event-', toString(number % 10))
end AS name,
${this.buildNestedMetadataMapSql(["'key'", "'value'"])} AS metadata,
- if(randUniform(0, 1) < 0.85, 'DEFAULT', if(randUniform(0, 1) < 0.7, 'DEBUG', if(randUniform(0, 1) < 0.3, 'ERROR', 'WARNING'))) AS level,
+ multiIf(h3 % 1000 < 850, 'DEFAULT', h3 % 1000 < 955, 'DEBUG', h3 % 1000 < 969, 'ERROR', 'WARNING') AS level,
NULL AS status_message,
NULL AS version,
- if(type = 'GENERATION',
- if(randUniform(0, 1) < 0.4, '${escapedHeavyMarkdown}', '${escapedChatMl}'),
+ if(type = 'GENERATION',
+ if(h2 % 10 < 4, '${escapedHeavyMarkdown}', '${escapedChatMl}'),
NULL) AS input,
- if(type = 'GENERATION',
- if(randUniform(0, 1) < 0.3, '${escapedNestedJson}', '${escapedChatMl}'),
+ if(type = 'GENERATION',
+ if(h2 % 10 >= 7, '${escapedNestedJson}', '${escapedChatMl}'),
NULL) AS output,
if(type = 'GENERATION', 'gpt-4', NULL) AS provided_model_name,
- if(type = 'GENERATION', concat('model_', toString(rand() % 1000)), NULL) AS internal_model_id,
+ if(type = 'GENERATION', concat('model_', toString(h2 % 1000)), NULL) AS internal_model_id,
if(type = 'GENERATION', '{"temperature": 0.7}', '{}') AS model_parameters,
- if(type = 'GENERATION', map('input', toUInt64(randUniform(20, 200)), 'output', toUInt64(randUniform(10, 100)), 'total', toUInt64(randUniform(30, 300))), map()) AS provided_usage_details,
- if(type = 'GENERATION', map('input', toUInt64(randUniform(20, 200)), 'output', toUInt64(randUniform(10, 100)), 'total', toUInt64(randUniform(30, 300))), map()) AS usage_details,
- if(type = 'GENERATION', map('input', toDecimal64(randUniform(0.00001, 0.001), 8), 'output', toDecimal64(randUniform(0.00001, 0.002), 8), 'total', toDecimal64(randUniform(0.00002, 0.003), 8)), map()) AS provided_cost_details,
- if(type = 'GENERATION', map('input', toDecimal64(randUniform(0.00001, 0.001), 8), 'output', toDecimal64(randUniform(0.00001, 0.002), 8), 'total', toDecimal64(randUniform(0.00002, 0.003), 8)), map()) AS cost_details,
- if(type = 'GENERATION', toDecimal64(randUniform(0.00002, 0.003), 8), NULL) AS total_cost,
- if(type = 'GENERATION', addMilliseconds(start_time, floor(randUniform(100, 500))), NULL) AS completion_start_time,
- if("type" = 'GENERATION' AND number % 10 = 0,
- arrayElement(['${SEED_TEXT_PROMPTS.map((p) => p.id).join("','")}'], 1 + (number % ${SEED_TEXT_PROMPTS.length})),
- NULL) AS prompt_id,
- if("type" = 'GENERATION' AND number % 10 = 0,
- arrayElement(['${SEED_TEXT_PROMPTS.map((p) => p.name).join("','")}'], 1 + (number % ${SEED_TEXT_PROMPTS.length})),
- NULL) AS prompt_name,
- if("type" = 'GENERATION' AND number % 10 = 0,
- arrayElement(['${SEED_TEXT_PROMPTS.map((p) => p.version).join("','")}'], 1 + (number % ${SEED_TEXT_PROMPTS.length})),
- NULL) AS prompt_version,
+ if(type = 'GENERATION', map('input', toUInt64(20 + h1 % 181), 'output', toUInt64(10 + h2 % 91), 'total', toUInt64(30 + h1 % 181 + h2 % 91)), map()) AS provided_usage_details,
+ if(type = 'GENERATION', map('input', toUInt64(20 + h1 % 181), 'output', toUInt64(10 + h2 % 91), 'total', toUInt64(30 + h1 % 181 + h2 % 91)), map()) AS usage_details,
+ if(type = 'GENERATION', map('input', toDecimal64((10 + h1 % 990) / 1000000, 8), 'output', toDecimal64((10 + h2 % 1990) / 1000000, 8), 'total', toDecimal64((20 + h1 % 990 + h2 % 1990) / 1000000, 8)), map()) AS provided_cost_details,
+ if(type = 'GENERATION', map('input', toDecimal64((10 + h1 % 990) / 1000000, 8), 'output', toDecimal64((10 + h2 % 1990) / 1000000, 8), 'total', toDecimal64((20 + h1 % 990 + h2 % 1990) / 1000000, 8)), map()) AS cost_details,
+ if(type = 'GENERATION', toDecimal64((20 + h1 % 990 + h2 % 1990) / 1000000, 8), NULL) AS total_cost,
+ if(type = 'GENERATION', addMilliseconds(start_time, toUInt32(100 + h3 % 400)), NULL) AS completion_start_time,
+ ${
+ prompts.length > 0
+ ? `if("type" = 'GENERATION' AND number % 10 = 0,
+ arrayElement(['${prompts.map((p) => this.escapeString(p.id)).join("','")}'], 1 + (h3 % ${prompts.length})),
+ NULL)`
+ : "NULL"
+ } AS prompt_id,
+ ${
+ prompts.length > 0
+ ? `if("type" = 'GENERATION' AND number % 10 = 0,
+ arrayElement(['${prompts.map((p) => this.escapeString(p.name)).join("','")}'], 1 + (h3 % ${prompts.length})),
+ NULL)`
+ : "NULL"
+ } AS prompt_name,
+ ${
+ prompts.length > 0
+ ? `if("type" = 'GENERATION' AND number % 10 = 0,
+ arrayElement([${prompts.map((p) => Math.floor(p.version)).join(",")}], 1 + (h3 % ${prompts.length})),
+ NULL)`
+ : "NULL"
+ } AS prompt_version,
start_time AS created_at,
start_time AS updated_at,
- start_time AS event_ts,
+ now() AS event_ts,
0 AS is_deleted,
'' AS usage_pricing_tier_id,
'' AS usage_pricing_tier_name,
@@ -215,7 +282,15 @@ export class ClickHouseQueryBuilder {
[] AS tool_calls,
[] AS tool_call_names
- FROM numbers(${totalObservations});
+ FROM
+ (
+ SELECT
+ number,
+ xxHash32(toUInt64(number * 4 + ${seedSalt})) AS h1,
+ xxHash32(toUInt64(number * 4 + 1 + ${seedSalt})) AS h2,
+ xxHash32(toUInt64(number * 4 + 2 + ${seedSalt})) AS h3
+ FROM numbers(${totalObservations})
+ );
`;
}
@@ -228,25 +303,46 @@ export class ClickHouseQueryBuilder {
tracesCount: number,
scoresPerTrace: number = 2,
environment: string = "default",
- opts: { numberOfDays: number } = { numberOfDays: 1 },
+ opts: {
+ numberOfDays: number;
+ idPrefix?: string;
+ observationsPerTrace?: number;
+ anchorSeconds?: number;
+ seed?: number;
+ } = { numberOfDays: 1 },
): string {
const totalScores = tracesCount * scoresPerTrace;
+ const observationsPerTrace = opts.observationsPerTrace ?? 5;
+ const idPrefix = opts.idPrefix
+ ? `${this.escapeString(opts.idPrefix)}-`
+ : "";
+ const escapedProjectId = this.escapeString(projectId);
+ const escapedEnvironment = this.escapeString(environment);
+ const idSuffix = this.escapeString(projectId.slice(-8));
+ const spreadSeconds = opts.numberOfDays * 86400;
+ const anchorSeconds =
+ opts.anchorSeconds ?? Math.floor(Date.now() / 86_400_000) * 86_400;
+ const seedSalt = (opts.seed ?? 0) >>> 0;
return `
INSERT INTO scores
- SELECT
- concat('score-bulk-', toString(number), '-${projectId.slice(-8)}') AS id,
- toDateTime(now() - randUniform(0, ${opts.numberOfDays} * 24 * 60 * 60)) AS timestamp,
- '${projectId}' AS project_id,
- '${environment}' AS environment,
- concat('trace-bulk-', toString(number % ${tracesCount}), '-${projectId.slice(-8)}') AS trace_id,
- if(randUniform(0, 1) < 0.3, concat('session_', toString(rand() % 100)), NULL) AS session_id,
+ SELECT
+ concat('${idPrefix}score-bulk-', toString(number), '-${idSuffix}') AS id,
+ toDateTime(${anchorSeconds} - intDiv((number % ${Math.max(tracesCount, 1)}) * ${spreadSeconds}, ${Math.max(tracesCount, 1)}) + intDiv(number, ${Math.max(tracesCount, 1)}) * 90) AS timestamp,
+ '${escapedProjectId}' AS project_id,
+ '${escapedEnvironment}' AS environment,
+ concat('${idPrefix}trace-bulk-', toString(number % ${tracesCount}), '-${idSuffix}') AS trace_id,
+ if(traceH1 % 100 < 30, concat('${idPrefix}session_', toString(traceH2 % 100)), NULL) AS session_id,
NULL AS dataset_run_id,
- if(randUniform(0, 1) < 0.1, concat('obs-bulk-', toString(rand() % (${tracesCount} * 5)), '-${projectId.slice(-8)}'), NULL) AS observation_id,
- concat('metric_', toString((number % ${scoresPerTrace * 5}) + 1)) AS name,
+ ${
+ observationsPerTrace > 0
+ ? `if(h1 % 10 = 0, concat('${idPrefix}obs-bulk-', toString((number % ${tracesCount}) + ${tracesCount} * (h2 % ${observationsPerTrace})), '-${idSuffix}'), NULL)`
+ : "NULL"
+ } AS observation_id,
+ concat('metric_', toString(nameKey + 1)) AS name,
case
- when (number % 3) = 0 then toDecimal64(randUniform(0, 100), 8)
- when (number % 3) = 1 then if(randUniform(0, 1) < 0.5, 1, 0)
+ when (nameKey % 3) = 0 then toDecimal64((h3 % 10000) / 100, 8)
+ when (nameKey % 3) = 1 then if(h3 % 2 = 0, 1, 0)
else NULL
end AS value,
'API' AS source,
@@ -255,23 +351,34 @@ export class ClickHouseQueryBuilder {
NULL AS author_user_id,
NULL AS config_id,
case
- when (number % 3) = 0 then 'NUMERIC'
- when (number % 3) = 1 then 'BOOLEAN'
+ when (nameKey % 3) = 0 then 'NUMERIC'
+ when (nameKey % 3) = 1 then 'BOOLEAN'
else 'CATEGORICAL'
end AS data_type,
case
- when (number % 3) = 1 then if(value = 1, 'true', 'false')
- when (number % 3) = 2 then concat('category_', toString((rand() % 5) + 1))
+ when (nameKey % 3) = 1 then if(value = 1, 'True', 'False')
+ when (nameKey % 3) = 2 then concat('category_', toString((h1 % 5) + 1))
else NULL
end AS string_value,
NULL AS queue_id,
timestamp AS created_at,
timestamp AS updated_at,
- timestamp AS event_ts,
+ now() AS event_ts,
0 AS is_deleted,
NULL AS execution_trace_id,
'' AS long_string_value
- FROM numbers(${totalScores});
+ FROM
+ (
+ SELECT
+ number,
+ xxHash32(toUInt64(number * 4 + ${seedSalt})) AS h1,
+ xxHash32(toUInt64(number * 4 + 1 + ${seedSalt})) AS h2,
+ xxHash32(toUInt64(number * 4 + 2 + ${seedSalt})) AS h3,
+ xxHash32(toUInt64((number % ${Math.max(tracesCount, 1)})) * 4 + ${seedSalt}) AS traceH1,
+ xxHash32(toUInt64((number % ${Math.max(tracesCount, 1)})) * 4 + 1 + ${seedSalt}) AS traceH2,
+ (number % ${scoresPerTrace * 5}) + intDiv(number, ${Math.max(tracesCount, 1)}) * ${scoresPerTrace * 5} AS nameKey
+ FROM numbers(${totalScores})
+ );
`;
}
}
diff --git a/packages/shared/scripts/seeder/utils/data-generators.ts b/packages/shared/scripts/seeder/utils/data-generators.ts
index 93a10cecb8..46b8ad84d6 100644
--- a/packages/shared/scripts/seeder/utils/data-generators.ts
+++ b/packages/shared/scripts/seeder/utils/data-generators.ts
@@ -617,7 +617,7 @@ export class DataGenerator {
break;
case "BOOLEAN":
value = this.randomBoolean() ? 1 : 0;
- stringValue = value === 1 ? "true" : "false";
+ stringValue = value === 1 ? "True" : "False";
break;
}
@@ -1275,7 +1275,7 @@ export class DataGenerator {
author_user_id: null,
config_id: null,
data_type: "BOOLEAN",
- string_value: safeVal === 1 ? "true" : "false",
+ string_value: safeVal === 1 ? "True" : "False",
queue_id: null,
created_at: baseTs + 10,
updated_at: baseTs + 10,
@@ -1304,7 +1304,7 @@ export class DataGenerator {
author_user_id: null,
config_id: null,
data_type: "BOOLEAN",
- string_value: "true",
+ string_value: "True",
queue_id: null,
created_at: baseTs + 20,
updated_at: baseTs + 20,
diff --git a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts b/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts
index f39f6c7c22..a2fd8c2771 100644
--- a/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts
+++ b/packages/shared/scripts/seeder/utils/seeder-orchestrator.ts
@@ -285,7 +285,7 @@ export class SeederOrchestrator {
tracesPerProject,
scoresPerTrace,
"default",
- { numberOfDays: opts.numberOfDays },
+ { numberOfDays: opts.numberOfDays, observationsPerTrace },
);
await this.executeQuery(traceQuery);