# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-the-observability-event-schema-as-a-lossy-projection-rather-than-a-faithful-record-of-agent-planning-reflecti.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-the-observability-event-schema-as-a-lossy-projection-rather-than-a-faithful-record-of-agent-planning-reflecti.warrant.json
# Markdown SHA-256:   e83916c9481ace70bd00008ae97afee9edccabbe3d7ef90ba2ef8fa76e7505bb
# Code AST SHA-256:   a7a3d5ff55a944e83b88ac2dac48a75c5cb90526e9789776cb4b99f32f8f5b39
# Verified Classes:   SchemaAliasingError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SchemaAliasingError(RuntimeError):
    """Raised when an event stream is treated as a faithful record but is a lossy projection."""
    pass


REQUIRED_FOR_RECONSTRUCTION = frozenset({
    "step_id", "parent_step_id", "status",
    "branch_field", "branch_value",          # the field control flow branched on
    "retrieval_path", "similarity_score",    # memory provenance
    "fidelity",
})


def assert_replayable(events: list[dict]) -> None:
    """
    Gate state reconstruction on schema fidelity. Call before any replay,
    resume, or reflection-audit that treats events as a causal graph.
    """
    if not events:
        raise SchemaAliasingError("empty event stream: cannot reconstruct state")

    for i, ev in enumerate(events):
        missing = REQUIRED_FOR_RECONSTRUCTION - ev.keys()
        if missing:
            raise SchemaAliasingError(
                f"event[{i}] id={ev.get('step_id')!r} missing fields {sorted(missing)}; "
                f"stream is a lossy projection and must not be replayed as a causal graph"
            )
        if ev["fidelity"] != "full":
            raise SchemaAliasingError(
                f"event[{i}] id={ev.get('step_id')!r} fidelity={ev['fidelity']!r}; "
                f"only fidelity='full' events are eligible for state reconstruction"
            )

    # Contiguity check: sampled/dropped events break adjacency-as-causality.
    for prev, cur in zip(events, events[1:]):
        if cur.get("seq") is not None and prev.get("seq") is not None:
            if cur["seq"] != prev["seq"] + 1:
                raise SchemaAliasingError(
                    f"sequence gap between seq={prev['seq']} and seq={cur['seq']}; "
                    f"non-contiguous stream cannot be replayed as a total order"
                )


def reconstruct_plan(events: list[dict]) -> dict:
    """Reconstruct dependency graph only after fidelity gate passes."""
    assert_replayable(events)
    graph: dict[str, list[str]] = {}
    for ev in events:
        graph.setdefault(ev["step_id"], [])
        if ev.get("parent_step_id") is not None:
            graph[ev["parent_step_id"]].append(ev["step_id"])
    return graph
