WITH ranked AS (
    SELECT ctid,
           ROW_NUMBER() OVER (
               PARTITION BY cluster_id, source_node_id, target_node_id
               ORDER BY observed_at DESC
           ) AS rn
    FROM mesh_latest_links
)
DELETE FROM mesh_latest_links
USING ranked
WHERE mesh_latest_links.ctid = ranked.ctid
  AND ranked.rn > 1;

DROP INDEX IF EXISTS idx_mesh_latest_links_cluster_observed;

ALTER TABLE mesh_latest_links
    DROP CONSTRAINT IF EXISTS mesh_latest_links_pkey;

ALTER TABLE mesh_latest_links
    ADD PRIMARY KEY (cluster_id, source_node_id, target_node_id);

ALTER TABLE mesh_latest_links
    DROP COLUMN IF EXISTS observation_key;
