-- V16 — Generalise open-alert_instance uniqueness via `_subjectFingerprint`.
--
-- V15 discriminated open instances by `context->'exchange'->>'id'` so that
-- EXCHANGE_MATCH / PER_EXCHANGE could emit one instance per exchange. The new
-- AGENT_LIFECYCLE / PER_AGENT condition has the same shape but a different
-- subject key (agentId + eventType + eventTs). Rather than bolt condition-kind
-- knowledge into the index, we introduce a canonical `_subjectFingerprint`
-- field in `context` that every "per-subject" evaluator writes. The index
-- prefers it over the legacy exchange.id discriminator.
--
-- Precedence in the COALESCE:
--   1. context->>'_subjectFingerprint'  — explicit per-subject key (new)
--   2. context->'exchange'->>'id'       — legacy EXCHANGE_MATCH instances (pre-V16)
--   3. ''                                — scalar condition kinds (one open per rule)
--
-- Existing open PER_EXCHANGE instances keep working because they never set
-- `_subjectFingerprint` but do carry `context.exchange.id`, so the index
-- still discriminates them correctly.
DROP INDEX IF EXISTS alert_instances_open_rule_uq;

CREATE UNIQUE INDEX alert_instances_open_rule_uq
  ON alert_instances (rule_id, (COALESCE(
        context->>'_subjectFingerprint',
        context->'exchange'->>'id',
        '')))
  WHERE rule_id IS NOT NULL
    AND state IN ('PENDING','FIRING','ACKNOWLEDGED');
