# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-forget-tombstone-has-been-orphaned-from-its-retention-policy-during-concurrent-memory-tool-re-issuance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-scoped-forget-tombstone-has-been-orphaned-from-its-retention-policy-during-concurrent-memory-tool-re-issuance.warrant.json
# Markdown SHA-256:   8d50bfdacb522730f201ebc28325377493cfafe7cf13955323c19d7d9f7d4066
# Code AST SHA-256:   f9fabcd7ca19da20ab9b49e020a67bc5b6315e9532d40023ac863be4ea088c43
# Verified Classes:   OrphanedTombstoneError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedTombstoneError(RuntimeError):
    """Raised when a forget tombstone cannot suppress a record due to scope-version
    divergence or an unresolvable pinned retention policy."""
    pass


def verify_suppression(tombstone: dict, record: dict, policy_registry: dict) -> bool:
    if tombstone is None:
        # No tombstone: the record is a legitimate fresh write.
        return False

    tomb_v = tombstone["scope_version"]
    rec_v = record["scope_version"]
    if tomb_v < rec_v:
        raise OrphanedTombstoneError(
            f"tombstone {tombstone['id']} at scope_version={tomb_v} is dominated by "
            f"record {record['id']} at scope_version={rec_v}; suppression invalid"
        )

    pinned = tombstone["policy_ref"]
    if pinned not in policy_registry:
        raise OrphanedTombstoneError(
            f"tombstone {tombstone['id']} pins unresolvable policy {pinned!r}; "
            f"reaper cannot compute retention horizon and must fail closed"
        )

    return True


def guarded_read(key: str, store, tombstone_index, policy_registry) -> dict:
    record = store.get(key)
    if record is None:
        return {"value": None, "quarantined": False}

    tombstone = tombstone_index.lookup(key)
    try:
        suppressed = verify_suppression(tombstone, record, policy_registry)
    except OrphanedTombstoneError:
        # Quarantine: do not propagate the value; force re-assertion.
        return {"value": None, "quarantined": True, "record_id": record["id"]}

    if suppressed:
        return {"value": None, "quarantined": False}
    return {"value": record["value"], "quarantined": False}
