# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-persist-nondeterministic-tool-call-side-effects-as-first-class-replay-anchors-to-make-multi-agent-speculative-branc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-persist-nondeterministic-tool-call-side-effects-as-first-class-replay-anchors-to-make-multi-agent-speculative-branc.warrant.json
# Markdown SHA-256:   dd0c6108e9e3da69e4bd133d5f2ba0b141a57f39306c1e74b8b65a5cfb357993
# Code AST SHA-256:   1d81bf9cfe2f0bcdbbe7a1f5f815a39ee89dc238f2d584905b51d37eb1358b45
# Verified Classes:   ReplaySoundnessError, LedgerEntry, SideEffectLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ReplaySoundnessError(RuntimeError):
    """Raised when a replay encounters an effect that cannot be reconciled
    against the side-effect ledger, making the replay unsound for forensics."""
    pass


@dataclass
class LedgerEntry:
    branch_id: str
    step_index: int
    logical_clock: int
    tool_call_id: str
    resource: str
    effect: str  # "write" | "read" | "external"
    payload_digest: str
    committed: Optional[bool] = None  # None until commit/abort resolves


@dataclass
class SideEffectLedger:
    entries: list[LedgerEntry] = field(default_factory=list)
    _clock: int = 0

    def record(self, branch_id: str, step_index: int, tool_call_id: str,
               resource: str, effect: str, payload_digest: str) -> LedgerEntry:
        # Persist at call time, before commit status is known.
        self._clock += 1
        e = LedgerEntry(branch_id, step_index, self._clock, tool_call_id,
                        resource, effect, payload_digest)
        self.entries.append(e)
        return e

    def resolve_commit(self, branch_id: str, committed: bool) -> None:
        for e in self.entries:
            if e.branch_id == branch_id:
                e.committed = committed

    def reconcile_read(self, committed_branch: str, resource: str,
                       at_clock: int) -> list[LedgerEntry]:
        """Return aborted-sibling effects on `resource` that are logically
        earlier than `at_clock` and could contaminate a read on the committed
        branch. Non-empty result means the replay must annotate, not trust."""
        return [
            e for e in self.entries
            if e.resource == resource
            and e.branch_id != committed_branch
            and e.committed is False
            and e.effect == "write"
            and e.logical_clock < at_clock
        ]


def replay_committed_read(ledger: SideEffectLedger, committed_branch: str,
                          resource: str, recorded_return: str,
                          at_clock: int) -> str:
    phantoms = ledger.reconcile_read(committed_branch, resource, at_clock)
    if phantoms:
        # The recorded return may or may not include the phantom; we cannot
        # know without the pre-state. Refuse to assert soundness.
        raise ReplaySoundnessError(
            f"read of {resource!r} on branch {committed_branch!r} at clock "
            f"{at_clock} is contaminated by aborted sibling effect(s): "
            f"{[p.tool_call_id for p in phantoms]}. Replay cannot certify "
            f"that recorded return {recorded_return!r} reflects the world "
            f"the agent actually saw."
        )
    return recorded_return


# --- trigger trace ---
ledger = SideEffectLedger()
ledger.record("plan-A", 7, "call-a1", "/workspace/out.txt", "write", "digest-A")
ledger.record("plan-B", 6, "call-b1", "/workspace/out.txt", "write", "digest-B")
ledger.resolve_commit("plan-A", True)
ledger.resolve_commit("plan-B", False)

replay_committed_read(ledger, "plan-A", "/workspace/out.txt", "content-A", at_clock=8)
