What prevents stale session variables from contaminating newly written external residuals?
**Date of Record:** 2026 October 25 **Scope:** Applies when an agentic instance resumes from a checkpoint, operates in a warm-start environment, or inherits an execution context from a predecessor, and is preparing to write new conclusions to an external memory layer. Does not apply to strictly cold-start stateless invocations where no prior session context exists.
Core Distinction
The separation between **inherited context** (the state, tokens, identifiers, and variables passed forward from a predecessor session) and **freshly verified environment state** (the current ground truth as probed by the active instance). An inherited variable is a historical pointer valid only at the predecessor's termination epoch; a residual is a newly synthesized operational conclusion. Writing an inherited variable into a new residual without re-verification commits stale context as if it were fresh ground truth, polluting the memory layer with ghost state.
What Was Observed
In warm-start and checkpoint-resume architectures, failing to isolate stale session variables produces three primary failure modes:
- **Ghost Resource Writes:** An instance inherits a `target_resource_id` from a predecessor session, writes a new conclusion attributing success to that resource, but the resource was destroyed during the gap. The residual points to a non-existent external entity.
- **Expired Token Attribution:** The instance inherits a bearer token from the predecessor, uses it to authenticate a write, and succeeds locally because the memory layer does not validate the token against the external issuer. The residual is later audited and found to have been written under revoked credentials.
- **Temporal Epoch Collapse:** The instance inherits a `session_uuid` or `write_timestamp` from the predecessor and attributes the new residual to the predecessor's epoch, corrupting the causal timeline of the memory layer.
Recorded Elements
- **`inherited_variable_manifest`:** The explicit enumeration of every variable, token, ID, and timestamp pulled from the predecessor session, tagged with its source epoch and marked `UNVERIFIED_INHERITED`.
- **`freshness_probe_receipt`:** For each inherited variable used in the write, the exact ground-truth probe (API lookup, resource existence check, token introspection) that re-validated it against current state.
- **`session_snapshot_boundary`:** The strict temporal and structural demarcation between the predecessor's terminal state and the successor's active write context, ensuring no variable crosses without explicit re-verification.
- **`generation_epoch_marker`:** A monotonic counter or fresh timestamp attached to the new residual, proving it was generated by the active session rather than inherited from the predecessor.
Condition of Validity
* **Applies when:** The active instance has inherited context from a predecessor session (via checkpoint, shared filesystem, environment variables, or context buffer), and that inherited context could contain variables that have since become stale. * **Does not apply when:** The instance is a cold-start stateless invocation with zero inherited context, or the inherited variables are provably immutable constants (e.g., permanent API schema versions).
Decision Boundary
- **Was the variable generated by the active session or inherited from a predecessor?** If generated fresh, write it. If inherited, proceed to re-verification.
- **Has the inherited variable been re-verified against current ground truth?** If no, quarantine the variable and either re-probe or regenerate it. If yes, attach the `freshness_probe_receipt` and proceed.
- **Does the new residual contain any `UNVERIFIED_INHERITED` variables in its payload?** If yes, reject the write and force the instance to either re-verify or strip the inherited component.
- **Conversely, when can an inherited variable be written without re-verification?** Only if the variable is explicitly declared as an immutable constant in the record's scope (e.g., a static schema version), or the write is explicitly marked as a `HISTORICAL_ATTRIBUTION` record documenting the predecessor's state rather than asserting current truth.
Operational Effect
- **Ghost-Write Prevention:** Ensures that no residual attributes success or failure to a resource that no longer exists or was never validated by the active session.
- **Credential Integrity:** Prevents residuals from being written under inherited credentials that may have been revoked during the session gap, preserving audit trail validity.
- **Causal Timeline Integrity:** Guarantees that every residual carries a fresh generation epoch, preventing temporal collapse where new conclusions are attributed to predecessor epochs.
from dataclasses import dataclass
from enum import Enum, auto
import hashlib
import json
class VariableFreshness(Enum):
FRESH_GENERATED = auto()
VERIFIED_INHERITED = auto()
UNVERIFIED_INHERITED = auto()
IMMUTABLE_CONSTANT = auto()
@dataclass(frozen=True)
class SessionVariable:
name: str
value: str
freshness: VariableFreshness
source_epoch: str
verification_receipt: str | None = None
@dataclass(frozen=True)
class ResidualWriteRequest:
residual_id: str
payload: str
variables_used: tuple[SessionVariable, ...]
generation_epoch: str
@dataclass(frozen=True)
class WriteVerdict:
is_safe: bool
rejected_variables: frozenset[str]
verdict_digest: str
class StaleStateGuard:
"""
Evaluates residual write requests to ensure no inherited session variable
contaminates the new residual without explicit re-verification.
"""
@staticmethod
def _hash(data: str) -> str:
return hashlib.sha256(data.encode("utf-8")).hexdigest()
@classmethod
def evaluate_write(cls, request: ResidualWriteRequest) -> WriteVerdict:
if not request.generation_epoch.strip():
raise ValueError(
"Write request lacks a fresh generation epoch marker."
)
rejected: set[str] = set()
for variable in request.variables_used:
# Gate 1: Fresh or immutable variables are always safe
if variable.freshness in (
VariableFreshness.FRESH_GENERATED,
VariableFreshness.IMMUTABLE_CONSTANT,
):
continue
# Gate 2: Verified inherited requires a receipt
if variable.freshness is VariableFreshness.VERIFIED_INHERITED:
if not variable.verification_receipt or not variable.verification_receipt.strip():
rejected.add(variable.name)
continue
# Gate 3: Unverified inherited is always a violation
if variable.freshness is VariableFreshness.UNVERIFIED_INHERITED:
rejected.add(variable.name)
is_safe = len(rejected) == 0
digest_payload = {
"residual_id": request.residual_id,
"generation_epoch": request.generation_epoch,
"rejected": tuple(sorted(rejected)),
}
digest = cls._hash(
json.dumps(digest_payload, sort_keys=True, separators=(",", ":"))
)
return WriteVerdict(
is_safe=is_safe,
rejected_variables=frozenset(rejected),
verdict_digest=digest,
)
@classmethod
def assert_write_safe(cls, verdict: WriteVerdict) -> None:
"""
Fail-closed enforcement: raise if the write contains stale variables.
"""
if not verdict.is_safe:
raise RuntimeError(
f"Residual write rejected: stale variables "
f"{sorted(verdict.rejected_variables)} lack fresh verification."
)