# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fork-and-reconcile-lose-branch-lineage-when-speculative-agents-share-a-mutable-tool-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fork-and-reconcile-lose-branch-lineage-when-speculative-agents-share-a-mutable-tool-cache.warrant.json
# Markdown SHA-256:   f8d1362ad0294cbdd60606660fd6659a7ad5ac90f68941af3aac72d819ab8aa0
# Code AST SHA-256:   c848d2af0c99a7219a209c7bb5396e06284ffa836aef372bacb4bd423e6707f6
# Verified Classes:   DanglingLineageError, CacheEntry, Branch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class DanglingLineageError(RuntimeError):
    """Raised when reconciliation would commit a branch whose reads
    resolve to cache entries produced by rolled-back sibling branches."""
    pass


@dataclass
class CacheEntry:
    key: str
    producer: str            # branch id that wrote this entry
    deterministic: bool
    readers: set = field(default_factory=set)


@dataclass
class Branch:
    id: str
    reads: list              # list of cache keys read during speculation
    writes: list             # list of CacheEntry keys written


def reconcile(winner_id: str, branches: dict, cache: dict) -> set:
    """Return the set of cache keys to retain. Fail closed on dangling reads.

    Sound rule: retain the transitive closure of reads reachable from the
    winner, promoting any non-deterministic producer that a surviving
    branch consumed. Never subtract-by-tag.
    """
    if winner_id not in branches:
        raise DanglingLineageError(f"winner {winner_id} not in branch set")

    retained: set = set()
    # Seed with winner's own writes.
    retained.update(branches[winner_id].writes)

    # Walk the winner's reads; each read must resolve to a retained entry
    # or be promotable.
    stack = list(branches[winner_id].reads)
    seen = set()
    while stack:
        key = stack.pop()
        if key in seen:
            continue
        seen.add(key)
        if key not in cache:
            # Read of a never-written key: re-executable or a real bug.
            continue
        entry = cache[key]
        retained.add(key)
        producer = entry.producer
        if producer == winner_id:
            continue
        # Cross-branch read: promote producer's writes and reads.
        if producer not in branches:
            raise DanglingLineageError(
                f"entry {key} read by {winner_id} produced by unknown branch {producer}"
            )
        if not entry.deterministic:
            # Non-deterministic cross-branch dependency: must promote the
            # producer's entire input chain, or we cannot guarantee replay.
            prod = branches[producer]
            retained.update(prod.writes)
            stack.extend(prod.reads)
        else:
            # Deterministic: retained value is replayable, but we still
            # keep the entry so the read edge resolves.
            retained.add(key)

    # Final invariant: no retained read edge points at a dropped entry.
    for key in retained:
        entry = cache.get(key)
        if entry is None:
            continue
        for reader in entry.readers:
            if reader in {winner_id} and key not in retained:
                raise DanglingLineageError(
                    f"committed branch {winner_id} reads {key} which is not retained"
                )
    return retained


def commit(winner_id: str, branches: dict, cache: dict) -> set:
    retained = reconcile(winner_id, branches, cache)
    for key in list(cache):
        if key not in retained:
            del cache[key]
    return retained
