CREATE UNIQUE INDEX IF NOT EXISTS uniq_gateway_tasks_kling_compat_external
  ON gateway_tasks (
    COALESCE(gateway_user_id::text, user_id),
    external_task_id
  )
  WHERE external_task_id IS NOT NULL
    AND external_task_id <> ''
    AND request->>'_compat_provider' = 'kling'
    AND request->>'_kling_compat_version' IN ('v1', 'v2');
