Run child tables cascade from run.id

Migration ccb21eacf5d5 deletes rows whose run is gone, then adds foreign keys
with ON DELETE CASCADE from run_node, run_metric and run_artifact to run.id.
Deleting runs is now the one statement. A node or metric written after its
run was deleted is dropped with an info line. Migrations run with foreign keys
off, since a batch rebuild of run would otherwise cascade into every child row.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WgBfkm4rCmtd1T4vHWjEPx
This commit is contained in:
2026-10-15 10:32:33 +02:00
co-authored by Claude Opus 5.5
parent ffa044724b
commit b4d7ffb982
6 changed files with 104 additions and 25 deletions
@@ -0,0 +1,38 @@
"""run_node, run_metric, run_artifact → run.id
A foreign key from each run child table to its run, cascading on delete, so
deleting a run takes its rows with it and nothing can write one for a run that
is not there.
Revision ID: ccb21eacf5d5
Revises: 2e7ca7d10044
Create Date: 2026-10-15
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "ccb21eacf5d5"
down_revision = "2e7ca7d10044"
branch_labels = None
depends_on = None
TABLES = ("run_node", "run_metric", "run_artifact")
def upgrade():
for table in TABLES:
# Rows a late write left behind after their run was deleted. Nothing
# reads them, and the constraint would refuse them.
op.execute(f"DELETE FROM {table} WHERE run_id NOT IN (SELECT id FROM run)")
with op.batch_alter_table(table) as batch_op:
batch_op.create_foreign_key(
f"fk_{table}_run_id_run", "run", ["run_id"], ["id"], ondelete="CASCADE"
)
def downgrade():
for table in TABLES:
with op.batch_alter_table(table) as batch_op:
batch_op.drop_constraint(f"fk_{table}_run_id_run", type_="foreignkey")