-- 0016_alerts_dedup_key.sql
--
-- Widen the open-alert uniqueness key from (host_id, kind) to
-- (host_id, kind, dedup_key) so two distinct failing source groups
-- on the same host produce two open alerts instead of collapsing
-- onto one. dedup_key is the source_group_id for
-- backup/forget/prune/check failures and the empty string for
-- agent_offline / stale_schedule (one-per-host alerts).
--
-- The original alerts_open partial index keyed on host_id only.
-- That was a coarse "is this host happy?" lookup; we replace it
-- with a proper partial unique index that the dedup logic relies
-- on. NOT NULL DEFAULT '' so existing rows backfill cleanly.
--
-- Column-level ALTER is safe under foreign_keys=ON.

ALTER TABLE alerts ADD COLUMN dedup_key TEXT NOT NULL DEFAULT '';

DROP INDEX IF EXISTS alerts_open;

CREATE UNIQUE INDEX alerts_open_unique
    ON alerts(host_id, kind, dedup_key)
    WHERE resolved_at IS NULL;
