# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-memory-write-has-been-invalidated-by-a-divergent-tool-call-result.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-speculative-memory-write-has-been-invalidated-by-a-divergent-tool-call-result.warrant.json
# Markdown SHA-256:   254339f9d9dbe3b4315cbc00e0a926af7c641cc141720d632c221b54373147aa
# Code AST SHA-256:   adc715255194fa4cbd749a68eefd8e871f65273dceaffa69c344a6a9b4e7f70c
# Verified Classes:   SpeculationDivergenceError, Provenance, MemoryRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class SpeculationDivergenceError(RuntimeError):
    """Raised when a speculative memory write cannot be safely promoted
    because the authoritative tool result structurally diverges from the
    hypothesized result, or because the speculation lacked a completeness
    attestation required for the downstream inference that consumed it."""


class Provenance(str, Enum):
    SPECULATIVE = "speculative"
    CONFIRMED = "confirmed"
    TOMBSTONED = "tombstoned"


@dataclass
class MemoryRecord:
    key: str
    value: dict[str, Any]
    hypothesis_id: str
    complete: bool          # did the speculation claim completeness?
    provenance: Provenance = Provenance.SPECULATIVE
    consumers: list[str] = field(default_factory=list)  # step-ids that read it


def _structural_diff(pred: dict[str, Any], actual: dict[str, Any]) -> dict[str, Any]:
    """Return a diff describing how pred and actual diverge structurally.

    Detects cardinality mismatch on collections, missing keys, and as_of skew —
    the signals a scalar-equality check would miss.
    """
    diff: dict[str, Any] = {"missing_in_pred": [], "cardinality": {}, "as_of_skew": False}
    for k, av in actual.items():
        if k not in pred:
            diff["missing_in_pred"].append(k)
            continue
        pv = pred[k]
        if isinstance(pv, (list, set, tuple)) and isinstance(av, (list, set, tuple)):
            if len(pv) != len(av):
                diff["cardinality"][k] = (len(pv), len(av))
    if ("as_of" in actual) != ("as_of" in pred):
        diff["as_of_skew"] = True
    return diff


def reconcile_speculative_write(
    record: MemoryRecord,
    actual_result: dict[str, Any],
    reasoned_about_absence: bool,
) -> MemoryRecord:
    """Gate promotion of a speculative record on a structural confirmation predicate.

    Promotion is permitted only when the speculation attested completeness and the
    authoritative result is structurally identical. A superset result is NOT
    confirmation when the record was consumed by an absence-reasoning step.
    """
    diff = _structural_diff(record.value, actual_result)
    diverges = bool(diff["missing_in_pred"] or diff["cardinality"] or diff["as_of_skew"])

    if not diverges:
        record.provenance = Provenance.CONFIRMED
        return record

    # Divergence detected. If a downstream step already reasoned about absence
    # using this record, in-place repair is unsound — force rollback.
    if reasoned_about_absence and record.consumers:
        raise SpeculationDivergenceError(
            f"speculative record {record.key!r} (hypothesis {record.hypothesis_id!r}) "
            f"diverged from authoritative result; consumers {record.consumers!r} "
            f"reasoned about absence and must be rolled back. diff={diff!r}"
        )

    # Otherwise tombstone and let the caller write the authoritative record fresh.
    record.provenance = Provenance.TOMBSTONED
    return record


def commit_or_rollback(record: MemoryRecord, actual_result: dict[str, Any]) -> MemoryRecord:
    """Convenience wrapper for the common path where the record was consumed
    by a step whose inference mode is tracked on the record itself."""
    reasoned_about_absence = any(c.startswith("absence:") for c in record.consumers)
    return reconcile_speculative_write(record, actual_result, reasoned_about_absence)
