# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-successful-memory-write-as-visible-to-memory-read-before-the-episodic-semantic-distillation-pass-commit.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-successful-memory-write-as-visible-to-memory-read-before-the-episodic-semantic-distillation-pass-commit.warrant.json
# Markdown SHA-256:   89846c38b1fc42d3c6633d9f564dae0b976da00cb11c80936d17c50655d9cda2
# Code AST SHA-256:   e0bd66f8bba4cb8168de264114e52861272429403c007983d438902c247ec2eb
# Verified Classes:   StaleTierReadError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class StaleTierReadError(RuntimeError):
    """Raised when an agent treats a cross-tier read as a read-back of its own write."""
    pass


def verify_write_visibility(write_ack, read_result, schema):
    """
    Enforce the write-acknowledgment discipline across episodic/semantic tiers.

    write_ack: the return value of memory.write(episodic, ...)
    read_result: the return value of memory.read(semantic, ...)
    schema: the tool schema dict, used to detect a watermark handshake
    """
    has_watermark_handshake = (
        "min_watermark" in schema.get("read", {}).get("params", {})
        or "read_token" in schema.get("write", {}).get("returns", {})
    )

    if not has_watermark_handshake:
        # Speculative-read regime: a stale semantic read is NOT evidence
        # the write failed. Do not re-issue, do not escalate on disagreement.
        if read_result is not None and read_result != write_ack.get("value"):
            return {
                "action": "defer_verification",
                "source_of_truth": write_ack,
                "reason": "cross-tier read may predate distillation watermark",
            }
        return {"action": "proceed", "source_of_truth": write_ack}

    # Watermark regime: read-after-write is a valid verification primitive.
    if read_result is None or read_result != write_ack.get("value"):
        raise StaleTierReadError(
            f"watermark-aware read did not reflect acknowledged write: "
            f"ack={write_ack!r} read={read_result!r}"
        )
    return {"action": "proceed", "source_of_truth": read_result}
