# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-because-its-namespace-lease-expired-mid-transaction-ttl-expiry-as-a-torn-write-hazard-in-scoped-memory-too.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-memory-write-because-its-namespace-lease-expired-mid-transaction-ttl-expiry-as-a-torn-write-hazard-in-scoped-memory-too.warrant.json
# Markdown SHA-256:   a9005f8b3c74e0c2aa403c1bbac7466daafbb5ca508f78b024a95b4af09c1eae
# Code AST SHA-256:   d9594dd46e427d0913aa7015a601b77cd328e86c5778e52ded2800f2766c1286
# Verified Classes:   LeaseExpiredError, GenerationMismatchError, MemoryView, ScopedMemoryClient
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any, Optional


class LeaseExpiredError(RuntimeError):
    """Namespace lease lapsed before commit; write must not resurrect."""


class GenerationMismatchError(RuntimeError):
    """Namespace generation advanced between read and write; in-context merge is stale."""


@dataclass(frozen=True)
class MemoryView:
    value: Any
    generation: int
    lease_expires_at: float
    missing: bool


class ScopedMemoryClient:
    """Client enforcing the generation-check invariant on leased namespaces."""

    def __init__(self, transport, clock):
        self._transport = transport
        self._clock = clock

    def get(self, namespace: str, key: str) -> MemoryView:
        raw = self._transport.get(namespace, key)
        return MemoryView(
            value=raw.get("value"),
            generation=raw["generation"],
            lease_expires_at=raw["lease_expires_at"],
            missing=raw.get("missing", False),
        )

    def set_if_lease_valid(
        self,
        namespace: str,
        key: str,
        value: Any,
        expected_generation: int,
    ) -> int:
        now = self._clock()
        current = self._transport.get_meta(namespace)

        if current["lease_expires_at"] <= now:
            # Fail closed. Do NOT let the server resurrect-on-write.
            raise LeaseExpiredError(
                f"namespace {namespace!r} lease expired at "
                f"{current['lease_expires_at']:.3f} (now {now:.3f}); "
                f"refusing write to key {key!r}"
            )

        if current["generation"] != expected_generation:
            # Another writer or tombstone-clear intervened; merge is stale.
            raise GenerationMismatchError(
                f"namespace {namespace!r} generation advanced "
                f"{expected_generation} -> {current['generation']}; "
                f"discard in-context merge for key {key!r} and re-read"
            )

        result = self._transport.set_cas(
            namespace, key, value, expected_generation=expected_generation
        )
        if not result["ok"]:
            # Lost a commit race despite the pre-check; treat as mismatch.
            raise GenerationMismatchError(
                f"CAS failed on {namespace!r}/{key!r}: "
                f"server generation is {result['generation']}"
            )
        return result["generation"]


def commit_step_result(
    client: ScopedMemoryClient,
    namespace: str,
    view: MemoryView,
    step_id: str,
) -> int:
    """Append a completed step to a plan under the generation invariant."""
    if view.missing:
        # Namespace was absent at read time; agent has no authority to
        # initialize it implicitly — that is the supervisor's job.
        raise LeaseExpiredError(
            f"namespace {namespace!r} was absent at read; "
            f"cannot commit step {step_id!r} without explicit renewal"
        )

    plan = dict(view.value or {})
    done = list(plan.get("done", []))
    if step_id in done:
        # Idempotent replay: do not re-execute, do not rewrite.
        return view.generation

    done.append(step_id)
    plan["done"] = done
    plan["cursor"] = len(done)

    return client.set_if_lease_valid(
        namespace=namespace,
        key="plan",
        value=plan,
        expected_generation=view.generation,
    )
