# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-treat-a-redaction-tombstone-as-authoritative-over-a-late-arriving-write-and-what-breaks-when-it-does-not.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-treat-a-redaction-tombstone-as-authoritative-over-a-late-arriving-write-and-what-breaks-when-it-does-not.warrant.json
# Markdown SHA-256:   43638d1c917a203ed52ca22d81ebbfaedceccaba64109285d5691f91f237f79f
# Code AST SHA-256:   9504f01b03c96fe177b765dc28c2a38abc0bcf7eb917a14a84a619070d03b04e
# Verified Classes:   TombstoneResurrectionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TombstoneResurrectionError(RuntimeError):
    """Raised when a write's causal parent predates an authoritative tombstone
    on the same key and overlapping scope, i.e. the write would resurrect
    redacted content."""
    def __init__(self, key, write_seq, write_parents, tombstone_seq, watermark, scope):
        self.key = key
        self.write_seq = write_seq
        self.write_parents = write_parents
        self.tombstone_seq = tombstone_seq
        self.watermark = watermark
        self.scope = scope
        super().__init__(
            f"write@{write_seq} on {key!r} (parents={sorted(write_parents)}) "
            f"would resurrect content dominated by tombstone@{tombstone_seq} "
            f"(watermark={watermark}, scope={scope})"
        )


def admit_write(key, write_seq, write_parents, scope, tombstones):
    """Validate a write against all live tombstones on the key.

    A write is admissible only if, for every tombstone whose scope overlaps
    the write's scope, the write's causal horizon is at or beyond the
    tombstone's watermark. Arrival order is irrelevant.
    """
    for ts in tombstones:
        if ts.key != key:
            continue
        if not scopes_overlap(ts.scope, scope):
            continue
        horizon = max(write_parents) if write_parents else -1
        if horizon < ts.watermark:
            raise TombstoneResurrectionError(
                key=key,
                write_seq=write_seq,
                write_parents=write_parents,
                tombstone_seq=ts.seq,
                watermark=ts.watermark,
                scope=scope,
            )
    return True


def scopes_overlap(a, b):
    # tenant=* overlaps everything; otherwise exact tenant match required.
    return a.get("tenant") == "*" or b.get("tenant") == "*" or a.get("tenant") == b.get("tenant")


def flush_checkpoint(buffer, tombstones):
    """Re-validate every buffered write at flush time. Buffers are untrusted
    on resume: they may carry causal parents from before a redaction."""
    for entry in buffer:
        try:
            admit_write(
                key=entry["key"],
                write_seq=entry["seq"],
                write_parents=entry["parents"],
                scope=entry["scope"],
                tombstones=tombstones,
            )
        except TombstoneResurrectionError:
            # Do not repair with a second redact; halt and surface.
            raise
    return buffer
