Trace-native CI/CD for AI agents — production failures become regression tests that block the PR. Auto-detect, cluster, freeze into hermetic cases, replay in CI for $0.
Python agentagent-observabilityai-agentsci-cdclickhouseevalsevaluationllmllm-as-judgellm-evaluationllm-observabilityllm-opsllmopsmcpmonitoringopentelemetrypythonself-hostedtracing
feat(spans): Postgres span store behind SPAN_STORE, with copy + verify (#140)
Wuthrich Juliene15782e55ba8
diff --git a/.env.example b/.env.exampleindex de390e8..4ae6d60 100644--- a/.env.example+++ b/.env.example@@ -6,6 +6,9 @@ DATABASE_URL=postgresql+asyncpg://tracely:tracely@localhost:5432/tracelyALEMBIC_DATABASE_URL=postgresql+psycopg://tracely:tracely@localhost:5432/tracely# ClickHouse (events + scores)+# Span store: clickhouse (legacy) | postgres. Set the SAME value on the API and the worker.+# Switch only after `python -m tracely.infrastructure.spans.copy` reports "OK — stores agree".+SPAN_STORE=clickhouseCLICKHOUSE_HOST=localhostCLICKHOUSE_PORT=8123CLICKHOUSE_USER=defaultdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex ff375bb..fb1944f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -20,6 +20,19 @@ jobs:backend:name: backend · ruff + pytestruns-on: ubuntu-latest+ # A scratch Postgres for the span-store tests (backend/tests/test_span_store_pg.py). They skip+ # without TRACELY_TEST_PG_URL, so the local suite stays infra-free.+ services:+ postgres:+ image: postgres:17+ env:+ POSTGRES_PASSWORD: test+ POSTGRES_DB: spans+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U postgres" --health-interval 2s --health-timeout 5s --health-retries 20+ env:+ TRACELY_TEST_PG_URL: postgresql://postgres:test@localhost:5432/spanssteps:- uses: actions/checkout@v7- uses: astral-sh/setup-uv@v5diff --git a/CLAUDE.md b/CLAUDE.mdindex eee0931..6090b05 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -55,7 +55,7 @@ Five stores: **ClickHouse** (`events` one row per span + `scores`, `ReplacingMer## Hard rules-- **No SQL in `api/routers/`.** ClickHouse reads go through `infrastructure/clickhouse/async_reader.py` (async, for the API) or `trace_reader.py` (sync, for workers/services); Postgres through `infrastructure/db/repositories.py`; auth lookups through `auth/queries.py`. Adding a query means adding a function there, not inlining SQL in a router. (`health.py`'s `SELECT 1` probe is the sole exception.)+- **No SQL in `api/routers/`.** Span/score reads go through the span store, imported **only** from `tracely.infrastructure.spans` (`async_reader`, `TraceReader`, `ScoreWriter`, `deletes`, `insert_events`); `SPAN_STORE` picks ClickHouse (`infrastructure/clickhouse/`) or Postgres (`infrastructure/spans/`), whose modules share names, signatures and return shapes — a new read is added to **both** while the two exist (design/part2-tracely/14-clickhouse-to-postgres.md). Registry Postgres goes through `infrastructure/db/repositories.py`; auth lookups through `auth/queries.py`. Adding a query means adding a function there, not inlining SQL in a router. (`health.py`'s `SELECT 1` probe is the sole exception.)- **Every LLM call goes through `infrastructure/llm/provider.py`** (`run_structured_agent` / `run_text_agent` — LangChain `create_agent` on OpenRouter, OpenAI as fallback). Never construct a client elsewhere. LLM modules are lazy-imported and `llm_enabled()` gates them: with no key the pipeline must still run (judge/FI/meta-analysis degrade, not crash). **Customers bring their own key**: inside `provider.use_project_key(project_id)` only that workspace's OpenRouter key applies — never the server-wide `OPENROUTER_API_KEY`/`LLM_JUDGE_API_KEY`/`OPENAI_API_KEY`. A project with no key configured is exactly an LLM-disabled deployment. Any new project-scoped LLM entry point wraps in `use_project_key` and checks `llm_enabled()` *inside* the wrap. The **one exception** is the in-app assistant (`services/assistant_service.py`): it explains and operates *our* product, so the model runs on *our* key via `provider.use_server_key()` (through `use_assistant_key`, which falls back to the workspace's own key only on a deployment with no key of ours, i.e. a self-host) — an explicit scope, not an unwrapped call, because under `REQUIRE_PROJECT_LLM_KEY` an unscoped call fails closed as a forgot-to-wrap bug. Anything else that spends the server key on a customer's behalf needs the same deliberate seam. Note the split: only the *model* is on our key. The assistant's **tools** re-enter our own routers carrying the caller's own credentials (`api/internal_client.py`), so we pay for tokens without widening anyone's reach.- **Agents reach the product through the routers, never the DB.** Both the MCP server (`api/mcp_server.py`) and the in-app assistant's tools (`services/assistant_tools.py`) call `internal_client.api_call`, which re-issues the request against our own ASGI app with the caller's `authorization`/`x-tracely-key`/`x-tracely-project` headers. That leaves `get_project_id` as the only place scoping happens and the routers' own 4xx bodies as the only place a bad write is rejected — handed back to the agent, that error text is what lets it correct itself. Assistant tools **return** their failures as text (langgraph re-raises anything that isn't a bad-args error, which would kill the stream mid-answer), and no assistant tool argument may be named `config` (`StructuredTool._arun` swallows it).- **Everything is scoped by `project_id`**, resolved from `Authorization: Bearer <ingest-key>` via `api/auth`. Every read and write takes it.@@ -64,7 +64,7 @@ Five stores: **ClickHouse** (`events` one row per span + `scores`, `ReplacingMer- **Ending a session means bumping `users.token_version`.** Sessions are stateless JWTs carrying it as `tv`; `_resolve_local_jwt` compares the two. Password change and reset bump it (and hand back a fresh token, or the caller logs themselves out). Nothing else can revoke a session early.- **An invite never logs anyone into an existing account.** The raw invite token is shown to the inviter; when the invited email already has an account, `accept_invitation` verifies that account's password before consuming the token.- **Writes are idempotent.** Deterministic ids (score id = `uuid5(trace_id:name:span_id)`) + `ReplacingMergeTree` mean re-ingest/re-eval converges instead of duplicating. Anything sampled must be deterministic per `(trace_id, score_name)` for the same reason (`domain/evaluation/targeting.py`).-- **One verdict policy.** A trace/turn/session fails iff it has a `FAIL` on a **non-advisory** evaluator. Python: `domain/evaluation/verdict.py`. Its SQL twin lives in `async_reader` (`name NOT IN {adv:Array(String)}`), fed by `api/advisory.py`. Change both together or the badge, threads dot, and trends disagree.+- **One verdict policy.** A trace/turn/session fails iff it has a `FAIL` on a **non-advisory** evaluator. Python: `domain/evaluation/verdict.py`. Its SQL twins live in `clickhouse/async_reader` (`name NOT IN {adv:Array(String)}`) and `spans/reads` (`name <> ALL(:adv)`), fed by `api/advisory.py`. Change both together or the badge, threads dot, and trends disagree.- **Frontend fetch pattern:** Server Components (pages) call `app/lib/api.ts` directly; Client Components fetch a thin proxy under `app/api/*` which re-issues with the Bearer key server-side. `TRACELY_KEY` / `TRACELY_API` must never reach the browser — do not add an `env:` block to `next.config.mjs`.- **New backend env var?** Add it to `config.py` (`Settings`) *and* the `x-app-env` anchor at the top of `docker-compose.yml` — `.env` alone won't reach the containers.- **Emulated conversations have four non-obvious invariants.** Break any one and the gate goes quietly green instead of failing loudly:diff --git a/backend/migrations/versions/0040_span_store.py b/backend/migrations/versions/0040_span_store.pynew file mode 100644index 0000000..5e75bb0--- /dev/null+++ b/backend/migrations/versions/0040_span_store.py@@ -0,0 +1,185 @@+"""Postgres span store: `events`, `scores` and the per-trace rollup `traces`++The ClickHouse tables' twins, read when `SPAN_STORE=postgres`. Raw DDL with no ORM models: the+span readers own their column lists (as the ClickHouse ones do), and the SQLite test harness only+creates registry tables — jsonb/text[] would not build there. Purely additive: with the store left+on ClickHouse these stay empty. See design/part2-tracely/14-clickhouse-to-postgres.md §2-§3.++Revision ID: 0040+Revises: 0039+Create Date: 2026-11-15+"""++from __future__ import annotations++from collections.abc import Sequence++from alembic import op++revision: str = "0040"+down_revision: str | None = "0039"+branch_labels: str | Sequence[str] | None = None+depends_on: str | Sequence[str] | None = None++_T = "text NOT NULL DEFAULT ''"++UPGRADE = f"""+CREATE EXTENSION IF NOT EXISTS pg_trgm;++CREATE TABLE IF NOT EXISTS events (+ project_id text NOT NULL,+ trace_id text NOT NULL,+ span_id text NOT NULL,+ parent_span_id {_T},+ start_time timestamptz NOT NULL,+ end_time timestamptz,+ completion_start_time timestamptz,+ name {_T},+ type {_T},+ environment text NOT NULL DEFAULT 'default',+ env text NOT NULL DEFAULT 'prod',+ version {_T},+ release {_T},+ level text NOT NULL DEFAULT 'DEFAULT',+ status_message {_T},+ is_app_root boolean NOT NULL DEFAULT false,+ trace_name {_T},+ user_id {_T},+ session_id {_T},+ tags text[] NOT NULL DEFAULT '{{}}',+ agent_id {_T},+ agent_version_id {_T},+ agent_run_id {_T},+ conversation_id {_T},+ turn_id {_T},+ turn_index integer NOT NULL DEFAULT 0,+ step_id {_T},+ step_name {_T},+ tool_call_id {_T},+ caller_agent_id {_T},+ callee_agent_id {_T},+ edge_type {_T},+ evaluation_case_id {_T},+ gate_run_id {_T},+ failure_cluster_id {_T},+ internal_kind {_T},+ subject_id {_T},+ model_id {_T},+ model_parameters {_T},+ usage_details jsonb NOT NULL DEFAULT '{{}}',+ cost_details jsonb NOT NULL DEFAULT '{{}}',+ -- summed once at write time (ClickHouse did arraySum(mapValues(...)) on every read)+ tokens bigint NOT NULL DEFAULT 0,+ input_tokens bigint NOT NULL DEFAULT 0,+ output_tokens bigint NOT NULL DEFAULT 0,+ cost double precision NOT NULL DEFAULT 0,+ tool_definitions jsonb NOT NULL DEFAULT '{{}}',+ tool_calls text[] NOT NULL DEFAULT '{{}}',+ tool_call_names text[] NOT NULL DEFAULT '{{}}',+ -- NULL = no text, never '' (events_schema.to_rows enforces it). TOASTed out of line, so a scan+ -- that does not select them never reads them.+ input text COMPRESSION lz4,+ output text COMPRESSION lz4,+ metadata jsonb NOT NULL DEFAULT '{{}}',+ source text NOT NULL DEFAULT 'otel',+ service_name {_T},+ scope_name {_T},+ telemetry_sdk_language {_T},+ telemetry_sdk_name {_T},+ telemetry_sdk_version {_T},+ created_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (project_id, trace_id, span_id)+);+CREATE INDEX IF NOT EXISTS events_conv ON events (project_id, conversation_id) WHERE conversation_id <> '';+CREATE INDEX IF NOT EXISTS events_time ON events (project_id, start_time);+CREATE INDEX IF NOT EXISTS events_agent ON events (project_id, agent_id);+CREATE INDEX IF NOT EXISTS events_root_input ON events (project_id, agent_id, md5(input)) WHERE is_app_root;+CREATE INDEX IF NOT EXISTS events_run_id ON events (project_id, (metadata->>'tracely.replay.run_id'))+ WHERE metadata ? 'tracely.replay.run_id';+-- Text search. A GENERATION's input is the whole history + system prompt, repeated every turn:+-- noise for search and most of the index, so only its OUTPUT is indexed.+CREATE INDEX IF NOT EXISTS events_output_trgm ON events USING gin (output gin_trgm_ops);+CREATE INDEX IF NOT EXISTS events_input_trgm ON events USING gin (input gin_trgm_ops) WHERE type <> 'GENERATION';++CREATE TABLE IF NOT EXISTS scores (+ project_id text NOT NULL,+ id text NOT NULL,+ trace_id text,+ observation_id text,+ session_id text,+ agent_run_id {_T},+ turn_id {_T},+ name text NOT NULL,+ source text NOT NULL,+ data_type {_T},+ value double precision,+ string_value {_T},+ verdict {_T},+ evaluation_case_id {_T},+ gate_run_id {_T},+ evaluation_level {_T},+ execution_trace_id {_T},+ comment {_T},+ metadata jsonb NOT NULL DEFAULT '{{}}',+ -- write time; a re-grade overwrites it, exactly as FINAL surfaced the newest version+ created_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (project_id, id)+);+CREATE INDEX IF NOT EXISTS scores_trace ON scores (project_id, trace_id);+CREATE INDEX IF NOT EXISTS scores_session ON scores (project_id, session_id) WHERE evaluation_level = 'CONVERSATION';+CREATE INDEX IF NOT EXISTS scores_name ON scores (project_id, name, created_at);+CREATE INDEX IF NOT EXISTS scores_online_fail ON scores (project_id, trace_id, name)+ WHERE source = 'EVAL' AND evaluation_case_id = '' AND verdict = 'FAIL';++-- One row per trace, recomputed from its spans in the same transaction as every span write or+-- delete (tracely.infrastructure.spans.rollup). Lists, counts and trends read this instead of+-- grouping spans. Verdicts are deliberately NOT here: the advisory set changes independently.+CREATE TABLE IF NOT EXISTS traces (+ project_id text NOT NULL,+ trace_id text NOT NULL,+ thread_id text NOT NULL,+ conversation_id {_T},+ env text NOT NULL DEFAULT 'prod',+ internal_kind {_T},+ subject_id {_T},+ agent_id {_T},+ app_root_agent_id {_T},+ root_name {_T},+ first_name {_T},+ root_input text COMPRESSION lz4,+ root_output text COMPRESSION lz4,+ has_input boolean NOT NULL DEFAULT false,+ has_output boolean NOT NULL DEFAULT false,+ spans integer NOT NULL DEFAULT 0,+ ts_min timestamptz NOT NULL,+ ts_max timestamptz NOT NULL,+ latency_ms bigint NOT NULL DEFAULT 0,+ tokens bigint NOT NULL DEFAULT 0,+ input_tokens bigint NOT NULL DEFAULT 0,+ output_tokens bigint NOT NULL DEFAULT 0,+ cost double precision NOT NULL DEFAULT 0,+ model_id {_T},+ has_error boolean NOT NULL DEFAULT false,+ tool_errors integer NOT NULL DEFAULT 0,+ first_error {_T},+ has_emulated_turn boolean NOT NULL DEFAULT false,+ metadata jsonb NOT NULL DEFAULT '{{}}',+ updated_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (project_id, trace_id)+);+CREATE INDEX IF NOT EXISTS traces_thread ON traces (project_id, thread_id);+CREATE INDEX IF NOT EXISTS traces_recent ON traces (project_id, ts_max DESC);+CREATE INDEX IF NOT EXISTS traces_start ON traces (project_id, ts_min);+CREATE INDEX IF NOT EXISTS traces_agent ON traces (project_id, agent_id);+CREATE INDEX IF NOT EXISTS traces_root_input_trgm ON traces USING gin (root_input gin_trgm_ops);+"""+++def upgrade() -> None:+ op.execute(UPGRADE)+++def downgrade() -> None:+ op.execute(+ "DROP TABLE IF EXISTS traces; DROP TABLE IF EXISTS scores; DROP TABLE IF EXISTS events;"+ )diff --git a/backend/tests/test_agents_workflow_root.py b/backend/tests/test_agents_workflow_root.pyindex 24caf07..6c2f590 100644--- a/backend/tests/test_agents_workflow_root.py+++ b/backend/tests/test_agents_workflow_root.py@@ -24,7 +24,7 @@ def _gen(i, inp, out):def test_the_empty_root_takes_the_first_call_input_and_last_call_output(monkeypatch):- monkeypatch.setattr(ingestion_service, "get_client", lambda: (_ for _ in ()).throw(RuntimeError("no db")))+ monkeypatch.setattr(ingestion_service, "_stored_generations", lambda *a: (_ for _ in ()).throw(RuntimeError("no db")))call = [{"role": "assistant", "content": "", "tool_calls": [{"function": {"name": "get_order"}}]}]events = [_root(), _gen(1, USER, call), _gen(2, USER + call, FINAL)]IngestionService._fill_agents_workflow_root("p", events)@@ -34,7 +34,7 @@ def test_the_empty_root_takes_the_first_call_input_and_last_call_output(monkeypadef test_other_roots_are_never_touched(monkeypatch):- monkeypatch.setattr(ingestion_service, "get_client", lambda: (_ for _ in ()).throw(RuntimeError("no db")))+ monkeypatch.setattr(ingestion_service, "_stored_generations", lambda *a: (_ for _ in ()).throw(RuntimeError("no db")))other = _root(name="lg-supervisor")recorded = _root(input="hi", output="hello")events = [other, recorded, _gen(1, USER, FINAL)]diff --git a/backend/tests/test_evaluators_api.py b/backend/tests/test_evaluators_api.pyindex ddfab9a..057fc7a 100644--- a/backend/tests/test_evaluators_api.py+++ b/backend/tests/test_evaluators_api.py@@ -361,7 +361,7 @@ async def test_chain_progress_reports_sequential_columns(client, sync_db, monkeycount, the next seed payload, freshness. Batch columns don't chain, so they don't appear."""from sqlalchemy import select- from tracely.infrastructure.clickhouse import async_reader+ from tracely.infrastructure.spans import async_reader # the active storefrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.models import Evaluatordiff --git a/backend/tests/test_span_store_pg.py b/backend/tests/test_span_store_pg.pynew file mode 100644index 0000000..c9c8d6c--- /dev/null+++ b/backend/tests/test_span_store_pg.py@@ -0,0 +1,220 @@+"""The Postgres span store against a real Postgres: write path, the `traces` rollup, the verdict+policy and the readers' shapes. ClickHouse-vs-Postgres parity is what+`python -m tracely.infrastructure.spans.copy --verify-only` proves on real data; this pins the rules.++Needs a scratch database — `TRACELY_TEST_PG_URL=postgresql://user:pass@host:5432/db` (CI sets it);+skipped otherwise, so the local suite stays infra-free. The tables are dropped and recreated.+"""++from __future__ import annotations++import os+from datetime import datetime, timedelta, timezone++import pytest++URL = os.environ.get("TRACELY_TEST_PG_URL", "")+pytestmark = pytest.mark.skipif(not URL, reason="TRACELY_TEST_PG_URL not set")++P = "p-test"+NOW = datetime.now(timezone.utc).replace(microsecond=0)++[email protected](scope="module")+def store():+ from sqlalchemy import create_engine, text+ from sqlalchemy.ext.asyncio import create_async_engine+ from sqlalchemy.pool import NullPool++ from tracely.infrastructure.spans import _pg++ base = URL.split("://", 1)[1]+ sync = create_engine(f"postgresql+psycopg://{base}", poolclass=NullPool)+ ddl = _load_upgrade_sql()+ with sync.begin() as conn:+ conn.execute(text("DROP TABLE IF EXISTS traces, scores, events"))+ conn.execute(text(ddl))+ old = _pg.SYNC, _pg.ASYNC+ # NullPool: every pytest-asyncio test runs its own loop, and asyncpg connections are loop-bound+ _pg.SYNC = sync+ _pg.ASYNC = create_async_engine(f"postgresql+asyncpg://{base}", poolclass=NullPool)+ try:+ yield _pg+ finally:+ _pg.SYNC, _pg.ASYNC = old+++def _load_upgrade_sql() -> str:+ """The 0040 migration's DDL, without needing Alembic's runtime."""+ import ast+ from pathlib import Path++ src = (+ Path(__file__).resolve().parents[1] / "migrations" / "versions" / "0040_span_store.py"+ ).read_text()+ tree = ast.parse(src)+ env: dict = {}+ for node in tree.body:+ if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "") in ("_T", "UPGRADE"):+ exec(compile(ast.Module([node], []), "0040", "exec"), env) # noqa: S102+ return env["UPGRADE"]+++def _span(trace, span, **kw):+ ev = dict(project_id=P, trace_id=trace, span_id=span, start_time=NOW, name="s", type="SPAN")+ ev.update(kw)+ return ev+++class _Res:+ def __init__(self, name, verdict, level="TRACE"):+ self.name, self.level, self.verdict, self.data_type = name, level, verdict, "BOOLEAN"+ self.value, self.string_value, self.target_span_id, self.comment, self.usage = (+ 0.0,+ "",+ "",+ "",+ None,+ )+++def _seed(store):+ from tracely.infrastructure.spans import pg_deletes, writer+ from tracely.infrastructure.spans.score_writer import ScoreWriter++ pg_deletes.delete_project_rows(P)+ # T1: a two-turn conversation's first turn, a normal root + a GENERATION delivered late+ writer.insert_events(+ [+ _span(+ "T1",+ "r",+ name="agent.run",+ type="CHAIN",+ input="refund please",+ end_time=NOW + timedelta(seconds=2),+ is_app_root=True,+ agent_id="a",+ conversation_id="C",+ metadata={"tracely.metadata.customer": "acme"},+ )+ ]+ )+ gen = _span(+ "T1",+ "g",+ parent_span_id="r",+ type="GENERATION",+ model_id="m",+ input="",+ output="sure",+ start_time=NOW + timedelta(milliseconds=10),+ end_time=NOW + timedelta(seconds=1),+ step_name="judge",+ usage_details={"input": 10, "output": 5},+ cost_details={"input": 0.25},+ )+ writer.insert_events([gen, gen]) # late + duplicated inside one batch+ # T2: second turn, ROOTLESS (driven through traceparent): app-root span only, an error+ writer.insert_events(+ [+ _span(+ "T2",+ "x",+ parent_span_id="ext",+ is_app_root=True,+ agent_id="a",+ conversation_id="C",+ input="thanks",+ level="ERROR",+ status_message="ValueError: kaboom",+ start_time=NOW + timedelta(minutes=1),+ )+ ]+ )+ # T3: Tracely's own eval run — never listed+ writer.insert_events([_span("T3", "e", internal_kind="eval", input="judge prompt")])+ sw = ScoreWriter()+ sw.write_eval_scores(+ P, "T1", "T1", [_Res("tool_ok", "FAIL"), _Res("quality", "FAIL")], thread_id="C"+ )+ sw.write_eval_scores(+ P, "T1", "T1", [_Res("tool_ok", "FAIL")], thread_id="C"+ ) # re-grade: same id+++def test_rollup_recomputes_from_spans(store):+ _seed(store)+ rows = {+ r["trace_id"]: r+ for r in store.query("SELECT * FROM traces WHERE project_id = :p", {"p": P})+ }+ t1, t2 = rows["T1"], rows["T2"]+ assert (t1["spans"], t1["tokens"], t1["model_id"], t1["thread_id"]) == (2, 15, "m", "C")+ assert t1["cost"] == pytest.approx(0.25) and t1["latency_ms"] == 2000+ assert (t1["root_input"], t1["has_input"], t1["has_output"]) == ("refund please", True, False)+ assert t1["metadata"] == {"tracely.metadata.customer": "acme"}+ # no parentless span: the app-root span is the root (the case `_TRACE_AGENT` exists for)+ assert (t2["root_input"], t2["agent_id"], t2["has_error"], t2["first_error"]) == (+ "thanks",+ "a",+ True,+ "ValueError: kaboom",+ )+ # '' is stored as NULL, so `has_input` never reads text+ assert store.query_rows("SELECT input IS NULL FROM events WHERE span_id = 'g'")[0][0] is True+ assert (+ store.query_rows("SELECT count(*) FROM scores WHERE project_id = :p", {"p": P})[0][0] == 2+ )+++async def test_readers_apply_the_verdict_policy_and_hide_internal_runs(store):+ from tracely.infrastructure.spans import reads++ _seed(store)+ stats = await reads.stats_counts(P)+ assert stats == {"traces": 2, "spans": 3, "failing_traces": 1, "auto_failures": 1}+ # both FAILs advisory -> nothing fails (`name <> ALL(:adv)`), an empty list excludes nothing+ assert (await reads.stats_counts(P, ["tool_ok", "quality"]))["auto_failures"] == 0+ page = await reads.sessions_overview(P, 50, 0)+ assert [r["thread"] for r in page] == ["C"]+ th = page[0]+ assert (th["turns"], th["failing"], th["first_input"], th["metadata"]) == (+ 2,+ 1,+ "refund please",+ {"customer": "acme"},+ )+ assert (+ isinstance(th["last_ts"], datetime) and th["last_ts"].tzinfo is None+ ) # naive UTC, like ClickHouse+ assert await reads.sessions_overview(P, 50, 0, count_only=True) == 1+ assert await reads.sessions_overview(P, 50, 0, include_internal=True, count_only=True) == 2+ assert await reads.sessions_overview(P, 50, 0, q="REFUND", count_only=True) == 1+ assert (+ await reads.sessions_overview(P, 50, 0, q="100%", count_only=True) == 0+ ) # wildcard escaped+ turns = await reads.session_turns(P, "C")+ assert [(t["trace_id"], t["failing"]) for t in turns] == [("T1", 1), ("T2", 0)]+ assert [s["span_id"] for s in await reads.trace_spans(P, "T1")] == ["r", "g"]+ assert await reads.thread_turn_count(P, "C") == 2+ ops = await reads.ops_metrics(P, 30)+ assert ops["summary"]["traces"] == 2 and ops["models"][0]["model"] == "m"+++def test_deletes_keep_the_rollup_in_step(store):+ from tracely.infrastructure.spans import pg_deletes, writer+ from tracely.infrastructure.spans.score_writer import ScoreWriter++ _seed(store)+ pg_deletes.delete_trace(P, "T1", ["other"]) # the root (no group) goes, the `judge` span stays+ assert store.query_rows("SELECT spans, root_input FROM traces WHERE trace_id = 'T1'")[0] == (+ 1,+ None,+ )+ pg_deletes.delete_trace(P, "T1")+ assert store.query_rows("SELECT count(*) FROM traces WHERE trace_id = 'T1'")[0][0] == 0+ assert ScoreWriter().retract_eval_scores(P, ["quality"], trace_id="T1", keep_ids=set()) == 1+ writer.insert_events([_span("OLD", "o", start_time=NOW - timedelta(days=100))])+ assert pg_deletes.delete_expired([P], 90) == 1+ assert store.query_rows("SELECT count(*) FROM traces WHERE trace_id = 'OLD'")[0][0] == 0diff --git a/backend/tracely/api/main.py b/backend/tracely/api/main.pyindex f5fdfa1..2523c8a 100644--- a/backend/tracely/api/main.py+++ b/backend/tracely/api/main.py@@ -37,7 +37,7 @@ from tracely.api import mcp_serverfrom tracely.api.routers import auth as auth_routerfrom tracely.auth import AuthErrorfrom tracely.config import settings-from tracely.infrastructure.clickhouse.client import close_async_client+from tracely.infrastructure import spansfrom tracely.infrastructure.db.engine import AsyncSessionLocal, async_engine, sync_enginefrom tracely.infrastructure.db.models import IngestKeyfrom tracely.log_config import configure_logging@@ -105,7 +105,10 @@ async def lifespan(app: FastAPI):async with mcp_server.mcp.session_manager.run():yield# Release pooled connections so reloads/restarts/shutdowns don't leak sockets + file descriptors.- await close_async_client()+ if not spans.POSTGRES:+ from tracely.infrastructure.clickhouse.client import close_async_client++ await close_async_client()await async_engine.dispose()sync_engine.dispose()diff --git a/backend/tracely/api/routers/admin.py b/backend/tracely/api/routers/admin.pyindex 9ab700f..46363ad 100644--- a/backend/tracely/api/routers/admin.py+++ b/backend/tracely/api/routers/admin.py@@ -19,7 +19,7 @@ from tracely.api.auth import get_project_id, require_role, require_userfrom tracely.auth import Principalfrom tracely.config import settingsfrom tracely.domain.evaluation.rolling_summary import budget_problem-from tracely.infrastructure.clickhouse import async_reader, deletes+from tracely.infrastructure.spans import async_reader, deletesfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.llm import checkpointer, providerdiff --git a/backend/tracely/api/routers/analytics.py b/backend/tracely/api/routers/analytics.pyindex 197c9f2..0266a97 100644--- a/backend/tracely/api/routers/analytics.py+++ b/backend/tracely/api/routers/analytics.py@@ -11,7 +11,7 @@ from starlette.concurrency import run_in_threadpoolfrom tracely.api.advisory import advisory_score_namesfrom tracely.api.auth import get_project_id-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocaldiff --git a/backend/tracely/api/routers/auth.py b/backend/tracely/api/routers/auth.pyindex 45ce2b0..0044928 100644--- a/backend/tracely/api/routers/auth.py+++ b/backend/tracely/api/routers/auth.py@@ -37,7 +37,7 @@ from tracely.auth.principal import Principal, select_membershipfrom tracely.config import settingsfrom tracely.domain.billing import KIND_COMPANYfrom tracely.infrastructure import mailer-from tracely.infrastructure.clickhouse import deletes+from tracely.infrastructure.spans import deletesfrom tracely.infrastructure.db import repositoriesfrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.session import get_sessiondiff --git a/backend/tracely/api/routers/calibration.py b/backend/tracely/api/routers/calibration.pyindex 106ba89..29e5eb1 100644--- a/backend/tracely/api/routers/calibration.py+++ b/backend/tracely/api/routers/calibration.py@@ -16,7 +16,7 @@ from starlette.concurrency import run_in_threadpoolfrom tracely.api.auth import get_principalfrom tracely.auth import Principalfrom tracely.domain.evaluation.calibration import merge_catalog_with_agreement-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocaldiff --git a/backend/tracely/api/routers/cases.py b/backend/tracely/api/routers/cases.pyindex 52f3804..095bad4 100644--- a/backend/tracely/api/routers/cases.py+++ b/backend/tracely/api/routers/cases.py@@ -13,7 +13,7 @@ from starlette.concurrency import run_in_threadpoolfrom tracely.api.advisory import advisory_score_namesfrom tracely.api.auth import get_project_id, require_user-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.models import EvaluationCasediff --git a/backend/tracely/api/routers/clusters.py b/backend/tracely/api/routers/clusters.pyindex 4b89e63..b82126e 100644--- a/backend/tracely/api/routers/clusters.py+++ b/backend/tracely/api/routers/clusters.py@@ -21,7 +21,7 @@ from tracely.config import settingsfrom tracely.domain.evaluation.evaluator_suggestion import suggest_evaluatorfrom tracely.domain.failure.histogram import histogramfrom tracely.domain.failure.versions import VersionRow, introduced_in-from tracely.infrastructure.clickhouse.trace_reader import TraceReader+from tracely.infrastructure.spans import TraceReaderfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.models import Agent, FailureClusterdiff --git a/backend/tracely/api/routers/evaluations.py b/backend/tracely/api/routers/evaluations.pyindex 6b29ae0..d89cc3f 100644--- a/backend/tracely/api/routers/evaluations.py+++ b/backend/tracely/api/routers/evaluations.py@@ -31,7 +31,7 @@ from starlette.concurrency import run_in_threadpoolfrom tracely.api.auth import get_project_idfrom tracely.domain import introspection-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.services.evaluation_service import EvaluationServicelog = structlog.get_logger()diff --git a/backend/tracely/api/routers/evaluators.py b/backend/tracely/api/routers/evaluators.pyindex 408bd27..c76eda2 100644--- a/backend/tracely/api/routers/evaluators.py+++ b/backend/tracely/api/routers/evaluators.py@@ -29,7 +29,7 @@ from tracely.domain.evaluation.template_resolver import (template_resolver,variables_for_level_json,)-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.models import Evaluator@@ -539,7 +539,7 @@ async def delete_evaluator(def _retract_scores(project_id: str, score_name: str) -> None:- from tracely.infrastructure.clickhouse.score_writer import ScoreWriter+ from tracely.infrastructure.spans import ScoreWritertry:ScoreWriter().retract_evaluator(project_id, score_name)diff --git a/backend/tracely/api/routers/health.py b/backend/tracely/api/routers/health.pyindex c13f4cd..2681164 100644--- a/backend/tracely/api/routers/health.py+++ b/backend/tracely/api/routers/health.py@@ -13,6 +13,7 @@ from fastapi import APIRouterfrom fastapi.responses import JSONResponsefrom sqlalchemy import text+from tracely.infrastructure import spansfrom tracely.infrastructure.clickhouse.client import get_async_clientfrom tracely.infrastructure.db.engine import AsyncSessionLocal@@ -48,12 +49,13 @@ async def queue_health() -> JSONResponse:async def health() -> JSONResponse:deps: dict[str, str] = {}- try:- client = await get_async_client()- deps["clickhouse"] = "ok" if await client.ping() else "error"- except Exception as exc: # unreachable / auth / pool exhausted- log.warning("health_clickhouse_failed", error=str(exc))- deps["clickhouse"] = "error"+ if not spans.POSTGRES: # on the Postgres store, the Postgres probe below covers spans too+ try:+ client = await get_async_client()+ deps["clickhouse"] = "ok" if await client.ping() else "error"+ except Exception as exc: # unreachable / auth / pool exhausted+ log.warning("health_clickhouse_failed", error=str(exc))+ deps["clickhouse"] = "error"try:async with AsyncSessionLocal() as s:diff --git a/backend/tracely/api/routers/meta_analysis.py b/backend/tracely/api/routers/meta_analysis.pyindex 0dcd7d4..c031b17 100644--- a/backend/tracely/api/routers/meta_analysis.py+++ b/backend/tracely/api/routers/meta_analysis.py@@ -17,7 +17,7 @@ from pydantic import BaseModelfrom starlette.concurrency import run_in_threadpoolfrom tracely.api.auth import get_project_id, require_user-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.services.meta_analysis_service import MetaAnalysisService, _to_responsediff --git a/backend/tracely/api/routers/scenarios.py b/backend/tracely/api/routers/scenarios.pyindex efcbc1d..b6c347c 100644--- a/backend/tracely/api/routers/scenarios.py+++ b/backend/tracely/api/routers/scenarios.py@@ -14,7 +14,7 @@ from starlette.concurrency import run_in_threadpoolfrom tracely.api.auth import get_project_id, require_userfrom tracely.domain.simulation import Turn, normalize_turns, serialize_turns, user_text-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.models import Agent, AgentEndpoint, Scenariodiff --git a/backend/tracely/api/routers/search.py b/backend/tracely/api/routers/search.pyindex 09868fa..c4864b8 100644--- a/backend/tracely/api/routers/search.py+++ b/backend/tracely/api/routers/search.py@@ -10,7 +10,7 @@ from fastapi import APIRouter, Dependsfrom starlette.concurrency import run_in_threadpoolfrom tracely.api.auth import get_project_id-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.text import message_textdiff --git a/backend/tracely/api/routers/sessions.py b/backend/tracely/api/routers/sessions.pyindex 6606814..fc7a31c 100644--- a/backend/tracely/api/routers/sessions.py+++ b/backend/tracely/api/routers/sessions.py@@ -19,7 +19,7 @@ from tracely.api.auth import get_project_id, require_userfrom tracely.domain.traces.replay import build_replayfrom tracely.domain.evaluation.template_resolver import AgentView, collect_agentsfrom tracely.domain.evaluation.verdict import rollup_verdict-from tracely.infrastructure.clickhouse import async_reader, deletes+from tracely.infrastructure.spans import async_reader, deletesfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.services.rolling_summary_service import RollingSummaryServicediff --git a/backend/tracely/api/routers/share.py b/backend/tracely/api/routers/share.pyindex 90acf54..62365ee 100644--- a/backend/tracely/api/routers/share.py+++ b/backend/tracely/api/routers/share.py@@ -34,7 +34,7 @@ from tracely.auth.tokens import (verify_share,)from tracely.domain.evaluation.verdict import rollup_verdict-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.models import Agent, GateRundiff --git a/backend/tracely/api/routers/traces.py b/backend/tracely/api/routers/traces.pyindex 9672970..16d5b55 100644--- a/backend/tracely/api/routers/traces.py+++ b/backend/tracely/api/routers/traces.py@@ -11,7 +11,7 @@ from tracely.api.advisory import advisory_score_namesfrom tracely.api.auth import get_project_idfrom tracely.api.dto.traces import SpanOut, TraceDetailfrom tracely.domain.evaluation.verdict import rollup_verdict-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerrouter = APIRouter(prefix="/api")diff --git a/backend/tracely/config.py b/backend/tracely/config.pyindex 8028fc2..915339b 100644--- a/backend/tracely/config.py+++ b/backend/tracely/config.py@@ -3,6 +3,7 @@from __future__ import annotationsfrom functools import lru_cache+from typing import Literalfrom pydantic import field_validator, model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDict@@ -17,6 +18,14 @@ class Settings(BaseSettings):database_url: str = "postgresql+asyncpg://tracely:tracely@localhost:5432/tracely"alembic_database_url: str = "postgresql+psycopg://tracely:tracely@localhost:5432/tracely"+ # Where spans (`events`) and `scores` live: "clickhouse" (legacy) or "postgres" (the same+ # database as the registry). Read once at import by `tracely.infrastructure.spans`, so the API+ # and the worker must agree — set it on both. See design/part2-tracely/14-clickhouse-to-postgres.md.+ span_store: Literal["clickhouse", "postgres"] = "clickhouse"+ # Days a trace is kept on the Postgres store (the ClickHouse TTL's twin; plan retention can+ # only shorten it). 0 disables expiry.+ span_retention_days: int = 90+# ClickHouseclickhouse_host: str = "localhost"clickhouse_port: int = 8123diff --git a/backend/tracely/infrastructure/clickhouse/async_reader.py b/backend/tracely/infrastructure/clickhouse/async_reader.pyindex 412554f..157d59a 100644--- a/backend/tracely/infrastructure/clickhouse/async_reader.py+++ b/backend/tracely/infrastructure/clickhouse/async_reader.py@@ -1245,3 +1245,21 @@ async def trace_failure_totals(project_id: str, advisory: Sequence[str] = ()) ->{"adv": list(advisory)},)return total, failures+++# ── ops ───────────────────────────────────────────────────────────────────────+++async def store_health() -> tuple[object, float | None]:+ """`(newest span time, disk free %)` for the self-check. One connection: a full disk is the+ failure mode that takes ClickHouse down entirely, and it arrives gradually enough to catch."""+ client = await get_async_client()+ rows = (await client.query("SELECT max(start_time) FROM events FINAL WHERE is_deleted = 0")).result_rows+ newest = rows[0][0] if rows and rows[0] else None+ disks = (+ await client.query(+ "SELECT free_space, total_space FROM system.disks ORDER BY total_space DESC LIMIT 1"+ )+ ).result_rows+ free = 100.0 * float(disks[0][0]) / float(disks[0][1]) if disks and disks[0][1] else None+ return newest, freediff --git a/backend/tracely/infrastructure/clickhouse/trace_reader.py b/backend/tracely/infrastructure/clickhouse/trace_reader.pyindex ff94902..8103272 100644--- a/backend/tracely/infrastructure/clickhouse/trace_reader.py+++ b/backend/tracely/infrastructure/clickhouse/trace_reader.py@@ -97,6 +97,18 @@ class TraceReader:).result_rowsreturn [tid for (tid,) in rows]+ def trace_generations(self, project_id: str, trace_id: str) -> list[tuple]:+ """`(input, output, start_time)` of one trace's GENERATION spans — the ingest-time+ "Agent workflow" root fill (was raw SQL inside `IngestionService`)."""+ return [+ tuple(r)+ for r in self.client.query(+ "SELECT input, output, start_time FROM events FINAL PREWHERE trace_id = {t:String} "+ "WHERE project_id = {p:String} AND is_deleted = 0 AND type = 'GENERATION'",+ parameters={"t": trace_id, "p": project_id},+ ).result_rows+ ]+def candidate_metrics(self, project_id: str, trace_ids: Iterable[str]) -> tuple[float, int, dict[str, tuple[float, int]]]:diff --git a/backend/tracely/infrastructure/queue/celery_app.py b/backend/tracely/infrastructure/queue/celery_app.pyindex 768467c..78c87f6 100644--- a/backend/tracely/infrastructure/queue/celery_app.py+++ b/backend/tracely/infrastructure/queue/celery_app.py@@ -58,6 +58,12 @@ celery_app.conf.update("task": "tracely.enforce_retention","schedule": crontab(hour="4", minute="47"),},+ # The Postgres span store's 90-day horizon (ClickHouse's table TTL did this itself; on+ # ClickHouse the task is a no-op). Every deployment, billing or not.+ "tracely.expire_spans-nightly": {+ "task": "tracely.expire_spans",+ "schedule": crontab(hour="4", minute="57"),+ },# ClickHouse's own logs have no TTL and outgrow the product's data on a small box. Same# nightly window, offset again so the solo worker takes one sweep at a time."tracely.cap_system_logs-nightly": {diff --git a/backend/tracely/infrastructure/spans/__init__.py b/backend/tracely/infrastructure/spans/__init__.pynew file mode 100644index 0000000..b9210b0--- /dev/null+++ b/backend/tracely/infrastructure/spans/__init__.py@@ -0,0 +1,42 @@+"""The span store: where `events` and `scores` live, picked once at import by `SPAN_STORE`.++Every caller imports the store from here — `async_reader`, `deletes`, `TraceReader`,+`ScoreWriter`, `insert_events` — never from `infrastructure.clickhouse` or the Postgres modules+directly, so flipping the setting moves the whole product at once. The two implementations have+identical names, signatures and return shapes. (The Postgres delete module is `pg_deletes`, not+`deletes`: a submodule named like an attribute this package exports gets swapped in by the import+system the moment anything imports it, silently pointing every `spans.deletes` caller at the+other store.)++ponytail: two stores exist only for the cutover (design/part2-tracely/14-clickhouse-to-postgres.md+§8). Once prod has run on Postgres for a while, delete `infrastructure/clickhouse/` and this switch.+"""++from __future__ import annotations++from typing import Any++from tracely.config import settings++POSTGRES = settings.span_store == "postgres"++if POSTGRES:+ from tracely.infrastructure.spans import pg_deletes as deletes+ from tracely.infrastructure.spans import reads as async_reader+ from tracely.infrastructure.spans.score_writer import ScoreWriter+ from tracely.infrastructure.spans.trace_reader import TraceReader+ from tracely.infrastructure.spans.writer import insert_events+else:+ from tracely.infrastructure.clickhouse import async_reader, deletes+ from tracely.infrastructure.clickhouse.score_writer import ScoreWriter+ from tracely.infrastructure.clickhouse.trace_reader import TraceReader++ def insert_events(events: list[dict[str, Any]]) -> int:+ from tracely.infrastructure.clickhouse.client import get_client, insert_rows+ from tracely.infrastructure.clickhouse.events_schema import EVENT_COLUMNS, to_rows++ insert_rows(get_client(), "events", EVENT_COLUMNS, to_rows(events))+ return len(events)+++__all__ = ["POSTGRES", "ScoreWriter", "TraceReader", "async_reader", "deletes", "insert_events"]diff --git a/backend/tracely/infrastructure/spans/_pg.py b/backend/tracely/infrastructure/spans/_pg.pynew file mode 100644index 0000000..31dac26--- /dev/null+++ b/backend/tracely/infrastructure/spans/_pg.py@@ -0,0 +1,80 @@+"""Connections + result shaping shared by the Postgres span-store modules.++Everything here exists so a Postgres reader returns *exactly* what its ClickHouse twin returned —+the routers, services and frontend were written against those shapes:++- datetimes come back **naive UTC** (clickhouse-connect returns naive `DateTime64`; a stray aware+ one breaks every `now() - ts` in the services and changes the JSON the frontend parses);+- `Decimal` (Postgres `sum(bigint)`/`numeric`) becomes float — readers cast integer sums to+ `bigint` in SQL, this is only the safety net.++`SYNC` / `ASYNC` are module globals so tests can point them at a scratch database.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from datetime import datetime, timezone+from decimal import Decimal+from typing import Any++from sqlalchemy import text++from tracely.infrastructure.db import engine as _engine++SYNC = _engine.sync_engine+ASYNC = _engine.async_engine+++def norm(v: Any) -> Any:+ if isinstance(v, datetime) and v.tzinfo is not None:+ return v.astimezone(timezone.utc).replace(tzinfo=None)+ if isinstance(v, Decimal):+ return float(v)+ return v+++def utc(v: Any) -> Any:+ """Writes: a naive datetime is UTC (that is what ClickHouse stored and what the OTel mapper+ produces), so say so before Postgres reads it in the session's time zone."""+ if isinstance(v, datetime) and v.tzinfo is None:+ return v.replace(tzinfo=timezone.utc)+ return v+++def dicts(rows: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:+ return [{k: norm(v) for k, v in r.items()} for r in rows]+++def tuples(rows: Iterable[Iterable[Any]]) -> list[tuple]:+ return [tuple(norm(v) for v in r) for r in rows]+++def query(sql: str, params: Mapping[str, Any] | None = None) -> list[dict[str, Any]]:+ """Sync read -> list of dicts (column name -> value)."""+ with SYNC.connect() as conn:+ return dicts(conn.execute(text(sql), dict(params or {})).mappings())+++def query_rows(sql: str, params: Mapping[str, Any] | None = None) -> list[tuple]:+ with SYNC.connect() as conn:+ return tuples(conn.execute(text(sql), dict(params or {})))+++async def aquery(sql: str, params: Mapping[str, Any] | None = None) -> list[dict[str, Any]]:+ """Async read (API) -> list of dicts."""+ async with ASYNC.connect() as conn:+ res = await conn.execute(text(sql), dict(params or {}))+ return dicts(res.mappings())+++async def aquery_rows(sql: str, params: Mapping[str, Any] | None = None) -> list[tuple]:+ async with ASYNC.connect() as conn:+ res = await conn.execute(text(sql), dict(params or {}))+ return tuples(res)+++def like(q: str) -> str:+ """`q` as a case-insensitive *substring* pattern (ClickHouse `positionCaseInsensitive > 0`):+ escape the LIKE wildcards the user typed, so `100%` searches for a literal percent sign."""+ return "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"diff --git a/backend/tracely/infrastructure/spans/copy.py b/backend/tracely/infrastructure/spans/copy.pynew file mode 100644index 0000000..838f542--- /dev/null+++ b/backend/tracely/infrastructure/spans/copy.py@@ -0,0 +1,322 @@+"""Copy spans + scores from ClickHouse into the Postgres span store, then prove the two agree.++ python -m tracely.infrastructure.spans.copy # every project, then --verify+ python -m tracely.infrastructure.spans.copy --project P # one project+ python -m tracely.infrastructure.spans.copy --verify-only # compare, copy nothing++Reads ClickHouse the way the product does (FINAL, `is_deleted = 0`, lightweight-deleted rows+masked), so only LIVE data crosses — prod's 89% of dead rows never do. Writes through the same+`writer.write_events` the ingest path uses, so spans and the `traces` rollup land together.+Idempotent: every write is an upsert on a deterministic key, so re-running after a crash, or once+more right before the cutover to pick up the stragglers, converges instead of duplicating.++Verification runs the product's own readers against BOTH stores (ClickHouse `async_reader` vs+Postgres `reads`) for every project and a sample of its threads and traces, and reports every+disagreement. Exit status 1 on any mismatch — do not flip `SPAN_STORE` until it is 0.+Known, accepted differences are listed in design/part2-tracely/14-clickhouse-to-postgres.md §5;+the readers they touch are compared on the parts that did not change.++ponytail: one process, trace batches of 500. Prod is ~66k spans (about a minute); a much bigger+workspace wants a per-month split.+"""++from __future__ import annotations++import argparse+import asyncio+import math+import sys+from datetime import datetime+from typing import Any++from sqlalchemy import text++from tracely.infrastructure.clickhouse import async_reader as ch_reads+from tracely.infrastructure.clickhouse.client import get_client+from tracely.infrastructure.clickhouse.events_schema import EVENT_COLUMNS+from tracely.infrastructure.spans import _pg+from tracely.infrastructure.spans import reads as pg_reads+from tracely.infrastructure.spans.score_writer import _COLS as SCORE_COLS+from tracely.infrastructure.spans.score_writer import _UPSERT as SCORE_UPSERT+from tracely.infrastructure.spans.score_writer import _row as score_row+from tracely.infrastructure.spans.writer import write_events++TRACE_BATCH = 500+SCORE_BATCH = 5000+_CH_SCORE_COLS = [c for c in SCORE_COLS if c != "metadata"] + ["metadata"]+++# ── copy ──────────────────────────────────────────────────────────────────────+++def projects(ch) -> list[str]:+ rows = ch.query(+ "SELECT DISTINCT project_id FROM events FINAL WHERE is_deleted = 0 "+ "UNION DISTINCT SELECT DISTINCT project_id FROM scores FINAL WHERE is_deleted = 0"+ ).result_rows+ return sorted(r[0] for r in rows)+++def copy_project(ch, project_id: str, log=print) -> dict[str, int]:+ trace_ids = [+ r[0]+ for r in ch.query(+ "SELECT DISTINCT trace_id FROM events FINAL WHERE project_id = {p:String} AND is_deleted = 0",+ parameters={"p": project_id},+ ).result_rows+ ]+ spans = 0+ for i in range(0, len(trace_ids), TRACE_BATCH):+ batch = trace_ids[i : i + TRACE_BATCH]+ res = ch.query(+ f"SELECT {', '.join(EVENT_COLUMNS)} FROM events FINAL PREWHERE trace_id IN {{t:Array(String)}} "+ "WHERE project_id = {p:String} AND is_deleted = 0",+ parameters={"p": project_id, "t": batch},+ )+ events = [dict(zip(res.column_names, row)) for row in res.result_rows]+ with _pg.SYNC.begin() as conn: # whole traces per batch, so each rollup sees all its spans+ spans += write_events(conn, events, lock=False)+ log(+ f" {project_id}: spans {spans} ({min(i + TRACE_BATCH, len(trace_ids))}/{len(trace_ids)} traces)"+ )+ scores = 0+ offset = 0+ while True:+ res = ch.query(+ f"SELECT {', '.join(_CH_SCORE_COLS)} FROM scores FINAL WHERE project_id = {{p:String}} "+ "AND is_deleted = 0 ORDER BY id LIMIT {n:UInt32} OFFSET {o:UInt32}",+ parameters={"p": project_id, "n": SCORE_BATCH, "o": offset},+ )+ rows = [score_row(**dict(zip(res.column_names, r))) for r in res.result_rows]+ if not rows:+ break+ with _pg.SYNC.begin() as conn:+ conn.execute(text(SCORE_UPSERT), rows)+ scores += len(rows)+ offset += SCORE_BATCH+ log(f" {project_id}: scores {scores}")+ return {"traces": len(trace_ids), "spans": spans, "scores": scores}+++# ── verify ────────────────────────────────────────────────────────────────────+++def _blank(v: Any) -> bool:+ return v is None or v == ""+++def same(a: Any, b: Any, path: str = "") -> list[str]:+ """Differences between a ClickHouse result and a Postgres one. Tolerates what is not a+ difference: None vs '' (ClickHouse Nullable text vs a NULL), int vs float of equal value,+ float noise, and ±1 on integer-rounded percentiles."""+ if _blank(a) and _blank(b):+ return []+ if path.endswith(".metadata") and isinstance(a, dict) and isinstance(b, dict):+ # A thread whose turns disagree on a metadata key: ClickHouse keeps an arbitrary one,+ # Postgres the latest turn's. The KEYS must match; the values are not comparable.+ return [] if set(a) == set(b) else [f"{path}: keys {sorted(a)} vs {sorted(b)}"]+ if isinstance(a, dict) and isinstance(b, dict):+ out: list[str] = []+ for k in sorted(set(a) | set(b), key=str):+ out += same(a.get(k), b.get(k), f"{path}.{k}")+ return out+ if isinstance(a, (list, tuple, set)) and isinstance(b, (list, tuple, set)):+ if isinstance(a, set) or isinstance(b, set):+ a, b = sorted(a, key=str), sorted(b, key=str)+ if len(a) != len(b):+ return [f"{path}: {len(a)} vs {len(b)} items"]+ out = []+ for i, (x, y) in enumerate(zip(a, b)):+ out += same(x, y, f"{path}[{i}]")+ return out+ if isinstance(a, bool) or isinstance(b, bool):+ return [] if bool(a) == bool(b) else [f"{path}: {a!r} vs {b!r}"]+ if isinstance(a, (int, float)) and isinstance(b, (int, float)):+ if math.isclose(a, b, rel_tol=1e-6, abs_tol=1e-9):+ return []+ if any(k in path for k in ("p50", "p95", "p99", "ttft")) and abs(a - b) <= 1:+ return []+ # ClickHouse dates a trace by EACH span's day, so one crossing midnight UTC counts on both+ # days; Postgres dates it once, by its first span. Off by a trace or two per day, no more.+ if "daily" in path:+ if abs(a - b) <= max(1, 0.01 * max(abs(a), abs(b))):+ return []+ return [f"{path}: {a!r} vs {b!r}"]+ if isinstance(a, datetime) and isinstance(b, datetime):+ return [] if a.replace(tzinfo=None) == b.replace(tzinfo=None) else [f"{path}: {a} vs {b}"]+ return [] if a == b else [f"{path}: {str(a)[:80]!r} vs {str(b)[:80]!r}"]+++def _by(rows: list[dict], key: str) -> dict:+ return {r[key]: r for r in rows}+++async def verify_project(project_id: str, samples: int = 25) -> list[str]:+ """Every mismatch between the two stores for one project (empty list = they agree)."""+ problems: list[str] = []++ async def check(name: str, ch_call, pg_call, key: str | None = None, sort: bool = False):+ try:+ a, b = await ch_call, await pg_call+ except Exception as exc: # noqa: BLE001 — a reader that crashes IS the finding+ problems.append(f"{name}: raised {exc!r}")+ return+ if key:+ a, b = _by(a, key), _by(b, key)+ elif sort:+ a, b = sorted(a, key=str), sorted(b, key=str)+ problems.extend(same(a, b, name)[:5])++ p = project_id+ await check("stats_counts", ch_reads.stats_counts(p), pg_reads.stats_counts(p))+ await check(+ "trace_failure_totals", ch_reads.trace_failure_totals(p), pg_reads.trace_failure_totals(p)+ )+ await check(+ "traces_in_window", ch_reads.traces_in_window(p, 7), pg_reads.traces_in_window(p, 7)+ )+ await check(+ "daily_trace_failures",+ ch_reads.daily_trace_failures(p, 30),+ pg_reads.daily_trace_failures(p, 30),+ )+ await check("ops_metrics", ch_reads.ops_metrics(p, 30), pg_reads.ops_metrics(p, 30))+ await check(+ "traces_overview",+ ch_reads.traces_overview(p, 200),+ pg_reads.traces_overview(p, 200),+ key="trace_id",+ )+ await check("trace_agent_ids", ch_reads.trace_agent_ids(p), pg_reads.trace_agent_ids(p))+ await check(+ "agent_ids_with_spans", ch_reads.agent_ids_with_spans(p), pg_reads.agent_ids_with_spans(p)+ )+ await check(+ "evaluator_catalog",+ ch_reads.evaluator_catalog(p),+ pg_reads.evaluator_catalog(p),+ key="name",+ )+ await check("evaluator_cost", ch_reads.evaluator_cost(p), pg_reads.evaluator_cost(p))+ await check(+ "sessions_overview.count",+ ch_reads.sessions_overview(p, 0, 0, count_only=True),+ pg_reads.sessions_overview(p, 0, 0, count_only=True),+ )+ await check(+ "sessions_overview.count(failing)",+ ch_reads.sessions_overview(p, 0, 0, failing=True, count_only=True),+ pg_reads.sessions_overview(p, 0, 0, failing=True, count_only=True),+ )+ await check(+ "sessions_overview.page",+ ch_reads.sessions_overview(p, 100, 0),+ pg_reads.sessions_overview(p, 100, 0),+ )+ threads = [r["thread"] for r in await pg_reads.sessions_overview(p, samples, 0)]+ for th in threads:+ await check(+ f"session_turns[{th}]",+ ch_reads.session_turns(p, th),+ pg_reads.session_turns(p, th),+ key="trace_id",+ )+ await check(+ f"thread_turn_count[{th}]",+ ch_reads.thread_turn_count(p, th),+ pg_reads.thread_turn_count(p, th),+ )+ await check(+ f"thread_spans_full[{th}]",+ ch_reads.thread_spans_full(p, th),+ pg_reads.thread_spans_full(p, th),+ key="span_id",+ )+ await check(+ f"conversation_scores[{th}]",+ ch_reads.conversation_scores(p, th),+ pg_reads.conversation_scores(p, th),+ sort=True,+ )+ traces = [r["trace_id"] for r in await pg_reads.traces_overview(p, samples)]+ for t in traces:+ await check(+ f"trace_spans[{t}]",+ ch_reads.trace_spans(p, t),+ pg_reads.trace_spans(p, t),+ key="span_id",+ )+ await check(+ f"trace_scores[{t}]",+ ch_reads.trace_scores(p, t, ""),+ pg_reads.trace_scores(p, t, ""),+ sort=True,+ )+ return problems+++def _counts_ch(ch, project_id: str) -> dict[str, int]:+ q = lambda sql: int(ch.query(sql, parameters={"p": project_id}).result_rows[0][0]) # noqa: E731+ return {+ "spans": q(+ "SELECT count() FROM events FINAL WHERE project_id = {p:String} AND is_deleted = 0"+ ),+ "traces": q(+ "SELECT uniqExact(trace_id) FROM events FINAL WHERE project_id = {p:String} AND is_deleted = 0"+ ),+ "scores": q(+ "SELECT count() FROM scores FINAL WHERE project_id = {p:String} AND is_deleted = 0"+ ),+ }+++def _counts_pg(project_id: str) -> dict[str, int]:+ q = lambda sql: int(_pg.query_rows(sql, {"p": project_id})[0][0]) # noqa: E731+ return {+ "spans": q("SELECT count(*) FROM events WHERE project_id = :p"),+ "traces": q("SELECT count(*) FROM traces WHERE project_id = :p"),+ "scores": q("SELECT count(*) FROM scores WHERE project_id = :p"),+ }+++def main(argv: list[str] | None = None) -> int:+ ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ ap.add_argument("--project", action="append", help="only this project (repeatable)")+ ap.add_argument("--verify-only", action="store_true", help="compare the stores, copy nothing")+ ap.add_argument("--no-verify", action="store_true", help="copy, skip the comparison")+ ap.add_argument("--samples", type=int, default=25, help="threads/traces compared per project")+ args = ap.parse_args(argv)++ ch = get_client()+ todo = args.project or projects(ch)+ print(f"{len(todo)} project(s)")+ if not args.verify_only:+ for p in todo:+ print(f"copy {p}: {copy_project(ch, p)}")+ if args.no_verify:+ return 0+ # One event loop for every project: both stores' async pools are bound to the loop they+ # were opened on, so a fresh `asyncio.run` per project would reuse dead connections.+ failed = asyncio.run(_verify_all(ch, todo, args.samples))+ print("FAILED — do not switch SPAN_STORE" if failed else "OK — stores agree")+ return 1 if failed else 0+++async def _verify_all(ch, todo: list[str], samples: int) -> bool:+ failed = False+ for p in todo:+ a, b = _counts_ch(ch, p), _counts_pg(p)+ counts_ok = a == b+ problems = await verify_project(p, samples)+ failed |= (not counts_ok) or bool(problems)+ print(+ f"verify {p}: counts {'ok' if counts_ok else f'MISMATCH clickhouse={a} postgres={b}'}, "+ f"{len(problems)} reader mismatch(es)"+ )+ for line in problems[:40]:+ print(f" {line}")+ return failed+++if __name__ == "__main__":+ sys.exit(main())diff --git a/backend/tracely/infrastructure/spans/pg_deletes.py b/backend/tracely/infrastructure/spans/pg_deletes.pynew file mode 100644index 0000000..8f22500--- /dev/null+++ b/backend/tracely/infrastructure/spans/pg_deletes.py@@ -0,0 +1,136 @@+"""Postgres twin of `clickhouse.deletes` (exported as `spans.deletes` on the Postgres store) — same functions, same return values.++Real DELETEs: no tombstones, no masked rows that every query still reads, no compaction job.+Every path that removes spans keeps the `traces` rollup in step in the same transaction.++ponytail: each project-wide delete is one statement. Fine at prod's size (tens of thousands of+spans); batch by ctid if a single workspace ever holds millions and the request times out.+"""++from __future__ import annotations++from datetime import datetime++from sqlalchemy import text++from tracely.infrastructure.spans import _pg, rollup+++def delete_trace(project_id: str, trace_id: str, step_names: list[str] | None = None) -> None:+ """Drop one trace's spans — or only `step_names`' spans plus the root (which carries no+ group) — before a re-recorded internal run lands. See the ClickHouse twin for why the+ narrowing exists."""+ sql = "DELETE FROM events WHERE project_id = :p AND trace_id = :t"+ params: dict = {"p": project_id, "t": trace_id}+ if step_names:+ sql += " AND (step_name = ANY(:n) OR step_name = '')"+ params["n"] = list(step_names)+ with _pg.SYNC.begin() as conn:+ rollup.lock(conn, project_id, [trace_id])+ if conn.execute(text(sql), params).rowcount:+ rollup.refresh(conn, project_id, [trace_id])+++async def delete_threads(project_id: str, threads: list[str]) -> int:+ """Delete every trace in these threads, plus their scores. Returns traces removed."""+ if not threads:+ return 0+ async with _pg.ASYNC.begin() as conn:+ res = await conn.execute(+ text(+ "DELETE FROM traces WHERE project_id = :p "+ "AND (thread_id = ANY(:t) OR trace_id = ANY(:t)) RETURNING trace_id"+ ),+ {"p": project_id, "t": list(threads)},+ )+ trace_ids = [r[0] for r in res]+ if not trace_ids:+ return 0+ params = {"p": project_id, "ids": trace_ids, "t": list(threads)}+ await conn.execute(+ text("DELETE FROM events WHERE project_id = :p AND trace_id = ANY(:ids)"), params+ )+ await conn.execute(+ text(+ "DELETE FROM scores WHERE project_id = :p "+ "AND (trace_id = ANY(:ids) OR session_id = ANY(:t))"+ ),+ params,+ )+ return len(trace_ids)+++async def delete_project_events(project_id: str) -> dict[str, int]:+ """Delete every span and score in a project. Returns the row counts removed."""+ counts: dict[str, int] = {}+ async with _pg.ASYNC.begin() as conn:+ for table in ("events", "scores"):+ res = await conn.execute(+ text(f"DELETE FROM {table} WHERE project_id = :p"), {"p": project_id}+ )+ counts[table] = res.rowcount or 0+ await conn.execute(text("DELETE FROM traces WHERE project_id = :p"), {"p": project_id})+ return {k: v for k, v in counts.items() if v}+++def delete_expired(project_ids: list[str], days: int) -> int:+ """Drop traces whose NEWEST span is older than `days`, with their spans; scores are cut on+ their own `created_at` (the ClickHouse twin's rule). Whole traces, so a long-running trace is+ never cut in half the way a per-span TTL did. Returns spans removed."""+ if not project_ids or days <= 0:+ return 0+ params = {"p": list(project_ids), "d": days}+ cutoff = "now() - make_interval(days => :d)"+ with _pg.SYNC.begin() as conn:+ doomed = conn.execute(+ text(+ f"DELETE FROM traces WHERE project_id = ANY(:p) AND ts_max < {cutoff} "+ "RETURNING project_id, trace_id"+ ),+ params,+ ).all()+ if not doomed:+ spans = 0+ else:+ spans = (+ conn.execute(+ text(+ "DELETE FROM events e USING unnest(CAST(:pp AS text[]), CAST(:tt AS text[])) AS d(p, t) "+ "WHERE e.project_id = d.p AND e.trace_id = d.t"+ ),+ {"pp": [r[0] for r in doomed], "tt": [r[1] for r in doomed]},+ ).rowcount+ or 0+ )+ conn.execute(+ text(f"DELETE FROM scores WHERE project_id = ANY(:p) AND created_at < {cutoff}"), params+ )+ return spans+++def expire_all(days: int) -> int:+ """The ClickHouse table TTL's twin: every project, `SPAN_RETENTION_DAYS`. Returns spans removed."""+ if days <= 0:+ return 0+ projects = [r[0] for r in _pg.query_rows("SELECT DISTINCT project_id FROM traces")]+ return delete_expired(projects, days)+++def delete_project_rows(project_id: str) -> None:+ """Every span, score and rollup row of one project — the orphan sweep's worker-side delete."""+ with _pg.SYNC.begin() as conn:+ for table in ("events", "scores", "traces"):+ conn.execute(text(f"DELETE FROM {table} WHERE project_id = :p"), {"p": project_id})+++def last_write_by_project() -> dict[str, datetime]:+ """`{project_id: newest write}` across spans and scores — the orphan sweep's guard. Naive UTC,+ like the ClickHouse twin (`purge_service` compares it with naive timestamps)."""+ out: dict[str, datetime] = {}+ for sql in (+ "SELECT project_id, max(updated_at) FROM traces GROUP BY project_id",+ "SELECT project_id, max(created_at) FROM scores GROUP BY project_id",+ ):+ for pid, ts in _pg.query_rows(sql):+ out[pid] = max(ts, out[pid]) if pid in out else ts+ return outdiff --git a/backend/tracely/infrastructure/spans/reads.py b/backend/tracely/infrastructure/spans/reads.pynew file mode 100644index 0000000..8c5dcaf--- /dev/null+++ b/backend/tracely/infrastructure/spans/reads.py@@ -0,0 +1,811 @@+"""Async Postgres reads for the API — the twin of `clickhouse.async_reader`, function for function.++Same names, signatures and return shapes, so routers and services do not change (pick the store+in `tracely.infrastructure.spans`). Two sources:++- `traces` — the per-trace rollup (`spans.rollup`): every list, count and trend;+- `events` — spans, by index: one trace or thread, span-level metrics (per model, per span name).++The SQL twins every caller relies on, defined once each:++- `_FAILING` / `_FAILING_THREADS` — the verdict policy: a FAIL on a NON-advisory evaluator,+ `name <> ALL(:adv)` (an empty array excludes nothing, exactly like ClickHouse `NOT IN []`).+ Mirror of `domain.evaluation.verdict`; change them together.+- `_REAL` — `internal_kind = ''`: Tracely's own eval/sim recordings stay out of every list, count+ and metric; `sessions_overview(include_internal=True)` is the only opt-in.++Deliberate differences from ClickHouse are listed in design/part2-tracely/14-clickhouse-to-postgres.md §5.+"""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Sequence++from tracely.domain.traces.metadata import parse_thread_meta+from tracely.domain.traces.spans import system_prompt+from tracely.infrastructure.spans._pg import aquery, aquery_rows, like++_ONLINE = "source = 'EVAL' AND evaluation_case_id = ''"+_FAILING = (+ f"SELECT trace_id FROM scores WHERE project_id = :p AND {_ONLINE} AND verdict = 'FAIL' "+ "AND name <> ALL(:adv)"+)+_FAILING_THREADS = (+ f"SELECT session_id FROM scores WHERE project_id = :p AND {_ONLINE} AND verdict = 'FAIL' "+ "AND evaluation_level = 'CONVERSATION' AND name <> ALL(:adv)"+)+_REAL = "internal_kind = ''"+_SCORE_COLS = (+ "name, evaluation_level, observation_id, value, string_value, verdict, comment, data_type"+)++# The span columns the eval runner / regression / gate / FI read (`trace_reader._SPAN_COLS`).+SPAN_COLS = [+ "span_id",+ "parent_span_id",+ "type",+ "name",+ "level",+ "status_message",+ "start_time",+ "end_time",+ "completion_start_time",+ "agent_id",+ "agent_version_id",+ "agent_run_id",+ "turn_id",+ "step_id",+ "model_id",+ "input",+ "output",+ "tool_call_names",+ "tool_calls",+ "trace_id",+ "is_app_root",+ "conversation_id",+ "env",+ "caller_agent_id",+ "callee_agent_id",+ "metadata",+ "tokens",+ "cost",+]+++# ClickHouse dateDiff('millisecond', a, b): whole milliseconds, each side truncated.+def _ms(a: str, b: str) -> str:+ return (+ f"(floor(extract(epoch FROM {b}) * 1000) - floor(extract(epoch FROM {a}) * 1000))::bigint"+ )+++_SPAN_MS = _ms("start_time", "coalesce(end_time, start_time)")+_UTC_DAY = "(ts_min AT TIME ZONE 'UTC')::date" # ClickHouse toDate(): the UTC calendar day+++def _days_ago(param: str = "d") -> str:+ return f"now() - make_interval(days => :{param})"+++def _mins_ago(param: str = "w") -> str:+ return f"now() - make_interval(mins => :{param})"+++def _int(v) -> int:+ return int(v) if v is not None else 0+++# ── traces ────────────────────────────────────────────────────────────────────+++async def traces_overview(project_id: str, limit: int, advisory: Sequence[str] = ()) -> list[dict]:+ rows = await aquery(+ "SELECT trace_id, ts_min AS ts, spans, coalesce(nullif(root_name, ''), first_name) AS root_name, "+ "agent_id, CASE WHEN has_error THEN 1 ELSE 0 END AS has_error "+ f"FROM traces WHERE project_id = :p AND {_REAL} ORDER BY ts_min DESC LIMIT :n",+ {"p": project_id, "n": max(limit, 0)},+ )+ if rows:+ ev = await aquery_rows(+ "SELECT trace_id, bool_or(verdict = 'FAIL' AND name <> ALL(:adv)) FROM scores "+ f"WHERE project_id = :p AND {_ONLINE} AND trace_id = ANY(:ids) GROUP BY trace_id",+ {"p": project_id, "adv": list(advisory), "ids": [r["trace_id"] for r in rows]},+ )+ verdict = {tid: ("FAIL" if fail else "PASS") for tid, fail in ev}+ for r in rows:+ r["eval"] = verdict.get(r["trace_id"])+ return rows+++async def trace_spans(project_id: str, trace_id: str) -> list[dict]:+ return await aquery(+ "SELECT span_id, parent_span_id, name, type, level, status_message, "+ "start_time, end_time, completion_start_time, agent_id, agent_run_id, turn_id, step_name, "+ "model_id, input, output, metadata, conversation_id, tokens, cost "+ "FROM events WHERE project_id = :p AND trace_id = :t ORDER BY start_time",+ {"p": project_id, "t": trace_id},+ )+++async def thread_spans_full(project_id: str, thread_id: str) -> list[dict]:+ """Same columns as the sync eval reader, so the template preview resolves what the run grades."""+ return await aquery(+ f"SELECT {', '.join(SPAN_COLS)} FROM events WHERE project_id = :p "+ "AND (conversation_id = :th OR trace_id = :th) ORDER BY start_time",+ {"p": project_id, "th": thread_id},+ )+++async def thread_turn_count(project_id: str, thread_id: str) -> int:+ rows = await aquery_rows(+ "SELECT count(*) FROM traces WHERE project_id = :p "+ f"AND (conversation_id = :th OR trace_id = :th) AND {_REAL}",+ {"p": project_id, "th": thread_id},+ )+ return _int(rows[0][0]) if rows else 0+++async def trace_scores(project_id: str, trace_id: str, thread_id: str) -> list[dict]:+ return await aquery(+ f"SELECT {_SCORE_COLS} FROM scores WHERE project_id = :p AND {_ONLINE} "+ "AND (trace_id = :t OR (evaluation_level = 'CONVERSATION' AND session_id = :th)) "+ "ORDER BY evaluation_level, name",+ {"p": project_id, "t": trace_id, "th": thread_id},+ )+++def _meta_int(key: str) -> str:+ """ClickHouse toUInt64OrZero(metadata[key]): the number, or 0 for missing / not a number."""+ v = f"(metadata->>'{key}')"+ return f"CASE WHEN {v} ~ '^[0-9]+$' THEN {v}::bigint ELSE 0 END"+++async def evaluator_cost(project_id: str, days: int = 30) -> dict[str, dict]:+ rows = await aquery_rows(+ "SELECT name, count(*) FILTER (WHERE metadata ? 'eval.total_tokens') AS runs, "+ f"sum({_meta_int('eval.input_tokens')})::bigint, sum({_meta_int('eval.output_tokens')})::bigint, "+ f"sum({_meta_int('eval.total_tokens')})::bigint, "+ "(array_agg(coalesce(metadata->>'eval.model', '') ORDER BY created_at DESC))[1] "+ f"FROM scores WHERE project_id = :p AND {_ONLINE} AND created_at >= {_days_ago()} "+ "GROUP BY name HAVING count(*) FILTER (WHERE metadata ? 'eval.total_tokens') > 0",+ {"p": project_id, "d": days},+ )+ return {+ r[0]: {+ "runs": _int(r[1]),+ "input_tokens": _int(r[2]),+ "output_tokens": _int(r[3]),+ "total_tokens": _int(r[4]),+ "model": r[5] or "",+ }+ for r in rows+ }+++async def traces_in_window(project_id: str, days: int) -> int:+ rows = await aquery_rows(+ f"SELECT count(*) FROM traces WHERE project_id = :p AND ts_max >= {_days_ago()} "+ f"AND env <> 'ci' AND {_REAL}",+ {"p": project_id, "d": days},+ )+ return _int(rows[0][0]) if rows else 0+++# ── monitors ──────────────────────────────────────────────────────────────────+++async def score_samples_in_window(+ project_id: str, score_name: str, window_minutes: int, target_agent: str = ""+) -> list[dict]:+ """See the ClickHouse twin. `target_agent` matches any span of the trace carrying that agent,+ exactly as before (span-level, through the `events_agent` index)."""+ params = {"p": project_id, "n": score_name, "w": window_minutes}+ agent = ""+ if target_agent:+ agent = (+ "AND trace_id IN (SELECT DISTINCT trace_id FROM events WHERE project_id = :p "+ f"AND agent_id = :ag AND env <> 'ci' AND {_REAL} AND start_time >= {_mins_ago()}) "+ )+ params["ag"] = target_agent+ rows = await aquery_rows(+ f"SELECT verdict, value FROM scores WHERE project_id = :p AND {_ONLINE} AND name = :n "+ f"AND created_at >= {_mins_ago()} {agent}",+ params,+ )+ return [{"verdict": v or "", "value": val} for v, val in rows]+++async def trace_failure_samples_in_window(+ project_id: str, window_minutes: int, advisory: Sequence[str], target_agent: str = ""+) -> list[dict]:+ params: dict[str, object] = {"p": project_id, "w": window_minutes, "adv": list(advisory)}+ agent = ""+ if target_agent:+ agent = "AND agent_id = :ag"+ params["ag"] = target_agent+ rows = await aquery_rows(+ "WITH m AS (SELECT trace_id FROM traces WHERE project_id = :p AND env <> 'ci' "+ f" AND {_REAL} AND ts_max >= {_mins_ago()} {agent}) "+ "SELECT CASE WHEN m.trace_id IN (" + _FAILING + ") THEN 'FAIL' ELSE 'PASS' END FROM m",+ params,+ )+ return [{"verdict": r[0]} for r in rows]+++# ── calibration ───────────────────────────────────────────────────────────────++# A score is reviewable only while its trace still exists (and is not one of Tracely's own runs).+_REVIEWABLE = (+ "EXISTS (SELECT 1 FROM traces t WHERE t.project_id = scores.project_id "+ "AND t.trace_id = scores.trace_id AND t.internal_kind = '')"+)+++async def evaluator_catalog(project_id: str) -> list[dict]:+ rows = await aquery_rows(+ "SELECT name, (array_agg(evaluation_level ORDER BY created_at DESC))[1], count(*), "+ "count(*) FILTER (WHERE verdict = 'FAIL') "+ f"FROM scores WHERE project_id = :p AND {_ONLINE} AND verdict <> '' AND {_REVIEWABLE} "+ "GROUP BY name ORDER BY count(*) DESC",+ {"p": project_id},+ )+ return [+ {"name": r[0], "level": r[1] or "", "total": _int(r[2]), "fails": _int(r[3])} for r in rows+ ]+++async def evaluator_score_queue(+ project_id: str, name: str, limit: int = 25, offset: int = 0, verdict: str = ""+) -> list[dict]:+ """A stable random sample (ordered by a hash of the score id), as in the ClickHouse twin."""+ rows = await aquery_rows(+ "SELECT trace_id, observation_id, session_id, evaluation_level, verdict, value, comment, "+ "to_char(created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.US') "+ f"FROM scores WHERE project_id = :p AND {_ONLINE} AND name = :n AND verdict <> '' "+ f"AND {_REVIEWABLE} AND (:v = '' OR verdict = :v) "+ "ORDER BY md5(id) LIMIT :lim OFFSET :off",+ {+ "p": project_id,+ "n": name,+ "lim": max(limit, 0),+ "off": max(offset, 0),+ "v": verdict.upper(),+ },+ )+ return [+ {+ "trace_id": r[0] or "",+ "observation_id": r[1] or "",+ "session_id": r[2] or "",+ "evaluation_level": r[3] or "",+ "verdict": r[4] or "",+ "value": r[5],+ "comment": r[6] or "",+ "created_at": r[7],+ }+ for r in rows+ ]+++# ── sessions / threads ────────────────────────────────────────────────────────++# Sortable list columns -> the aggregate each displays (a whitelist: ORDER BY cannot be bound).+SESSION_SORTS = {+ "recent": "last_ts",+ "started": "first_ts",+ "duration": "(last_ts - first_ts)",+ "tokens": "tokens",+}++_SESSION_HAYSTACK = "concat_ws(' ', model, metadata, agent_id, _root_name, subject_id)"+++def session_filter_clauses(failing: bool | None, multi: bool | None, q: str) -> tuple[str, dict]:+ """Status / multi-turn / text filters over the whole thread set (not the loaded page).+ Returns `(sql_suffix, params)`; `None` = don't filter."""+ parts, params = [], {}+ if failing is True:+ parts.append(" AND failing = 1")+ elif failing is False:+ parts.append(" AND failing = 0")+ if multi is True:+ parts.append(" AND turns > 1")+ elif multi is False:+ parts.append(" AND turns = 1")+ if q and q.strip():+ parts.append(f" AND (text_hit OR {_SESSION_HAYSTACK} ILIKE :q)")+ params["q"] = like(q.strip()[:200])+ return "".join(parts), params+++def session_order_clause(sort: str, order: str) -> str:+ """Ends in the unique `thread` (byte order, like ClickHouse) so LIMIT/OFFSET pages are total."""+ expr = SESSION_SORTS.get(sort, SESSION_SORTS["recent"])+ direction = "ASC" if str(order).lower() == "asc" else "DESC"+ return f'ORDER BY {expr} {direction}, last_ts DESC, thread COLLATE "C" ASC'+++async def sessions_overview(+ project_id: str,+ limit: int,+ offset: int,+ from_ts: str | None = None,+ to_ts: str | None = None,+ advisory: Sequence[str] = (),+ include_internal: bool = False,+ sort: str = "recent",+ order: str = "desc",+ agent_id: str = "",+ failing: bool | None = None,+ multi: bool | None = None,+ q: str = "",+ count_only: bool = False,+) -> list[dict] | int:+ """Traces grouped into threads from the `traces` rollup. See the ClickHouse twin for the+ contract (filters over the whole set, content-less 1-turn threads dropped, text fetched for+ the page only — here straight from the rollup's root text)."""+ params: dict = {"p": project_id, "n": max(limit, 0), "o": max(offset, 0), "adv": list(advisory)}+ where = "" if include_internal else f" AND tr.{_REAL}"+ if from_ts:+ where += " AND tr.ts_max >= CAST(CAST(:from AS text) AS timestamptz)"+ params["from"] = from_ts+ if to_ts:+ where += " AND tr.ts_min < CAST(CAST(:to AS text) AS timestamptz)"+ params["to"] = to_ts+ if agent_id:+ where += " AND tr.agent_id = :ag"+ params["ag"] = agent_id+ filter_clause, fparams = session_filter_clauses(failing, multi, q)+ params.update(fparams)+ hits_cte = hit_col = hit_join = text_hit = ""+ if "q" in fparams:+ # any span's text in the thread (GENERATION inputs excluded: whole history + system prompt)+ hits_cte = (+ ", hits AS (SELECT DISTINCT trace_id FROM events WHERE project_id = :p "+ "AND (output ILIKE :q OR (type <> 'GENERATION' AND input ILIKE :q)))"+ )+ hit_col = ", (h.trace_id IS NOT NULL) AS t_q"+ hit_join = "LEFT JOIN hits h ON h.trace_id = tr.trace_id"+ text_hit = ", bool_or(t_q) AS text_hit"+ body = f"""+ WITH fail_t AS ({_FAILING}), fail_th AS ({_FAILING_THREADS}){hits_cte},+ t AS (+ SELECT tr.*, (f.trace_id IS NOT NULL) AS t_failing{hit_col}+ FROM traces tr LEFT JOIN (SELECT DISTINCT trace_id FROM fail_t) f ON f.trace_id = tr.trace_id+ {hit_join}+ WHERE tr.project_id = :p{where}+ ),+ meta AS (+ SELECT t.thread_id, jsonb_object_agg(kv.key, kv.value ORDER BY t.ts_max) AS md+ FROM t, jsonb_each_text(t.metadata) kv GROUP BY t.thread_id+ ),+ th AS (+ SELECT t.thread_id AS thread,+ count(*) AS turns,+ (array_agg(t.agent_id ORDER BY t.ts_max DESC))[1] AS agent_id,+ (array_agg(t.trace_id ORDER BY t.ts_min))[1] AS _first_trace,+ (array_agg(t.trace_id ORDER BY t.ts_min DESC))[1] AS _last_trace,+ max(t.root_name) AS _root_name,+ CASE WHEN max(t.internal_kind) <> '' THEN (max(t.root_name) <> '' OR max(t.subject_id) <> '')+ ELSE (bool_or(t.has_input) OR bool_or(t.has_output)) END AS _has_content,+ sum(t.tokens)::bigint AS tokens,+ sum(t.input_tokens)::bigint AS input_tokens,+ sum(t.output_tokens)::bigint AS output_tokens,+ (array_agg(t.model_id ORDER BY t.tokens DESC))[1] AS model,+ sum(t.cost)::float8 AS cost,+ min(t.ts_min) AS first_ts,+ max(t.ts_max) AS last_ts,+ (array_agg(t.trace_id ORDER BY t.ts_max DESC))[1] AS last_trace_id,+ CASE WHEN bool_or(t.t_failing) OR t.thread_id IN (SELECT session_id FROM fail_th)+ THEN 1 ELSE 0 END AS failing,+ max(t.internal_kind) AS internal_kind,+ max(t.subject_id) AS subject_id{text_hit}+ FROM t GROUP BY t.thread_id+ ),+ x AS (+ SELECT th.*, coalesce(meta.md, '{{}}'::jsonb)::text AS metadata+ FROM th LEFT JOIN meta ON meta.thread_id = th.thread+ )+ SELECT * FROM x+ WHERE NOT (turns = 1 AND NOT _has_content AND failing = 0){filter_clause}+ """+ if count_only:+ rows = await aquery_rows(f"SELECT count(*) FROM ({body}) c", params)+ return _int(rows[0][0]) if rows else 0+ rows = await aquery(f"{body} {session_order_clause(sort, order)} LIMIT :n OFFSET :o", params)+ ids = sorted(+ {t for r in rows if not r["internal_kind"] for t in (r["_first_trace"], r["_last_trace"])}+ )+ texts: dict[str, tuple] = {}+ if ids:+ texts = {+ r[0]: (r[1], r[2])+ for r in await aquery_rows(+ "SELECT trace_id, root_input, root_output FROM traces "+ "WHERE project_id = :p AND trace_id = ANY(:ids)",+ {"p": project_id, "ids": ids},+ )+ }+ for d in rows:+ first, last = d.pop("_first_trace"), d.pop("_last_trace")+ root_name = d.pop("_root_name")+ d.pop("_has_content")+ d.pop("text_hit", None)+ if d["internal_kind"]:+ d["first_input"], d["last_output"] = root_name, d["subject_id"]+ else:+ d["first_input"] = texts.get(first, ("", ""))[0]+ d["last_output"] = texts.get(last, ("", ""))[1]+ d["metadata"] = parse_thread_meta(d.get("metadata"))+ return rows+++async def thread_agents(+ project_id: str, thread_id: str, spans: list[dict] | None = None+) -> list[dict]:+ """Agents in a thread and the tools each used, derived from its spans (pure Python — identical+ to the ClickHouse twin)."""+ if spans is None:+ spans = await thread_spans_full(project_id, thread_id)+ spans_by_agent: dict[str, int] = defaultdict(int)+ tools_touched: dict[str, set[str]] = defaultdict(set)+ tool_execs: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))+ by_agent: dict[str, list[dict]] = defaultdict(list)+ models: dict[str, set[str]] = defaultdict(set)+ for s in spans:+ aid = s.get("agent_id") or ""+ spans_by_agent[aid] += 1+ by_agent[aid].append(s)+ if s.get("model_id"):+ models[aid].add(str(s["model_id"]))+ name = s.get("name")+ if s.get("type") == "TOOL" and name:+ tool_execs[aid][str(name)] += 1+ tools_touched[aid].add(str(name))+ for t in s.get("tool_call_names") or []:+ if t:+ tools_touched[aid].add(str(t))+ out: list[dict] = []+ for aid, span_count in spans_by_agent.items():+ tools = sorted(+ ({"name": n, "count": tool_execs[aid].get(n, 0)} for n in tools_touched[aid]),+ key=lambda t: (-t["count"], t["name"]),+ )+ out.append(+ {+ "agent_id": aid,+ "tools": tools,+ "span_count": span_count,+ "tool_call_count": sum(t["count"] for t in tools),+ "system_prompt": system_prompt(by_agent[aid]),+ "models": sorted(models[aid]),+ }+ )+ out.sort(key=lambda a: (a["tool_call_count"], a["span_count"]), reverse=True)+ return out+++async def session_turns(+ project_id: str, thread_id: str, advisory: Sequence[str] = ()+) -> list[dict]:+ """A thread's turns oldest-first. An internal run's "message" is its root span's title plus+ input (what it did), not the judge's raw prompt — same rule as the ClickHouse twin."""+ return await aquery(+ "SELECT trace_id, "+ "CASE WHEN internal_kind <> '' THEN root_name || chr(10) || chr(10) || coalesce(root_input, '') "+ " ELSE root_input END AS input, "+ "CASE WHEN internal_kind <> '' THEN coalesce(root_output, '') ELSE root_output END AS output, "+ "tokens, input_tokens, output_tokens, model_id AS model, cost, latency_ms, ts_min AS ts, "+ f"CASE WHEN trace_id IN ({_FAILING}) THEN 1 ELSE 0 END AS failing "+ "FROM traces WHERE project_id = :p AND thread_id = :th ORDER BY ts_min ASC",+ {"p": project_id, "th": thread_id, "adv": list(advisory)},+ )+++# ── scores ────────────────────────────────────────────────────────────────────+++async def scores_by_trace(project_id: str, trace_ids: list[str]) -> dict[str, list[dict]]:+ if not trace_ids:+ return {}+ rows = await aquery(+ f"SELECT trace_id, {_SCORE_COLS} FROM scores WHERE project_id = :p "+ f"AND trace_id = ANY(:t) AND {_ONLINE} ORDER BY evaluation_level, name",+ {"p": project_id, "t": list(trace_ids)},+ )+ by_trace: dict[str, list[dict]] = defaultdict(list)+ for d in rows:+ by_trace[d.pop("trace_id")].append(d)+ return by_trace+++async def conversation_scores_by_thread(+ project_id: str, thread_ids: list[str]+) -> dict[str, list[dict]]:+ if not thread_ids:+ return {}+ rows = await aquery(+ f"SELECT session_id, {_SCORE_COLS} FROM scores WHERE project_id = :p AND {_ONLINE} "+ "AND evaluation_level = 'CONVERSATION' AND session_id = ANY(:t) ORDER BY name",+ {"p": project_id, "t": list(thread_ids)},+ )+ by_thread: dict[str, list[dict]] = defaultdict(list)+ for d in rows:+ by_thread[d.pop("session_id")].append(d)+ return by_thread+++async def conversation_scores(project_id: str, thread_id: str) -> list[dict]:+ return (await conversation_scores_by_thread(project_id, [thread_id])).get(thread_id, [])+++async def agent_trace_ids(project_id: str, agent_id: str, limit: int = 2000) -> list[dict]:+ params: dict = {"p": project_id, "n": max(1, limit)}+ agent = ""+ if agent_id:+ agent = "AND agent_id = :a"+ params["a"] = agent_id+ rows = await aquery_rows(+ f"SELECT trace_id, thread_id FROM traces WHERE project_id = :p AND {_REAL} {agent} "+ "ORDER BY ts_min DESC LIMIT :n",+ params,+ )+ return [{"trace_id": r[0], "thread": r[1]} for r in rows]+++async def trace_agent_ids(project_id: str) -> set[str]:+ """Agents DECLARED as a turn owner (the app-root span's agent) — see the ClickHouse twin."""+ rows = await aquery_rows(+ f"SELECT DISTINCT app_root_agent_id FROM traces WHERE project_id = :p AND {_REAL} "+ "AND app_root_agent_id <> ''",+ {"p": project_id},+ )+ return {r[0] for r in rows}+++async def agent_ids_with_spans(project_id: str) -> set[str]:+ rows = await aquery_rows(+ "SELECT DISTINCT agent_id FROM events WHERE project_id = :p AND agent_id <> ''",+ {"p": project_id},+ )+ return {r[0] for r in rows}+++async def _trace_ops_rows(project_id: str, trace_ids: list[str]) -> list[dict]:+ rows = await aquery_rows(+ f"SELECT trace_id, latency_ms, tokens, tool_errors FROM traces WHERE project_id = :p "+ f"AND {_REAL} AND trace_id = ANY(:ids)",+ {"p": project_id, "ids": list(trace_ids)},+ )+ return [+ {+ "trace_id": r[0],+ "ops.latency_ms": float(r[1]),+ "ops.tokens": float(r[2]),+ "ops.tool_errors": float(r[3]),+ }+ for r in rows+ ]+++async def agent_score_rows(project_id: str, agent_id: str, max_traces: int = 2000) -> list[dict]:+ """Flat online-eval + operational rows for meta-analysis (composition only — see the+ ClickHouse twin)."""+ traces = await agent_trace_ids(project_id, agent_id, max_traces)+ if not traces:+ return []+ thread_of = {t["trace_id"]: t["thread"] for t in traces}+ trace_ids = list(thread_of)+ threads = list(dict.fromkeys(thread_of.values()))+ by_trace = await scores_by_trace(project_id, trace_ids)+ conv = await conversation_scores_by_thread(project_id, threads)++ def row(thread: str, tid: str | None, sc: dict) -> dict:+ return {+ "conversation_id": thread,+ "trace_id": tid,+ "metric_name": sc["name"],+ "evaluation_level": sc["evaluation_level"],+ "value": sc["value"],+ "string_value": sc.get("string_value", ""),+ "verdict": sc.get("verdict", ""),+ }++ rows = [row(thread_of.get(tid, tid), tid, sc) for tid, scs in by_trace.items() for sc in scs]+ rows += [row(thread, None, sc) for thread, scs in conv.items() for sc in scs]++ def ops_row(thread: str, tid: str | None, metric: str, value: float) -> dict:+ return {+ "conversation_id": thread,+ "trace_id": tid,+ "metric_name": metric,+ "evaluation_level": "OPS",+ "value": value,+ "string_value": "",+ "verdict": "",+ }++ for o in await _trace_ops_rows(project_id, trace_ids):+ thread = thread_of.get(o["trace_id"], o["trace_id"])+ for metric in ("ops.latency_ms", "ops.tokens", "ops.tool_errors"):+ rows.append(ops_row(thread, o["trace_id"], metric, o[metric]))+ turns: dict[str, int] = {}+ for thread in thread_of.values():+ turns[thread] = turns.get(thread, 0) + 1+ for thread, n in turns.items():+ rows.append(ops_row(thread, None, "ops.turns", float(n)))+ return rows+++# ── search / stats / trends ───────────────────────────────────────────────────+++async def search_threads(project_id: str, q: str, limit: int = 8) -> list[dict]:+ """Threads with a turn whose root (user) message contains `q`, newest first."""+ rows = await aquery_rows(+ "SELECT thread_id, (array_agg(root_input ORDER BY ts_min))[1], "+ "(array_agg(trace_id ORDER BY ts_max DESC))[1], count(*), max(ts_max) AS last_ts "+ f"FROM traces WHERE project_id = :p AND {_REAL} AND thread_id IN ("+ f" SELECT thread_id FROM traces WHERE project_id = :p AND {_REAL} AND root_input ILIKE :q) "+ "GROUP BY thread_id ORDER BY last_ts DESC LIMIT :n",+ {"p": project_id, "q": like(q), "n": limit},+ )+ return [+ {"thread": th, "first_input": fi, "last_trace": lt, "turns": _int(n)}+ for th, fi, lt, n, _ in rows+ ]+++async def stats_counts(project_id: str, advisory: Sequence[str] = ()) -> dict:+ r = await aquery_rows(+ "SELECT count(*), coalesce(sum(spans), 0)::bigint, count(*) FILTER (WHERE has_error) "+ f"FROM traces WHERE project_id = :p AND {_REAL}",+ {"p": project_id},+ )+ af = await aquery_rows(+ f"SELECT count(DISTINCT trace_id) FROM ({_FAILING}) f",+ {"p": project_id, "adv": list(advisory)},+ )+ traces, spans, failing = (_int(r[0][0]), _int(r[0][1]), _int(r[0][2])) if r else (0, 0, 0)+ return {+ "traces": traces,+ "spans": spans,+ "failing_traces": failing,+ "auto_failures": _int(af[0][0]) if af else 0,+ }+++def _pct(q: float, col: str, cond: str = "") -> str:+ f = f" FILTER (WHERE {cond})" if cond else ""+ return f"floor(percentile_cont({q}) WITHIN GROUP (ORDER BY {col}){f})::bigint"+++async def ops_metrics(project_id: str, days: int) -> dict:+ """Latency / throughput / cost over the last `days`: per day (from the rollup), per model and+ by slowest span name (span-level). `GROUP BY ROLLUP` appends the grand total in the same scan,+ keyed like ClickHouse's WITH ROLLUP (`1970-01-01` / `''`) so the shaping below is unchanged."""+ params = {"p": project_id, "d": days}+ daily_rows = await aquery_rows(+ "SELECT coalesce(d, DATE '1970-01-01') AS d, traces, p50, p95, p99, errors, tokens, cost FROM ("+ f" SELECT {_UTC_DAY} AS d, count(*) AS traces, {_pct(0.5, 'latency_ms')} AS p50, "+ f" {_pct(0.95, 'latency_ms')} AS p95, {_pct(0.99, 'latency_ms')} AS p99, "+ " count(*) FILTER (WHERE has_error) AS errors, sum(tokens)::bigint AS tokens, "+ " sum(cost)::float8 AS cost "+ f" FROM traces WHERE project_id = :p AND ts_min >= {_days_ago()} AND {_REAL} "+ f" GROUP BY ROLLUP ({_UTC_DAY})) x ORDER BY d",+ params,+ )+ model_rows = await aquery_rows(+ "SELECT coalesce(model_id, ''), calls, p50, p95, ttft_p50, errors, tokens, in_tokens, out_tokens, cost FROM ("+ f" SELECT model_id, count(*) AS calls, {_pct(0.5, 'ms')} AS p50, {_pct(0.95, 'ms')} AS p95, "+ f" coalesce({_pct(0.5, 'ttft', 'ttft > 0')}, 0) AS ttft_p50, "+ " count(*) FILTER (WHERE level = 'ERROR') AS errors, sum(tokens)::bigint AS tokens, "+ " sum(input_tokens)::bigint AS in_tokens, sum(output_tokens)::bigint AS out_tokens, "+ " sum(cost)::float8 AS cost "+ f" FROM (SELECT model_id, level, {_SPAN_MS} AS ms, "+ f" {_ms('start_time', 'completion_start_time')} AS ttft, tokens, input_tokens, "+ " output_tokens, cost FROM events WHERE project_id = :p AND model_id <> '' "+ f" AND {_REAL} AND start_time >= {_days_ago()}) s "+ " GROUP BY ROLLUP (model_id)) x ORDER BY calls DESC",+ params,+ )+ slow_rows = await aquery_rows(+ f"SELECT name, type, count(*) AS calls, {_pct(0.5, 'ms')} AS p50, {_pct(0.95, 'ms')} AS p95, "+ "max(ms) AS p_max, count(*) FILTER (WHERE level = 'ERROR') AS errors "+ f"FROM (SELECT name, type, level, {_SPAN_MS} AS ms FROM events WHERE project_id = :p "+ f" AND {_REAL} AND start_time >= {_days_ago()}) s "+ "GROUP BY name, type ORDER BY p95 DESC LIMIT 8",+ params,+ )++ def _lat(r: Sequence) -> dict:+ return {+ "traces": _int(r[1]),+ "p50": _int(r[2]),+ "p95": _int(r[3]),+ "p99": _int(r[4]),+ "errors": _int(r[5]),+ "tokens": _int(r[6]),+ "cost": float(r[7] or 0),+ }++ total = next((_lat(r) for r in daily_rows if str(r[0]) == "1970-01-01"), _lat([0] * 8))+ daily = [{"date": str(r[0]), **_lat(r)} for r in daily_rows if str(r[0]) != "1970-01-01"]++ def _model(r: Sequence) -> dict:+ return {+ "model": r[0],+ "calls": _int(r[1]),+ "p50": _int(r[2]),+ "p95": _int(r[3]),+ "ttft_p50": _int(r[4]),+ "errors": _int(r[5]),+ "tokens": _int(r[6]),+ "input_tokens": _int(r[7]),+ "output_tokens": _int(r[8]),+ "cost": float(r[9] or 0),+ }++ models = [_model(r) for r in model_rows if r[0]]+ gen_total = next((_model(r) for r in model_rows if not r[0]), _model([""] + [0] * 9))+ return {+ "days": days,+ "summary": {+ **total,+ "error_rate": round(total["errors"] / total["traces"], 4) if total["traces"] else 0.0,+ "traces_per_day": round(total["traces"] / days, 1),+ "ttft_p50": gen_total["ttft_p50"],+ "llm_calls": gen_total["calls"],+ "cost_per_1k_traces": round(total["cost"] / total["traces"] * 1000, 2)+ if total["traces"]+ else 0.0,+ },+ "daily": daily,+ "models": models[:8],+ "slowest": [+ {+ "name": r[0],+ "type": r[1],+ "calls": _int(r[2]),+ "p50": _int(r[3]),+ "p95": _int(r[4]),+ "max": _int(r[5]),+ "errors": _int(r[6]),+ }+ for r in slow_rows+ ],+ }+++async def daily_trace_failures(+ project_id: str, days: int, advisory: Sequence[str] = ()+) -> list[dict]:+ rows = await aquery_rows(+ f"SELECT {_UTC_DAY} AS d, count(*), count(*) FILTER (WHERE trace_id IN ({_FAILING})) "+ f"FROM traces WHERE project_id = :p AND ts_min >= {_days_ago()} AND {_REAL} "+ "GROUP BY d ORDER BY d",+ {"p": project_id, "d": days, "adv": list(advisory)},+ )+ return [{"date": str(d), "traces": _int(t), "failures": _int(f)} for d, t, f in rows]+++async def trace_failure_totals(project_id: str, advisory: Sequence[str] = ()) -> tuple[int, int]:+ total = await aquery_rows(+ f"SELECT count(*) FROM traces WHERE project_id = :p AND {_REAL}", {"p": project_id}+ )+ fails = await aquery_rows(+ f"SELECT count(DISTINCT trace_id) FROM ({_FAILING}) f",+ {"p": project_id, "adv": list(advisory)},+ )+ return (_int(total[0][0]) if total else 0), (_int(fails[0][0]) if fails else 0)+++# ── ops ───────────────────────────────────────────────────────────────────────+++async def store_health() -> tuple[object, float | None]:+ """`(newest span time, disk free %)` for the self-check. Postgres cannot see its filesystem+ from SQL, so the disk half is None here (the verdict is skipped, as when the store is down)."""+ rows = await aquery_rows("SELECT max(ts_max) FROM traces")+ return (rows[0][0] if rows else None), Nonediff --git a/backend/tracely/infrastructure/spans/rollup.py b/backend/tracely/infrastructure/spans/rollup.pynew file mode 100644index 0000000..83e2706--- /dev/null+++ b/backend/tracely/infrastructure/spans/rollup.py@@ -0,0 +1,123 @@+"""The per-trace rollup (`traces`): one row per trace, recomputed from its spans.++`refresh` runs in the SAME transaction as every span write or delete, and recomputes from scratch+(never increments), so late spans, re-deliveries and partial deletes all converge — the property+ReplacingMergeTree used to give. Each column is the SQL twin of a ClickHouse read-time expression:++- `root_*` / `has_*` — `async_reader._root` / `_root_has`: the parentless span, else the+ `is_app_root` one (most of prod has no parentless span);+- `agent_id` — `_TRACE_AGENT` (root's, else app-root's, else any span's);+- `app_root_agent_id` — `trace_agent_ids`' stricter rule (the app-root span only);+- `metadata` — the `tracely.metadata.*` keys the threads list surfaces.++Verdicts are deliberately absent: scores change on their own schedule and the advisory set can+change at any time, so "failing" stays a read-time join (the one verdict policy, one place).+"""++from __future__ import annotations++from collections.abc import Iterable++from sqlalchemy import Connection, text++_ROOT = "parent_span_id = ''"+++def _root(expr_agg: str, col: str) -> str:+ """`_root(col)`: from the parentless span when there is one, else from the app-root span."""+ return (+ f"CASE WHEN bool_or({_ROOT}) THEN {expr_agg.format(col=col, cond=_ROOT)} "+ f"ELSE {expr_agg.format(col=col, cond='is_app_root')} END"+ )+++_FIRST = "(array_agg({col} ORDER BY start_time) FILTER (WHERE {cond} AND {col} IS NOT NULL))[1]"+_HAS = "coalesce(bool_or({col} IS NOT NULL) FILTER (WHERE {cond}), false)"++REFRESH = f"""+INSERT INTO traces (+ project_id, trace_id, thread_id, conversation_id, env, internal_kind, subject_id,+ agent_id, app_root_agent_id, root_name, first_name, root_input, root_output, has_input,+ has_output, spans, ts_min, ts_max, latency_ms, tokens, input_tokens, output_tokens, cost,+ model_id, has_error, tool_errors, first_error, has_emulated_turn, metadata, updated_at)+SELECT+ g.project_id, g.trace_id,+ coalesce(nullif(max(g.conversation_id), ''), g.trace_id),+ max(g.conversation_id),+ max(g.env),+ max(g.internal_kind),+ max(g.subject_id),+ coalesce(nullif(max(g.agent_id) FILTER (WHERE g.{_ROOT}), ''),+ nullif(max(g.agent_id) FILTER (WHERE g.is_app_root), ''),+ max(g.agent_id) FILTER (WHERE g.agent_id <> ''), ''),+ coalesce(max(g.agent_id) FILTER (WHERE g.is_app_root), ''),+ coalesce({_root(_FIRST, "name")}, ''),+ (array_agg(g.name ORDER BY g.start_time))[1],+ {_root(_FIRST, "input")},+ {_root(_FIRST, "output")},+ {_root(_HAS, "input")},+ {_root(_HAS, "output")},+ count(*),+ min(g.start_time),+ max(coalesce(g.end_time, g.start_time)),+ (floor(extract(epoch FROM max(coalesce(g.end_time, g.start_time))) * 1000)+ - floor(extract(epoch FROM min(g.start_time)) * 1000))::bigint,+ sum(g.tokens)::bigint,+ sum(g.input_tokens)::bigint,+ sum(g.output_tokens)::bigint,+ sum(g.cost)::float8,+ coalesce((array_agg(g.model_id ORDER BY g.tokens DESC)+ FILTER (WHERE g.type = 'GENERATION' AND g.model_id <> ''))[1], ''),+ bool_or(g.level = 'ERROR'),+ count(*) FILTER (WHERE g.type = 'TOOL' AND g.level = 'ERROR'),+ coalesce((array_agg(g.status_message ORDER BY g.start_time) FILTER (WHERE g.status_message <> ''))[1], ''),+ bool_or(g.name = 'emulated.turn'),+ coalesce((SELECT jsonb_object_agg(kv.key, kv.value ORDER BY m.start_time)+ FROM events m, jsonb_each_text(m.metadata) kv+ WHERE m.project_id = g.project_id AND m.trace_id = g.trace_id+ AND kv.key LIKE 'tracely.metadata.%'), '{{}}'::jsonb),+ now()+FROM events g+WHERE g.project_id = :p AND g.trace_id = ANY(:ids)+GROUP BY g.project_id, g.trace_id+ON CONFLICT (project_id, trace_id) DO UPDATE SET+ thread_id = EXCLUDED.thread_id, conversation_id = EXCLUDED.conversation_id, env = EXCLUDED.env,+ internal_kind = EXCLUDED.internal_kind, subject_id = EXCLUDED.subject_id,+ agent_id = EXCLUDED.agent_id, app_root_agent_id = EXCLUDED.app_root_agent_id,+ root_name = EXCLUDED.root_name, first_name = EXCLUDED.first_name,+ root_input = EXCLUDED.root_input, root_output = EXCLUDED.root_output,+ has_input = EXCLUDED.has_input, has_output = EXCLUDED.has_output, spans = EXCLUDED.spans,+ ts_min = EXCLUDED.ts_min, ts_max = EXCLUDED.ts_max, latency_ms = EXCLUDED.latency_ms,+ tokens = EXCLUDED.tokens, input_tokens = EXCLUDED.input_tokens,+ output_tokens = EXCLUDED.output_tokens, cost = EXCLUDED.cost, model_id = EXCLUDED.model_id,+ has_error = EXCLUDED.has_error, tool_errors = EXCLUDED.tool_errors,+ first_error = EXCLUDED.first_error, has_emulated_turn = EXCLUDED.has_emulated_turn,+ metadata = EXCLUDED.metadata, updated_at = EXCLUDED.updated_at+"""++# The rows of traces whose last span just went (a delete), so the rollup never outlives its spans.+PRUNE = """+DELETE FROM traces t+WHERE t.project_id = :p AND t.trace_id = ANY(:ids)+ AND NOT EXISTS (SELECT 1 FROM events e WHERE e.project_id = t.project_id AND e.trace_id = t.trace_id)+"""+++def lock(conn: Connection, project_id: str, trace_ids: Iterable[str]) -> None:+ """Serialize writers per trace for the rest of this transaction. Without it two workers+ ingesting spans of one trace each recompute without the other's uncommitted spans, and the+ later commit's rollup silently misses some. Sorted, so two writers never deadlock.+ Free today (`--pool=solo --concurrency=1`); load-bearing the day concurrency goes above 1."""+ for tid in sorted(set(trace_ids)):+ conn.execute(+ text("SELECT pg_advisory_xact_lock(hashtextextended(:k, 0))"),+ {"k": f"{project_id}:{tid}"},+ )+++def refresh(conn: Connection, project_id: str, trace_ids: Iterable[str]) -> None:+ ids = sorted({t for t in trace_ids if t})+ if not ids:+ return+ conn.execute(text(REFRESH), {"p": project_id, "ids": ids})+ conn.execute(text(PRUNE), {"p": project_id, "ids": ids})diff --git a/backend/tracely/infrastructure/spans/schema.py b/backend/tracely/infrastructure/spans/schema.pynew file mode 100644index 0000000..00ffbed--- /dev/null+++ b/backend/tracely/infrastructure/spans/schema.py@@ -0,0 +1,74 @@+"""The Postgres `events` row: the ClickHouse column list (`events_schema.EVENT_COLUMNS`, still the+one source of truth for what a span carries) minus ReplacingMergeTree bookkeeping, plus the four+spend columns summed once here instead of `arraySum(mapValues(...))` on every read."""++from __future__ import annotations++import json+from datetime import datetime, timezone+from typing import Any++from tracely.infrastructure.clickhouse.events_schema import (+ _ARRAYS,+ _BOOLS,+ _INTS,+ _MAPS,+ _NULLABLE,+ EVENT_COLUMNS,+)+from tracely.infrastructure.spans._pg import utc++_DROPPED = {"event_ts", "is_deleted"}+SPEND = ["tokens", "input_tokens", "output_tokens", "cost"]+COLUMNS: list[str] = [c for c in EVENT_COLUMNS if c not in _DROPPED] + SPEND+_TIMES = {"start_time", "end_time", "completion_start_time", "created_at"}+++def _default(col: str) -> Any:+ if col in _NULLABLE:+ return None+ if col in _MAPS:+ return {}+ if col in _ARRAYS:+ return []+ if col in _INTS:+ return 0+ if col in _BOOLS:+ return False+ return ""+++def _num(v: Any) -> float:+ try:+ return float(v or 0)+ except (TypeError, ValueError):+ return 0.0+++def to_row(ev: dict[str, Any], now: datetime | None = None) -> dict[str, Any]:+ """One event dict (the OTel mapper's shape) -> bind params for `writer._UPSERT`.++ '' is stored as NULL for `input`/`output`: "no text" has ONE representation, so the rollup's+ `has_input` is a NULL test that never reads the text."""+ row: dict[str, Any] = {}+ for col in COLUMNS[: -len(SPEND)]:+ v = ev.get(col)+ if v is None or (v == "" and col in _NULLABLE):+ v = _default(col)+ if col in _MAPS:+ v = json.dumps(+ {str(k): (_num(x) if col == "cost_details" else x) for k, x in dict(v).items()},+ default=str,+ )+ elif col in _ARRAYS:+ v = [str(x) for x in v]+ elif col in _TIMES:+ v = utc(v)+ row[col] = v+ row["created_at"] = row["created_at"] or (now or datetime.now(timezone.utc))+ usage = ev.get("usage_details") or {}+ row["tokens"] = int(sum(_num(x) for x in usage.values()))+ row["input_tokens"] = int(_num(usage.get("input")))+ row["output_tokens"] = int(_num(usage.get("output")))+ row["cost"] = sum(_num(x) for x in (ev.get("cost_details") or {}).values())+ return rowdiff --git a/backend/tracely/infrastructure/spans/score_writer.py b/backend/tracely/infrastructure/spans/score_writer.pynew file mode 100644index 0000000..4a67760--- /dev/null+++ b/backend/tracely/infrastructure/spans/score_writer.py@@ -0,0 +1,186 @@+"""Postgres twin of `clickhouse.score_writer.ScoreWriter` — same methods, same deterministic ids.++ReplacingMergeTree + FINAL becomes `ON CONFLICT (project_id, id) DO UPDATE`: re-grading a target+overwrites its score (and `created_at`, exactly as FINAL surfaced the newest version), and a+retraction is a real DELETE instead of a tombstone."""++from __future__ import annotations++import json+import uuid+from datetime import datetime, timezone++from sqlalchemy import text++from tracely.infrastructure.clickhouse.score_writer import (+ _CONVERSATION,+ ScoreWriter as _ClickHouseScoreWriter,+ _EvalResultLike,+ _usage_metadata,+)+from tracely.infrastructure.spans import _pg++_COLS = [+ "project_id",+ "id",+ "trace_id",+ "observation_id",+ "session_id",+ "agent_run_id",+ "name",+ "source",+ "data_type",+ "value",+ "string_value",+ "verdict",+ "evaluation_case_id",+ "evaluation_level",+ "comment",+ "metadata",+ "created_at",+ "turn_id",+ "gate_run_id",+ "execution_trace_id",+]+_UPSERT = (+ f"INSERT INTO scores ({', '.join(_COLS)}) VALUES ("+ + ", ".join("CAST(:metadata AS jsonb)" if c == "metadata" else f":{c}" for c in _COLS)+ + ") ON CONFLICT (project_id, id) DO UPDATE SET "+ + ", ".join(f"{c} = EXCLUDED.{c}" for c in _COLS if c not in ("project_id", "id"))+)+++def _row(**kw) -> dict:+ row = {c: kw.get(c) for c in _COLS}+ for c in (+ "agent_run_id",+ "string_value",+ "verdict",+ "evaluation_case_id",+ "evaluation_level",+ "comment",+ "data_type",+ "turn_id",+ "gate_run_id",+ "execution_trace_id",+ ):+ row[c] = row[c] or ""+ row["metadata"] = json.dumps(dict(kw.get("metadata") or {}))+ row["created_at"] = _pg.utc(row["created_at"]) or datetime.now(timezone.utc)+ return row+++class ScoreWriter:+ def __init__(self, client=None) -> None: # `client` kept for call-site compatibility+ self._client = client++ eval_score_id = staticmethod(_ClickHouseScoreWriter.eval_score_id)++ def _write(self, rows: list[dict]) -> None:+ if rows:+ with _pg.SYNC.begin() as conn:+ conn.execute(text(_UPSERT), rows)++ def write_eval_scores(+ self,+ project_id: str,+ trace_id: str,+ agent_run_id: str,+ results: list[_EvalResultLike],+ thread_id: str = "",+ ) -> None:+ now = datetime.now(timezone.utc)+ rows = []+ for r in results:+ sid = self.eval_score_id(trace_id, thread_id, r.name, r.level, r.target_span_id)+ if r.level == _CONVERSATION:+ row_trace, row_session = None, thread_id+ else:+ row_trace, row_session = trace_id, thread_id or None+ rows.append(+ _row(+ project_id=project_id,+ id=sid,+ trace_id=row_trace,+ observation_id=r.target_span_id or None,+ session_id=row_session,+ agent_run_id=agent_run_id,+ name=r.name,+ source="EVAL",+ data_type=r.data_type,+ value=r.value,+ string_value=r.string_value,+ verdict=r.verdict,+ evaluation_level=r.level,+ comment=r.comment,+ metadata=_usage_metadata(getattr(r, "usage", None)),+ created_at=now,+ )+ )+ self._write(rows)++ def retract_eval_scores(+ self,+ project_id: str,+ names: list[str],+ *,+ trace_id: str = "",+ thread_id: str = "",+ keep_ids: set[str] | None = None,+ ) -> int:+ """Same contract as the ClickHouse twin: delete these evaluators' online scores for one+ item except `keep_ids`. Returns rows retracted."""+ if not names or not (trace_id or thread_id):+ return 0+ if trace_id:+ scope, params = "trace_id = :t", {"t": trace_id}+ else:+ scope, params = (+ "session_id = :s AND evaluation_level = 'CONVERSATION'",+ {"s": thread_id},+ )+ with _pg.SYNC.begin() as conn:+ res = conn.execute(+ text(+ "DELETE FROM scores WHERE project_id = :p AND source = 'EVAL' "+ f"AND evaluation_case_id = '' AND name = ANY(:n) AND {scope} "+ "AND NOT (id = ANY(:keep))"+ ),+ {+ "p": project_id,+ "n": sorted(set(names)),+ "keep": sorted(keep_ids or ()),+ **params,+ },+ )+ return res.rowcount or 0++ def retract_evaluator(self, project_id: str, name: str) -> int:+ with _pg.SYNC.begin() as conn:+ res = conn.execute(+ text(+ "DELETE FROM scores WHERE project_id = :p AND source = 'EVAL' "+ "AND evaluation_case_id = '' AND name = :n"+ ),+ {"p": project_id, "n": name},+ )+ return res.rowcount or 0++ def write_regression_verdict(self, case, trace_id: str, verdict: str) -> None:+ self._write(+ [+ _row(+ project_id=case.project_id,+ id=str(uuid.uuid4()),+ trace_id=trace_id,+ name="tracely.regression.verdict",+ source="EVAL",+ data_type="BOOLEAN",+ value=1.0 if verdict == "PASS" else 0.0,+ verdict=verdict,+ evaluation_case_id=case.id,+ evaluation_level=case.level,+ created_at=datetime.now(timezone.utc),+ )+ ]+ )diff --git a/backend/tracely/infrastructure/spans/trace_reader.py b/backend/tracely/infrastructure/spans/trace_reader.pynew file mode 100644index 0000000..131d65b--- /dev/null+++ b/backend/tracely/infrastructure/spans/trace_reader.py@@ -0,0 +1,212 @@+"""Sync Postgres reads for workers and services — the twin of `clickhouse.trace_reader.TraceReader`,+method for method (same names, signatures, return shapes). Span-level reads hit `events` by+index; per-trace facts come from the `traces` rollup."""++from __future__ import annotations++from collections import defaultdict+from typing import Any, Iterable++from tracely.infrastructure.spans import _pg+from tracely.infrastructure.spans.reads import SPAN_COLS+++def _uniq(ids: Iterable[str]) -> list[str]:+ return sorted({t for t in ids if t})+++class TraceReader:+ def __init__(self, client: Any = None) -> None: # `client` kept for call-site compatibility+ self._client = client++ @property+ def client(self) -> Any:+ """Services hand this to `ScoreWriter(...)`; on Postgres both share the engine."""+ return self._client or _pg.SYNC++ # ── span reads ────────────────────────────────────────────────────────────++ def read_spans(self, project_id: str, trace_id: str) -> list[dict]:+ return _pg.query(+ f"SELECT {', '.join(SPAN_COLS)} FROM events WHERE project_id = :p AND trace_id = :t "+ "ORDER BY start_time",+ {"p": project_id, "t": trace_id},+ )++ def read_thread_spans(self, project_id: str, thread_id: str) -> list[dict]:+ return _pg.query(+ f"SELECT {', '.join(SPAN_COLS)} FROM events WHERE project_id = :p "+ "AND (conversation_id = :th OR trace_id = :th) ORDER BY start_time",+ {"p": project_id, "th": thread_id},+ )++ def thread_trace_ids(self, project_id: str, thread_id: str) -> list[str]:+ rows = _pg.query_rows(+ "SELECT trace_id FROM events WHERE project_id = :p "+ "AND (conversation_id = :th OR trace_id = :th) GROUP BY trace_id ORDER BY min(start_time)",+ {"p": project_id, "th": thread_id},+ )+ return [tid for (tid,) in rows]++ def trace_generations(self, project_id: str, trace_id: str) -> list[tuple]:+ """`(input, output, start_time)` of one trace's GENERATION spans — the ingest-time+ "Agent workflow" root fill (was raw SQL inside `IngestionService`)."""+ return _pg.query_rows(+ "SELECT input, output, start_time FROM events WHERE project_id = :p AND trace_id = :t "+ "AND type = 'GENERATION'",+ {"p": project_id, "t": trace_id},+ )++ def candidate_metrics(+ self, project_id: str, trace_ids: Iterable[str]+ ) -> tuple[float, int, dict[str, tuple[float, int]]]:+ uniq = _uniq(trace_ids)+ if not uniq:+ return 0.0, 0, {}+ rows = _pg.query_rows(+ "SELECT trace_id, latency_ms, tokens FROM traces WHERE project_id = :p AND trace_id = ANY(:t)",+ {"p": project_id, "t": uniq},+ )+ per = {tid: (float(lat), int(toks)) for tid, lat, toks in rows}+ return sum(v[0] for v in per.values()), sum(v[1] for v in per.values()), per++ def latest_traces_for_env(+ self, project_id: str, agent_id: str, env: str, limit: int = 300+ ) -> list[str]:+ """Span-level, exactly as before: among this agent's spans in `env`, no `emulated.turn`."""+ rows = _pg.query_rows(+ "SELECT trace_id FROM events WHERE project_id = :p AND agent_id = :a AND env = :e "+ "AND internal_kind = '' GROUP BY trace_id "+ "HAVING count(*) FILTER (WHERE name = 'emulated.turn') = 0 "+ "ORDER BY max(start_time) DESC LIMIT :n",+ {"p": project_id, "a": agent_id, "e": env, "n": limit},+ )+ return [tid for (tid,) in rows]++ def traces_with_input(+ self, project_id: str, agent_id: str, input_text: str, limit: int = 20+ ) -> list[dict]:+ rows = _pg.query_rows(+ "SELECT trace_id, max(env), max(start_time), max(metadata->>'tracely.replay.run_id'), "+ "max(level) FROM events WHERE project_id = :p AND agent_id = :a AND internal_kind = '' "+ "AND is_app_root AND md5(input) = md5(:i) AND input = :i "+ "GROUP BY trace_id ORDER BY max(start_time) DESC LIMIT :n",+ {"p": project_id, "a": agent_id, "i": input_text, "n": limit},+ )+ return [+ {+ "trace_id": tid,+ "env": env,+ "ts": ts.isoformat() if hasattr(ts, "isoformat") else str(ts),+ "run_id": run_id or "",+ "level": level or "",+ }+ for tid, env, ts, run_id, level in rows+ ]++ def traces_for_run(+ self, project_id: str, agent_id: str, run_id: str, limit: int = 500+ ) -> list[str]:+ rows = _pg.query_rows(+ "SELECT trace_id FROM events WHERE project_id = :p AND agent_id = :a AND internal_kind = '' "+ "AND metadata ? 'tracely.replay.run_id' AND metadata->>'tracely.replay.run_id' = :r "+ "GROUP BY trace_id ORDER BY max(start_time) DESC LIMIT :n",+ {"p": project_id, "a": agent_id, "r": run_id, "n": limit},+ )+ return [tid for (tid,) in rows]++ # ── score reads ───────────────────────────────────────────────────────────++ def failing_trace_reasons(+ self, project_id: str, limit: int = 5000+ ) -> dict[str, list[tuple[str, str]]]:+ rows = _pg.query_rows(+ "SELECT trace_id, name, comment FROM scores WHERE project_id = :p AND source = 'EVAL' "+ "AND verdict = 'FAIL' AND evaluation_case_id = '' LIMIT :n",+ {"p": project_id, "n": limit},+ )+ by_tid: dict[str, list[tuple[str, str]]] = defaultdict(list)+ for tid, name, comment in rows:+ by_tid[tid].append((name, comment))+ return by_tid++ def recent_failing_traces(self, project_id: str, limit: int = 20) -> list[dict]:+ rows = _pg.query_rows(+ "SELECT t.trace_id, t.ts_max, t.agent_id, t.root_input FROM traces t "+ "WHERE t.project_id = :p AND t.internal_kind = '' AND t.trace_id IN ("+ " SELECT trace_id FROM scores WHERE project_id = :p AND verdict = 'FAIL') "+ "ORDER BY t.ts_max DESC LIMIT :n",+ {"p": project_id, "n": limit},+ )+ return [+ {"trace_id": tid, "ts": str(ts), "agent_id": aid, "input": inp}+ for tid, ts, aid, inp in rows+ ]++ def scores_by_trace(self, project_id: str, trace_ids: Iterable[str]) -> dict[str, list[dict]]:+ uniq = _uniq(trace_ids)+ if not uniq:+ return {}+ rows = _pg.query_rows(+ "SELECT trace_id, name, verdict, value, comment FROM scores "+ "WHERE project_id = :p AND trace_id = ANY(:t)",+ {"p": project_id, "t": uniq},+ )+ by_tid: dict[str, list[dict]] = defaultdict(list)+ for tid, name, verdict, value, comment in rows:+ by_tid[tid].append(+ {"name": name, "verdict": verdict, "value": value, "comment": comment}+ )+ return dict(by_tid)++ def span_count(self, project_id: str, trace_ids: Iterable[str]) -> int:+ """A stability signal (spans still arriving?), so it counts spans, not the rollup."""+ uniq = _uniq(trace_ids)+ if not uniq:+ return 0+ rows = _pg.query_rows(+ "SELECT count(*) FROM events WHERE project_id = :p AND trace_id = ANY(:t)",+ {"p": project_id, "t": uniq},+ )+ return int(rows[0][0]) if rows else 0++ # ── ui helpers ────────────────────────────────────────────────────────────++ def member_timestamps(self, project_id: str, trace_ids: Iterable[str]) -> list[Any]:+ uniq = _uniq(trace_ids)+ if not uniq:+ return []+ rows = _pg.query_rows(+ "SELECT ts_min FROM traces WHERE project_id = :p AND trace_id = ANY(:t)",+ {"p": project_id, "t": uniq},+ )+ return [r[0] for r in rows]++ def version_breakdown(+ self, project_id: str, agent_id: str, member_ids: Iterable[str]+ ) -> list[dict[str, Any]]:+ rows = _pg.query_rows(+ "SELECT v, count(*), count(*) FILTER (WHERE trace_id = ANY(:m)), min(ts) FROM ("+ " SELECT trace_id, coalesce(max(agent_version_id) FILTER (WHERE agent_version_id <> ''), '') AS v, "+ " min(start_time) AS ts FROM events WHERE project_id = :p AND agent_id = :ag "+ " AND env <> 'ci' AND internal_kind = '' GROUP BY trace_id) x GROUP BY v",+ {"p": project_id, "ag": agent_id, "m": _uniq(member_ids)},+ )+ return [+ {"version_id": v, "runs": int(runs), "members": int(hits), "first_seen": first}+ for v, runs, hits, first in rows+ ]++ def member_meta(self, project_id: str, trace_ids: Iterable[str]) -> dict[str, dict[str, Any]]:+ uniq = _uniq(trace_ids)+ if not uniq:+ return {}+ rows = _pg.query_rows(+ "SELECT trace_id, ts_min, latency_ms, root_input, first_error FROM traces "+ "WHERE project_id = :p AND trace_id = ANY(:t)",+ {"p": project_id, "t": uniq},+ )+ return {+ r[0]: {"ts": r[1], "latency_ms": float(r[2]), "input": r[3], "error": r[4]}+ for r in rows+ }diff --git a/backend/tracely/infrastructure/spans/writer.py b/backend/tracely/infrastructure/spans/writer.pynew file mode 100644index 0000000..54eaef6--- /dev/null+++ b/backend/tracely/infrastructure/spans/writer.py@@ -0,0 +1,59 @@+"""The Postgres span insert — the twin of `clickhouse.client.insert_rows(..., "events", ...)`.++Idempotent the way ReplacingMergeTree was: a span is keyed by (project_id, trace_id, span_id), so a+re-delivered batch overwrites instead of duplicating, and the trace's rollup is recomputed from the+spans in the same transaction (see `rollup`)."""++from __future__ import annotations++from collections import defaultdict+from collections.abc import Iterable+from datetime import datetime, timezone+from typing import Any++from sqlalchemy import Connection, text++from tracely.infrastructure.spans import _pg, rollup+from tracely.infrastructure.spans.schema import COLUMNS, to_row++_KEY = ("project_id", "trace_id", "span_id")+_JSONB = {"usage_details", "cost_details", "tool_definitions", "metadata"}+++def _value(col: str) -> str:+ return f"CAST(:{col} AS jsonb)" if col in _JSONB else f":{col}"+++UPSERT = (+ f"INSERT INTO events ({', '.join(COLUMNS)}) VALUES ({', '.join(_value(c) for c in COLUMNS)}) "+ f"ON CONFLICT ({', '.join(_KEY)}) DO UPDATE SET "+ + ", ".join(f"{c} = EXCLUDED.{c}" for c in COLUMNS if c not in _KEY)+)+++def write_events(conn: Connection, events: Iterable[dict[str, Any]], *, lock: bool = True) -> int:+ """Upsert spans + refresh their traces' rollups on `conn` (caller owns the transaction)."""+ now = datetime.now(timezone.utc)+ by_project: dict[str, list[dict[str, Any]]] = defaultdict(list)+ for ev in events:+ if ev.get("project_id") and ev.get("trace_id") and ev.get("span_id"):+ by_project[ev["project_id"]].append(to_row(ev, now))+ n = 0+ for project_id, rows in by_project.items():+ trace_ids = {r["trace_id"] for r in rows}+ if lock:+ rollup.lock(conn, project_id, trace_ids)+ # executemany = one statement per row, so a span repeated inside one batch is simply+ # written twice (last wins) instead of tripping "ON CONFLICT cannot affect a row twice".+ conn.execute(text(UPSERT), rows)+ rollup.refresh(conn, project_id, trace_ids)+ n += len(rows)+ return n+++def insert_events(events: list[dict[str, Any]]) -> int:+ """`IngestionService`'s one write: spans + rollups, atomically."""+ if not events:+ return 0+ with _pg.SYNC.begin() as conn:+ return write_events(conn, events)diff --git a/backend/tracely/services/alert_events.py b/backend/tracely/services/alert_events.pyindex f6e62ce..e819913 100644--- a/backend/tracely/services/alert_events.py+++ b/backend/tracely/services/alert_events.py@@ -21,7 +21,7 @@ from sqlalchemy.orm import Sessionfrom tracely.config import settingsfrom tracely.domain.traces.spans import root_span-from tracely.infrastructure.clickhouse.trace_reader import TraceReader+from tracely.infrastructure.spans import TraceReaderfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.models import Agent, FailureCluster, GateRun, Projectdiff --git a/backend/tracely/services/evaluation_service.py b/backend/tracely/services/evaluation_service.pyindex 6af1810..8488e48 100644--- a/backend/tracely/services/evaluation_service.py+++ b/backend/tracely/services/evaluation_service.py@@ -40,8 +40,8 @@ from tracely.domain.evaluation.results import chain_payloadfrom tracely.domain.evaluation.targeting import spec_appliesfrom tracely.domain.evaluation.template_resolver import references_conversation_scopefrom tracely.domain.traces.spans import root_span-from tracely.infrastructure.clickhouse.score_writer import ScoreWriter-from tracely.infrastructure.clickhouse.trace_reader import TraceReader+from tracely.infrastructure.spans import ScoreWriter+from tracely.infrastructure.spans import TraceReaderfrom tracely.infrastructure.db import repositoriesfrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.llm import providerdiff --git a/backend/tracely/services/failure_intel_service.py b/backend/tracely/services/failure_intel_service.pyindex 27f50d1..6a50638 100644--- a/backend/tracely/services/failure_intel_service.py+++ b/backend/tracely/services/failure_intel_service.py@@ -25,7 +25,7 @@ from tracely.domain.failure.clustering import ClusterEnginefrom tracely.domain.failure.signature import text_partfrom tracely.domain.failure.text import embedding_text, summarize_failurefrom tracely.domain.traces.spans import root_span-from tracely.infrastructure.clickhouse.trace_reader import TraceReader+from tracely.infrastructure.spans import TraceReaderfrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.models import (ClusterMember,diff --git a/backend/tracely/services/gate_service.py b/backend/tracely/services/gate_service.pyindex 242795b..a1e49be 100644--- a/backend/tracely/services/gate_service.py+++ b/backend/tracely/services/gate_service.py@@ -45,8 +45,8 @@ from tracely.domain.simulation import (from tracely.domain.trajectory import build_trajectory, tool_sequencefrom tracely.domain.traces.spans import input_digestfrom tracely.infrastructure.blob import s3 as blobstore-from tracely.infrastructure.clickhouse.score_writer import ScoreWriter-from tracely.infrastructure.clickhouse.trace_reader import TraceReader+from tracely.infrastructure.spans import ScoreWriter+from tracely.infrastructure.spans import TraceReaderfrom tracely.infrastructure.db import repositoriesfrom tracely.infrastructure.db.models import (Agent,diff --git a/backend/tracely/services/ingestion_service.py b/backend/tracely/services/ingestion_service.pyindex e758bef..7de7f22 100644--- a/backend/tracely/services/ingestion_service.py+++ b/backend/tracely/services/ingestion_service.py@@ -17,8 +17,7 @@ import structlogfrom tracely.config import settingsfrom tracely.domain.cost import cost_detailsfrom tracely.infrastructure.blob import s3 as blobstore-from tracely.infrastructure.clickhouse.client import get_client, insert_rows-from tracely.infrastructure.clickhouse.events_schema import EVENT_COLUMNS, to_rows+from tracely.infrastructure import spansfrom tracely.infrastructure.db import repositoriesfrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.llm.provider import resolve_rate@@ -49,7 +48,7 @@ def ingest_otlp(project_id: str, content_type: str, raw: bytes) -> str:class IngestionService:- """Worker-side pipeline: blob → events → registry resolve → ClickHouse insert → schedule+ """Worker-side pipeline: blob → events → registry resolve → span-store insert → scheduleonline eval. Called from the `ingest_otlp_blob` Celery task."""def process_blob(self, project_id: str, key: str, content_type: str) -> dict:@@ -67,8 +66,7 @@ class IngestionService:self._extract_agent_definitions(project_id, events)self._fill_agents_workflow_root(project_id, events)- client = get_client()- insert_rows(client, "events", EVENT_COLUMNS, to_rows(events))+ spans.insert_events(events)trace_ids = sorted({ev.get("trace_id") for ev in events if ev.get("trace_id")})# Recordings of Tracely's own work (an evaluation, a scenario run) are reported separately@@ -115,21 +113,13 @@ class IngestionService:]if not roots:return- try:- client = get_client()- except Exception: # noqa: BLE001 — a missing fill must never fail ingestion- client = None # the batch's own model spans still countfor root in roots:tid = root.get("trace_id")gens = [ev for ev in events if ev.get("trace_id") == tid and ev.get("type") == "GENERATION"]try:- rows = [] if client is None else client.query(- "SELECT input, output, start_time FROM events FINAL PREWHERE trace_id = {t:String} "- "WHERE project_id = {p:String} AND is_deleted = 0 AND type = 'GENERATION'",- parameters={"t": tid, "p": project_id},- ).result_rows- except Exception: # noqa: BLE001- rows = []+ rows = _stored_generations(project_id, tid)+ except Exception: # noqa: BLE001 — a missing fill must never fail ingestion+ rows = [] # the batch's own model spans still countgens += [{"input": i, "output": o, "start_time": st} for i, o, st in rows]gens = sorted((g for g in gens if g.get("start_time") is not None), key=lambda g: g["start_time"])first_in = next((g["input"] for g in gens if g.get("input")), None)@@ -140,7 +130,7 @@ class IngestionService:@staticmethoddef _milestone_first_trace(project_id: str, events: list[dict]) -> None:- """`first_trace_received` — from a confirmed ClickHouse insert, not from a request."""+ """`first_trace_received` — from a confirmed span-store insert, not from a request."""try:from tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.services import milestones@@ -275,3 +265,8 @@ class IngestionService:ev["agent_version_id"] = registry.upsert_agent_version(session, slug_to_id[slug], ver)+++def _stored_generations(project_id: str, trace_id: str) -> list[tuple]:+ """`(input, output, start_time)` of the trace's GENERATION spans already in the span store."""+ return spans.TraceReader().trace_generations(project_id, trace_id)diff --git a/backend/tracely/services/introspection_service.py b/backend/tracely/services/introspection_service.pyindex 1e77aea..329bbb1 100644--- a/backend/tracely/services/introspection_service.py+++ b/backend/tracely/services/introspection_service.py@@ -30,7 +30,7 @@ from tracely.config import settingsfrom tracely.domain import introspectionfrom tracely.domain.introspection import Recordingfrom tracely.infrastructure.blob import s3 as blobstore-from tracely.infrastructure.clickhouse import deletes+from tracely.infrastructure.spans import deletesfrom tracely.services.ingestion_service import IngestionServicelog = structlog.get_logger(__name__)diff --git a/backend/tracely/services/monitoring_service.py b/backend/tracely/services/monitoring_service.pyindex 88f9667..6a82ce6 100644--- a/backend/tracely/services/monitoring_service.py+++ b/backend/tracely/services/monitoring_service.py@@ -38,7 +38,7 @@ from tracely.domain.monitoring.conditions import (event_matches,is_event_condition,)-from tracely.infrastructure.clickhouse import async_reader+from tracely.infrastructure.spans import async_readerfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.models import Monitordiff --git a/backend/tracely/services/purge_service.py b/backend/tracely/services/purge_service.pyindex 41f30d9..46e0e9e 100644--- a/backend/tracely/services/purge_service.py+++ b/backend/tracely/services/purge_service.py@@ -23,7 +23,9 @@ from datetime import datetime, timedelta, timezoneimport structlogfrom tracely.infrastructure.blob import s3-from tracely.infrastructure.clickhouse import deletes, maintenance+from tracely.infrastructure import spans+from tracely.infrastructure.clickhouse import maintenance+from tracely.infrastructure.spans import deletesfrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.repositories import project_plansfrom tracely.infrastructure.llm import checkpointer@@ -57,7 +59,7 @@ def purge_project(project_id: str, before: str | None) -> dict:Idempotent — a retry re-lists what is left and finishes the job."""cutoff = datetime.fromisoformat(before) if before else Noneblobs = s3.delete_project_blobs(project_id, traces_only=cutoff is not None, before=cutoff)- maintenance.compact_tables()+ _compact()log.info("project_purged", project_id=project_id, blobs=blobs, before=before)return {"project_id": project_id, "blobs": blobs}@@ -97,7 +99,7 @@ def purge_orphans(now: datetime | None = None) -> dict:blobs += s3.delete_project_blobs(pid)checkpointer.delete_project_chats(pid)if orphans:- maintenance.compact_tables()+ _compact()log.info("orphans_purged", projects=orphans, blobs=blobs)return {"purged": orphans, "blobs": blobs}@@ -125,3 +127,8 @@ def expire_otlp_blobs(now: datetime | None = None) -> dict:log.info("otlp_blobs_expired", before=cutoff.isoformat(), by_project=removed)return {"expired": sum(removed.values()), "before": cutoff.isoformat()}++def _compact() -> None:+ """Take masked rows off disk — a ClickHouse-only chore (Postgres DELETEs are real)."""+ if not spans.POSTGRES:+ maintenance.compact_tables()diff --git a/backend/tracely/services/regression_service.py b/backend/tracely/services/regression_service.pyindex 50521e0..6e02101 100644--- a/backend/tracely/services/regression_service.py+++ b/backend/tracely/services/regression_service.py@@ -34,8 +34,8 @@ from tracely.domain.trajectory import ()from tracely.domain.traces.spans import input_digest, root_spanfrom tracely.infrastructure.blob import s3 as blobstore-from tracely.infrastructure.clickhouse.score_writer import ScoreWriter-from tracely.infrastructure.clickhouse.trace_reader import TraceReader+from tracely.infrastructure.spans import ScoreWriter+from tracely.infrastructure.spans import TraceReaderfrom tracely.infrastructure.db.models import (CaseReplay,EvaluationCase,diff --git a/backend/tracely/services/retention_service.py b/backend/tracely/services/retention_service.pyindex 5d36aa0..8b926b0 100644--- a/backend/tracely/services/retention_service.py+++ b/backend/tracely/services/retention_service.py@@ -18,10 +18,12 @@ import structlogfrom tracely.config import settingsfrom tracely.domain.billing import retention_days_for-from tracely.infrastructure.clickhouse.deletes import delete_expired+from tracely.infrastructure.spans import deletes as _storefrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.repositories import project_plans+delete_expired = _store.delete_expired+log = structlog.get_logger()diff --git a/backend/tracely/services/rolling_summary_service.py b/backend/tracely/services/rolling_summary_service.pyindex bbcb74c..a97a16b 100644--- a/backend/tracely/services/rolling_summary_service.py+++ b/backend/tracely/services/rolling_summary_service.py@@ -39,7 +39,7 @@ from tracely.domain.evaluation.rolling_summary import (user_input_for_turn,)from tracely.domain.traces.spans import root_span-from tracely.infrastructure.clickhouse.trace_reader import TraceReader+from tracely.infrastructure.spans import TraceReaderfrom tracely.infrastructure.db import repositoriesfrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.llm import providerdiff --git a/backend/tracely/services/selfcheck_service.py b/backend/tracely/services/selfcheck_service.pyindex 458788c..9600f64 100644--- a/backend/tracely/services/selfcheck_service.py+++ b/backend/tracely/services/selfcheck_service.py@@ -71,25 +71,15 @@ async def snapshot() -> Snapshot:last_trace_age = disk_free_pct = Nonetry:- from tracely.infrastructure.clickhouse.client import get_async_client+ from tracely.infrastructure.spans import async_reader- ch = await get_async_client()- rows = (await ch.query("SELECT max(start_time) FROM events")).result_rows- newest = rows[0][0] if rows and rows[0] else None+ # The store's newest span + its own disk (ClickHouse; Postgres reports no disk figure).+ newest, disk_free_pct = await async_reader.store_health()if isinstance(newest, datetime):newest = newest if newest.tzinfo else newest.replace(tzinfo=timezone.utc)last_trace_age = (datetime.now(timezone.utc) - newest).total_seconds()- # The store's own disk. One query, same connection: a full disk is the failure mode that- # takes ClickHouse down entirely, and it arrives gradually enough to be caught.- disks = (- await ch.query(- "SELECT free_space, total_space FROM system.disks ORDER BY total_space DESC LIMIT 1"- )- ).result_rows- if disks and disks[0][1]:- disk_free_pct = 100.0 * float(disks[0][0]) / float(disks[0][1])except Exception as exc: # noqa: BLE001- log.warning("selfcheck_clickhouse_unreachable", error=str(exc))+ log.warning("selfcheck_span_store_unreachable", error=str(exc))return Snapshot(queue_depth=queue_depth,diff --git a/backend/tracely/workers/tasks.py b/backend/tracely/workers/tasks.pyindex c89b500..be6c8b2 100644--- a/backend/tracely/workers/tasks.py+++ b/backend/tracely/workers/tasks.py@@ -323,6 +323,23 @@ def enforce_retention_task(self) -> dict:return {"error": str(exc)}+@celery_app.task(name="tracely.expire_spans", bind=True, max_retries=0)+def expire_spans_task(self) -> dict:+ """Drop traces past `SPAN_RETENTION_DAYS` on the Postgres span store (beat, nightly) — the+ ClickHouse table TTL's twin, for every deployment. A no-op on ClickHouse, whose TTL does it.+ Runs after `enforce_retention`, so tonight's case-artifact snapshot already happened."""+ from tracely.config import settings+ from tracely.infrastructure import spans++ if not spans.POSTGRES:+ return {"skipped": "clickhouse ttl"}+ try:+ return {"spans": spans.deletes.expire_all(settings.span_retention_days)}+ except Exception as exc: # noqa: BLE001 — a missed night costs disk, never a grade+ log.warning("expire_spans_failed", error=str(exc))+ return {"error": str(exc)}++@celery_app.task(name="tracely.cap_system_logs", bind=True, max_retries=0)def cap_system_logs_task(self) -> dict:"""Cap ClickHouse's own telemetry tables with a TTL (beat, nightly).@@ -330,6 +347,10 @@ def cap_system_logs_task(self) -> dict:The database fills its disk with `query_log` / `trace_log` / `part_log` long before customertraces get near it, and nothing reads those. Idempotent — once a table carries a TTL this isa few reads. Never retried: reclaiming space is not correctness, and the next night retries."""+ from tracely.infrastructure import spans++ if spans.POSTGRES:+ return {"skipped": "postgres span store"}from tracely.infrastructure.clickhouse.maintenance import cap_system_logstry:@@ -388,6 +409,10 @@ def expire_otlp_blobs_task(self) -> dict:def compact_tables_task(self) -> dict:"""Physically drop masked and superseded rows from `events`/`scores` (beat, nightly) — see`maintenance.compact_tables`. Never retried: a missed night costs read speed, not data."""+ from tracely.infrastructure import spans++ if spans.POSTGRES:+ return {"skipped": "postgres span store"}from tracely.infrastructure.clickhouse.maintenance import compact_tablestry:diff --git a/deploy/railway/.env.railway.example b/deploy/railway/.env.railway.exampleindex 7c60605..9c6da39 100644--- a/deploy/railway/.env.railway.example+++ b/deploy/railway/.env.railway.example@@ -17,6 +17,9 @@ DATABASE_URL=postgresql+asyncpg://${{Postgres.PGUSER}}:${{Postgres.PGPASSWORD}}@ALEMBIC_DATABASE_URL=postgresql+psycopg://${{Postgres.PGUSER}}:${{Postgres.PGPASSWORD}}@${{Postgres.RAILWAY_PRIVATE_DOMAIN}}:5432/${{Postgres.PGDATABASE}}# ClickHouse template (HTTP interface on 8123, private). The migrate step creates the `tracely` DB.+# Span store: clickhouse (legacy) | postgres. Set the SAME value on the API and the worker.+# Switch only after `python -m tracely.infrastructure.spans.copy` reports "OK — stores agree".+SPAN_STORE=clickhouseCLICKHOUSE_HOST=${{ClickHouse.RAILWAY_PRIVATE_DOMAIN}}CLICKHOUSE_PORT=8123CLICKHOUSE_USER=${{ClickHouse.CLICKHOUSE_USER}}diff --git a/design/part2-tracely/14-clickhouse-to-postgres.md b/design/part2-tracely/14-clickhouse-to-postgres.mdnew file mode 100644index 0000000..4a6b089--- /dev/null+++ b/design/part2-tracely/14-clickhouse-to-postgres.md@@ -0,0 +1,583 @@+# 14 — Moving `events` / `scores` from ClickHouse to Postgres++**Status:** PRs 1–4 implemented (branch `feat/postgres-span-store`); cutover and PR 5 pending · **Date:** 2026-11-15 · **Supersedes:** the ClickHouse half of+[`09-database-schema.md`](09-database-schema.md) and the "ClickHouse `events`" box in+[`02-system-architecture.md`](02-system-architecture.md).++**Decision.** Tracely stores spans and scores in the Postgres it already runs. ClickHouse, its+DDL runner, its config and its maintenance jobs are deleted. This leaves four stores: Postgres,+S3/MinIO (raw OTLP stays the source of truth), Redis and pgvector (which lives in the same Postgres).++---++## 1. Why++What prod looked like on 2026-11-15:++| | |+|---|---|+| Live spans | **66.5k** (3 projects, 18.5k traces, 4.9k conversations) |+| Physical rows in `events` | 612k. **89% are lightweight-deleted rows** that were never compacted. Every query that reads `input` scans them. |+| Prompt text | 630 MiB live (9.3 GiB including dead rows), GENERATION input averages 30 KB |+| Read mix (24 days, 207k SELECTs) | **93% are by-trace span reads.** The threads list read 9 GiB per call and took 6–300 s. |++Benchmark: the real `async_reader` functions on ClickHouse 24.8 against hand-ported Postgres 17,+using synthetic data shaped like prod, with 2 CPU / 3 GB per container. Warm median times:++| Query | 1×: CH | 1×: PG | 10×: CH | 10×: PG (rollup) |+|---|---|---|---|---|+| Open a trace | 12.9 ms | **0.5 ms** | 24 ms | **1.0 ms** |+| Threads page | 72 ms | 85 ms | 427 ms | **400 ms** |+| Threads count | 29 ms | 29 ms | 167 ms | **120 ms** |+| Dashboard stats | 24 ms | 43 ms | 105 ms | **34 ms** |+| Ops trends, 30 days | 36 ms | 65 ms | **150 ms** | 744 ms (span table, not re-run on the rollup) |+| Text search (trigram, root + non-GENERATION spans) | 214 ms | **3 ms** | 2.7–4.3 s | **3–16 ms** |++ClickHouse is about 5× smaller on disk, and wins a brute-force scan over all text (3.9 s vs 88 s+without an index). Neither matters at 630 MiB. Every other number favours Postgres, or ties once the+per-trace rollup (§3) exists. The larger cost has been operations: hand-written PREWHERE, FINAL on+every read, tombstones instead of mutations, mark-cache ghosts, thread-pool jemalloc bloat, a+crash-loop from `background_pool_size`, 8 GB of unbounded `system.*` logs, lightweight deletes that+never leave the disk, and `MEMORY_LIMIT_EXCEEDED` on eks-dev. Self-hosting (Coolify, EKS) means+running one more stateful service.++ClickHouse has no row index, so a query either matches the sort key and is fast, or it+decompresses whole columns and is slow. Postgres's B-tree plus TOAST (large text stored out of+line, read only for rows that are returned) matches this workload: point lookups, lists of small+rows, and one trace's large text.++---++## 2. Schema (Alembic `0040_span_store`)++Raw DDL through `op.execute`, with **no ORM models**. The readers own their column lists, as they+do today. The SQLite test harness (`backend/tests/conftest.py`) creates only the registry tables,+and `jsonb`/`text[]` would break it there.++> Rebase on `origin/master` first: it has `0039_project_assistant_model` and the CH+> `0006_events_has_text` DDL. Postgres does not need 0006, because `input IS NOT NULL` reads no text.++```sql+CREATE EXTENSION IF NOT EXISTS pg_trgm; -- contrib: present in pgvector/pgvector and timescaledb-ha++CREATE TABLE events (+ project_id text NOT NULL,+ trace_id text NOT NULL,+ span_id text NOT NULL,+ parent_span_id text NOT NULL DEFAULT '',+ start_time timestamptz NOT NULL,+ end_time timestamptz,+ completion_start_time timestamptz,+ name text NOT NULL,+ type text NOT NULL,+ environment text NOT NULL DEFAULT 'default',+ env text NOT NULL DEFAULT 'prod',+ version text NOT NULL DEFAULT '',+ release text NOT NULL DEFAULT '',+ level text NOT NULL DEFAULT 'DEFAULT',+ status_message text NOT NULL DEFAULT '',+ is_app_root boolean NOT NULL DEFAULT false,+ trace_name text NOT NULL DEFAULT '',+ user_id text NOT NULL DEFAULT '',+ session_id text NOT NULL DEFAULT '',+ tags text[] NOT NULL DEFAULT '{}',+ agent_id text NOT NULL DEFAULT '',+ agent_version_id text NOT NULL DEFAULT '',+ agent_run_id text NOT NULL DEFAULT '',+ conversation_id text NOT NULL DEFAULT '',+ turn_id text NOT NULL DEFAULT '',+ turn_index integer NOT NULL DEFAULT 0,+ step_id text NOT NULL DEFAULT '',+ step_name text NOT NULL DEFAULT '',+ tool_call_id text NOT NULL DEFAULT '',+ caller_agent_id text NOT NULL DEFAULT '',+ callee_agent_id text NOT NULL DEFAULT '',+ edge_type text NOT NULL DEFAULT '',+ evaluation_case_id text NOT NULL DEFAULT '',+ gate_run_id text NOT NULL DEFAULT '',+ failure_cluster_id text NOT NULL DEFAULT '',+ internal_kind text NOT NULL DEFAULT '',+ subject_id text NOT NULL DEFAULT '',+ model_id text NOT NULL DEFAULT '',+ model_parameters text NOT NULL DEFAULT '',+ usage_details jsonb NOT NULL DEFAULT '{}',+ cost_details jsonb NOT NULL DEFAULT '{}',+ -- computed once in events_schema.to_rows (CH did arraySum(mapValues(...)) on every read)+ tokens bigint NOT NULL DEFAULT 0,+ input_tokens bigint NOT NULL DEFAULT 0,+ output_tokens bigint NOT NULL DEFAULT 0,+ cost double precision NOT NULL DEFAULT 0,+ tool_definitions jsonb NOT NULL DEFAULT '{}',+ tool_calls text[] NOT NULL DEFAULT '{}',+ tool_call_names text[] NOT NULL DEFAULT '{}',+ input text COMPRESSION lz4, -- NULL = no text (to_rows already enforces '' -> NULL)+ output text COMPRESSION lz4,+ metadata jsonb NOT NULL DEFAULT '{}',+ source text NOT NULL DEFAULT 'otel',+ service_name text NOT NULL DEFAULT '',+ scope_name text NOT NULL DEFAULT '',+ telemetry_sdk_language text NOT NULL DEFAULT '',+ telemetry_sdk_name text NOT NULL DEFAULT '',+ telemetry_sdk_version text NOT NULL DEFAULT '',+ created_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (project_id, trace_id, span_id) -- by-trace reads, span_count, dedup key+);+CREATE INDEX events_conv ON events (project_id, conversation_id) WHERE conversation_id <> '';+CREATE INDEX events_time ON events (project_id, start_time); -- ops windows, retention+CREATE INDEX events_agent ON events (project_id, agent_id); -- gate candidates, versions+CREATE INDEX events_root_input ON events (project_id, agent_id, md5(input)) WHERE is_app_root; -- traces_with_input+CREATE INDEX events_run_id ON events (project_id, (metadata->>'tracely.replay.run_id'))+ WHERE metadata ? 'tracely.replay.run_id'; -- traces_for_run+-- Text search. GENERATION input is the whole history plus the system prompt, repeated on every+-- turn, so it is noise for search and would be most of the index.+CREATE INDEX events_output_trgm ON events USING gin (output gin_trgm_ops);+CREATE INDEX events_input_trgm ON events USING gin (input gin_trgm_ops) WHERE type <> 'GENERATION';++CREATE TABLE scores (+ project_id text NOT NULL,+ id text NOT NULL, -- uuid5, deterministic (score_writer.eval_score_id)+ trace_id text,+ observation_id text,+ session_id text,+ agent_run_id text NOT NULL DEFAULT '',+ turn_id text NOT NULL DEFAULT '',+ name text NOT NULL,+ source text NOT NULL,+ data_type text NOT NULL,+ value double precision,+ string_value text NOT NULL DEFAULT '',+ verdict text NOT NULL DEFAULT '',+ evaluation_case_id text NOT NULL DEFAULT '',+ gate_run_id text NOT NULL DEFAULT '',+ evaluation_level text NOT NULL DEFAULT '',+ execution_trace_id text NOT NULL DEFAULT '',+ comment text NOT NULL DEFAULT '',+ metadata jsonb NOT NULL DEFAULT '{}',+ created_at timestamptz NOT NULL DEFAULT now(), -- write time; re-grade overwrites it, as FINAL did+ PRIMARY KEY (project_id, id)+);+CREATE INDEX scores_trace ON scores (project_id, trace_id);+CREATE INDEX scores_session ON scores (project_id, session_id) WHERE evaluation_level = 'CONVERSATION';+CREATE INDEX scores_name ON scores (project_id, name, created_at);+CREATE INDEX scores_online_fail ON scores (project_id, trace_id, name)+ WHERE source = 'EVAL' AND evaluation_case_id = '' AND verdict = 'FAIL'; -- every "failing" subquery+```++No FINAL, `is_deleted`, `event_ts`, `SAMPLE BY` or TTL. The CH bloom filters on `agent_run_id`,+`gate_run_id`, `evaluation_case_id` and `subject_id` are not carried over, because no query filters+`events` on them.++---++## 3. The per-trace rollup: `traces`++At 10× the thread list was 1.06 s when grouped from spans and 0.40 s from this table. Each list,+count and trend reads one row per trace instead of 3.6 spans.++```sql+CREATE TABLE traces (+ project_id text NOT NULL,+ trace_id text NOT NULL,+ thread_id text NOT NULL, -- coalesce(nullif(max(conversation_id), ''), trace_id)+ conversation_id text NOT NULL DEFAULT '',+ env text NOT NULL DEFAULT 'prod',+ internal_kind text NOT NULL DEFAULT '', -- _REAL lives here too+ subject_id text NOT NULL DEFAULT '',+ agent_id text NOT NULL DEFAULT '', -- the _TRACE_AGENT rule (root, else app-root, else any)+ app_root_agent_id text NOT NULL DEFAULT '', -- anyIf(agent_id, is_app_root): trace_agent_ids+ root_name text NOT NULL DEFAULT '', -- _root("name"), else earliest span's name+ root_input text COMPRESSION lz4, -- _root("input"): what every judge grades+ root_output text COMPRESSION lz4,+ has_input boolean NOT NULL DEFAULT false, -- _root_has, NULL map semantics+ has_output boolean NOT NULL DEFAULT false,+ spans integer NOT NULL,+ ts_min timestamptz NOT NULL,+ ts_max timestamptz NOT NULL, -- max(coalesce(end_time, start_time))+ latency_ms bigint NOT NULL,+ tokens bigint NOT NULL DEFAULT 0,+ input_tokens bigint NOT NULL DEFAULT 0,+ output_tokens bigint NOT NULL DEFAULT 0,+ cost double precision NOT NULL DEFAULT 0,+ model_id text NOT NULL DEFAULT '', -- argMaxIf(model_id, tokens, GENERATION)+ has_error boolean NOT NULL DEFAULT false,+ tool_errors integer NOT NULL DEFAULT 0,+ first_error text NOT NULL DEFAULT '', -- earliest non-empty status_message (member_meta)+ has_emulated_turn boolean NOT NULL DEFAULT false, -- latest_traces_for_env excludes these+ metadata jsonb NOT NULL DEFAULT '{}', -- merged tracely.metadata.* keys+ updated_at timestamptz NOT NULL DEFAULT now(),+ PRIMARY KEY (project_id, trace_id)+);+CREATE INDEX traces_thread ON traces (project_id, thread_id);+CREATE INDEX traces_recent ON traces (project_id, ts_max DESC);+CREATE INDEX traces_start ON traces (project_id, ts_min);+CREATE INDEX traces_agent ON traces (project_id, agent_id);+CREATE INDEX traces_root_input_trgm ON traces USING gin (root_input gin_trgm_ops); -- search_threads+```++**Write rule.** `rollup.refresh(conn, project_id, trace_ids)` is a single+`INSERT INTO traces SELECT … FROM events WHERE project_id = $1 AND trace_id = ANY($2) GROUP BY trace_id+ON CONFLICT (project_id, trace_id) DO UPDATE SET …`, followed by+`DELETE FROM traces t WHERE … AND NOT EXISTS (spans)`. It recomputes from the spans every time,+so late spans, re-deliveries and partial deletes all converge, the same way ReplacingMergeTree did.++It is called **in the same transaction** as every span write or delete:++1. `IngestionService.process_blob` (`services/ingestion_service.py:71`), which is the one span+ insert. The inline emulated-turn ingest and introspection recordings reach the same writer.+2. `deletes.delete_trace`, `delete_threads`, and retention.++**Concurrency.** Two workers can ingest spans of the same trace at once. Under READ COMMITTED,+each recompute would miss the other's uncommitted spans. Before the insert, take+`pg_advisory_xact_lock(hashtextextended(project_id || ':' || trace_id, 0))` for each touched trace,+in sorted order so there are no deadlocks. Today this costs nothing: the worker runs+`--pool=solo --concurrency=1`. It matters as soon as `CELERY_CONCURRENCY` is above 1.++**What the rollup does not contain: verdicts.** Scores change separately, and the advisory set can+change at any time. The "failing" flag stays a read-time join against `scores_online_fail` with+`name <> ALL(adv)`. That keeps the one verdict policy in one SQL expression (§7).++---++## 4. Read mapping++New modules live under `backend/tracely/infrastructure/spans/`: `reads.py` (async, for the API),+`trace_reader.py` (sync `TraceReader`, for workers), `writer.py`, `rollup.py`, `pg_deletes.py`+(not `deletes.py`: the package exports an attribute named `deletes`, and a same-named submodule+would be swapped in by the import system and silently repoint callers at the other store).+**Function names, signatures and return shapes do not change**, so routers, services and the+frontend are untouched. Async goes through `db/engine.async_engine` (asyncpg) and sync through+`db/engine.sync_engine` (psycopg), both with `text()` and bound parameters.++### `async_reader.py` → `spans/reads.py`++| Function | Reads | Notes |+|---|---|---|+| `traces_overview` | `traces` + fail join | `ORDER BY ts_min DESC LIMIT n` |+| `trace_spans` | `events` PK | was PREWHERE; now an index range |+| `thread_spans_full` | `events` PK ∪ `events_conv` | `conversation_id = $th OR trace_id = $th` → BitmapOr |+| `thread_turn_count` | `traces_thread` | `count(*) WHERE thread_id = $th AND internal_kind = ''` |+| `trace_scores` | `scores_trace` ∪ `scores_session` | |+| `evaluator_cost` | `scores_name` | `metadata->>'eval.total_tokens'` with `jsonb ?` instead of `mapContains` |+| `traces_in_window` | `traces_start` | `env <> 'ci' AND internal_kind = ''` |+| `score_samples_in_window` | `scores_name` (+ `events_agent` for an agent) | same span-level agent match as before |+| `trace_failure_samples_in_window` | `traces` + fail join | `root_agent` is `traces.agent_id` |+| `evaluator_catalog`, `evaluator_score_queue` | `scores` + `EXISTS traces` (`_REVIEWABLE`) | `ORDER BY md5(id)` replaces `cityHash64(id)` |+| `sessions_overview` (page / `count_only`) | `traces` grouped by `thread_id` + fail join | page text comes from `traces.root_input/root_output`, so `_trace_texts` is no longer a separate query |+| `sessions_overview(q=…)` | thread rollup ∪ trigram hit on `events` | `text_hit` = `EXISTS (events … AND (output ILIKE q OR (type <> 'GENERATION' AND input ILIKE q)))` per thread, plus the haystack (`model`, `metadata::text`, `agent_id`, `root_name`, `subject_id`) |+| `thread_agents` | — | Python over `thread_spans_full` |+| `session_turns` | `traces` + fail join | `WHERE thread_id = $th`; the "other conversation_id" guard is the key itself |+| `scores_by_trace`, `conversation_scores_by_thread` | `scores_trace`, `scores_session` | `trace_id = ANY($ids)` |+| `agent_trace_ids` | `traces_agent` / `traces_recent` | |+| `trace_agent_ids` | `traces` | `DISTINCT app_root_agent_id` |+| `agent_ids_with_spans` | `events_agent` | `DISTINCT agent_id` including internal, as today |+| `_trace_ops_rows` | `traces` | `latency_ms`, `tokens`, `tool_errors` |+| `agent_score_rows` | — | composition, no SQL of its own |+| `search_threads` | `traces_root_input_trgm` | matches `root_input`: see §5 |+| `stats_counts` | `traces` + `scores_online_fail` | spans = `sum(spans)` |+| `ops_metrics` daily | `traces_start` | `percentile_cont(...) WITHIN GROUP`, `GROUP BY ROLLUP (d)` (same ROLLUP trick) |+| `ops_metrics` per model / slowest | `events_time` | still span-level; 0.5–0.7 s at 10×, see §10 |+| `daily_trace_failures`, `trace_failure_totals` | `traces` + fail join | |++### `trace_reader.py` (sync) → `spans/trace_reader.py`++| Method | Reads | Notes |+|---|---|---|+| `read_spans`, `read_thread_spans` | `events` PK / `events_conv` | the eval runner, regression, gate and FI keep their `_SPAN_COLS` |+| `thread_trace_ids` | `traces_thread` | `ORDER BY ts_min` |+| `candidate_metrics` | `traces` | `latency_ms`, `tokens` |+| `latest_traces_for_env` | `events_agent` | span-level, exactly as before |+| `traces_with_input` | `events_root_input` | `md5(input) = md5($i) AND input = $i` |+| `traces_for_run` | `events_run_id` | |+| `failing_trace_reasons`, `scores_by_trace` | `scores_online_fail`, `scores_trace` | |+| `recent_failing_traces` | `scores_online_fail` ⋈ `traces` | input = `root_input`: see §5 |+| `span_count` | `events` PK | index-only count; it is a stability signal, so it reads spans, not the rollup |+| `member_timestamps` | `traces` | `ts_min` |+| `version_breakdown` | `events_agent` | per-trace `anyIf(agent_version_id)` stays span-level |+| `member_meta` | `traces` | `ts_min`, `latency_ms`, `root_input`, `first_error` |++### Raw ClickHouse SQL outside the two readers (move it into them)++| Where | Today | Postgres |+|---|---|---|+| `services/ingestion_service.py:119-127` (`_fill_agents_workflow_root`) | `SELECT input, output, start_time FROM events FINAL PREWHERE trace_id …` on its own client | new `TraceReader.trace_generations(project_id, trace_id)` on `events` PK. This also removes a second "SQL outside the readers" exception. |+| `services/selfcheck_service.py:74-92` | `max(start_time) FROM events` + `system.disks` | `max(ts_max) FROM traces`. Postgres cannot see its filesystem's free space from SQL. Report `pg_database_size()` against an optional `DB_VOLUME_GB` setting, and skip the disk verdict when it is unset (it is already skipped when CH is unreachable). **Open decision.** |+| `api/routers/health.py:52-56` | `deps["clickhouse"]` = async client `ping()` | drop the dependency. Postgres is already probed. |++Translation idioms used throughout: `countIf(x)` → `count(*) FILTER (WHERE x)`;+`anyIf(c, x)` → `max(c) FILTER (WHERE x)`; `argMin(a, b)` → `(array_agg(a ORDER BY b))[1]`;+`uniqExact(x)` → `count(DISTINCT x)`; `positionCaseInsensitiveUTF8(h, q) > 0` → `h ILIKE '%' || q || '%'`+(escape `%`/`_` in `q`); `x IN {a:Array(String)}` → `x = ANY($a)`;+`subtractDays(now(), d)` → `now() - make_interval(days => $d)`.++---++## 5. Deliberate behaviour changes++Each needs a line in the release notes and a test that pins the new rule.++1. **Text search skips GENERATION *inputs*.** They hold the whole history and the system prompt,+ so any word in a system prompt matched every thread. Root input, tool I/O and every output+ (assistant replies included) are still searched.+2. **"First input" means the root input** (the `_root` rule) in `search_threads`,+ `recent_failing_traces` and `member_meta`. It used to be the earliest non-empty input of any+ span. The two agree whenever the root carries the user message. Otherwise the old rule returned+ a GENERATION's full history.+3. **The calibration queue order changes** (`md5(id)` instead of `cityHash64(id)`). It is still a+ stable random sample. Existing labels are keyed by score id and are unaffected.+4. **Retention removes whole traces** once a trace's newest span is past the cutoff. A per-span+ TTL used to cut a long-running trace in half.+5. **Dedup key is `(project_id, trace_id, span_id)`.** CH also keyed on the exact `start_time`, so a+ re-delivered span with a shifted clock duplicated. Now it replaces.+6. **Deletes are immediate.** No tombstone window, and no "masked but still read" rows.+7. **Thread metadata takes the latest turn's value** when turns disagree on a key. ClickHouse kept an+ arbitrary one. The copy's verifier compares metadata keys only, for that reason.+8. **A trace is dated once, by its first span** (`daily_trace_failures`, ops daily). ClickHouse+ counted a trace that crosses midnight UTC on both days. The verifier allows ±1%.++---++## 6. Writes and deletes++| Today (ClickHouse) | Postgres |+|---|---|+| `client.insert_rows` + `async_insert` | `writer.upsert_events`: dedupe the batch by key in Python (ON CONFLICT cannot touch a row twice in one statement), `executemany` `INSERT … ON CONFLICT (project_id, trace_id, span_id) DO UPDATE SET <all columns> = EXCLUDED.*`, then `rollup.refresh`, in one transaction |+| `events_schema.to_rows` | same column list plus the computed `tokens / input_tokens / output_tokens / cost`; Maps become dicts (jsonb), Arrays become lists |+| `ScoreWriter.write_eval_scores` | `INSERT … ON CONFLICT (project_id, id) DO UPDATE` (same uuid5 ids) |+| `retract_eval_scores`, `retract_evaluator` (tombstones) | `DELETE FROM scores WHERE project_id = $1 AND id = ANY($2)` |+| `write_regression_verdict` | plain INSERT (uuid4) |+| `deletes.delete_trace(step_names)` (tombstones) | `DELETE FROM events WHERE … AND step_name = ANY($s)` + `rollup.refresh` |+| `delete_threads` | delete `events` / `scores` / `traces` by trace ids, in one transaction |+| `delete_project_events`, `delete_project_rows` | `DELETE … WHERE project_id = $1` in 10k-row batches (`ctid IN (SELECT … LIMIT 10000)`), still queued through `tracely.purge_project` |+| CH TTL 90 days + `delete_expired` (plan retention) | one beat task `expire_traces`: `SELECT trace_id FROM traces WHERE project_id = ANY($p) AND ts_max < $cutoff LIMIT 1000`, then delete those traces' events, scores and rollup, looping. This replaces both the TTL and the per-plan path. It **must run on every deployment** with the 90-day cutoff, which the TTL used to give self-hosters for free. Plan retention (hosted only, today's `enforce_retention`) only narrows the cutoff for each project. |+| `last_write_by_project` (orphan sweep) | `SELECT project_id, max(updated_at) FROM traces GROUP BY project_id` |+| `maintenance.compact_tables`, `cap_system_logs` | deleted. Autovacuum handles dead tuples. |++---++## 7. Hard rules (CLAUDE.md): how each survives++- **No SQL in routers.** Unchanged in spirit. The rule's module names change from+ `clickhouse/async_reader.py` / `trace_reader.py` to `spans/reads.py` / `spans/trace_reader.py`.+- **One verdict policy.** The SQL twin becomes `name <> ALL(:adv)`. Do not use `NOT IN`, which+ cannot bind an array. `<> ALL('{}')` is true, so an empty advisory list excludes nothing,+ exactly like CH `NOT IN []`. Defined once (`_FAILING` / `_FAILING_THREADS` equivalents in+ `spans/reads.py`), as now.+- **Internal runs are never evaluated.** The ingest-hop skip and the `evaluate_trace` refusal are+ Python and keep working (`read_spans` keeps its signature). `_REAL` becomes+ `internal_kind = ''` on `traces` for every list, count and metric, and on `events` for the+ span-level ones. `sessions_overview(include_internal=True)` is still the only opt-in.+- **Writes are idempotent.** Deterministic ids are unchanged. `ON CONFLICT DO UPDATE` replaces+ ReplacingMergeTree + FINAL. The rollup is recomputed from spans, never incremented.+- **Scoped by `project_id`.** Every PK and index starts with it. Every query binds it.+- **SKIP scores dropped before roll-up, emulated-conversation invariants.** Untouched (domain+ code). The inline turn ingest must call `writer.upsert_events`, which it does if it goes through+ `IngestionService`. Verify this in PR 2.+- **"Five stores" becomes four.** Remove the ClickHouse gotchas. The "worker does not hot-reload"+ note stays.++---++## 8. Rollout++There is **no dual-write**. The ingest path writes OTLP to S3 *before* enqueueing, so a stopped+worker loses nothing: requests keep landing in S3/Redis and are ingested when the worker comes+back. A short cutover window is lossless, and dual-write would be code deleted two weeks later.++| # | PR | Contents | Risk |+|---|---|---|---|+| 1 | **Schema** | Alembic `0040_span_store` (§2, §3). Purely additive. | none |+| 2 | **Writer** | `spans/writer.py`, `rollup.py`, `pg_deletes.py`, `expire_spans` beat task, `to_rows` computed columns. Writes go to Postgres when `SPAN_STORE=postgres` (default `clickhouse`). Wire into `docker-compose.yml`'s `x-app-env`. | low (flag off) |+| 3 | **Readers** | `spans/reads.py`, `spans/trace_reader.py` with identical signatures. `tracely.infrastructure.spans` exposes `async_reader` / `TraceReader` / `ScoreWriter` / `deletes` chosen by `SPAN_STORE` (about 10 lines). Callers switch imports to it (mechanical). **Parity tests** load one fixture set into both stores and compare outputs. | low (flag off) |+| 4 | **Copy + verify** | `python -m tracely.infrastructure.spans.copy`: reads CH `FINAL WHERE is_deleted = 0` in batches of 500 whole traces through `writer.write_events`, then scores. Idempotent, safe to re-run. `--verify` compares per-project span/trace/score counts and runs every read in §4 against both stores for N sample threads. | none |+| — | **Cutover (ops)** | Stop the worker. Set `SPAN_STORE=postgres` on api + worker. Run the copy for all projects (66.5k spans, about a minute). Run `--verify`. Start the worker; it drains the queued ingest into Postgres. Watch `/health/queue` and the traces tab. **Rollback:** set `SPAN_STORE=clickhouse` (CH is untouched; traces ingested after cutover replay from S3). | low |+| 5 | **Remove ClickHouse** | after about a week on Postgres: delete `infrastructure/clickhouse/`, the CH DDL, the flag, `maintenance.py`, CH tests, `clickhouse-connect` (moves to a `clickhouse` extra for the copy script only), CH services in every deploy target, docs (§9). | low |+| 6 | (later) | delete the copy script and the extra after two releases | none |++**Self-hosters** (compose, Coolify, EKS) follow the same steps. The release notes for PR 4 give+the commands. PR 5's notes say: if you skipped the copy, your data is still in ClickHouse; run+`python -m tracely.infrastructure.spans.copy` from the last release that still has it, with the old `CLICKHOUSE_*`+variables before removing the volume.++**Before any of this:** the prod worker has been stuck since 2026-11-08 04:02 UTC (41,712 queued).+Fix it first, or the cutover's "drain the queue" step means 41k tasks at once.++---++## 9. What gets deleted in PR 5++Inventory taken 2026-11-15 from local `master` plus `origin/master` (`b9dbe1d`).++**Code.** Delete:++- `backend/tracely/infrastructure/clickhouse/`: `client.py`, `async_reader.py`, `trace_reader.py`,+ `score_writer.py`, `deletes.py`, `events_schema.py` (its column list moves to `spans/`),+ `maintenance.py`, `migrations.py`, and `ddl/0001-0006`.+- Beat entries in `infrastructure/queue/celery_app.py:57-78`, and the tasks in `workers/tasks.py`+ (about lines 326-391): `cap_system_logs`, `compact_tables`.+- In `services/purge_service.py`, its call to `compact_tables`.++Two beat entries stay but get new bodies: `enforce_retention`, which now calls `expire_traces`,+and `purge_orphans`, which now calls `last_write_by_project` on `traces`.++`api/main.py:40,108` (the `close_async_client` lifespan hook) is deleted. The engines already+dispose themselves.++**Callers whose import line changes** (mechanical, no logic change):++- Routers: `traces`, `sessions`, `share`, `search`, `analytics`, `cases`, `scenarios`,+ `evaluations`, `evaluators`, `calibration`, `meta_analysis`, `admin`, `auth`, `clusters`.+ `gate` is indirect, through `gate_svc.trace_reader`.+- Services: `ingestion`, `evaluation`, `gate`, `regression`, `failure_intel`, `rolling_summary`,+ `alert_events`, `monitoring`, `purge`, `retention`, `introspection`, `selfcheck`.+ `simulation_service` reaches the writer through `IngestionService.process_blob`, which is what+ keeps the inline-ingest invariant.+- Scripts: `debug_evaluation.py`, `debug_failure_clustering.py`.++**Scripts.**++| Action | Script |+|---|---|+| delete | `scripts/ch_usage.py` |+| rewrite the store section for Postgres (`pg_total_relation_size` per table + TOAST) | `scripts/storage_report.py:74-150,321-334` |+| replace the `curl localhost:8123 TRUNCATE` | `scripts/run_all_examples.sh:45-46` |+| drop the CH migration step | `scripts/docker-start.sh:11-17` |++**Tests.**++| Action | Tests |+|---|---|+| delete | `test_ch_read_invariants.py`, `test_ch_maintenance.py`, `test_ch_migrations_wait.py` |+| rewrite for the PG store | `test_calibration_queue.py` (its tombstone case becomes a DELETE case), `test_eval_prompt.py` (`delete_trace`), `test_otel_mapping.py` (`to_rows` + computed tokens/cost), `test_purge_service.py` (no compaction, aware timestamps), `test_health.py` (`_FakeCH`), `test_agents_workflow_root.py` (`get_client` patch → reader method) |+| change only the patched import path | `test_session_filters.py`, `test_conversation_agents.py`, `test_evaluators_api.py`, `test_llm_judge_levels.py`, `test_evaluation_run_stream.py`, `test_bulk_export.py`, `test_mcp_server.py`, `test_sessions_delete.py`, `test_data_delete.py`, `test_workspace_delete.py`, `test_retention.py`, `test_scenario_hardening.py`, `test_case_grading_parity.py`, `test_case_artifacts.py`, `test_gate_eval.py`, `test_rolling_summary.py`, `test_simulation.py` |+| keep | `test_net_guard.py` (`clickhouse:8123` is still a private host worth blocking until the service is gone) |++`session_filter_clauses` is used by tests directly. Keep the function and its name, and return+PG HAVING fragments.++**Config and env.**++- `config.py:20-26` (`clickhouse_*`), `:306` (`ch_system_log_ttl_days`) and the `:109` comment.+- `.env.example:8-16,30` and `deploy/railway/.env.railway.example:19-25`.+- The `x-app-env` anchor in `docker-compose.yml:10-18` and `docker-compose.coolify.yml:14-19,32`.++`SPAN_STORE` exists in PRs 2–4 only.++**Deploy.**++- `docker-compose.yml`: the `clickhouse` service (`:146-159`), `.data/clickhouse`, the migrate+ command (`:228`) and `depends_on` (`:224,269`).+- `docker-compose.coolify.yml`: service `:57-69`, migrate `:113-126`, volume `:193`.+- `deploy/coolify/setup.py:176-186,253-255`.+- `deploy/eks/base/tracely.yaml`: ConfigMap `:16-20`, Service + StatefulSet `:73-100`, migrate Job.+- `deploy/eks/create-secret.sh:14`.+- `deploy/railway/backend.json:8` (preDeploy runs CH migrations first). Then the Railway+ `ClickHouse` service itself, deleted after the copy is verified and a final backup is taken.+- `Makefile:6,19-22` (`migrate-ch`).++**Dependency.** `backend/pyproject.toml:14` `clickhouse-connect` moves to an optional `clickhouse`+extra (for the copy script), then is deleted. Regenerate `uv.lock`, since CI runs `uv sync --frozen`.++**Frontend.** `frontend/app/components/PipelinePeek.tsx:34,51,66,243` has hard-coded "clickhouse" labels.++**Docs.**++| File | Sections |+|---|---|+| `CLAUDE.md` | Commands, Architecture, Hard rules (§7) |+| `backend/README.md` | five stores, ingest, eval, meta-analysis, module map, API surface, data schemas, key decisions |+| `README.md` | Docker, local dev, deploy, architecture, repo map |+| `CONTRIBUTING.md` | |+| `guides/OVERVIEW.md` | |+| `guides/DEPLOY.md` | env, beat, restore test, health probe |+| `guides/EVALUATION_GUIDE.md` | §6 |+| `guides/EVALUATION_CODE_MAP.md` | §2, §5 |+| `docs/pages/index.mdx` | |+| `docs/pages/self-hosting.mdx` | "Add the four databases" becomes three |+| `scripts/README.md` | |+| `workers/README.md` | |+| `deploy/railway/README.md` | |+| `deploy/eks/README.md` | |+| `deploy/coolify/README.md` | |+| `design/part2-tracely/02-system-architecture.md`, `09-database-schema.md` | point to this doc |++---++## 10. Tests and CI++- **The local suite stays infra-free.** The new Postgres tests skip unless `TRACELY_TEST_PG_URL`+ is set.+- **CI adds a Postgres service** to `.github/workflows/ci.yml`+ (`services: postgres: image: pgvector/pgvector:pg17`) and sets the URL, so the reader, rollup+ and parity tests run on every PR.+- **New invariant tests** replace `test_ch_read_invariants.py`:+ - Every reader binds `project_id`.+ - Every list, count or metric filters `internal_kind = ''`.+ - The verdict twin uses `<> ALL`.+ - `rollup.refresh` is called in the same transaction as every span write or delete.+ - A recomputed rollup equals the span-level aggregation for random fixtures.++## 11. Size++| PR | Lines |+|---|---|+| 1 | about 150 |+| 2 | about 450 |+| 3 | about 1,400 readers + about 400 tests |+| 4 | about 200 |+| 5 | about −2,400 Python (the CH package), plus DDL, maintenance, CH tests, compose/deploy blocks and the Railway CH service |++The net result is **smaller** code and one fewer stateful service everywhere. Estimated effort+is about one focused week.++## 12. Ceilings: when to revisit++| What | Measured | Upgrade path |+|---|---|---|+| Thread list from `traces` | 0.40 s at 200k traces | about 4 s at 2M traces: add a `threads` rollup refreshed the same way |+| `ops_metrics` per-model / slowest | 0.5–0.7 s at 625k spans | partial index `WHERE model_id <> ''`, or a daily per-model rollup |+| Text storage | GENERATION input repeats the history, so it grows quadratically per conversation | store only the new messages and rebuild history on read, or keep large inputs in the S3 blob only |+| Insert throughput | `executemany` | COPY into a temp table + `INSERT … SELECT … ON CONFLICT` |+| Scale | — | revisit a columnar store (or Timescale compression) past about 50M spans, or when rollup reads pass 1 s p95 |++## 13. Rejected alternatives++- **TimescaleDB hypertables.** Only Railway runs the Timescale image; compose, Coolify and EKS+ run `pgvector/pgvector`. Per-plan retention is per project, so dropping a chunk can't implement it.+- **Declarative partitioning.** It needs partition-management code, and deletes are per project anyway.+- **Triggers maintaining `traces`.** That is a hidden cost on every span. An explicit+ recompute in the ingest transaction is visible and testable.+- **Dual-write.** S3-first ingest already makes a cutover window lossless (§8).+- **Keeping ClickHouse for analytics only.** That means two span stores to keep consistent, and+ no query at this scale needs it.++---++## 14. What was built (PRs 1–4) and how it was checked++| Piece | Where |+|---|---|+| Schema | `backend/migrations/versions/0040_span_store.py` |+| Store switch | `SPAN_STORE` (`config.py`, compose `x-app-env`), `tracely.infrastructure.spans` |+| Postgres store | `spans/` `writer.py`, `rollup.py`, `reads.py`, `trace_reader.py`, `score_writer.py`, `pg_deletes.py` |+| Copy + verify | `python -m tracely.infrastructure.spans.copy [--project P] [--verify-only]` |+| Retention | beat `tracely.expire_spans` (04:57, `SPAN_RETENTION_DAYS`, default 90) |+| Tests | `backend/tests/test_span_store_pg.py` (CI Postgres service, skipped locally without `TRACELY_TEST_PG_URL`) |++Every caller (routers, services, ingestion, selfcheck, health, purge, retention) imports the store+from `tracely.infrastructure.spans`. The ingest-time "Agent workflow" fill and the selfcheck read+moved into the readers (`TraceReader.trace_generations`, `async_reader.store_health`). With+`SPAN_STORE=postgres`, the ClickHouse-only chores (`cap_system_logs`, `compact_tables`, the CH+health ping, the async-client close) are skipped.++**Checked on 2026-11-15** with local ClickHouse 24.8 and Postgres 17. The fixture had 400+conversations and 3,766 spans across 2 projects, including rootless traces, internal runs,+tombstoned spans, retracted scores, conversation scores, error spans, replay run ids and+emulated turns.++- **Async readers.** The copy's `--verify` reported **0 mismatches** after the two §5 rules (7, 8)+ were encoded.+- **Sync `TraceReader`.** Every method compared ClickHouse vs Postgres with **0 mismatches**.+- **Copy.** Re-running converged to the same counts.+- **Full suite.** It passes on the default ClickHouse store, and with `TRACELY_TEST_PG_URL` set.+ Under `SPAN_STORE=postgres`, only the tests that assert ClickHouse-only behaviour differ (the+ health `clickhouse` key, compaction calls).diff --git a/docker-compose.yml b/docker-compose.ymlindex 5a8056f..fe19b11 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -7,6 +7,9 @@ x-app-env: &app-envTRACELY_ENV: dockerDATABASE_URL: postgresql+asyncpg://tracely:tracely@postgres:5432/tracelyALEMBIC_DATABASE_URL: postgresql+psycopg://tracely:tracely@postgres:5432/tracely+ # Span store: clickhouse (legacy) | postgres. API and worker must agree.+ SPAN_STORE: ${SPAN_STORE:-clickhouse}+ SPAN_RETENTION_DAYS: ${SPAN_RETENTION_DAYS:-90}CLICKHOUSE_HOST: clickhouseCLICKHOUSE_PORT: "8123"CLICKHOUSE_USER: default