# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-abandon-speculative-tool-call-staging-when-a-staged-side-effect-s-precondition-is-invalidated-by-a-concurrent-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-abandon-speculative-tool-call-staging-when-a-staged-side-effect-s-precondition-is-invalidated-by-a-concurrent-commit.warrant.json
# Markdown SHA-256:   e5a76cdbe786a1a08f1c39317b9f5d613489bce1fc1278fc2fc0a8e34a9ec817
# Code AST SHA-256:   c9caeb11901b10d3b3b530740e57bdef091f889bb95bc4163a78be16234929e0
# Verified Classes:   OrphanedStagedEffect
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class OrphanedStagedEffect(RuntimeError):
    """Raised when a staged effect's precondition read-set no longer validates
    against live state at commit time. The effect must be discarded and
    re-planned; it MUST NOT be merged, even if its write-set is disjoint
    from any concurrent commit."""
    pass


def commit_staged_effect(effect, live_state):
    # effect = {"write_set": [...], "read_set": [(res, field), ...],
    #           "preconditions": {(res, field): (observed_value, version_token)},
    #           "payload": ...}
    for (res, field) in effect["read_set"]:
        observed, token = effect["preconditions"][(res, field)]
        current_value, current_token = live_state.get((res, field), (None, None))
        if current_token != token or current_value != observed:
            # Disjoint write-set does NOT save us: the derivation is orphaned.
            raise OrphanedStagedEffect(
                f"precondition invalidated: {res}.{field} was "
                f"{observed!r}@{token!r}, now {current_value!r}@{current_token!r}; "
                f"effect payload {effect['payload']!r} derived from stale belief "
                f"-> discard and re-plan, do not merge"
            )
    # Only after full read-set re-validation may we attempt write-set merge.
    return apply_write_set(effect["write_set"], effect["payload"], live_state)
