Files
watchman/services/watchman/migrations/versions/20261119_0015_alarm_handling.py
T
unknownandCursor 47d3b85a4b feat(alarms): 完成 M06 报警中心与人工处理
落地正式异常创建/合并、三状态人工处置与控制台,关闭 M06 DONE_LOCAL(含 D40 认领文案「处理」)。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-19 15:27:06 +08:00

426 lines
18 KiB
Python

"""Add alarm handling history and stop direct status updates.
Revision ID: 20261119_0015
Revises: 20261119_0014
Create Date: 2026-11-19
0014 stays unchanged. Status, handler, and close columns are no longer updated
by a plain UPDATE from the application role. The handling service calls
alarm_apply_transition, which is the only writer of those columns.
"""
from __future__ import annotations
from typing import Sequence, Union
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision: str = "20261119_0015"
down_revision: Union[str, None] = "20261119_0014"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
APP_ROLE = "watchman_app"
ALARMS = "alarms"
EVENTS = "alarm_handling_events"
COMMANDS = "alarm_handling_commands"
BASIS = "alarm_closed_basis"
GUARD_FUNCTION = "alarms_guard_status"
GUARD_TRIGGER = "trg_alarms_status_guard"
TRANSITION_FUNCTION = "alarm_apply_transition"
_EVENT_SHAPE = """
(
command = 'claim'
AND from_status = 'pending'
AND to_status = 'processing'
AND note IS NULL
AND close_result IS NULL
AND evidence_ref IS NULL
) OR (
command = 'progress'
AND from_status = 'processing'
AND to_status = 'processing'
AND note IS NOT NULL
AND char_length(btrim(note)) > 0
AND close_result IS NULL
) OR (
command = 'close'
AND from_status = 'processing'
AND to_status = 'closed'
AND note IS NOT NULL
AND char_length(btrim(note)) > 0
AND close_result IN ('resolved', 'false_positive')
)
"""
def _enable_rls_insert_only(table: str) -> None:
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
op.execute(
f"""
CREATE POLICY tenant_isolation ON {table}
FOR ALL
TO {APP_ROLE}
USING (tenant_id = current_setting('app.tenant_id', true))
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
"""
)
op.execute(f"GRANT SELECT, INSERT ON TABLE {table} TO {APP_ROLE}")
def _append_only(table: str, function: str, trigger: str, message: str) -> None:
op.execute(
f"""
CREATE FUNCTION {function}() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION '{message}'
USING ERRCODE = 'restrict_violation';
END;
$$
"""
)
op.execute(
f"""
CREATE TRIGGER {trigger}
BEFORE UPDATE OR DELETE OR TRUNCATE ON {table}
FOR EACH STATEMENT EXECUTE FUNCTION {function}()
"""
)
def upgrade() -> None:
op.add_column(ALARMS, sa.Column("claimed_at", sa.DateTime(timezone=True), nullable=True))
op.add_column(ALARMS, sa.Column("closed_at", sa.DateTime(timezone=True), nullable=True))
op.add_column(ALARMS, sa.Column("close_result", sa.String(length=32), nullable=True))
op.create_check_constraint(
"ck_alarms_close_result",
ALARMS,
"close_result IS NULL OR close_result IN ('resolved', 'false_positive')",
)
op.create_check_constraint(
"ck_alarms_pending_unassigned",
ALARMS,
"status <> 'pending' OR current_handler IS NULL",
)
op.create_check_constraint(
"ck_alarms_processing_handler",
ALARMS,
"status <> 'processing' OR current_handler IS NOT NULL",
)
# GUARD: table-level UPDATE would let a caller skip the handling service.
op.execute(f"REVOKE UPDATE ON TABLE {ALARMS} FROM {APP_ROLE}")
op.execute(
f"GRANT UPDATE (occurrence_count, last_occurred_at, updated_at) ON TABLE {ALARMS} TO {APP_ROLE}"
)
op.execute(
f"""
CREATE FUNCTION {GUARD_FUNCTION}() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
IF NEW.status IS DISTINCT FROM 'pending'
OR NEW.current_handler IS NOT NULL
OR NEW.claimed_at IS NOT NULL
OR NEW.closed_at IS NOT NULL
OR NEW.close_result IS NOT NULL THEN
RAISE EXCEPTION 'alarms are inserted as pending; status changes only through the handling service'
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
END IF;
IF NEW.status IS NOT DISTINCT FROM OLD.status
AND NEW.current_handler IS NOT DISTINCT FROM OLD.current_handler
AND NEW.claimed_at IS NOT DISTINCT FROM OLD.claimed_at
AND NEW.closed_at IS NOT DISTINCT FROM OLD.closed_at
AND NEW.close_result IS NOT DISTINCT FROM OLD.close_result THEN
RETURN NEW;
END IF;
IF current_setting('app.alarm_transition', true) IS DISTINCT FROM 'service' THEN
RAISE EXCEPTION 'alarm status transitions only through the handling service'
USING ERRCODE = 'restrict_violation';
END IF;
IF NEW.current_handler IS DISTINCT FROM OLD.current_handler
AND NOT (OLD.status = 'pending' AND NEW.status = 'processing') THEN
RAISE EXCEPTION 'alarm handler changes only when a pending alarm is claimed'
USING ERRCODE = 'restrict_violation';
END IF;
IF NEW.claimed_at IS DISTINCT FROM OLD.claimed_at
AND NOT (OLD.status = 'pending' AND NEW.status = 'processing') THEN
RAISE EXCEPTION 'claimed_at is set only when a pending alarm is claimed'
USING ERRCODE = 'restrict_violation';
END IF;
IF OLD.status = 'pending' AND NEW.status = 'processing' THEN
IF NEW.current_handler IS NULL OR btrim(NEW.current_handler) = ''
OR NEW.claimed_at IS NULL
OR NEW.closed_at IS NOT NULL
OR NEW.close_result IS NOT NULL THEN
RAISE EXCEPTION 'a claim must record one handler and no close result'
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
END IF;
IF OLD.status = 'processing' AND NEW.status = 'closed' THEN
IF NEW.current_handler IS DISTINCT FROM OLD.current_handler
OR NEW.claimed_at IS DISTINCT FROM OLD.claimed_at
OR NEW.close_result IS NULL
OR NEW.close_result NOT IN ('resolved', 'false_positive')
OR NEW.closed_at IS NULL
OR (NEW.claimed_at IS NOT NULL AND NEW.closed_at < NEW.claimed_at) THEN
RAISE EXCEPTION 'a close must keep the handler and record one final result'
USING ERRCODE = 'restrict_violation';
END IF;
RETURN NEW;
END IF;
RAISE EXCEPTION 'alarm status only moves pending to processing to closed'
USING ERRCODE = 'restrict_violation';
END;
$$
"""
)
op.execute(
f"""
CREATE TRIGGER {GUARD_TRIGGER}
BEFORE INSERT OR UPDATE ON {ALARMS}
FOR EACH ROW EXECUTE FUNCTION {GUARD_FUNCTION}()
"""
)
# GUARD: owner bypasses RLS, so the tenant predicate is mandatory.
op.execute(
f"""
CREATE FUNCTION {TRANSITION_FUNCTION}(
p_alarm_id uuid,
p_status text,
p_handler text,
p_claimed_at timestamptz,
p_closed_at timestamptz,
p_close_result text
) RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
IF current_setting('app.tenant_id', true) IS NULL
OR btrim(current_setting('app.tenant_id', true)) = '' THEN
RAISE EXCEPTION 'tenant is required'
USING ERRCODE = 'insufficient_privilege';
END IF;
PERFORM set_config('app.alarm_transition', 'service', true);
UPDATE {ALARMS}
SET status = p_status,
current_handler = p_handler,
claimed_at = CASE
WHEN p_status = 'processing' AND status = 'pending' THEN p_claimed_at
ELSE claimed_at
END,
closed_at = CASE
WHEN p_status = 'closed' THEN p_closed_at
ELSE closed_at
END,
close_result = CASE
WHEN p_status = 'closed' THEN p_close_result
ELSE close_result
END,
updated_at = now()
WHERE id = p_alarm_id
AND tenant_id = current_setting('app.tenant_id', true);
IF NOT FOUND THEN
RAISE EXCEPTION 'alarm not found for tenant'
USING ERRCODE = 'no_data_found';
END IF;
PERFORM set_config('app.alarm_transition', '', true);
END;
$$
"""
)
op.execute(f"REVOKE ALL ON FUNCTION {TRANSITION_FUNCTION}(uuid, text, text, timestamptz, timestamptz, text) FROM PUBLIC")
op.execute(
f"GRANT EXECUTE ON FUNCTION {TRANSITION_FUNCTION}(uuid, text, text, timestamptz, timestamptz, text) TO {APP_ROLE}"
)
# FORCE RLS applies to the table owner, and the existing policy targets only
# watchman_app. The definer function would otherwise update zero rows.
op.execute(
"""
DO $$
DECLARE
owner_name text;
BEGIN
SELECT pg_get_userbyid(c.relowner) INTO owner_name
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relname = 'alarms';
EXECUTE format(
'CREATE POLICY tenant_isolation_definer ON alarms FOR ALL TO %I '
'USING (tenant_id = current_setting(''app.tenant_id'', true)) '
'WITH CHECK (tenant_id = current_setting(''app.tenant_id'', true))',
owner_name
);
END $$;
"""
)
op.create_table(
EVENTS,
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
sa.Column("seq", sa.BigInteger(), sa.Identity(), nullable=False),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
sa.Column("command", sa.String(length=16), nullable=False),
sa.Column("actor_subject", sa.String(length=128), nullable=False),
sa.Column("actor_role", sa.String(length=64), nullable=False),
sa.Column("handler_subject", sa.String(length=128), nullable=False),
sa.Column("from_status", sa.String(length=16), nullable=False),
sa.Column("to_status", sa.String(length=16), nullable=False),
sa.Column("note", sa.String(length=2000), nullable=True),
sa.Column("close_result", sa.String(length=32), nullable=True),
sa.Column("evidence_ref", sa.String(length=512), nullable=True),
sa.Column("recorded_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.CheckConstraint("command IN ('claim', 'progress', 'close')", name="ck_alarm_handling_events_command"),
sa.CheckConstraint(
"from_status IN ('pending', 'processing', 'closed')",
name="ck_alarm_handling_events_from_status",
),
sa.CheckConstraint(
"to_status IN ('pending', 'processing', 'closed')",
name="ck_alarm_handling_events_to_status",
),
sa.CheckConstraint(
"actor_role IN ('watchman-admin', 'watchman-operator')",
name="ck_alarm_handling_events_actor_role",
),
sa.CheckConstraint("char_length(btrim(actor_subject)) > 0", name="ck_alarm_handling_events_actor"),
sa.CheckConstraint("char_length(btrim(handler_subject)) > 0", name="ck_alarm_handling_events_handler"),
sa.CheckConstraint(_EVENT_SHAPE, name="ck_alarm_handling_events_shape"),
sa.CheckConstraint(
"evidence_ref IS NULL OR char_length(btrim(evidence_ref)) > 0",
name="ck_alarm_handling_events_evidence_ref",
),
)
op.create_index("ix_alarm_handling_events_alarm_id", EVENTS, ["alarm_id", "seq"])
op.create_table(
COMMANDS,
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
sa.Column(
"event_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("alarm_handling_events.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column("command", sa.String(length=16), nullable=False),
sa.Column("idempotency_key", sa.String(length=128), nullable=False),
sa.Column("payload_hash", sa.String(length=64), nullable=False),
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.UniqueConstraint("tenant_id", "idempotency_key", name="uq_alarm_handling_commands_idem"),
sa.CheckConstraint("command IN ('claim', 'progress', 'close')", name="ck_alarm_handling_commands_command"),
sa.CheckConstraint("char_length(btrim(idempotency_key)) > 0", name="ck_alarm_handling_commands_key"),
sa.CheckConstraint("payload_hash ~ '^[0-9a-f]{64}$'", name="ck_alarm_handling_commands_hash"),
)
op.create_index("ix_alarm_handling_commands_alarm_id", COMMANDS, ["alarm_id"])
op.create_table(
BASIS,
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
sa.Column("tenant_id", sa.String(length=64), nullable=False),
sa.Column("alarm_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("alarms.id", ondelete="RESTRICT"), nullable=False),
sa.Column(
"original_occurrence_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("alarm_occurrences.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column(
"mapped_input_revision_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column(
"mapping_version_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column(
"rule_version_id",
postgresql.UUID(as_uuid=True),
sa.ForeignKey("rule_versions.id", ondelete="RESTRICT"),
nullable=False,
),
sa.Column("snapshot_id", postgresql.UUID(as_uuid=True), nullable=False),
sa.Column("snapshot_version_no", sa.Integer(), nullable=False),
sa.Column("cycle_key", sa.String(length=128), nullable=False),
sa.Column("event_key", sa.String(length=128), nullable=False),
sa.Column("observed_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("received_at", sa.DateTime(timezone=True), nullable=False),
sa.Column("recorded_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
sa.UniqueConstraint(
"tenant_id",
"mapped_input_revision_id",
"mapping_version_id",
"rule_version_id",
"snapshot_id",
"cycle_key",
"event_key",
"observed_at",
name="uq_alarm_closed_basis_formal_identity",
),
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_closed_basis_snapshot_version"),
sa.CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_closed_basis_cycle_key"),
sa.CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_closed_basis_event_key"),
)
op.create_index("ix_alarm_closed_basis_alarm_id", BASIS, ["alarm_id"])
for table in (EVENTS, COMMANDS, BASIS):
_enable_rls_insert_only(table)
_append_only(EVENTS, "alarm_handling_events_reject_mutation", "trg_alarm_handling_events_append_only", "alarm_handling_events is append-only")
_append_only(COMMANDS, "alarm_handling_commands_reject_mutation", "trg_alarm_handling_commands_append_only", "alarm_handling_commands is append-only")
_append_only(BASIS, "alarm_closed_basis_reject_mutation", "trg_alarm_closed_basis_append_only", "alarm_closed_basis is append-only")
def downgrade() -> None:
for table, function, trigger in (
(BASIS, "alarm_closed_basis_reject_mutation", "trg_alarm_closed_basis_append_only"),
(COMMANDS, "alarm_handling_commands_reject_mutation", "trg_alarm_handling_commands_append_only"),
(EVENTS, "alarm_handling_events_reject_mutation", "trg_alarm_handling_events_append_only"),
):
op.execute(f"DROP TRIGGER IF EXISTS {trigger} ON {table}")
op.execute(f"DROP FUNCTION IF EXISTS {function}()")
for table in (BASIS, COMMANDS, EVENTS):
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
op.drop_index("ix_alarm_closed_basis_alarm_id", table_name=BASIS)
op.drop_table(BASIS)
op.drop_index("ix_alarm_handling_commands_alarm_id", table_name=COMMANDS)
op.drop_table(COMMANDS)
op.drop_index("ix_alarm_handling_events_alarm_id", table_name=EVENTS)
op.drop_table(EVENTS)
op.execute("DROP POLICY IF EXISTS tenant_isolation_definer ON alarms")
op.execute(
f"DROP FUNCTION IF EXISTS {TRANSITION_FUNCTION}(uuid, text, text, timestamptz, timestamptz, text)"
)
op.execute(f"DROP TRIGGER IF EXISTS {GUARD_TRIGGER} ON {ALARMS}")
op.execute(f"DROP FUNCTION IF EXISTS {GUARD_FUNCTION}()")
op.execute(f"REVOKE UPDATE (occurrence_count, last_occurred_at, updated_at) ON TABLE {ALARMS} FROM {APP_ROLE}")
op.execute(f"GRANT UPDATE ON TABLE {ALARMS} TO {APP_ROLE}")
op.drop_constraint("ck_alarms_processing_handler", ALARMS, type_="check")
op.drop_constraint("ck_alarms_pending_unassigned", ALARMS, type_="check")
op.drop_constraint("ck_alarms_close_result", ALARMS, type_="check")
op.drop_column(ALARMS, "close_result")
op.drop_column(ALARMS, "closed_at")
op.drop_column(ALARMS, "claimed_at")