# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-siblings-when-speculative-branches-commit-against-a-shared-tool-ledger.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-diverge-from-its-siblings-when-speculative-branches-commit-against-a-shared-tool-ledger.warrant.json
# Markdown SHA-256:   f2817b22162ef83329e57e191e47f23b7ce7f03286c9055e35e1ea768e3229b7
# Code AST SHA-256:   643814e91a7c2c9f8ffbbf446215cc288c4526fea9112aa997fc26d00c6204fb
# Verified Classes:   OptimisticWindowViolation, Envelope, MergeResult, Ledger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OptimisticWindowViolation(RuntimeError):
    """Raised when a tainted observation is merged into a durable fact."""
    pass


@dataclass
class Envelope:
    branch_id: str
    source: str
    value: object
    confidence: float
    taint_window: Optional[str] = None  # set if read inside an open optimistic window
    provenance_model: str = "fresh"     # "fresh" | "stale_discounted"


@dataclass
class MergeResult:
    value: object
    confidence: float
    source: str


class Ledger:
    def __init__(self) -> None:
        self.open_windows: dict[str, str] = {}   # window_id -> mutating branch
        self.closed_windows: dict[str, str] = {} # window_id -> "committed" | "compensated"

    def open_window(self, window_id: str, branch_id: str) -> None:
        self.open_windows[window_id] = branch_id

    def close_window(self, window_id: str, outcome: str) -> None:
        if window_id not in self.open_windows:
            raise OptimisticWindowViolation(f"unknown window {window_id}")
        self.closed_windows[window_id] = outcome
        del self.open_windows[window_id]

    def is_tainted(self, env: Envelope) -> bool:
        if env.taint_window is None:
            return False
        outcome = self.closed_windows.get(env.taint_window)
        # Unresolved window => still tainted. Compensated => permanently tainted.
        if outcome is None:
            return True
        return outcome == "compensated"


def reconcile(
    ledger: Ledger,
    envelopes: list[Envelope],
    fact_is_durable: bool,
) -> MergeResult:
    """Merge envelopes, refusing to promote tainted observations to durable facts."""
    eligible = []
    for env in envelopes:
        if ledger.is_tainted(env):
            if fact_is_durable:
                # A tainted read observed a state that may have been compensated.
                # It cannot ground a fact that outlives the optimistic window.
                raise OptimisticWindowViolation(
                    f"branch {env.branch_id} envelope reads window "
                    f"{env.taint_window} which was compensated; "
                    f"cannot merge into durable fact"
                )
            continue  # non-durable: drop tainted, fall through
        eligible.append(env)

    if not eligible:
        raise OptimisticWindowViolation("no clean envelopes eligible for merge")

    # Confidence is only comparable within a provenance model.
    models = {e.provenance_model for e in eligible}
    if len(models) > 1:
        raise OptimisticWindowViolation(
            f"cannot compare confidences across provenance models {models}"
        )

    best = max(eligible, key=lambda e: e.confidence)
    return MergeResult(value=best.value, confidence=best.confidence, source=best.source)


# Reproduction of the third-fork failure:
# F opens window w1 and optimistically applies a credit; G reads balance inside w1.
# F compensates; the ledger write is undone but G's envelope is now tainted.
ledger = Ledger()
ledger.open_window("w1", "branch_F")
g_env = Envelope("branch_G", "billing.balance", 1250, 0.90,
                 taint_window="w1", provenance_model="fresh")
ledger.close_window("w1", "compensated")

try:
    reconcile(ledger, [g_env], fact_is_durable=True)
except OptimisticWindowViolation as e:
    print(f"blocked: {e}")
