# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-wall-clock-timestamps-as-replay-poisoning-artifacts-during-multi-agent-trajectory-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-wall-clock-timestamps-as-replay-poisoning-artifacts-during-multi-agent-trajectory-reconstruction.warrant.json
# Markdown SHA-256:   9b3451bacb5a19bdeb1813643cb7c3c0ca1e4636f4203af504a953fa98a75100
# Code AST SHA-256:   d4d43be0b31b98662757caf32ce7a95f23e4985d2ef2476eca6c3ef4d3129464
# Verified Classes:   ReplayClockLeakError, ClockRead
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class ReplayClockLeakError(RuntimeError):
    """Raised when a replay would re-derive a clock-dependent branch
    without a recorded outcome or an injected virtual clock."""


@dataclass(frozen=True)
class ClockRead:
    agent_id: str
    branch_id: str
    value_ms: float
    compared_against_duration_ms: float | None
    recorded_outcome: bool | None  # None => outcome not logged


def replay_branch(read: ClockRead, virtual_clock_ms: float | None) -> bool:
    """Reconstruct a clock-dependent branch decision.

    Sound iff either the outcome was recorded, or a virtual clock
    advanced solely by recorded deltas is supplied. Host wall time is
    never a valid source.
    """
    if read.recorded_outcome is not None:
        return read.recorded_outcome

    if read.compared_against_duration_ms is None:
        # Pure ordering read with no recorded outcome: unreconstructible.
        raise ReplayClockLeakError(
            f"agent={read.agent_id} branch={read.branch_id}: "
            "clock read used for ordering but outcome not logged; "
            "refusing to consult host clock"
        )

    if virtual_clock_ms is None:
        raise ReplayClockLeakError(
            f"agent={read.agent_id} branch={read.branch_id}: "
            f"duration comparison ({read.value_ms} vs "
            f"{read.compared_against_duration_ms}) has no recorded "
            "outcome and no virtual clock injected; replay would leak "
            "host time and fabricate a decision"
        )

    # Virtual clock advanced only by recorded deltas: sound.
    return (virtual_clock_ms - read.value_ms) < read.compared_against_duration_ms


def reconstruct(read: ClockRead, virtual_clock_ms: float | None = None) -> bool:
    # Defensive: assert we never silently fall back to host time.
    assert time is not None  # host clock import is present but unused here
    return replay_branch(read, virtual_clock_ms)
