astrbot_plugin_private_comp.../p4_manual_review.py

864 行
34 KiB
Python

# -*- coding: utf-8 -*-
"""Default-off P4 manual-review contracts and isolated queue helpers.
This module intentionally knows nothing about P4 shadow settlement, P4 effect
preparation, model output, pages, request carriers, or live enforcement. A
review decision is only an audited queue record; it never causes a punishment,
release, recovery, reply, or memory write.
"""
from __future__ import annotations
from copy import deepcopy
from dataclasses import dataclass
from datetime import datetime, timezone
import hashlib
import json
import re
import threading
import time
import unicodedata
from typing import Any
try:
from .context_orchestration import (
CONTRACT_NAME as P3_CONTRACT_NAME,
CONTRACT_VERSION as P3_CONTRACT_VERSION,
LAYERS as P3_LAYERS,
contract_fingerprint as p3_contract_fingerprint,
)
except ImportError:
from context_orchestration import (
CONTRACT_NAME as P3_CONTRACT_NAME,
CONTRACT_VERSION as P3_CONTRACT_VERSION,
LAYERS as P3_LAYERS,
contract_fingerprint as p3_contract_fingerprint,
)
P4_REVIEW_VERSION = 1
P4_REVIEW_ALLOWED_SECURITY_STATUSES = frozenset({"allowed", "sanitized"})
P4_REVIEW_ALLOWED_ASSURANCES = frozenset({"verified", "explicit_linked"})
P4_REVIEW_ALLOWED_DECISIONS = frozenset({"approve", "reject"})
P4_REVIEW_ALLOWED_POLICIES = frozenset({"inherit", "allow"})
_MAX_ID_LENGTH = 160
_MAX_REASON_LENGTH = 120
_REASON_RE = re.compile(r"[a-z0-9][a-z0-9_.:-]{0,119}\Z")
_OWNER_PLACEHOLDERS = frozenset({"", "none", "null", "undefined", "default"})
_ATTESTATION_CREATION_TOKEN = object()
_HANDLE_CREATION_TOKEN = object()
P4_REVIEW_ATTESTATION_DEFAULT_TTL_SECONDS = 30.0
P4_REVIEW_ATTESTATION_MAX_ENTRIES = 1024
class P4ReviewProducerAttestationHandle:
"""Opaque, non-serializable, one-shot P3 observer attestation."""
__slots__ = ("_registry",)
def __init__(self, creation_token: object, registry: object) -> None:
if creation_token is not _HANDLE_CREATION_TOKEN:
raise TypeError("P4 review attestations are minted only by the host registry")
self._registry = registry
def __reduce__(self) -> object:
raise TypeError("P4 review attestations cannot be serialized")
def __reduce_ex__(self, protocol: int) -> object:
raise TypeError("P4 review attestations cannot be serialized")
def __getstate__(self) -> object:
raise TypeError("P4 review attestations cannot be serialized")
def __repr__(self) -> str:
return "<P4ReviewProducerAttestationHandle opaque>"
def __init_subclass__(cls, **kwargs: object) -> None:
raise TypeError("P4 review attestations cannot be subclassed")
@dataclass(slots=True)
class _ProducerAttestationEntry:
request: object
event: object
p3_state: object
candidate_fingerprint: str
candidate_id: str
event_id: str
person_id: str
scope_kind: str
scope_id: str
operation_id: str
expires_at: float
class P4ReviewAttestationRegistry:
"""Host-owned bounded issuer for exact-carrier, one-shot P4 review handles."""
def __init__(
self,
creation_token: object | None = None,
*,
clock: Any | None = None,
default_ttl_seconds: float = P4_REVIEW_ATTESTATION_DEFAULT_TTL_SECONDS,
max_entries: int = P4_REVIEW_ATTESTATION_MAX_ENTRIES,
) -> None:
if creation_token is not _ATTESTATION_CREATION_TOKEN:
raise TypeError("P4 review attestation registries are host-owned")
if isinstance(default_ttl_seconds, bool) or not isinstance(default_ttl_seconds, (int, float)):
raise TypeError("P4 review attestation TTL is invalid")
if default_ttl_seconds <= 0 or default_ttl_seconds > 300:
raise ValueError("P4 review attestation TTL is invalid")
if isinstance(max_entries, bool) or not isinstance(max_entries, int) or max_entries < 1:
raise ValueError("P4 review attestation capacity is invalid")
self._clock = clock or time.monotonic
self._default_ttl_seconds = float(default_ttl_seconds)
self._max_entries = max_entries
self._lock = threading.RLock()
self._entries: dict[P4ReviewProducerAttestationHandle, _ProducerAttestationEntry] = {}
self._unloaded = False
def mint(
self,
request: object,
event: object,
p3_state: object,
candidate: Any,
*,
operation_id: Any,
ttl_seconds: float | None = None,
) -> P4ReviewProducerAttestationHandle | None:
"""Mint only after binding all live carriers and the normalized candidate."""
if request is None or event is None or p3_state is None:
return None
try:
operation_id = _required_id(operation_id)
normalized, code = normalize_review_candidate(
candidate,
now=datetime.min.replace(tzinfo=timezone.utc),
)
except Exception:
return None
if not operation_id or normalized is None or code:
return None
try:
ttl = self._default_ttl_seconds if ttl_seconds is None else float(ttl_seconds)
except (TypeError, ValueError):
return None
if ttl <= 0 or ttl > 300:
return None
proof = build_p3_review_proof(
p3_state,
person_id=normalized["person_id"],
identity_assurance=normalized["p3_proof"]["identity_assurance"],
scope_kind=normalized["scope_kind"],
scope_id=normalized["scope_id"],
)
if proof is None or proof != normalized["p3_proof"]:
return None
with self._lock:
self._cleanup_locked(self._clock())
if self._unloaded or len(self._entries) >= self._max_entries:
return None
handle = P4ReviewProducerAttestationHandle(_HANDLE_CREATION_TOKEN, self)
self._entries[handle] = _ProducerAttestationEntry(
request=request,
event=event,
p3_state=p3_state,
candidate_fingerprint=candidate_fingerprint(normalized),
candidate_id=normalized["candidate_id"],
event_id=normalized["event_id"],
person_id=normalized["person_id"],
scope_kind=normalized["scope_kind"],
scope_id=normalized["scope_id"],
operation_id=operation_id,
expires_at=self._clock() + ttl,
)
return handle
def consume(
self,
handle: object,
request: object,
event: object,
p3_state: object,
candidate: Any,
*,
operation_id: Any,
) -> dict[str, str] | None:
"""Consume once; wrong carriers, candidate, operation or expiry fail closed."""
if type(handle) is not P4ReviewProducerAttestationHandle:
return None
try:
if handle._registry is not self:
return None
except Exception:
return None
with self._lock:
entry = self._entries.pop(handle, None)
if entry is None or self._unloaded or self._clock() >= entry.expires_at:
return None
if request is not entry.request or event is not entry.event or p3_state is not entry.p3_state:
return None
try:
operation_id = _required_id(operation_id)
normalized, code = normalize_review_candidate(
candidate,
now=datetime.min.replace(tzinfo=timezone.utc),
)
except Exception:
return None
if (
not operation_id
or operation_id != entry.operation_id
or normalized is None
or code
or normalized["candidate_id"] != entry.candidate_id
or normalized["event_id"] != entry.event_id
or normalized["person_id"] != entry.person_id
or normalized["scope_kind"] != entry.scope_kind
or normalized["scope_id"] != entry.scope_id
or candidate_fingerprint(normalized) != entry.candidate_fingerprint
):
return None
return {
"candidate_fingerprint": entry.candidate_fingerprint,
"candidate_id": entry.candidate_id,
"event_id": entry.event_id,
"person_id": entry.person_id,
"scope_kind": entry.scope_kind,
"scope_id": entry.scope_id,
"operation_id": entry.operation_id,
}
def pending_count(self) -> int:
with self._lock:
self._cleanup_locked(self._clock())
return len(self._entries)
def unload(self) -> None:
with self._lock:
self._entries.clear()
self._unloaded = True
def _cleanup_locked(self, now: float) -> None:
for handle, entry in list(self._entries.items()):
if now >= entry.expires_at:
self._entries.pop(handle, None)
def _new_p4_review_attestation_registry(
*,
clock: Any | None = None,
default_ttl_seconds: float = P4_REVIEW_ATTESTATION_DEFAULT_TTL_SECONDS,
max_entries: int = P4_REVIEW_ATTESTATION_MAX_ENTRIES,
) -> P4ReviewAttestationRegistry:
"""Create the host-owned issuer used by the P3 observer."""
return P4ReviewAttestationRegistry(
_ATTESTATION_CREATION_TOKEN,
clock=clock,
default_ttl_seconds=default_ttl_seconds,
max_entries=max_entries,
)
def consume_p4_review_producer_attestation(
handle: Any,
request: object,
event: object,
p3_state: object,
candidate: Any,
*,
operation_id: Any,
) -> dict[str, str] | None:
if type(handle) is not P4ReviewProducerAttestationHandle:
return None
try:
registry = handle._registry
except Exception:
return None
if not isinstance(registry, P4ReviewAttestationRegistry):
return None
return registry.consume(
handle,
request,
event,
p3_state,
candidate,
operation_id=operation_id,
)
def _canonical(value: Any) -> str:
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def _single_line_id(value: Any, *, limit: int = _MAX_ID_LENGTH) -> str:
"""Normalize one runtime/config ID without accepting a carrier-like value."""
if isinstance(value, bool) or not isinstance(value, (str, int)):
return ""
text = unicodedata.normalize("NFKC", str(value)).strip()
if not text or len(text) > limit or text.lower() in _OWNER_PLACEHOLDERS:
return ""
# IDs are deliberately one token: no newline, whitespace, NUL, or other
# control/format character may survive configuration parsing.
if any(character.isspace() or unicodedata.category(character).startswith("C") for character in text):
return ""
return text
def parse_owner_allowlist(value: Any) -> tuple[str, ...]:
"""Parse a config-only owner allowlist, accepting list/string separators.
The output is merely an allowlist. It is never a runtime credential: a
later gate must still obtain its actor from ``event.get_sender_id()``.
"""
raw_items: list[Any] = []
if isinstance(value, str):
raw_items.extend(piece for piece in re.split(r"[\s,,;;]+", value) if piece)
elif isinstance(value, (list, tuple, set, frozenset)):
for item in value:
if isinstance(item, str):
raw_items.extend(piece for piece in re.split(r"[\s,,;;]+", item) if piece)
else:
raw_items.append(item)
else:
raw_items.append(value)
result: list[str] = []
for raw in raw_items:
owner_id = _single_line_id(raw)
if owner_id and owner_id not in result:
result.append(owner_id)
return tuple(result)
def runtime_owner_identity(event: Any, configured_owner_ids: Any) -> dict[str, Any]:
"""Accept only a direct AstrBot runtime sender matching the config allowlist.
This intentionally does not inspect a dict, page field, request carrier,
model text, ``event.sender_id``, or ``event.user_id``. A test double is
valid only when it exposes a callable ``get_sender_id`` method.
"""
allowlist = parse_owner_allowlist(configured_owner_ids)
if not allowlist:
return {"accepted": False, "code": "p4_review_owner_allowlist_empty", "actor_id": ""}
if event is None:
return {"accepted": False, "code": "p4_review_owner_runtime_missing", "actor_id": ""}
try:
getter = getattr(event, "get_sender_id", None)
except Exception:
return {"accepted": False, "code": "p4_review_owner_runtime_unavailable", "actor_id": ""}
if not callable(getter):
return {"accepted": False, "code": "p4_review_owner_runtime_missing", "actor_id": ""}
try:
actor_id = _single_line_id(getter())
except Exception:
return {"accepted": False, "code": "p4_review_owner_runtime_unavailable", "actor_id": ""}
if not actor_id:
return {"accepted": False, "code": "p4_review_owner_runtime_invalid", "actor_id": ""}
if actor_id not in allowlist:
return {"accepted": False, "code": "p4_review_owner_not_allowed", "actor_id": ""}
return {
"accepted": True,
"code": "p4_review_owner_runtime_verified",
"actor_id": actor_id,
"allowlist_size": len(allowlist),
}
def runtime_scope_identity(event: Any) -> dict[str, str]:
"""Read a scope only from direct AstrBot runtime methods.
Group IDs must never fall back to raw payload fields or unified message
origins. Unknown or exceptional scope identity is therefore rejected.
"""
if event is None:
return {"scope_kind": "", "scope_id": ""}
try:
group_getter = getattr(event, "get_group_id", None)
except Exception:
return {"scope_kind": "", "scope_id": ""}
if not callable(group_getter):
return {"scope_kind": "", "scope_id": ""}
try:
group_id = _single_line_id(group_getter())
except Exception:
return {"scope_kind": "", "scope_id": ""}
if not group_id:
return {"scope_kind": "", "scope_id": ""}
try:
platform_getter = getattr(event, "get_platform_name", None)
except Exception:
return {"scope_kind": "", "scope_id": ""}
if not callable(platform_getter):
return {"scope_kind": "", "scope_id": ""}
try:
platform_id = _single_line_id(platform_getter())
except Exception:
return {"scope_kind": "", "scope_id": ""}
if not platform_id:
return {"scope_kind": "", "scope_id": ""}
return {"scope_kind": "group", "scope_id": f"{platform_id}:{group_id}"}
def _timestamp(value: Any) -> tuple[str, datetime | None]:
if not isinstance(value, str) or not value or len(value) > 80 or "\x00" in value:
return "", None
text = value.strip()
if not text or any(character.isspace() for character in text[:-1]):
return "", None
try:
parsed = datetime.fromisoformat(text[:-1] + "+00:00" if text.endswith("Z") else text)
except (TypeError, ValueError):
return "", None
if parsed.tzinfo is None:
return "", None
utc = parsed.astimezone(timezone.utc)
return utc.isoformat(timespec="seconds").replace("+00:00", "Z"), utc
def _reason_code(value: Any) -> str:
if not isinstance(value, str):
return ""
code = value.strip().lower()
return code if len(code) <= _MAX_REASON_LENGTH and _REASON_RE.fullmatch(code) else ""
def _required_id(value: Any) -> str:
return _single_line_id(value, limit=_MAX_ID_LENGTH)
def build_p3_review_proof(
state: Any,
*,
person_id: Any,
identity_assurance: Any,
scope_kind: Any,
scope_id: Any,
) -> dict[str, Any] | None:
"""Project only a validated P3 final state into the review contract."""
if not isinstance(state, dict):
return None
if (
state.get("contract_name") != P3_CONTRACT_NAME
or state.get("contract_version") != P3_CONTRACT_VERSION
or state.get("contract_fingerprint") != p3_contract_fingerprint()
or state.get("phase") != "finalized"
or state.get("finalized") is not True
or state.get("completed_layers") != list(P3_LAYERS)
):
return None
normalized_person_id = _required_id(person_id)
assurance = str(identity_assurance or "").strip()
normalized_scope_kind = str(scope_kind or "").strip().lower()
normalized_scope_id = _required_id(scope_id)
security = state.get("security")
if (
not normalized_person_id
or assurance not in P4_REVIEW_ALLOWED_ASSURANCES
or normalized_scope_kind != "group"
or not normalized_scope_id
or state.get("scope") != normalized_scope_kind
or not isinstance(security, dict)
or security.get("status") not in P4_REVIEW_ALLOWED_SECURITY_STATUSES
or security.get("response_policy") not in P4_REVIEW_ALLOWED_POLICIES
):
return None
security_event_id = security.get("event_id")
if not isinstance(security_event_id, str) or len(security_event_id) > 180 or "\x00" in security_event_id:
return None
created_at = state.get("created_at")
normalized_created_at, _ = _timestamp(created_at)
if not normalized_created_at:
return None
return {
"contract_name": P3_CONTRACT_NAME,
"contract_version": P3_CONTRACT_VERSION,
"contract_fingerprint": p3_contract_fingerprint(),
"completed_layers": list(P3_LAYERS),
"phase": "finalized",
"finalized": True,
"security_status": security["status"],
"response_policy": security["response_policy"],
"security_event_id": security_event_id,
"person_id": normalized_person_id,
"identity_assurance": assurance,
"scope_kind": normalized_scope_kind,
"scope_id": normalized_scope_id,
"created_at": normalized_created_at,
}
def normalize_review_candidate(candidate: Any, *, now: datetime | None = None) -> tuple[dict[str, Any] | None, str]:
"""Validate the immutable, observer-produced review-candidate contract."""
if not isinstance(candidate, dict):
return None, "p4_review_candidate_invalid"
candidate_id = _required_id(candidate.get("candidate_id"))
event_id = _required_id(candidate.get("event_id"))
person_id = _required_id(candidate.get("person_id"))
scope_kind = str(candidate.get("scope_kind") or "").strip().lower()
scope_id = _required_id(candidate.get("scope_id"))
reason_code = _reason_code(candidate.get("reason_code"))
created_at, created_when = _timestamp(candidate.get("created_at"))
expires_at, expires_when = _timestamp(candidate.get("expires_at"))
proof = candidate.get("p3_proof")
if not all((candidate_id, event_id, person_id, scope_kind, scope_id, reason_code, created_at, expires_at)):
return None, "p4_review_candidate_missing_required_field"
if scope_kind != "group":
return None, "p4_review_candidate_scope_invalid"
if created_when is None or expires_when is None or expires_when <= created_when:
return None, "p4_review_candidate_time_invalid"
if not isinstance(proof, dict):
return None, "p4_review_candidate_p3_proof_invalid"
proof_created_at, proof_when = _timestamp(proof.get("created_at"))
proof_fingerprint = proof.get("contract_fingerprint")
proof_layers = proof.get("completed_layers")
proof_policy = proof.get("response_policy")
proof_event_id = proof.get("security_event_id")
proof_scope_kind = str(proof.get("scope_kind") or "").strip().lower()
proof_scope_id = _required_id(proof.get("scope_id"))
if (
proof.get("contract_name") != P3_CONTRACT_NAME
or proof.get("contract_version") != P3_CONTRACT_VERSION
or proof_fingerprint != p3_contract_fingerprint()
or proof_layers != list(P3_LAYERS)
or proof.get("phase") != "finalized"
or proof.get("finalized") is not True
or proof.get("security_status") not in P4_REVIEW_ALLOWED_SECURITY_STATUSES
or proof_policy not in P4_REVIEW_ALLOWED_POLICIES
or not isinstance(proof_event_id, str)
or len(proof_event_id) > 180
or "\x00" in proof_event_id
or proof.get("person_id") != person_id
or proof.get("identity_assurance") not in P4_REVIEW_ALLOWED_ASSURANCES
or proof_scope_kind != scope_kind
or proof_scope_id != scope_id
or proof_created_at != created_at
or proof_when is None
):
return None, "p4_review_candidate_p3_proof_invalid"
clock = now or datetime.now(timezone.utc)
if expires_when <= clock.astimezone(timezone.utc):
return None, "p4_review_candidate_expired"
return {
"candidate_id": candidate_id,
"event_id": event_id,
"person_id": person_id,
"scope_kind": scope_kind,
"scope_id": scope_id,
"created_at": created_at,
"expires_at": expires_at,
"reason_code": reason_code,
"p3_proof": {
"phase": "finalized",
"finalized": True,
"contract_name": P3_CONTRACT_NAME,
"contract_version": P3_CONTRACT_VERSION,
"contract_fingerprint": p3_contract_fingerprint(),
"completed_layers": list(P3_LAYERS),
"security_status": proof["security_status"],
"response_policy": proof_policy,
"security_event_id": proof_event_id,
"person_id": person_id,
"identity_assurance": proof["identity_assurance"],
"scope_kind": scope_kind,
"scope_id": scope_id,
"created_at": created_at,
},
}, ""
def candidate_fingerprint(candidate: dict[str, Any]) -> str:
return hashlib.sha256(_canonical(candidate).encode("utf-8")).hexdigest()
def decision_fingerprint(record: dict[str, Any], *, candidate_fp: str) -> str:
return hashlib.sha256(
_canonical(
{
"candidate_fingerprint": candidate_fp,
"candidate_id": record.get("candidate_id"),
"event_id": record.get("event_id"),
"person_id": record.get("person_id"),
"scope_kind": record.get("scope_kind"),
"scope_id": record.get("scope_id"),
"actor_id": record.get("actor_id"),
"decision": record.get("decision"),
"reason_code": record.get("reason_code"),
"occurred_at": record.get("occurred_at"),
"operation_id": record.get("operation_id"),
}
).encode("utf-8")
).hexdigest()
def ensure_review_container(root: dict[str, Any]) -> tuple[dict[str, Any] | None, str]:
"""Create an additive ``unified_person.p4_review`` container once.
Existing malformed containers fail closed rather than being replaced.
"""
if not isinstance(root, dict):
return None, "p4_review_corrupt"
container = root.get("p4_review")
if container is None:
container = {
"version": P4_REVIEW_VERSION,
"candidates": {},
"event_index": {},
"decisions": {},
}
root["p4_review"] = container
return container, ""
if not isinstance(container, dict):
return None, "p4_review_corrupt"
if container.get("version") != P4_REVIEW_VERSION:
return None, "p4_review_corrupt"
for key in ("candidates", "event_index", "decisions"):
if not isinstance(container.get(key), dict):
return None, "p4_review_corrupt"
return container, ""
def queue_candidate(
container: dict[str, Any],
candidate: dict[str, Any],
*,
operation_id: str,
recorded_at: str,
) -> tuple[dict[str, Any] | None, str]:
"""Append a candidate to only the separate review queue."""
candidates = container.get("candidates")
event_index = container.get("event_index")
if not isinstance(candidates, dict) or not isinstance(event_index, dict):
return None, "p4_review_corrupt"
fingerprint = candidate_fingerprint(candidate)
candidate_id = candidate["candidate_id"]
event_id = candidate["event_id"]
known = candidates.get(candidate_id)
if known is not None:
if not isinstance(known, dict) or known.get("candidate_fingerprint") != fingerprint:
return None, "p4_review_candidate_id_conflict"
indexed_known = event_index.get(candidate["event_id"])
if (
not isinstance(indexed_known, dict)
or indexed_known.get("candidate_id") != candidate_id
or indexed_known.get("candidate_fingerprint") != fingerprint
):
return None, "p4_review_candidate_integrity_error"
return deepcopy(known), "p4_review_candidate_duplicate"
indexed = event_index.get(event_id)
if indexed is not None:
if not isinstance(indexed, dict) or indexed.get("candidate_fingerprint") != fingerprint:
return None, "p4_review_event_id_conflict"
return None, "p4_review_candidate_id_conflict"
record = {
**deepcopy(candidate),
"candidate_fingerprint": fingerprint,
"recorded_at": recorded_at,
"operation_id": operation_id,
}
candidates[candidate_id] = record
event_index[event_id] = {"candidate_id": candidate_id, "candidate_fingerprint": fingerprint}
return deepcopy(record), "p4_review_candidate_recorded"
def queue_decision(
container: dict[str, Any],
*,
person_id: str,
candidate_id: str,
actor_id: str,
scope_kind: str,
scope_id: str,
decision: str,
reason_code: str,
operation_id: str,
occurred_at: str,
now: datetime | None = None,
) -> tuple[dict[str, Any] | None, str]:
"""Append an audited conclusion without any live P4 effect."""
candidates = container.get("candidates")
event_index = container.get("event_index")
decisions = container.get("decisions")
if not isinstance(candidates, dict) or not isinstance(event_index, dict) or not isinstance(decisions, dict):
return None, "p4_review_corrupt"
candidate = candidates.get(candidate_id)
if not isinstance(candidate, dict):
return None, "p4_review_candidate_not_found"
normalized, code = normalize_review_candidate(candidate, now=now)
if normalized is None:
return None, code
stored_fingerprint = candidate.get("candidate_fingerprint")
if stored_fingerprint != candidate_fingerprint(normalized):
return None, "p4_review_candidate_integrity_error"
indexed = event_index.get(normalized["event_id"])
if (
not isinstance(indexed, dict)
or indexed.get("candidate_id") != candidate_id
or indexed.get("candidate_fingerprint") != stored_fingerprint
):
return None, "p4_review_candidate_integrity_error"
if normalized["person_id"] != person_id:
return None, "p4_review_candidate_person_mismatch"
if normalized["scope_kind"] != scope_kind or normalized["scope_id"] != scope_id:
return None, "p4_review_candidate_scope_mismatch"
existing = decisions.get(candidate_id)
if existing is not None:
if not isinstance(existing, dict):
return None, "p4_review_corrupt"
expected_existing = {
"candidate_id": candidate_id,
"event_id": normalized["event_id"],
"person_id": normalized["person_id"],
"scope_kind": normalized["scope_kind"],
"scope_id": normalized["scope_id"],
"actor_id": existing.get("actor_id"),
"decision": existing.get("decision"),
"reason_code": existing.get("reason_code"),
"occurred_at": existing.get("occurred_at"),
"operation_id": existing.get("operation_id"),
}
if (
existing.get("candidate_fingerprint") != stored_fingerprint
or existing.get("event_id") != expected_existing["event_id"]
or existing.get("person_id") != expected_existing["person_id"]
or existing.get("scope_kind") != expected_existing["scope_kind"]
or existing.get("scope_id") != expected_existing["scope_id"]
or existing.get("decision_fingerprint") != decision_fingerprint(expected_existing, candidate_fp=stored_fingerprint)
):
return None, "p4_review_decision_integrity_error"
if existing.get("decision") != decision:
return None, "p4_review_decision_conflict"
if (
existing.get("actor_id") != actor_id
or existing.get("reason_code") != reason_code
or existing.get("scope_kind") != scope_kind
or existing.get("scope_id") != scope_id
):
return None, "p4_review_decision_conflict"
return deepcopy(existing), "p4_review_decision_duplicate"
record = {
"candidate_id": candidate_id,
"event_id": normalized["event_id"],
"person_id": person_id,
"scope_kind": scope_kind,
"scope_id": scope_id,
"actor_id": actor_id,
"decision": decision,
"reason_code": reason_code,
"occurred_at": occurred_at,
"operation_id": operation_id,
}
record["candidate_fingerprint"] = stored_fingerprint
record["decision_fingerprint"] = decision_fingerprint(record, candidate_fp=stored_fingerprint)
decisions[candidate_id] = record
return deepcopy(record), "p4_review_decision_recorded"
def validate_review_operation_replay(
container: Any,
*,
action: str,
result: dict[str, Any],
payload: dict[str, Any],
) -> str:
"""Re-check the ledger envelope before returning a cached operation result."""
if not result.get("ok"):
return ""
if not isinstance(container, dict):
return "p4_review_corrupt"
candidates = container.get("candidates")
event_index = container.get("event_index")
decisions = container.get("decisions")
if not isinstance(candidates, dict) or not isinstance(event_index, dict) or not isinstance(decisions, dict):
return "p4_review_corrupt"
candidate_id = payload.get("candidate_id")
if not isinstance(candidate_id, str) and isinstance(payload.get("candidate"), dict):
candidate_id = payload["candidate"].get("candidate_id")
if not isinstance(candidate_id, str):
return "p4_review_candidate_integrity_error"
stored_candidate = candidates.get(candidate_id)
if not isinstance(stored_candidate, dict):
return "p4_review_candidate_integrity_error"
normalized_candidate, candidate_code = normalize_review_candidate(
stored_candidate,
now=datetime.min.replace(tzinfo=timezone.utc),
)
stored_candidate_fp = stored_candidate.get("candidate_fingerprint")
if (
normalized_candidate is None
or candidate_code
or stored_candidate_fp != candidate_fingerprint(normalized_candidate)
or normalized_candidate["person_id"] != payload.get("person_id")
or not isinstance(event_index.get(normalized_candidate["event_id"]), dict)
or event_index[normalized_candidate["event_id"]].get("candidate_id") != candidate_id
or event_index[normalized_candidate["event_id"]].get("candidate_fingerprint") != stored_candidate_fp
):
return "p4_review_candidate_integrity_error"
if (
result.get("candidate_id") is not None
and result.get("candidate_id") != candidate_id
) or (
result.get("person_id") is not None
and result.get("person_id") != normalized_candidate["person_id"]
):
return "p4_review_candidate_integrity_error"
if action == "record_p4_manual_review_candidate":
if result.get("event_id") is not None and result.get("event_id") != normalized_candidate["event_id"]:
return "p4_review_candidate_integrity_error"
return ""
if action != "record_p4_manual_review_decision":
return ""
stored_decision = decisions.get(candidate_id)
if not isinstance(stored_decision, dict):
return "p4_review_decision_integrity_error"
expected_decision = {
"candidate_id": candidate_id,
"event_id": normalized_candidate["event_id"],
"person_id": normalized_candidate["person_id"],
"scope_kind": normalized_candidate["scope_kind"],
"scope_id": normalized_candidate["scope_id"],
"actor_id": stored_decision.get("actor_id"),
"decision": stored_decision.get("decision"),
"reason_code": stored_decision.get("reason_code"),
"occurred_at": stored_decision.get("occurred_at"),
"operation_id": stored_decision.get("operation_id"),
}
if (
stored_decision.get("candidate_fingerprint") != stored_candidate_fp
or any(stored_decision.get(key) != value for key, value in expected_decision.items() if key not in {"candidate_id", "actor_id", "decision", "reason_code", "occurred_at", "operation_id"})
or stored_decision.get("decision_fingerprint") != decision_fingerprint(expected_decision, candidate_fp=stored_candidate_fp)
or stored_decision.get("actor_id") != payload.get("actor_id")
or stored_decision.get("decision") != payload.get("decision")
or stored_decision.get("reason_code") != payload.get("reason_code")
or stored_decision.get("scope_kind") != payload.get("scope_kind")
or stored_decision.get("scope_id") != payload.get("scope_id")
):
return "p4_review_decision_integrity_error"
return ""
def normalize_decision_request(
*,
person_id: Any,
candidate_id: Any,
decision: Any,
reason_code: Any,
operation_id: Any,
) -> tuple[dict[str, str] | None, str]:
normalized_person_id = _required_id(person_id)
normalized_candidate_id = _required_id(candidate_id)
normalized_operation_id = _required_id(operation_id)
normalized_reason_code = _reason_code(reason_code)
normalized_decision = decision.strip().lower() if isinstance(decision, str) else ""
if not all((normalized_person_id, normalized_candidate_id, normalized_operation_id, normalized_reason_code)):
return None, "p4_review_decision_invalid"
if normalized_decision not in P4_REVIEW_ALLOWED_DECISIONS:
return None, "p4_review_decision_invalid"
return {
"person_id": normalized_person_id,
"candidate_id": normalized_candidate_id,
"decision": normalized_decision,
"reason_code": normalized_reason_code,
"operation_id": normalized_operation_id,
}, ""