# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-tool-call-pre-execution-when-optimistic-concurrency-collides-with-semantic-conflict-detection.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-abort-speculative-tool-call-pre-execution-when-optimistic-concurrency-collides-with-semantic-conflict-detection.warrant.json
# Markdown SHA-256:   68890217b824d82cca17975abef513641a2e3a174c5ecddad2d7c0c1b522edc0
# Code AST SHA-256:   0750f664130f1fa8f40ef3c65283fd9a0066119e1128649ddf89c55f25a86269
# Verified Classes:   SpeculativeCommitConflict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class SpeculativeCommitConflict(RuntimeError):
    """Raised when a buffered speculative write must be aborted.

    Covers the dangerous PASS/CONFLICT cell (concurrency passes, semantics
    conflict) and the fail-closed PASS/UNKNOWN cell (semantic detector could
    not verify intent). Both require abort, not commit.
    """
    pass


def commit_speculative_buffer(buffer, resource, semantic_detector):
    """Commit a speculative tool-call buffer under dual invariants.

    Concurrency (version token) guards the narrow resource scope.
    Semantic detection guards the wide scope (resource + peer annotations +
    distilled memory). The wide invariant dominates: any semantic conflict or
    unverifiable semantic state aborts, regardless of the concurrency verdict.
    """
    # Narrow invariant: has anyone written to THIS resource since we read it?
    concurrency_ok = buffer.expected_version == resource.version

    # Wide invariant: is the reason we are writing still true, given external
    # annotations and freshly distilled memory?
    try:
        semantic_verdict = semantic_detector.evaluate(
            intent=buffer.intent,
            constraints=semantic_detector.load_constraints(refresh=True),
        )
    except Exception as exc:  # detector failed to load; fail closed
        semantic_verdict = "UNKNOWN"
        semantic_error = exc

    if not concurrency_ok:
        # Benign race: discard and re-read. No contradiction possible.
        buffer.discard()
        return {"action": "retry", "reason": "version_mismatch"}

    if semantic_verdict == "CONFLICT":
        # Dangerous cell: version passed but intent is refuted by wider state.
        buffer.discard()
        buffer.inject_constraint_into_loop(semantic_detector.last_conflict)
        raise SpeculativeCommitConflict(
            f"semantic conflict on buffered intent {buffer.intent!r} "
            f"despite version match {buffer.expected_version}; "
            f"aborting buffer and re-entering reasoning loop"
        )

    if semantic_verdict == "UNKNOWN":
        # Fail closed: unverified is not cleared.
        buffer.discard()
        raise SpeculativeCommitConflict(
            "semantic detector could not verify intent "
            f"({semantic_error!r}); refusing to commit unverified write"
        )

    # PASS/PASS: both invariants hold.
    resource.apply(buffer.intent, expected_version=buffer.expected_version)
    buffer.clear()
    return {"action": "committed"}
