CREATE TABLE alert_instances ( id uuid PRIMARY KEY, rule_id uuid NOT NULL REFERENCES alert_rules(id) ON DELETE RESTRICT, rule_version_id uuid NOT NULL REFERENCES alert_rule_versions(id) ON DELETE RESTRICT, fingerprint text NOT NULL CHECK (length(fingerprint) BETWEEN 1 AND 160), entity_id uuid REFERENCES entities(id) ON DELETE RESTRICT, current_state text NOT NULL DEFAULT 'inactive' CHECK (current_state IN ('inactive', 'pending', 'firing', 'acknowledged', 'resolved', 'unknown')), retained_state text NOT NULL DEFAULT 'inactive' CHECK (retained_state IN ('inactive', 'pending', 'firing', 'acknowledged', 'resolved', 'unknown')), active_since timestamptz, recovery_since timestamptz, last_evaluated_at timestamptz NOT NULL, last_known_at timestamptz, last_value jsonb NOT NULL DEFAULT 'null'::jsonb, reason text NOT NULL DEFAULT '' CHECK (length(reason) <= 500), source_health jsonb NOT NULL DEFAULT '{}'::jsonb, acknowledged_by text, acknowledged_at timestamptz, revision bigint NOT NULL DEFAULT 1 CHECK (revision > 0), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (rule_id, fingerprint) ); CREATE TABLE alert_occurrences ( id uuid PRIMARY KEY, instance_id uuid NOT NULL REFERENCES alert_instances(id) ON DELETE RESTRICT, evaluation_key text NOT NULL CHECK (length(evaluation_key) BETWEEN 1 AND 160), event_type text NOT NULL CHECK (event_type IN ('evaluation', 'transition', 'acknowledge')), from_state text NOT NULL CHECK (from_state IN ('inactive', 'pending', 'firing', 'acknowledged', 'resolved', 'unknown')), to_state text NOT NULL CHECK (to_state IN ('inactive', 'pending', 'firing', 'acknowledged', 'resolved', 'unknown')), observed_at timestamptz NOT NULL, value jsonb NOT NULL DEFAULT 'null'::jsonb, reason text NOT NULL DEFAULT '' CHECK (length(reason) <= 500), source_health jsonb NOT NULL DEFAULT '{}'::jsonb, created_at timestamptz NOT NULL DEFAULT now(), UNIQUE (instance_id, evaluation_key) ); CREATE INDEX alert_instances_state_idx ON alert_instances (current_state, last_evaluated_at DESC, id ASC); CREATE INDEX alert_instances_rule_idx ON alert_instances (rule_id, current_state, updated_at DESC, id ASC); CREATE INDEX alert_occurrences_history_idx ON alert_occurrences (instance_id, observed_at DESC, id ASC);