tg_model.execution

Execution subsystem: frozen topology, dependency graph, validation, and evaluation.

Typical pipeline: compile element types (SomeSystem.compile()), build a ConfiguredModel with instantiate(), then call evaluate() (lazy compile + optional validation per call) or explicitly compile_graph(), optionally validate_graph(), then run Evaluator with a fresh RunContext. Per-run values live in RunContext; the configured model may cache a compiled graph on the instance.

Notes

Behavioral APIs (dispatch_event(), etc.) mutate RunContext discrete state and optional BehaviorTrace records; they do not change ConfiguredModel topology.

class tg_model.execution.AllocationBinding(*, stable_id, requirement, target, input_bindings=None)[source]

Bases: object

Resolved allocate edge from a requirement to a target element.

Parameters:
  • input_bindings (dict[str, ValueSlot], optional) – Maps tg_model.model.definition_context.ModelDefinitionContext.requirement_input() names to concrete value slots on the allocated subtree.

  • stable_id (str)

  • requirement (ElementInstance)

  • target (ElementInstance)

stable_id
requirement
target
input_bindings
class tg_model.execution.BehaviorStep(step_index, part_path, event_name, from_state, to_state, effect_name)[source]

Bases: object

One state-machine transition recorded in BehaviorTrace.

Parameters:
  • step_index (int)

  • part_path (str)

  • event_name (str)

  • from_state (str)

  • to_state (str)

  • effect_name (str | None)

step_index: int
part_path: str
event_name: str
from_state: str
to_state: str
effect_name: str | None
class tg_model.execution.BehaviorTrace(steps=<factory>, item_flows=<factory>, decision_steps=<factory>, fork_join_steps=<factory>, merge_steps=<factory>, sequence_steps=<factory>)[source]

Bases: object

Mutable collector for behavioral steps (multiple parallel lists).

Notes

Paths are PartInstance.path_string values and declared names, not slot stable ids. Global ordering uses step_index across lists (see behavior_trace_to_records()).

Parameters:
steps: list[BehaviorStep]
item_flows: list[ItemFlowStep]
decision_steps: list[DecisionTraceStep]
fork_join_steps: list[ForkJoinTraceStep]
merge_steps: list[MergeTraceStep]
sequence_steps: list[SequenceTraceStep]
class tg_model.execution.ConfiguredModel(root, *, path_registry, id_registry, connections, allocations, references, requirement_value_slots=None)[source]

Bases: object

Immutable configured topology for one root type instance.

Notes

Evaluations use fresh RunContext objects per evaluate() call; the part tree and registries do not change. A successful compile may be cached on this instance (_compiled_graph) for reuse.

Thread safety: Do not call evaluate() or compile_graph() concurrently on the same instance from multiple threads; the cache is not locked.

Copy / pickle: Caching a compiled graph on the instance means copying or unpickling a configured model without clearing _compiled_graph is unsupported; treat cached graphs as invalid across process or deep-copy boundaries unless you add an explicit clear or rebuild.

Attribute access delegates to the root part for ergonomics.

Parameters:
handle(path)[source]

Look up an instance or value slot by dotted path string.

Parameters:

path (str) – Instance path such as Rocket.tank.mass_kg.

Returns:

Registered topology object.

Return type:

ElementInstance or ValueSlot

Raises:

KeyError – If path is not in path_registry.

evaluate(inputs=None, *, run_context=None, validate=True)[source]

Run one synchronous evaluation over the compiled dependency graph.

Compiles the graph on first use (same cache as compile_graph()), optionally runs validate_graph(), then delegates to Evaluator.

Parameters:
  • inputs (dict, optional) – Per-run values keyed by ValueSlot handles belonging to this model, or by str giving the stable_id of such a slot only (not arbitrary element or part ids). Values are typically unitflow.Quantity instances.

  • run_context (RunContext, optional) – Fresh context per call by default. Supply only for advanced testing or tooling.

  • validate (bool, default True) – When True, runs validate_graph() before each evaluation (static checks). For tight loops, sweeps, or optimizers, pass validate=False after you have validated once out-of-band, to avoid repeating that work every run. On validation failure, raises GraphValidationError.

Returns:

Same aggregate type as tg_model.execution.evaluator.Evaluator.evaluate(). Missing inputs, failed constraints, and other runtime issues appear in failures / constraint_results — not as exceptions from this method.

Return type:

RunResult

Raises:
  • GraphCompilationError – If graph compilation fails (from compile_graph()).

  • GraphValidationError – If validate is True and static validation fails (subclass of Exception).

  • KeyError – If a string key is not present in this model’s id registry.

  • TypeError – Propagated from the evaluator when an async external is used in sync mode.

  • ValueError – If an input key is a ValueSlot not registered on this model, or a string id that does not refer to a ValueSlot.

See also

tg_model.execution.graph_compiler.compile_graph, tg_model.execution.evaluator.Evaluator

class tg_model.execution.ConnectionBinding(*, stable_id, source, target, carrying=None)[source]

Bases: object

Resolved connection between two PortInstance objects.

Parameters:
  • stable_id (str) – Unique edge id (derived at instantiate time).

  • source (PortInstance) – Endpoint ports.

  • target (PortInstance) – Endpoint ports.

  • carrying (str, optional) – Item kind discriminator for emit_item().

stable_id
source
target
carrying
class tg_model.execution.ConstraintResult(name, passed, evidence='', *, requirement_path=None, allocation_target_path=None)[source]

Bases: object

Outcome of one constraint or requirement-acceptance check.

Parameters:
  • name (str)

  • passed (bool)

  • evidence (str)

  • requirement_path (str | None)

  • allocation_target_path (str | None)

name
passed
evidence
requirement_path
allocation_target_path
class tg_model.execution.DecisionDispatchOutcome(*values)[source]

Bases: StrEnum

Outcome of dispatch_decision() (action ran vs not).

ACTION_RAN = 'action_ran'

A branch or default_action ran (name in DecisionDispatchResult.chosen_action).

NO_ACTION = 'no_action'

No branch matched and there was no default_action.

class tg_model.execution.DecisionDispatchResult(outcome, chosen_action=None, merge_ran=False)[source]

Bases: object

Structured result of dispatch_decision().

Notes

bool(result) is true when chosen_action is not None.

Parameters:
outcome: DecisionDispatchOutcome
chosen_action: str | None = None
merge_ran: bool = False

True when a paired merge was executed (after a chosen action).

class tg_model.execution.DecisionTraceStep(step_index, part_path, decision_name, chosen_action)[source]

Bases: object

Record of one dispatch_decision() invocation.

Parameters:
  • step_index (int)

  • part_path (str)

  • decision_name (str)

  • chosen_action (str | None)

step_index: int
part_path: str
decision_name: str
chosen_action: str | None
class tg_model.execution.DependencyGraph[source]

Bases: object

Directed graph of value and compute nodes for one compile of a configured model.

Notes

add_edge(from_id, to_id) means from_id must be satisfied before to_id.

add_node(node)[source]
Parameters:

node (DependencyNode)

Return type:

None

add_edge(from_id, to_id)[source]

Add dependency edge (from_id before to_id).

Parameters:
  • from_id (str)

  • to_id (str)

Return type:

None

get_node(node_id)[source]

Return node by id.

Raises:

KeyError – If unknown.

Parameters:

node_id (str)

Return type:

DependencyNode

property nodes: dict[str, DependencyNode]
property edges: list[tuple[str, str]]
dependencies_of(node_id)[source]
Parameters:

node_id (str)

Return type:

list[str]

dependents_of(node_id)[source]
Parameters:

node_id (str)

Return type:

list[str]

topological_order()[source]

Deterministic topological sort (stable tie-break by sorted ready queue).

Returns:

Node ids in evaluation order.

Return type:

list[str]

Raises:

ValueError – If a cycle remains (not all nodes scheduled).

dependency_closure(seeds)[source]

Walk upstream dependencies from seeds.

Raises:

KeyError – If a seed is not a known node id.

Parameters:

seeds (Iterable[str])

Return type:

set[str]

dependent_closure(seeds)[source]

Walk downstream dependents from seeds.

Raises:

KeyError – If a seed is not a known node id.

Parameters:

seeds (Iterable[str])

Return type:

set[str]

induced_subgraph(node_ids)[source]

Copy restricted to node_ids (internal edges only).

Raises:

KeyError – If any requested id is unknown.

Parameters:

node_ids (set[str])

Return type:

DependencyGraph

class tg_model.execution.DependencyNode(node_id, kind, slot_id=None, metadata=None)[source]

Bases: object

Single node in a DependencyGraph (value or compute kind).

Parameters:
  • node_id (str)

  • kind (NodeKind)

  • slot_id (str | None)

  • metadata (dict[str, Any] | None)

node_id
kind
slot_id
metadata
property is_value_node: bool
property is_compute_node: bool
class tg_model.execution.DispatchOutcome(*values)[source]

Bases: StrEnum

Outcome of dispatch_event() (transition fired vs skipped).

FIRED = 'fired'
NO_MATCH = 'no_match'

No transition for the current state and event name (or no behavior spec).

GUARD_FAILED = 'guard_failed'

A transition matched but its when guard returned false.

class tg_model.execution.DispatchResult(outcome)[source]

Bases: object

Structured result of dispatch_event().

Notes

bool(result) is true only when a transition fired (legacy truthiness preserved).

Parameters:

outcome (DispatchOutcome)

outcome: DispatchOutcome
class tg_model.execution.ElementInstance(*, stable_id, definition_type, definition_path, instance_path, kind, metadata=None)[source]

Bases: object

One materialized declaration (requirement, port, block, …) under the configured root.

Parameters:
  • stable_id (str)

  • definition_type (type)

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

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

  • kind (str)

  • metadata (dict[str, Any] | None)

stable_id
definition_type
definition_path
instance_path
kind
metadata
property path_string: str

Dotted path from configured root to this instance.

class tg_model.execution.Evaluator(graph, *, compute_handlers=None)[source]

Bases: object

Synchronous evaluation engine over a dependency graph.

Walks the topological order, evaluates ready compute nodes, and materializes results into the RunContext.

evaluate and evaluate_async intentionally duplicate the topological driver: bridging them through one coroutine would force asyncio.run (or worse) from evaluate, which breaks callers that already own an event loop. Shared helpers only cover non-async steps (see _bind_run_inputs / _finalize_run).

Parameters:
evaluate(ctx, inputs=None)[source]

Run one synchronous evaluation (external compute must not be async).

Parameters:
  • ctx (RunContext) – Fresh or reset per-run state.

  • inputs (dict, optional) – Bound by stable slot id (see graph node metadata / compile conventions).

Returns:

Aggregated failures and constraint outcomes.

Return type:

RunResult

Raises:

TypeError – Propagated from assert_sync_external() when an async external is present.

See also

evaluate_async

async evaluate_async(ctx, *, configured_model, inputs=None)[source]

Evaluate with async external backends (await compute when it returns a coroutine).

Parameters:
  • ctx (RunContext) – Per-run state.

  • configured_model (ConfiguredModel) – Topology context for external resolution paths.

  • inputs (dict, optional) – Same binding convention as evaluate().

Returns:

Same shape as evaluate().

Return type:

RunResult

See also

evaluate

class tg_model.execution.ForkJoinTraceStep(step_index, part_path, block_name)[source]

Bases: object

Record of one dispatch_fork_join() invocation.

Parameters:
  • step_index (int)

  • part_path (str)

  • block_name (str)

step_index: int
part_path: str
block_name: str
exception tg_model.execution.GraphCompilationError[source]

Bases: Exception

Raised when graph compilation cannot resolve symbols, slots, or bindings.

exception tg_model.execution.GraphValidationError(message, *, result)[source]

Bases: Exception

Raised when validate_graph() fails before evaluation.

Typical source: tg_model.execution.configured_model.ConfiguredModel.evaluate() when validate=True and static checks do not pass.

Subclasses Exception (not BaseException) so typical except Exception handlers catch it; use this type or inspect result when you need to distinguish validation from other failures.

Parameters:
Return type:

None

result

Structured failures from validate_graph().

Type:

ValidationResult

class tg_model.execution.ItemFlowStep(step_index, source_port_path, target_port_path, item_kind, payload=None)[source]

Bases: object

Inter-part item flow across one ConnectionBinding.

Parameters:
  • step_index (int)

  • source_port_path (str)

  • target_port_path (str)

  • item_kind (str)

  • payload (Any | None)

step_index: int
source_port_path: str
target_port_path: str
item_kind: str
payload: Any | None = None
class tg_model.execution.MergeTraceStep(step_index, part_path, merge_name, then_action)[source]

Bases: object

Record of one dispatch_merge() invocation.

Parameters:
  • step_index (int)

  • part_path (str)

  • merge_name (str)

  • then_action (str | None)

step_index: int
part_path: str
merge_name: str
then_action: str | None
class tg_model.execution.NodeKind(*values)[source]

Bases: Enum

Compute vs value classification for dependency nodes.

INPUT_PARAMETER = 'input_parameter'
ATTRIBUTE_VALUE = 'attribute_value'
CONSTRAINT_RESULT = 'constraint_result'
LOCAL_EXPRESSION = 'local_expression'
ROLLUP_COMPUTATION = 'rollup_computation'
SOLVE_GROUP = 'solve_group'
CONSTRAINT_CHECK = 'constraint_check'
EXTERNAL_COMPUTATION = 'external_computation'
class tg_model.execution.PartInstance(*, stable_id, definition_type, definition_path, instance_path, metadata=None)[source]

Bases: ElementInstance

Materialized Part / System.

Owns child parts, ports, and value slots. After freeze(), structure is immutable.

Raises:

RuntimeError – If mutators run after freeze().

Parameters:
  • stable_id (str)

  • definition_type (type)

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

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

  • metadata (dict[str, Any] | None)

freeze()[source]

Recursively freeze this part subtree (called on the full model after instantiate).

Return type:

None

add_child(name, child)[source]

Register a child part under name (instantiation only).

Raises:

RuntimeError – If this instance is frozen.

Parameters:
Return type:

None

add_port(name, port)[source]

Register a port under name (instantiation only).

Parameters:
Return type:

None

add_value_slot(name, slot)[source]

Register a value slot under name (instantiation only).

Parameters:
Return type:

None

add_requirement_package(name, pkg)[source]

Register a composable requirement package under name (instantiation only).

Parameters:
Return type:

None

property children: list[PartInstance]

Shallow copy of child parts.

property ports: list[PortInstance]

Shallow copy of owned ports.

property value_slots: list[ValueSlot]

Shallow copy of owned parameter/attribute slots.

class tg_model.execution.PortInstance(*, stable_id, definition_type, definition_path, instance_path, metadata=None)[source]

Bases: ElementInstance

Concrete port endpoint; direction comes from declaration metadata.

Parameters:
  • stable_id (str)

  • definition_type (type)

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

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

  • metadata (dict[str, Any] | None)

direction
class tg_model.execution.ReferenceBinding(*, stable_id, source, citation)[source]

Bases: object

Resolved references edge from a declaration to a citation node (provenance).

Parameters:
stable_id
source
citation
class tg_model.execution.RequirementPackageInstance(*, stable_id, definition_type, definition_path, instance_path, package_type, metadata=None)[source]

Bases: ElementInstance

Materialized composable requirement package under the configured root.

Exposes nested requirements, citations, nested packages, and package-level value slots via attribute access (e.g. root.mission.x_m for a package parameter).

Parameters:
  • stable_id (str)

  • definition_type (type)

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

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

  • package_type (type)

  • metadata (dict[str, Any] | None)

package_type
add_member(name, obj)[source]

Register a child (instantiation only).

Parameters:
Return type:

None

freeze()[source]

Freeze this package and nested packages recursively.

Return type:

None

class tg_model.execution.RequirementSatisfactionResult(requirement_path, allocation_target_path, passed, evidence, check_name)[source]

Bases: object

Outcome of one requirement acceptance check (one allocation x one compiled check).

Parameters:
  • requirement_path (str)

  • allocation_target_path (str)

  • passed (bool)

  • evidence (str)

  • check_name (str)

requirement_path: str
allocation_target_path: str
passed: bool
evidence: str
check_name: str
class tg_model.execution.RequirementSatisfactionSummary(results)[source]

Bases: object

Aggregated requirement acceptance outcomes for one run.

Use check_count to detect the case where no acceptance checks ran (no expr= requirements compiled into the graph for this configuration). all_passed is False when check_count == 0 so callers do not treat “nothing to verify” as green compliance.

Parameters:

results (tuple[RequirementSatisfactionResult, ...])

results: tuple[RequirementSatisfactionResult, ...]
property check_count: int
property all_passed: bool

True only when there is at least one acceptance check and every check passed.

class tg_model.execution.RunContext[source]

Bases: object

Per-run mutable state. Created fresh for each evaluation.

Keyed by ValueSlot.stable_id to maintain isolation from topology.

Behavior effects and guards (Phase 6): while push_behavior_effect_scope() is active (during transition guards, decision predicates, and action effects), slot and discrete-state accessors above are restricted to the active part subtree. This is API discipline for well-behaved callables — not a security sandbox: code can still close over ConfiguredModel or use other Python escape hatches. Item payload staging (prime_item_payload(), etc.) is intentionally not subtree-scoped (inter-part delivery).

push_behavior_effect_scope(part)[source]

Restrict value-slot access to the subtree of part until pop_behavior_effect_scope().

Parameters:

part (PartInstance) – Active part for guard/effect callables.

Return type:

None

pop_behavior_effect_scope()[source]

Pop the innermost behavior scope pushed by push_behavior_effect_scope().

Raises:

RuntimeError – If the stack is empty.

Return type:

None

get_or_create_record(slot_id)[source]

Return the mutable SlotRecord for slot_id, creating it if needed.

When a behavior effect scope is active, the same subtree rule as bind_input() applies (see class docstring).

Parameters:

slot_id (str)

Return type:

SlotRecord

bind_input(slot_id, value)[source]

Bind value to slot_id (creates record if needed).

Parameters:
  • slot_id (str)

  • value (Any)

Return type:

None

realize(slot_id, value, provenance='computed')[source]

Write computed value to slot_id.

Parameters:
  • slot_id (str)

  • value (Any)

  • provenance (Any)

Return type:

None

mark_pending(slot_id, note='')[source]

Mark slot_id pending (external deferral hook).

Parameters:
  • slot_id (str)

  • note (str)

Return type:

None

get_value(slot_id)[source]

Return the current value when the slot is in a ready state.

Raises:
  • ValueError – If the slot has no record or is not ready.

  • RuntimeError – If a behavior scope forbids access to this slot.

Parameters:

slot_id (str)

Return type:

Any

get_state(slot_id)[source]

Return SlotState for slot_id (UNBOUND if no record).

Raises:

RuntimeError – If a behavior effect scope forbids access to this slot.

Parameters:

slot_id (str)

Return type:

SlotState

add_constraint_result(result)[source]

Append one constraint or requirement-acceptance outcome to this run.

Parameters:

result (ConstraintResult)

Return type:

None

property constraint_results: list[ConstraintResult]

Copy of all ConstraintResult rows recorded during evaluation.

property all_passed: bool

True when every stored ConstraintResult has passed (empty is vacuously true).

get_active_behavior_state(part_path_string)[source]

Return the current discrete behavior state name for part_path_string, if any.

Raises:

RuntimeError – If called from a behavior effect with an out-of-scope part_path_string.

Parameters:

part_path_string (str)

Return type:

str | None

set_active_behavior_state(part_path_string, state_name)[source]

Set discrete behavior state for part_path_string (dotted instance path).

Raises:

RuntimeError – If a behavior effect scope forbids mutating this part’s state.

Parameters:
  • part_path_string (str)

  • state_name (str)

Return type:

None

prime_item_payload(part_path_string, event_name, payload)[source]

Stage payload for the next event_name on part_path_string (see emit_item()).

Notes

Not restricted by behavior subtree scope (inter-part delivery).

Parameters:
  • part_path_string (str)

  • event_name (str)

  • payload (Any)

Return type:

None

peek_item_payload(part_path_string, event_name)[source]

Return staged payload for (part_path_string, event_name) without consuming it.

Parameters:
  • part_path_string (str)

  • event_name (str)

Return type:

Any | None

clear_item_payload(part_path_string, event_name)[source]

Remove staged payload for (part_path_string, event_name) after handling.

Parameters:
  • part_path_string (str)

  • event_name (str)

Return type:

None

class tg_model.execution.RunResult(outputs=<factory>, constraint_results=<factory>, failures=<factory>)[source]

Bases: object

Aggregated outcome of one evaluate() / evaluate_async() run.

Parameters:
  • outputs (dict[str, Any])

  • constraint_results (list[ConstraintResult])

  • failures (list[str])

outputs: dict[str, Any]
constraint_results: list[ConstraintResult]
failures: list[str]
property passed: bool

True when there are no failures and every constraint result passed.

class tg_model.execution.SequenceTraceStep(step_index, part_path, sequence_name)[source]

Bases: object

Record of one dispatch_sequence() invocation.

Parameters:
  • step_index (int)

  • part_path (str)

  • sequence_name (str)

step_index: int
part_path: str
sequence_name: str
class tg_model.execution.SlotState(*values)[source]

Bases: Enum

Lifecycle state for one ValueSlot in a RunContext.

UNBOUND = 'unbound'
BOUND_INPUT = 'bound_input'
PENDING = 'pending'
REALIZED = 'realized'
FAILED = 'failed'
BLOCKED = 'blocked'
class tg_model.execution.ValidationResult(failures=<factory>)[source]

Bases: object

Aggregate result of validate_graph().

Parameters:

failures (list[ValidationFailure])

failures: list[ValidationFailure]
property passed: bool

True when failures is empty.

add(category, message, path=None)[source]

Append a ValidationFailure.

Parameters:
  • category (str)

  • message (str)

  • path (str | None)

Return type:

None

class tg_model.execution.ValueSlot(*, stable_id, instance_path, kind, definition_type=None, definition_path=None, metadata=None, has_expr=False, has_computed_by=False)[source]

Bases: object

Describes what can hold a value in the configured topology.

A ValueSlot is part of the configured topology. It describes the slot, not the per-run mutable value. Per-run state lives in RunContext.

Parameters:
  • stable_id (str)

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

  • kind (str)

  • definition_type (type | None)

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

  • metadata (dict[str, Any] | None)

  • has_expr (bool)

  • has_computed_by (bool)

stable_id
instance_path
kind
definition_type
definition_path
metadata
has_expr
has_computed_by
property path_string: str

Dotted instance path for handles and debugging.

property is_parameter: bool

True when kind == "parameter".

property is_attribute: bool

True when kind == "attribute".

tg_model.execution.all_requirements_satisfied(ctx)[source]

Return RequirementSatisfactionSummary.all_passed for ctx.

Returns:

False when there are zero requirement acceptance checks (not vacuously true).

Return type:

bool

Parameters:

ctx (RunContext | RunResult)

tg_model.execution.behavior_authoring_projection(definition_type)[source]

Return a JSON-oriented projection of behavioral declarations on definition_type.

Parameters:

definition_type (type) – Compiled part/system type.

Returns:

Node name lists by kind, serialized transitions, and edges (refs via to_dict()).

Return type:

dict

Notes

Tooling hook only: not a strict schema for every metadata field.

tg_model.execution.behavior_trace_to_records(trace)[source]

Flatten trace into JSON-friendly dict rows sorted by step_index.

Parameters:

trace (BehaviorTrace) – Collected steps from one or more dispatch calls.

Returns:

Each dict has kind, step_index, and kind-specific keys.

Return type:

list[dict]

tg_model.execution.compile_graph(model)[source]

Compile dependency graph and per-node compute handlers from a configured model.

This is the only supported public entry point for graph compilation.

Parameters:

model (ConfiguredModel) – Frozen topology from instantiate().

Returns:

  • graph (DependencyGraph) – Bipartite value/compute graph in topological-evaluable form.

  • handlers (dict[str, Callable]) – Sync callables keyed by compute node_id (expressions, roll-ups, externals, constraints).

Raises:

GraphCompilationError – On unresolvable references, binding errors, or other compile failures.

Return type:

tuple[DependencyGraph, dict[str, Callable]]

Notes

Walks value slots, requirement acceptance, constraints, solve groups, and external nodes. Async externals are still scheduled from sync evaluate_async().

Successful results are cached on model._compiled_graph so repeated calls and evaluate() reuse the same (graph, handlers) tuple without recompilation.

tg_model.execution.dispatch_decision(ctx, part, decision_name, *, trace=None, run_merge=True)[source]

Run a declared decision: first branch whose guard passes runs its action.

Parameters:
  • ctx (RunContext) – Current run state.

  • part (PartInstance) – Owner of the decision declaration.

  • decision_name (str) – Declared decision node name.

  • trace (BehaviorTrace, optional) – Records DecisionTraceStep when provided.

  • run_merge (bool, default True) – When False, skip automatic paired merge (advanced sequencing).

Raises:

KeyError – If decision_name is not declared on part.definition_type.

Returns:

outcome is NO_ACTION only when no branch matched and there is no default_action. bool(result) is true iff an action ran.

Return type:

DecisionDispatchResult

Notes

If the decision was declared with merge_point= to a merge() node, also runs that merge’s then_action after the branch action (unless run_merge=False for manual dispatch_merge() — do not call dispatch_merge() again for the same merge when pairing is enabled, or the continuation runs twice).

Branches with guard is None match unconditionally (place them last unless you intend a catch-all).

tg_model.execution.dispatch_event(ctx, part, event_name, *, trace=None)[source]

Dispatch one discrete event on part’s state machine.

Parameters:
  • ctx (RunContext) – Run state (discrete state + optional item payloads).

  • part (PartInstance) – Part whose compiled type owns transitions.

  • event_name (str) – Declared event name (last segment of the event ref path).

  • trace (BehaviorTrace, optional) – When passed, appends a BehaviorStep on success.

Returns:

NO_MATCH, GUARD_FAILED, or fired.

Return type:

DispatchResult

Raises:

Exception – Any guard/effect error propagates; if the effect fails after the state advanced, the prior discrete state is restored first.

Notes

bool(result) is true only when a transition fired.

tg_model.execution.dispatch_fork_join(ctx, part, block_name, *, trace=None)[source]

Execute a fork_join block: branches run one after another (fixed list order).

Raises:
  • KeyError – If block_name is not declared.

  • v0 semantics are deterministic serial execution, not OS-level parallelism or

  • arbitrary interleaving; fork/join name the logical activity structure.

Parameters:
Return type:

None

tg_model.execution.dispatch_merge(ctx, part, merge_name, *, trace=None)[source]

Continue at a declared merge: runs optional then_action (shared after branches).

Call after exclusive branches (e.g. following dispatch_decision()) to model a methodology Merge node. If no then_action was declared, returns None and only records the trace step when trace is set.

Raises:

KeyError – If merge_name is not declared.

Parameters:
Return type:

str | None

tg_model.execution.dispatch_sequence(ctx, part, sequence_name, *, trace=None)[source]

Run a declared linear sequence of actions (methodology default simplicity rule).

Raises:

KeyError – If sequence_name is not declared.

Parameters:
Return type:

None

tg_model.execution.emit_item(ctx, cm, source_port, item_kind, payload, *, trace=None)[source]

Send an item from source_port across structural connections.

Parameters:
  • ctx (RunContext) – Stages payloads per receiving part/event.

  • cm (ConfiguredModel) – Supplies connections and handle().

  • source_port (PortInstance) – Emitting port.

  • item_kind (str) – Event name / kind matched on receivers; may be filtered by binding carrying.

  • payload (Any) – Opaque payload for receiver effects.

  • trace (BehaviorTrace, optional) – Records ItemFlowStep rows.

Returns:

One result per matched connection (may be empty).

Return type:

list[DispatchResult]

Notes

For each matching ConnectionBinding (same source port; optional carrying must match item_kind), dispatches item_kind on the receiving part. Payload is staged via RunContext.prime_item_payload() and cleared if dispatch does not fire.

Bindings are visited in cm.connections order (deterministic for a frozen model).

tg_model.execution.instantiate(root_type)[source]

Build a ConfiguredModel from a compiled root type.

Walks the compiled definition depth-first, creating PartInstance, PortInstance, RequirementPackageInstance (composable requirement packages with package-level value slots), ValueSlot, connection bindings, and allocation bindings. Registers handles then freezes all parts.

Parameters:

root_type (type) – Compiled System / Part subclass.

Returns:

Frozen topology ready for compile_graph().

Return type:

ConfiguredModel

Notes

Stable IDs derive from the configured root type plus full instance path so identities stay unique regardless of which intermediate type owns a declaration.

See also

tg_model.execution.graph_compiler.compile_graph, tg_model.execution.evaluator.Evaluator

tg_model.execution.iter_requirement_satisfaction(ctx)[source]

Filter constraint rows that carry requirement_path (acceptance checks).

Parameters:

ctx (RunContext or RunResult) – Object exposing constraint_results (same ordering as evaluation).

Returns:

One row per tagged constraint result.

Return type:

list of RequirementSatisfactionResult

tg_model.execution.scenario_expected_event_names(definition_type, scenario_name)[source]

Return authored expected_event_order names for a scenario node.

Raises:
  • KeyError – If the scenario is missing.

  • ValueError – If metadata is malformed.

Parameters:
  • definition_type (type)

  • scenario_name (str)

Return type:

list[str]

tg_model.execution.summarize_requirement_satisfaction(ctx)[source]

Aggregate iter_requirement_satisfaction() into a summary tuple.

Returns:

Includes RequirementSatisfactionSummary.all_passed semantics for zero checks.

Return type:

RequirementSatisfactionSummary

Parameters:

ctx (RunContext | RunResult)

tg_model.execution.trace_events_chronological(trace)[source]

List (part_path, event_name) for state-machine steps sorted by step_index.

Returns:

Transition events only (excludes decisions, merges, item flows).

Return type:

list[tuple[str, str]]

Parameters:

trace (BehaviorTrace)

tg_model.execution.validate_graph(graph, *, configured_model=None)[source]

Run static checks before evaluation (cycles, orphans, roll-ups, externals).

Parameters:
Returns:

Non-passing result lists structured ValidationFailure rows (never raises for soft checks).

Return type:

ValidationResult

tg_model.execution.validate_scenario_trace(*, definition_type, scenario_name, part_path, trace, ctx=None, root=None)[source]

Compare trace slices to an authored scenario (partial contracts).

Parameters:
  • definition_type (type) – Owner type of the scenario declaration.

  • scenario_name (str) – Scenario node name on that type.

  • part_path (str) – Instance path string for transition-focused checks.

  • trace (BehaviorTrace) – Collected behavioral steps.

  • ctx (RunContext, optional) – Needed when checking final discrete state.

  • root (PartInstance, optional) – Configured root when validating expected_interaction_order.

Returns:

  • ok (bool) – True when every enabled check passes.

  • errors (list[str]) – Human-readable failure messages (empty when ok).

Return type:

tuple[bool, list[str]]

Notes

This is a bundle of independent checks, not one end-to-end story:

  • Transition events for part_path vs expected_event_order.

  • Optional final/initial discrete state (ctx needed for final).

  • Optional global transition order via trace_events_chronological() (state-machine steps only — not decisions, merges, or item flows).

  • Optional item kind order from ItemFlowStep.

Passing everything still does not prove full causal intent; combine with tests or tooling. Call with ctx from outside behavior effects when checking final state.

For expected_interaction_order, pass root (configured root part) so global ordering can be compared. For expected_item_kind_order, compares item flow kinds.