# -*- coding: utf-8 -*- from __future__ import annotations from copy import deepcopy import importlib import pathlib import sys import types import unittest from unified_person_contract import build_person_projection, empty_unified_person_store from unified_person_registry import UnifiedPersonRegistry sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) import _host_stub # noqa: E402 _host_stub.install() _PACKAGE_NAME = "_p4_shadow_registry_companion" if _PACKAGE_NAME not in sys.modules: package = types.ModuleType(_PACKAGE_NAME) package.__path__ = [str(pathlib.Path(__file__).resolve().parents[1])] sys.modules[_PACKAGE_NAME] = package core_store_module = importlib.import_module(f"{_PACKAGE_NAME}.core_store") def identity(subject_id: str) -> dict[str, str]: return { "companion_instance_id": "companion-a", "bot_account_id": "bot-1", "adapter_instance_id": "telegram-main", "subject_namespace": "telegram.user", "platform_subject_id": subject_id, } def normal_event(event_id: str, *, occurred_at: str = "2026-07-29T00:00:00Z") -> dict[str, str]: return { "event_id": event_id, "occurred_at": occurred_at, "kind": "normal", } def violation_event(event_id: str) -> dict: return { "event_id": event_id, "occurred_at": "2026-07-29T00:00:00Z", "kind": "violation", "review": { "schema_version": "p4.review.v1", "verdict": "violation", "category": "prompt_injection", "confidence": 0.95, "risk_flags": [], "evidence": [{ "message_id": "message-p4-1", "code": "direct_instruction_override", "source": "current_message", }], }, } class _CoreStoreHost(core_store_module.CoreStoreMixin): def __init__(self, data: dict) -> None: self.data = data self.save_calls = 0 def _schedule_data_save(self) -> None: self.save_calls += 1 class P4ShadowRegistryTests(unittest.TestCase): def setUp(self) -> None: self.store = {"unified_person": empty_unified_person_store()} self.registry = UnifiedPersonRegistry(self.store) def _observe(self, subject_id: str = "42") -> str: result = self.registry.upsert_observed_identity( identity(subject_id), operation_id=f"observe-{subject_id}", display_name=f"user-{subject_id}", ) self.assertTrue(result["ok"]) return result["person_id"] def test_shadow_event_is_persisted_under_additive_container_only(self): person_id = self._observe() before_profile = deepcopy(self.store["unified_person"]["profiles"][person_id]) before_projection = build_person_projection(self.store, person_id) result = self.registry.record_p4_shadow_event( person_id, normal_event("p4-event-1"), operation_id="p4-operation-1", actor_id="system", ) self.assertTrue(result["ok"]) self.assertTrue(result["changed"]) self.assertEqual(result["code"], "p4_shadow_event_recorded") self.assertEqual(result["event_id"], "p4-event-1") self.assertEqual(self.store["unified_person"]["profiles"][person_id], before_profile) self.assertEqual(build_person_projection(self.store, person_id), before_projection) shadow = self.store["unified_person"]["p4_shadow"] entry = shadow["people"][person_id] self.assertEqual(entry["person_id"], person_id) self.assertEqual(entry["origin_person_id"], person_id) self.assertEqual(entry["events"][0]["person_id"], person_id) self.assertEqual(entry["events"][0]["origin_person_id"], person_id) self.assertEqual(entry["events"][0]["event"]["event_id"], "p4-event-1") self.assertEqual(entry["state"]["score"], 0) self.assertEqual(entry["state"]["event_log"][0]["event_id"], "p4-event-1") read = self.registry.read_p4_shadow_state(person_id) self.assertTrue(read["ok"]) self.assertTrue(read["p4_shadow_exists"]) self.assertEqual(read["p4_shadow_state"], entry["state"]) audit = self.registry.audit_events() self.assertEqual(audit[-1]["action"], "p4_shadow_event_recorded") self.assertEqual(audit[-1]["details"]["origin_person_id"], person_id) def test_registry_uses_pure_engine_for_violation_shadow_without_profile_projection_write(self): person_id = self._observe() before_profile = deepcopy(self.store["unified_person"]["profiles"][person_id]) before_projection = build_person_projection(self.store, person_id) result = self.registry.record_p4_shadow_event( person_id, violation_event("p4-event-violation"), operation_id="p4-operation-violation", actor_id="reviewer", ) self.assertTrue(result["ok"]) self.assertTrue(result["event_applied"]) self.assertEqual(result["p4_shadow_summary"]["score"], -400) entry = self.store["unified_person"]["p4_shadow"]["people"][person_id] self.assertEqual(entry["state"]["score"], -400) self.assertEqual(entry["events"][0]["event"]["review"]["category"], "prompt_injection") self.assertNotIn("severity_steps", entry["events"][0]["event"]["review"]) self.assertEqual(self.store["unified_person"]["profiles"][person_id], before_profile) self.assertEqual(build_person_projection(self.store, person_id), before_projection) def test_event_and_operation_idempotence_conflicts_do_not_replay_or_overwrite(self): person_id = self._observe() event = normal_event("p4-event-idempotent") first = self.registry.record_p4_shadow_event( person_id, event, operation_id="p4-operation-idempotent", actor_id="system", ) self.assertTrue(first["ok"]) after_first = deepcopy(self.store) repeated = self.registry.record_p4_shadow_event( person_id, event, operation_id="p4-operation-idempotent", actor_id="system", ) self.assertTrue(repeated["ok"]) self.assertTrue(repeated["idempotent"]) self.assertEqual(self.store, after_first) duplicate = self.registry.record_p4_shadow_event( person_id, event, operation_id="p4-operation-new", actor_id="system", ) self.assertTrue(duplicate["ok"]) self.assertEqual(duplicate["code"], "p4_shadow_event_duplicate") self.assertFalse(duplicate["changed"]) self.assertTrue(duplicate["event_duplicate"]) entry = self.store["unified_person"]["p4_shadow"]["people"][person_id] self.assertEqual(len(entry["events"]), 1) self.assertEqual(len(self.registry.audit_events()), 2) # observed identity plus initial P4 event after_duplicate = deepcopy(self.store) event_conflict = self.registry.record_p4_shadow_event( person_id, normal_event("p4-event-idempotent", occurred_at="2026-07-30T00:00:00Z"), operation_id="p4-operation-event-conflict", actor_id="system", ) self.assertEqual(event_conflict["code"], "p4_shadow_event_id_conflict") self.assertEqual(self.store, after_duplicate) operation_conflict = self.registry.record_p4_shadow_event( person_id, normal_event("p4-event-other"), operation_id="p4-operation-idempotent", actor_id="system", ) self.assertEqual(operation_conflict["code"], "operation_id_conflict") self.assertEqual(self.store, after_duplicate) def test_unknown_inactive_and_mismatched_origin_are_rejected_without_shadow_writes(self): before_unknown = deepcopy(self.store) unknown = self.registry.record_p4_shadow_event( "person_missing", normal_event("p4-event-unknown"), operation_id="p4-operation-unknown", actor_id="system", ) self.assertEqual(unknown["code"], "person_not_found") self.assertEqual(self.store, before_unknown) person_id = self._observe() before_mismatch = deepcopy(self.store) mismatch = self.registry.record_p4_shadow_event( person_id, {**normal_event("p4-event-mismatch"), "origin_person_id": "person_other"}, operation_id="p4-operation-mismatch", actor_id="system", ) self.assertEqual(mismatch["code"], "p4_shadow_person_mismatch") self.assertEqual(self.store, before_mismatch) self.store["unified_person"]["profiles"][person_id]["profile_status"] = "suspended" before_inactive = deepcopy(self.store) inactive = self.registry.record_p4_shadow_event( person_id, normal_event("p4-event-inactive"), operation_id="p4-operation-inactive", actor_id="system", ) self.assertEqual(inactive["code"], "person_not_active") self.assertEqual(self.store, before_inactive) read_inactive = self.registry.read_p4_shadow_state(person_id) self.assertEqual(read_inactive["code"], "person_not_active") def test_core_store_whitelist_persists_only_non_idempotent_successes(self): person_id = self._observe() host = _CoreStoreHost(self.store) event = normal_event("p4-event-core-store") first = host._apply_unified_person_lifecycle( "record_p4_shadow_event", person_id, event, operation_id="p4-operation-core-store", actor_id="system", ) self.assertTrue(first["ok"]) self.assertEqual(host.save_calls, 1) repeated = host._apply_unified_person_lifecycle( "record_p4_shadow_event", person_id, event, operation_id="p4-operation-core-store", actor_id="system", ) self.assertTrue(repeated["idempotent"]) self.assertEqual(host.save_calls, 1) duplicate = host._apply_unified_person_lifecycle( "record_p4_shadow_event", person_id, event, operation_id="p4-operation-core-store-duplicate", actor_id="system", ) self.assertEqual(duplicate["code"], "p4_shadow_event_duplicate") self.assertEqual(host.save_calls, 2) read = host._apply_unified_person_lifecycle("read_p4_shadow_state", person_id) self.assertTrue(read["ok"]) self.assertEqual(read["code"], "p4_shadow_state") self.assertEqual(read["p4_shadow_summary"]["score"], 0) self.assertEqual(host.save_calls, 2) if __name__ == "__main__": unittest.main()