What deterministic seed states must be saved to reproduce stochastic execution outcomes?

**Date of Record:** 2026 October 25 **Scope:** Applies when an agentic session executes stochastic operations (LLM sampling, random module usage, probabilistic routing) and must persist the state required to reproduce the exact outcome for debugging, audit, or deterministic replay. Does not apply to strictly deterministic algorithms or operations where the outcome is invariant to random number generation.

Core Distinction

The separation between **transient sampled output** (the specific random number generated, the specific token sampled, or the specific probabilistic path taken) and the **deterministic seed state** (the exact entropy source, PRNG algorithm version, and consumption parameters that produced the sample). Transient output is an artifact; the seed state is the generative engine. Furthermore, a seed value alone is insufficient: it must be atomically bound to the **PRNG implementation version** and the **consumption parameters** (temperature, top-p, dropout rate). Saving a seed without the algorithm and parameters creates a **Seed-Replay Fallacy**, where a successor attempts to replay the seed but generates a completely different outcome due to an underlying library upgrade or a shifted probability distribution.

What Was Observed

In distributed agent architectures and LLM pipelines, failing to properly record deterministic seed states produces three primary failure modes:

  1. **Ghost Bug Irreproducibility:** A stochastic failure (e.g., a hallucination at high temperature, or a random shuffle causing a race condition) occurs. The instance logs the seed as `42`, but the successor runs the replay and gets a different result because the environment upgraded from `numpy<1.17` to `numpy>=1.17`, changing the PRNG algorithm.
  2. **Entropy Leakage:** An instance explicitly sets `random.seed(123)`, but a downstream library silently calls `os.urandom()` or `uuid.uuid4()` without routing through the seeded PRNG. The seed is recorded, but the actual execution path is non-reproducible.
  3. **Parameter Drift:** The exact seed is saved, but the inference parameters (temperature, top_p) shift between sessions. The random draw is identical, but the mapping of that draw to a token or action diverges.

Recorded Elements

  1. **`prng_algorithm_identifier`:** The exact algorithm and version used for generation (e.g., `Mersenne_Twister_MT19937`, `PCG64`, `Philox_4x32_10`), ensuring the seed maps to the correct mathematical sequence.
  2. **`initial_entropy_seed`:** The root seed value or entropy pool snapshot injected into the algorithm.
  3. **`consumption_parameters`:** The exact parameters that map the random draw to an outcome (e.g., `temperature=0.7`, `top_p=0.9`, `dropout=0.1`).
  4. **`external_entropy_bypass_log`:** An explicit record of any sub-components that bypassed the seeded PRNG and consumed OS-level or hardware-level entropy (e.g., `/dev/urandom`), flagging the execution as `PARTIALLY_NON_DETERMINISTIC`.

Condition of Validity

* **Applies when:** The session executes operations that rely on pseudo-random number generation, and a successor, auditor, or replay engine must be able to reproduce the exact sequence of outcomes. * **Does not apply when:** The operation is mathematically deterministic, or the exact stochastic outcome is irrelevant to the downstream conclusion (e.g., picking a random jitter delay where any delay is acceptable).

Decision Boundary

  1. **Did the session execute stochastic operations that affect the final conclusion?** If no, no seed state is required. If yes, proceed to capture the seed.
  2. **Is the PRNG algorithm identifier recorded alongside the seed value?** If no, the seed is non-replayable across environments. The instance must record the algorithm version or fail closed. If yes, proceed.
  3. **Are the consumption parameters (temperature, distribution bounds) explicitly saved?** If no, the stochastic draw cannot be mapped to the same outcome. The parameters must be persisted alongside the seed.
  4. **Conversely, when must a replay attempt be rejected entirely?** If the `external_entropy_bypass_log` indicates unseeded OS-level entropy was consumed in the critical path, the outcome is fundamentally non-reproducible. The successor must be instructed to treat the replay as invalid and seek the original output artifact instead.

Operational Effect

  1. **Exact Replay Guarantee:** Replaces probabilistic reproduction with mathematical certainty, allowing successors to step through stochastic failures line-by-line.
  2. **Algorithm-Awareness:** Prevents the silent failure of the Seed-Replay Fallacy by locking the seed to its exact mathematical implementation.
  3. **Entropy Transparency:** Surfaces hidden OS-level entropy consumption, preventing the illusion of determinism in environments that are actually only partially seeded.
from dataclasses import dataclass
from enum import Enum, auto
import hashlib
import json


class PRNGAlgorithm(Enum):
    MT19937 = auto()
    PCG64 = auto()
    PHILOX_4X32 = auto()
    OS_URANDOM = auto()


@dataclass(frozen=True)
class StochasticExecutionContext:
    algorithm: PRNGAlgorithm
    initial_seed: str
    consumption_parameters: tuple[tuple[str, str], ...]
    external_entropy_bypass: bool


@dataclass(frozen=True)
class DeterministicReplayManifest:
    context: StochasticExecutionContext
    replay_digest: str


class SeedStateRecorder:
    """
    Evaluates and seals stochastic execution contexts, ensuring that
    replayability is mathematically sound and not subject to the
    Seed-Replay Fallacy.
    """

    @staticmethod
    def _hash(data: str) -> str:
        return hashlib.sha256(data.encode("utf-8")).hexdigest()

    @classmethod
    def seal_manifest(
        cls, context: StochasticExecutionContext
    ) -> DeterministicReplayManifest:
        
        if not context.initial_seed.strip():
            raise ValueError("Initial seed must be explicitly provided.")
            
        if context.algorithm is PRNGAlgorithm.OS_URANDOM:
            raise ValueError(
                "OS_URANDOM cannot be deterministically replayed; use a seeded algorithm."
            )

        digest_payload = {
            "algorithm": context.algorithm.name,
            "seed": context.initial_seed,
            "parameters": tuple(sorted(context.consumption_parameters)),
            "bypass": str(context.external_entropy_bypass),
        }
        
        digest = cls._hash(
            json.dumps(digest_payload, sort_keys=True, separators=(",", ":"))
        )

        return DeterministicReplayManifest(
            context=context,
            replay_digest=digest,
        )

    @classmethod
    def verify_replay_admissibility(
        cls,
        manifest: DeterministicReplayManifest,
        current_algorithm: PRNGAlgorithm,
    ) -> tuple[bool, str]:
        """
        Fetching-time check: confirms the environment can accurately replay the
        seed, returning (is_admissible, reason).
        """
        
        if manifest.context.external_entropy_bypass:
            return False, "REJECTED: Execution consumed unseeded external entropy; replay is not deterministic."

        if manifest.context.algorithm != current_algorithm:
            return False, f"REJECTED: PRNG algorithm mismatch. Expected {manifest.context.algorithm.name}, found {current_algorithm.name}."

        return True, "ADMISSIBLE: Environment matches replay constraints."