mixle.experimental.typed_runtime package

Experimental statistically typed optimization and context-runtime foundation.

The package implements the semantic compiler, measured scheduler, transactional proposal runtime, structured placement, reference-checked local model-parallel adapter, geometry-routed torch optimizer execution, and transactional context-action execution. Real multi-host transport (today’s structured executor uses local worker threads), a general execution adapter for every compiled estimator, and persistent external retrieval/vector-store adapters remain behind later dependency gates – see this package’s README.md (“Not implemented yet”) for the full, current boundary.

class AcceptanceGateReceipt(gate, status, claims, observed, evidence_uri=None, required_evidence_count=1, observed_evidence_count=0, required_fields=())[source]

Bases: object

One falsifiable gate attached to one or more public claims.

Parameters:
  • gate (str)

  • status (GateStatus)

  • claims (tuple[ClaimKind, ...])

  • observed (str)

  • evidence_uri (str | None)

  • required_evidence_count (int)

  • observed_evidence_count (int)

  • required_fields (tuple[str, ...])

class ArtifactKind(*values)[source]

Bases: StrEnum

Versionable artifacts read or written by update nodes.

class AttentionCandidate(node_id, key, value, position, token_ids, tokenizer_id, materialized_content_hash)[source]

Bases: object

One graph node with retrieval vectors and content-bound materialized token IDs.

Parameters:
property measured_token_count: int

Token work derived from the materialized token-ID sequence.

class BenchmarkPoint(step, objective, elapsed_seconds, operation_count=0, model_evaluations=0, bytes_read=0, bytes_written=0, collective_bytes=0, peak_memory_bytes=0, maximum_staleness_steps=0, accepted_updates=0, rejected_updates=0, work_counter_semantics=CounterSemantics.CUMULATIVE, peak_memory_semantics=CounterSemantics.HIGH_WATER_MARK, staleness_semantics=CounterSemantics.HIGH_WATER_MARK)[source]

Bases: object

One cumulative quality/work observation from an actual run.

Parameters:
  • step (int)

  • objective (float)

  • elapsed_seconds (float)

  • operation_count (int)

  • model_evaluations (int)

  • bytes_read (int)

  • bytes_written (int)

  • collective_bytes (int)

  • peak_memory_bytes (int)

  • maximum_staleness_steps (int)

  • accepted_updates (int)

  • rejected_updates (int)

  • work_counter_semantics (CounterSemantics)

  • peak_memory_semantics (CounterSemantics)

  • staleness_semantics (CounterSemantics)

as_dict()[source]

Return a JSON-compatible benchmark observation.

Return type:

dict[str, Any]

class BoundaryInbox(graph, *, run_id, model_id)[source]

Bases: object

Validate versions, order, approximation, and exactly-once delivery.

Parameters:
  • graph (UpdateGraph)

  • run_id (str)

  • model_id (str)

property receipts: tuple[BoundaryReceipt, ...]

Return an immutable snapshot of receive decisions.

receive(message, versions)[source]

Validate and consume one message without applying its runtime payload.

Parameters:
  • message (BoundaryMessage)

  • versions (RuntimeVersions)

Return type:

BoundaryReceipt

next_sequence(message)[source]

Return the next expected sequence number for a message’s stream.

Parameters:

message (BoundaryMessage)

Return type:

int

as_dict()[source]

Return replay-relevant inbox state and receipts.

Return type:

dict[str, Any]

class BoundaryMessage(message_id, run_id, model_id, node_id, source_shard, target_shard, model_version, node_version, dependency_versions, sequence_number, kind, payload, observations=0.0, tokens=0, responsibility_mass=0.0, precision=None, approximate=False, error_bound=None, payload_hash='')[source]

Bases: object

One immutable versioned shard-boundary payload.

Parameters:
  • message_id (str)

  • run_id (str)

  • model_id (str)

  • node_id (str)

  • source_shard (str)

  • target_shard (str)

  • model_version (int)

  • node_version (int)

  • dependency_versions (tuple[tuple[str, int], ...])

  • sequence_number (int)

  • kind (BoundaryMessageKind)

  • payload (Any)

  • observations (float)

  • tokens (int)

  • responsibility_mass (float)

  • precision (str | None)

  • approximate (bool)

  • error_bound (float | None)

  • payload_hash (str)

property stream_key: tuple[str, str, str, str, str, BoundaryMessageKind]

Ordering domain for this message.

property dependency_version_map: dict[str, int]

Return the declared dependency vector as a fresh mapping.

as_dict()[source]

Return metadata and payload fingerprint, never the runtime payload.

Return type:

dict[str, Any]

class BoundaryMessageKind(*values)[source]

Bases: StrEnum

Semantic payload crossing a model, graph, cache, or provider boundary.

class BoundaryReceipt(message_id, run_id, model_id, node_id, accepted, reason, expected_sequence, observed_sequence, current_model_version, current_node_version, declared_dependency_versions, current_dependency_versions, payload_hash)[source]

Bases: object

Accepted/rejected boundary message with expected and observed versions.

Parameters:
as_dict()[source]

Return a JSON-compatible boundary receipt.

Return type:

dict[str, Any]

class BatchSemanticsReceipt(examples_per_microbatch, tokens_per_microbatch, responsibility_mass_per_microbatch, accumulation_steps, data_parallel_world_size, optimizer_updates, loss_reduction, loss_scale, schedule_position)[source]

Bases: object

Unambiguous microbatch, accumulation, world-size, and update accounting.

Parameters:
  • examples_per_microbatch (int)

  • tokens_per_microbatch (int)

  • responsibility_mass_per_microbatch (float)

  • accumulation_steps (int)

  • data_parallel_world_size (int)

  • optimizer_updates (int)

  • loss_reduction (str)

  • loss_scale (float)

  • schedule_position (int)

class BoundaryFaultInjector(events)[source]

Bases: object

Apply each scripted message fault at most once and retain delayed payloads.

Parameters:

events (tuple[FaultEvent, ...])

intercept(message, *, step)[source]

Return zero, one, or two messages after applying a scripted fault.

Parameters:
  • message (BoundaryMessage)

  • step (int)

Return type:

tuple[BoundaryMessage, …]

release(*, step)[source]

Release delayed messages whose scripted step has arrived.

Parameters:

step (int)

Return type:

tuple[BoundaryMessage, …]

recover(shard_id)[source]

Mark a failed source shard available for retried messages.

Parameters:

shard_id (str)

Return type:

None

as_dict()[source]

Return replay-relevant injector state and receipts.

Return type:

dict[str, Any]

class CachedArtifact(node_id, artifact, generation, value)[source]

Bases: object

One cached value tied to the producing node’s generation.

Parameters:
  • node_id (str)

  • artifact (ArtifactKind)

  • generation (int)

  • value (Any)

class CachedGraphPartition(partition, content_hash, graph_version, measured_token_count, boundary_edge_ids, pinned=False)[source]

Bases: object

Partition content fingerprint captured at cache insertion.

Parameters:
  • partition (GraphPartition)

  • content_hash (str)

  • graph_version (int)

  • measured_token_count (int)

  • boundary_edge_ids (tuple[str, ...])

  • pinned (bool)

class CanaryVerdict(accepted, reason, objective_before=None, objective_after=None, lower_confidence_gain=None, confidence_level=None, sample_count=0, metrics=<factory>, proposal_objectives=<factory>)[source]

Bases: object

Measured acceptance evidence after proposals have been tentatively applied.

Parameters:
  • accepted (bool)

  • reason (str)

  • objective_before (float | None)

  • objective_after (float | None)

  • lower_confidence_gain (float | None)

  • confidence_level (float | None)

  • sample_count (int)

  • metrics (dict[str, float])

  • proposal_objectives (dict[str, ObjectiveGateEvidence])

property objective_gain: float | None

Measured objective difference when both values are available.

as_dict()[source]

Return a JSON-compatible canary receipt.

Return type:

dict[str, Any]

class ClaimKind(*values)[source]

Bases: StrEnum

Scale claims guarded by independently inspectable evidence.

class ClockDecision(node_id, due, triggers, progress, last_commit, commit_count)[source]

Bases: object

Due/not-due decision and elapsed work since the last commit.

Parameters:
  • node_id (str)

  • due (bool)

  • triggers (tuple[ClockTrigger, ...])

  • progress (ClockProgress)

  • last_commit (ClockProgress | None)

  • commit_count (int)

as_dict()[source]

Return a JSON-compatible clock decision.

Return type:

dict[str, Any]

class ClockProgress(step=0, tokens=0, observations=0.0, counter_semantics=CounterSemantics.CUMULATIVE)[source]

Bases: object

Monotone run progress against which node cadences are evaluated.

Parameters:
  • step (int)

  • tokens (int)

  • observations (float)

  • counter_semantics (CounterSemantics)

as_dict()[source]

Return a JSON-compatible progress vector.

Return type:

dict[str, int | float]

class ClockTrigger(*values)[source]

Bases: StrEnum

Reason an update clock became due.

class ClusterTopology(devices, links)[source]

Bases: object

Directed measured network over topology-aware compute devices.

Parameters:
  • devices (tuple[TopologyDevice, ...])

  • links (tuple[LinkProfile, ...])

property islands: tuple[str, ...]

Sorted failure/network islands.

devices_in(island)[source]

Devices in one island, ordered by id.

Parameters:

island (str)

Return type:

tuple[TopologyDevice, …]

resources(island=None)[source]

Adapt topology devices to the stable placement planner’s resource type.

Parameters:

island (str | None)

Return type:

Resources

best_island()[source]

Island with the largest declared aggregate throughput.

Return type:

str

transfer(source, target, nbytes)[source]

Shortest transfer-time route under current link profiles.

Parameters:
Return type:

TransferEstimate

as_dict()[source]

Return a JSON-compatible topology receipt.

Return type:

dict[str, Any]

class CollectiveNumericsEvidence(evidence_id, update_id, collective, mesh_axes, backend, dtype, deterministic, maximum_absolute_error, maximum_relative_error, sample_count, ordering_fingerprint)[source]

Bases: object

Observed backend determinism and error for one exact collective identity.

Parameters:
  • evidence_id (str)

  • update_id (str)

  • collective (CollectiveKind)

  • mesh_axes (tuple[ParallelAxis, ...])

  • backend (str)

  • dtype (str)

  • deterministic (bool)

  • maximum_absolute_error (float)

  • maximum_relative_error (float)

  • sample_count (int)

  • ordering_fingerprint (str)

class CommitReceipt(commit_id, batch_id, proposal_ids, status, reason, versions_before, versions_after, invalidated_nodes=(), canary=None, participant_fingerprints_before=<factory>, participant_fingerprints_after=<factory>, rollback_verified=None, error_type=None, error_message=None, run_id='', model_id='', elapsed_seconds=0.0)[source]

Bases: object

Coordinator decision, state fingerprints, and version transition.

Parameters:
  • commit_id (str)

  • batch_id (str)

  • proposal_ids (tuple[str, ...])

  • status (CommitStatus)

  • reason (str)

  • versions_before (dict[str, Any])

  • versions_after (dict[str, Any])

  • invalidated_nodes (tuple[str, ...])

  • canary (CanaryVerdict | None)

  • participant_fingerprints_before (dict[str, str])

  • participant_fingerprints_after (dict[str, str])

  • rollback_verified (bool | None)

  • error_type (str | None)

  • error_message (str | None)

  • run_id (str)

  • model_id (str)

  • elapsed_seconds (float)

property accepted: bool

Whether this transaction advanced the model version.

as_dict()[source]

Return a JSON-compatible commit receipt.

Return type:

dict[str, Any]

class CommitStatus(*values)[source]

Bases: StrEnum

Terminal result of one commit attempt.

class CompressedDelta(method, shape, dtype, arrays, receipt, feedback_token)[source]

Bases: object

Immutable wire payload whose residual transition is pending acknowledgement.

Parameters:
  • method (CompressionMethod)

  • shape (tuple[int, ...])

  • dtype (str)

  • arrays (tuple[ndarray, ...])

  • receipt (CompressionReceipt)

  • feedback_token (str)

reconstruct()[source]

Reconstruct a dense delta in the declared dtype and shape.

Return type:

ndarray

property payload_hash: str

Deterministic transport fingerprint.

as_dict()[source]

Return metadata without serializing array contents.

Return type:

dict[str, Any]

class CompressionAcknowledgement(key, feedback_token, payload_hash, applied, residual_l2_norm_before, residual_l2_norm_after)[source]

Bases: object

Committed or rejected residual transition for one delivered payload.

Parameters:
  • key (str)

  • feedback_token (str)

  • payload_hash (str)

  • applied (bool)

  • residual_l2_norm_before (float)

  • residual_l2_norm_after (float)

class CompressionMethod(*values)[source]

Bases: StrEnum

Wire representation selected for one delta.

class CompressionReceipt(key, method, input_bytes, payload_bytes, rank_or_nnz, realized_l2_error, relative_l2_error, pending_residual_l2_norm, exact, approximation_authorized, maximum_relative_l2_error)[source]

Bases: object

Measured bytes/error and authorization for one staged transport payload.

Parameters:
  • key (str)

  • method (CompressionMethod)

  • input_bytes (int)

  • payload_bytes (int)

  • rank_or_nnz (int)

  • realized_l2_error (float)

  • relative_l2_error (float)

  • pending_residual_l2_norm (float)

  • exact (bool)

  • approximation_authorized (bool)

  • maximum_relative_l2_error (float | None)

property compression_ratio: float

Dense bytes divided by transmitted payload bytes.

as_dict()[source]

Return a JSON-compatible staged-compression receipt.

Return type:

dict[str, Any]

class CorrectionResult(source_proposal_id, source_payload_hash, run_id, model_id, node_id, target_model_version, target_dependency_versions, semantics, method, evidence_id, payload, payload_hash='')[source]

Bases: object

Identity-bound payload recomputed or approximated for target versions.

Parameters:
  • source_proposal_id (str)

  • source_payload_hash (str)

  • run_id (str)

  • model_id (str)

  • node_id (str)

  • target_model_version (int)

  • target_dependency_versions (tuple[tuple[str, int], ...])

  • semantics (CorrectionSemantics)

  • method (str)

  • evidence_id (str)

  • payload (Any)

  • payload_hash (str)

property fingerprint: str

Bind the exact correction payload, target state, method, and evidence.

class CorrectionSemantics(*values)[source]

Bases: StrEnum

Whether a corrected payload is exact at the target state or approximate.

class ConsistencyRequirement(*values)[source]

Bases: StrEnum

Strongest distributed consistency mode known to preserve semantics.

class ComputeBand(*values)[source]

Bases: StrEnum

Model-side compute-precision eligibility of a node’s scoring subtree.

float32_eligible means the subtree fuses AND every leaf family is in the validated reduced-precision set (mixle.inference.precision_plan.FP32_SAFE_FAMILIES) – the fused float32 kernel’s summed-log-likelihood error is verified < ~1e-6 relative there. The DATA-side conditions (bounded magnitude, non-degenerate variances) remain a runtime decision (optimize(precision="minimal")); this axis declares what the model structure permits. Composition is weakest-link: one ineligible node keeps the tree at float64.

class ConvergenceCertificate(*values)[source]

Bases: StrEnum

Strongest convergence-guarantee class attributable to a node’s update rule.

Guarantees compose by WEAKEST LINK: a tree’s certificate is the minimum over its nodes’ (see weakest_certificate()). A frozen node is vacuously monotone – a preserved dependency cannot decline the objective.

  • monotone_certified: exact / generalized-EM updates under the strict acceptance gate; the accepted-objective sequence is non-decreasing and (bounded above by the estimator variance floors) converges.

  • robbins_monro_schedule: first-order updates whose per-round step schedule lies in the Robbins–Monro window (lr_decay in (0.5, 1]) – the step-size conditions stochastic-approximation EM analyses require for almost-sure convergence to stationary points.

  • best_visited: stochastic/mutable updates with no schedule guarantee; the outer loop returns the best visited iterate.

  • unknown: no attributable guarantee.

property strength: int

Total order for weakest-link composition (higher is stronger).

class ContextAction(action_id, kind, expected_graph_version=None, input_nodes=(), query=None, source_scope=(), expected_information_gain=0.0, gain_standard_error=0.0, gain_sample_count=0, expected_latency_seconds=0.0, expected_tokens=0, expected_monetary_cost=0.0, expected_tool_calls=0, maximum_outputs=1, generated_output=False, resource_limits=None)[source]

Bases: object

Inspectable proposal for one context-construction operation.

Parameters:
  • action_id (str)

  • kind (ContextActionKind)

  • expected_graph_version (int | None)

  • input_nodes (tuple[str, ...])

  • query (str | None)

  • source_scope (tuple[str, ...])

  • expected_information_gain (float)

  • gain_standard_error (float)

  • gain_sample_count (int)

  • expected_latency_seconds (float)

  • expected_tokens (int)

  • expected_monetary_cost (float)

  • expected_tool_calls (int)

  • maximum_outputs (int)

  • generated_output (bool)

  • resource_limits (ContextActionLimits | None)

as_dict()[source]

Return a JSON-compatible context action.

Return type:

dict[str, Any]

class ContextActionKind(*values)[source]

Bases: StrEnum

Operation that may create, expand, verify, or materialize context.

class ContextActionLimits(latency_seconds, materialized_tokens, monetary_cost, tool_calls)[source]

Bases: object

Finite worst-case resources an adapter is permitted to consume.

Parameters:
  • latency_seconds (float)

  • materialized_tokens (int)

  • monetary_cost (float)

  • tool_calls (int)

as_dict()[source]

Return JSON-compatible action resource limits.

Return type:

dict[str, Any]

class ContextActionExecutor(graph, adapters=None)[source]

Bases: object

Apply adapter results atomically to a versioned context graph.

Parameters:
  • graph (ContextGraph)

  • adapters (Mapping[ContextActionKind, ContextActionAdapter] | None)

register(kind, adapter)[source]

Register or deliberately replace one action adapter.

Parameters:
  • kind (ContextActionKind)

  • adapter (Callable[[ContextAction, ContextGraphView], ContextActionResult])

Return type:

None

execute(action)[source]

Execute one context action and return success or rollback receipt.

Parameters:

action (ContextAction)

Return type:

ContextActionReceipt

as_dict()[source]

Return graph and action ledger.

Return type:

dict[str, Any]

class ContextActionResult(nodes=(), edges=(), verifications=(), remove_nodes=(), external_latency_seconds=0.0, materialized_tokens=0, tool_calls=0, monetary_cost=0.0, measured_information_gain=None, outcome='completed')[source]

Bases: object

Pure graph mutations and actual external work returned by an adapter.

Parameters:
  • nodes (tuple[ContextNode, ...])

  • edges (tuple[ContextEdge, ...])

  • verifications (tuple[VerificationUpdate, ...])

  • remove_nodes (tuple[str, ...])

  • external_latency_seconds (float)

  • materialized_tokens (int)

  • tool_calls (int)

  • monetary_cost (float)

  • measured_information_gain (float | None)

  • outcome (str)

class ContextGraphView(version, nodes, edges)[source]

Bases: object

Detached, read-only graph snapshot supplied to action adapters.

Parameters:
classmethod from_snapshot(snapshot)[source]

Create a view whose mappings and values are detached from the live graph.

Parameters:

snapshot (tuple[int, dict[str, ContextNode], dict[str, ContextEdge]])

Return type:

ContextGraphView

neighbors(node_id)[source]

Return both incoming and outgoing neighbors from this fixed snapshot.

Parameters:

node_id (str)

Return type:

tuple[str, …]

class ContextAttentionConfig(tokenizer_id, exact_near_tokens=4096, exact_near_nodes=64, retrieved_nodes=32, maximum_active_tokens=8192, maximum_active_nodes=96, maximum_scored_nodes=4096, maximum_attention_elements=1000000, temperature=1.0)[source]

Bases: object

Hard bounds and the tokenizer identity used by materialized token sequences.

Parameters:
  • tokenizer_id (str)

  • exact_near_tokens (int)

  • exact_near_nodes (int)

  • retrieved_nodes (int)

  • maximum_active_tokens (int)

  • maximum_active_nodes (int)

  • maximum_scored_nodes (int)

  • maximum_attention_elements (int)

  • temperature (float)

class ContextAttentionReceipt(tokenizer_id, source_nodes, source_horizon_tokens, maximum_scored_nodes, maximum_attention_elements, maximum_active_nodes, maximum_active_tokens, scored_nodes, scoring_elements, exact_node_ids, retrieved_node_ids, active_nodes, active_tokens, active_token_counts, excluded_unverified_generated, similarities)[source]

Bases: object

Selected nodes plus measured, independently bounded token and vector work.

Parameters:
  • tokenizer_id (str)

  • source_nodes (int)

  • source_horizon_tokens (int | None)

  • maximum_scored_nodes (int)

  • maximum_attention_elements (int)

  • maximum_active_nodes (int)

  • maximum_active_tokens (int)

  • scored_nodes (int)

  • scoring_elements (int)

  • exact_node_ids (tuple[str, ...])

  • retrieved_node_ids (tuple[str, ...])

  • active_nodes (int)

  • active_tokens (int)

  • active_token_counts (tuple[tuple[str, int], ...])

  • excluded_unverified_generated (tuple[str, ...])

  • similarities (dict[str, float])

as_dict()[source]

Return a JSON-compatible attention receipt.

Return type:

dict[str, Any]

class ContextAttentionResult(value, receipt)[source]

Bases: object

Attended value and selection receipt.

Parameters:
  • value (ndarray)

  • receipt (ContextAttentionReceipt)

class ContextActionReceipt(action, graph_version_before, graph_version_after, output_nodes, output_edges, latency_seconds, materialized_tokens, tool_calls, monetary_cost, measured_information_gain, outcome, rolled_back=False)[source]

Bases: object

Actual graph transition and cost for one context action.

Parameters:
  • action (ContextAction)

  • graph_version_before (int)

  • graph_version_after (int)

  • output_nodes (tuple[str, ...])

  • output_edges (tuple[str, ...])

  • latency_seconds (float)

  • materialized_tokens (int)

  • tool_calls (int)

  • monetary_cost (float)

  • measured_information_gain (float | None)

  • outcome (str)

  • rolled_back (bool)

as_dict()[source]

Return a JSON-compatible context action receipt.

Return type:

dict[str, Any]

class ContextBudget(latency_seconds=inf, materialized_tokens=9223372036854775807, monetary_cost=inf, tool_calls=2147483647, maximum_actions=2147483647)[source]

Bases: object

Hard cumulative context-construction resource limits.

Parameters:
  • latency_seconds (float)

  • materialized_tokens (int)

  • monetary_cost (float)

  • tool_calls (int)

  • maximum_actions (int)

class ContextEdge(edge_id, source_node, target_node, kind, confidence=None, provenance=())[source]

Bases: object

One versionable typed relation in the context graph.

Parameters:
  • edge_id (str)

  • source_node (str)

  • target_node (str)

  • kind (ContextEdgeKind)

  • confidence (float | None)

  • provenance (tuple[Provenance, ...])

as_dict()[source]

Return a JSON-compatible context edge.

Return type:

dict[str, Any]

class ContextEdgeKind(*values)[source]

Bases: StrEnum

Typed relation between context artifacts.

class ContextGraph[source]

Bases: object

Mutable, versioned evidence graph with deterministic snapshot/restore.

add_node(node)[source]

Add an immutable node or accept an idempotent duplicate.

Parameters:

node (ContextNode)

Return type:

None

add_edge(edge)[source]

Add an immutable edge after endpoint validation.

Parameters:

edge (ContextEdge)

Return type:

None

verify(node_id, status, *, provenance=(), confidence=None)[source]

Replace verification fields without erasing generated provenance.

Parameters:
  • node_id (str)

  • status (EvidenceStatus)

  • provenance (tuple[Provenance, ...])

  • confidence (float | None)

Return type:

ContextNode

remove_node(node_id)[source]

Remove one node and all incident edges as one versioned mutation.

Parameters:

node_id (str)

Return type:

None

neighbors(node_id, *, kinds=None)[source]

Return both incoming and outgoing neighbors for revisitation.

Parameters:
  • node_id (str)

  • kinds (tuple[ContextEdgeKind, ...] | None)

Return type:

tuple[str, …]

unresolved_nodes()[source]

Generated hypotheses/claims that still need verification.

Return type:

tuple[ContextNode, …]

snapshot()[source]

Capture graph state for transactional context actions.

Return type:

tuple[int, dict[str, ContextNode], dict[str, ContextEdge]]

restore(snapshot)[source]

Restore an action snapshot after failure, or leave the graph untouched.

Validation happens on the candidate before anything is installed, so a rejected snapshot is a no-op rather than a half-applied state: this is the recovery path, and a restore that corrupts the graph it is restoring is worse than one that fails (MXR-080-1859).

Parameters:

snapshot (tuple[int, dict[str, ContextNode], dict[str, ContextEdge]])

Return type:

None

transaction()[source]

Exclude concurrent graph mutations while a staged transaction is prepared.

Return type:

Iterator[None]

replace_if_unchanged(expected, replacement)[source]

Install a staged state only when the complete base snapshot still matches.

Like restore(), the replacement is validated before it is installed, so a rejected staging attempt leaves the live graph exactly as it was (MXR-080-1859).

Parameters:
Return type:

None

as_dict()[source]

Return a JSON-compatible graph sorted by stable ids.

Return type:

dict[str, Any]

class ContextNode(node_id, kind, text, token_count, provenance=(), evidence_status=EvidenceStatus.UNVERIFIED, confidence=None, generated=False, source_horizon_position=None, metadata=<factory>, evidence_history=())[source]

Bases: object

One source, claim, generated artifact, summary, result, or memory unit.

Parameters:
  • node_id (str)

  • kind (ContextNodeKind)

  • text (str)

  • token_count (int)

  • provenance (tuple[Provenance, ...])

  • evidence_status (EvidenceStatus)

  • confidence (float | None)

  • generated (bool)

  • source_horizon_position (int | None)

  • metadata (Mapping[str, Any])

  • evidence_history (tuple[EvidenceTransition, ...])

property content_hash: str

Deterministic node-content fingerprint.

as_dict()[source]

Return a JSON-compatible context node.

Return type:

dict[str, Any]

class ContextNodeKind(*values)[source]

Bases: StrEnum

Semantic role of one bounded context artifact.

class ContextScheduleDecision(selected, ranked_action_ids, lower_confidence_gains, expected_costs, net_values, inadmissible, stopping_reason)[source]

Bases: object

One selected action or explicit stopping action with ranked evidence.

Parameters:
property stopped: bool

Whether the scheduler selected its explicit STOP action.

as_dict()[source]

Return a JSON-compatible decision receipt.

Return type:

dict[str, Any]

class ContextSchedulerConfig(confidence_z=1.645, latency_cost=1.0, token_cost=1e-05, monetary_cost=1.0, tool_call_cost=0.01, minimum_net_value=0.0)[source]

Bases: object

Confidence and resource exchange rates for value-of-information.

Parameters:
class ContextTokenizer(tokenizer_id, encode)[source]

Bases: object

Named deterministic tokenizer used for hard rendered-prompt bounds.

Parameters:
token_ids(text)[source]

Encode twice to reject stateful tokenizers and validate stable integer ids.

Parameters:

text (str)

Return type:

tuple[int, …]

class ContractEvidenceKind(*values)[source]

Bases: StrEnum

Provenance class supporting a compiled update contract.

class ContractRegistry[source]

Bases: object

Explicit contract adapters for models that cannot declare a hook.

Registries are caller-owned rather than process-global. Compiling a test or plugin therefore cannot silently change another run’s semantics.

register(model_type, contract, *, estimator_type=None)[source]

Register one immutable, already constructed contract for a model/estimator pair.

Parameters:
  • model_type (type[Any])

  • contract (UpdateContract)

  • estimator_type (type[Any] | None)

Return type:

None

resolve(model, estimator)[source]

Resolve the most recently registered matching adapter.

Parameters:
  • model (Any)

  • estimator (Any | None)

Return type:

UpdateContract | None

class CostEstimate(compute_units=0.0, wall_time_seconds=None, communication_bytes=0, peak_memory_bytes=0, source='structural_proxy', sample_count=0)[source]

Bases: object

Planning cost with provenance separating measured data from a proxy.

Parameters:
  • compute_units (float)

  • wall_time_seconds (float | None)

  • communication_bytes (int)

  • peak_memory_bytes (int)

  • source (str)

  • sample_count (int)

property measured: bool

Whether this estimate came from runtime observations.

as_dict()[source]

Return a JSON-compatible representation.

Return type:

dict[str, Any]

class CounterSemantics(*values)[source]

Bases: StrEnum

How a numeric work field relates to earlier observations in the same run.

class CurvatureKind(*values)[source]

Bases: StrEnum

Curvature information available to a geometry-aware optimizer.

class CurvatureCache(max_version_lag=0)[source]

Bases: object

Share versioned curvature sketches across related parameters/experts.

Parameters:

max_version_lag (int)

class CurvatureSketch(key, kind, factors, model_id, parameter_fingerprint, model_version, observations)[source]

Bases: object

Versioned curvature factors that may be reused until their staleness bound.

Parameters:
  • key (str)

  • kind (CurvatureKind)

  • factors (tuple[ndarray, ...])

  • model_id (str)

  • parameter_fingerprint (str)

  • model_version (int)

  • observations (float)

property factor_fingerprint: str

Content identity for immutable cached factors.

class DependencyEdge(source_node, target_node, artifact=ArtifactKind.PARAMETERS, reason='child update invalidates parent computation')[source]

Bases: object

A source-node artifact whose change invalidates a dependent target.

Parameters:
  • source_node (str)

  • target_node (str)

  • artifact (ArtifactKind)

  • reason (str)

as_dict()[source]

Return a JSON-compatible representation.

Return type:

dict[str, str]

class EffectiveContextMeasurement(source_horizon_tokens=None, materialized_tokens=0, attended_tokens=0, evidence_nodes=0, evidence_edges=0, context_actions=0, retrieval_actions=0, generation_actions=0, verification_actions=0, tool_calls=0, latency_seconds=0.0, monetary_cost=0.0, verified_claim_fraction=None, stopped_reason=None)[source]

Bases: object

Receipt separating source horizon from bounded active computation.

source_horizon_tokens may be unknown for graph/database/tool sources. It is never inferred from attended tokens. Generated context is counted separately so it cannot be mislabeled as retrieved evidence.

Parameters:
  • source_horizon_tokens (int | None)

  • materialized_tokens (int)

  • attended_tokens (int)

  • evidence_nodes (int)

  • evidence_edges (int)

  • context_actions (int)

  • retrieval_actions (int)

  • generation_actions (int)

  • verification_actions (int)

  • tool_calls (int)

  • latency_seconds (float)

  • monetary_cost (float)

  • verified_claim_fraction (float | None)

  • stopped_reason (str | None)

property active_to_source_ratio: float | None

Materialized/source ratio when the source horizon is known and nonzero.

as_dict()[source]

Return the complete measurement vocabulary as JSON-compatible data.

Return type:

dict[str, Any]

class EffectiveContextRun(decisions, action_receipts, stopping_reason, final_graph_version)[source]

Bases: object

Every scheduler decision and actual action receipt through stopping.

Parameters:
  • decisions (tuple[ContextScheduleDecision, ...])

  • action_receipts (tuple[ContextActionReceipt, ...])

  • stopping_reason (str)

  • final_graph_version (int)

property completed_actions: tuple[ContextActionReceipt, ...]

Receipts excluding the zero-cost STOP marker.

as_dict()[source]

Return a JSON-compatible closed-loop receipt.

Return type:

dict[str, Any]

class EffectiveContextRuntime(graph, scheduler, executor, action_provider)[source]

Bases: object

Run value-of-information context actions until an explicit stopping rule.

Parameters:
  • graph (ContextGraph)

  • scheduler (ValueOfInformationScheduler)

  • executor (ContextActionExecutor)

  • action_provider (ContextActionProvider)

run(*, maximum_iterations=100)[source]

Construct/revisit context until VOI stops or the hard loop guard fires.

Parameters:

maximum_iterations (int)

Return type:

EffectiveContextRun

materialize(relevance, policy, tokenizer, *, source_horizon_tokens=None, required_node_ids=())[source]

Materialize the last run with its measured action costs.

Parameters:
  • relevance (dict[str, float])

  • policy (MaterializationPolicy)

  • tokenizer (ContextTokenizer)

  • source_horizon_tokens (int | None)

  • required_node_ids (tuple[str, ...])

Return type:

MaterializedContext

class ErrorFeedbackCompressor(*, default_rank=1, default_topk_fraction=0.1, exact_threshold_bytes=4_096)[source]

Bases: object

Compressor whose residual changes only after acknowledged payload application.

Parameters:
  • default_rank (int)

  • default_topk_fraction (float)

  • exact_threshold_bytes (int)

residual(key)[source]

Return a copy of one committed error-feedback residual.

Parameters:

key (str)

Return type:

ndarray | None

compress(key, delta, contract, *, allow_approximation=False, maximum_relative_l2_error=None, rank=None, topk_fraction=None)[source]

Stage one payload without changing committed residual state.

Lossy transport requires allow_approximation=True, a finite error budget, and a non-exact update contract. Merge-law metadata never authorizes approximation. Call acknowledge() after delivery/application; until then another payload for key is refused.

Parameters:
  • key (str)

  • delta (Any)

  • contract (UpdateContract)

  • allow_approximation (bool)

  • maximum_relative_l2_error (float | None)

  • rank (int | None)

  • topk_fraction (float | None)

Return type:

CompressedDelta

acknowledge(delta, *, applied)[source]

Commit a staged residual only after the payload was applied, or discard it on failure.

Parameters:
  • delta (CompressedDelta)

  • applied (bool)

Return type:

CompressionAcknowledgement

state_dict()[source]

Return checkpointable committed state; in-flight transitions must be resolved first.

Return type:

dict[str, Any]

load_state_dict(state)[source]

Atomically restore validated committed error-feedback state.

Parameters:

state (dict[str, Any])

Return type:

None

class EvidenceTransition(graph_version, status, provenance=(), confidence=None)[source]

Bases: object

One immutable, graph-versioned evidentiary state.

Parameters:
  • graph_version (int)

  • status (EvidenceStatus)

  • provenance (tuple[Provenance, ...])

  • confidence (float | None)

as_dict()[source]

Return a JSON-compatible evidence transition.

Return type:

dict[str, Any]

class EvidenceStatus(*values)[source]

Bases: StrEnum

Verification status kept separate from model confidence.

class FailureKind(*values)[source]

Bases: StrEnum

Failure families used by Stage-0 negative controls.

class FailureLedger(receipts=())[source]

Bases: object

Append-only in-memory ledger for benchmark failure oracles.

Append-only in fact, not only in the docstring (MXR-080-1905). receipts was a public list on a dataclass, so a ledger holding one failed oracle answered all_oracles_passed: False until ledger.receipts.clear(), after which it answered True – the negative control it was recording had been erased through the very attribute that reports it, and the duplicate-case check in record() was bypassable the same way. receipts is a detached tuple now.

Parameters:

receipts (Sequence[FailureReceipt])

property receipts: tuple[FailureReceipt, ...]

Every recorded failure-oracle receipt, in the order recorded.

record(receipt)[source]

Record one uniquely identified case.

Parameters:

receipt (FailureReceipt)

Return type:

None

property failed_oracles: tuple[FailureReceipt, ...]

Expected failures missed or clean controls falsely flagged.

as_dict()[source]

Return a JSON-compatible ledger.

Return type:

dict[str, Any]

class FailureReceipt(benchmark_id, case_id, kind, oracle, expected_failure, detected, observed, details=<factory>)[source]

Bases: object

Outcome of one expected or naturally occurring failure case.

Parameters:
property oracle_passed: bool

Whether the detector behaved as expected for this case.

as_dict()[source]

Return a JSON-compatible negative-control receipt.

Return type:

dict[str, Any]

class FaultEvent(message_id, kind, release_step=None, version_delta=1)[source]

Bases: object

One scripted fault targeting a message id.

Parameters:
  • message_id (str)

  • kind (FaultKind)

  • release_step (int | None)

  • version_delta (int)

class FaultInjectionReceipt(message_id, kind, step, emitted_messages, reason, applied, target_state_before, target_state_after)[source]

Bases: object

Scripted fault action and number of resulting deliveries.

Parameters:
  • message_id (str)

  • kind (FaultKind | None)

  • step (int)

  • emitted_messages (int)

  • reason (str)

  • applied (bool)

  • target_state_before (str)

  • target_state_after (str)

as_dict()[source]

Return a JSON-compatible fault receipt.

Return type:

dict[str, Any]

class FaultKind(*values)[source]

Bases: StrEnum

Injected delivery or worker failure.

class FrontierClaimAssessment(gates)[source]

Bases: object

Claim decision that remains false for failed or missing required evidence.

Parameters:

gates (tuple[AcceptanceGateReceipt, ...])

class FrozenMetadata(values=None)[source]

Bases: Mapping[str, Any]

Deterministic, recursively immutable context metadata.

Parameters:

values (Mapping[str, Any] | None)

class GainEvidence(node_id, objective_kind, expected_gain, model_version, standard_error=0.0, sample_count=0, normalized_to=None, staleness_risk=0.0)[source]

Bases: object

Objective-gain estimate for one update node.

normalized_to is required when a surrogate gain has been transformed to the scheduler’s reporting objective. Merely setting outer_objective_compatible on a contract does not make unlike numeric scales comparable.

Parameters:
  • node_id (str)

  • objective_kind (ObjectiveKind)

  • expected_gain (float)

  • model_version (int)

  • standard_error (float)

  • sample_count (int)

  • normalized_to (ObjectiveKind | None)

  • staleness_risk (float)

property effective_objective: ObjectiveKind

Objective scale on which expected_gain is expressed.

lower_confidence_bound(z_value)[source]

Return the one-sided normal-approximation lower bound.

Parameters:

z_value (float)

Return type:

float

as_dict()[source]

Return a JSON-compatible representation.

Return type:

dict[str, Any]

class GainPerCostScheduler(config=None)[source]

Bases: object

Stateful deterministic scheduler with terminal-evidence fairness.

Starved nodes move to the front of the ranking, but no scheduling decision may claim resources outside the declared budget.

Parameters:

config (SchedulerConfig | None)

property states: dict[str, NodeScheduleState]

Return a copy of the fairness clocks.

reset()[source]

Reset round and starvation state without changing configuration.

Return type:

None

schedule(graph, evidence=None, *, target_objective=None, model_version, round_index=None, candidate_nodes=None)[source]

Select a budgeted set without claiming that scheduled work succeeded.

Parameters:
  • graph (UpdateGraph)

  • evidence (dict[str, GainEvidence] | None)

  • target_objective (ObjectiveKind | None)

  • model_version (int)

  • round_index (int | None)

  • candidate_nodes (Collection[str] | None)

Return type:

ScheduleReceipt

record_terminal(receipt, outcomes, *, terminal_id)[source]

Advance fairness clocks only after every selected node is terminal.

Parameters:
  • receipt (ScheduleReceipt)

  • outcomes (Sequence[NodeTerminalReceipt])

  • terminal_id (str)

Return type:

ScheduleCompletionReceipt

class GeometryRouterConfig(matrix_min_elements=4096, matrix_min_dimension=16, max_state_to_parameter_ratio=4.0, use_muon=True, use_kronecker=True)[source]

Bases: object

Conservative matrix thresholds and optimizer-state memory limit.

Parameters:
  • matrix_min_elements (int)

  • matrix_min_dimension (int)

  • max_state_to_parameter_ratio (float)

  • use_muon (bool)

  • use_kronecker (bool)

class GraphMemoryPilotReceipt(seed, source_nodes, local_adamw, graph_adamw, graph_routed, recovery, failure_receipts)[source]

Bases: object

Complete context-quality, optimizer, and recovery evidence for the pilot.

Parameters:
  • seed (int)

  • source_nodes (int)

  • local_adamw (PilotStrategyReceipt)

  • graph_adamw (PilotStrategyReceipt)

  • graph_routed (PilotStrategyReceipt)

  • recovery (RecoveryDrillReceipt)

  • failure_receipts (tuple[FailureReceipt, ...])

class GraphMemoryCache(*, maximum_tokens, maximum_partitions)[source]

Bases: object

LRU partition cache bounded by both tokens and partition count.

Parameters:
  • maximum_tokens (int)

  • maximum_partitions (int)

property resident_tokens: int

Total tokens in resident partitions.

get(partition_id, graph)[source]

Return a current partition, dropping stale content fingerprints.

Parameters:
  • partition_id (str)

  • graph (ContextGraph)

Return type:

CachedGraphPartition | None

put(partition, graph, *, pinned=False)[source]

Insert/refresh one partition and return evicted ids.

Parameters:
  • partition (GraphPartition)

  • graph (ContextGraph)

  • pinned (bool)

Return type:

tuple[str, …]

prefetch(plan, graph, partition_ids)[source]

Load requested partitions in order under LRU bounds.

Parameters:
  • plan (GraphPartitionPlan)

  • graph (ContextGraph)

  • partition_ids (tuple[str, ...])

Return type:

GraphPrefetchReceipt

as_dict()[source]

Return resident cache metadata in LRU order.

Return type:

dict[str, Any]

class GraphPartition(partition_id, node_ids, token_count, source_ids)[source]

Bases: object

Bounded graph region and its source-locality metadata.

Parameters:
as_dict()[source]

Return a JSON-compatible partition descriptor.

Return type:

dict[str, Any]

class GraphPartitionPlan(partitions, boundary_edge_ids)[source]

Bases: object

Complete node ownership and cross-partition edge list.

Parameters:
  • partitions (tuple[GraphPartition, ...])

  • boundary_edge_ids (tuple[str, ...])

partition(partition_id)[source]

Return a partition by id.

Parameters:

partition_id (str)

Return type:

GraphPartition

owner(node_id)[source]

Return the unique partition that owns a node.

Parameters:

node_id (str)

Return type:

str

as_dict()[source]

Return a JSON-compatible partition plan.

Return type:

dict[str, Any]

class GraphPrefetchReceipt(requested, loaded, evicted, resident_tokens, resident_before=None)[source]

Bases: object

Requested, loaded, and evicted partition ids for one prefetch.

Parameters:
property eviction_claim_verified: bool

Whether this receipt’s eviction claim was checked against real residency.

A machine-readable verdict rather than an inference from a field being None (MXR-080-0643). False means the receipt was built without resident_before, so its eviction list is an assertion nothing was able to test – the cache’s own producer always supplies it, so a receipt that reports False did not come from a prefetch.

as_dict()[source]

Return a JSON-compatible prefetch receipt.

Return type:

dict[str, Any]

class GateStatus(*values)[source]

Bases: StrEnum

Outcome of one claim gate.

class IssueSeverity(*values)[source]

Bases: StrEnum

Validation issue severity.

class HierarchicalProposalCoordinator(coordinator, *, default_staleness_policy=None, node_staleness_policies=None, payload_mergers=None, correction_provider=None)[source]

Bases: object

Turn local-island proposals into one canonical outer transaction.

Parameters:
  • coordinator (TransactionalCoordinator)

  • default_staleness_policy (StalenessPolicy | None)

  • node_staleness_policies (Mapping[str, StalenessPolicy] | None)

  • payload_mergers (Mapping[str, PayloadMerger] | None)

  • correction_provider (CorrectionProvider | None)

submit(round_id, proposals)[source]

Admit, transform, merge, and commit one set of island proposals.

Parameters:
Return type:

HierarchicalRoundReceipt

class HierarchicalRoundReceipt(round_id, input_proposal_ids, staleness, admitted_proposal_ids, merged_proposals, rejected, commit)[source]

Bases: object

Admission, merge, rejection, and commit result for one outer round.

Parameters:
as_dict()[source]

Return a JSON-compatible hierarchical receipt.

Return type:

dict[str, Any]

class InvalidationReceipt(source_nodes, written_artifact, invalidated_nodes, removed_entries, generations)[source]

Bases: object

Exact cache entries and node generations invalidated by a write.

Parameters:
as_dict()[source]

Return a JSON-compatible receipt without cached values.

Return type:

dict[str, Any]

class LinkProfile(source, target, latency_seconds, bandwidth_bytes_per_second, contention_multiplier=1.0, sample_count=0, provenance='declared')[source]

Bases: object

Directed link startup latency and sustained bandwidth.

Parameters:
  • source (str)

  • target (str)

  • latency_seconds (float)

  • bandwidth_bytes_per_second (float)

  • contention_multiplier (float)

  • sample_count (int)

  • provenance (str)

transfer_seconds(nbytes)[source]

Estimated one-way time including startup and measured contention.

Parameters:

nbytes (int)

Return type:

float

as_dict()[source]

Return a JSON-compatible link profile.

Return type:

dict[str, Any]

class MaterializationPolicy(token_budget, attended_token_budget=None, maximum_nodes=128, minimum_relevance=0.0, require_supported_claims=True, exclude_contradicted=True)[source]

Bases: object

Hard active-context bounds and evidence admission policy.

Parameters:
  • token_budget (int)

  • attended_token_budget (int | None)

  • maximum_nodes (int)

  • minimum_relevance (float)

  • require_supported_claims (bool)

  • exclude_contradicted (bool)

class MaterializedContext(text, node_ids, edge_ids, tokenizer_id, token_ids, token_count, attended_token_indices, attended_tokens, excluded, measurement)[source]

Bases: object

Bounded prompt text, selected evidence subgraph, and honest context receipt.

Parameters:
as_dict()[source]

Return a JSON-compatible materialization receipt.

Return type:

dict[str, Any]

class MeasurementCatalog(records=None)[source]

Bases: object

In-memory measured-cost catalog used by the experimental compiler.

Medians make a small catalog robust to one noisy timing observation. A persistent/versioned catalog is deliberately deferred until the receipt schema has survived real backends.

Parameters:

records (Iterable[WorkMeasurement] | None)

property records: tuple[WorkMeasurement, ...]

The measurements, as a detached read-only view.

This was a public list, so a caller could append a fabricated measurement, delete a real one, or rewrite the catalog the compiler reads its cost estimates from – all without going through record(), which is the only place the type is checked (MXR-080-1878). The catalog is append-only evidence; record/extend are the way in.

record(measurement)[source]

Append one immutable measurement.

Parameters:

measurement (WorkMeasurement)

Return type:

None

extend(measurements)[source]

Append several measurements.

Parameters:

measurements (Iterable[WorkMeasurement])

Return type:

None

matching(node_type, update_kind, backend)[source]

Return exact-key measurements.

Parameters:
  • node_type (str)

  • update_kind (UpdateKind)

  • backend (str)

Return type:

tuple[WorkMeasurement, …]

estimate(node_type, update_kind, backend)[source]

Return a median measured cost, or None when no matching evidence exists.

Parameters:
  • node_type (str)

  • update_kind (UpdateKind)

  • backend (str)

Return type:

CostEstimate | None

as_dict()[source]

Return a JSON-compatible catalog.

Return type:

dict[str, Any]

class MergeLaw(*values)[source]

Bases: StrEnum

Algebra available for combining work from separate data/model shards.

class MultiRateUpdateClocks(cadences)[source]

Bases: object

Stateful cadence registry that never permits progress to move backward.

Parameters:

cadences (dict[str, UpdateCadence])

evaluate(progress, node_ids=None)[source]

Evaluate selected or all registered clocks without marking a commit.

Parameters:
  • progress (ClockProgress)

  • node_ids (tuple[str, ...] | None)

Return type:

tuple[ClockDecision, …]

mark_committed(node_ids, progress)[source]

Advance selected clocks after a successful transaction only.

Parameters:
  • node_ids (tuple[str, ...])

  • progress (ClockProgress)

Return type:

None

as_dict()[source]

Return replay-relevant clock state.

Return type:

dict[str, Any]

class NodePlacement(node_id, scope, primary_island, replica_islands, shards, rationale)[source]

Bases: object

Placement and cross-island replication policy for one typed node.

Parameters:
  • node_id (str)

  • scope (PlacementScope)

  • primary_island (str)

  • replica_islands (tuple[str, ...])

  • shards (tuple[StructuredShard, ...])

  • rationale (str)

as_dict()[source]

Return a JSON-compatible node placement.

Return type:

dict[str, Any]

class NodeExecutionStatus(*values)[source]

Bases: StrEnum

Terminal execution status for one scheduled node.

class ObjectiveKind(*values)[source]

Bases: StrEnum

Objective whose value gives an update its statistical meaning.

class ObjectiveGateEvidence(objective_before, objective_after, lower_confidence_gain=None)[source]

Bases: object

Proposal-specific objective evidence used for mixed or multi-update gates.

Parameters:
  • objective_before (float)

  • objective_after (float)

  • lower_confidence_gain (float | None)

as_dict()[source]

Return a JSON-compatible objective gate.

Return type:

dict[str, float | None]

class ObjectiveTarget(name, direction, threshold, tolerance=0.0)[source]

Bases: object

Explicit quality threshold for a time-to-target benchmark.

Parameters:
  • name (str)

  • direction (TargetDirection)

  • threshold (float)

  • tolerance (float)

reached(value)[source]

Whether value reaches this target within tolerance.

Parameters:

value (float)

Return type:

bool

as_dict()[source]

Return a JSON-compatible target declaration.

Return type:

dict[str, Any]

class OptimizerEvidence(parameter_name, family, target_name, parameter_fingerprint, model_version, target_achieved, time_to_target_seconds, consumed_tokens, optimizer_updates, state_bytes, collective_bytes=0)[source]

Bases: object

Measured candidate performance at a fixed target definition.

Parameters:
  • parameter_name (str)

  • family (OptimizerFamily)

  • target_name (str)

  • parameter_fingerprint (str)

  • model_version (int)

  • target_achieved (bool)

  • time_to_target_seconds (float | None)

  • consumed_tokens (int)

  • optimizer_updates (int)

  • state_bytes (int)

  • collective_bytes (int)

class OptimizerFamily(*values)[source]

Bases: StrEnum

Optimizer/update family chosen for a parameter block.

class OptimizerPlan(routes)[source]

Bases: object

Per-parameter geometry routes for one typed node.

Parameters:

routes (tuple[ParameterRoute, ...])

property optimizer_state_bytes: int

Total planned optimizer and curvature state.

route(name)[source]

Return a route by parameter name.

Parameters:

name (str)

Return type:

ParameterRoute

as_dict()[source]

Return a JSON-compatible plan.

Return type:

dict[str, Any]

class ParameterDescriptor(name, shape, numel, itemsize, role, requires_grad=True, shared_group=None, aliases=(), alias_roles=())[source]

Bases: object

Shape, role, and storage facts for one named parameter.

Parameters:
  • name (str)

  • shape (tuple[int, ...])

  • numel (int)

  • itemsize (int)

  • role (ParameterRole)

  • requires_grad (bool)

  • shared_group (str | None)

  • aliases (tuple[str, ...])

  • alias_roles (tuple[ParameterRole, ...])

property identity_fingerprint: str

Stable logical identity used to bind measurements and curvature.

property parameter_bytes: int

Dense parameter footprint.

as_dict()[source]

Return a JSON-compatible descriptor.

Return type:

dict[str, Any]

class ParameterRole(*values)[source]

Bases: StrEnum

Optimization-relevant role inferred from shape and module path.

class ParameterRoute(parameter, family, fallback_family, reason, optimizer_state_bytes, curvature_kind, separate_clock=False)[source]

Bases: object

Chosen family, fallback, state cost, and scheduling behavior.

Parameters:
  • parameter (ParameterDescriptor)

  • family (OptimizerFamily)

  • fallback_family (OptimizerFamily)

  • reason (str)

  • optimizer_state_bytes (int)

  • curvature_kind (CurvatureKind)

  • separate_clock (bool)

as_dict()[source]

Return a JSON-compatible route.

Return type:

dict[str, Any]

class PlacementScope(*values)[source]

Bases: StrEnum

Communication scope permitted for one typed node.

class PilotStrategyReceipt(strategy, context_mode, optimizer, final_loss, test_accuracy, time_to_target_updates, time_to_target_seconds, target_accuracy, elapsed_seconds, batch, optimizer_families, maximum_active_context_tokens, source_horizon_tokens)[source]

Bases: object

Fixed-budget training and evaluation result for one context/optimizer strategy.

Parameters:
  • strategy (str)

  • context_mode (str)

  • optimizer (str)

  • final_loss (float)

  • test_accuracy (float)

  • time_to_target_updates (int | None)

  • time_to_target_seconds (float | None)

  • target_accuracy (float)

  • elapsed_seconds (float)

  • batch (BatchSemanticsReceipt)

  • optimizer_families (tuple[str, ...])

  • maximum_active_context_tokens (int)

  • source_horizon_tokens (int)

as_dict()[source]

Return a JSON-compatible strategy receipt.

Return type:

dict[str, Any]

class ProposalBatch(batch_id, proposals)[source]

Bases: object

Proposals intended to commit as one versioned transaction.

Parameters:
  • batch_id (str)

  • proposals (tuple[ProposalPacket, ...])

as_dict()[source]

Return a JSON-compatible batch receipt.

Return type:

dict[str, Any]

class ProposalConflict(left_proposal, right_proposal, reason)[source]

Bases: object

A pair of proposals that cannot be committed concurrently.

Parameters:
  • left_proposal (str)

  • right_proposal (str)

  • reason (str)

class ProposalPacket(proposal_id, run_id, model_id, node_id, shard_id, base_model_version, dependency_versions, update_kind, objective_kind, payload, writes=frozenset({ArtifactKind.PARAMETERS}), observations=0.0, tokens=0, responsibility_mass=0.0, local_objective_before=None, local_objective_after=None, global_objective_before=None, global_objective_after=None, predicted_gain=None, measured_gain=None, gain_standard_error=None, optimizer_steps=0, effective_batch_size=0.0, wall_time_seconds=0.0, compute_units=0.0, communication_bytes=0, precision=None, overflow_count=0, underflow_count=0, data_fingerprint=None, data_contribution_ids=(), ordering_fingerprint=None, rng_fingerprint=None, invalidates=(), rollback_reference=None, surrogate_disclosed=False, staleness_semantics=None, correction_fingerprint=None, merge_error_bound=None, payload_hash='')[source]

Bases: object

One worker’s complete, immutable update proposal receipt.

Parameters:
  • proposal_id (str)

  • run_id (str)

  • model_id (str)

  • node_id (str)

  • shard_id (str)

  • base_model_version (int)

  • dependency_versions (tuple[tuple[str, int], ...])

  • update_kind (UpdateKind)

  • objective_kind (ObjectiveKind)

  • payload (Any)

  • writes (frozenset[ArtifactKind])

  • observations (float)

  • tokens (int)

  • responsibility_mass (float)

  • local_objective_before (float | None)

  • local_objective_after (float | None)

  • global_objective_before (float | None)

  • global_objective_after (float | None)

  • predicted_gain (float | None)

  • measured_gain (float | None)

  • gain_standard_error (float | None)

  • optimizer_steps (int)

  • effective_batch_size (float)

  • wall_time_seconds (float)

  • compute_units (float)

  • communication_bytes (int)

  • precision (str | None)

  • overflow_count (int)

  • underflow_count (int)

  • data_fingerprint (str | None)

  • data_contribution_ids (tuple[str, ...])

  • ordering_fingerprint (str | None)

  • rng_fingerprint (str | None)

  • invalidates (tuple[str, ...])

  • rollback_reference (str | None)

  • surrogate_disclosed (bool)

  • staleness_semantics (str | None)

  • correction_fingerprint (str | None)

  • merge_error_bound (float | None)

  • payload_hash (str)

property dependency_version_map: dict[str, int]

Return dependency versions as a fresh mapping.

as_dict()[source]

Return metadata and payload fingerprint, never the runtime payload.

Return type:

dict[str, Any]

class Provenance(source_id, source_version, locator, content_hash, provider=None, uri=None)[source]

Bases: object

Stable source identity and exact locator for one context artifact.

Parameters:
  • source_id (str)

  • source_version (str)

  • locator (str)

  • content_hash (str)

  • provider (str | None)

  • uri (str | None)

as_dict()[source]

Return a JSON-compatible provenance record.

Return type:

dict[str, Any]

class ReplayEntry(batch, expected_receipt, expected_state=None)[source]

Bases: object

One immutable batch, expected receipt, and optional resulting state.

Parameters:
  • batch (ProposalBatch)

  • expected_receipt (CommitReceipt)

  • expected_state (Any)

as_dict()[source]

Return metadata without serializing arbitrary expected state.

Return type:

dict[str, Any]

class ReplayLog(entries=())[source]

Bases: object

Append-only sequence of proposal batches and terminal commit receipts.

record() deep-copies its inputs so a later caller mutation cannot rewrite history – but the list holding them was public, so log.entries[0] = other and log.entries.clear() rewrote exactly the history the copying protects, and replay_log would then replay a sequence that no coordinator ever committed (MXR-080-1905). entries is a detached tuple now; indexing into it (log.entries[0].batch) is unchanged.

Parameters:

entries (Sequence[ReplayEntry])

property entries: tuple[ReplayEntry, ...]

The recorded replay entries, oldest first, as a detached tuple.

record(batch, receipt, *, expected_state=None)[source]

Record detached replay inputs so later caller mutation cannot rewrite history.

Parameters:
  • batch (ProposalBatch)

  • receipt (CommitReceipt)

  • expected_state (Any)

Return type:

None

as_dict()[source]

Return a JSON-compatible replay manifest.

Return type:

dict[str, Any]

class ReplayMode(*values)[source]

Bases: StrEnum

State comparison guarantee expected from a backend.

class ReplayReport(mode, absolute_tolerance, relative_tolerance, steps)[source]

Bases: object

Whole-log replay verdict with explicit numeric tolerance.

Parameters:
  • mode (ReplayMode)

  • absolute_tolerance (float)

  • relative_tolerance (float)

  • steps (tuple[ReplayStepReceipt, ...])

property status: ReplayStatus

Distinguish successful evidence from mismatch and absent evidence.

property ran: bool

Whether at least one replay step was attempted.

property matched: bool

Whether every recorded transaction replayed under the selected guarantee.

as_dict()[source]

Return a JSON-compatible replay report.

Return type:

dict[str, Any]

class ReplayStatus(*values)[source]

Bases: StrEnum

Whole-log replay outcome; an empty log is explicitly not run.

class ReplayStepReceipt(index, commit_id, matched, mismatches, actual_receipt=None)[source]

Bases: object

Comparison result for one replayed transaction.

Parameters:
  • index (int)

  • commit_id (str)

  • matched (bool)

  • mismatches (tuple[str, ...])

  • actual_receipt (CommitReceipt | None)

as_dict()[source]

Return a JSON-compatible replay comparison.

Return type:

dict[str, Any]

class RecoveryDrillReceipt(checkpoint_update, final_update, model_bitwise_equal, optimizer_state_equal, rng_state_equal, uninterrupted_model_hash, resumed_model_hash)[source]

Bases: object

Checkpoint/restart comparison for model, optimizer, and RNG state.

Parameters:
  • checkpoint_update (int)

  • final_update (int)

  • model_bitwise_equal (bool)

  • optimizer_state_equal (bool)

  • rng_state_equal (bool)

  • uninterrupted_model_hash (str)

  • resumed_model_hash (str)

class RuntimeVersions(model_version, node_versions)[source]

Bases: object

Coordinator-owned global and per-node versions.

Parameters:
classmethod for_graph(graph, *, model_version=0)[source]

Create a zero-node-version vector for a compiled graph.

Parameters:
  • graph (UpdateGraph)

  • model_version (int)

Return type:

RuntimeVersions

as_dict()[source]

Return a detached JSON-compatible version vector.

Return type:

dict[str, Any]

class RuntimeCapability(name, status, boundary, evidence)[source]

Bases: object

One capability claim with its operative boundary and source evidence.

Parameters:
  • name (str)

  • status (RuntimeCapabilityStatus)

  • boundary (str)

  • evidence (str)

class RuntimeCapabilityStatus(*values)[source]

Bases: StrEnum

Maturity of one typed-runtime capability.

class ScaleRunReceipt(run_id, accelerator_count, host_count, real_distributed_transport, model_parameters, source_horizon_tokens, maximum_active_context_tokens, baseline_time_to_target_seconds, candidate_time_to_target_seconds, baseline_peak_memory_bytes, candidate_peak_memory_bytes, quality_target_achieved, worker_loss_recovered, replay_verified, provenance_complete, evidence_uri)[source]

Bases: object

Externally measured scale evidence consumed by the claim evaluator.

Parameters:
  • run_id (str)

  • accelerator_count (int)

  • host_count (int)

  • real_distributed_transport (bool)

  • model_parameters (int)

  • source_horizon_tokens (int)

  • maximum_active_context_tokens (int)

  • baseline_time_to_target_seconds (float | None)

  • candidate_time_to_target_seconds (float | None)

  • baseline_peak_memory_bytes (int | None)

  • candidate_peak_memory_bytes (int | None)

  • quality_target_achieved (bool)

  • worker_loss_recovered (bool)

  • replay_verified (bool)

  • provenance_complete (bool)

  • evidence_uri (str)

property resource_improvement_measured: bool

Whether candidate time-to-target or peak memory beats its paired baseline.

class NodeScheduleState(committed_count=0, skip_rounds=0, last_committed_round=None)[source]

Bases: object

Persistent fairness clock advanced only by terminal execution evidence.

Parameters:
  • committed_count (int)

  • skip_rounds (int)

  • last_committed_round (int | None)

property selected_count: int

Compatibility alias whose value now counts committed selections only.

property last_selected_round: int | None

Compatibility alias whose value now records the last committed round.

class NodeTerminalReceipt(round_index, node_id, status, evidence_id)[source]

Bases: object

Execution evidence binding a scheduled node to one terminal outcome.

Parameters:
  • round_index (int)

  • node_id (str)

  • status (NodeExecutionStatus)

  • evidence_id (str)

as_dict()[source]

Return a JSON-compatible terminal receipt.

Return type:

dict[str, Any]

class ScheduleReceipt(round_index, model_version, target_objective, selected_nodes, ranked_nodes, eligible_nodes, forced_starvation, bootstrap_nodes, lower_confidence_bounds, effective_costs, priorities, invalidation_costs, skipped, rejected_evidence, budget, spent)[source]

Bases: object

Complete, replayable record of one deterministic scheduling decision.

Parameters:
property budget_overrun: float

Amount by which a fairness-forced decision exceeds its soft budget.

as_dict()[source]

Return a JSON-compatible receipt.

Return type:

dict[str, Any]

class ScheduleCompletionReceipt(terminal_id, round_index, outcomes, committed_nodes, unsuccessful_nodes, states_after)[source]

Bases: object

Fairness-state transition justified by complete terminal node evidence.

Parameters:
  • terminal_id (str)

  • round_index (int)

  • outcomes (tuple[NodeTerminalReceipt, ...])

  • committed_nodes (tuple[str, ...])

  • unsuccessful_nodes (tuple[str, ...])

  • states_after (dict[str, NodeScheduleState])

as_dict()[source]

Return a JSON-compatible completion receipt.

Return type:

dict[str, Any]

class SchedulerConfig(budget_fraction=0.5, confidence_z=1.645, lambda_network=0.0, lambda_memory=0.0, lambda_stale=1.0, lambda_invalidation=0.1, minimum_gain_lcb=0.0, max_skip_rounds=2, bootstrap_unmeasured=True)[source]

Bases: object

Resource weights and fairness policy for typed greedy scheduling.

Parameters:
  • budget_fraction (float)

  • confidence_z (float)

  • lambda_network (float)

  • lambda_memory (float)

  • lambda_stale (float)

  • lambda_invalidation (float)

  • minimum_gain_lcb (float)

  • max_skip_rounds (int)

  • bootstrap_unmeasured (bool)

class StateSemantics(*values)[source]

Bases: StrEnum

Kinds of mutable or replay-relevant state touched by an update.

class StalenessAction(*values)[source]

Bases: StrEnum

Coordinator action for a locally computed proposal.

class StalenessPolicy(max_model_lag=0, max_node_lag=0, shrink_decay=0.5)[source]

Bases: object

Hard lag limits and conservative stale-delta decay.

Parameters:
  • max_model_lag (int)

  • max_node_lag (int)

  • shrink_decay (float)

class StalenessReceipt(proposal_id, action, reason, model_lag, node_lag, scale, correction_fingerprint, correction_semantics, source_payload_hash, target_model_version, target_dependency_versions)[source]

Bases: object

Measured lag, consistency contract, and admission decision.

Parameters:
  • proposal_id (str)

  • action (StalenessAction)

  • reason (str)

  • model_lag (int)

  • node_lag (int)

  • scale (float)

  • correction_fingerprint (str | None)

  • correction_semantics (CorrectionSemantics | None)

  • source_payload_hash (str)

  • target_model_version (int)

  • target_dependency_versions (tuple[tuple[str, int], ...])

property accepted: bool

Whether the proposal may proceed to versioned commit preflight.

as_dict()[source]

Return a JSON-compatible staleness receipt.

Return type:

dict[str, Any]

class StructuredPlacementPlan(primary_island, placements, graph_fingerprint, topology_fingerprint)[source]

Bases: object

Typed placement over one calibrated cluster topology.

Parameters:
  • primary_island (str)

  • placements (tuple[NodePlacement, ...])

  • graph_fingerprint (str)

  • topology_fingerprint (str)

placement(node_id)[source]

Return placement metadata for one node.

Parameters:

node_id (str)

Return type:

NodePlacement

as_dict()[source]

Return a JSON-compatible plan.

Return type:

dict[str, Any]

class StructuredShard(shard_id, node_id, island, device_id, axis, start, stop, reduction, exact, required_memory_bytes)[source]

Bases: object

One contiguous typed model-axis cut.

Parameters:
as_dict()[source]

Return a JSON-compatible shard placement.

Return type:

dict[str, Any]

class StructuredEstimationReceipt(placement, observations, num_workers, worker_device_ids, execution_backend, parallel_node_ids, parallel_statistics_hash, reference_statistics_hash, parallel_model_hash, reference_model_hash, exact_parity, work, reference_seconds=None)[source]

Bases: object

Placement, work, sufficient-statistic, and model parity for one M-step.

Parameters:
  • placement (StructuredPlacementPlan)

  • observations (float)

  • num_workers (int)

  • worker_device_ids (tuple[str, ...])

  • execution_backend (str)

  • parallel_node_ids (tuple[str, ...])

  • parallel_statistics_hash (str)

  • reference_statistics_hash (str | None)

  • parallel_model_hash (str)

  • reference_model_hash (str | None)

  • exact_parity (bool | None)

  • work (WorkMeasurement)

  • reference_seconds (float | None)

as_dict()[source]

Return a JSON-compatible structured-execution receipt.

Return type:

dict[str, Any]

class StructuredEstimationResult(model, receipt)[source]

Bases: object

Estimated model and receipt; runtime model excluded from serialization.

Parameters:
  • model (ProbabilityDistribution)

  • receipt (StructuredEstimationReceipt)

class TargetDirection(*values)[source]

Bases: StrEnum

Whether reaching a target requires increasing or decreasing a metric.

class TimeToTargetTrace(benchmark_id, strategy, target, points=())[source]

Bases: object

Monotone cumulative work trace for one strategy and one target.

Not a dataclass any more (MXR-080-1905): points was a public list, so the chronology and cumulative-counter contract that record() enforces could be walked straight past – trace.points.append(BenchmarkPoint(0, 0.95, 0.0)) after a step-1 point produced a trace whose steps ran 1, 0 and whose elapsed times ran 1.0, 0.0, and achieved then reported True from that out-of-order point. points is a read-only view now and record() is the only way in. The constructor signature is unchanged.

Parameters:
  • benchmark_id (str)

  • strategy (str)

  • target (ObjectiveTarget)

  • points (Sequence[BenchmarkPoint])

property points: tuple[BenchmarkPoint, ...]

The recorded observations, oldest first, as a detached tuple.

record(point)[source]

Append a cumulative point after checking chronology and counters.

Parameters:

point (BenchmarkPoint)

Return type:

None

property first_target_point: BenchmarkPoint | None

First observed point that reaches the declared quality target.

property achieved: bool

Whether this trace reaches its declared target.

as_dict()[source]

Return the complete trace without collapsing time and operations.

Return type:

dict[str, Any]

class TopologyDevice(device_id, host, island, provider, region, spec, storage_region=None)[source]

Bases: object

A compute device with failure, network, provider, and storage locality.

Parameters:
  • device_id (str)

  • host (str)

  • island (str)

  • provider (str)

  • region (str)

  • spec (DeviceSpec)

  • storage_region (str | None)

as_dict()[source]

Return a JSON-compatible device declaration.

Return type:

dict[str, Any]

class TransferEstimate(source, target, nbytes, seconds, path)[source]

Bases: object

Best measured route and transfer time between two devices.

Parameters:
class TransferSample(source, target, bytes_transferred, elapsed_seconds)[source]

Bases: object

One observed point-to-point transfer.

Parameters:
  • source (str)

  • target (str)

  • bytes_transferred (int)

  • elapsed_seconds (float)

class TypedMixtureRoundReceipt(round_index, schedule, schedule_completion, coordinator_nodes, objective_before, candidate_objective, committed_objective, accepted, realized_gain, gain_attribution, active_components, invalidation, work)[source]

Bases: object

Selection, objective gate, invalidation, and work for one local round.

Parameters:
  • round_index (int)

  • schedule (ScheduleReceipt)

  • schedule_completion (ScheduleCompletionReceipt)

  • coordinator_nodes (tuple[str, ...])

  • objective_before (float)

  • candidate_objective (float)

  • committed_objective (float)

  • accepted (bool)

  • realized_gain (float)

  • gain_attribution (str)

  • active_components (tuple[int, ...])

  • invalidation (InvalidationReceipt | None)

  • work (WorkMeasurement)

as_dict()[source]

Return a JSON-compatible execution receipt.

Return type:

dict[str, Any]

class TypedMixtureRun(model, graph, rounds)[source]

Bases: object

Final model and immutable evidence from a typed local mixture fit.

Parameters:
  • model (MixtureDistribution)

  • graph (UpdateGraph)

  • rounds (tuple[TypedMixtureRoundReceipt, ...])

property objective_trace: tuple[float, ...]

Committed observed-data objective after every round.

property total_model_evaluations: int

Total real component log-density calls across the fit.

as_dict()[source]

Return run metadata and receipts without serializing the model graph objects.

Return type:

dict[str, Any]

class TransactionParticipant(name, semantics, snapshot_fn, restore_fn, fingerprint_fn, artifacts=frozenset({}))[source]

Bases: object

Snapshot/restore adapter for one mutable state domain.

Parameters:
snapshot()[source]

Capture state before applying a proposal.

Return type:

Any

restore(snapshot)[source]

Restore a previously captured snapshot.

Parameters:

snapshot (Any)

Return type:

None

fingerprint()[source]

Return a deterministic current-state fingerprint.

Return type:

str

class TransactionalCoordinator(graph, apply_proposal, canary, *, run_id, model_id, participants=(), versions=None, objective_tolerance=1.0e-9, enforce_monotone_objective=True)[source]

Bases: object

Serialize proposal commits through preflight, snapshot, canary, and commit.

Parameters:
  • graph (UpdateGraph)

  • apply_proposal (ApplyProposalFn)

  • canary (CanaryFn)

  • run_id (str)

  • model_id (str)

  • participants (Iterable[TransactionParticipant])

  • versions (RuntimeVersions | None)

  • objective_tolerance (float)

  • enforce_monotone_objective (bool)

property receipts: tuple[CommitReceipt, ...]

Every terminal commit receipt this coordinator produced, oldest first.

A detached tuple: the receipts themselves are frozen and sealed, and the sequence they form is the coordinator’s own record, not a caller-editable list (MXR-080-1905).

property proposal_receipts: tuple[dict[str, Any], ...]

Serialized proposals seen by this coordinator, in arrival order.

Each row is a fresh as_dict() payload built at commit time, so the tuple shares no structure a caller can reach (MXR-080-1905).

property poisoned: bool

Whether an unverified rollback has disabled further commits.

Read-only: this was a plain attribute, so coordinator.poisoned = False un-poisoned a coordinator whose rollback could not be verified and let it accept commits on top of state nothing had confirmed was restored (MXR-080-1905). Only commit() sets it, from the rollback verification itself.

commit(batch, *, commit_id=None)[source]

Attempt one atomic commit and always return a terminal receipt.

Parameters:
  • batch (ProposalBatch | ProposalPacket)

  • commit_id (str | None)

Return type:

CommitReceipt

ledger_fingerprint()[source]

Fingerprint receipt metadata for deterministic replay comparisons.

Return type:

str

class UpdateContract(objective_kind, update_kind, merge_law, state_semantics=<factory>, consistency=ConsistencyRequirement.STRICT_SYNCHRONOUS, curvature_kind=CurvatureKind.UNAVAILABLE, decomposition_axes=(), reads=<factory>, writes=<factory>, outer_objective_compatible=True, exact=True, convergence_certificate=ConvergenceCertificate.UNKNOWN, compute_band=ComputeBand.FLOAT64, declared_by='compiler_default', evidence_kind=ContractEvidenceKind.UNVERIFIED, evidence_id=None, notes=())[source]

Bases: object

Complete semantic declaration for one independently schedulable node.

Parameters:
  • objective_kind (ObjectiveKind)

  • update_kind (UpdateKind)

  • merge_law (MergeLaw)

  • state_semantics (frozenset[StateSemantics])

  • consistency (ConsistencyRequirement)

  • curvature_kind (CurvatureKind)

  • decomposition_axes (tuple[str, ...])

  • reads (frozenset[ArtifactKind])

  • writes (frozenset[ArtifactKind])

  • outer_objective_compatible (bool)

  • exact (bool)

  • convergence_certificate (ConvergenceCertificate)

  • compute_band (ComputeBand)

  • declared_by (str)

  • evidence_kind (ContractEvidenceKind)

  • evidence_id (str | None)

  • notes (tuple[str, ...])

property is_mutable: bool

Whether committing/rejecting this update requires state management.

property shard_mergeable: bool

Whether independent shard payloads have a declared merge operation.

as_dict()[source]

Return a stable JSON-compatible representation.

Return type:

dict[str, Any]

class UpdateCadence(every_steps=None, every_tokens=None, every_observations=None, max_staleness_steps=None)[source]

Bases: object

Any-trigger cadence with an optional hard staleness bound.

Parameters:
  • every_steps (int | None)

  • every_tokens (int | None)

  • every_observations (float | None)

  • max_staleness_steps (int | None)

class UpdateGraph(nodes, edges, root_node, compiler_version=1)[source]

Bases: object

Directed acyclic graph of typed updates and invalidation dependencies.

Edges point from an updated source to a dependent computation. Consequently, invalidated_by(node) walks forward from that node toward ancestors and any other consumers of shared state.

Parameters:
  • nodes (tuple[UpdateNode, ...])

  • edges (tuple[DependencyEdge, ...])

  • root_node (str)

  • compiler_version (int)

node(node_id)[source]

Return a node by id.

Parameters:

node_id (str)

Return type:

UpdateNode

node_at(path)[source]

Return the first node compiled at path.

Parameters:

path (str)

Return type:

UpdateNode

dependents(node_id)[source]

Return direct computations invalidated by an update to node_id.

Parameters:

node_id (str)

Return type:

tuple[str, …]

invalidated_by(node_id, *, include_self=True)[source]

Return the transitive invalidation closure in dependency order.

Parameters:
  • node_id (str)

  • include_self (bool)

Return type:

tuple[str, …]

topological_order()[source]

Return child-before-dependent order, raising on a dependency cycle.

Return type:

tuple[str, …]

as_dict()[source]

Return a JSON-compatible graph without runtime object references.

Return type:

dict[str, Any]

property compute_band

float32 only when every node’s subtree qualifies.

Type:

Tree-level precision eligibility

property convergence_certificate

the weakest node certificate (guarantees compose by minimum).

Type:

Tree-level guarantee

explain()[source]

Render a compact human-readable execution-plan explanation.

Return type:

str

classmethod from_parts(nodes, edges, *, root_node)[source]

Build and validate an immutable graph from iterables.

Parameters:
Return type:

UpdateGraph

exception UpdateGraphError[source]

Bases: ValueError

Raised when a compiled update graph violates structural invariants.

exception UpdateGraphValidationError(issues)[source]

Bases: ValueError

Raised when strict validation finds one or more errors.

Parameters:

issues (tuple[ValidationIssue, ...])

Return type:

None

class UpdateKind(*values)[source]

Bases: StrEnum

Algorithmic family used to propose a node update.

class UpdateNode(node_id, path, model_type, estimator_type, contract, cost, parameter_count, model=None, estimator=None)[source]

Bases: object

One independently inspectable and potentially schedulable model node.

Parameters:
  • node_id (str)

  • path (str)

  • model_type (str)

  • estimator_type (str | None)

  • contract (UpdateContract)

  • cost (CostEstimate)

  • parameter_count (int)

  • model (Any)

  • estimator (Any)

as_dict()[source]

Return metadata without runtime model or estimator objects.

Return type:

dict[str, Any]

class ValidationIssue(severity, code, node_id, message)[source]

Bases: object

One actionable contract or planning defect.

Parameters:
  • severity (IssueSeverity)

  • code (str)

  • node_id (str)

  • message (str)

class VersionedArtifactCache(graph)[source]

Bases: object

Thread-safe local cache with graph-derived transitive invalidation.

A node generation advances even when no entry currently exists. A late worker can therefore compare its captured generation to the current one and detect that its result was computed before an intervening update.

Parameters:

graph (UpdateGraph)

generation(node_id)[source]

Return the current generation for a node.

Parameters:

node_id (str)

Return type:

int

put(node_id, artifact, value)[source]

Store a value at the node’s current generation.

Parameters:
  • node_id (str)

  • artifact (ArtifactKind)

  • value (Any)

Return type:

CachedArtifact

get(node_id, artifact)[source]

Return a current value or raise KeyError for absent/stale data.

Parameters:
  • node_id (str)

  • artifact (ArtifactKind)

Return type:

Any

contains(node_id, artifact)[source]

Whether a current cache entry exists.

Parameters:
  • node_id (str)

  • artifact (ArtifactKind)

Return type:

bool

invalidate(source_node, written_artifact=ArtifactKind.PARAMETERS)[source]

Invalidate one source and every transitively dependent node.

Parameters:
  • source_node (str)

  • written_artifact (ArtifactKind)

Return type:

InvalidationReceipt

invalidate_many(source_nodes, written_artifact=ArtifactKind.PARAMETERS)[source]

Atomically invalidate the union of several dependency closures.

Parameters:
Return type:

InvalidationReceipt

clear()[source]

Invalidate all nodes and remove all entries.

Return type:

None

as_dict()[source]

Return cache metadata without serializing runtime values.

Return type:

dict[str, Any]

class VerificationUpdate(node_id, status, provenance=(), confidence=None)[source]

Bases: object

Proposed evidence-status transition for an existing graph node.

Parameters:
  • node_id (str)

  • status (EvidenceStatus)

  • provenance (tuple[Provenance, ...])

  • confidence (float | None)

class ValueOfInformationScheduler(budget=None, config=None)[source]

Bases: object

Stateful context-action scheduler debited by actual execution receipts.

Parameters:
  • budget (ContextBudget | None)

  • config (ContextSchedulerConfig | None)

stop_decision(graph, reason)[source]

Create an explicit zero-work scheduling decision for termination.

Parameters:
  • graph (ContextGraph)

  • reason (str)

Return type:

ContextScheduleDecision

choose(actions, graph)[source]

Choose the highest positive net VOI action or stop explicitly.

Parameters:
  • actions (tuple[ContextAction, ...])

  • graph (ContextGraph)

Return type:

ContextScheduleDecision

record(receipt)[source]

Debit actual work once; rejected/rolled-back work still costs resources.

Parameters:

receipt (ContextActionReceipt)

Return type:

None

as_dict()[source]

Return cumulative actual context-construction spend.

Return type:

dict[str, Any]

class WorkMeasurement(node_type, update_kind, backend, wall_time_seconds, compute_units=0.0, communication_bytes=0, peak_memory_bytes=0, observations=0.0, tokens=0, model_evaluations=0, operation_count=0, bytes_read=0, bytes_written=0, collective_bytes=0, staleness_steps=0, run_id=None, extra=<factory>, work_counter_semantics=CounterSemantics.INCREMENTAL, peak_memory_semantics=CounterSemantics.HIGH_WATER_MARK, staleness_semantics=CounterSemantics.HIGH_WATER_MARK)[source]

Bases: object

One measured execution of a typed node operation.

Parameters:
  • node_type (str)

  • update_kind (UpdateKind)

  • backend (str)

  • wall_time_seconds (float)

  • compute_units (float)

  • communication_bytes (int)

  • peak_memory_bytes (int)

  • observations (float)

  • tokens (int)

  • model_evaluations (int)

  • operation_count (int)

  • bytes_read (int)

  • bytes_written (int)

  • collective_bytes (int)

  • staleness_steps (int)

  • run_id (str | None)

  • extra (dict[str, Any])

  • work_counter_semantics (CounterSemantics)

  • peak_memory_semantics (CounterSemantics)

  • staleness_semantics (CounterSemantics)

as_dict()[source]

Return a JSON-compatible receipt.

Return type:

dict[str, Any]

assess_frontier_claims(pilot, scale_run=None)[source]

Apply the work plan’s conservative claim policy to local and scale receipts.

Parameters:
  • pilot (GraphMemoryPilotReceipt)

  • scale_run (ScaleRunReceipt | None)

Return type:

FrontierClaimAssessment

assess_staleness(proposal, contract, current, policy, *, correction=None)[source]

Apply exact/strict/bounded/corrected semantics before payload mutation.

Parameters:
  • proposal (ProposalPacket)

  • contract (UpdateContract)

  • current (RuntimeVersions)

  • policy (StalenessPolicy)

  • correction (CorrectionResult | None)

Return type:

StalenessReceipt

apply_optimizer_evidence(plan, evidence, *, target_name, model_version, minimum_time_improvement=0.02)[source]

Fall back when a routed family does not beat measured AdamW time-to-target.

Parameters:
  • plan (OptimizerPlan)

  • evidence (tuple[OptimizerEvidence, ...])

  • target_name (str)

  • model_version (int)

  • minimum_time_improvement (float)

Return type:

OptimizerPlan

compile_update_graph(model, estimator=None, *, nobs=1.0, backend='local', registry=None, bindings=None, contract_overrides=None, measurements=None)[source]

Compile a model into an immutable typed update and invalidation graph.

Compilation reads inert instance/class dictionaries only. It never calls factories, descriptors, capability predicates, contract hooks, parameters(), scoring/sampling methods, estimators, or accumulators. Child estimators are aligned from the supplied estimator’s stored child objects where the binding is unambiguous; otherwise the child contract is UNKNOWN/frozen unless an explicit path binding is supplied.

Parameters:
  • model (ProbabilityDistribution)

  • estimator (ParameterEstimator | None)

  • nobs (float)

  • backend (str)

  • registry (ContractRegistry | None)

  • bindings (Mapping[str, ParameterEstimator] | None)

  • contract_overrides (Mapping[str, UpdateContract] | None)

  • measurements (MeasurementCatalog | None)

Return type:

UpdateGraph

class ExecutionPlan(precision, monotone, notes=(), adapter_notes=(), blockers=(), graph=None)[source]

Bases: object

Contract-derived execution knobs plus the receipts that justify them.

Parameters:
  • precision (str | None)

  • monotone (bool | None)

  • notes (tuple[str, ...])

  • adapter_notes (tuple[str, ...])

  • blockers (tuple[str, ...])

  • graph (UpdateGraph | None)

property optimize_kwargs: dict[str, Any]

Keyword arguments for mixle.inference.optimize; raises if the plan carries blockers.

plan_execution(model, estimator, *, nobs)[source]

Compile model/estimator and derive optimize-ready execution knobs from the contracts.

Raises whatever compile_update_graph() raises for an uncompilable pair – unsupported semantics fail here, before any fitting.

Parameters:
Return type:

ExecutionPlan

plan_distributed_updates(graph, plan, *, numerics_evidence=None)[source]

Produce an auditable collective plan for every compiled update node.

The result deliberately distinguishes additive sufficient statistics from gradients. It also emits model-axis transfers separately, so a scheduler cannot mistake an EP token exchange or PP activation send for gradient synchronization.

Parameters:
  • graph (UpdateGraph)

  • plan (ParallelPlan)

  • numerics_evidence (Mapping[str, CollectiveNumericsEvidence] | None)

Return type:

tuple[DistributedUpdate, …]

calibrate_links(samples)[source]

Fit time = latency + bytes / bandwidth independently per direction.

Parameters:

samples (tuple[TransferSample, ...])

Return type:

tuple[LinkProfile, …]

build_routed_torch_optimizer(module, plan, *, lr=1.0e-3, betas=(0.9, 0.999), eps=1.0e-8, weight_decay=0.0, precondition_frequency=10, muon_backend='newton_schulz', muon_steps=7, fisher_provider=None, projection_provider=None)[source]

Build a real torch.optim.Optimizer executing a typed geometry plan.

Muon routes use a fixed-step Newton-Schulz polar approximation by default; muon_backend="svd" retains the exact polar factor as an audit reference. Kronecker routes maintain row/column second-moment factors and refresh inverse fourth-roots at precondition_frequency.

Parameters:
Return type:

Any

bounded_context_attention(query, candidates, graph, config, *, source_horizon_tokens=None)[source]

Attend to recent/retrieved nodes under hard node, token, and vector-work caps.

Parameters:
  • query (Any)

  • candidates (tuple[AttentionCandidate, ...])

  • graph (ContextGraph)

  • config (ContextAttentionConfig)

  • source_horizon_tokens (int | None)

Return type:

ContextAttentionResult

infer_update_contract(model, estimator)[source]

Return a static/audited contract or an explicit UNKNOWN contract.

No factories, descriptors, methods, capability predicates, scoring functions, or estimator hooks are called. Names and method presence are not semantic evidence.

Parameters:
  • model (Any)

  • estimator (Any | None)

Return type:

UpdateContract

describe_parameters(module)[source]

Describe a torch-like module without importing torch.

Parameters:

module (Any)

Return type:

tuple[ParameterDescriptor, …]

kronecker_precondition(gradient, row_factor, column_factor, *, damping=1.0e-6)[source]

Apply inverse fourth-root Kronecker factors to a matrix gradient.

Parameters:
Return type:

ndarray

merge_same_node_proposals(proposals, *, merged_proposal_id, merge_law, payload_merger=None)[source]

Merge shard proposals for one node under an explicitly declared law.

Parameters:
Return type:

ProposalPacket

materialize_context(graph, relevance, policy, tokenizer, *, source_horizon_tokens=None, required_node_ids=(), context_actions=0, retrieval_actions=0, generation_actions=0, verification_actions=0, tool_calls=0, latency_seconds=0.0, monetary_cost=0.0, stopped_reason=None)[source]

Greedily pack relevance-per-token evidence bundles under hard bounds.

Parameters:
  • graph (ContextGraph)

  • relevance (dict[str, float])

  • policy (MaterializationPolicy)

  • tokenizer (ContextTokenizer)

  • source_horizon_tokens (int | None)

  • required_node_ids (tuple[str, ...])

  • context_actions (int)

  • retrieval_actions (int)

  • generation_actions (int)

  • verification_actions (int)

  • tool_calls (int)

  • latency_seconds (float)

  • monetary_cost (float)

  • stopped_reason (str | None)

Return type:

MaterializedContext

natural_gradient_direction(gradient, fisher, *, damping=1.0e-6)[source]

Solve a damped Fisher system for a natural-gradient direction.

Parameters:
Return type:

ndarray

orthogonalized_matrix_direction(gradient)[source]

Exact polar factor used as a reference for Muon-style orthogonalization.

Parameters:

gradient (Any)

Return type:

ndarray

payload_fingerprint(value)[source]

Return a deterministic SHA-256 fingerprint without pickle or repr.

Parameters:

value (Any)

Return type:

str

partition_context_graph(graph, *, maximum_tokens, maximum_nodes)[source]

Greedily partition connected/source-local regions under hard bounds.

Parameters:
  • graph (ContextGraph)

  • maximum_tokens (int)

  • maximum_nodes (int)

Return type:

GraphPartitionPlan

proposal_conflicts(graph, batch)[source]

Return same-state and dependency-order conflicts in deterministic order.

Parameters:
  • graph (UpdateGraph)

  • batch (ProposalBatch)

Return type:

tuple[ProposalConflict, …]

plan_structured_placement(graph, topology, *, n_data=None)[source]

Place exact structured cuts inside one island and proposals across islands.

Parameters:
  • graph (UpdateGraph)

  • topology (ClusterTopology)

  • n_data (int | None)

Return type:

StructuredPlacementPlan

replay_log(log, coordinator, *, mode=ReplayMode.BITWISE, state_probe=None, absolute_tolerance=0.0, relative_tolerance=0.0)[source]

Replay every batch and compare semantic receipts plus resulting state.

Parameters:
  • log (ReplayLog)

  • coordinator (TransactionalCoordinator)

  • mode (ReplayMode)

  • state_probe (Callable[[], Any] | None)

  • absolute_tolerance (float)

  • relative_tolerance (float)

Return type:

ReplayReport

validate_update_graph(graph, *, strict=False)[source]

Return semantic issues and optionally raise when any are errors.

Parameters:
  • graph (UpdateGraph)

  • strict (bool)

Return type:

tuple[ValidationIssue, …]

weakest_band(bands)[source]

FLOAT32_ELIGIBLE only when every node is eligible; FLOAT64 otherwise (or when empty).

Parameters:

bands (Iterable[ComputeBand])

Return type:

ComputeBand

weakest_certificate(certificates)[source]

The minimum certificate over an iterable (the tree-level guarantee); UNKNOWN when empty.

Parameters:

certificates (Iterable[ConvergenceCertificate])

Return type:

ConvergenceCertificate

run_typed_mixture_em(enc_data, estimator, initial_model, *, max_its=10, delta=1.0e-9, stall_patience=3, accept_tolerance=1.0e-9, scheduler=None, gain_provider=None)[source]

Run objective-gated component EM selected by the typed scheduler.

The root mixture-weight update is an explicit always-on coordinator. Only component nodes enter the scheduler’s budget. Internal gain evidence comes from committed global-objective improvement and is therefore labelled joint_with_coordinator rather than misrepresented as an isolated causal contribution. A caller with better per-block probes may supply gain_provider; objective compatibility is still enforced by the scheduler.

Budgeting changes convergence dynamics, not only speed: leaving a component’s parameters fixed for one or more rounds makes this a different asynchronous coordinate-ascent process than full-tree EM, and on a non-convex mixture likelihood the two can settle at different fixed points – occasionally a meaningfully worse one – even though each trajectory is individually monotone in its own committed objective. This is not something a gentler scheduler fixes: the gap shrinks but does not vanish at every budget short of updating every component every round (see mixle/tests/typed_local_mixture_test.py’s LocalOptimumDivergenceRiskTestCase). A caller that needs the same fixed point full EM would reach should pass a scheduler with budget_fraction=1.0, or use mixle.inference.freeze_rollup instead, which reaches an identical fixed point by construction – it only skips a component once its own convergence has already been demonstrated, rather than rationing updates among components before any evidence exists.

Parameters:
  • enc_data (Any)

  • estimator (MixtureEstimator)

  • initial_model (MixtureDistribution)

  • max_its (int)

  • delta (float | None)

  • stall_patience (int)

  • accept_tolerance (float)

  • scheduler (GainPerCostScheduler | None)

  • gain_provider (Callable[[int, MixtureDistribution, UpdateGraph, tuple[TypedMixtureRoundReceipt, ...]], Mapping[str, GainEvidence]] | None)

Return type:

TypedMixtureRun

run_structured_estimation_step(encoded_data, estimator, model, topology, *, weights=None, num_workers=None, verify_reference=True)[source]

Execute one exact typed model-axis E/M step and optionally verify serial parity.

Parameters:
  • encoded_data (Any)

  • estimator (ParameterEstimator)

  • model (ProbabilityDistribution)

  • topology (ClusterTopology)

  • weights (ndarray | None)

  • num_workers (int | None)

  • verify_reference (bool)

Return type:

StructuredEstimationResult

run_graph_memory_pilot(*, seed=17, source_nodes=256, train_examples=192, test_examples=96, updates=80, microbatch_size=32, accumulation_steps=2, target_accuracy=0.9)[source]

Run a fixed-budget graph-context MoE ablation and deterministic restart drill.

The pilot seeds the PROCESS-GLOBAL torch RNG – it has to, because the restart drill compares bitwise reproducibility and the models it trains draw from the default generator. What it did not do was put it back (MXR-080-1905): a caller who seeded their own process, ran the pilot and then drew got different numbers than if they had not run it, and nothing said so. The entry state is captured and restored here, including on failure, so running the pilot is not itself an observable event in the caller’s stream. The pilot’s internal determinism is unchanged: it still seeds from seed on the way in.

NOT restored: NumPy’s global RNG, because the pilot never touches it – it builds its own np.random.default_rng(seed) – and CUDA generator state, because the pilot runs on CPU.

Parameters:
  • seed (int)

  • source_nodes (int)

  • train_examples (int)

  • test_examples (int)

  • updates (int)

  • microbatch_size (int)

  • accumulation_steps (int)

  • target_accuracy (float)

Return type:

GraphMemoryPilotReceipt

route_optimizer_geometry(parameters, contract, config=None)[source]

Build a conservative per-parameter optimizer plan.

Parameters:
  • parameters (tuple[ParameterDescriptor, ...])

  • contract (UpdateContract)

  • config (GeometryRouterConfig | None)

Return type:

OptimizerPlan

runtime_capabilities()[source]

Return the immutable, machine-readable typed-runtime capability inventory.

Return type:

tuple[RuntimeCapability, …]

shrink_proposal(proposal, receipt, *, proposal_id, correction=None)[source]

Create an identity-bound proposal after an admitted stale transformation.

Parameters:
  • proposal (ProposalPacket)

  • receipt (StalenessReceipt)

  • proposal_id (str)

  • correction (CorrectionResult | None)

Return type:

ProposalPacket

Submodules