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
fix: make "delete all data" actually delete it, and keep ClickHouse lean on its own
Wuthrich Julienc6ab9e1d975f
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex c490465..ea59a2d 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -188,3 +188,15 @@ def make_workspace(session):return proj, user, kreturn _make++[email protected](autouse=True)+def purges(monkeypatch):+ """Every workspace-level delete hands its slow half to `tracely.purge_project` via+ `purge_service.schedule_purge`. Unstubbed, a test would reach for a real Redis broker. The+ list records `(project_id, before)` so tests can assert the hand-off itself."""+ from tracely.services import purge_service++ calls: list[tuple] = []+ monkeypatch.setattr(purge_service, "schedule_purge", lambda pid, before=None: calls.append((pid, before)))+ return callsdiff --git a/backend/tests/test_ch_maintenance.py b/backend/tests/test_ch_maintenance.pyindex 9850e03..a37b409 100644--- a/backend/tests/test_ch_maintenance.py+++ b/backend/tests/test_ch_maintenance.py@@ -119,3 +119,22 @@ def test_leaves_an_unrecognized_ttl_expression_alone(client):c = client([("query_log", 900)], [("query_log", "MergeTree TTL toDate(event_time) + 7", 1)])assert maintenance.cap_system_logs(3)["capped"] == []assert c.commands == []+++# ── nightly compaction ────────────────────────────────────────────────────────+++def test_compaction_rewrites_both_tables(monkeypatch):+ """A lightweight DELETE leaves rows on disk until a part is rewritten; nothing else rewrites+ the big parts, so without this a workspace wipe keeps every read slow indefinitely."""+ fake = FakeClient([], [])+ monkeypatch.setattr(maintenance, "get_client", lambda **_: fake)+ assert maintenance.compact_tables() == {"compacted": ["events", "scores"]}+ assert fake.commands == ["OPTIMIZE TABLE events FINAL", "OPTIMIZE TABLE scores FINAL"]+++def test_compaction_is_scheduled_nightly():+ from tracely.infrastructure.queue.celery_app import celery_app++ entry = celery_app.conf.beat_schedule["tracely.compact_tables-nightly"]+ assert entry["task"] == "tracely.compact_tables"diff --git a/backend/tests/test_ch_read_invariants.py b/backend/tests/test_ch_read_invariants.pyindex 0917ba7..ca01385 100644--- a/backend/tests/test_ch_read_invariants.py+++ b/backend/tests/test_ch_read_invariants.py@@ -157,10 +157,14 @@ def test_the_order_is_total():def _fn_body(path: Path, name: str) -> str:+ """The function's code with its docstring and comments removed — so a comment that merely+ *mentions* PREWHERE cannot satisfy a guard that the SQL dropped."""src = path.read_text()body = src[src.index(f"def {name}(") :]nxt = re.search(r"\n(?:async def |def | def )", body[1:])- return body[: nxt.start()] if nxt else body+ body = body[: nxt.start()] if nxt else body+ body = re.sub(r'"""[\s\S]*?"""', "", body, count=1)+ return "\n".join(line.split("#", 1)[0] for line in body.splitlines())def test_by_trace_span_reads_use_prewhere():@@ -174,6 +178,7 @@ def test_by_trace_span_reads_use_prewhere():("trace_reader.py", "member_meta"),("async_reader.py", "thread_spans_full"),("async_reader.py", "trace_spans"),+ ("deletes.py", "delete_trace"), # ran per evaluation; was a full scan without it):assert "PREWHERE" in _fn_body(_CH_DIR / filename, fn), f"{filename}:{fn} lost its PREWHERE"@@ -226,3 +231,13 @@ def test_is_deleted_is_never_pushed_into_prewhere():assert "is_deleted" not in q[pre : where if where > 0 else len(q)], (f"{f}:{line} filters is_deleted in PREWHERE — it must sit in WHERE")++++def test_the_threads_list_skips_internal_recordings_in_prewhere():+ """Eval recordings carry the judge prompt (the whole conversation) — the widest rows, and+ ~75% of them in prod. Filtering them in WHERE under FINAL decompressed every one of them on+ each page load of the threads list, which is what made it take seconds."""+ body = _fn_body(_CH_DIR / "async_reader.py", "sessions_overview")+ assert 'internal_prewhere = "" if include_internal else f"PREWHERE {_REAL} "' in body+ assert "FROM events FINAL {internal_prewhere}WHERE" in bodydiff --git a/backend/tests/test_data_delete.py b/backend/tests/test_data_delete.pyindex 5cafe36..81fce00 100644--- a/backend/tests/test_data_delete.py+++ b/backend/tests/test_data_delete.py@@ -72,22 +72,6 @@ def no_clickhouse(monkeypatch):return calls[email protected](autouse=True)-def no_blobs(monkeypatch):- """Stub object storage. Autouse: without it the wipe reaches for a real bucket, and- `_delete_prefix` swallows the failure — so the leak this pins would come back green."""- import tracely.api.routers.admin as admin_router-- calls: list[tuple[str, bool]] = []-- def fake(project_id: str, *, traces_only: bool = False) -> int:- calls.append((project_id, traces_only))- return 42-- monkeypatch.setattr(admin_router.s3, "delete_project_blobs", fake)- return calls--async def _owner(client) -> tuple[str, str]:r = await client.post("/auth/register", json={"email": "[email protected]", "password": "hunter2-pw"})assert r.status_code == 200, r.text@@ -294,12 +278,16 @@ async def test_wipe_is_project_scoped_and_idempotent(client, sync_db, no_clickhoassert s.get(models.EvaluationCase, other) is not None # another project is untouched-async def test_wipe_deletes_the_raw_otlp_bodies(client, sync_db, no_clickhouse, no_blobs):+async def test_wipe_queues_the_purge_of_the_raw_otlp_bodies(client, sync_db, no_clickhouse, purges):"""The bug this pins: the wipe used to clear ClickHouse and Postgres and leave every raw OTLP- body in the bucket — gigabytes of the customer's payloads, unreachable by anything in the- product, on an endpoint whose docstring promises to delete their data."""+ body in the bucket. Then it ran the purge inline — 197 s just to list one workspace's bodies,+ killed by a deploy, 2 GB left behind. Now it hands the purge to the worker, with the moment+ the button was pressed as the cutoff so bodies that arrive afterwards survive."""+ from datetime import datetime, timezone+tok, project_id = await _owner(client)_seed_case(sync_db, project_id)+ t0 = datetime.now(timezone.utc)r = await client.request("DELETE",@@ -308,15 +296,16 @@ async def test_wipe_deletes_the_raw_otlp_bodies(client, sync_db, no_clickhouse,json={"confirm": "DELETE"},)assert r.status_code == 200, r.text- # traces_only: the OTLP bodies and the deleted cases' fixtures, not the chat attachments- assert no_blobs == [(project_id, True)]- assert r.json()["deleted"]["blobs"] == 42+ assert r.json()["purge"] == "queued"+ [(pid, before)] = purges+ assert pid == project_id+ assert before is not None and t0 <= before <= datetime.now(timezone.utc)-async def test_wipe_refused_before_anything_is_deleted(client, sync_db, no_clickhouse, no_blobs):+async def test_wipe_refused_before_anything_is_deleted(client, sync_db, no_clickhouse, purges):tok, _ = await _owner(client)r = await client.request("DELETE", "/api/project/data", headers={"Authorization": f"Bearer {tok}"}, json={})assert r.status_code == 400- assert no_blobs == [] # the confirm guard covers the blobs too+ assert purges == [] # the confirm guard covers the purge toodiff --git a/backend/tests/test_eval_prompt.py b/backend/tests/test_eval_prompt.pyindex e4c1251..f689430 100644--- a/backend/tests/test_eval_prompt.py+++ b/backend/tests/test_eval_prompt.py@@ -97,6 +97,10 @@ def test_delete_trace_scopes_to_the_recorded_groups(monkeypatch):deletes.delete_trace("p1", "t1", ["on_topic"])sql, params = read[-1]assert "step_name IN" in sql and params["n"] == ["on_topic"]+ # trace_id narrows before FINAL; step_name must not (a tombstone does not carry it)+ prewhere, where = sql.split("PREWHERE", 1)[1].split(" WHERE ", 1)+ assert "trace_id = {t:String}" in prewhere and "step_name" not in prewhere+ assert "step_name" in where and "is_deleted = 0" in whereread.clear()deletes.delete_trace("p1", "t1") # no groups → the old whole-trace replacediff --git a/backend/tests/test_purge_service.py b/backend/tests/test_purge_service.pynew file mode 100644index 0000000..6fbaa78--- /dev/null+++ b/backend/tests/test_purge_service.py@@ -0,0 +1,239 @@+"""Making "deleted" mean deleted: the background purge behind every workspace-level delete, and+the nightly sweep for data whose workspace is gone.++Both delete customer data with nobody watching, so the tests that matter most are the refusals:+the sweep must never act on a registry read that looks wrong, and a wipe's purge must never take+data that arrived after the button was pressed.+"""++from __future__ import annotations++from datetime import datetime, timedelta, timezone++import pytest++from tracely.infrastructure.blob import s3+from tracely.services import purge_service++# Bound at collection, before conftest's autouse `purges` stubs it for every test.+REAL_SCHEDULE_PURGE = purge_service.schedule_purge++NOW = datetime(2026, 10, 3, 12, 0, tzinfo=timezone.utc)+++# ── object storage ────────────────────────────────────────────────────────────+++class FakeBucket:+ """list_objects_v2 (flat or delimited) + delete_objects over an in-memory key -> mtime map."""++ def __init__(self, objects: dict[str, datetime], errors: list | None = None):+ self.objects = dict(objects)+ self.errors = errors++ def get_paginator(self, _name):+ bucket = self++ class P:+ def paginate(self, Bucket, Prefix, Delimiter=None):+ keys = sorted(k for k in bucket.objects if k.startswith(Prefix))+ if Delimiter:+ tops = sorted({Prefix + k[len(Prefix):].split(Delimiter)[0] + Delimiter+ for k in keys if Delimiter in k[len(Prefix):]})+ yield {"CommonPrefixes": [{"Prefix": t} for t in tops]}+ else:+ yield {"Contents": [{"Key": k, "LastModified": bucket.objects[k]} for k in keys]}++ return P()++ def delete_objects(self, Bucket, Delete):+ if self.errors:+ return {"Errors": self.errors}+ for o in Delete["Objects"]:+ self.objects.pop(o["Key"])+ return {"Deleted": Delete["Objects"]}+++def bucket(monkeypatch):+ def install(objects, errors=None):+ b = FakeBucket(objects, errors)+ monkeypatch.setattr(s3, "_s3", lambda: b)+ return b++ return install+++def test_a_wipe_only_takes_what_existed_when_the_button_was_pressed(bucket):+ """The purge is queued, so a busy workspace keeps ingesting while it waits. Those new bodies+ are new data — taking them would silently lose the first traces after a wipe."""+ old, new = NOW - timedelta(hours=1), NOW + timedelta(seconds=5)+ b = bucket({+ "events/p1/otlp/a.json": old,+ "events/p1/otlp/b.json": new,+ "events/fixtures/p1/f.json": old,+ "events/p1/assistant/chat.png": old, # not a trace: a wipe keeps attachments+ "events/p2/otlp/z.json": old, # someone else's+ })+ assert s3.delete_project_blobs("p1", traces_only=True, before=NOW) == 2+ assert set(b.objects) == {+ "events/p1/otlp/b.json", "events/p1/assistant/chat.png", "events/p2/otlp/z.json"+ }+++def test_a_workspace_delete_takes_everything_of_that_workspace_only(bucket):+ b = bucket({+ "events/p1/otlp/a.json": NOW,+ "events/p1/assistant/chat.png": NOW,+ "events/cases/p1/c.json": NOW,+ "events/p2/otlp/z.json": NOW,+ })+ assert s3.delete_project_blobs("p1") == 3+ assert set(b.objects) == {"events/p2/otlp/z.json"}+++def test_a_failed_delete_is_loud_so_the_task_retries(bucket):+ """`delete_objects` reports per-key failures in its response without raising. The old purge+ returned 0 and moved on — that is how 2 GB stayed in the bucket with nothing logged."""+ bucket({"events/p1/otlp/a.json": NOW}, errors=[{"Key": "events/p1/otlp/a.json", "Code": "X"}])+ with pytest.raises(RuntimeError, match="delete_objects"):+ s3.delete_project_blobs("p1")+++def test_storage_lists_project_ids_at_all_three_depths(bucket):+ bucket({+ "events/p1/otlp/a.json": NOW,+ "events/fixtures/p2/f.json": NOW,+ "events/cases/p3/c.json": NOW,+ })+ # `fixtures` and `cases` are directories of projects, not projects+ assert s3.project_ids_in_storage() == {"p1", "p2", "p3"}+++# ── the queued purge ──────────────────────────────────────────────────────────+++def test_purge_project_takes_the_blobs_then_the_masked_rows(monkeypatch):+ calls = []+ monkeypatch.setattr(s3, "delete_project_blobs",+ lambda pid, traces_only, before: calls.append(("blobs", pid, traces_only, before)) or 7)+ monkeypatch.setattr(purge_service.maintenance, "compact_tables", lambda: calls.append(("compact",)))++ assert purge_service.purge_project("p1", NOW.isoformat()) == {"project_id": "p1", "blobs": 7}+ assert calls == [("blobs", "p1", True, NOW), ("compact",)]++ calls.clear()+ purge_service.purge_project("p1", None) # workspace delete: everything+ assert calls[0] == ("blobs", "p1", False, None)+++def test_schedule_purge_hands_the_cutoff_to_the_worker_by_name(monkeypatch):+ """By task name and as an ISO string: the API never imports the worker module, and a+ datetime does not survive the JSON serializer."""+ sent = []+ monkeypatch.setattr(purge_service.celery_app, "send_task", lambda name, args: sent.append((name, args)))+ REAL_SCHEDULE_PURGE("p1", NOW)+ REAL_SCHEDULE_PURGE("p2")+ assert sent == [("tracely.purge_project", ["p1", NOW.isoformat()]),+ ("tracely.purge_project", ["p2", None])]+++def test_both_sweeps_are_scheduled_nightly():+ from tracely.infrastructure.queue.celery_app import celery_app++ beat = celery_app.conf.beat_schedule+ assert beat["tracely.purge_orphans-nightly"]["task"] == "tracely.purge_orphans"+ assert beat["tracely.compact_tables-nightly"]["task"] == "tracely.compact_tables"+++# ── the nightly orphan sweep ──────────────────────────────────────────────────+++def world(monkeypatch):+ """Storage, ClickHouse and the registry as plain data, plus a log of what the sweep did —+ in order, because reading the registry LAST is part of the contract."""+ log: list = []++ def install(*, storage, last_write, registry):+ def read_storage():+ log.append("read storage")+ return set(storage)++ def read_ch():+ log.append("read clickhouse")+ return dict(last_write)++ class Session:+ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ def plans(_s):+ log.append("read registry")+ return [(pid, "free") for pid in registry]++ monkeypatch.setattr(s3, "project_ids_in_storage", read_storage)+ monkeypatch.setattr(purge_service.deletes, "last_write_by_project", read_ch)+ monkeypatch.setattr(purge_service, "SyncSessionLocal", Session)+ monkeypatch.setattr(purge_service, "project_plans", plans)+ monkeypatch.setattr(purge_service.deletes, "delete_project_rows", lambda p: log.append(("rows", p)))+ monkeypatch.setattr(s3, "delete_project_blobs", lambda p: log.append(("blobs", p)) or 1)+ monkeypatch.setattr(purge_service.checkpointer, "delete_project_chats", lambda p: 0)+ monkeypatch.setattr(purge_service.maintenance, "compact_tables", lambda: log.append("compact"))+ return log++ return install+++def test_sweep_purges_only_workspaces_missing_from_the_registry(world):+ old = NOW - timedelta(days=30)+ log = world(+ storage={"live", "gone_both", "gone_bucket_only"},+ last_write={"live": NOW, "gone_both": old},+ registry={"live"},+ )+ out = purge_service.purge_orphans(now=NOW)+ assert out["purged"] == ["gone_both", "gone_bucket_only"]+ assert ("rows", "gone_both") in log and ("blobs", "gone_both") in log+ assert ("blobs", "gone_bucket_only") in log and ("rows", "gone_bucket_only") not in log+ assert not any(isinstance(e, tuple) and e[1] == "live" for e in log)+ assert log[-1] == "compact"+++def test_sweep_reads_the_registry_last(world):+ """A workspace must exist in Postgres before it can write. Read the data first and anything+ still missing from the registry afterwards really was deleted; read the registry first and a+ workspace created in between loses its first traces."""+ log = world(storage={"a"}, last_write={}, registry={"a"})+ purge_service.purge_orphans(now=NOW)+ reads = [e for e in log if isinstance(e, str) and e.startswith("read")]+ assert reads[-1] == "read registry"+++def test_sweep_refuses_on_an_empty_registry(world):+ """Pointed at the wrong / an empty database, every workspace looks deleted."""+ log = world(storage={"a", "b"}, last_write={"a": NOW - timedelta(days=30)}, registry=set())+ assert purge_service.purge_orphans(now=NOW) == {"refused": "empty registry"}+ assert not any(isinstance(e, tuple) for e in log)+++def test_sweep_refuses_when_a_would_be_orphan_wrote_recently(world):+ """A deleted workspace cannot write. If one did, the registry read is wrong — and the sweep+ deletes NOTHING, not just that one: the other "orphans" came from the same bad read."""+ log = world(+ storage={"live", "ancient"},+ last_write={"live": NOW - timedelta(hours=2), "ancient": NOW - timedelta(days=60)},+ registry={"someone_else"},+ )+ out = purge_service.purge_orphans(now=NOW)+ assert out == {"refused": "recent writes", "projects": ["live"]}+ assert not any(isinstance(e, tuple) for e in log)+++def test_sweep_handles_naive_clickhouse_timestamps(world):+ """ClickHouse hands back naive UTC; comparing one with an aware `now` raises."""+ world(storage=set(), last_write={"gone": (NOW - timedelta(days=30)).replace(tzinfo=None)}, registry={"x"})+ assert purge_service.purge_orphans(now=NOW)["purged"] == ["gone"]diff --git a/backend/tests/test_workspace_delete.py b/backend/tests/test_workspace_delete.pyindex 83d9019..5b38772 100644--- a/backend/tests/test_workspace_delete.py+++ b/backend/tests/test_workspace_delete.py@@ -59,7 +59,6 @@ def _stores(tmp_path, monkeypatch, engine):return {"events": 0}monkeypatch.setattr(admin.deletes, "delete_project_events", _no_events)- monkeypatch.setattr(admin.s3, "delete_project_blobs", lambda project_id: 0)yieldsync_eng.dispose()@@ -86,7 +85,7 @@ async def _second_workspace(session, project, slug="second") -> str:return sib.id-async def test_admin_deletes_the_active_workspace(client, make_workspace, session):+async def test_admin_deletes_the_active_workspace(client, make_workspace, session, purges):proj, _user, _key = await make_workspace("acme", "tk_acme", "[email protected]")sib_id = await _second_workspace(session, proj)proj_id = proj.id@@ -100,6 +99,8 @@ async def test_admin_deletes_the_active_workspace(client, make_workspace, sessio)assert r.status_code == 200, r.textassert r.json()["switch_to"] == sib_id # the caller's cookie must move here+ # every blob of it (attachments too) — no cutoff, the workspace is gone — in the background+ assert purges == [(proj_id, None)]session.expire_all()assert await session.get(models.Project, proj_id) is Nonediff --git a/backend/tracely/api/routers/admin.py b/backend/tracely/api/routers/admin.pyindex b46b074..2f46c0d 100644--- a/backend/tracely/api/routers/admin.py+++ b/backend/tracely/api/routers/admin.py@@ -8,6 +8,7 @@ Pure HTTP shaping — ClickHouse deletes live in `infrastructure.clickhouse.delefrom __future__ import annotationsimport json+from datetime import datetime, timezoneimport structlogfrom fastapi import APIRouter, Depends, HTTPException@@ -18,12 +19,11 @@ 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.blob import s3from tracely.infrastructure.clickhouse import async_reader, deletesfrom tracely.infrastructure.db import repositories as repofrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.llm import checkpointer, provider-from tracely.services import demo_seed+from tracely.services import demo_seed, purge_servicelog = structlog.get_logger()@@ -49,18 +49,18 @@ async def wipe_project_data(body: WipeBody, project_id: str = Depends(get_projecwhile leaving every byte on disk, and nothing left in the product could ever reach them again.Chat attachments stay: they are not traces (a workspace delete takes those).- Not transactional across the stores: ClickHouse goes first, then Postgres, then the blobs. If the Postgres- half fails you're left with derived rows pointing at deleted traces — run it again, it's- idempotent.+ Inline: mask the ClickHouse rows, then Postgres — the fast part, so the UI is empty on the next+ fetch. Queued (`purge_service.schedule_purge`): the blobs and the rewrite that takes the masked+ rows off disk. Those used to run here and took longer than any request lives — MinIO needed+ 197 s just to list one workspace's bodies — so a deploy killed the wipe half-way and the bucket+ kept 2 GB. Only bodies written before this request go: anything ingested while the purge is+ queued is new data. Idempotent — run it again if the Postgres half fails."""if body.confirm != CONFIRM:raise HTTPException(status_code=400, detail=f"confirm must be exactly '{CONFIRM}'")+ pressed_at = datetime.now(timezone.utc)events = await deletes.delete_project_events(project_id)- # The raw OTLP bodies. Without this the ClickHouse rows go and every byte the customer sent- # stays in the bucket for ever — the wipe looks complete in the UI while the payloads it- # promised to delete are all still there, unreachable by anything that could clean them up.- blobs = await run_in_threadpool(s3.delete_project_blobs, project_id, traces_only=True)def work():with SyncSessionLocal() as s:@@ -72,13 +72,16 @@ async def wipe_project_data(body: WipeBody, project_id: str = Depends(get_projec# just removed the chain-progress rows they pair with — leaving them would keep a copy of the# very data this endpoint promises to delete.chats = await run_in_threadpool(checkpointer.delete_project_chats, project_id)+ # The raw OTLP bodies + the masked rows' disk. Without this the UI empties while every byte+ # the customer sent stays in the bucket — see the docstring for why it is not inline.+ await run_in_threadpool(purge_service.schedule_purge, project_id, pressed_at)return {"deleted": {**events,**registry,- **({"blobs": blobs} if blobs else {}),**({"judge_chats": chats} if chats else {}),- }+ },+ "purge": "queued",}@@ -146,7 +149,9 @@ async def delete_workspace(return repo.project_delete(s, project_id, usage_heir_id=siblings[0])deleted = await run_in_threadpool(work)- deleted["blobs"] = await run_in_threadpool(s3.delete_project_blobs, project_id)+ # Every blob (attachments too) + the masked rows' disk, in the background — inline, a large+ # workspace's purge outlives the request. The nightly orphan sweep backstops it.+ await run_in_threadpool(purge_service.schedule_purge, project_id, None)# A deleted workspace never grades again, so nothing would ever reset these conversations —# without this they would sit until the 90-day retention sweep reached them.if chats := await run_in_threadpool(checkpointer.delete_project_chats, project_id):diff --git a/backend/tracely/api/routers/auth.py b/backend/tracely/api/routers/auth.pyindex 60fc0ab..45ce2b0 100644--- a/backend/tracely/api/routers/auth.py+++ b/backend/tracely/api/routers/auth.py@@ -37,11 +37,11 @@ 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.blob import s3from tracely.infrastructure.clickhouse import deletesfrom tracely.infrastructure.db import repositoriesfrom tracely.infrastructure.db.engine import SyncSessionLocalfrom tracely.infrastructure.db.session import get_session+from tracely.services import purge_servicelog = structlog.get_logger()@@ -221,7 +221,9 @@ async def delete_organization(repositories.project_delete(s, pid, usage_heir_id=None)await run_in_threadpool(drop)- await run_in_threadpool(s3.delete_project_blobs, pid)+ # Blobs + masked rows in the background: inline, one big workspace's bucket purge+ # outlived the request and was killed half-way. The nightly orphan sweep backstops it.+ await run_in_threadpool(purge_service.schedule_purge, pid, None)def finish() -> dict:with SyncSessionLocal() as s:diff --git a/backend/tracely/infrastructure/blob/s3.py b/backend/tracely/infrastructure/blob/s3.pyindex 1f5885a..5436624 100644--- a/backend/tracely/infrastructure/blob/s3.py+++ b/backend/tracely/infrastructure/blob/s3.py@@ -5,6 +5,8 @@ nothing is queued unless the blob is durable). The worker reads it back.from __future__ import annotations+from datetime import datetime+import boto3import structlogfrom botocore.config import Config@@ -73,30 +75,60 @@ def get_blob_typed(key: str) -> tuple[bytes, str]:return obj["Body"].read(), obj.get("ContentType") or "application/octet-stream"-def _delete_prefix(prefix: str) -> int:- """Delete every object under one key prefix. Returns how many went.+def _delete_prefix(prefix: str, before: datetime | None = None) -> int:+ """Delete every object under one key prefix — only those written before `before`, when given.+ Returns how many went.++ RAISES on failure, including the per-key `Errors` a `delete_objects` call reports without+ raising. This used to swallow everything and return 0, and run inside the HTTP request: on a+ workspace with 108k bodies, MinIO alone took 197 s to *list* the prefix, the request outlived+ the browser, a deploy killed it, and 2 GB stayed in the bucket with nothing to say so. It now+ only runs in `tracely.purge_project`, which retries — so failing loudly is what makes it finish.- Best-effort: object storage being unavailable must not block the delete (the rows are already- gone), so failures are counted as zero rather than raised.+ `before` is what makes a background purge safe on a workspace that keeps ingesting: a wipe+ deletes the bodies that existed when the user pressed the button, never the ones that+ arrived while the purge was queued."""client = _s3()removed = 0- try:+ for page in client.get_paginator("list_objects_v2").paginate(+ Bucket=settings.s3_bucket, Prefix=prefix+ ):+ batch = [+ {"Key": o["Key"]}+ for o in page.get("Contents", [])+ if before is None or o["LastModified"] < before+ ]+ if not batch:+ continue+ # delete_objects caps at 1000 keys, which is exactly one page's default maximum.+ res = client.delete_objects(Bucket=settings.s3_bucket, Delete={"Objects": batch})+ if res.get("Errors"):+ raise RuntimeError(f"delete_objects under {prefix!r}: {res['Errors'][:3]}")+ removed += len(batch)+ return removed+++def project_ids_in_storage() -> set[str]:+ """Every project id that owns at least one object, at any of the three depths a project's+ keys live at. Delimiter listing — a handful of entries, not the objects themselves."""+ base = settings.s3_event_prefix+ client = _s3()+ found: set[str] = set()+ for sub in ("", "fixtures/", "cases/"):for page in client.get_paginator("list_objects_v2").paginate(- Bucket=settings.s3_bucket, Prefix=prefix+ Bucket=settings.s3_bucket, Prefix=f"{base}{sub}", Delimiter="/"):- batch = [{"Key": o["Key"]} for o in page.get("Contents", [])]- if not batch:- continue- # delete_objects caps at 1000 keys, which is exactly one page's default maximum.- client.delete_objects(Bucket=settings.s3_bucket, Delete={"Objects": batch})- removed += len(batch)- except Exception as exc:- log.warning("blob_prefix_delete_failed", prefix=prefix, error=str(exc))- return removed+ for cp in page.get("CommonPrefixes", []):+ name = cp["Prefix"][len(base) + len(sub) :].rstrip("/")+ if name and not (sub == "" and name in ("fixtures", "cases")):+ found.add(name)+ return found-def delete_project_blobs(project_id: str, *, traces_only: bool = False) -> int:+def delete_project_blobs(+ project_id: str, *, traces_only: bool = False, before: datetime | None = None+) -> int:"""Delete a project's blobs. Returns how many objects went.The blobs are the source of truth — the customer's payloads verbatim — so anything that@@ -115,8 +147,8 @@ def delete_project_blobs(project_id: str, *, traces_only: bool = False) -> int:base = settings.s3_event_prefixproject_prefix = f"{base}{project_id}/otlp/" if traces_only else f"{base}{project_id}/"return (- _delete_prefix(project_prefix)- + _delete_prefix(f"{base}fixtures/{project_id}/")+ _delete_prefix(project_prefix, before)+ + _delete_prefix(f"{base}fixtures/{project_id}/", before)# the durable case artifacts (`domain/regression/artifact.py`) — deleted with the cases- + _delete_prefix(f"{base}cases/{project_id}/")+ + _delete_prefix(f"{base}cases/{project_id}/", before))diff --git a/backend/tracely/infrastructure/clickhouse/async_reader.py b/backend/tracely/infrastructure/clickhouse/async_reader.pyindex bb79497..4c94611 100644--- a/backend/tracely/infrastructure/clickhouse/async_reader.py+++ b/backend/tracely/infrastructure/clickhouse/async_reader.py@@ -536,6 +536,11 @@ async def sessions_overview(order_clause = session_order_clause(sort, order)time_clause = ""internal_clause = "" if include_internal else f" AND {_REAL}"+ # PREWHERE, so an eval recording's judge prompt — which embeds the whole conversation, making+ # these the widest rows in the table, ~75% of them in prod — is never decompressed just to be+ # dropped. Safe under FINAL only because `internal_kind` is identical across every version of+ # a row (a tombstone copies it); `is_deleted` is NOT, which is why it stays in WHERE.+ internal_prewhere = "" if include_internal else f"PREWHERE {_REAL} "params: dict = {"p": project_id, "n": max(limit, 0), "o": max(offset, 0), "adv": list(advisory)}if from_ts:time_clause += " AND start_time >= parseDateTimeBestEffort({from:String})"@@ -607,7 +612,7 @@ async def sessions_overview((groupArrayArray(mapKeys(mapFilter((k, v) -> startsWith(k, 'tracely.metadata.'), CAST(metadata, 'Map(String, String)')))),groupArrayArray(mapValues(mapFilter((k, v) -> startsWith(k, 'tracely.metadata.'), CAST(metadata, 'Map(String, String)'))))),'Map(String, String)') AS t_meta{q_inner}- FROM events FINAL WHERE project_id = {{p:String}} AND is_deleted = 0{time_clause}{internal_clause}+ FROM events FINAL {internal_prewhere}WHERE project_id = {{p:String}} AND is_deleted = 0{time_clause}GROUP BY trace_id{agent_clause})diff --git a/backend/tracely/infrastructure/clickhouse/deletes.py b/backend/tracely/infrastructure/clickhouse/deletes.pyindex 1bc2138..5f47c87 100644--- a/backend/tracely/infrastructure/clickhouse/deletes.py+++ b/backend/tracely/infrastructure/clickhouse/deletes.py@@ -1,12 +1,19 @@"""ClickHouse deletes for the API — the write twin of `async_reader` (same rule: no SQL in routers).Conversation deletion and the whole-project wipe live here. Uses lightweight `DELETE FROM` (GA-since CH 23.3): rows are masked from every read immediately and dropped on the next merge, so the-UI reflects a delete on the next fetch without waiting for a mutation.+since CH 23.3): rows are masked from every read immediately, so the UI reflects a delete on the+next fetch without waiting for a mutation.++Masked is not gone. The rows stay on disk until their part is rewritten, and a big part is never+merged again on its own — after one workspace wipe prod held 733,788 physical rows behind 1,083+visible ones, and every query read all of them. `services/purge_service` (right after a wipe) and+`maintenance.compact_tables` (nightly) are what actually remove them."""from __future__ import annotations+from datetime import datetime+from tracely.infrastructure.clickhouse.client import get_async_client, get_client, insert_rowsfrom tracely.infrastructure.clickhouse.events_schema import EVENT_COLUMNS, to_rows@@ -42,12 +49,15 @@ def delete_trace(project_id: str, trace_id: str, step_names: list[str] | None ="""client = get_client()params = {"p": project_id, "t": trace_id, "n": step_names or []}- where = "project_id = {p:String} AND trace_id = {t:String}" + (+ where = "project_id = {p:String}" + (" AND (step_name IN {n:Array(String)} OR step_name = '')" if step_names else "")+ # trace_id in PREWHERE (identical across a row's versions, so safe under FINAL) — without it+ # this read scanned the whole table on every evaluation. step_name stays in WHERE: a+ # tombstone does not carry it, so filtering on it before FINAL would split a row's versions.doomed = client.query(f"SELECT span_id, start_time, internal_kind FROM events FINAL "- f"WHERE {where} AND is_deleted = 0",+ f"PREWHERE trace_id = {{t:String}} WHERE {where} AND is_deleted = 0",parameters=params,).result_rowsif not doomed:@@ -161,3 +171,31 @@ def delete_expired(project_ids: list[str], days: int) -> int:parameters=params,)return spans+++def delete_project_rows(project_id: str) -> None:+ """Mask every span and score of one project — the worker's twin of `delete_project_events`,+ for the orphan sweep. Masking only; `maintenance.compact_tables` is what takes them off disk.+ No count first: the sweep only calls this for a project it already found rows or blobs for."""+ client = get_client()+ for table in ("events", "scores"):+ client.command(+ f"DELETE FROM {table} WHERE project_id = {{p:String}}", parameters={"p": project_id}+ )+++def last_write_by_project() -> dict[str, datetime]:+ """`{project_id: newest event_ts}` across `events` and `scores` — the orphan sweep's guard.++ A deleted workspace cannot receive data (its keys go with it), so a "deleted" project that+ wrote yesterday means the registry read was wrong, and the sweep must stop rather than act.+ Masked rows are invisible here, which is the point: a workspace delete masks its rows before+ the sweep ever sees it."""+ client = get_client()+ out: dict[str, datetime] = {}+ for table in ("events", "scores"):+ for pid, ts in client.query(+ f"SELECT project_id, max(event_ts) FROM {table} GROUP BY project_id"+ ).result_rows:+ out[pid] = max(ts, out[pid]) if pid in out else ts+ return outdiff --git a/backend/tracely/infrastructure/clickhouse/maintenance.py b/backend/tracely/infrastructure/clickhouse/maintenance.pyindex fe70ddf..7fcf7e3 100644--- a/backend/tracely/infrastructure/clickhouse/maintenance.py+++ b/backend/tracely/infrastructure/clickhouse/maintenance.py@@ -112,3 +112,31 @@ def cap_system_logs(days: int | None = None) -> dict:if capped:log.info("system_logs_capped", tables=capped, days=days, bytes_under_ttl=freed)return {"capped": capped, "skipped": skipped, "bytes": freed, "days": days}+++def compact_tables() -> dict:+ """`OPTIMIZE TABLE … FINAL` on `events` and `scores` (beat, nightly).++ Nothing else ever rewrites the big parts, and two kinds of dead rows only leave a table when+ a part is rewritten:++ - **Lightweight-deleted rows.** `DELETE FROM` (a workspace wipe, thread delete, retention)+ only *masks* rows; they stay on disk and every query still reads them. Prod after one wipe:+ 733,788 physical rows behind 1,083 visible ones, every read paying for all of them.+ - **Superseded eval recordings.** `deletes.delete_trace` tombstones the previous recording+ instead of mutating; `ReplacingMergeTree` only collapses a span with its tombstone when the+ two land in the same merge.++ Measured on prod: 406 MiB -> 202 KiB in 2 s, visible rows unchanged — FINAL reads already+ see the collapsed, unmasked view, this just makes the disk agree with it.++ ponytail: whole-table rewrite. Fine at hundreds of MiB; once `events` is in the GiBs, switch+ to `OPTIMIZE … PARTITION <id> FINAL` for partitions whose parts carry a delete mask.+ """+ client = get_client()+ done = []+ for table in ("events", "scores"):+ client.command(f"OPTIMIZE TABLE {table} FINAL")+ done.append(table)+ log.info("tables_compacted", tables=done)+ return {"compacted": done}diff --git a/backend/tracely/infrastructure/queue/celery_app.py b/backend/tracely/infrastructure/queue/celery_app.pyindex 767c84f..691c267 100644--- a/backend/tracely/infrastructure/queue/celery_app.py+++ b/backend/tracely/infrastructure/queue/celery_app.py@@ -64,6 +64,19 @@ celery_app.conf.update("task": "tracely.cap_system_logs","schedule": crontab(hour="5", minute="7"),},+ # A lightweight DELETE only masks rows and a tombstoned eval recording only collapses in a+ # merge — neither leaves the disk until a part is rewritten, and every read pays for them+ # until then. After the system-log sweep so the solo worker takes one at a time.+ "tracely.compact_tables-nightly": {+ "task": "tracely.compact_tables",+ "schedule": crontab(hour="5", minute="27"),+ },+ # Data whose workspace no longer exists (a delete whose purge never finished, or one from+ # before purges existed). Refuses on any sign the registry read is wrong.+ "tracely.purge_orphans-nightly": {+ "task": "tracely.purge_orphans",+ "schedule": crontab(hour="5", minute="47"),+ },},timezone="UTC",)diff --git a/backend/tracely/services/purge_service.py b/backend/tracely/services/purge_service.pynew file mode 100644index 0000000..a83fba8--- /dev/null+++ b/backend/tracely/services/purge_service.py@@ -0,0 +1,102 @@+"""Making "deleted" mean deleted — the background half of every workspace-level delete.++The routes (Data → wipe, workspace delete, organization delete) do the fast part inline: mask the+ClickHouse rows and drop the registry rows, so the UI is empty on the next fetch. What they must+NOT do inline is the rest, because it is slow and was silently not happening:++- **Object storage.** The raw OTLP bodies are the customer's payloads verbatim. MinIO took 197 s+ just to *list* one workspace's 108k bodies; inside the request that outlived the browser, a+ deploy killed it, and 2 GB stayed in the bucket while the UI said "deleted".+- **ClickHouse disk.** A lightweight DELETE only masks; every query keeps reading masked rows+ until their part is rewritten, which for a big part is never.++So `schedule_purge` hands both to `tracely.purge_project` — acks-late, retried with backoff, so a+deploy or a MinIO hiccup delays it instead of losing it. And `purge_orphans` (nightly) is the+backstop for anything that still slips through: data in ClickHouse or the bucket whose workspace+no longer exists in Postgres.+"""++from __future__ import annotations++from datetime import datetime, timedelta, timezone++import structlog++from tracely.infrastructure.blob import s3+from tracely.infrastructure.clickhouse import deletes, maintenance+from tracely.infrastructure.db.engine import SyncSessionLocal+from tracely.infrastructure.db.repositories import project_plans+from tracely.infrastructure.llm import checkpointer+from tracely.infrastructure.queue.celery_app import celery_app++log = structlog.get_logger()++# A deleted workspace cannot write (its keys are gone). Recent writes from a "deleted" project+# therefore mean the registry read is wrong — the sweep refuses rather than act on it.+ORPHAN_QUIET_DAYS = 7+++def schedule_purge(project_id: str, before: datetime | None = None) -> None:+ """Queue the physical purge of one workspace's deleted data.++ `before`: only objects written before it go — a wipe keeps whatever arrives after the+ button was pressed. None (workspace / organization delete) takes everything, attachments+ included. By task name, so the API never imports the worker module."""+ celery_app.send_task(+ "tracely.purge_project", args=[project_id, before.isoformat() if before else None]+ )+++def purge_project(project_id: str, before: str | None) -> dict:+ """Delete the workspace's blobs, then rewrite ClickHouse so the masked rows leave the disk.+ Idempotent — a retry re-lists what is left and finishes the job."""+ cutoff = datetime.fromisoformat(before) if before else None+ blobs = s3.delete_project_blobs(project_id, traces_only=cutoff is not None, before=cutoff)+ maintenance.compact_tables()+ log.info("project_purged", project_id=project_id, blobs=blobs, before=before)+ return {"project_id": project_id, "blobs": blobs}+++def purge_orphans(now: datetime | None = None) -> dict:+ """Remove ClickHouse rows and objects whose workspace no longer exists (beat, nightly).++ Order matters: storage and ClickHouse are read FIRST, the registry LAST. A workspace has to+ exist in Postgres before it can write anything, so anything still missing from the registry+ after we have seen its data was deleted — never "just created". Read the other way round, a+ workspace created between the two reads would look orphaned and lose its first traces.++ Refuses, and deletes nothing, when the registry comes back empty or a would-be orphan wrote+ within ORPHAN_QUIET_DAYS: both mean we are looking at the wrong database, and this is the+ one job that deletes across every workspace at once."""+ now = now or datetime.now(timezone.utc)+ in_storage = s3.project_ids_in_storage()+ last_write = deletes.last_write_by_project()+ with SyncSessionLocal() as s:+ live = {pid for pid, _ in project_plans(s)}++ if not live:+ log.error("orphan_sweep_refused", reason="registry returned no workspaces")+ return {"refused": "empty registry"}++ orphans = sorted((in_storage | set(last_write)) - live)+ quiet_since = now - timedelta(days=ORPHAN_QUIET_DAYS)+ noisy = [p for p in orphans if p in last_write and _aware(last_write[p]) > quiet_since]+ if noisy:+ log.error("orphan_sweep_refused", reason="recent writes", projects=noisy)+ return {"refused": "recent writes", "projects": noisy}++ blobs = 0+ for pid in orphans:+ if pid in last_write:+ deletes.delete_project_rows(pid)+ blobs += s3.delete_project_blobs(pid)+ checkpointer.delete_project_chats(pid)+ if orphans:+ maintenance.compact_tables()+ log.info("orphans_purged", projects=orphans, blobs=blobs)+ return {"purged": orphans, "blobs": blobs}+++def _aware(ts: datetime) -> datetime:+ """ClickHouse hands back naive UTC datetimes."""+ return ts if ts.tzinfo else ts.replace(tzinfo=timezone.utc)diff --git a/backend/tracely/workers/tasks.py b/backend/tracely/workers/tasks.pyindex 5a6c067..07a2bbf 100644--- a/backend/tracely/workers/tasks.py+++ b/backend/tracely/workers/tasks.py@@ -336,6 +336,50 @@ def cap_system_logs_task(self) -> dict:return {"error": str(exc)}+@celery_app.task(+ name="tracely.purge_project",+ bind=True,+ autoretry_for=(Exception,),+ retry_backoff=60,+ retry_backoff_max=3600,+ max_retries=10,+)+def purge_project_task(self, project_id: str, before: str | None = None) -> dict:+ """Physically remove a wiped / deleted workspace's data — its blobs and its masked+ ClickHouse rows (`services/purge_service`). Retried with backoff and acks-late, because the+ whole point is that it finishes: the version that ran inside the HTTP request was killed by a+ deploy and left 2 GB in the bucket. Idempotent, so a retry just finishes the job."""+ from tracely.services.purge_service import purge_project++ return purge_project(project_id, before)+++@celery_app.task(name="tracely.purge_orphans", bind=True, max_retries=0)+def purge_orphans_task(self) -> dict:+ """Nightly backstop: ClickHouse rows and objects whose workspace no longer exists. Refuses+ (deletes nothing) when the registry read looks wrong — see `purge_service.purge_orphans`."""+ from tracely.services.purge_service import purge_orphans++ try:+ return purge_orphans()+ except Exception as exc: # noqa: BLE001 — tomorrow's run retries; this one deletes nothing more+ log.warning("purge_orphans_failed", error=str(exc))+ return {"error": str(exc)}+++@celery_app.task(name="tracely.compact_tables", bind=True, max_retries=0)+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.clickhouse.maintenance import compact_tables++ try:+ return compact_tables()+ except Exception as exc: # noqa: BLE001 — a missed compaction costs speed, never a grade+ log.warning("compact_tables_failed", error=str(exc))+ return {"error": str(exc)}++@celery_app.task(name="tracely.selfcheck", bind=True, max_retries=0)def selfcheck_task(self) -> dict:"""Watch our own deployment (beat, every 5 min). Tracely's failure modes are quiet — a dead