# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-divergence-from-corrupting-the-committed-lineage-during-multi-agent-rollback.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-divergence-from-corrupting-the-committed-lineage-during-multi-agent-rollback.warrant.json
# Markdown SHA-256:   7fe6837b1718ff4303d5cdad645f24f04b2e90e753334d38de60128d30ffb264
# Code AST SHA-256:   40df207d6a9a4a30b501ccadcba1bd97e0b252d492ca2a258739da51f619021d
# Verified Classes:   RollbackLineageCorruption
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RollbackLineageCorruption(RuntimeError):
    """Raised when post-rollback head references a revision from a non-committed branch."""
    pass


def verify_committed_lineage(effect_log, committed_branches):
    """
    Re-derive the resource head from committed branches only, then assert the
    live head matches. Must be called AFTER rollback completes.
    """
    # 1. Rebuild what head *should* be from the committed set alone.
    expected_head = {}
    for rev in effect_log.revisions_ordered():
        if rev.branch_id not in committed_branches:
            continue
        expected_head[rev.resource] = rev.revision_id

    # 2. Pull the actual live head (what merge/rollback left behind).
    actual_head = effect_log.live_head()

    # 3. Any divergence means a losing branch leaked past compensation.
    for resource, expected_rev in expected_head.items():
        actual_rev = actual_head.get(resource)
        if actual_rev != expected_rev:
            provenance = effect_log.provenance_of(actual_rev)
            if provenance.branch_id not in committed_branches:
                raise RollbackLineageCorruption(
                    f"resource={resource!r} head={actual_rev!r} "
                    f"produced_by_losing_branch={provenance.branch_id!r} "
                    f"expected={expected_rev!r}; rollback was scoped to agent "
                    f"identity, not effect provenance"
                )

    # 4. Memory writes are effects: same assertion over the memory store.
    for entry in effect_log.memory_entries():
        if entry.branch_id not in committed_branches and entry.is_live():
            raise RollbackLineageCorruption(
                f"memory entry {entry.id!r} from losing branch "
                f"{entry.branch_id!r} survived rollback; will cause stale-memory drift"
            )

    return True
