"""usage_events.task_id 放宽为 NULL(知识库入库记账).

Revision ID: 0022
Revises: 0021
Create Date: 2026-07-22

kb 入库(kind="kb_ingest")在任何 task 之外跑(上传/手动触发的后台任务),
没有 task 上下文可挂 —— task_id NOT NULL 挡住这类事件。放宽为 NULL:
纯放宽约束,存量行全部满足,零数据迁移;NULL = "非 task 维度的用量事件"。
统计侧不受影响(按 user/kind 聚合的 query 不依赖 task_id 非空)。
"""
from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op


revision: str = "0022"
down_revision: Union[str, None] = "0021"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.alter_column(
        "usage_events", "task_id",
        existing_type=sa.dialects.postgresql.UUID(as_uuid=True),
        nullable=True,
    )


def downgrade() -> None:
    # 回滚前提:已无 task_id IS NULL 的行(kb_ingest 事件需先清理),否则失败。
    op.alter_column(
        "usage_events", "task_id",
        existing_type=sa.dialects.postgresql.UUID(as_uuid=True),
        nullable=False,
    )
