UPDATE tasks
   SET lease_owner = NULL,
       lease_expires_at = NULL,
       updated_at = now()
 WHERE status IN ('awaiting_confirmation', 'completed', 'cancelled', 'parse_failed', 'reconciliation_pending')
   AND (lease_owner IS NOT NULL OR lease_expires_at IS NOT NULL);

UPDATE task_attempts AS attempt
   SET status = CASE WHEN task.status = 'cancelled' THEN 'cancelled' ELSE 'abandoned' END,
       error_code = COALESCE(
         attempt.error_code,
         CASE WHEN task.status = 'cancelled' THEN 'task_cancelled' ELSE 'task_terminal_reconciliation' END
       ),
       finished_at = COALESCE(attempt.finished_at, now())
  FROM tasks AS task
 WHERE attempt.task_id = task.id
   AND attempt.status = 'running'
   AND task.status IN ('awaiting_confirmation', 'completed', 'cancelled', 'parse_failed', 'reconciliation_pending');
