-- Apply after 20260909_watch_sessions.sql. -- Preflight: this intentionally fails if historical data has more than one -- active session per student. Reconcile those rows to ended/invalidated first. ALTER TABLE watch_sessions ADD COLUMN active_student_id BIGINT UNSIGNED GENERATED ALWAYS AS (CASE WHEN status = 'active' THEN student_id ELSE NULL END) STORED, ADD UNIQUE KEY uq_watch_one_active_per_student (active_student_id); -- One decision per event, including repeated positions that are legitimately -- excluded. Position pairs alone are not an event identity. ALTER TABLE eligible_watch_intervals DROP INDEX uq_eligible_interval, ADD COLUMN event_sequence_no INT UNSIGNED NULL AFTER watch_session_id, ADD UNIQUE KEY uq_watch_interval_event (watch_session_id, event_sequence_no, policy_version); -- Rollback: stop writers that rely on the invariant first. Dropping the key -- weakens protection and is not a routine production rollback.