# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-speculatively-committed-downstream-state-after-a-parallel-branch-s-tool-call-returns-a-late-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-invalidate-speculatively-committed-downstream-state-after-a-parallel-branch-s-tool-call-returns-a-late-failure.warrant.json
# Markdown SHA-256:   53d667afd9274e303c09ee7b662d86f64fa2199e976906c3e0fea47abddebad1
# Code AST SHA-256:   78852d4a130fb46e2063714b8bffe3d490ae0b79033ae0af2ca438af944bbf19
# Verified Classes:   DanglingSpeculativeCommit
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DanglingSpeculativeCommit(RuntimeError):
    """Raised when a consumer branch's provisional commit is consumed by a durable
    executor while a dependency remains non-terminal or has failed late."""
    pass


TERMINAL_SUCCESS = "SUCCESS"
TERMINAL_FAILURE = "FAILURE"
PENDING = "PENDING"


def seal_and_promote(commit, dependencies):
    """
    commit: dict with keys 'epoch', 'deps', 'provisional', 'durable_read'
    dependencies: dict dep_id -> terminal state
    Promote a provisional commit to durable only if every dependency is a
    terminal SUCCESS. If any dependency failed late, the commit must be
    invalidated or compensated -- never silently promoted.
    """
    if not commit.get("provisional", True):
        return commit  # already durable; nothing to seal

    for dep_id in commit["deps"]:
        state = dependencies.get(dep_id, PENDING)

        if state == PENDING:
            # Cannot seal on a non-terminal dependency. This is the boundary:
            # committing here is exactly the premature-seal bug.
            raise DanglingSpeculativeCommit(
                f"commit epoch={commit['epoch']} depends on non-terminal "
                f"dependency {dep_id}; seal forbidden"
            )

        if state == TERMINAL_FAILURE:
            if commit.get("durable_read"):
                # Rollback is no longer free; require compensation, not un-send.
                commit["status"] = "SUPERSEDED"
                commit["compensation_required"] = True
                return commit
            # Still provisional and unread: safe to invalidate outright.
            commit["status"] = "INVALIDATED"
            commit["provisional"] = False
            return commit

        if state != TERMINAL_SUCCESS:
            raise DanglingSpeculativeCommit(
                f"unknown dependency state {state!r} for {dep_id}"
            )

    commit["provisional"] = False
    commit["status"] = "DURABLE"
    return commit
