# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-from-laundering-taint-during-post-incident-agent-trace-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-from-laundering-taint-during-post-incident-agent-trace-reconstruction.warrant.json
# Markdown SHA-256:   7ccd05cb123b4675415bf7792ff66c2eac4212b2a28a3f2b43a99fec066f7fba
# Code AST SHA-256:   3505b4b94afff4b62efd039e9f51a99afab7e6a44e2eded42270361ea3777d03
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when replay divergence would silently drop a taint label."""
    pass


def replay_decision(recorded_event, replayed_action, taint_reachable):
    """
    recorded_event: dict with 'action', 'target', 'tainted' (recorded label)
    replayed_action: str, the action the re-derived model chose
    taint_reachable: bool, whether either branch touches taint-reachable state
    """
    if replayed_action == recorded_event["action"]:
        return "converged"

    if not taint_reachable:
        return "diverged_neutral"

    # Divergence on a taint-relevant branch: fail closed toward taint.
    if not recorded_event.get("tainted", False):
        # Replayed agent reached a branch the original did not, on state
        # reachable from a taint source. The recorded event carries no label,
        # so we cannot trust the replayed path either. Halt.
        raise TaintLaunderingError(
            f"Divergence at recorded action={recorded_event['action']!r} "
            f"vs replayed={replayed_action!r} on taint-reachable target "
            f"{recorded_event.get('target')!r}; replay is non-authoritative "
            f"for this region and must be marked indeterminate."
        )

    # Recorded event was tainted: propagate the recorded label, ignore replay.
    return "diverged_taint_preserved"


def propagate(recorded_events, replayed_actions, taint_reachable_fn):
    labels = {}
    for ev, act in zip(recorded_events, replayed_actions):
        reachable = taint_reachable_fn(ev["target"])
        outcome = replay_decision(ev, act, reachable)
        if outcome == "diverged_neutral":
            continue
        # I2/I3: label follows the recorded event, never the replayed branch.
        if ev.get("tainted", False) or outcome == "diverged_taint_preserved":
            labels[ev["target"]] = True
    return labels
