feat(alarms): 完成 M06 报警中心与人工处理
落地正式异常创建/合并、三状态人工处置与控制台,关闭 M06 DONE_LOCAL(含 D40 认领文案「处理」)。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
df991417d7
commit
47d3b85a4b
88 files changed
+12658
-30
No files matched your search
@@ -0,0 +1,226 @@
|
||||
"""Create tenant-scoped alarm facts, occurrences, and revision evidence.
|
||||
|
||||
Revision ID: 20261119_0014
|
||||
Revises: 20261118_0013
|
||||
Create Date: 2026-11-19
|
||||
|
||||
Synthetic snapshot columns are stored on the fact rows. This migration does not
|
||||
create a scenario publish table.
|
||||
"""
|
||||
|
||||
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_0014"
|
||||
down_revision: Union[str, None] = "20261118_0013"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
ALARMS = "alarms"
|
||||
OCCURRENCES = "alarm_occurrences"
|
||||
EVIDENCE = "alarm_revision_evidence"
|
||||
OCCURRENCE_FUNCTION = "alarm_occurrences_reject_mutation"
|
||||
OCCURRENCE_TRIGGER = "trg_alarm_occurrences_append_only"
|
||||
EVIDENCE_FUNCTION = "alarm_revision_evidence_reject_mutation"
|
||||
EVIDENCE_TRIGGER = "trg_alarm_revision_evidence_append_only"
|
||||
|
||||
# Same minimal scope guard as the ORM. Subject-level contents are enforced by
|
||||
# the domain service; this check only blocks an empty or all-tenant blob.
|
||||
_SCOPE_SQL = (
|
||||
"jsonb_typeof(handling_scope) = 'object' "
|
||||
"AND NOT jsonb_exists(handling_scope, 'all_tenant') "
|
||||
"AND jsonb_typeof(handling_scope -> 'principals') = 'array' "
|
||||
"AND jsonb_array_length(handling_scope -> 'principals') >= 1"
|
||||
)
|
||||
|
||||
|
||||
def _enable_rls(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, UPDATE, DELETE ON TABLE {table} TO {APP_ROLE}")
|
||||
|
||||
|
||||
def _append_only(table: str, function: str, trigger: str, message: str) -> None:
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {table} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {table} TO {APP_ROLE}")
|
||||
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.create_table(
|
||||
ALARMS,
|
||||
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("status", sa.String(length=16), server_default=sa.text("'pending'"), nullable=False),
|
||||
sa.Column("current_handler", sa.String(length=128), nullable=True),
|
||||
sa.Column("occurrence_count", sa.Integer(), server_default=sa.text("1"), nullable=False),
|
||||
sa.Column("first_occurred_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("last_occurred_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("previous_alarm_id", postgresql.UUID(as_uuid=True), nullable=True),
|
||||
sa.Column("mapped_input_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapped_inputs.id", ondelete="RESTRICT"), nullable=False),
|
||||
sa.Column("mapping_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_definitions.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_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_definitions.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("module_key", sa.String(length=128), nullable=False),
|
||||
sa.Column("scenario_key", sa.String(length=128), nullable=False),
|
||||
sa.Column("scenario_name", sa.String(length=256), nullable=False),
|
||||
sa.Column("handling_scope", postgresql.JSONB(), nullable=False),
|
||||
sa.Column("cycle_key", sa.String(length=128), nullable=False),
|
||||
sa.Column("event_key", sa.String(length=128), nullable=False),
|
||||
sa.Column("opened_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.ForeignKeyConstraint(["previous_alarm_id"], ["alarms.id"], ondelete="RESTRICT"),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id",
|
||||
"module_key",
|
||||
"scenario_key",
|
||||
"mapped_input_id",
|
||||
"cycle_key",
|
||||
"event_key",
|
||||
name="uq_alarms_structured_merge_key",
|
||||
),
|
||||
sa.CheckConstraint("status IN ('pending', 'processing', 'closed')", name="ck_alarms_status"),
|
||||
sa.CheckConstraint("occurrence_count >= 1", name="ck_alarms_occurrence_count"),
|
||||
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarms_snapshot_version"),
|
||||
sa.CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarms_module_key"),
|
||||
sa.CheckConstraint("char_length(btrim(scenario_key)) > 0", name="ck_alarms_scenario_key"),
|
||||
sa.CheckConstraint("char_length(btrim(scenario_name)) > 0", name="ck_alarms_scenario_name"),
|
||||
sa.CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarms_cycle_key"),
|
||||
sa.CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarms_event_key"),
|
||||
sa.CheckConstraint("last_occurred_at >= first_occurred_at", name="ck_alarms_occurred_order"),
|
||||
sa.CheckConstraint("previous_alarm_id IS NULL OR previous_alarm_id <> id", name="ck_alarms_previous_not_self"),
|
||||
sa.CheckConstraint(_SCOPE_SQL, name="ck_alarms_handling_scope"),
|
||||
)
|
||||
op.create_index("ix_alarms_previous_alarm_id", ALARMS, ["previous_alarm_id"])
|
||||
op.create_index(
|
||||
"ix_alarms_subject_opened",
|
||||
ALARMS,
|
||||
["tenant_id", "module_key", "scenario_key", "mapped_input_id", "opened_at"],
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
OCCURRENCES,
|
||||
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("mapped_input_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapped_inputs.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_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_definitions.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_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_definitions.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("module_key", sa.String(length=128), nullable=False),
|
||||
sa.Column("scenario_key", sa.String(length=128), nullable=False),
|
||||
sa.Column("scenario_name", sa.String(length=256), nullable=False),
|
||||
sa.Column("handling_scope", postgresql.JSONB(), 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("created_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_occurrences_formal_identity",
|
||||
),
|
||||
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_occurrences_snapshot_version"),
|
||||
sa.CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarm_occurrences_module_key"),
|
||||
sa.CheckConstraint("char_length(btrim(scenario_key)) > 0", name="ck_alarm_occurrences_scenario_key"),
|
||||
sa.CheckConstraint("char_length(btrim(scenario_name)) > 0", name="ck_alarm_occurrences_scenario_name"),
|
||||
sa.CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_occurrences_cycle_key"),
|
||||
sa.CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_occurrences_event_key"),
|
||||
sa.CheckConstraint(_SCOPE_SQL, name="ck_alarm_occurrences_handling_scope"),
|
||||
)
|
||||
op.create_index("ix_alarm_occurrences_alarm_id", OCCURRENCES, ["alarm_id"])
|
||||
|
||||
op.create_table(
|
||||
EVIDENCE,
|
||||
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("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("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("alarm_id", "mapped_input_revision_id", name="uq_alarm_revision_evidence_alarm_revision"),
|
||||
sa.CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_revision_evidence_snapshot_version"),
|
||||
)
|
||||
op.create_index("ix_alarm_revision_evidence_alarm_id", EVIDENCE, ["alarm_id"])
|
||||
|
||||
for table in (ALARMS, OCCURRENCES, EVIDENCE):
|
||||
_enable_rls(table)
|
||||
_append_only(
|
||||
OCCURRENCES,
|
||||
OCCURRENCE_FUNCTION,
|
||||
OCCURRENCE_TRIGGER,
|
||||
"alarm_occurrences is append-only: formal facts are immutable",
|
||||
)
|
||||
_append_only(
|
||||
EVIDENCE,
|
||||
EVIDENCE_FUNCTION,
|
||||
EVIDENCE_TRIGGER,
|
||||
"alarm_revision_evidence is append-only: correction basis is immutable",
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in (EVIDENCE, OCCURRENCES, ALARMS):
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {EVIDENCE_TRIGGER} ON {EVIDENCE}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {OCCURRENCE_TRIGGER} ON {OCCURRENCES}")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {EVIDENCE_FUNCTION}()")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {OCCURRENCE_FUNCTION}()")
|
||||
op.drop_index("ix_alarm_revision_evidence_alarm_id", table_name=EVIDENCE)
|
||||
op.drop_table(EVIDENCE)
|
||||
op.drop_index("ix_alarm_occurrences_alarm_id", table_name=OCCURRENCES)
|
||||
op.drop_table(OCCURRENCES)
|
||||
op.drop_index("ix_alarms_subject_opened", table_name=ALARMS)
|
||||
op.drop_index("ix_alarms_previous_alarm_id", table_name=ALARMS)
|
||||
op.drop_table(ALARMS)
|
||||
@@ -0,0 +1,425 @@
|
||||
"""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")
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Seed a few synthetic M06 alarms for local console demos.
|
||||
|
||||
Why: the Playwright demo used route mocks; the real DB starts empty, so the
|
||||
logged-in console shows no rows. This script creates formal failures under a
|
||||
synthetic mapping graph and puts the caller's Casdoor subject into the snapshot
|
||||
handling scope so the list is visible.
|
||||
Boundary: local/dev only; does not send notifications or create M08 scenarios.
|
||||
Depends on alarm services, mappings, and the configured PostgreSQL tenant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from watchman.core.config import get_settings, reload_settings
|
||||
from watchman.core.db import reset_engine, set_tenant
|
||||
from watchman.models.auth_session import AuthSession
|
||||
from watchman.models.datasource import DataSource
|
||||
from watchman.models.mapping import MappedInput, MappedInputRevision
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
from watchman.services.alarms import FormalFailure, SyntheticPublishSnapshot, record_formal_failure
|
||||
from watchman.services.mappings import create_mapping, persist_mapped_rows, save_mapping_version
|
||||
from watchman.services.rules import create_rule, save_rule_version
|
||||
|
||||
FAKE_CIPHERTEXT = "gAAAA-demo-placeholder-ciphertext-not-a-secret"
|
||||
|
||||
|
||||
def _is_test_login(login: str) -> bool:
|
||||
return (
|
||||
login in {"worker", "idem-admin"}
|
||||
or login.startswith("worker-")
|
||||
or login.startswith("idem-")
|
||||
or login.startswith("Alarm")
|
||||
)
|
||||
|
||||
|
||||
def _recent_subjects(session: Session, limit: int = 20) -> list[tuple[str, str]]:
|
||||
rows = session.scalars(select(AuthSession).order_by(AuthSession.expires_at.desc()).limit(300)).all()
|
||||
seen: dict[str, str] = {}
|
||||
for row in rows:
|
||||
login = (row.login_name or "").strip()
|
||||
subject = (row.subject or "").strip()
|
||||
if not subject or _is_test_login(login):
|
||||
continue
|
||||
seen.setdefault(subject, login or subject)
|
||||
if len(seen) >= limit:
|
||||
break
|
||||
return list(seen.items())
|
||||
|
||||
|
||||
def _build_graph(session: Session, tenant_id: str, label: str) -> tuple[uuid.UUID, uuid.UUID, uuid.UUID]:
|
||||
serial = f"DEMO-{uuid.uuid4().hex[:8]}"
|
||||
datasource = DataSource(
|
||||
tenant_id=tenant_id,
|
||||
name=f"demo-alarm-ds-{uuid.uuid4().hex[:8]}",
|
||||
kind="database",
|
||||
engine="postgresql",
|
||||
host="127.0.0.1",
|
||||
port=5432,
|
||||
database_name="synthetic",
|
||||
username="synthetic_user",
|
||||
secret_ciphertext=FAKE_CIPHERTEXT,
|
||||
)
|
||||
session.add(datasource)
|
||||
session.flush()
|
||||
query = QueryDefinition(
|
||||
tenant_id=tenant_id,
|
||||
name=f"demo-alarm-query-{label}-{uuid.uuid4().hex[:6]}",
|
||||
datasource_id=datasource.id,
|
||||
draft_sql_template="SELECT 1",
|
||||
current_version_no=1,
|
||||
latest_published_version_no=1,
|
||||
)
|
||||
session.add(query)
|
||||
session.flush()
|
||||
session.add(
|
||||
QueryVersion(
|
||||
tenant_id=tenant_id,
|
||||
definition_id=query.id,
|
||||
version_no=1,
|
||||
sql_template="SELECT 1",
|
||||
param_schema=[],
|
||||
output_schema=[
|
||||
{"name": "serial", "type": "string"},
|
||||
{"name": "temperature", "type": "number"},
|
||||
],
|
||||
allowed_identifiers=[],
|
||||
timeout_ms=10000,
|
||||
max_rows=100,
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||
mapping_version = save_mapping_version(
|
||||
session,
|
||||
str(definition.id),
|
||||
[
|
||||
{
|
||||
"source_column_name": "serial",
|
||||
"value_type": "string",
|
||||
"is_identity": True,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
{
|
||||
"source_column_name": "temperature",
|
||||
"value_type": "number",
|
||||
"is_identity": False,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
],
|
||||
)
|
||||
persist_mapped_rows(session, str(definition.id), [{"serial": serial, "temperature": 88}])
|
||||
mapped = session.scalar(
|
||||
select(MappedInput).where(MappedInput.mapping_definition_id == definition.id)
|
||||
)
|
||||
if mapped is None:
|
||||
raise RuntimeError("mapped input missing after persist")
|
||||
revision = session.scalar(
|
||||
select(MappedInputRevision)
|
||||
.where(MappedInputRevision.input_id == mapped.id)
|
||||
.order_by(MappedInputRevision.revision_no.desc())
|
||||
.limit(1)
|
||||
)
|
||||
if revision is None:
|
||||
raise RuntimeError("mapped revision missing after persist")
|
||||
rule = create_rule(session, mapping_definition_id=str(definition.id))
|
||||
rule_version = save_rule_version(
|
||||
session,
|
||||
str(rule.id),
|
||||
{"column": "temperature", "operator": "gt", "value": 80},
|
||||
)
|
||||
return mapping_version.id, rule_version.id, revision.id
|
||||
|
||||
|
||||
def seed(subjects: list[str]) -> list[str]:
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||
session = factory()
|
||||
created: list[str] = []
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
cases = [
|
||||
("furnace", "furnace-overtemp", "炉温超限", "cycle-demo-a", "event-overheat"),
|
||||
("utility", "air-pressure", "气压偏低", "cycle-demo-b", "event-pressure"),
|
||||
("quality", "dimension", "尺寸超差", "cycle-demo-c", "event-dimension"),
|
||||
]
|
||||
base = datetime.now(timezone.utc) - timedelta(hours=2)
|
||||
for index, (module_key, scenario_key, scenario_name, cycle_key, event_key) in enumerate(cases):
|
||||
mapping_version_id, rule_version_id, revision_id = _build_graph(
|
||||
session, settings.tenant_id, scenario_key
|
||||
)
|
||||
observed = base + timedelta(minutes=15 * index)
|
||||
result = record_formal_failure(
|
||||
session,
|
||||
FormalFailure(
|
||||
mapped_input_revision_id=revision_id,
|
||||
snapshot=SyntheticPublishSnapshot(
|
||||
snapshot_id=uuid.uuid4(),
|
||||
version_no=1,
|
||||
module_key=module_key,
|
||||
scenario_key=scenario_key,
|
||||
scenario_name=scenario_name,
|
||||
handling_scope={
|
||||
"principals": [
|
||||
{"kind": "subject", "value": subject} for subject in subjects
|
||||
],
|
||||
},
|
||||
mapping_version_id=mapping_version_id,
|
||||
rule_version_id=rule_version_id,
|
||||
),
|
||||
observed_at=observed,
|
||||
received_at=observed + timedelta(seconds=5),
|
||||
cycle_key=cycle_key,
|
||||
event_key=event_key,
|
||||
),
|
||||
confirmed_abnormal=True,
|
||||
)
|
||||
if result is None or result.alarm_id is None:
|
||||
raise RuntimeError(f"failed to create alarm for {scenario_key}")
|
||||
created.append(str(result.alarm_id))
|
||||
session.commit()
|
||||
return created
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Seed local demo alarms visible to named subjects.")
|
||||
parser.add_argument(
|
||||
"--subject",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Casdoor subject that should see the alarms. Repeatable.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--from-sessions",
|
||||
action="store_true",
|
||||
help="Also include recent non-test auth_session subjects.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--list-sessions",
|
||||
action="store_true",
|
||||
help="Only list recent non-test sessions, then exit.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
session = sessionmaker(bind=engine)()
|
||||
subjects: list[str] = []
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
found = _recent_subjects(session)
|
||||
print("recent non-test sessions:")
|
||||
if not found:
|
||||
print(" (none)")
|
||||
for subject, login in found:
|
||||
print(f" subject={subject} login={login}")
|
||||
if args.list_sessions:
|
||||
return
|
||||
if args.from_sessions:
|
||||
subjects.extend(subject for subject, _login in found)
|
||||
subjects.extend(args.subject)
|
||||
cleaned: list[str] = []
|
||||
for item in subjects:
|
||||
value = item.strip()
|
||||
if value and value not in cleaned:
|
||||
cleaned.append(value)
|
||||
if not cleaned:
|
||||
print(
|
||||
"No subjects provided. Log into the console once, then re-run with "
|
||||
"--from-sessions, or pass --subject <casdoor-sub>."
|
||||
)
|
||||
raise SystemExit(2)
|
||||
finally:
|
||||
session.close()
|
||||
engine.dispose()
|
||||
|
||||
alarm_ids = seed(cleaned)
|
||||
print(f"seeded {len(alarm_ids)} alarms for subjects: {cleaned}")
|
||||
for alarm_id in alarm_ids:
|
||||
print(f" alarm_id={alarm_id}")
|
||||
print("Refresh http://127.0.0.1:5173/#/alarms and click 查询.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,6 +1,6 @@
|
||||
"""FastAPI application factory.
|
||||
|
||||
Registers envelope middleware and global exception handlers.
|
||||
Registers envelope middleware, global exception handlers, and the HTTP routers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from watchman.api.routes import auth, datasources, health, mappings, platform, queries
|
||||
from watchman.api.routes import alarms, auth, datasources, health, mappings, platform, queries
|
||||
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
|
||||
from watchman.core.errors import AppError, ValidationError
|
||||
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
|
||||
@@ -80,6 +80,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
|
||||
app.include_router(datasources.router)
|
||||
app.include_router(queries.router)
|
||||
app.include_router(mappings.router)
|
||||
app.include_router(alarms.router)
|
||||
|
||||
@app.exception_handler(AppError)
|
||||
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
"""Alarm list, detail, and handling command routes.
|
||||
|
||||
Why: the console needs scoped reads and three idempotent commands without a
|
||||
frontend permission bypass. Filters are applied only when the client sends them.
|
||||
Boundary: checks the approved alarm nodes, then snapshot subject scope. It does
|
||||
not hand-write error JSON, invent a role, or accept tenant_id from the caller.
|
||||
Depends on alarm reads and the handling service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.auth.access import ALARM_CLOSE_NODE, ALARM_PROGRESS_NODE, ALARM_TAKE_NODE
|
||||
from watchman.auth.principal import (
|
||||
AlarmCaller,
|
||||
require_alarm_closer,
|
||||
require_alarm_progress_writer,
|
||||
require_alarm_reader,
|
||||
require_alarm_taker,
|
||||
)
|
||||
from watchman.core.db import get_db_session
|
||||
from watchman.core.errors import ForbiddenError, ValidationError
|
||||
from watchman.core.response import success_body
|
||||
from watchman.services import alarm_reads
|
||||
from watchman.services.alarm_handling import (
|
||||
HandlingActor,
|
||||
HandlingResult,
|
||||
append_progress,
|
||||
claim_alarm,
|
||||
close_alarm,
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/alarms", tags=["alarms"])
|
||||
|
||||
# GUARD: reject an over-long key here. The handling service truncates at 128.
|
||||
_IDEMPOTENCY_KEY_MAX = 128
|
||||
Note = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=2000)]
|
||||
EvidenceRef = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=512)]
|
||||
|
||||
|
||||
class EmptyBody(BaseModel):
|
||||
"""Claim has no business fields. Unknown fields, including tenant_id, are rejected."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class ProgressBody(BaseModel):
|
||||
"""One appended note. It cannot carry a status or a handler."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
note: Note
|
||||
evidence_ref: EvidenceRef | None = None
|
||||
|
||||
|
||||
class CloseBody(BaseModel):
|
||||
"""Close result and required note. Status is not accepted from the client."""
|
||||
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
result: str = Field(pattern="^(resolved|false_positive)$")
|
||||
note: Note
|
||||
evidence_ref: EvidenceRef | None = None
|
||||
|
||||
|
||||
def _ok(request: Request, data: Any) -> JSONResponse:
|
||||
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
|
||||
|
||||
|
||||
def _command_key(value: str | None) -> str:
|
||||
"""Require x-idempotency-key and refuse a value the column would truncate."""
|
||||
if value is None or not value.strip():
|
||||
raise ValidationError(
|
||||
"x-idempotency-key is required",
|
||||
details={"field": "x-idempotency-key", "reason": "idempotency_key_required"},
|
||||
)
|
||||
cleaned = value.strip()
|
||||
if len(cleaned) > _IDEMPOTENCY_KEY_MAX:
|
||||
raise ValidationError(
|
||||
"x-idempotency-key is too long",
|
||||
details={
|
||||
"field": "x-idempotency-key",
|
||||
"reason": "idempotency_key_too_long",
|
||||
"max": _IDEMPOTENCY_KEY_MAX,
|
||||
},
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _actor(caller: AlarmCaller, node: str) -> HandlingActor:
|
||||
"""Build the handling actor only when the session has an explicit subject.
|
||||
|
||||
A blank subject is not an operator-wide grant. The role check already ran.
|
||||
"""
|
||||
subject = alarm_reads.scope_subject(caller.subject)
|
||||
if subject is None:
|
||||
raise ForbiddenError(
|
||||
"Alarm handling requires an explicit snapshot subject",
|
||||
permission_node=node,
|
||||
)
|
||||
return HandlingActor(subject=subject, roles=caller.roles)
|
||||
|
||||
|
||||
def _command_data(result: HandlingResult) -> dict[str, Any]:
|
||||
return {
|
||||
"alarm_id": str(result.alarm_id),
|
||||
"event_id": str(result.event_id),
|
||||
"command": result.command,
|
||||
"status": result.status,
|
||||
"current_handler": result.current_handler,
|
||||
"close_result": result.close_result,
|
||||
"replayed": result.replayed,
|
||||
}
|
||||
|
||||
|
||||
def _reader_subject(caller: AlarmCaller) -> str | None:
|
||||
return alarm_reads.scope_subject(caller.subject)
|
||||
|
||||
|
||||
def _parse_command_id(alarm_id: str) -> uuid.UUID:
|
||||
"""Parse an id that visibility already accepted, so the service receives a UUID."""
|
||||
return uuid.UUID(alarm_id)
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_alarms(
|
||||
request: Request,
|
||||
module_key: str | None = None,
|
||||
scenario_key: str | None = None,
|
||||
scenario_name: str | None = None,
|
||||
status: str | None = None,
|
||||
mapped_input_id: str | None = None,
|
||||
occurred_from: datetime | None = None,
|
||||
occurred_to: datetime | None = None,
|
||||
sort_by: str = "last_occurred_at",
|
||||
sort_order: str = "desc",
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
"""List alarms inside the caller's snapshot subjects. Sort and page in SQL."""
|
||||
# GUARD: do not read a tenant_id query parameter. Scope comes from the session subject.
|
||||
result = alarm_reads.search_alarms(
|
||||
session,
|
||||
subject=_reader_subject(caller),
|
||||
module_key=module_key,
|
||||
scenario_key=scenario_key,
|
||||
scenario_name=scenario_name,
|
||||
status=status,
|
||||
mapped_input_id=mapped_input_id,
|
||||
occurred_from=occurred_from,
|
||||
occurred_to=occurred_to,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
)
|
||||
return _ok(request, result)
|
||||
|
||||
|
||||
@router.get("/{alarm_id}")
|
||||
def get_alarm(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
"""Return one alarm. An id outside the snapshot scope is not found."""
|
||||
return _ok(request, alarm_reads.get_alarm(session, alarm_id, _reader_subject(caller)))
|
||||
|
||||
|
||||
@router.get("/{alarm_id}/occurrences")
|
||||
def get_alarm_occurrences(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
"""Return formal occurrences for one visible alarm."""
|
||||
return _ok(request, alarm_reads.list_occurrences(session, alarm_id, _reader_subject(caller)))
|
||||
|
||||
|
||||
@router.get("/{alarm_id}/evidence")
|
||||
def get_alarm_evidence(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
"""Return revision evidence and closed-repeat basis. Neither means recovered."""
|
||||
return _ok(request, alarm_reads.list_evidence(session, alarm_id, _reader_subject(caller)))
|
||||
|
||||
|
||||
@router.get("/{alarm_id}/history")
|
||||
def get_alarm_history(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
"""Return append-only handling history for one visible alarm."""
|
||||
return _ok(request, alarm_reads.list_history(session, alarm_id, _reader_subject(caller)))
|
||||
|
||||
|
||||
@router.get("/{alarm_id}/close-validity")
|
||||
def get_alarm_close_validity(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
caller: AlarmCaller = Depends(require_alarm_reader),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
"""Return the derived close flag after the scope check."""
|
||||
return _ok(
|
||||
request,
|
||||
alarm_reads.read_close_validity(session, alarm_id, _reader_subject(caller)),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{alarm_id}/claim")
|
||||
def post_claim(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
body: EmptyBody | None = None,
|
||||
caller: AlarmCaller = Depends(require_alarm_taker),
|
||||
session: Session = Depends(get_db_session),
|
||||
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||
) -> JSONResponse:
|
||||
"""Claim one in-scope pending alarm. A repeated key returns the original event."""
|
||||
del body
|
||||
actor = _actor(caller, ALARM_TAKE_NODE)
|
||||
alarm_reads.get_alarm(session, alarm_id, actor.subject)
|
||||
result = claim_alarm(
|
||||
session,
|
||||
alarm_id=_parse_command_id(alarm_id),
|
||||
actor=actor,
|
||||
idempotency_key=_command_key(x_idempotency_key),
|
||||
)
|
||||
data = _command_data(result)
|
||||
session.commit()
|
||||
return _ok(request, data)
|
||||
|
||||
|
||||
@router.post("/{alarm_id}/progress")
|
||||
def post_progress(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
body: ProgressBody,
|
||||
caller: AlarmCaller = Depends(require_alarm_progress_writer),
|
||||
session: Session = Depends(get_db_session),
|
||||
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||
) -> JSONResponse:
|
||||
"""Append one progress note for the current handler."""
|
||||
actor = _actor(caller, ALARM_PROGRESS_NODE)
|
||||
alarm_reads.get_alarm(session, alarm_id, actor.subject)
|
||||
result = append_progress(
|
||||
session,
|
||||
alarm_id=_parse_command_id(alarm_id),
|
||||
actor=actor,
|
||||
note=body.note,
|
||||
evidence_ref=body.evidence_ref,
|
||||
idempotency_key=_command_key(x_idempotency_key),
|
||||
)
|
||||
data = _command_data(result)
|
||||
session.commit()
|
||||
return _ok(request, data)
|
||||
|
||||
|
||||
@router.post("/{alarm_id}/close")
|
||||
def post_close(
|
||||
request: Request,
|
||||
alarm_id: str,
|
||||
body: CloseBody,
|
||||
caller: AlarmCaller = Depends(require_alarm_closer),
|
||||
session: Session = Depends(get_db_session),
|
||||
x_idempotency_key: str | None = Header(default=None, alias="x-idempotency-key"),
|
||||
) -> JSONResponse:
|
||||
"""Close as resolved or false_positive. Same content with a new key replays (D37)."""
|
||||
actor = _actor(caller, ALARM_CLOSE_NODE)
|
||||
alarm_reads.get_alarm(session, alarm_id, actor.subject)
|
||||
result = close_alarm(
|
||||
session,
|
||||
alarm_id=_parse_command_id(alarm_id),
|
||||
actor=actor,
|
||||
result=body.result,
|
||||
note=body.note,
|
||||
evidence_ref=body.evidence_ref,
|
||||
idempotency_key=_command_key(x_idempotency_key),
|
||||
)
|
||||
data = _command_data(result)
|
||||
session.commit()
|
||||
return _ok(request, data)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Role checks for the Watchman permission nodes.
|
||||
|
||||
Decides enter, platform write, object read, and the three datasource nodes (read,
|
||||
write, test) and the four query nodes (read, write, publish, preview) from Casdoor role names.
|
||||
Decides enter, platform write, object read, datasource, query, mapping, and the
|
||||
four approved alarm nodes from the existing Casdoor role names.
|
||||
Depends on semantic errors only; it does not call Casdoor or open a session.
|
||||
"""
|
||||
|
||||
@@ -25,6 +25,12 @@ MAPPING_READ_NODE = "perm:data:emp:watchman.mapping.read"
|
||||
MAPPING_WRITE_NODE = "perm:data:emp:watchman.mapping.write"
|
||||
MAPPING_TRIAL_NODE = "perm:data:emp:watchman.mapping.trial"
|
||||
|
||||
# GUARD: these four literals are D38. Do not add another alarm permission node here.
|
||||
ALARM_READ_NODE = "perm:data:emp:watchman.alarm.read"
|
||||
ALARM_TAKE_NODE = "perm:data:emp:watchman.alarm.take"
|
||||
ALARM_PROGRESS_NODE = "perm:data:emp:watchman.alarm.progress"
|
||||
ALARM_CLOSE_NODE = "perm:data:emp:watchman.alarm.close"
|
||||
|
||||
ROLE_ADMIN = "watchman-admin"
|
||||
ROLE_OPERATOR = "watchman-operator"
|
||||
ROLE_VIEWER = "watchman-viewer"
|
||||
@@ -115,6 +121,43 @@ def require_mapping_trial(role_names: list[str]) -> None:
|
||||
raise ForbiddenError(permission_node=MAPPING_TRIAL_NODE)
|
||||
|
||||
|
||||
def require_alarm_read(role_names: list[str]) -> None:
|
||||
"""Allow alarm reads for the three existing roles.
|
||||
|
||||
Viewer, operator, and admin may read. An empty or unknown role list is
|
||||
denied with the alarm read node. Snapshot scope is a separate check.
|
||||
"""
|
||||
if not ENTER_ROLES.intersection(role_names):
|
||||
raise ForbiddenError(permission_node=ALARM_READ_NODE)
|
||||
|
||||
|
||||
def _require_alarm_handler(role_names: list[str], node: str) -> None:
|
||||
"""Allow a handling command for operator or admin, and name the missing node.
|
||||
|
||||
Viewer stays read-only. This does not grant a snapshot scope or a new role.
|
||||
"""
|
||||
if ROLE_ADMIN not in role_names and ROLE_OPERATOR not in role_names:
|
||||
raise ForbiddenError(permission_node=node)
|
||||
|
||||
|
||||
def require_alarm_take(role_names: list[str]) -> None:
|
||||
"""Allow claim only for operator or admin."""
|
||||
_require_alarm_handler(role_names, ALARM_TAKE_NODE)
|
||||
|
||||
|
||||
def require_alarm_progress(role_names: list[str]) -> None:
|
||||
"""Allow a progress note only for operator or admin."""
|
||||
_require_alarm_handler(role_names, ALARM_PROGRESS_NODE)
|
||||
|
||||
|
||||
def require_alarm_close(role_names: list[str]) -> None:
|
||||
"""Allow a close attempt only for operator or admin.
|
||||
|
||||
The current-handler rule is enforced by the handling service, not here.
|
||||
"""
|
||||
_require_alarm_handler(role_names, ALARM_CLOSE_NODE)
|
||||
|
||||
|
||||
def require_object_access(role_names: list[str], object_id: str) -> None:
|
||||
"""Reject every object id until a later module grants row access.
|
||||
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
"""Reload Casdoor roles for a login name without keeping a user token.
|
||||
|
||||
Uses the application client to read one user. Tests replace the transport.
|
||||
Session gates for datasource, query, mapping, and alarm actions live here too.
|
||||
Depends on settings and the shared HTTP transport used by password login.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
from typing import Protocol
|
||||
from urllib.parse import quote
|
||||
@@ -15,6 +17,10 @@ from fastapi import Cookie, Depends, Request
|
||||
|
||||
from watchman.auth.casdoor import DefaultCasdoorPort, UrllibCasdoorHttpTransport
|
||||
from watchman.auth.access import (
|
||||
require_alarm_close,
|
||||
require_alarm_progress,
|
||||
require_alarm_read,
|
||||
require_alarm_take,
|
||||
require_datasource_read,
|
||||
require_datasource_test,
|
||||
require_datasource_write,
|
||||
@@ -136,8 +142,8 @@ def _load_session(
|
||||
session_token: str | None,
|
||||
sessions: SessionStore,
|
||||
directory: RoleDirectory,
|
||||
) -> tuple[str, list[str]]:
|
||||
"""Return (login_name, fresh role names) for the caller's session, or raise 41000 / 503.
|
||||
) -> tuple[str, str, list[str]]:
|
||||
"""Return (subject, login_name, fresh roles) or raise 41000 / 503.
|
||||
|
||||
Same session and freshness rules as require_platform_writer: a stale snapshot is
|
||||
reloaded from Casdoor and, if that fails, the old roles are not used.
|
||||
@@ -153,7 +159,7 @@ def _load_session(
|
||||
if now - row.role_checked_at >= ROLE_FRESHNESS:
|
||||
roles = directory.lookup_roles(login_name=row.login_name)
|
||||
sessions.update_roles(token_hash=row.token_hash, role_names=roles, now=now)
|
||||
return row.login_name, roles
|
||||
return row.subject, row.login_name, roles
|
||||
|
||||
|
||||
def _load_session_roles(
|
||||
@@ -163,7 +169,7 @@ def _load_session_roles(
|
||||
directory: RoleDirectory,
|
||||
) -> list[str]:
|
||||
"""Return fresh role names for the caller's session, or raise 41000 / 503."""
|
||||
return _load_session(request, session_token, sessions, directory)[1]
|
||||
return _load_session(request, session_token, sessions, directory)[2]
|
||||
|
||||
|
||||
def require_datasource_reader(
|
||||
@@ -223,7 +229,7 @@ def require_query_publisher(
|
||||
directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> str:
|
||||
"""Reject a publish unless the session is admin; return the login name to record."""
|
||||
login_name, roles = _load_session(request, session_token, sessions, directory)
|
||||
_subject, login_name, roles = _load_session(request, session_token, sessions, directory)
|
||||
require_query_publish(roles)
|
||||
return login_name
|
||||
|
||||
@@ -260,3 +266,77 @@ def require_mapping_trialer(
|
||||
) -> None:
|
||||
"""Reject mapping trials unless the session is watchman-admin."""
|
||||
require_mapping_trial(_load_session_roles(request, session_token, sessions, directory))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AlarmCaller:
|
||||
"""Session identity for an alarm route.
|
||||
|
||||
`subject` is the snapshot scope key. `roles` are the existing three names
|
||||
after a fresh load. This object does not by itself grant a row.
|
||||
"""
|
||||
|
||||
subject: str
|
||||
roles: tuple[str, ...]
|
||||
|
||||
|
||||
def _alarm_caller(
|
||||
request: Request,
|
||||
session_token: str | None,
|
||||
sessions: SessionStore,
|
||||
directory: RoleDirectory,
|
||||
) -> AlarmCaller:
|
||||
"""Load the session subject and roles. A missing session is 41000, not an empty scope."""
|
||||
subject, _login_name, roles = _load_session(request, session_token, sessions, directory)
|
||||
return AlarmCaller(subject=subject, roles=tuple(roles))
|
||||
|
||||
|
||||
def require_alarm_reader(
|
||||
request: Request,
|
||||
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> AlarmCaller:
|
||||
"""Reject alarm reads unless the session holds one of the three existing roles."""
|
||||
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||
require_alarm_read(list(caller.roles))
|
||||
return caller
|
||||
|
||||
|
||||
def require_alarm_taker(
|
||||
request: Request,
|
||||
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> AlarmCaller:
|
||||
"""Reject a claim unless the session is operator or admin."""
|
||||
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||
require_alarm_take(list(caller.roles))
|
||||
return caller
|
||||
|
||||
|
||||
def require_alarm_progress_writer(
|
||||
request: Request,
|
||||
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> AlarmCaller:
|
||||
"""Reject a progress note unless the session is operator or admin."""
|
||||
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||
require_alarm_progress(list(caller.roles))
|
||||
return caller
|
||||
|
||||
|
||||
def require_alarm_closer(
|
||||
request: Request,
|
||||
session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store),
|
||||
directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> AlarmCaller:
|
||||
"""Reject a close attempt unless the session is operator or admin.
|
||||
|
||||
Being in this dependency does not make the caller the current handler.
|
||||
"""
|
||||
caller = _alarm_caller(request, session_token, sessions, directory)
|
||||
require_alarm_close(list(caller.roles))
|
||||
return caller
|
||||
@@ -1,5 +1,7 @@
|
||||
"""SQLAlchemy models for the Watchman service package."""
|
||||
|
||||
from watchman.models.alarm import Alarm, AlarmOccurrence, AlarmRevisionEvidence
|
||||
from watchman.models.alarm_handling import AlarmClosedBasis, AlarmHandlingCommand, AlarmHandlingEvent
|
||||
from watchman.models.auth_session import AuthSession
|
||||
from watchman.models.datasource import DataSource
|
||||
from watchman.models.mapping import MappingColumnConfig, MappingDefinition, MappingVersion
|
||||
@@ -7,6 +9,12 @@ from watchman.models.platform import AuditEvent, RunRecord
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
|
||||
__all__ = [
|
||||
"Alarm",
|
||||
"AlarmClosedBasis",
|
||||
"AlarmHandlingCommand",
|
||||
"AlarmHandlingEvent",
|
||||
"AlarmOccurrence",
|
||||
"AlarmRevisionEvidence",
|
||||
"AuthSession",
|
||||
"AuditEvent",
|
||||
"DataSource",
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
"""Tenant-scoped alarm facts, formal occurrences, and same-cycle revision evidence.
|
||||
|
||||
Boundary: stores fact rows and the current handling projection. Claim, progress,
|
||||
and close decisions live in the handling service; this module does not notify
|
||||
or count escalation windows. Depends on M05 inputs, mapping versions, and rule versions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
String,
|
||||
UniqueConstraint,
|
||||
func,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from watchman.models.base import Base
|
||||
|
||||
# Status values are stored for the later handling slice. S1 only inserts pending.
|
||||
ALARM_STATUS_PENDING = "pending"
|
||||
ALARM_STATUS_PROCESSING = "processing"
|
||||
ALARM_STATUS_CLOSED = "closed"
|
||||
ALARM_STATUSES = (
|
||||
ALARM_STATUS_PENDING,
|
||||
ALARM_STATUS_PROCESSING,
|
||||
ALARM_STATUS_CLOSED,
|
||||
)
|
||||
|
||||
# D33 close results. These two literals are the whole set.
|
||||
ALARM_CLOSE_RESOLVED = "resolved"
|
||||
ALARM_CLOSE_FALSE_POSITIVE = "false_positive"
|
||||
ALARM_CLOSE_RESULTS = (
|
||||
ALARM_CLOSE_RESOLVED,
|
||||
ALARM_CLOSE_FALSE_POSITIVE,
|
||||
)
|
||||
|
||||
# GUARD: handling scope must name at least one subject. This layout is an
|
||||
# implementation assumption, not a new confirmed authorization model.
|
||||
_SCOPE_SQL = (
|
||||
"jsonb_typeof(handling_scope) = 'object' "
|
||||
"AND NOT jsonb_exists(handling_scope, 'all_tenant') "
|
||||
"AND jsonb_typeof(handling_scope -> 'principals') = 'array' "
|
||||
"AND jsonb_array_length(handling_scope -> 'principals') >= 1"
|
||||
)
|
||||
|
||||
|
||||
class Alarm(Base):
|
||||
"""One bounded alarm for a structured subject, cycle, and independent event.
|
||||
|
||||
Mutable for occurrence counters, last-seen time, and the handling projection.
|
||||
Status, handler, and close columns move only through the handling transition
|
||||
function; a direct update is rejected. Merge identity is the structured key,
|
||||
never message text. Writers must hold the subject advisory lock.
|
||||
"""
|
||||
|
||||
__tablename__ = "alarms"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"module_key",
|
||||
"scenario_key",
|
||||
"mapped_input_id",
|
||||
"cycle_key",
|
||||
"event_key",
|
||||
name="uq_alarms_structured_merge_key",
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('pending', 'processing', 'closed')",
|
||||
name="ck_alarms_status",
|
||||
),
|
||||
CheckConstraint(
|
||||
"close_result IS NULL OR close_result IN ('resolved', 'false_positive')",
|
||||
name="ck_alarms_close_result",
|
||||
),
|
||||
CheckConstraint(
|
||||
"status <> 'pending' OR current_handler IS NULL",
|
||||
name="ck_alarms_pending_unassigned",
|
||||
),
|
||||
CheckConstraint(
|
||||
"status <> 'processing' OR current_handler IS NOT NULL",
|
||||
name="ck_alarms_processing_handler",
|
||||
),
|
||||
CheckConstraint("occurrence_count >= 1", name="ck_alarms_occurrence_count"),
|
||||
CheckConstraint("snapshot_version_no >= 1", name="ck_alarms_snapshot_version"),
|
||||
CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarms_module_key"),
|
||||
CheckConstraint("char_length(btrim(scenario_key)) > 0", name="ck_alarms_scenario_key"),
|
||||
CheckConstraint("char_length(btrim(scenario_name)) > 0", name="ck_alarms_scenario_name"),
|
||||
CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarms_cycle_key"),
|
||||
CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarms_event_key"),
|
||||
CheckConstraint("last_occurred_at >= first_occurred_at", name="ck_alarms_occurred_order"),
|
||||
CheckConstraint(
|
||||
"previous_alarm_id IS NULL OR previous_alarm_id <> id",
|
||||
name="ck_alarms_previous_not_self",
|
||||
),
|
||||
CheckConstraint(_SCOPE_SQL, name="ck_alarms_handling_scope"),
|
||||
Index("ix_alarms_previous_alarm_id", "previous_alarm_id"),
|
||||
Index(
|
||||
"ix_alarms_subject_opened",
|
||||
"tenant_id",
|
||||
"module_key",
|
||||
"scenario_key",
|
||||
"mapped_input_id",
|
||||
"opened_at",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=text("'pending'")
|
||||
)
|
||||
current_handler: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
claimed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
closed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
close_result: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
occurrence_count: Mapped[int] = mapped_column(
|
||||
Integer, nullable=False, server_default=text("1")
|
||||
)
|
||||
first_occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
last_occurred_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
previous_alarm_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||
nullable=True,
|
||||
)
|
||||
mapped_input_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapped_inputs.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
rule_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
module_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
scenario_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
scenario_name: Mapped[str] = mapped_column(String(256), nullable=False)
|
||||
handling_scope: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
|
||||
cycle_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
event_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
opened_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class AlarmOccurrence(Base):
|
||||
"""One formal abnormal fact. Replays of the same identity return this row.
|
||||
|
||||
Append-only: the cited input revision is the original FAIL and must not be
|
||||
rewritten when a later same-cycle correction arrives. Not safe to update.
|
||||
"""
|
||||
|
||||
__tablename__ = "alarm_occurrences"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"mapped_input_revision_id",
|
||||
"mapping_version_id",
|
||||
"rule_version_id",
|
||||
"snapshot_id",
|
||||
"cycle_key",
|
||||
"event_key",
|
||||
"observed_at",
|
||||
name="uq_alarm_occurrences_formal_identity",
|
||||
),
|
||||
CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_occurrences_snapshot_version"),
|
||||
CheckConstraint("char_length(btrim(module_key)) > 0", name="ck_alarm_occurrences_module_key"),
|
||||
CheckConstraint(
|
||||
"char_length(btrim(scenario_key)) > 0",
|
||||
name="ck_alarm_occurrences_scenario_key",
|
||||
),
|
||||
CheckConstraint(
|
||||
"char_length(btrim(scenario_name)) > 0",
|
||||
name="ck_alarm_occurrences_scenario_name",
|
||||
),
|
||||
CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_occurrences_cycle_key"),
|
||||
CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_occurrences_event_key"),
|
||||
CheckConstraint(_SCOPE_SQL, name="ck_alarm_occurrences_handling_scope"),
|
||||
Index("ix_alarm_occurrences_alarm_id", "alarm_id"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapped_input_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapped_inputs.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapped_input_revision_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
rule_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
module_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
scenario_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
scenario_name: Mapped[str] = mapped_column(String(256), nullable=False)
|
||||
handling_scope: Mapped[dict[str, Any]] = mapped_column(JSONB, nullable=False)
|
||||
cycle_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
event_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class AlarmRevisionEvidence(Base):
|
||||
"""Append-only same-cycle correction basis. It never opens an alarm.
|
||||
|
||||
Points at a later M05 revision while the original occurrence keeps the
|
||||
first FAIL revision. Not safe to update or delete.
|
||||
"""
|
||||
|
||||
__tablename__ = "alarm_revision_evidence"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"alarm_id",
|
||||
"mapped_input_revision_id",
|
||||
name="uq_alarm_revision_evidence_alarm_revision",
|
||||
),
|
||||
CheckConstraint(
|
||||
"snapshot_version_no >= 1",
|
||||
name="ck_alarm_revision_evidence_snapshot_version",
|
||||
),
|
||||
Index("ix_alarm_revision_evidence_alarm_id", "alarm_id"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
occurrence_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarm_occurrences.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapped_input_revision_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
recorded_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
@@ -0,0 +1,217 @@
|
||||
"""Append-only alarm handling history, command keys, and closed-repeat basis.
|
||||
|
||||
Boundary: stores what the handling service and the closed-repeat path append.
|
||||
It does not decide who may claim or close, and it does not store intents or
|
||||
escalation windows. Depends on alarm facts and the server tenant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, CheckConstraint, DateTime, ForeignKey, Identity, Index, Integer, String, UniqueConstraint, func, text
|
||||
from sqlalchemy.dialects.postgresql import UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from watchman.models.base import Base
|
||||
|
||||
HANDLING_CLAIM = "claim"
|
||||
HANDLING_PROGRESS = "progress"
|
||||
HANDLING_CLOSE = "close"
|
||||
HANDLING_COMMANDS = (
|
||||
HANDLING_CLAIM,
|
||||
HANDLING_PROGRESS,
|
||||
HANDLING_CLOSE,
|
||||
)
|
||||
|
||||
_COMMAND_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')
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
class AlarmHandlingEvent(Base):
|
||||
"""One handling step. Later steps are new rows; this row is not edited.
|
||||
|
||||
`seq` is the append order. Recorded time can tie, so readers order by `seq`.
|
||||
Not safe to update or delete. The alarm projection is a separate write.
|
||||
"""
|
||||
|
||||
__tablename__ = "alarm_handling_events"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"command IN ('claim', 'progress', 'close')",
|
||||
name="ck_alarm_handling_events_command",
|
||||
),
|
||||
CheckConstraint(
|
||||
"from_status IN ('pending', 'processing', 'closed')",
|
||||
name="ck_alarm_handling_events_from_status",
|
||||
),
|
||||
CheckConstraint(
|
||||
"to_status IN ('pending', 'processing', 'closed')",
|
||||
name="ck_alarm_handling_events_to_status",
|
||||
),
|
||||
CheckConstraint(
|
||||
"actor_role IN ('watchman-admin', 'watchman-operator')",
|
||||
name="ck_alarm_handling_events_actor_role",
|
||||
),
|
||||
CheckConstraint("char_length(btrim(actor_subject)) > 0", name="ck_alarm_handling_events_actor"),
|
||||
CheckConstraint("char_length(btrim(handler_subject)) > 0", name="ck_alarm_handling_events_handler"),
|
||||
CheckConstraint(_COMMAND_SHAPE, name="ck_alarm_handling_events_shape"),
|
||||
CheckConstraint(
|
||||
"evidence_ref IS NULL OR char_length(btrim(evidence_ref)) > 0",
|
||||
name="ck_alarm_handling_events_evidence_ref",
|
||||
),
|
||||
Index("ix_alarm_handling_events_alarm_id", "alarm_id", "seq"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
seq: Mapped[int] = mapped_column(BigInteger, Identity(), nullable=False)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
command: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
actor_subject: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
actor_role: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
handler_subject: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
from_status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
to_status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
note: Mapped[str | None] = mapped_column(String(2000), nullable=True)
|
||||
close_result: Mapped[str | None] = mapped_column(String(32), nullable=True)
|
||||
evidence_ref: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
recorded_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class AlarmHandlingCommand(Base):
|
||||
"""Idempotency record for one accepted handling command.
|
||||
|
||||
The same key with a different payload hash is a conflict, not a second
|
||||
effect. Not safe to update or delete.
|
||||
"""
|
||||
|
||||
__tablename__ = "alarm_handling_commands"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("tenant_id", "idempotency_key", name="uq_alarm_handling_commands_idem"),
|
||||
CheckConstraint(
|
||||
"command IN ('claim', 'progress', 'close')",
|
||||
name="ck_alarm_handling_commands_command",
|
||||
),
|
||||
CheckConstraint("char_length(btrim(idempotency_key)) > 0", name="ck_alarm_handling_commands_key"),
|
||||
CheckConstraint("payload_hash ~ '^[0-9a-f]{64}$'", name="ck_alarm_handling_commands_hash"),
|
||||
Index("ix_alarm_handling_commands_alarm_id", "alarm_id"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
event_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarm_handling_events.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
command: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
payload_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class AlarmClosedBasis(Base):
|
||||
"""Trace of a formal failure that arrived after the merge key was closed.
|
||||
|
||||
It does not open an alarm, reopen the closed one, or replace the original
|
||||
FAIL occurrence. Not safe to update or delete.
|
||||
"""
|
||||
|
||||
__tablename__ = "alarm_closed_basis"
|
||||
__table_args__ = (
|
||||
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",
|
||||
),
|
||||
CheckConstraint("snapshot_version_no >= 1", name="ck_alarm_closed_basis_snapshot_version"),
|
||||
CheckConstraint("char_length(btrim(cycle_key)) > 0", name="ck_alarm_closed_basis_cycle_key"),
|
||||
CheckConstraint("char_length(btrim(event_key)) > 0", name="ck_alarm_closed_basis_event_key"),
|
||||
Index("ix_alarm_closed_basis_alarm_id", "alarm_id"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
alarm_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarms.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
original_occurrence_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("alarm_occurrences.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapped_input_revision_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapped_input_revisions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
rule_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
snapshot_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
|
||||
snapshot_version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
cycle_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
event_key: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
observed_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
recorded_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
@@ -0,0 +1,733 @@
|
||||
"""Forward-only alarm handling: claim, progress, and close.
|
||||
|
||||
Boundary: one current handler, append-only history, and a close-validity read.
|
||||
It does not register permission nodes, open routes, write intents, retract
|
||||
messages, or touch escalation windows. Depends on alarm facts and the server tenant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.auth.access import ROLE_ADMIN, ROLE_OPERATOR
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from watchman.models.alarm import (
|
||||
ALARM_CLOSE_RESULTS,
|
||||
ALARM_STATUS_CLOSED,
|
||||
ALARM_STATUS_PENDING,
|
||||
ALARM_STATUS_PROCESSING,
|
||||
Alarm,
|
||||
)
|
||||
from watchman.models.alarm_handling import (
|
||||
HANDLING_CLAIM,
|
||||
HANDLING_CLOSE,
|
||||
HANDLING_PROGRESS,
|
||||
AlarmHandlingCommand,
|
||||
AlarmHandlingEvent,
|
||||
)
|
||||
from watchman.services.alarms import lock_alarm_subject
|
||||
|
||||
# GUARD: status columns are not assigned here. alarm_apply_transition is the writer.
|
||||
# GUARD: do not invent a permission node. Actor checks use the current handler and the three roles.
|
||||
_NOTE_MAX = 2000
|
||||
_REF_MAX = 512
|
||||
_SUBJECT_MAX = 128
|
||||
_TRANSITION_SQL = """
|
||||
SELECT alarm_apply_transition(
|
||||
:alarm_id, :status, :handler, :claimed_at, :closed_at, :close_result
|
||||
)
|
||||
"""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HandlingActor:
|
||||
"""Who is acting. `subject` must match a scope subject; roles are the three existing names."""
|
||||
|
||||
subject: str
|
||||
roles: tuple[str, ...]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HandlingResult:
|
||||
"""The handling event this command created or replayed.
|
||||
|
||||
`status` and `close_result` come from that event, which is the original
|
||||
command outcome. A later command does not rewrite this result.
|
||||
"""
|
||||
|
||||
alarm_id: uuid.UUID
|
||||
event_id: uuid.UUID
|
||||
command: str
|
||||
status: str
|
||||
current_handler: str | None
|
||||
close_result: str | None
|
||||
replayed: bool
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CloseValidity:
|
||||
"""Whether unexecuted intents bound to this alarm should be treated as invalid.
|
||||
|
||||
Derived from the terminal status. This is not an intent row and not a window.
|
||||
"""
|
||||
|
||||
alarm_id: uuid.UUID
|
||||
status: str
|
||||
unexecuted_intents_should_invalidate: bool
|
||||
|
||||
|
||||
def _tenant_id() -> str:
|
||||
# GUARD: tenant_id comes only from server settings, never from the caller.
|
||||
return get_settings().tenant_id
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _require_key(idempotency_key: str | None) -> str:
|
||||
"""Require the command key. The same key with another payload conflicts later."""
|
||||
if idempotency_key is None or not str(idempotency_key).strip():
|
||||
raise ValidationError(
|
||||
"x-idempotency-key is required",
|
||||
details={"field": "x-idempotency-key", "reason": "idempotency_key_required"},
|
||||
)
|
||||
return str(idempotency_key).strip()[:128]
|
||||
|
||||
|
||||
def _normalize_actor(actor: HandlingActor) -> HandlingActor:
|
||||
"""Canonicalize the actor so the idempotency hash does not depend on role order."""
|
||||
if not isinstance(actor, HandlingActor) or not isinstance(actor.subject, str):
|
||||
raise ValidationError("Invalid alarm actor", details={"reason": "actor_invalid", "field": "actor"})
|
||||
subject = actor.subject.strip()
|
||||
if not subject or len(subject) > _SUBJECT_MAX or any(char in subject for char in "\r\n\x00"):
|
||||
raise ValidationError(
|
||||
"Invalid alarm actor",
|
||||
details={"reason": "actor_subject_invalid", "field": "actor"},
|
||||
)
|
||||
if isinstance(actor.roles, str) or not isinstance(actor.roles, tuple):
|
||||
raise ValidationError(
|
||||
"Invalid alarm actor",
|
||||
details={"reason": "actor_role_invalid", "field": "actor"},
|
||||
)
|
||||
cleaned: list[str] = []
|
||||
for role in actor.roles:
|
||||
if not isinstance(role, str):
|
||||
raise ValidationError(
|
||||
"Invalid alarm actor",
|
||||
details={"reason": "actor_role_invalid", "field": "actor"},
|
||||
)
|
||||
value = role.strip()
|
||||
if not value or len(value) > 64 or any(char in value for char in "\r\n\x00"):
|
||||
raise ValidationError(
|
||||
"Invalid alarm actor",
|
||||
details={"reason": "actor_role_invalid", "field": "actor"},
|
||||
)
|
||||
cleaned.append(value)
|
||||
return HandlingActor(subject=subject, roles=tuple(sorted(set(cleaned))))
|
||||
|
||||
|
||||
def _deciding_role(actor: HandlingActor) -> str:
|
||||
"""Pick admin over operator. Viewer and unknown roles cannot handle.
|
||||
|
||||
Raises ForbiddenError with no permission node. S3 must not treat that as a
|
||||
registered alarm permission.
|
||||
"""
|
||||
if ROLE_ADMIN in actor.roles:
|
||||
return ROLE_ADMIN
|
||||
if ROLE_OPERATOR in actor.roles:
|
||||
return ROLE_OPERATOR
|
||||
raise ForbiddenError("Alarm handling is limited to operator and admin")
|
||||
|
||||
|
||||
def _require_note(value: object, reason: str) -> str:
|
||||
if not isinstance(value, str):
|
||||
raise ValidationError("A handling note is required", details={"reason": reason, "field": "note"})
|
||||
cleaned = value.strip()
|
||||
if not cleaned:
|
||||
raise ValidationError("A handling note is required", details={"reason": reason, "field": "note"})
|
||||
if len(cleaned) > _NOTE_MAX or "\x00" in cleaned:
|
||||
raise ValidationError("A handling note is invalid", details={"reason": "note_invalid", "field": "note"})
|
||||
return cleaned
|
||||
|
||||
|
||||
def _require_ref(value: object) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
if not isinstance(value, str):
|
||||
raise ValidationError(
|
||||
"Evidence reference is invalid",
|
||||
details={"reason": "evidence_ref_invalid", "field": "evidence_ref"},
|
||||
)
|
||||
cleaned = value.strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
if len(cleaned) > _REF_MAX or "\x00" in cleaned:
|
||||
raise ValidationError(
|
||||
"Evidence reference is invalid",
|
||||
details={"reason": "evidence_ref_invalid", "field": "evidence_ref"},
|
||||
)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _require_result(value: object) -> str:
|
||||
if not isinstance(value, str) or value.strip() not in ALARM_CLOSE_RESULTS:
|
||||
raise ValidationError(
|
||||
"Close result must be resolved or false_positive",
|
||||
details={"reason": "close_result_invalid", "field": "result"},
|
||||
)
|
||||
return value.strip()
|
||||
|
||||
|
||||
def _payload_hash(payload: dict[str, Any]) -> str:
|
||||
encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
||||
return hashlib.sha256(encoded.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _command_payload(
|
||||
command: str,
|
||||
alarm_id: uuid.UUID,
|
||||
actor: HandlingActor,
|
||||
*,
|
||||
note: str | None = None,
|
||||
close_result: str | None = None,
|
||||
evidence_ref: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"alarm_id": str(alarm_id),
|
||||
"command": command,
|
||||
"roles": list(actor.roles),
|
||||
"subject": actor.subject,
|
||||
}
|
||||
if command != HANDLING_CLAIM:
|
||||
payload["evidence_ref"] = evidence_ref
|
||||
payload["note"] = note
|
||||
if command == HANDLING_CLOSE:
|
||||
payload["close_result"] = close_result
|
||||
return payload
|
||||
|
||||
|
||||
def _subject_in_scope(alarm: Alarm, subject: str) -> bool:
|
||||
"""Match a named subject on the snapshot. A role entry alone does not grant handling.
|
||||
|
||||
NOTE(ai): this subject match is the same implementation assumption as the fact
|
||||
scope guard. It is not a new confirmed authorization model.
|
||||
"""
|
||||
scope = alarm.handling_scope
|
||||
if not isinstance(scope, dict):
|
||||
return False
|
||||
principals = scope.get("principals")
|
||||
if not isinstance(principals, list):
|
||||
return False
|
||||
return any(
|
||||
isinstance(item, dict) and item.get("kind") == "subject" and item.get("value") == subject
|
||||
for item in principals
|
||||
)
|
||||
|
||||
|
||||
def _lock_alarm(session: Session, alarm_id: uuid.UUID) -> Alarm:
|
||||
"""Lock the subject, then the alarm row, in the same order as fact writes."""
|
||||
if not isinstance(alarm_id, uuid.UUID):
|
||||
raise NotFoundError("Alarm not found")
|
||||
tenant_id = _tenant_id()
|
||||
alarm = session.get(Alarm, alarm_id)
|
||||
if alarm is None or alarm.tenant_id != tenant_id:
|
||||
raise NotFoundError("Alarm not found")
|
||||
lock_alarm_subject(
|
||||
session,
|
||||
module_key=alarm.module_key,
|
||||
scenario_key=alarm.scenario_key,
|
||||
mapped_input_id=alarm.mapped_input_id,
|
||||
)
|
||||
locked = session.scalar(
|
||||
select(Alarm)
|
||||
.where(Alarm.id == alarm_id, Alarm.tenant_id == tenant_id)
|
||||
.with_for_update()
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
if locked is None:
|
||||
raise NotFoundError("Alarm not found")
|
||||
return locked
|
||||
|
||||
|
||||
def _find_command(session: Session, key: str) -> AlarmHandlingCommand | None:
|
||||
return session.scalar(
|
||||
select(AlarmHandlingCommand)
|
||||
.where(
|
||||
AlarmHandlingCommand.tenant_id == _tenant_id(),
|
||||
AlarmHandlingCommand.idempotency_key == key,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
|
||||
|
||||
def _first_event(session: Session, alarm_id: uuid.UUID, command: str) -> AlarmHandlingEvent | None:
|
||||
return session.scalar(
|
||||
select(AlarmHandlingEvent)
|
||||
.where(
|
||||
AlarmHandlingEvent.tenant_id == _tenant_id(),
|
||||
AlarmHandlingEvent.alarm_id == alarm_id,
|
||||
AlarmHandlingEvent.command == command,
|
||||
)
|
||||
.order_by(AlarmHandlingEvent.seq.asc())
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
|
||||
def _result_from_event(event: AlarmHandlingEvent, *, replayed: bool) -> HandlingResult:
|
||||
return HandlingResult(
|
||||
alarm_id=event.alarm_id,
|
||||
event_id=event.id,
|
||||
command=event.command,
|
||||
status=event.to_status,
|
||||
current_handler=event.handler_subject,
|
||||
close_result=event.close_result,
|
||||
replayed=replayed,
|
||||
)
|
||||
|
||||
|
||||
def _replay(session: Session, existing: AlarmHandlingCommand, digest: str) -> HandlingResult:
|
||||
if existing.payload_hash != digest:
|
||||
raise ConflictError(
|
||||
"Idempotency key was already used with a different payload",
|
||||
details={"reason": "idempotency_payload_mismatch"},
|
||||
)
|
||||
event = session.get(AlarmHandlingEvent, existing.event_id)
|
||||
if event is None or event.tenant_id != _tenant_id():
|
||||
raise ConflictError(
|
||||
"Handling history for this command is missing",
|
||||
details={"reason": "handling_history_missing"},
|
||||
)
|
||||
return _result_from_event(event, replayed=True)
|
||||
|
||||
|
||||
def _recover_command(session: Session, key: str, digest: str) -> HandlingResult:
|
||||
session.expire_all()
|
||||
existing = _find_command(session, key)
|
||||
if existing is None:
|
||||
raise
|
||||
return _replay(session, existing, digest)
|
||||
|
||||
|
||||
def _authorize(alarm: Alarm, actor: HandlingActor) -> str:
|
||||
if not _subject_in_scope(alarm, actor.subject):
|
||||
raise NotFoundError("Alarm not found")
|
||||
return _deciding_role(actor)
|
||||
|
||||
|
||||
def _apply_transition(
|
||||
session: Session,
|
||||
alarm: Alarm,
|
||||
*,
|
||||
status: str,
|
||||
handler: str,
|
||||
claimed_at: datetime | None,
|
||||
closed_at: datetime | None,
|
||||
close_result: str | None,
|
||||
) -> None:
|
||||
"""Move the projection through the database function, then reload it.
|
||||
|
||||
The ORM must not emit an UPDATE of status, handler, or close columns.
|
||||
"""
|
||||
session.execute(
|
||||
text(_TRANSITION_SQL),
|
||||
{
|
||||
"alarm_id": alarm.id,
|
||||
"status": status,
|
||||
"handler": handler,
|
||||
"claimed_at": claimed_at,
|
||||
"closed_at": closed_at,
|
||||
"close_result": close_result,
|
||||
},
|
||||
)
|
||||
session.expire(alarm)
|
||||
session.refresh(alarm)
|
||||
|
||||
|
||||
def _insert_command(
|
||||
session: Session,
|
||||
*,
|
||||
alarm_id: uuid.UUID,
|
||||
event_id: uuid.UUID,
|
||||
command: str,
|
||||
key: str,
|
||||
digest: str,
|
||||
) -> None:
|
||||
session.add(
|
||||
AlarmHandlingCommand(
|
||||
tenant_id=_tenant_id(),
|
||||
alarm_id=alarm_id,
|
||||
event_id=event_id,
|
||||
command=command,
|
||||
idempotency_key=key,
|
||||
payload_hash=digest,
|
||||
created_at=_now(),
|
||||
)
|
||||
)
|
||||
session.flush()
|
||||
|
||||
|
||||
def _bind_existing(
|
||||
session: Session,
|
||||
event: AlarmHandlingEvent,
|
||||
*,
|
||||
command: str,
|
||||
key: str,
|
||||
digest: str,
|
||||
) -> HandlingResult:
|
||||
"""Point a new key at an existing event without a second history row."""
|
||||
try:
|
||||
with session.begin_nested():
|
||||
_insert_command(
|
||||
session,
|
||||
alarm_id=event.alarm_id,
|
||||
event_id=event.id,
|
||||
command=command,
|
||||
key=key,
|
||||
digest=digest,
|
||||
)
|
||||
except IntegrityError:
|
||||
return _recover_command(session, key, digest)
|
||||
return _result_from_event(event, replayed=True)
|
||||
|
||||
|
||||
def _new_event(
|
||||
alarm: Alarm,
|
||||
*,
|
||||
command: str,
|
||||
actor: HandlingActor,
|
||||
role: str,
|
||||
handler_subject: str,
|
||||
from_status: str,
|
||||
to_status: str,
|
||||
note: str | None,
|
||||
close_result: str | None,
|
||||
evidence_ref: str | None,
|
||||
) -> AlarmHandlingEvent:
|
||||
return AlarmHandlingEvent(
|
||||
tenant_id=_tenant_id(),
|
||||
alarm_id=alarm.id,
|
||||
command=command,
|
||||
actor_subject=actor.subject,
|
||||
actor_role=role,
|
||||
handler_subject=handler_subject,
|
||||
from_status=from_status,
|
||||
to_status=to_status,
|
||||
note=note,
|
||||
close_result=close_result,
|
||||
evidence_ref=evidence_ref,
|
||||
recorded_at=_now(),
|
||||
)
|
||||
|
||||
|
||||
def _start(
|
||||
session: Session,
|
||||
*,
|
||||
alarm_id: uuid.UUID,
|
||||
actor: HandlingActor,
|
||||
idempotency_key: str | None,
|
||||
command: str,
|
||||
note: str | None = None,
|
||||
close_result: str | None = None,
|
||||
evidence_ref: str | None = None,
|
||||
) -> tuple[HandlingResult | None, Alarm, HandlingActor, str, str]:
|
||||
key = _require_key(idempotency_key)
|
||||
normalized = _normalize_actor(actor)
|
||||
digest = _payload_hash(
|
||||
_command_payload(
|
||||
command,
|
||||
alarm_id,
|
||||
normalized,
|
||||
note=note,
|
||||
close_result=close_result,
|
||||
evidence_ref=evidence_ref,
|
||||
)
|
||||
)
|
||||
alarm = _lock_alarm(session, alarm_id)
|
||||
existing = _find_command(session, key)
|
||||
if existing is not None:
|
||||
return _replay(session, existing, digest), alarm, normalized, key, digest
|
||||
return None, alarm, normalized, key, digest
|
||||
|
||||
|
||||
def claim_alarm(
|
||||
session: Session,
|
||||
*,
|
||||
alarm_id: uuid.UUID,
|
||||
actor: HandlingActor,
|
||||
idempotency_key: str | None,
|
||||
) -> HandlingResult:
|
||||
"""Claim a pending alarm for one in-scope operator or admin.
|
||||
|
||||
A second claim by the same handler replays the original event. A different
|
||||
handler gets a conflict and does not replace the current one. Closed alarms
|
||||
are not reopened. The same idempotency key with a different actor conflicts.
|
||||
Raises NotFoundError when the alarm is missing or outside the snapshot
|
||||
subjects, and ForbiddenError when the actor is not an operator or admin.
|
||||
"""
|
||||
replay, alarm, normalized, key, digest = _start(
|
||||
session,
|
||||
alarm_id=alarm_id,
|
||||
actor=actor,
|
||||
idempotency_key=idempotency_key,
|
||||
command=HANDLING_CLAIM,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
role = _authorize(alarm, normalized)
|
||||
if alarm.status == ALARM_STATUS_PROCESSING and alarm.current_handler == normalized.subject:
|
||||
event = _first_event(session, alarm.id, HANDLING_CLAIM)
|
||||
if event is None:
|
||||
raise ConflictError(
|
||||
"Claim history is missing",
|
||||
details={"reason": "handling_history_missing"},
|
||||
)
|
||||
return _bind_existing(session, event, command=HANDLING_CLAIM, key=key, digest=digest)
|
||||
if alarm.status == ALARM_STATUS_PROCESSING:
|
||||
raise ConflictError("Alarm already has a handler", details={"reason": "already_claimed"})
|
||||
if alarm.status != ALARM_STATUS_PENDING:
|
||||
raise ConflictError(
|
||||
"Alarm cannot be claimed from this status",
|
||||
details={"reason": "illegal_transition"},
|
||||
)
|
||||
claimed_at = _now()
|
||||
event = _new_event(
|
||||
alarm,
|
||||
command=HANDLING_CLAIM,
|
||||
actor=normalized,
|
||||
role=role,
|
||||
handler_subject=normalized.subject,
|
||||
from_status=ALARM_STATUS_PENDING,
|
||||
to_status=ALARM_STATUS_PROCESSING,
|
||||
note=None,
|
||||
close_result=None,
|
||||
evidence_ref=None,
|
||||
)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
_apply_transition(
|
||||
session,
|
||||
alarm,
|
||||
status=ALARM_STATUS_PROCESSING,
|
||||
handler=normalized.subject,
|
||||
claimed_at=claimed_at,
|
||||
closed_at=None,
|
||||
close_result=None,
|
||||
)
|
||||
session.add(event)
|
||||
session.flush()
|
||||
_insert_command(
|
||||
session,
|
||||
alarm_id=alarm.id,
|
||||
event_id=event.id,
|
||||
command=HANDLING_CLAIM,
|
||||
key=key,
|
||||
digest=digest,
|
||||
)
|
||||
except IntegrityError:
|
||||
return _recover_command(session, key, digest)
|
||||
return _result_from_event(event, replayed=False)
|
||||
|
||||
|
||||
def append_progress(
|
||||
session: Session,
|
||||
*,
|
||||
alarm_id: uuid.UUID,
|
||||
actor: HandlingActor,
|
||||
note: str,
|
||||
idempotency_key: str | None,
|
||||
evidence_ref: str | None = None,
|
||||
) -> HandlingResult:
|
||||
"""Append one progress note without changing older notes or the original FAIL.
|
||||
|
||||
Only the current handler can append, and only while the alarm is processing.
|
||||
A repeated key returns the same event. A repeated key with another note
|
||||
conflicts. Raises the same not-found and forbidden errors as claim, or
|
||||
ConflictError when the status or handler does not allow a note.
|
||||
"""
|
||||
cleaned = _require_note(note, "progress_note_required")
|
||||
reference = _require_ref(evidence_ref)
|
||||
replay, alarm, normalized, key, digest = _start(
|
||||
session,
|
||||
alarm_id=alarm_id,
|
||||
actor=actor,
|
||||
idempotency_key=idempotency_key,
|
||||
command=HANDLING_PROGRESS,
|
||||
note=cleaned,
|
||||
evidence_ref=reference,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
role = _authorize(alarm, normalized)
|
||||
if alarm.status != ALARM_STATUS_PROCESSING:
|
||||
raise ConflictError(
|
||||
"Progress can be added only while the alarm is processing",
|
||||
details={"reason": "illegal_transition"},
|
||||
)
|
||||
if alarm.current_handler != normalized.subject:
|
||||
raise ConflictError(
|
||||
"Only the current handler can append progress",
|
||||
details={"reason": "not_current_handler"},
|
||||
)
|
||||
handler = alarm.current_handler
|
||||
assert handler is not None
|
||||
event = _new_event(
|
||||
alarm,
|
||||
command=HANDLING_PROGRESS,
|
||||
actor=normalized,
|
||||
role=role,
|
||||
handler_subject=handler,
|
||||
from_status=ALARM_STATUS_PROCESSING,
|
||||
to_status=ALARM_STATUS_PROCESSING,
|
||||
note=cleaned,
|
||||
close_result=None,
|
||||
evidence_ref=reference,
|
||||
)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
alarm.updated_at = _now()
|
||||
session.add(event)
|
||||
session.flush()
|
||||
_insert_command(
|
||||
session,
|
||||
alarm_id=alarm.id,
|
||||
event_id=event.id,
|
||||
command=HANDLING_PROGRESS,
|
||||
key=key,
|
||||
digest=digest,
|
||||
)
|
||||
except IntegrityError:
|
||||
return _recover_command(session, key, digest)
|
||||
return _result_from_event(event, replayed=False)
|
||||
|
||||
|
||||
def close_alarm(
|
||||
session: Session,
|
||||
*,
|
||||
alarm_id: uuid.UUID,
|
||||
actor: HandlingActor,
|
||||
result: str,
|
||||
note: str,
|
||||
idempotency_key: str | None,
|
||||
evidence_ref: str | None = None,
|
||||
) -> HandlingResult:
|
||||
"""Close a processing alarm as resolved or false_positive.
|
||||
|
||||
The current handler or an in-scope admin may close. Pending alarms cannot
|
||||
be closed, and a closed alarm is not reopened. The note is required. An
|
||||
exact repeat returns the terminal event; a different result or note conflicts.
|
||||
Raises NotFoundError, ForbiddenError, ValidationError, or ConflictError.
|
||||
"""
|
||||
close_result = _require_result(result)
|
||||
cleaned = _require_note(note, "close_note_required")
|
||||
reference = _require_ref(evidence_ref)
|
||||
replay, alarm, normalized, key, digest = _start(
|
||||
session,
|
||||
alarm_id=alarm_id,
|
||||
actor=actor,
|
||||
idempotency_key=idempotency_key,
|
||||
command=HANDLING_CLOSE,
|
||||
note=cleaned,
|
||||
close_result=close_result,
|
||||
evidence_ref=reference,
|
||||
)
|
||||
if replay is not None:
|
||||
return replay
|
||||
role = _authorize(alarm, normalized)
|
||||
if alarm.status == ALARM_STATUS_CLOSED:
|
||||
terminal = _first_event(session, alarm.id, HANDLING_CLOSE)
|
||||
same_terminal = (
|
||||
terminal is not None
|
||||
and terminal.actor_subject == normalized.subject
|
||||
and terminal.close_result == close_result
|
||||
and terminal.note == cleaned
|
||||
and terminal.evidence_ref == reference
|
||||
)
|
||||
if same_terminal and terminal is not None:
|
||||
return _bind_existing(session, terminal, command=HANDLING_CLOSE, key=key, digest=digest)
|
||||
raise ConflictError("Alarm is already closed", details={"reason": "already_closed"})
|
||||
if alarm.status != ALARM_STATUS_PROCESSING:
|
||||
raise ConflictError(
|
||||
"Alarm cannot be closed from this status",
|
||||
details={"reason": "illegal_transition"},
|
||||
)
|
||||
if alarm.current_handler != normalized.subject and role != ROLE_ADMIN:
|
||||
raise ConflictError(
|
||||
"Only the current handler or an admin can close this alarm",
|
||||
details={"reason": "not_current_handler"},
|
||||
)
|
||||
handler = alarm.current_handler
|
||||
if handler is None or alarm.claimed_at is None:
|
||||
raise ConflictError(
|
||||
"Processing alarm has no claim",
|
||||
details={"reason": "handling_history_missing"},
|
||||
)
|
||||
closed_at = _now()
|
||||
if closed_at < alarm.claimed_at:
|
||||
closed_at = alarm.claimed_at
|
||||
event = _new_event(
|
||||
alarm,
|
||||
command=HANDLING_CLOSE,
|
||||
actor=normalized,
|
||||
role=role,
|
||||
handler_subject=handler,
|
||||
from_status=ALARM_STATUS_PROCESSING,
|
||||
to_status=ALARM_STATUS_CLOSED,
|
||||
note=cleaned,
|
||||
close_result=close_result,
|
||||
evidence_ref=reference,
|
||||
)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
_apply_transition(
|
||||
session,
|
||||
alarm,
|
||||
status=ALARM_STATUS_CLOSED,
|
||||
handler=handler,
|
||||
claimed_at=alarm.claimed_at,
|
||||
closed_at=closed_at,
|
||||
close_result=close_result,
|
||||
)
|
||||
session.add(event)
|
||||
session.flush()
|
||||
_insert_command(
|
||||
session,
|
||||
alarm_id=alarm.id,
|
||||
event_id=event.id,
|
||||
command=HANDLING_CLOSE,
|
||||
key=key,
|
||||
digest=digest,
|
||||
)
|
||||
except IntegrityError:
|
||||
return _recover_command(session, key, digest)
|
||||
return _result_from_event(event, replayed=False)
|
||||
|
||||
|
||||
def close_validity(session: Session, alarm_id: uuid.UUID) -> CloseValidity:
|
||||
"""Report whether unexecuted intents for this alarm should be treated as invalid.
|
||||
|
||||
D32 is a read of ``closed``. This does not insert an intent, retract an
|
||||
accepted message, or read or clear an escalation window.
|
||||
Raises NotFoundError when the server tenant cannot see the alarm.
|
||||
"""
|
||||
# GUARD: do not write intent, notification, or window rows from this read.
|
||||
if not isinstance(alarm_id, uuid.UUID):
|
||||
raise NotFoundError("Alarm not found")
|
||||
alarm = session.get(Alarm, alarm_id)
|
||||
if alarm is None or alarm.tenant_id != _tenant_id():
|
||||
raise NotFoundError("Alarm not found")
|
||||
return CloseValidity(
|
||||
alarm_id=alarm.id,
|
||||
status=alarm.status,
|
||||
unexecuted_intents_should_invalidate=alarm.status == ALARM_STATUS_CLOSED,
|
||||
)
|
||||
@@ -0,0 +1,403 @@
|
||||
"""Scoped alarm reads for the list, detail, basis, history, and close-validity APIs.
|
||||
|
||||
Boundary: returns alarms whose synthetic snapshot names the caller as a subject.
|
||||
It does not claim, close, notify, or treat a role entry as a tenant-wide grant.
|
||||
Depends on alarm facts, handling history, and the server tenant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import asc, desc, func, select, text
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.core.errors import NotFoundError, ValidationError
|
||||
from watchman.models.alarm import ALARM_STATUSES, Alarm, AlarmOccurrence, AlarmRevisionEvidence
|
||||
from watchman.models.alarm_handling import AlarmClosedBasis, AlarmHandlingEvent
|
||||
from watchman.models.mapping import MappedInput
|
||||
from watchman.services.alarm_handling import close_validity
|
||||
|
||||
# NOTE(ai): subject match follows the S1 snapshot layout. It is not a new auth model.
|
||||
# GUARD: a missing subject must yield no rows. Do not drop this clause for admin or operator.
|
||||
_PAGE_SIZE_MAX = 100
|
||||
_KEY_MAX = 128
|
||||
_NAME_MAX = 256
|
||||
_SORT = {
|
||||
"opened_at": Alarm.opened_at,
|
||||
"updated_at": Alarm.updated_at,
|
||||
"first_occurred_at": Alarm.first_occurred_at,
|
||||
"last_occurred_at": Alarm.last_occurred_at,
|
||||
"status": Alarm.status,
|
||||
"module_key": Alarm.module_key,
|
||||
"scenario_key": Alarm.scenario_key,
|
||||
"scenario_name": Alarm.scenario_name,
|
||||
"occurrence_count": Alarm.occurrence_count,
|
||||
}
|
||||
_SORT_DEFAULT = "last_occurred_at"
|
||||
|
||||
|
||||
def scope_subject(value: str | None) -> str | None:
|
||||
"""Return a snapshot subject, or None when the session has none.
|
||||
|
||||
None means the caller has no scope source. Callers must not replace that
|
||||
with every alarm in the tenant. Length is not trimmed.
|
||||
"""
|
||||
if not isinstance(value, str):
|
||||
return None
|
||||
cleaned = value.strip()
|
||||
if not cleaned or any(char in cleaned for char in "\r\n\x00"):
|
||||
return None
|
||||
return cleaned
|
||||
|
||||
|
||||
def _tenant_id() -> str:
|
||||
# GUARD: tenant_id comes only from server settings, never from the caller.
|
||||
return get_settings().tenant_id
|
||||
|
||||
|
||||
def _isoformat(value: datetime | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
return value.astimezone(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def _parse_alarm_id(alarm_id: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(alarm_id)
|
||||
except (TypeError, ValueError, AttributeError) as exc:
|
||||
raise NotFoundError("Alarm not found") from exc
|
||||
|
||||
|
||||
def _scope_clause(subject: str) -> Any:
|
||||
"""Match a named subject. A role entry in the same array does not qualify."""
|
||||
return text(
|
||||
"EXISTS (SELECT 1 FROM jsonb_array_elements(alarms.handling_scope -> 'principals') AS elem "
|
||||
"WHERE elem ->> 'kind' = 'subject' AND elem ->> 'value' = :scope_subject)"
|
||||
).bindparams(scope_subject=subject)
|
||||
|
||||
|
||||
def _aware(value: datetime | None, field: str) -> datetime | None:
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None or value.utcoffset() is None:
|
||||
raise ValidationError(
|
||||
"Time filters must be timezone-aware",
|
||||
details={"field": field, "reason": "timestamp_timezone_required"},
|
||||
)
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _bounded(value: str | None, field: str, limit: int) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
cleaned = value.strip()
|
||||
if not cleaned:
|
||||
return None
|
||||
if len(cleaned) > limit:
|
||||
raise ValidationError("Filter is too long", details={"field": field, "max": limit})
|
||||
return cleaned
|
||||
|
||||
|
||||
def _visible(session: Session, alarm_id: str, subject: str | None) -> tuple[Alarm, str]:
|
||||
"""Load one alarm the subject may see, or raise NotFound for missing and out-of-scope ids."""
|
||||
if subject is None:
|
||||
raise NotFoundError("Alarm not found")
|
||||
parsed = _parse_alarm_id(alarm_id)
|
||||
row = session.execute(
|
||||
select(Alarm, MappedInput.identity_key)
|
||||
.join(MappedInput, MappedInput.id == Alarm.mapped_input_id)
|
||||
.where(
|
||||
Alarm.id == parsed,
|
||||
Alarm.tenant_id == _tenant_id(),
|
||||
MappedInput.tenant_id == _tenant_id(),
|
||||
_scope_clause(subject),
|
||||
)
|
||||
).one_or_none()
|
||||
if row is None:
|
||||
raise NotFoundError("Alarm not found")
|
||||
alarm, identity_key = row
|
||||
return alarm, identity_key
|
||||
|
||||
|
||||
def alarm_public(alarm: Alarm, identity_key: str) -> dict[str, Any]:
|
||||
"""Public alarm projection. Scope principals and tenant id stay off the payload."""
|
||||
return {
|
||||
"id": str(alarm.id),
|
||||
"status": alarm.status,
|
||||
"current_handler": alarm.current_handler,
|
||||
"claimed_at": _isoformat(alarm.claimed_at),
|
||||
"closed_at": _isoformat(alarm.closed_at),
|
||||
"close_result": alarm.close_result,
|
||||
"occurrence_count": alarm.occurrence_count,
|
||||
"first_occurred_at": _isoformat(alarm.first_occurred_at),
|
||||
"last_occurred_at": _isoformat(alarm.last_occurred_at),
|
||||
"previous_alarm_id": str(alarm.previous_alarm_id) if alarm.previous_alarm_id else None,
|
||||
"mapped_input_id": str(alarm.mapped_input_id),
|
||||
"identity_key": identity_key,
|
||||
"module_key": alarm.module_key,
|
||||
"scenario_key": alarm.scenario_key,
|
||||
"scenario_name": alarm.scenario_name,
|
||||
"snapshot_id": str(alarm.snapshot_id),
|
||||
"snapshot_version_no": alarm.snapshot_version_no,
|
||||
"cycle_key": alarm.cycle_key,
|
||||
"event_key": alarm.event_key,
|
||||
"opened_at": _isoformat(alarm.opened_at),
|
||||
"updated_at": _isoformat(alarm.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def search_alarms(
|
||||
session: Session,
|
||||
*,
|
||||
subject: str | None,
|
||||
module_key: str | None = None,
|
||||
scenario_key: str | None = None,
|
||||
scenario_name: str | None = None,
|
||||
status: str | None = None,
|
||||
mapped_input_id: str | None = None,
|
||||
occurred_from: datetime | None = None,
|
||||
occurred_to: datetime | None = None,
|
||||
sort_by: str = _SORT_DEFAULT,
|
||||
sort_order: str = "desc",
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
"""Filter, sort, and page alarms in SQL for the caller's snapshot subjects.
|
||||
|
||||
Filters apply only when the client sends them. A caller with no subject
|
||||
gets an empty page even if the tenant has alarms.
|
||||
"""
|
||||
if sort_by not in _SORT:
|
||||
raise ValidationError(
|
||||
"Invalid sort_by",
|
||||
details={"field": "sort_by", "allowed": sorted(_SORT)},
|
||||
)
|
||||
if sort_order not in ("asc", "desc"):
|
||||
raise ValidationError(
|
||||
"Invalid sort_order",
|
||||
details={"field": "sort_order", "allowed": ["asc", "desc"]},
|
||||
)
|
||||
if page < 1:
|
||||
raise ValidationError("Invalid page", details={"field": "page"})
|
||||
if page_size < 1 or page_size > _PAGE_SIZE_MAX:
|
||||
raise ValidationError(
|
||||
"Invalid page_size",
|
||||
details={"field": "page_size", "min": 1, "max": _PAGE_SIZE_MAX},
|
||||
)
|
||||
module = _bounded(module_key, "module_key", _KEY_MAX)
|
||||
scenario = _bounded(scenario_key, "scenario_key", _KEY_MAX)
|
||||
name = _bounded(scenario_name, "scenario_name", _NAME_MAX)
|
||||
started = _aware(occurred_from, "occurred_from")
|
||||
ended = _aware(occurred_to, "occurred_to")
|
||||
if started is not None and ended is not None and started > ended:
|
||||
raise ValidationError(
|
||||
"occurred_from is after occurred_to",
|
||||
details={"field": "occurred_from"},
|
||||
)
|
||||
status_value = _bounded(status, "status", 16)
|
||||
if status_value is not None and status_value not in ALARM_STATUSES:
|
||||
raise ValidationError(
|
||||
"Invalid status",
|
||||
details={"field": "status", "allowed": list(ALARM_STATUSES)},
|
||||
)
|
||||
object_id: uuid.UUID | None = None
|
||||
if mapped_input_id is not None and mapped_input_id.strip():
|
||||
try:
|
||||
object_id = uuid.UUID(mapped_input_id.strip())
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
"Invalid mapped_input_id",
|
||||
details={"field": "mapped_input_id"},
|
||||
) from exc
|
||||
if subject is None:
|
||||
return {"items": [], "total": 0, "page": page, "page_size": page_size}
|
||||
|
||||
filters = [
|
||||
Alarm.tenant_id == _tenant_id(),
|
||||
MappedInput.tenant_id == _tenant_id(),
|
||||
_scope_clause(subject),
|
||||
]
|
||||
if module is not None:
|
||||
filters.append(Alarm.module_key == module)
|
||||
if scenario is not None:
|
||||
filters.append(Alarm.scenario_key == scenario)
|
||||
if name is not None:
|
||||
filters.append(Alarm.scenario_name.ilike(f"%{name}%"))
|
||||
if status_value is not None:
|
||||
filters.append(Alarm.status == status_value)
|
||||
if object_id is not None:
|
||||
filters.append(Alarm.mapped_input_id == object_id)
|
||||
if started is not None:
|
||||
filters.append(Alarm.last_occurred_at >= started)
|
||||
if ended is not None:
|
||||
filters.append(Alarm.last_occurred_at <= ended)
|
||||
|
||||
joined = select(Alarm).join(MappedInput, MappedInput.id == Alarm.mapped_input_id).where(*filters)
|
||||
total = int(session.scalar(select(func.count()).select_from(joined.subquery())) or 0)
|
||||
order_col = _SORT[sort_by]
|
||||
order_expr = asc(order_col) if sort_order == "asc" else desc(order_col)
|
||||
rows = session.execute(
|
||||
select(Alarm, MappedInput.identity_key)
|
||||
.join(MappedInput, MappedInput.id == Alarm.mapped_input_id)
|
||||
.where(*filters)
|
||||
.order_by(order_expr, asc(Alarm.id))
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
).all()
|
||||
return {
|
||||
"items": [alarm_public(alarm, identity_key) for alarm, identity_key in rows],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
}
|
||||
|
||||
|
||||
def get_alarm(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||
"""Return one in-scope alarm. Missing and out-of-scope ids are both not found."""
|
||||
alarm, identity_key = _visible(session, alarm_id, subject)
|
||||
return alarm_public(alarm, identity_key)
|
||||
|
||||
|
||||
def list_occurrences(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||
"""Return formal occurrences for one visible alarm, oldest observation first."""
|
||||
alarm, _identity = _visible(session, alarm_id, subject)
|
||||
rows = session.scalars(
|
||||
select(AlarmOccurrence)
|
||||
.where(
|
||||
AlarmOccurrence.alarm_id == alarm.id,
|
||||
AlarmOccurrence.tenant_id == _tenant_id(),
|
||||
)
|
||||
.order_by(AlarmOccurrence.observed_at.asc(), AlarmOccurrence.id.asc())
|
||||
)
|
||||
return {
|
||||
"alarm_id": str(alarm.id),
|
||||
"items": [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"mapped_input_revision_id": str(row.mapped_input_revision_id),
|
||||
"mapping_version_id": str(row.mapping_version_id),
|
||||
"rule_version_id": str(row.rule_version_id),
|
||||
"snapshot_id": str(row.snapshot_id),
|
||||
"snapshot_version_no": row.snapshot_version_no,
|
||||
"module_key": row.module_key,
|
||||
"scenario_key": row.scenario_key,
|
||||
"scenario_name": row.scenario_name,
|
||||
"cycle_key": row.cycle_key,
|
||||
"event_key": row.event_key,
|
||||
"observed_at": _isoformat(row.observed_at),
|
||||
"received_at": _isoformat(row.received_at),
|
||||
"created_at": _isoformat(row.created_at),
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def list_evidence(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||
"""Return same-cycle revision evidence and closed-repeat basis for one visible alarm.
|
||||
|
||||
Closed basis is a trace of a later formal failure. It is not a recovery.
|
||||
"""
|
||||
alarm, _identity = _visible(session, alarm_id, subject)
|
||||
revisions = session.scalars(
|
||||
select(AlarmRevisionEvidence)
|
||||
.where(
|
||||
AlarmRevisionEvidence.alarm_id == alarm.id,
|
||||
AlarmRevisionEvidence.tenant_id == _tenant_id(),
|
||||
)
|
||||
.order_by(AlarmRevisionEvidence.recorded_at.asc(), AlarmRevisionEvidence.id.asc())
|
||||
)
|
||||
basis_rows = session.scalars(
|
||||
select(AlarmClosedBasis)
|
||||
.where(
|
||||
AlarmClosedBasis.alarm_id == alarm.id,
|
||||
AlarmClosedBasis.tenant_id == _tenant_id(),
|
||||
)
|
||||
.order_by(AlarmClosedBasis.recorded_at.asc(), AlarmClosedBasis.id.asc())
|
||||
)
|
||||
return {
|
||||
"alarm_id": str(alarm.id),
|
||||
"revision_evidence": [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"occurrence_id": str(row.occurrence_id),
|
||||
"mapped_input_revision_id": str(row.mapped_input_revision_id),
|
||||
"mapping_version_id": str(row.mapping_version_id),
|
||||
"rule_version_id": str(row.rule_version_id),
|
||||
"snapshot_id": str(row.snapshot_id),
|
||||
"snapshot_version_no": row.snapshot_version_no,
|
||||
"received_at": _isoformat(row.received_at),
|
||||
"recorded_at": _isoformat(row.recorded_at),
|
||||
}
|
||||
for row in revisions
|
||||
],
|
||||
"closed_basis": [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"original_occurrence_id": str(row.original_occurrence_id),
|
||||
"mapped_input_revision_id": str(row.mapped_input_revision_id),
|
||||
"mapping_version_id": str(row.mapping_version_id),
|
||||
"rule_version_id": str(row.rule_version_id),
|
||||
"snapshot_id": str(row.snapshot_id),
|
||||
"snapshot_version_no": row.snapshot_version_no,
|
||||
"cycle_key": row.cycle_key,
|
||||
"event_key": row.event_key,
|
||||
"observed_at": _isoformat(row.observed_at),
|
||||
"received_at": _isoformat(row.received_at),
|
||||
"recorded_at": _isoformat(row.recorded_at),
|
||||
}
|
||||
for row in basis_rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def list_history(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||
"""Return append-only handling events for one visible alarm, in seq order."""
|
||||
alarm, _identity = _visible(session, alarm_id, subject)
|
||||
rows = session.scalars(
|
||||
select(AlarmHandlingEvent)
|
||||
.where(
|
||||
AlarmHandlingEvent.alarm_id == alarm.id,
|
||||
AlarmHandlingEvent.tenant_id == _tenant_id(),
|
||||
)
|
||||
.order_by(AlarmHandlingEvent.seq.asc())
|
||||
)
|
||||
return {
|
||||
"alarm_id": str(alarm.id),
|
||||
"items": [
|
||||
{
|
||||
"id": str(row.id),
|
||||
"seq": row.seq,
|
||||
"command": row.command,
|
||||
"actor_subject": row.actor_subject,
|
||||
"actor_role": row.actor_role,
|
||||
"handler_subject": row.handler_subject,
|
||||
"from_status": row.from_status,
|
||||
"to_status": row.to_status,
|
||||
"note": row.note,
|
||||
"close_result": row.close_result,
|
||||
"evidence_ref": row.evidence_ref,
|
||||
"recorded_at": _isoformat(row.recorded_at),
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def read_close_validity(session: Session, alarm_id: str, subject: str | None) -> dict[str, Any]:
|
||||
"""Return the derived close flag after the snapshot scope check.
|
||||
|
||||
The domain function does not apply scope, so this read must not call it
|
||||
for an id the subject cannot see.
|
||||
"""
|
||||
alarm, _identity = _visible(session, alarm_id, subject)
|
||||
validity = close_validity(session, alarm.id)
|
||||
return {
|
||||
"alarm_id": str(validity.alarm_id),
|
||||
"status": validity.status,
|
||||
"unexecuted_intents_should_invalidate": validity.unexecuted_intents_should_invalidate,
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
"""Formal alarm facts: idempotent occurrences and bounded structured merge.
|
||||
|
||||
Boundary: records facts and a closed-repeat basis. Claim, progress, and close
|
||||
live in the handling service. No notifications, trial writes, or caller tenants.
|
||||
Depends on M05 revisions, mapping versions, rule versions, and the server tenant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select, text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from watchman.models.alarm import (
|
||||
ALARM_STATUS_CLOSED,
|
||||
ALARM_STATUS_PENDING,
|
||||
Alarm,
|
||||
AlarmOccurrence,
|
||||
AlarmRevisionEvidence,
|
||||
)
|
||||
from watchman.models.alarm_handling import AlarmClosedBasis
|
||||
from watchman.services.platform_records import create_audit_event
|
||||
from watchman.models.mapping import (
|
||||
MappedInput,
|
||||
MappedInputRevision,
|
||||
RuleDefinition,
|
||||
RuleVersion,
|
||||
)
|
||||
|
||||
# NOTE(ai): merge columns are an S1 implementation choice, not a new confirmed rule.
|
||||
# GUARD: do not merge on message text, payload hash, or an unbounded history of a label.
|
||||
# GUARD: a closed merge key stays closed. Continued failures append basis and an audit row.
|
||||
CLOSED_REPEAT_ACTION = "alarm.continued_after_close"
|
||||
_KEY_MAX = 128
|
||||
_NAME_MAX = 256
|
||||
_SUBJECT_KINDS = frozenset({"role", "subject"})
|
||||
_REJECTED_SUBJECTS = frozenset({"*", "all", "tenant", "all_tenant"})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SyntheticPublishSnapshot:
|
||||
"""Minimal synthetic publish context carried on a formal fact.
|
||||
|
||||
`handling_scope` must declare an explicit subject. There is no scenario table.
|
||||
"""
|
||||
|
||||
snapshot_id: uuid.UUID
|
||||
version_no: int
|
||||
module_key: str
|
||||
scenario_key: str
|
||||
scenario_name: str
|
||||
handling_scope: dict[str, Any]
|
||||
mapping_version_id: uuid.UUID
|
||||
rule_version_id: uuid.UUID
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FormalFailure:
|
||||
"""One confirmed abnormal observation. Replay identity includes `observed_at`."""
|
||||
|
||||
mapped_input_revision_id: uuid.UUID
|
||||
snapshot: SyntheticPublishSnapshot
|
||||
observed_at: datetime
|
||||
received_at: datetime
|
||||
cycle_key: str
|
||||
event_key: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SameCycleCorrection:
|
||||
"""A later revision inside an existing cycle. It must not open an alarm."""
|
||||
|
||||
mapped_input_revision_id: uuid.UUID
|
||||
snapshot: SyntheticPublishSnapshot
|
||||
cycle_key: str
|
||||
event_key: str
|
||||
received_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AlarmFactResult:
|
||||
"""What the fact write did. Flags stay false on replay and on non-fail outcomes."""
|
||||
|
||||
alarm_id: uuid.UUID
|
||||
occurrence_id: uuid.UUID | None
|
||||
evidence_id: uuid.UUID | None
|
||||
created_alarm: bool
|
||||
created_occurrence: bool
|
||||
created_evidence: bool
|
||||
suppressed: bool
|
||||
basis_id: uuid.UUID | None = None
|
||||
created_basis: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Resolved:
|
||||
revision: MappedInputRevision
|
||||
mapped_input: MappedInput
|
||||
rule_version: RuleVersion
|
||||
rule_definition: RuleDefinition
|
||||
snapshot: SyntheticPublishSnapshot
|
||||
observed_at: datetime | None
|
||||
received_at: datetime
|
||||
cycle_key: str
|
||||
event_key: str
|
||||
|
||||
|
||||
def _tenant_id() -> str:
|
||||
# GUARD: tenant_id comes only from server settings, never from the caller.
|
||||
return get_settings().tenant_id
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _fail(reason: str, field: str | None = None) -> ValidationError:
|
||||
details: dict[str, Any] = {"reason": reason}
|
||||
if field is not None:
|
||||
details["field"] = field
|
||||
return ValidationError("Invalid alarm fact", details=details)
|
||||
|
||||
|
||||
def _require_uuid(value: object, field: str) -> uuid.UUID:
|
||||
if not isinstance(value, uuid.UUID):
|
||||
raise _fail("snapshot_field_invalid", field)
|
||||
return value
|
||||
|
||||
|
||||
def _require_version(value: object) -> int:
|
||||
if isinstance(value, bool) or not isinstance(value, int) or value < 1:
|
||||
raise _fail("snapshot_field_invalid", "version_no")
|
||||
return value
|
||||
|
||||
|
||||
def _require_key(value: object, field: str, limit: int) -> str:
|
||||
if not isinstance(value, str):
|
||||
raise _fail("snapshot_field_invalid", field)
|
||||
cleaned = value.strip()
|
||||
if not cleaned or len(cleaned) > limit or any(char in cleaned for char in "\r\n"):
|
||||
raise _fail("merge_key_not_text", field)
|
||||
return cleaned
|
||||
|
||||
|
||||
def _require_aware(value: object, field: str) -> datetime:
|
||||
if not isinstance(value, datetime) or value.tzinfo is None or value.utcoffset() is None:
|
||||
raise _fail("timestamp_timezone_required", field)
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _require_scope(scope: object) -> dict[str, Any]:
|
||||
"""Reject a missing scope and any all-tenant operator default.
|
||||
|
||||
A subject entry is required so a role name alone cannot cover the tenant.
|
||||
That requirement is an implementation assumption, not a confirmed auth model.
|
||||
"""
|
||||
if not isinstance(scope, dict) or "all_tenant" in scope:
|
||||
reason = (
|
||||
"snapshot_scope_rejects_all_tenant"
|
||||
if isinstance(scope, dict) and "all_tenant" in scope
|
||||
else "snapshot_scope_missing"
|
||||
)
|
||||
raise _fail(reason, "handling_scope")
|
||||
principals = scope.get("principals")
|
||||
if not isinstance(principals, list) or not principals:
|
||||
raise _fail("snapshot_scope_missing", "handling_scope")
|
||||
normalized: list[dict[str, str]] = []
|
||||
for item in principals:
|
||||
if not isinstance(item, dict):
|
||||
raise _fail("snapshot_scope_missing", "handling_scope")
|
||||
kind = item.get("kind")
|
||||
raw_value = item.get("value")
|
||||
if kind not in _SUBJECT_KINDS or not isinstance(raw_value, str):
|
||||
raise _fail("snapshot_scope_missing", "handling_scope")
|
||||
cleaned = raw_value.strip()
|
||||
if not cleaned or cleaned.casefold() in _REJECTED_SUBJECTS:
|
||||
raise _fail("snapshot_scope_rejects_all_tenant", "handling_scope")
|
||||
normalized.append({"kind": kind, "value": cleaned})
|
||||
if not any(item["kind"] == "subject" for item in normalized):
|
||||
raise _fail("snapshot_scope_rejects_all_tenant", "handling_scope")
|
||||
return {"principals": normalized}
|
||||
|
||||
|
||||
def _normalize_snapshot(snapshot: SyntheticPublishSnapshot) -> SyntheticPublishSnapshot:
|
||||
if not isinstance(snapshot, SyntheticPublishSnapshot):
|
||||
raise _fail("snapshot_field_invalid", "snapshot")
|
||||
return SyntheticPublishSnapshot(
|
||||
snapshot_id=_require_uuid(snapshot.snapshot_id, "snapshot_id"),
|
||||
version_no=_require_version(snapshot.version_no),
|
||||
module_key=_require_key(snapshot.module_key, "module_key", _KEY_MAX),
|
||||
scenario_key=_require_key(snapshot.scenario_key, "scenario_key", _KEY_MAX),
|
||||
scenario_name=_require_key(snapshot.scenario_name, "scenario_name", _NAME_MAX),
|
||||
handling_scope=_require_scope(snapshot.handling_scope),
|
||||
mapping_version_id=_require_uuid(snapshot.mapping_version_id, "mapping_version_id"),
|
||||
rule_version_id=_require_uuid(snapshot.rule_version_id, "rule_version_id"),
|
||||
)
|
||||
|
||||
|
||||
def _load_refs(
|
||||
session: Session,
|
||||
*,
|
||||
revision_id: uuid.UUID,
|
||||
snapshot: SyntheticPublishSnapshot,
|
||||
cycle_key: str,
|
||||
event_key: str,
|
||||
received_at: datetime,
|
||||
observed_at: datetime | None,
|
||||
) -> _Resolved:
|
||||
"""Load the M05 revision and rule cited by the snapshot, or refuse the write."""
|
||||
if not isinstance(revision_id, uuid.UUID):
|
||||
raise NotFoundError("Mapped input revision not found")
|
||||
normalized = _normalize_snapshot(snapshot)
|
||||
cycle = _require_key(cycle_key, "cycle_key", _KEY_MAX)
|
||||
event = _require_key(event_key, "event_key", _KEY_MAX)
|
||||
received = _require_aware(received_at, "received_at")
|
||||
observed = _require_aware(observed_at, "observed_at") if observed_at is not None else None
|
||||
tenant_id = _tenant_id()
|
||||
revision = session.scalar(
|
||||
select(MappedInputRevision).where(
|
||||
MappedInputRevision.id == revision_id,
|
||||
MappedInputRevision.tenant_id == tenant_id,
|
||||
)
|
||||
)
|
||||
if revision is None:
|
||||
raise NotFoundError("Mapped input revision not found")
|
||||
if revision.mapping_version_id != normalized.mapping_version_id:
|
||||
raise _fail("snapshot_version_mismatch", "mapping_version_id")
|
||||
mapped_input = session.scalar(
|
||||
select(MappedInput).where(
|
||||
MappedInput.id == revision.input_id,
|
||||
MappedInput.tenant_id == tenant_id,
|
||||
)
|
||||
)
|
||||
if mapped_input is None:
|
||||
raise NotFoundError("Mapped input not found")
|
||||
rule_version = session.scalar(
|
||||
select(RuleVersion).where(
|
||||
RuleVersion.id == normalized.rule_version_id,
|
||||
RuleVersion.tenant_id == tenant_id,
|
||||
)
|
||||
)
|
||||
if rule_version is None:
|
||||
raise NotFoundError("Rule version not found")
|
||||
rule_definition = session.scalar(
|
||||
select(RuleDefinition).where(
|
||||
RuleDefinition.id == rule_version.definition_id,
|
||||
RuleDefinition.tenant_id == tenant_id,
|
||||
)
|
||||
)
|
||||
if rule_definition is None or rule_definition.mapping_definition_id != mapped_input.mapping_definition_id:
|
||||
raise _fail("rule_mapping_mismatch", "rule_version_id")
|
||||
return _Resolved(
|
||||
revision=revision,
|
||||
mapped_input=mapped_input,
|
||||
rule_version=rule_version,
|
||||
rule_definition=rule_definition,
|
||||
snapshot=normalized,
|
||||
observed_at=observed,
|
||||
received_at=received,
|
||||
cycle_key=cycle,
|
||||
event_key=event,
|
||||
)
|
||||
|
||||
|
||||
def lock_alarm_subject(
|
||||
session: Session,
|
||||
*,
|
||||
module_key: str,
|
||||
scenario_key: str,
|
||||
mapped_input_id: uuid.UUID,
|
||||
) -> None:
|
||||
"""Hold the subject advisory lock until this transaction ends.
|
||||
|
||||
Fact writes and handling transitions share this token so a close cannot
|
||||
interleave with a merge. Callers take it before SELECT FOR UPDATE.
|
||||
The token is tenant, module, scenario, and mapped input, not the cycle.
|
||||
"""
|
||||
token = "|".join((_tenant_id(), module_key, scenario_key, str(mapped_input_id)))
|
||||
session.execute(
|
||||
text("SELECT pg_advisory_xact_lock(hashtextextended(:token, 0))"),
|
||||
{"token": token},
|
||||
)
|
||||
|
||||
|
||||
def _lock_subject(session: Session, refs: _Resolved) -> None:
|
||||
"""Serialize create/merge for one scenario subject until this transaction ends."""
|
||||
lock_alarm_subject(
|
||||
session,
|
||||
module_key=refs.snapshot.module_key,
|
||||
scenario_key=refs.snapshot.scenario_key,
|
||||
mapped_input_id=refs.mapped_input.id,
|
||||
)
|
||||
|
||||
|
||||
def _find_occurrence(session: Session, refs: _Resolved) -> AlarmOccurrence | None:
|
||||
assert refs.observed_at is not None
|
||||
return session.scalar(
|
||||
select(AlarmOccurrence)
|
||||
.where(
|
||||
AlarmOccurrence.tenant_id == _tenant_id(),
|
||||
AlarmOccurrence.mapped_input_revision_id == refs.revision.id,
|
||||
AlarmOccurrence.mapping_version_id == refs.snapshot.mapping_version_id,
|
||||
AlarmOccurrence.rule_version_id == refs.rule_version.id,
|
||||
AlarmOccurrence.snapshot_id == refs.snapshot.snapshot_id,
|
||||
AlarmOccurrence.cycle_key == refs.cycle_key,
|
||||
AlarmOccurrence.event_key == refs.event_key,
|
||||
AlarmOccurrence.observed_at == refs.observed_at,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
|
||||
|
||||
def _find_alarm(session: Session, refs: _Resolved) -> Alarm | None:
|
||||
snapshot = refs.snapshot
|
||||
return session.scalar(
|
||||
select(Alarm)
|
||||
.where(
|
||||
Alarm.tenant_id == _tenant_id(),
|
||||
Alarm.module_key == snapshot.module_key,
|
||||
Alarm.scenario_key == snapshot.scenario_key,
|
||||
Alarm.mapped_input_id == refs.mapped_input.id,
|
||||
Alarm.cycle_key == refs.cycle_key,
|
||||
Alarm.event_key == refs.event_key,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
|
||||
|
||||
def _latest_alarm(session: Session, refs: _Resolved) -> Alarm | None:
|
||||
snapshot = refs.snapshot
|
||||
return session.scalar(
|
||||
select(Alarm)
|
||||
.where(
|
||||
Alarm.tenant_id == _tenant_id(),
|
||||
Alarm.module_key == snapshot.module_key,
|
||||
Alarm.scenario_key == snapshot.scenario_key,
|
||||
Alarm.mapped_input_id == refs.mapped_input.id,
|
||||
)
|
||||
.order_by(Alarm.opened_at.desc(), Alarm.id.desc())
|
||||
.limit(1)
|
||||
.with_for_update()
|
||||
)
|
||||
|
||||
|
||||
def _original_occurrence(session: Session, alarm_id: uuid.UUID) -> AlarmOccurrence | None:
|
||||
return session.scalar(
|
||||
select(AlarmOccurrence)
|
||||
.where(
|
||||
AlarmOccurrence.tenant_id == _tenant_id(),
|
||||
AlarmOccurrence.alarm_id == alarm_id,
|
||||
)
|
||||
.order_by(AlarmOccurrence.created_at.asc(), AlarmOccurrence.id.asc())
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
|
||||
def _find_evidence(session: Session, alarm_id: uuid.UUID, revision_id: uuid.UUID) -> AlarmRevisionEvidence | None:
|
||||
return session.scalar(
|
||||
select(AlarmRevisionEvidence)
|
||||
.where(
|
||||
AlarmRevisionEvidence.tenant_id == _tenant_id(),
|
||||
AlarmRevisionEvidence.alarm_id == alarm_id,
|
||||
AlarmRevisionEvidence.mapped_input_revision_id == revision_id,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
|
||||
|
||||
def _result(
|
||||
*,
|
||||
alarm_id: uuid.UUID,
|
||||
occurrence_id: uuid.UUID | None = None,
|
||||
evidence_id: uuid.UUID | None = None,
|
||||
created_alarm: bool = False,
|
||||
created_occurrence: bool = False,
|
||||
created_evidence: bool = False,
|
||||
suppressed: bool = False,
|
||||
basis_id: uuid.UUID | None = None,
|
||||
created_basis: bool = False,
|
||||
) -> AlarmFactResult:
|
||||
return AlarmFactResult(
|
||||
alarm_id=alarm_id,
|
||||
occurrence_id=occurrence_id,
|
||||
evidence_id=evidence_id,
|
||||
created_alarm=created_alarm,
|
||||
created_occurrence=created_occurrence,
|
||||
created_evidence=created_evidence,
|
||||
suppressed=suppressed,
|
||||
basis_id=basis_id,
|
||||
created_basis=created_basis,
|
||||
)
|
||||
|
||||
|
||||
def _new_alarm(refs: _Resolved, previous: Alarm | None) -> Alarm:
|
||||
assert refs.observed_at is not None
|
||||
snapshot = refs.snapshot
|
||||
return Alarm(
|
||||
tenant_id=_tenant_id(),
|
||||
status=ALARM_STATUS_PENDING,
|
||||
current_handler=None,
|
||||
occurrence_count=1,
|
||||
first_occurred_at=refs.observed_at,
|
||||
last_occurred_at=refs.observed_at,
|
||||
previous_alarm_id=None if previous is None else previous.id,
|
||||
mapped_input_id=refs.mapped_input.id,
|
||||
mapping_definition_id=refs.mapped_input.mapping_definition_id,
|
||||
mapping_version_id=refs.revision.mapping_version_id,
|
||||
rule_definition_id=refs.rule_definition.id,
|
||||
rule_version_id=refs.rule_version.id,
|
||||
snapshot_id=snapshot.snapshot_id,
|
||||
snapshot_version_no=snapshot.version_no,
|
||||
module_key=snapshot.module_key,
|
||||
scenario_key=snapshot.scenario_key,
|
||||
scenario_name=snapshot.scenario_name,
|
||||
handling_scope=snapshot.handling_scope,
|
||||
cycle_key=refs.cycle_key,
|
||||
event_key=refs.event_key,
|
||||
opened_at=_now(),
|
||||
updated_at=_now(),
|
||||
)
|
||||
|
||||
|
||||
def _new_occurrence(refs: _Resolved, alarm_id: uuid.UUID) -> AlarmOccurrence:
|
||||
assert refs.observed_at is not None
|
||||
snapshot = refs.snapshot
|
||||
return AlarmOccurrence(
|
||||
tenant_id=_tenant_id(),
|
||||
alarm_id=alarm_id,
|
||||
mapped_input_id=refs.mapped_input.id,
|
||||
mapped_input_revision_id=refs.revision.id,
|
||||
mapping_definition_id=refs.mapped_input.mapping_definition_id,
|
||||
mapping_version_id=refs.revision.mapping_version_id,
|
||||
rule_definition_id=refs.rule_definition.id,
|
||||
rule_version_id=refs.rule_version.id,
|
||||
snapshot_id=snapshot.snapshot_id,
|
||||
snapshot_version_no=snapshot.version_no,
|
||||
module_key=snapshot.module_key,
|
||||
scenario_key=snapshot.scenario_key,
|
||||
scenario_name=snapshot.scenario_name,
|
||||
handling_scope=snapshot.handling_scope,
|
||||
cycle_key=refs.cycle_key,
|
||||
event_key=refs.event_key,
|
||||
observed_at=refs.observed_at,
|
||||
received_at=refs.received_at,
|
||||
created_at=_now(),
|
||||
)
|
||||
|
||||
|
||||
def _attach(session: Session, alarm: Alarm, refs: _Resolved) -> AlarmFactResult:
|
||||
"""Add one occurrence to an open alarm without changing its original snapshot."""
|
||||
occurrence = _new_occurrence(refs, alarm.id)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.add(occurrence)
|
||||
alarm.occurrence_count += 1
|
||||
assert refs.observed_at is not None
|
||||
if refs.observed_at > alarm.last_occurred_at:
|
||||
alarm.last_occurred_at = refs.observed_at
|
||||
alarm.updated_at = _now()
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
session.expire_all()
|
||||
existing = _find_occurrence(session, refs)
|
||||
if existing is None:
|
||||
raise
|
||||
return _result(alarm_id=existing.alarm_id, occurrence_id=existing.id)
|
||||
return _result(
|
||||
alarm_id=alarm.id,
|
||||
occurrence_id=occurrence.id,
|
||||
created_occurrence=True,
|
||||
)
|
||||
|
||||
|
||||
def _find_closed_basis(session: Session, refs: _Resolved) -> AlarmClosedBasis | None:
|
||||
assert refs.observed_at is not None
|
||||
return session.scalar(
|
||||
select(AlarmClosedBasis)
|
||||
.where(
|
||||
AlarmClosedBasis.tenant_id == _tenant_id(),
|
||||
AlarmClosedBasis.mapped_input_revision_id == refs.revision.id,
|
||||
AlarmClosedBasis.mapping_version_id == refs.snapshot.mapping_version_id,
|
||||
AlarmClosedBasis.rule_version_id == refs.rule_version.id,
|
||||
AlarmClosedBasis.snapshot_id == refs.snapshot.snapshot_id,
|
||||
AlarmClosedBasis.cycle_key == refs.cycle_key,
|
||||
AlarmClosedBasis.event_key == refs.event_key,
|
||||
AlarmClosedBasis.observed_at == refs.observed_at,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
)
|
||||
|
||||
|
||||
def _closed_audit_key(alarm_id: uuid.UUID, refs: _Resolved) -> str:
|
||||
assert refs.observed_at is not None
|
||||
identity = "|".join(
|
||||
(
|
||||
str(alarm_id),
|
||||
str(refs.revision.id),
|
||||
str(refs.snapshot.mapping_version_id),
|
||||
str(refs.rule_version.id),
|
||||
str(refs.snapshot.snapshot_id),
|
||||
refs.cycle_key,
|
||||
refs.event_key,
|
||||
refs.observed_at.isoformat(),
|
||||
)
|
||||
)
|
||||
digest = hashlib.sha256(identity.encode("utf-8")).hexdigest()
|
||||
return f"{CLOSED_REPEAT_ACTION}:{digest}"[:128]
|
||||
|
||||
|
||||
def _record_closed_basis(session: Session, alarm: Alarm, refs: _Resolved) -> AlarmFactResult:
|
||||
"""Append a trace for a formal failure on an already closed merge key.
|
||||
|
||||
Does not reopen the alarm, open another one, or change the original FAIL.
|
||||
A replay of the same formal identity returns the existing basis and does
|
||||
not write a second audit row. Raises ConflictError when the closed alarm
|
||||
has no original occurrence to point at.
|
||||
"""
|
||||
# GUARD: closed merge keys stay closed. Do not insert an occurrence here.
|
||||
assert refs.observed_at is not None
|
||||
alarm_id = alarm.id
|
||||
existing = _find_closed_basis(session, refs)
|
||||
if existing is not None:
|
||||
return _result(alarm_id=alarm_id, basis_id=existing.id, suppressed=True)
|
||||
anchor = _original_occurrence(session, alarm_id)
|
||||
if anchor is None:
|
||||
raise ConflictError(
|
||||
"Closed alarm has no original fact",
|
||||
details={"reason": "closed_basis_without_occurrence"},
|
||||
)
|
||||
basis = AlarmClosedBasis(
|
||||
tenant_id=_tenant_id(),
|
||||
alarm_id=alarm_id,
|
||||
original_occurrence_id=anchor.id,
|
||||
mapped_input_revision_id=refs.revision.id,
|
||||
mapping_version_id=refs.snapshot.mapping_version_id,
|
||||
rule_version_id=refs.rule_version.id,
|
||||
snapshot_id=refs.snapshot.snapshot_id,
|
||||
snapshot_version_no=refs.snapshot.version_no,
|
||||
cycle_key=refs.cycle_key,
|
||||
event_key=refs.event_key,
|
||||
observed_at=refs.observed_at,
|
||||
received_at=refs.received_at,
|
||||
recorded_at=_now(),
|
||||
)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.add(basis)
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
session.expire_all()
|
||||
existing = _find_closed_basis(session, refs)
|
||||
if existing is None:
|
||||
raise
|
||||
return _result(alarm_id=alarm_id, basis_id=existing.id, suppressed=True)
|
||||
create_audit_event(
|
||||
session,
|
||||
action=CLOSED_REPEAT_ACTION,
|
||||
payload={
|
||||
"alarm_id": str(alarm_id),
|
||||
"basis_id": str(basis.id),
|
||||
"original_occurrence_id": str(anchor.id),
|
||||
"mapped_input_revision_id": str(refs.revision.id),
|
||||
"cycle_key": refs.cycle_key,
|
||||
"event_key": refs.event_key,
|
||||
"observed_at": refs.observed_at.isoformat(),
|
||||
"reason": "closed_merge_key",
|
||||
},
|
||||
idempotency_key=_closed_audit_key(alarm_id, refs),
|
||||
)
|
||||
return _result(alarm_id=alarm_id, basis_id=basis.id, created_basis=True, suppressed=True)
|
||||
|
||||
|
||||
def record_formal_failure(
|
||||
session: Session,
|
||||
failure: FormalFailure,
|
||||
*,
|
||||
confirmed_abnormal: bool = False,
|
||||
) -> AlarmFactResult | None:
|
||||
"""Create or reuse one formal FAIL occurrence and its bounded alarm.
|
||||
|
||||
Input is an already confirmed abnormal fact. `confirmed_abnormal` must be
|
||||
true; otherwise the call writes nothing. Output is the existing row on
|
||||
replay, a closed-key basis, or the row just inserted.
|
||||
Raises NotFoundError or ValidationError before any insert when the
|
||||
revision, rule, or snapshot does not hang together. A closed merge key
|
||||
does not reopen or open another alarm; it appends a basis and an audit row.
|
||||
"""
|
||||
# GUARD: PASS / UNKNOWN / failure / trial must not reach this with True.
|
||||
if confirmed_abnormal is not True:
|
||||
return None
|
||||
if not isinstance(failure, FormalFailure):
|
||||
raise _fail("snapshot_field_invalid", "failure")
|
||||
refs = _load_refs(
|
||||
session,
|
||||
revision_id=failure.mapped_input_revision_id,
|
||||
snapshot=failure.snapshot,
|
||||
cycle_key=failure.cycle_key,
|
||||
event_key=failure.event_key,
|
||||
received_at=failure.received_at,
|
||||
observed_at=failure.observed_at,
|
||||
)
|
||||
_lock_subject(session, refs)
|
||||
existing = _find_occurrence(session, refs)
|
||||
if existing is not None:
|
||||
return _result(alarm_id=existing.alarm_id, occurrence_id=existing.id)
|
||||
alarm = _find_alarm(session, refs)
|
||||
if alarm is not None and alarm.status == ALARM_STATUS_CLOSED:
|
||||
return _record_closed_basis(session, alarm, refs)
|
||||
if alarm is None:
|
||||
previous = _latest_alarm(session, refs)
|
||||
alarm = _new_alarm(refs, previous)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.add(alarm)
|
||||
session.flush()
|
||||
occurrence = _new_occurrence(refs, alarm.id)
|
||||
session.add(occurrence)
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
session.expire_all()
|
||||
raced = _find_occurrence(session, refs)
|
||||
if raced is not None:
|
||||
return _result(alarm_id=raced.alarm_id, occurrence_id=raced.id)
|
||||
alarm = _find_alarm(session, refs)
|
||||
if alarm is None:
|
||||
raise
|
||||
if alarm.status == ALARM_STATUS_CLOSED:
|
||||
return _record_closed_basis(session, alarm, refs)
|
||||
return _attach(session, alarm, refs)
|
||||
return _result(
|
||||
alarm_id=alarm.id,
|
||||
occurrence_id=occurrence.id,
|
||||
created_alarm=True,
|
||||
created_occurrence=True,
|
||||
)
|
||||
return _attach(session, alarm, refs)
|
||||
|
||||
|
||||
def append_same_cycle_revision(session: Session, correction: SameCycleCorrection) -> AlarmFactResult:
|
||||
"""Append a same-cycle revision without a new alarm or a rewritten FAIL.
|
||||
|
||||
Requires an alarm already opened for that structured key. A missing alarm
|
||||
raises ConflictError and writes nothing. Replaying the original revision
|
||||
or the same correction returns the existing basis.
|
||||
"""
|
||||
if not isinstance(correction, SameCycleCorrection):
|
||||
raise _fail("snapshot_field_invalid", "correction")
|
||||
refs = _load_refs(
|
||||
session,
|
||||
revision_id=correction.mapped_input_revision_id,
|
||||
snapshot=correction.snapshot,
|
||||
cycle_key=correction.cycle_key,
|
||||
event_key=correction.event_key,
|
||||
received_at=correction.received_at,
|
||||
observed_at=None,
|
||||
)
|
||||
_lock_subject(session, refs)
|
||||
alarm = _find_alarm(session, refs)
|
||||
if alarm is None:
|
||||
raise ConflictError(
|
||||
"Same-cycle correction does not open an alarm",
|
||||
details={"reason": "correction_without_alarm"},
|
||||
)
|
||||
anchor = _original_occurrence(session, alarm.id)
|
||||
if anchor is None:
|
||||
raise ConflictError(
|
||||
"Same-cycle correction has no original fact",
|
||||
details={"reason": "correction_without_occurrence"},
|
||||
)
|
||||
if refs.revision.id == anchor.mapped_input_revision_id:
|
||||
return _result(alarm_id=alarm.id, occurrence_id=anchor.id)
|
||||
existing = _find_evidence(session, alarm.id, refs.revision.id)
|
||||
if existing is not None:
|
||||
return _result(alarm_id=alarm.id, occurrence_id=anchor.id, evidence_id=existing.id)
|
||||
evidence = AlarmRevisionEvidence(
|
||||
tenant_id=_tenant_id(),
|
||||
alarm_id=alarm.id,
|
||||
occurrence_id=anchor.id,
|
||||
mapped_input_revision_id=refs.revision.id,
|
||||
mapping_version_id=refs.revision.mapping_version_id,
|
||||
rule_version_id=refs.rule_version.id,
|
||||
snapshot_id=refs.snapshot.snapshot_id,
|
||||
snapshot_version_no=refs.snapshot.version_no,
|
||||
received_at=refs.received_at,
|
||||
recorded_at=_now(),
|
||||
)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.add(evidence)
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
session.expire_all()
|
||||
existing = _find_evidence(session, alarm.id, refs.revision.id)
|
||||
if existing is None:
|
||||
raise
|
||||
return _result(alarm_id=alarm.id, occurrence_id=anchor.id, evidence_id=existing.id)
|
||||
return _result(
|
||||
alarm_id=alarm.id,
|
||||
occurrence_id=anchor.id,
|
||||
evidence_id=evidence.id,
|
||||
created_evidence=True,
|
||||
)
|
||||
|
||||
|
||||
def apply_monitored_outcome(
|
||||
session: Session,
|
||||
*,
|
||||
source: str,
|
||||
outcome: str,
|
||||
code: str | None = None,
|
||||
failure: FormalFailure | None = None,
|
||||
) -> AlarmFactResult | None:
|
||||
"""Record a fact only for a formal abnormal result. Every other outcome is a no-op.
|
||||
|
||||
`source` must be ``formal``. Trial runs, normal, unknown, empty, and error
|
||||
results return None before any alarm read that could insert. A formal
|
||||
abnormal result without a failure payload raises ValidationError and still
|
||||
does not insert.
|
||||
"""
|
||||
# GUARD: trial and non-abnormal outcomes have zero alarm side effects.
|
||||
if source != "formal" or outcome != "result" or code != "abnormal":
|
||||
return None
|
||||
if failure is None:
|
||||
raise _fail("formal_failure_required", "failure")
|
||||
return record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||
@@ -0,0 +1,610 @@
|
||||
"""S3 alarm API authorization on PostgreSQL.
|
||||
|
||||
Why: list, detail, and the three commands must enforce the D38 nodes plus
|
||||
snapshot subject scope, and conflicts must stay on the existing envelope.
|
||||
Boundary: does not cover the Vue console, a new role, or a new error code.
|
||||
Depends on S1 facts, S2 handling, and the session cookie.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import delete
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from test_alarm_occurrences import ( # type: ignore[attr-defined]
|
||||
OBSERVED,
|
||||
RECEIVED,
|
||||
alarm_db,
|
||||
_build,
|
||||
_revise,
|
||||
_snapshot,
|
||||
)
|
||||
from watchman.api.app import create_app
|
||||
from watchman.auth.access import (
|
||||
ALARM_CLOSE_NODE,
|
||||
ALARM_PROGRESS_NODE,
|
||||
ALARM_READ_NODE,
|
||||
ALARM_TAKE_NODE,
|
||||
ENTER_ROLES,
|
||||
ROLE_ADMIN,
|
||||
ROLE_OPERATOR,
|
||||
ROLE_VIEWER,
|
||||
require_alarm_close,
|
||||
require_alarm_progress,
|
||||
require_alarm_read,
|
||||
require_alarm_take,
|
||||
)
|
||||
from watchman.auth.principal import get_role_directory
|
||||
from watchman.auth.sessions import SESSION_COOKIE_NAME, hash_cookie_token, issue_cookie_token
|
||||
from watchman.core.config import reload_settings
|
||||
from watchman.core.db import reset_engine, set_tenant
|
||||
from watchman.core.errors import ForbiddenError
|
||||
from watchman.models.auth_session import AuthSession
|
||||
from watchman.services.alarms import (
|
||||
FormalFailure,
|
||||
SameCycleCorrection,
|
||||
append_same_cycle_revision,
|
||||
apply_monitored_outcome,
|
||||
)
|
||||
|
||||
OP = "op-line"
|
||||
OTHER_OP = "op-other"
|
||||
ADMIN = "admin-line"
|
||||
OUTSIDER = "outside-line"
|
||||
D38_NODES = (
|
||||
"perm:data:emp:watchman.alarm.read",
|
||||
"perm:data:emp:watchman.alarm.take",
|
||||
"perm:data:emp:watchman.alarm.progress",
|
||||
"perm:data:emp:watchman.alarm.close",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def alarm_api(alarm_db): # type: ignore[no-untyped-def]
|
||||
"""Reuse the alarm database fixture and delete only this test's sessions."""
|
||||
factory, registry, settings = alarm_db
|
||||
tokens: list[str] = []
|
||||
yield factory, registry, settings, tokens
|
||||
session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
if tokens:
|
||||
session.execute(
|
||||
delete(AuthSession).where(
|
||||
AuthSession.token_hash.in_([hash_cookie_token(token) for token in tokens])
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_alarm_nodes_stay_on_the_approved_d38_literals() -> None:
|
||||
"""D38 is the only alarm permission set, and the three role names stay put."""
|
||||
assert (ALARM_READ_NODE, ALARM_TAKE_NODE, ALARM_PROGRESS_NODE, ALARM_CLOSE_NODE) == D38_NODES
|
||||
assert ENTER_ROLES == frozenset({ROLE_ADMIN, ROLE_OPERATOR, ROLE_VIEWER})
|
||||
require_alarm_read([ROLE_VIEWER])
|
||||
require_alarm_take([ROLE_OPERATOR])
|
||||
require_alarm_progress([ROLE_ADMIN])
|
||||
require_alarm_close([ROLE_ADMIN, ROLE_VIEWER])
|
||||
with pytest.raises(ForbiddenError) as denied:
|
||||
require_alarm_take([ROLE_VIEWER])
|
||||
assert denied.value.code == 42000
|
||||
assert denied.value.permission_node == ALARM_TAKE_NODE
|
||||
with pytest.raises(ForbiddenError) as unknown:
|
||||
require_alarm_read(["watchman-alarm"])
|
||||
assert unknown.value.permission_node == ALARM_READ_NODE
|
||||
|
||||
|
||||
def test_reads_honor_role_and_snapshot_scope(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||
"""A-040: in-scope roles can read; an outside id and a missing cookie cannot."""
|
||||
factory, registry, settings, tokens = alarm_api
|
||||
visible, hidden = _open_pair(factory, registry, settings)
|
||||
viewer = _client(factory, settings, tokens, roles=[ROLE_VIEWER], subject=OP)
|
||||
outsider = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OUTSIDER)
|
||||
blank = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=" ")
|
||||
unknown = _client(factory, settings, tokens, roles=["watchman-alarm"], subject=OP)
|
||||
anon = _client(factory, settings, tokens, roles=None, subject=OP)
|
||||
|
||||
listed = viewer.get("/alarms")
|
||||
assert listed.status_code == 200, listed.text
|
||||
body = listed.json()
|
||||
assert body["success"] is True
|
||||
assert body["request_id"]
|
||||
ids = {item["id"] for item in body["data"]["items"]}
|
||||
assert visible in ids
|
||||
assert hidden not in ids
|
||||
assert "tenant_id" not in body["data"]["items"][0]
|
||||
assert "handling_scope" not in body["data"]["items"][0]
|
||||
assert "recovered" not in body["data"]["items"][0]
|
||||
|
||||
detail = viewer.get(f"/alarms/{visible}")
|
||||
assert detail.status_code == 200, detail.text
|
||||
assert detail.json()["data"]["id"] == visible
|
||||
assert detail.json()["data"]["status"] == "pending"
|
||||
|
||||
hidden_detail = viewer.get(f"/alarms/{hidden}")
|
||||
_assert_not_found(hidden_detail)
|
||||
_assert_not_found(viewer.get(f"/alarms/{uuid.uuid4()}"))
|
||||
_assert_not_found(viewer.get("/alarms/not-a-uuid"))
|
||||
_assert_not_found(outsider.get(f"/alarms/{visible}"))
|
||||
_assert_not_found(outsider.get(f"/alarms/{visible}/occurrences"))
|
||||
_assert_not_found(outsider.get(f"/alarms/{visible}/history"))
|
||||
_assert_not_found(outsider.get(f"/alarms/{visible}/close-validity"))
|
||||
|
||||
claim = viewer.post(f"/alarms/{visible}/claim", headers=_key("viewer-claim"))
|
||||
_assert_forbidden(claim, ALARM_TAKE_NODE)
|
||||
_assert_forbidden(
|
||||
viewer.post(
|
||||
f"/alarms/{visible}/progress",
|
||||
json={"note": "no"},
|
||||
headers=_key("viewer-progress"),
|
||||
),
|
||||
ALARM_PROGRESS_NODE,
|
||||
)
|
||||
_assert_forbidden(
|
||||
viewer.post(
|
||||
f"/alarms/{visible}/close",
|
||||
json={"result": "resolved", "note": "no"},
|
||||
headers=_key("viewer-close"),
|
||||
),
|
||||
ALARM_CLOSE_NODE,
|
||||
)
|
||||
|
||||
blank_list = blank.get("/alarms")
|
||||
assert blank_list.status_code == 200, blank_list.text
|
||||
assert blank_list.json()["data"]["total"] == 0
|
||||
_assert_forbidden(blank.post(f"/alarms/{visible}/claim", headers=_key("blank")), ALARM_TAKE_NODE)
|
||||
_assert_forbidden(unknown.get("/alarms"), ALARM_READ_NODE)
|
||||
anon_response = anon.get("/alarms")
|
||||
assert anon_response.status_code == 401
|
||||
assert anon_response.json()["success"] is False
|
||||
assert anon_response.json()["error"]["code"] == 41000
|
||||
|
||||
|
||||
def test_commands_conflict_idempotency_and_same_content_replay(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||
"""A-041–A-043: one handler, 409 conflicts, and D37 same-content close replay."""
|
||||
factory, registry, settings, tokens = alarm_api
|
||||
alarm_id, built, snapshot = _open_one(factory, registry, settings, subjects=(OP, OTHER_OP, ADMIN))
|
||||
operator = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OP)
|
||||
other = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OTHER_OP)
|
||||
admin = _client(factory, settings, tokens, roles=[ROLE_ADMIN], subject=ADMIN)
|
||||
|
||||
early = operator.post(
|
||||
f"/alarms/{alarm_id}/close",
|
||||
json={"result": "resolved", "note": "too early"},
|
||||
headers=_key("early-close"),
|
||||
)
|
||||
_assert_conflict(early, "illegal_transition")
|
||||
assert operator.get(f"/alarms/{alarm_id}").json()["data"]["status"] == "pending"
|
||||
|
||||
missing = operator.post(f"/alarms/{alarm_id}/claim")
|
||||
assert missing.status_code == 400
|
||||
assert missing.json()["error"]["code"] == 40000
|
||||
assert missing.json()["error"]["details"]["reason"] == "idempotency_key_required"
|
||||
|
||||
long_key = "k" * 129
|
||||
too_long = operator.post(f"/alarms/{alarm_id}/claim", headers={"x-idempotency-key": long_key})
|
||||
assert too_long.status_code == 400, too_long.text
|
||||
assert too_long.json()["error"]["code"] == 40000
|
||||
assert too_long.json()["error"]["details"]["reason"] == "idempotency_key_too_long"
|
||||
assert operator.get(f"/alarms/{alarm_id}").json()["data"]["status"] == "pending"
|
||||
|
||||
extra = operator.post(
|
||||
f"/alarms/{alarm_id}/claim",
|
||||
json={"tenant_id": "other"},
|
||||
headers=_key("extra"),
|
||||
)
|
||||
assert extra.status_code == 400
|
||||
assert extra.json()["error"]["code"] == 40000
|
||||
|
||||
claim_key = _key("claim")
|
||||
request_id = f"req-{uuid.uuid4().hex}"
|
||||
claimed = operator.post(
|
||||
f"/alarms/{alarm_id}/claim",
|
||||
headers={**claim_key, "X-Request-Id": request_id},
|
||||
)
|
||||
assert claimed.status_code == 200, claimed.text
|
||||
assert claimed.headers["X-Request-Id"] == request_id
|
||||
assert claimed.json()["request_id"] == request_id
|
||||
claim_data = claimed.json()["data"]
|
||||
assert claim_data["replayed"] is False
|
||||
assert claim_data["status"] == "processing"
|
||||
assert claim_data["current_handler"] == OP
|
||||
replay = operator.post(f"/alarms/{alarm_id}/claim", headers=claim_key)
|
||||
assert replay.status_code == 200, replay.text
|
||||
assert replay.json()["data"]["replayed"] is True
|
||||
assert replay.json()["data"]["event_id"] == claim_data["event_id"]
|
||||
mismatch = operator.post(
|
||||
f"/alarms/{uuid.uuid4()}/claim",
|
||||
headers=claim_key,
|
||||
)
|
||||
# The key's payload includes the original alarm id, so another path conflicts
|
||||
# only after scope. This id is not visible, so it stays not found.
|
||||
_assert_not_found(mismatch)
|
||||
changed = operator.post(f"/alarms/{alarm_id}/claim", json={"note": "different"}, headers=claim_key)
|
||||
assert changed.status_code == 400
|
||||
|
||||
stolen = other.post(f"/alarms/{alarm_id}/claim", headers=_key("steal"))
|
||||
_assert_conflict(stolen, "already_claimed")
|
||||
assert operator.get(f"/alarms/{alarm_id}").json()["data"]["current_handler"] == OP
|
||||
|
||||
progress_key = _key("progress")
|
||||
progress = operator.post(
|
||||
f"/alarms/{alarm_id}/progress",
|
||||
json={"note": "checked the line", "evidence_ref": "note-1"},
|
||||
headers=progress_key,
|
||||
)
|
||||
assert progress.status_code == 200, progress.text
|
||||
assert progress.json()["data"]["replayed"] is False
|
||||
again = operator.post(
|
||||
f"/alarms/{alarm_id}/progress",
|
||||
json={"note": "checked the line", "evidence_ref": "note-1"},
|
||||
headers=progress_key,
|
||||
)
|
||||
assert again.json()["data"]["event_id"] == progress.json()["data"]["event_id"]
|
||||
assert again.json()["data"]["replayed"] is True
|
||||
other_note = operator.post(
|
||||
f"/alarms/{alarm_id}/progress",
|
||||
json={"note": "a different note"},
|
||||
headers=progress_key,
|
||||
)
|
||||
_assert_conflict(other_note, "idempotency_payload_mismatch")
|
||||
not_handler = other.post(
|
||||
f"/alarms/{alarm_id}/progress",
|
||||
json={"note": "not mine"},
|
||||
headers=_key("other-progress"),
|
||||
)
|
||||
_assert_conflict(not_handler, "not_current_handler")
|
||||
|
||||
close_key = _key("close")
|
||||
closed = operator.post(
|
||||
f"/alarms/{alarm_id}/close",
|
||||
json={"result": "resolved", "note": "line is stable"},
|
||||
headers=close_key,
|
||||
)
|
||||
assert closed.status_code == 200, closed.text
|
||||
assert closed.json()["data"]["status"] == "closed"
|
||||
assert closed.json()["data"]["close_result"] == "resolved"
|
||||
assert closed.json()["data"]["replayed"] is False
|
||||
same_key = operator.post(
|
||||
f"/alarms/{alarm_id}/close",
|
||||
json={"result": "resolved", "note": "line is stable"},
|
||||
headers=close_key,
|
||||
)
|
||||
assert same_key.json()["data"]["replayed"] is True
|
||||
assert same_key.json()["data"]["event_id"] == closed.json()["data"]["event_id"]
|
||||
same_content = operator.post(
|
||||
f"/alarms/{alarm_id}/close",
|
||||
json={"result": "resolved", "note": "line is stable"},
|
||||
headers=_key("close-again"),
|
||||
)
|
||||
assert same_content.status_code == 200, same_content.text
|
||||
assert same_content.json()["data"]["replayed"] is True
|
||||
assert same_content.json()["data"]["event_id"] == closed.json()["data"]["event_id"]
|
||||
different = operator.post(
|
||||
f"/alarms/{alarm_id}/close",
|
||||
json={"result": "false_positive", "note": "line is stable"},
|
||||
headers=_key("close-other"),
|
||||
)
|
||||
_assert_conflict(different, "already_closed")
|
||||
|
||||
history = operator.get(f"/alarms/{alarm_id}/history")
|
||||
assert history.status_code == 200, history.text
|
||||
commands = [item["command"] for item in history.json()["data"]["items"]]
|
||||
assert commands == ["claim", "progress", "close"]
|
||||
assert history.json()["data"]["items"][1]["note"] == "checked the line"
|
||||
validity = operator.get(f"/alarms/{alarm_id}/close-validity")
|
||||
assert validity.json()["data"]["unexecuted_intents_should_invalidate"] is True
|
||||
occurrences = operator.get(f"/alarms/{alarm_id}/occurrences")
|
||||
assert len(occurrences.json()["data"]["items"]) == 1
|
||||
assert occurrences.json()["data"]["items"][0]["mapped_input_revision_id"] == str(built.revision_id)
|
||||
|
||||
revision_id = _revise(factory, settings.tenant_id, built, 90)
|
||||
_append_evidence(factory, settings.tenant_id, built, snapshot, revision_id)
|
||||
evidence = operator.get(f"/alarms/{alarm_id}/evidence")
|
||||
assert evidence.status_code == 200, evidence.text
|
||||
assert len(evidence.json()["data"]["revision_evidence"]) == 1
|
||||
assert evidence.json()["data"]["closed_basis"] == []
|
||||
assert "recovered" not in evidence.text
|
||||
|
||||
# Admin is in scope but is not the handler; the service still allows the close.
|
||||
# This alarm is already closed, so a different note conflicts rather than reopening.
|
||||
admin_close = admin.post(
|
||||
f"/alarms/{alarm_id}/close",
|
||||
json={"result": "resolved", "note": "admin review"},
|
||||
headers=_key("admin-close"),
|
||||
)
|
||||
_assert_conflict(admin_close, "already_closed")
|
||||
|
||||
|
||||
def test_admin_can_close_and_cannot_read_outside_scope(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||
"""Admin still needs a snapshot subject. ID alone is not authorization."""
|
||||
factory, registry, settings, tokens = alarm_api
|
||||
alarm_id, _built, _snapshot_value = _open_one(
|
||||
factory, registry, settings, subjects=(OP, ADMIN)
|
||||
)
|
||||
hidden, _built_hidden, _hidden_snapshot = _open_one(
|
||||
factory, registry, settings, subjects=(OUTSIDER,), scenario_key="hidden-temp"
|
||||
)
|
||||
operator = _client(factory, settings, tokens, roles=[ROLE_OPERATOR], subject=OP)
|
||||
admin = _client(factory, settings, tokens, roles=[ROLE_ADMIN], subject=ADMIN)
|
||||
assert operator.post(f"/alarms/{alarm_id}/claim", headers=_key("op-claim")).status_code == 200
|
||||
closed = admin.post(
|
||||
f"/alarms/{alarm_id}/close",
|
||||
json={"result": "false_positive", "note": "admin closed it"},
|
||||
headers=_key("admin-close"),
|
||||
)
|
||||
assert closed.status_code == 200, closed.text
|
||||
assert closed.json()["data"]["close_result"] == "false_positive"
|
||||
assert closed.json()["data"]["current_handler"] == OP
|
||||
_assert_not_found(admin.get(f"/alarms/{hidden}"))
|
||||
_assert_not_found(admin.post(f"/alarms/{hidden}/claim", headers=_key("admin-hidden")))
|
||||
listed = admin.get("/alarms")
|
||||
ids = {item["id"] for item in listed.json()["data"]["items"]}
|
||||
assert alarm_id in ids
|
||||
assert hidden not in ids
|
||||
|
||||
|
||||
def test_list_filters_sort_and_pages_in_sql(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||
"""D25: filters apply when sent, and sort plus page run on the server."""
|
||||
factory, registry, settings, tokens = alarm_api
|
||||
marker = uuid.uuid4().hex[:8]
|
||||
early, _built, _snap = _open_one(
|
||||
factory,
|
||||
registry,
|
||||
settings,
|
||||
subjects=(OP,),
|
||||
module_key=f"alpha-{marker}",
|
||||
scenario_key=f"a-line-{marker}",
|
||||
scenario_name=f"Alpha {marker}",
|
||||
event_key="event-early",
|
||||
observed_at=OBSERVED,
|
||||
)
|
||||
late, _late_built, _late_snap = _open_one(
|
||||
factory,
|
||||
registry,
|
||||
settings,
|
||||
subjects=(OP,),
|
||||
module_key=f"beta-{marker}",
|
||||
scenario_key=f"b-line-{marker}",
|
||||
scenario_name=f"Beta {marker}",
|
||||
event_key="event-late",
|
||||
observed_at=OBSERVED + timedelta(hours=2),
|
||||
)
|
||||
client = _client(factory, settings, tokens, roles=[ROLE_VIEWER], subject=OP)
|
||||
both = client.get("/alarms", params={"scenario_name": marker})
|
||||
assert both.json()["data"]["total"] == 2
|
||||
alpha = client.get("/alarms", params={"module_key": f"alpha-{marker}"})
|
||||
assert [item["id"] for item in alpha.json()["data"]["items"]] == [early]
|
||||
named = client.get("/alarms", params={"scenario_name": f"Beta {marker}"})
|
||||
assert [item["id"] for item in named.json()["data"]["items"]] == [late]
|
||||
window = client.get(
|
||||
"/alarms",
|
||||
params={
|
||||
"scenario_name": marker,
|
||||
"occurred_from": (OBSERVED + timedelta(hours=1)).isoformat(),
|
||||
},
|
||||
)
|
||||
assert [item["id"] for item in window.json()["data"]["items"]] == [late]
|
||||
page = client.get(
|
||||
"/alarms",
|
||||
params={
|
||||
"scenario_name": marker,
|
||||
"sort_by": "scenario_key",
|
||||
"sort_order": "asc",
|
||||
"page": 1,
|
||||
"page_size": 1,
|
||||
},
|
||||
)
|
||||
assert page.status_code == 200, page.text
|
||||
assert page.json()["data"]["page_size"] == 1
|
||||
assert page.json()["data"]["total"] == 2
|
||||
assert page.json()["data"]["items"][0]["id"] == early
|
||||
second = client.get(
|
||||
"/alarms",
|
||||
params={
|
||||
"scenario_name": marker,
|
||||
"sort_by": "scenario_key",
|
||||
"sort_order": "asc",
|
||||
"page": 2,
|
||||
"page_size": 1,
|
||||
},
|
||||
)
|
||||
assert second.json()["data"]["items"][0]["id"] == late
|
||||
bad_sort = client.get("/alarms", params={"sort_by": "tenant_id"})
|
||||
assert bad_sort.status_code == 400
|
||||
assert bad_sort.json()["error"]["code"] == 40000
|
||||
naive = client.get("/alarms", params={"occurred_from": "2026-11-19T01:00:00"})
|
||||
assert naive.status_code == 400
|
||||
assert naive.json()["error"]["details"]["reason"] == "timestamp_timezone_required"
|
||||
|
||||
|
||||
def test_trial_outcome_does_not_create_a_listed_alarm(alarm_api) -> None: # type: ignore[no-untyped-def]
|
||||
"""S1 regression: a trial abnormal result still adds nothing the API can list."""
|
||||
factory, registry, settings, tokens = alarm_api
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
session = _open_session(factory, settings.tenant_id)
|
||||
try:
|
||||
result = apply_monitored_outcome(
|
||||
session,
|
||||
source="trial",
|
||||
outcome="result",
|
||||
code="abnormal",
|
||||
failure=_failure(built, _scope_snapshot(built, (OP,))),
|
||||
)
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
assert result is None
|
||||
client = _client(factory, settings, tokens, roles=[ROLE_ADMIN], subject=OP)
|
||||
listed = client.get("/alarms", params={"mapped_input_id": str(built.input_id)})
|
||||
assert listed.status_code == 200, listed.text
|
||||
assert listed.json()["data"]["items"] == []
|
||||
|
||||
|
||||
def _assert_forbidden(response, node: str) -> None: # type: ignore[no-untyped-def]
|
||||
assert response.status_code == 403, response.text
|
||||
body = response.json()
|
||||
assert body["success"] is False
|
||||
assert body["error"]["code"] == 42000
|
||||
assert body["error"]["permission_node"] == node
|
||||
assert "data" not in body
|
||||
|
||||
|
||||
def _assert_not_found(response) -> None: # type: ignore[no-untyped-def]
|
||||
assert response.status_code == 404, response.text
|
||||
body = response.json()
|
||||
assert body["success"] is False
|
||||
assert body["error"]["code"] == 40000
|
||||
assert body["error"]["details"]["reason"] == "not_found"
|
||||
assert "permission_node" not in body["error"]
|
||||
|
||||
|
||||
def _assert_conflict(response, reason: str) -> None: # type: ignore[no-untyped-def]
|
||||
assert response.status_code == 409, response.text
|
||||
body = response.json()
|
||||
assert body["success"] is False
|
||||
assert body["error"]["code"] == 40000
|
||||
assert body["error"]["details"]["reason"] == reason
|
||||
assert "permission_node" not in body["error"]
|
||||
assert body["request_id"]
|
||||
|
||||
|
||||
def _key(prefix: str) -> dict[str, str]:
|
||||
return {"x-idempotency-key": f"{prefix}-{uuid.uuid4().hex}"}
|
||||
|
||||
|
||||
class _NoDirectory:
|
||||
def lookup_roles(self, *, login_name: str) -> list[str]:
|
||||
raise AssertionError("a fresh session must not reload roles")
|
||||
|
||||
|
||||
def _client(factory, settings, tokens: list[str], *, roles: list[str] | None, subject: str) -> TestClient: # type: ignore[no-untyped-def]
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
app = create_app()
|
||||
app.dependency_overrides[get_role_directory] = lambda: _NoDirectory()
|
||||
client = TestClient(app)
|
||||
if roles is not None:
|
||||
client.cookies.set(SESSION_COOKIE_NAME, _seed(factory, settings, tokens, roles, subject))
|
||||
return client
|
||||
|
||||
|
||||
def _seed(factory, settings, tokens: list[str], roles: list[str], subject: str) -> str: # type: ignore[no-untyped-def]
|
||||
token = issue_cookie_token()
|
||||
now = datetime.now(timezone.utc)
|
||||
session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
session.add(
|
||||
AuthSession(
|
||||
token_hash=hash_cookie_token(token),
|
||||
subject=subject,
|
||||
issuer="https://casdoor.test",
|
||||
display_name="Alarm Worker",
|
||||
login_name=f"worker-{uuid.uuid4().hex[:8]}",
|
||||
role_snapshot=list(roles),
|
||||
role_checked_at=now,
|
||||
expires_at=now + timedelta(hours=1),
|
||||
tenant_id=settings.tenant_id,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
tokens.append(token)
|
||||
return token
|
||||
|
||||
|
||||
def _open_session(factory, tenant_id: str) -> Session: # type: ignore[no-untyped-def]
|
||||
session = factory()
|
||||
set_tenant(session, tenant_id)
|
||||
return session
|
||||
|
||||
|
||||
def _scope_snapshot(built, subjects: tuple[str, ...], **overrides: object): # type: ignore[no-untyped-def]
|
||||
scope = {
|
||||
"principals": [{"kind": "subject", "value": subject} for subject in subjects]
|
||||
+ [{"kind": "role", "value": ROLE_OPERATOR}]
|
||||
}
|
||||
return _snapshot(built, handling_scope=scope, **overrides)
|
||||
|
||||
|
||||
def _failure(built, snapshot, **overrides: object) -> FormalFailure: # type: ignore[no-untyped-def]
|
||||
values = {
|
||||
"mapped_input_revision_id": built.revision_id,
|
||||
"snapshot": snapshot,
|
||||
"observed_at": OBSERVED,
|
||||
"received_at": RECEIVED,
|
||||
"cycle_key": "cycle-2026-11",
|
||||
"event_key": "event-overheat",
|
||||
}
|
||||
values.update(overrides)
|
||||
return FormalFailure(**values) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def _open_one(factory, registry, settings, *, subjects: tuple[str, ...], **overrides: object): # type: ignore[no-untyped-def]
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
snapshot_overrides = {
|
||||
key: overrides.pop(key)
|
||||
for key in ("module_key", "scenario_key", "scenario_name")
|
||||
if key in overrides
|
||||
}
|
||||
snapshot = _scope_snapshot(built, subjects, **snapshot_overrides)
|
||||
session = _open_session(factory, settings.tenant_id)
|
||||
try:
|
||||
created = apply_monitored_outcome(
|
||||
session,
|
||||
source="formal",
|
||||
outcome="result",
|
||||
code="abnormal",
|
||||
failure=_failure(built, snapshot, **overrides),
|
||||
)
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
assert created is not None and created.alarm_id is not None
|
||||
return str(created.alarm_id), built, snapshot
|
||||
|
||||
|
||||
def _open_pair(factory, registry, settings): # type: ignore[no-untyped-def]
|
||||
visible, _built, _snapshot_value = _open_one(factory, registry, settings, subjects=(OP, ADMIN))
|
||||
hidden, _hidden_built, _hidden_snapshot = _open_one(
|
||||
factory,
|
||||
registry,
|
||||
settings,
|
||||
subjects=(OUTSIDER,),
|
||||
scenario_key="other-temp",
|
||||
event_key="event-hidden",
|
||||
)
|
||||
return visible, hidden
|
||||
|
||||
|
||||
def _append_evidence(factory, tenant_id: str, built, snapshot, revision_id: uuid.UUID) -> None: # type: ignore[no-untyped-def]
|
||||
session = _open_session(factory, tenant_id)
|
||||
try:
|
||||
append_same_cycle_revision(
|
||||
session,
|
||||
SameCycleCorrection(
|
||||
mapped_input_revision_id=revision_id,
|
||||
snapshot=snapshot,
|
||||
cycle_key="cycle-2026-11",
|
||||
event_key="event-overheat",
|
||||
received_at=RECEIVED + timedelta(minutes=5),
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
raise
|
||||
finally:
|
||||
session.close()
|
||||
@@ -0,0 +1,643 @@
|
||||
"""S2 forward handling, close validity, and direct-status rejection on PostgreSQL.
|
||||
|
||||
Boundary: covers claim, progress, close, idempotency, and the derived close flag.
|
||||
Does not cover alarm routes, permission-node registration, or a frontend.
|
||||
Depends on S1 facts and the handling transition function.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import timedelta
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import func, select, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from _privileged_cleanup import _superuser_engine
|
||||
from test_alarm_occurrences import ( # type: ignore[attr-defined]
|
||||
OBSERVED,
|
||||
RECEIVED,
|
||||
alarm_db,
|
||||
_build,
|
||||
_failure,
|
||||
_open,
|
||||
_revise,
|
||||
_snapshot,
|
||||
)
|
||||
from watchman.auth.access import ROLE_ADMIN, ROLE_OPERATOR, ROLE_VIEWER
|
||||
from watchman.core.db import set_tenant
|
||||
from watchman.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from watchman.models.alarm import Alarm, AlarmOccurrence
|
||||
from watchman.models.alarm_handling import AlarmClosedBasis, AlarmHandlingCommand, AlarmHandlingEvent
|
||||
from watchman.services.alarm_handling import (
|
||||
HandlingActor,
|
||||
append_progress,
|
||||
claim_alarm,
|
||||
close_alarm,
|
||||
close_validity,
|
||||
)
|
||||
from watchman.services.alarms import apply_monitored_outcome
|
||||
|
||||
SCOPE = {
|
||||
"principals": [
|
||||
{"kind": "subject", "value": "line-a"},
|
||||
{"kind": "subject", "value": "line-b"},
|
||||
{"kind": "subject", "value": "line-admin"},
|
||||
{"kind": "role", "value": "watchman-operator"},
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _operator(subject: str = "line-a") -> HandlingActor:
|
||||
return HandlingActor(subject=subject, roles=(ROLE_OPERATOR,))
|
||||
|
||||
|
||||
def _admin() -> HandlingActor:
|
||||
return HandlingActor(subject="line-admin", roles=(ROLE_ADMIN,))
|
||||
|
||||
|
||||
def _key(prefix: str) -> str:
|
||||
return f"{prefix}-{uuid.uuid4()}"
|
||||
|
||||
|
||||
def _events(session, alarm_id: uuid.UUID) -> list[AlarmHandlingEvent]: # type: ignore[no-untyped-def]
|
||||
return list(
|
||||
session.scalars(
|
||||
select(AlarmHandlingEvent)
|
||||
.where(AlarmHandlingEvent.alarm_id == alarm_id)
|
||||
.order_by(AlarmHandlingEvent.seq.asc())
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _opened(alarm_db): # type: ignore[no-untyped-def]
|
||||
"""Create one pending alarm whose scope names the handling subjects."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
session = _open(factory, settings.tenant_id)
|
||||
created = None
|
||||
try:
|
||||
created = apply_monitored_outcome(
|
||||
session,
|
||||
source="formal",
|
||||
outcome="result",
|
||||
code="abnormal",
|
||||
failure=_failure(built, _snapshot(built, handling_scope=SCOPE)),
|
||||
)
|
||||
session.commit()
|
||||
except Exception:
|
||||
session.rollback()
|
||||
session.close()
|
||||
raise
|
||||
assert created is not None and created.occurrence_id is not None
|
||||
return factory, settings, built, session, created
|
||||
|
||||
|
||||
def test_forward_handling_keeps_history_and_original_fact(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V034–V036: pending becomes processing then closed, and older notes stay put."""
|
||||
_factory, settings, built, session, created = _opened(alarm_db)
|
||||
try:
|
||||
actor = _operator()
|
||||
with pytest.raises(ConflictError) as pending_close:
|
||||
close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
result="resolved",
|
||||
note="too early",
|
||||
idempotency_key=_key("early"),
|
||||
)
|
||||
assert pending_close.value.details["reason"] == "illegal_transition"
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
|
||||
claim = claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("claim"))
|
||||
session.commit()
|
||||
first = append_progress(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
note="checked the sensor",
|
||||
idempotency_key=_key("note-1"),
|
||||
)
|
||||
session.commit()
|
||||
second = append_progress(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
note="replaced the probe",
|
||||
evidence_ref="bench-log-1",
|
||||
idempotency_key=_key("note-2"),
|
||||
)
|
||||
session.commit()
|
||||
closed = close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
result="false_positive",
|
||||
note="probe drift",
|
||||
idempotency_key=_key("close"),
|
||||
)
|
||||
session.commit()
|
||||
|
||||
alarm = session.get(Alarm, created.alarm_id)
|
||||
occurrence = session.get(AlarmOccurrence, created.occurrence_id)
|
||||
history = _events(session, created.alarm_id)
|
||||
kept_first = session.get(AlarmHandlingEvent, first.event_id)
|
||||
kept_second = session.get(AlarmHandlingEvent, second.event_id)
|
||||
assert alarm is not None and occurrence is not None
|
||||
assert kept_first is not None and kept_second is not None
|
||||
assert claim.replayed is False and claim.status == "processing"
|
||||
assert alarm.status == "closed"
|
||||
assert alarm.current_handler == "line-a"
|
||||
assert alarm.close_result == "false_positive"
|
||||
assert alarm.claimed_at is not None and alarm.closed_at is not None
|
||||
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||
assert alarm.occurrence_count == 1
|
||||
details = [(item.command, item.note, item.recorded_at.isoformat()) for item in history]
|
||||
assert [item[0] for item in details] == ["claim", "progress", "progress", "close"], details
|
||||
assert kept_first.note == "checked the sensor"
|
||||
assert kept_first.actor_subject == "line-a"
|
||||
assert kept_first.command == "progress"
|
||||
assert kept_second.note == "replaced the probe"
|
||||
assert kept_second.evidence_ref == "bench-log-1"
|
||||
assert kept_first.recorded_at <= kept_second.recorded_at
|
||||
assert closed.close_result == "false_positive"
|
||||
assert closed.event_id == history[-1].id
|
||||
with pytest.raises(ConflictError) as reopen:
|
||||
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("reopen"))
|
||||
assert reopen.value.details["reason"] == "illegal_transition"
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_claim_and_close_authorization(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V036: viewer, outsider, and a non-handler operator are rejected; admin may close."""
|
||||
_factory, settings, _built, session, created = _opened(alarm_db)
|
||||
try:
|
||||
with pytest.raises(ForbiddenError) as viewer:
|
||||
claim_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=HandlingActor(subject="line-a", roles=(ROLE_VIEWER,)),
|
||||
idempotency_key=_key("viewer"),
|
||||
)
|
||||
assert viewer.value.permission_node is None
|
||||
with pytest.raises(NotFoundError):
|
||||
claim_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator("line-other"),
|
||||
idempotency_key=_key("outsider"),
|
||||
)
|
||||
with pytest.raises(NotFoundError):
|
||||
claim_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator("watchman-operator"),
|
||||
idempotency_key=_key("role-only"),
|
||||
)
|
||||
with pytest.raises(NotFoundError):
|
||||
claim_alarm(
|
||||
session,
|
||||
alarm_id=uuid.uuid4(),
|
||||
actor=_operator(),
|
||||
idempotency_key=_key("missing"),
|
||||
)
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
claim_alarm(session, alarm_id=created.alarm_id, actor=_operator(), idempotency_key=_key("claim"))
|
||||
session.commit()
|
||||
with pytest.raises(ConflictError) as rival:
|
||||
append_progress(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_admin(),
|
||||
note="admin is not the handler",
|
||||
idempotency_key=_key("admin-note"),
|
||||
)
|
||||
assert rival.value.details["reason"] == "not_current_handler"
|
||||
with pytest.raises(ConflictError) as other:
|
||||
close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator("line-b"),
|
||||
result="resolved",
|
||||
note="not mine",
|
||||
idempotency_key=_key("other-close"),
|
||||
)
|
||||
assert other.value.details["reason"] == "not_current_handler"
|
||||
with pytest.raises(ValidationError) as missing_note:
|
||||
close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_admin(),
|
||||
result="resolved",
|
||||
note=" ",
|
||||
idempotency_key=_key("blank"),
|
||||
)
|
||||
assert missing_note.value.details["reason"] == "close_note_required"
|
||||
with pytest.raises(ValidationError) as bad_result:
|
||||
close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_admin(),
|
||||
result="recovered",
|
||||
note="not a result",
|
||||
idempotency_key=_key("bad-result"),
|
||||
)
|
||||
assert bad_result.value.details["reason"] == "close_result_invalid"
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
closed = close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_admin(),
|
||||
result="resolved",
|
||||
note="admin closed it",
|
||||
idempotency_key=_key("admin-close"),
|
||||
)
|
||||
session.commit()
|
||||
alarm = session.get(Alarm, created.alarm_id)
|
||||
assert alarm is not None
|
||||
assert closed.status == "closed"
|
||||
assert alarm.current_handler == "line-a"
|
||||
assert alarm.close_result == "resolved"
|
||||
terminal = _events(session, created.alarm_id)[-1]
|
||||
assert terminal.actor_subject == "line-admin"
|
||||
assert terminal.actor_role == ROLE_ADMIN
|
||||
assert terminal.handler_subject == "line-a"
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_command_idempotency_replays_or_conflicts(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""The same key returns the original event; the same key with another payload conflicts."""
|
||||
_factory, _settings, _built, session, created = _opened(alarm_db)
|
||||
try:
|
||||
actor = _operator()
|
||||
key = _key("claim")
|
||||
with pytest.raises(ValidationError) as missing:
|
||||
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=" ")
|
||||
assert missing.value.details["field"] == "x-idempotency-key"
|
||||
first = claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=key)
|
||||
session.commit()
|
||||
second = claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=key)
|
||||
session.commit()
|
||||
assert second.replayed is True
|
||||
assert second.event_id == first.event_id
|
||||
with pytest.raises(ConflictError) as changed:
|
||||
claim_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator("line-b"),
|
||||
idempotency_key=key,
|
||||
)
|
||||
assert changed.value.details["reason"] == "idempotency_payload_mismatch"
|
||||
session.rollback()
|
||||
note_key = _key("note")
|
||||
append_progress(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
note="first wording",
|
||||
idempotency_key=note_key,
|
||||
)
|
||||
session.commit()
|
||||
replayed = append_progress(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
note="first wording",
|
||||
idempotency_key=note_key,
|
||||
)
|
||||
session.commit()
|
||||
assert replayed.replayed is True
|
||||
with pytest.raises(ConflictError) as other_note:
|
||||
append_progress(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
note="different wording",
|
||||
idempotency_key=note_key,
|
||||
)
|
||||
assert other_note.value.details["reason"] == "idempotency_payload_mismatch"
|
||||
session.rollback()
|
||||
assert len(_events(session, created.alarm_id)) == 2
|
||||
assert int(
|
||||
session.scalar(
|
||||
select(func.count()).select_from(AlarmHandlingCommand).where(
|
||||
AlarmHandlingCommand.alarm_id == created.alarm_id
|
||||
)
|
||||
)
|
||||
or 0
|
||||
) == 2
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_concurrent_claim_and_close_have_one_outcome(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V034 / V036: two claimers leave one handler, and two closes leave one terminal event."""
|
||||
factory, settings, _built, session, created = _opened(alarm_db)
|
||||
session.close()
|
||||
|
||||
def _claim(subject: str, key: str) -> str:
|
||||
local = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
claim_alarm(
|
||||
local,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator(subject),
|
||||
idempotency_key=key,
|
||||
)
|
||||
local.commit()
|
||||
return "ok"
|
||||
except ConflictError as exc:
|
||||
local.rollback()
|
||||
return str(exc.details["reason"])
|
||||
finally:
|
||||
local.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
outcomes = list(pool.map(lambda subject: _claim(subject, _key("race")), ("line-a", "line-b")))
|
||||
assert sorted(outcomes) == ["already_claimed", "ok"]
|
||||
check = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
alarm = check.get(Alarm, created.alarm_id)
|
||||
assert alarm is not None
|
||||
assert alarm.status == "processing"
|
||||
assert alarm.current_handler in {"line-a", "line-b"}
|
||||
assert len(_events(check, created.alarm_id)) == 1
|
||||
winner = alarm.current_handler
|
||||
assert winner is not None
|
||||
close_alarm(
|
||||
check,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator(winner),
|
||||
result="resolved",
|
||||
note="shared close",
|
||||
idempotency_key=_key("seed-close"),
|
||||
)
|
||||
check.commit()
|
||||
finally:
|
||||
check.close()
|
||||
|
||||
def _close(note: str) -> str:
|
||||
local = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
close_alarm(
|
||||
local,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator(winner),
|
||||
result="resolved",
|
||||
note=note,
|
||||
idempotency_key=_key("close-race"),
|
||||
)
|
||||
local.commit()
|
||||
return "ok"
|
||||
except ConflictError as exc:
|
||||
local.rollback()
|
||||
return str(exc.details["reason"])
|
||||
finally:
|
||||
local.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
close_outcomes = list(pool.map(_close, ("shared close", "a different ending")))
|
||||
assert "ok" in close_outcomes
|
||||
assert "already_closed" in close_outcomes
|
||||
final = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
alarm = final.get(Alarm, created.alarm_id)
|
||||
closes = [item for item in _events(final, created.alarm_id) if item.command == "close"]
|
||||
assert alarm is not None
|
||||
assert alarm.status == "closed"
|
||||
assert alarm.close_result == "resolved"
|
||||
assert len(closes) == 1
|
||||
assert closes[0].note == "shared close"
|
||||
finally:
|
||||
final.close()
|
||||
|
||||
|
||||
def test_repeated_claim_key_is_safe_under_concurrency(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""Two deliveries of one claim key create one event."""
|
||||
factory, settings, _built, session, created = _opened(alarm_db)
|
||||
session.close()
|
||||
key = _key("same")
|
||||
|
||||
def _once() -> uuid.UUID:
|
||||
local = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
result = claim_alarm(
|
||||
local,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=_operator(),
|
||||
idempotency_key=key,
|
||||
)
|
||||
local.commit()
|
||||
return result.event_id
|
||||
finally:
|
||||
local.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
ids = list(pool.map(lambda _index: _once(), range(2)))
|
||||
assert ids[0] == ids[1]
|
||||
check = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
assert len(_events(check, created.alarm_id)) == 1
|
||||
finally:
|
||||
check.close()
|
||||
|
||||
|
||||
def test_direct_status_update_cannot_skip_the_service(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""A plain UPDATE cannot close a pending alarm, and a skipped edge is rejected too."""
|
||||
_factory, settings, _built, session, created = _opened(alarm_db)
|
||||
try:
|
||||
alarm = session.get(Alarm, created.alarm_id)
|
||||
assert alarm is not None
|
||||
alarm.status = "closed"
|
||||
with pytest.raises(DBAPIError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
with pytest.raises(DBAPIError):
|
||||
session.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT alarm_apply_transition(
|
||||
:alarm_id, 'closed', 'line-a', now(), now(), 'resolved'
|
||||
)
|
||||
"""
|
||||
),
|
||||
{"alarm_id": created.alarm_id},
|
||||
)
|
||||
session.commit()
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
kept = session.get(Alarm, created.alarm_id)
|
||||
assert kept is not None
|
||||
assert kept.status == "pending"
|
||||
assert kept.current_handler is None
|
||||
engine = _superuser_engine()
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
definer = conn.execute(
|
||||
text("SELECT prosecdef FROM pg_proc WHERE proname = 'alarm_apply_transition'")
|
||||
).scalar_one()
|
||||
assert definer is True
|
||||
grantees = set(
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT grantee FROM information_schema.routine_privileges
|
||||
WHERE routine_schema = 'public'
|
||||
AND routine_name = 'alarm_apply_transition'
|
||||
"""
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
finally:
|
||||
engine.dispose()
|
||||
assert "watchman_app" in grantees
|
||||
assert "PUBLIC" not in grantees
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_close_validity_is_derived_without_intent_rows(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V037 / V042: closing invalidates unexecuted intents by status only, and PASS does not reopen."""
|
||||
factory, settings, built, session, created = _opened(alarm_db)
|
||||
try:
|
||||
open_validity = close_validity(session, created.alarm_id)
|
||||
assert open_validity.unexecuted_intents_should_invalidate is False
|
||||
actor = _operator()
|
||||
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("claim"))
|
||||
close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
result="resolved",
|
||||
note="done",
|
||||
idempotency_key=_key("close"),
|
||||
)
|
||||
session.commit()
|
||||
validity = close_validity(session, created.alarm_id)
|
||||
assert validity.status == "closed"
|
||||
assert validity.unexecuted_intents_should_invalidate is True
|
||||
failure = _failure(built, _snapshot(built, handling_scope=SCOPE))
|
||||
for source, outcome, code in (
|
||||
("formal", "result", "normal"),
|
||||
("formal", "result", "unknown"),
|
||||
("formal", "error", None),
|
||||
):
|
||||
assert apply_monitored_outcome(
|
||||
session, source=source, outcome=outcome, code=code, failure=failure
|
||||
) is None
|
||||
session.commit()
|
||||
alarm = session.get(Alarm, created.alarm_id)
|
||||
occurrence = session.get(AlarmOccurrence, created.occurrence_id)
|
||||
assert alarm is not None and occurrence is not None
|
||||
assert alarm.status == "closed"
|
||||
assert alarm.close_result == "resolved"
|
||||
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||
continued = apply_monitored_outcome(
|
||||
session,
|
||||
source="formal",
|
||||
outcome="result",
|
||||
code="abnormal",
|
||||
failure=_failure(
|
||||
built,
|
||||
_snapshot(built, handling_scope=SCOPE),
|
||||
revision_id=revised,
|
||||
observed_at=OBSERVED + timedelta(minutes=3),
|
||||
received_at=RECEIVED + timedelta(minutes=3),
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
assert continued is not None and continued.created_basis is True
|
||||
assert continued.created_alarm is False
|
||||
basis = session.get(AlarmClosedBasis, continued.basis_id)
|
||||
assert basis is not None
|
||||
assert basis.original_occurrence_id == created.occurrence_id
|
||||
assert basis.mapped_input_revision_id == revised
|
||||
assert alarm.occurrence_count == 1
|
||||
engine = _superuser_engine()
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
names = list(
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT tablename FROM pg_tables
|
||||
WHERE schemaname = 'public'
|
||||
AND (
|
||||
tablename ILIKE '%intent%'
|
||||
OR tablename ILIKE '%window%'
|
||||
OR tablename ILIKE '%escalat%'
|
||||
)
|
||||
"""
|
||||
)
|
||||
).scalars()
|
||||
)
|
||||
finally:
|
||||
engine.dispose()
|
||||
assert names == []
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_handling_and_basis_rows_are_append_only(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""History, command keys, and closed basis reject update and delete."""
|
||||
factory, settings, built, session, created = _opened(alarm_db)
|
||||
try:
|
||||
actor = _operator()
|
||||
claim_alarm(session, alarm_id=created.alarm_id, actor=actor, idempotency_key=_key("claim"))
|
||||
close_alarm(
|
||||
session,
|
||||
alarm_id=created.alarm_id,
|
||||
actor=actor,
|
||||
result="resolved",
|
||||
note="closed",
|
||||
idempotency_key=_key("close"),
|
||||
)
|
||||
session.commit()
|
||||
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||
recorded = apply_monitored_outcome(
|
||||
session,
|
||||
source="formal",
|
||||
outcome="result",
|
||||
code="abnormal",
|
||||
failure=_failure(
|
||||
built,
|
||||
_snapshot(built, handling_scope=SCOPE),
|
||||
revision_id=revised,
|
||||
observed_at=OBSERVED + timedelta(minutes=4),
|
||||
),
|
||||
)
|
||||
session.commit()
|
||||
assert recorded is not None and recorded.basis_id is not None
|
||||
event = _events(session, created.alarm_id)[0]
|
||||
event.note = "rewritten"
|
||||
with pytest.raises(DBAPIError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
command = session.scalar(
|
||||
select(AlarmHandlingCommand).where(AlarmHandlingCommand.alarm_id == created.alarm_id)
|
||||
)
|
||||
assert command is not None
|
||||
session.delete(command)
|
||||
with pytest.raises(DBAPIError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
basis = session.get(AlarmClosedBasis, recorded.basis_id)
|
||||
assert basis is not None
|
||||
basis.event_key = "rewritten"
|
||||
with pytest.raises(DBAPIError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
finally:
|
||||
session.close()
|
||||
@@ -0,0 +1,797 @@
|
||||
"""S1 formal alarm facts on PostgreSQL.
|
||||
|
||||
Boundary: covers idempotent occurrences, bounded merge, new-cycle links, same-cycle
|
||||
corrections, closed-repeat basis, trial isolation, and RLS. The closed-cycle case
|
||||
closes through the handling service. Does not cover alarm APIs.
|
||||
Depends on M05 mappings, revisions, and rule versions.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, func, select, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from _privileged_cleanup import _superuser_engine, purge_query_rows
|
||||
from watchman.api.routes import mappings as mapping_routes
|
||||
from watchman.core.config import get_settings, reload_settings
|
||||
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
|
||||
from watchman.core.errors import ConflictError, ValidationError
|
||||
from watchman.models.alarm import Alarm, AlarmOccurrence, AlarmRevisionEvidence
|
||||
from watchman.models.platform import AuditEvent
|
||||
from watchman.services.alarm_handling import HandlingActor, claim_alarm, close_alarm
|
||||
from watchman.services.alarms import CLOSED_REPEAT_ACTION
|
||||
from watchman.models.datasource import DataSource
|
||||
from watchman.models.mapping import MappedInput, MappedInputRevision, MappingDefinition
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
from watchman.services import judgment
|
||||
from watchman.services.alarms import (
|
||||
FormalFailure,
|
||||
SameCycleCorrection,
|
||||
SyntheticPublishSnapshot,
|
||||
append_same_cycle_revision,
|
||||
apply_monitored_outcome,
|
||||
record_formal_failure,
|
||||
)
|
||||
from watchman.services.mappings import create_mapping, persist_mapped_rows, save_mapping_version
|
||||
from watchman.services.rules import create_rule, save_rule_version
|
||||
|
||||
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
|
||||
SCOPE = {"principals": [{"kind": "subject", "value": "line-a"}]}
|
||||
OBSERVED = datetime(2026, 11, 19, 1, 0, tzinfo=timezone.utc)
|
||||
RECEIVED = datetime(2026, 11, 19, 1, 0, 5, tzinfo=timezone.utc)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class _Built:
|
||||
mapping_definition_id: uuid.UUID
|
||||
mapping_version_id: uuid.UUID
|
||||
rule_definition_id: uuid.UUID
|
||||
rule_version_id: uuid.UUID
|
||||
input_id: uuid.UUID
|
||||
revision_id: uuid.UUID
|
||||
serial: str
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def alarm_db():
|
||||
"""Open a tenant-scoped session factory and remove only this test's rows."""
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
_ensure_after_begin_listener()
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||
datasource_ids: list[uuid.UUID] = []
|
||||
yield factory, datasource_ids, settings
|
||||
try:
|
||||
for datasource_id in datasource_ids:
|
||||
_purge_graph(datasource_id)
|
||||
purge_query_rows(datasource_id=datasource_id)
|
||||
_delete_datasource(datasource_id)
|
||||
finally:
|
||||
engine.dispose()
|
||||
reset_engine()
|
||||
|
||||
|
||||
def _purge_graph(datasource_id: uuid.UUID) -> None:
|
||||
"""Delete alarm and mapping rows for one synthetic datasource as superuser."""
|
||||
engine = _superuser_engine()
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
params = {"datasource_id": str(datasource_id)}
|
||||
definitions = (
|
||||
"SELECT id FROM mapping_definitions WHERE query_definition_id IN "
|
||||
"(SELECT id FROM query_definitions WHERE datasource_id = :datasource_id)"
|
||||
)
|
||||
inputs = f"SELECT id FROM mapped_inputs WHERE mapping_definition_id IN ({definitions})"
|
||||
alarms = f"SELECT id FROM alarms WHERE mapped_input_id IN ({inputs})"
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM audit_events WHERE action = :action "
|
||||
f"AND payload->>'alarm_id' IN (SELECT id::text FROM alarms WHERE id IN ({alarms}))"
|
||||
),
|
||||
{**params, "action": "alarm.continued_after_close"},
|
||||
)
|
||||
conn.execute(text(f"DELETE FROM alarm_handling_commands WHERE alarm_id IN ({alarms})"), params)
|
||||
conn.execute(text(f"DELETE FROM alarm_handling_events WHERE alarm_id IN ({alarms})"), params)
|
||||
conn.execute(text(f"DELETE FROM alarm_closed_basis WHERE alarm_id IN ({alarms})"), params)
|
||||
conn.execute(text(f"DELETE FROM alarm_revision_evidence WHERE alarm_id IN ({alarms})"), params)
|
||||
conn.execute(text(f"DELETE FROM alarm_occurrences WHERE alarm_id IN ({alarms})"), params)
|
||||
conn.execute(text(f"UPDATE alarms SET previous_alarm_id = NULL WHERE id IN ({alarms})"), params)
|
||||
conn.execute(text(f"DELETE FROM alarms WHERE id IN ({alarms})"), params)
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM rule_versions WHERE definition_id IN "
|
||||
f"(SELECT id FROM rule_definitions WHERE mapping_definition_id IN ({definitions}))"
|
||||
),
|
||||
params,
|
||||
)
|
||||
conn.execute(text(f"DELETE FROM rule_definitions WHERE mapping_definition_id IN ({definitions})"), params)
|
||||
conn.execute(text(f"DELETE FROM mapped_input_revisions WHERE input_id IN ({inputs})"), params)
|
||||
conn.execute(text(f"DELETE FROM mapped_inputs WHERE mapping_definition_id IN ({definitions})"), params)
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM mapping_column_configs WHERE mapping_version_id IN "
|
||||
f"(SELECT id FROM mapping_versions WHERE definition_id IN ({definitions}))"
|
||||
),
|
||||
params,
|
||||
)
|
||||
conn.execute(text(f"DELETE FROM mapping_versions WHERE definition_id IN ({definitions})"), params)
|
||||
conn.execute(text(f"DELETE FROM mapping_definitions WHERE id IN ({definitions})"), params)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _delete_datasource(datasource_id: uuid.UUID) -> None:
|
||||
engine = _superuser_engine()
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("DELETE FROM data_sources WHERE id = :id"), {"id": str(datasource_id)})
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _build(factory, registry: list[uuid.UUID], tenant_id: str) -> _Built: # type: ignore[no-untyped-def]
|
||||
"""Create one mapped input revision and one rule version under the server tenant."""
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, tenant_id)
|
||||
serial = f"SN-{uuid.uuid4().hex[:12]}"
|
||||
datasource = DataSource(
|
||||
tenant_id=tenant_id,
|
||||
name=f"alarm-ds-{uuid.uuid4().hex[:12]}",
|
||||
kind="database",
|
||||
engine="postgresql",
|
||||
host="127.0.0.1",
|
||||
port=5432,
|
||||
database_name="synthetic",
|
||||
username="synthetic_user",
|
||||
secret_ciphertext=FAKE_CIPHERTEXT,
|
||||
)
|
||||
session.add(datasource)
|
||||
session.flush()
|
||||
registry.append(datasource.id)
|
||||
query = QueryDefinition(
|
||||
tenant_id=tenant_id,
|
||||
name=f"alarm-query-{uuid.uuid4().hex[:12]}",
|
||||
datasource_id=datasource.id,
|
||||
draft_sql_template="SELECT 1",
|
||||
current_version_no=1,
|
||||
latest_published_version_no=1,
|
||||
)
|
||||
session.add(query)
|
||||
session.flush()
|
||||
session.add(
|
||||
QueryVersion(
|
||||
tenant_id=tenant_id,
|
||||
definition_id=query.id,
|
||||
version_no=1,
|
||||
sql_template="SELECT 1",
|
||||
param_schema=[],
|
||||
output_schema=[
|
||||
{"name": "serial", "type": "string"},
|
||||
{"name": "temperature", "type": "number"},
|
||||
],
|
||||
allowed_identifiers=[],
|
||||
timeout_ms=10000,
|
||||
max_rows=100,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
definition: MappingDefinition = create_mapping(session, query_definition_id=str(query.id))
|
||||
mapping_version = save_mapping_version(
|
||||
session,
|
||||
str(definition.id),
|
||||
[
|
||||
{
|
||||
"source_column_name": "serial",
|
||||
"value_type": "string",
|
||||
"is_identity": True,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
{
|
||||
"source_column_name": "temperature",
|
||||
"value_type": "number",
|
||||
"is_identity": False,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
],
|
||||
)
|
||||
persist_mapped_rows(
|
||||
session,
|
||||
str(definition.id),
|
||||
[{"serial": serial, "temperature": 80}],
|
||||
)
|
||||
rule = create_rule(session, mapping_definition_id=str(definition.id))
|
||||
rule_version = save_rule_version(
|
||||
session,
|
||||
str(rule.id),
|
||||
{"column": "temperature", "operator": "gt", "value": 100},
|
||||
)
|
||||
session.commit()
|
||||
mapped = session.scalar(
|
||||
select(MappedInput).where(MappedInput.mapping_definition_id == definition.id)
|
||||
)
|
||||
assert mapped is not None
|
||||
revision = session.scalar(
|
||||
select(MappedInputRevision).where(MappedInputRevision.input_id == mapped.id)
|
||||
)
|
||||
assert revision is not None
|
||||
return _Built(
|
||||
mapping_definition_id=definition.id,
|
||||
mapping_version_id=mapping_version.id,
|
||||
rule_definition_id=rule.id,
|
||||
rule_version_id=rule_version.id,
|
||||
input_id=mapped.id,
|
||||
revision_id=revision.id,
|
||||
serial=serial,
|
||||
)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def _revise(factory, tenant_id: str, built: _Built, temperature: int) -> uuid.UUID: # type: ignore[no-untyped-def]
|
||||
"""Append one M05 value revision and return its id. Does not touch alarms."""
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, tenant_id)
|
||||
persist_mapped_rows(
|
||||
session,
|
||||
str(built.mapping_definition_id),
|
||||
[{"serial": built.serial, "temperature": temperature}],
|
||||
)
|
||||
session.commit()
|
||||
revision_id = session.scalar(
|
||||
select(MappedInputRevision.id)
|
||||
.where(MappedInputRevision.input_id == built.input_id)
|
||||
.order_by(MappedInputRevision.revision_no.desc())
|
||||
.limit(1)
|
||||
)
|
||||
assert isinstance(revision_id, uuid.UUID)
|
||||
return revision_id
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def _snapshot(built: _Built, **overrides: object) -> SyntheticPublishSnapshot:
|
||||
values: dict[str, object] = {
|
||||
"snapshot_id": uuid.uuid4(),
|
||||
"version_no": 1,
|
||||
"module_key": "pack",
|
||||
"scenario_key": "pack-temp",
|
||||
"scenario_name": "Pack temperature",
|
||||
"handling_scope": SCOPE,
|
||||
"mapping_version_id": built.mapping_version_id,
|
||||
"rule_version_id": built.rule_version_id,
|
||||
}
|
||||
values.update(overrides)
|
||||
return SyntheticPublishSnapshot(**values) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def _failure(
|
||||
built: _Built,
|
||||
snapshot: SyntheticPublishSnapshot,
|
||||
*,
|
||||
revision_id: uuid.UUID | None = None,
|
||||
observed_at: datetime = OBSERVED,
|
||||
received_at: datetime = RECEIVED,
|
||||
cycle_key: str = "cycle-2026-11",
|
||||
event_key: str = "event-overheat",
|
||||
) -> FormalFailure:
|
||||
return FormalFailure(
|
||||
mapped_input_revision_id=revision_id or built.revision_id,
|
||||
snapshot=snapshot,
|
||||
observed_at=observed_at,
|
||||
received_at=received_at,
|
||||
cycle_key=cycle_key,
|
||||
event_key=event_key,
|
||||
)
|
||||
|
||||
|
||||
def _counts(session: Session, input_id: uuid.UUID) -> tuple[int, int, int]:
|
||||
alarms = int(
|
||||
session.scalar(select(func.count()).select_from(Alarm).where(Alarm.mapped_input_id == input_id)) or 0
|
||||
)
|
||||
occurrences = int(
|
||||
session.scalar(
|
||||
select(func.count()).select_from(AlarmOccurrence).where(AlarmOccurrence.mapped_input_id == input_id)
|
||||
)
|
||||
or 0
|
||||
)
|
||||
evidence = int(
|
||||
session.scalar(
|
||||
select(func.count())
|
||||
.select_from(AlarmRevisionEvidence)
|
||||
.where(AlarmRevisionEvidence.alarm_id.in_(select(Alarm.id).where(Alarm.mapped_input_id == input_id)))
|
||||
)
|
||||
or 0
|
||||
)
|
||||
return alarms, occurrences, evidence
|
||||
|
||||
|
||||
def _open(factory, tenant_id: str) -> Session: # type: ignore[no-untyped-def]
|
||||
session: Session = factory()
|
||||
set_tenant(session, tenant_id)
|
||||
return session
|
||||
|
||||
|
||||
def test_alarm_tables_have_no_message_merge_column() -> None:
|
||||
"""V031: merge identity is structured columns, not message text."""
|
||||
forbidden = {"message", "body", "title", "text", "payload", "payload_hash"}
|
||||
assert forbidden.isdisjoint(Alarm.__table__.columns.keys())
|
||||
assert forbidden.isdisjoint(AlarmOccurrence.__table__.columns.keys())
|
||||
assert "uq_alarms_structured_merge_key" in {item.name for item in Alarm.__table__.constraints}
|
||||
|
||||
|
||||
def test_trial_and_non_fail_outcomes_write_nothing(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V030: PASS, UNKNOWN, empty, error, and trial evaluation create no alarm rows."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
failure = _failure(built, _snapshot(built))
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
assert _counts(session, built.input_id) == (0, 0, 0)
|
||||
assert record_formal_failure(session, failure, confirmed_abnormal=False) is None
|
||||
cases = (
|
||||
("formal", "result", "normal"),
|
||||
("formal", "result", "unknown"),
|
||||
("formal", "empty", None),
|
||||
("formal", "error", None),
|
||||
("trial", "result", "abnormal"),
|
||||
)
|
||||
for source, outcome, code in cases:
|
||||
assert apply_monitored_outcome(
|
||||
session, source=source, outcome=outcome, code=code, failure=failure
|
||||
) is None
|
||||
judgment.evaluate_rows(
|
||||
[{"temperature": 200}],
|
||||
[_Column()],
|
||||
{"column": "temperature", "operator": "gt", "value": 100},
|
||||
["temperature"],
|
||||
)
|
||||
session.commit()
|
||||
assert _counts(session, built.input_id) == (0, 0, 0)
|
||||
finally:
|
||||
session.close()
|
||||
judgment_source = inspect.getsource(judgment)
|
||||
route_source = inspect.getsource(mapping_routes)
|
||||
assert "watchman.services.alarms" not in judgment_source
|
||||
assert "record_formal_failure" not in judgment_source
|
||||
assert "watchman.services.alarms" not in route_source
|
||||
|
||||
|
||||
def test_repeated_formal_failure_is_one_occurrence(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V030: the first formal FAIL opens one alarm, and a replay does not add another."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
failure = _failure(built, _snapshot(built))
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
first = record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||
session.commit()
|
||||
second = record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||
session.commit()
|
||||
assert first is not None and second is not None
|
||||
assert first.created_alarm is True
|
||||
assert first.created_occurrence is True
|
||||
assert second.created_alarm is False
|
||||
assert second.created_occurrence is False
|
||||
assert second.alarm_id == first.alarm_id
|
||||
assert second.occurrence_id == first.occurrence_id
|
||||
assert _counts(session, built.input_id) == (1, 1, 0)
|
||||
alarm = session.get(Alarm, first.alarm_id)
|
||||
assert alarm is not None
|
||||
assert alarm.status == "pending"
|
||||
assert alarm.current_handler is None
|
||||
assert alarm.previous_alarm_id is None
|
||||
assert alarm.tenant_id == settings.tenant_id
|
||||
assert alarm.handling_scope["principals"][0]["value"] == "line-a"
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_concurrent_replay_keeps_one_occurrence(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""The formal identity constraint keeps one occurrence when two transactions race."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
failure = _failure(built, _snapshot(built))
|
||||
|
||||
def _once() -> uuid.UUID:
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
result = record_formal_failure(session, failure, confirmed_abnormal=True)
|
||||
session.commit()
|
||||
assert result is not None and result.occurrence_id is not None
|
||||
return result.occurrence_id
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
ids = list(pool.map(lambda _index: _once(), range(2)))
|
||||
assert ids[0] == ids[1]
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
assert _counts(session, built.input_id) == (1, 1, 0)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_merge_range_and_new_event_link(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V031: the same structured key adds an occurrence; a new event links history."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
snapshot = _snapshot(built)
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
first = record_formal_failure(
|
||||
session, _failure(built, snapshot), confirmed_abnormal=True
|
||||
)
|
||||
session.commit()
|
||||
renamed = _snapshot(
|
||||
built,
|
||||
snapshot_id=snapshot.snapshot_id,
|
||||
scenario_name="Pack temperature renamed",
|
||||
)
|
||||
second = record_formal_failure(
|
||||
session,
|
||||
_failure(
|
||||
built,
|
||||
renamed,
|
||||
observed_at=OBSERVED + timedelta(minutes=5),
|
||||
received_at=RECEIVED + timedelta(minutes=5),
|
||||
),
|
||||
confirmed_abnormal=True,
|
||||
)
|
||||
session.commit()
|
||||
other_event = record_formal_failure(
|
||||
session,
|
||||
_failure(
|
||||
built,
|
||||
snapshot,
|
||||
observed_at=OBSERVED + timedelta(minutes=10),
|
||||
event_key="event-independent",
|
||||
),
|
||||
confirmed_abnormal=True,
|
||||
)
|
||||
session.commit()
|
||||
other_scenario = record_formal_failure(
|
||||
session,
|
||||
_failure(
|
||||
built,
|
||||
_snapshot(built, scenario_key="pack-pressure", scenario_name="Pack pressure"),
|
||||
observed_at=OBSERVED,
|
||||
event_key="event-independent",
|
||||
),
|
||||
confirmed_abnormal=True,
|
||||
)
|
||||
session.commit()
|
||||
assert first is not None and second is not None
|
||||
assert other_event is not None and other_scenario is not None
|
||||
assert second.alarm_id == first.alarm_id
|
||||
assert second.created_alarm is False
|
||||
assert second.created_occurrence is True
|
||||
assert other_event.created_alarm is True
|
||||
assert other_event.alarm_id != first.alarm_id
|
||||
linked = session.get(Alarm, other_event.alarm_id)
|
||||
original = session.get(Alarm, first.alarm_id)
|
||||
separate = session.get(Alarm, other_scenario.alarm_id)
|
||||
assert linked is not None and original is not None and separate is not None
|
||||
assert linked.previous_alarm_id == first.alarm_id
|
||||
assert original.scenario_name == "Pack temperature"
|
||||
assert original.occurrence_count == 2
|
||||
assert separate.previous_alarm_id is None
|
||||
assert _counts(session, built.input_id) == (3, 4, 0)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_closed_cycle_does_not_reopen_and_new_cycle_links(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V032 / D36: a closed cycle keeps its alarm, records basis and audit, and a new cycle links."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
snapshot = _snapshot(built)
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
first = record_formal_failure(session, _failure(built, snapshot), confirmed_abnormal=True)
|
||||
session.commit()
|
||||
assert first is not None and first.occurrence_id is not None
|
||||
actor = HandlingActor(subject="line-a", roles=("watchman-operator",))
|
||||
claim_alarm(
|
||||
session,
|
||||
alarm_id=first.alarm_id,
|
||||
actor=actor,
|
||||
idempotency_key=f"claim-{uuid.uuid4()}",
|
||||
)
|
||||
close_alarm(
|
||||
session,
|
||||
alarm_id=first.alarm_id,
|
||||
actor=actor,
|
||||
result="resolved",
|
||||
note="stop the open cycle",
|
||||
idempotency_key=f"close-{uuid.uuid4()}",
|
||||
)
|
||||
session.commit()
|
||||
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||
continued = _failure(
|
||||
built,
|
||||
snapshot,
|
||||
revision_id=revised,
|
||||
observed_at=OBSERVED + timedelta(minutes=1),
|
||||
)
|
||||
suppressed = record_formal_failure(session, continued, confirmed_abnormal=True)
|
||||
session.commit()
|
||||
assert suppressed is not None
|
||||
assert suppressed.alarm_id == first.alarm_id
|
||||
assert suppressed.suppressed is True
|
||||
assert suppressed.created_alarm is False
|
||||
assert suppressed.created_occurrence is False
|
||||
assert suppressed.created_basis is True
|
||||
assert suppressed.basis_id is not None
|
||||
replayed = record_formal_failure(session, continued, confirmed_abnormal=True)
|
||||
session.commit()
|
||||
assert replayed is not None
|
||||
assert replayed.created_basis is False
|
||||
assert replayed.basis_id == suppressed.basis_id
|
||||
closed = session.get(Alarm, first.alarm_id)
|
||||
occurrence = session.get(AlarmOccurrence, first.occurrence_id)
|
||||
assert closed is not None and occurrence is not None
|
||||
assert closed.status == "closed"
|
||||
assert closed.occurrence_count == 1
|
||||
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||
audit_count = session.scalar(
|
||||
select(func.count())
|
||||
.select_from(AuditEvent)
|
||||
.where(
|
||||
AuditEvent.action == CLOSED_REPEAT_ACTION,
|
||||
AuditEvent.payload["alarm_id"].astext == str(first.alarm_id),
|
||||
)
|
||||
)
|
||||
assert int(audit_count or 0) == 1
|
||||
assert _counts(session, built.input_id) == (1, 1, 0)
|
||||
nxt = record_formal_failure(
|
||||
session,
|
||||
_failure(built, snapshot, revision_id=revised, cycle_key="cycle-2026-12"),
|
||||
confirmed_abnormal=True,
|
||||
)
|
||||
session.commit()
|
||||
assert nxt is not None and nxt.created_alarm is True
|
||||
linked = session.get(Alarm, nxt.alarm_id)
|
||||
kept = session.get(Alarm, first.alarm_id)
|
||||
assert linked is not None and kept is not None
|
||||
assert linked.previous_alarm_id == first.alarm_id
|
||||
assert linked.status == "pending"
|
||||
assert linked.id != kept.id
|
||||
assert kept.status == "closed"
|
||||
assert kept.occurrence_count == 1
|
||||
assert _counts(session, built.input_id) == (2, 2, 0)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_same_cycle_correction_appends_evidence_only(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""V033 / D34: a same-cycle value correction keeps the original FAIL and adds no alarm."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
snapshot = _snapshot(built)
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
first = record_formal_failure(session, _failure(built, snapshot), confirmed_abnormal=True)
|
||||
session.commit()
|
||||
assert first is not None and first.occurrence_id is not None
|
||||
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||
correction = SameCycleCorrection(
|
||||
mapped_input_revision_id=revised,
|
||||
snapshot=snapshot,
|
||||
cycle_key="cycle-2026-11",
|
||||
event_key="event-overheat",
|
||||
received_at=RECEIVED + timedelta(minutes=2),
|
||||
)
|
||||
appended = append_same_cycle_revision(session, correction)
|
||||
session.commit()
|
||||
replayed = append_same_cycle_revision(session, correction)
|
||||
session.commit()
|
||||
occurrence = session.get(AlarmOccurrence, first.occurrence_id)
|
||||
alarm = session.get(Alarm, first.alarm_id)
|
||||
assert occurrence is not None and alarm is not None
|
||||
assert occurrence.mapped_input_revision_id == built.revision_id
|
||||
assert alarm.occurrence_count == 1
|
||||
assert alarm.status == "pending"
|
||||
assert appended.created_evidence is True
|
||||
assert appended.created_alarm is False
|
||||
assert replayed.created_evidence is False
|
||||
assert replayed.evidence_id == appended.evidence_id
|
||||
assert _counts(session, built.input_id) == (1, 1, 1)
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
append_same_cycle_revision(
|
||||
session,
|
||||
SameCycleCorrection(
|
||||
mapped_input_revision_id=revised,
|
||||
snapshot=snapshot,
|
||||
cycle_key="cycle-missing",
|
||||
event_key="event-overheat",
|
||||
received_at=RECEIVED,
|
||||
),
|
||||
)
|
||||
assert caught.value.details["reason"] == "correction_without_alarm"
|
||||
session.rollback()
|
||||
assert _counts(session, built.input_id) == (1, 1, 1)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_missing_scope_and_version_mismatch_write_nothing(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""D35: an undeclared or all-tenant scope, and a mismatched snapshot, do not insert."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
rejected = (
|
||||
({}, "snapshot_scope_missing"),
|
||||
({"principals": [{"kind": "role", "value": "operator"}]}, "snapshot_scope_rejects_all_tenant"),
|
||||
(
|
||||
{"all_tenant": True, "principals": [{"kind": "subject", "value": "line-a"}]},
|
||||
"snapshot_scope_rejects_all_tenant",
|
||||
),
|
||||
({"principals": [{"kind": "subject", "value": "*"}]}, "snapshot_scope_rejects_all_tenant"),
|
||||
)
|
||||
for scope, reason in rejected:
|
||||
with pytest.raises(ValidationError) as caught:
|
||||
record_formal_failure(
|
||||
session,
|
||||
_failure(built, _snapshot(built, handling_scope=scope)),
|
||||
confirmed_abnormal=True,
|
||||
)
|
||||
assert caught.value.details["reason"] == reason
|
||||
with pytest.raises(ValidationError) as mismatched:
|
||||
record_formal_failure(
|
||||
session,
|
||||
_failure(built, _snapshot(built, mapping_version_id=uuid.uuid4())),
|
||||
confirmed_abnormal=True,
|
||||
)
|
||||
assert mismatched.value.details["reason"] == "snapshot_version_mismatch"
|
||||
session.rollback()
|
||||
assert _counts(session, built.input_id) == (0, 0, 0)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_occurrence_fact_cannot_be_rewritten(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""D34: the original occurrence revision is immutable at the database."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
first = record_formal_failure(
|
||||
session, _failure(built, _snapshot(built)), confirmed_abnormal=True
|
||||
)
|
||||
session.commit()
|
||||
assert first is not None and first.occurrence_id is not None
|
||||
revised = _revise(factory, settings.tenant_id, built, 70)
|
||||
occurrence = session.get(AlarmOccurrence, first.occurrence_id)
|
||||
assert occurrence is not None
|
||||
occurrence.mapped_input_revision_id = revised
|
||||
with pytest.raises(DBAPIError):
|
||||
session.commit()
|
||||
session.rollback()
|
||||
set_tenant(session, settings.tenant_id)
|
||||
kept = session.get(AlarmOccurrence, first.occurrence_id)
|
||||
assert kept is not None
|
||||
assert kept.mapped_input_revision_id == built.revision_id
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_alarm_rls_is_forced_and_tenant_scoped(alarm_db) -> None: # type: ignore[no-untyped-def]
|
||||
"""Alarm facts are invisible without the server tenant and to any other tenant."""
|
||||
factory, registry, settings = alarm_db
|
||||
built = _build(factory, registry, settings.tenant_id)
|
||||
session = _open(factory, settings.tenant_id)
|
||||
try:
|
||||
first = record_formal_failure(
|
||||
session, _failure(built, _snapshot(built)), confirmed_abnormal=True
|
||||
)
|
||||
session.commit()
|
||||
assert first is not None
|
||||
alarm_id = first.alarm_id
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
bare: Session = factory()
|
||||
try:
|
||||
visible = bare.execute(text("SELECT count(*) FROM alarms")).scalar_one()
|
||||
assert visible == 0
|
||||
bare.add(
|
||||
Alarm(
|
||||
tenant_id=settings.tenant_id,
|
||||
status="pending",
|
||||
occurrence_count=1,
|
||||
first_occurred_at=OBSERVED,
|
||||
last_occurred_at=OBSERVED,
|
||||
mapped_input_id=built.input_id,
|
||||
mapping_definition_id=built.mapping_definition_id,
|
||||
mapping_version_id=built.mapping_version_id,
|
||||
rule_definition_id=built.rule_definition_id,
|
||||
rule_version_id=built.rule_version_id,
|
||||
snapshot_id=uuid.uuid4(),
|
||||
snapshot_version_no=1,
|
||||
module_key="pack",
|
||||
scenario_key="pack-temp",
|
||||
scenario_name="Pack temperature",
|
||||
handling_scope=SCOPE,
|
||||
cycle_key="cycle-bare",
|
||||
event_key="event-bare",
|
||||
)
|
||||
)
|
||||
with pytest.raises(DBAPIError):
|
||||
bare.commit()
|
||||
bare.rollback()
|
||||
finally:
|
||||
bare.close()
|
||||
|
||||
other = _open(factory, "other-tenant")
|
||||
try:
|
||||
seen = other.scalar(select(func.count()).select_from(Alarm).where(Alarm.id == alarm_id))
|
||||
assert int(seen or 0) == 0
|
||||
finally:
|
||||
other.close()
|
||||
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
try:
|
||||
with engine.connect() as conn:
|
||||
for table in (
|
||||
"alarms",
|
||||
"alarm_occurrences",
|
||||
"alarm_revision_evidence",
|
||||
"alarm_handling_events",
|
||||
"alarm_handling_commands",
|
||||
"alarm_closed_basis",
|
||||
):
|
||||
flags = conn.execute(
|
||||
text(
|
||||
"SELECT c.relrowsecurity, c.relforcerowsecurity, t.tableowner "
|
||||
"FROM pg_class c "
|
||||
"JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
"JOIN pg_tables t ON t.tablename = c.relname AND t.schemaname = n.nspname "
|
||||
"WHERE n.nspname = 'public' AND c.relname = :table"
|
||||
),
|
||||
{"table": table},
|
||||
).one()
|
||||
assert flags.relrowsecurity is True
|
||||
assert flags.relforcerowsecurity is True
|
||||
assert flags.tableowner != "watchman_app"
|
||||
policies = set(
|
||||
conn.execute(
|
||||
text(
|
||||
"SELECT policyname FROM pg_policies "
|
||||
"WHERE schemaname = 'public' AND tablename = :table"
|
||||
),
|
||||
{"table": table},
|
||||
).scalars()
|
||||
)
|
||||
assert "tenant_isolation" in policies
|
||||
assert policies <= {"tenant_isolation", "tenant_isolation_definer"}
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
class _Column:
|
||||
"""Minimal mapping column for the pure judgment call."""
|
||||
|
||||
source_column_name = "temperature"
|
||||
value_type = "number"
|
||||
is_identity = False
|
||||
numeric_multiply = None
|
||||
numeric_offset = None
|
||||
Reference in new issue
Block a user