# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-crossed-the-causal-commit-boundary-in-multi-agent-deterministic-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-branch-has-crossed-the-causal-commit-boundary-in-multi-agent-deterministic-replay.warrant.json
# Markdown SHA-256:   383dd807bed9472d3f677e8fe88f693e9e1ff928ae99ba9a44d325c4264bfb7d
# Code AST SHA-256:   c796db3ce7a560670fb7da39b7bcb10acef1a640a46267264877ee635680884b
# Verified Classes:   CausalCommitViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CausalCommitViolation(RuntimeError):
    """Raised when a speculative branch has written to parent-attributed state."""
    pass


def assert_commit_boundary(trace, committed_branch_id):
    """
    Validate that the committed lineage is replay-sound with respect to
    the causal-commit boundary. Raises CausalCommitViolation on:
      - an orphaned causal edge (reads_from resolving to a discarded branch)
      - a monotonic counter discontinuity on the committed path
    """
    committed_edges = trace.edges_for(committed_branch_id)

    for edge in committed_edges:
        writer = trace.provenance(edge.written_by_key)
        if writer is None:
            raise CausalCommitViolation(
                f"edge {edge.id} on committed branch {committed_branch_id} "
                f"has no provenance for key {edge.written_by_key!r}"
            )
        if writer.branch_id != committed_branch_id:
            raise CausalCommitViolation(
                f"orphaned causal edge {edge.id}: committed branch "
                f"{committed_branch_id} reads key {edge.written_by_key!r} "
                f"written by discarded branch {writer.branch_id}"
            )

    committed_sum = sum(
        trace.counter_delta(b) for b in trace.committed_branches()
    )
    observed = trace.counter_at_commit(committed_branch_id)
    if observed > committed_sum:
        raise CausalCommitViolation(
            f"counter discontinuity on committed path: observed {observed} "
            f"exceeds committed-branch sum {committed_sum}; "
            f"a discarded branch advanced parent-scoped state"
        )

    return True
