"""Harden V3 heartbeat identity and concurrent updates. Revision ID: 202607260001 Revises: 202607150001 Create Date: 2026-07-26 """ from alembic import op import sqlalchemy as sa revision = "202607260001" down_revision = "202607150001" branch_labels = None depends_on = None HEARTBEAT_TABLE = "system_heartbeats" HEARTBEAT_IDENTITY_CONSTRAINT = "uq_system_heartbeat_component_instance" def upgrade() -> None: op.execute( sa.text( """ DELETE FROM system_heartbeats WHERE id IN ( SELECT id FROM ( SELECT id, ROW_NUMBER() OVER ( PARTITION BY component, instance_id ORDER BY last_seen_at DESC, id DESC ) AS duplicate_rank FROM system_heartbeats ) ranked WHERE duplicate_rank > 1 ) """ ) ) with op.batch_alter_table(HEARTBEAT_TABLE) as batch_op: batch_op.create_unique_constraint( HEARTBEAT_IDENTITY_CONSTRAINT, ["component", "instance_id"], ) def downgrade() -> None: with op.batch_alter_table(HEARTBEAT_TABLE) as batch_op: batch_op.drop_constraint(HEARTBEAT_IDENTITY_CONSTRAINT, type_="unique")