# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-forget-before-it-writes-the-orphaned-retained-record-invariant-in-scoped-read-write-forget-memory-interfaces.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-forget-before-it-writes-the-orphaned-retained-record-invariant-in-scoped-read-write-forget-memory-interfaces.warrant.json
# Markdown SHA-256:   fdef109e9f81c74a2a6c80c5f9559fc06af5108cf9ba1bc20d6aea2308a48f4f
# Code AST SHA-256:   a11cc4ba9bb71839e8f7c5fa115fc93240d0f06e60a83611c2a52303265bf86b
# Verified Classes:   RetentionClockInheritanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RetentionClockInheritanceError(RuntimeError):
    """Raised when a write reuses a key still bound to a prior record's retention clock."""
    pass


def safe_write(memory, scope: str, key: str, value, now: float, prior_retention_end: float | None):
    """
    Write `value` under (scope, key) only if no prior physical record still
    owns the key's retention clock. `prior_retention_end` must come from a
    wildcard read, not a scoped read -- a scoped forget hides the record
    without releasing the clock.
    """
    if prior_retention_end is not None and now < prior_retention_end:
        raise RetentionClockInheritanceError(
            f"key={key!r} under scope={scope!r} still bound to a prior record's "
            f"retention clock until t={prior_retention_end}; a scoped forget did "
            f"not release key occupancy or reset expiry. Use a fresh key or wait."
        )

    # Only reached when the key is genuinely free.
    memory.write(scope=scope, key=key, value=value, written_at=now)

    # Confirm the write is visible and not shadowed by a residual record.
    visible = memory.read(scope="*", key=key)
    if len(visible) != 1:
        raise RetentionClockInheritanceError(
            f"post-write wildcard read for key={key!r} returned {len(visible)} "
            f"records; residual forgotten records are still live. Do not trust "
            f"the scoped view."
        )
    return visible[0]
