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:
objectResolved
allocateedge 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:
objectOne 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:
objectMutable collector for behavioral steps (multiple parallel lists).
Notes
Paths are
PartInstance.path_stringvalues and declared names, not slot stable ids. Global ordering usesstep_indexacross lists (seebehavior_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])
- 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:
objectImmutable configured topology for one root type instance.
Notes
Evaluations use fresh
RunContextobjects perevaluate()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()orcompile_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_graphis 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:
root (PartInstance)
path_registry (dict[str, ElementInstance | ValueSlot])
id_registry (dict[str, ElementInstance | ValueSlot])
connections (list[ConnectionBinding])
allocations (list[AllocationBinding])
references (list[ReferenceBinding])
requirement_value_slots (list[ValueSlot] | None)
- 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:
- Raises:
KeyError – If
pathis not inpath_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 runsvalidate_graph(), then delegates toEvaluator.- Parameters:
inputs (dict, optional) – Per-run values keyed by
ValueSlothandles belonging to this model, or bystrgiving thestable_idof such a slot only (not arbitrary element or part ids). Values are typicallyunitflow.Quantityinstances.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, passvalidate=Falseafter you have validated once out-of-band, to avoid repeating that work every run. On validation failure, raisesGraphValidationError.
- Returns:
Same aggregate type as
tg_model.execution.evaluator.Evaluator.evaluate(). Missing inputs, failed constraints, and other runtime issues appear infailures/constraint_results— not as exceptions from this method.- Return type:
- Raises:
GraphCompilationError – If graph compilation fails (from
compile_graph()).GraphValidationError – If
validateis True and static validation fails (subclass ofException).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
ValueSlotnot registered on this model, or a string id that does not refer to aValueSlot.
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:
objectResolved connection between two
PortInstanceobjects.- 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:
objectOutcome 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:
StrEnumOutcome of
dispatch_decision()(action ran vs not).- ACTION_RAN = 'action_ran'¶
A branch or
default_actionran (name inDecisionDispatchResult.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:
objectStructured result of
dispatch_decision().Notes
bool(result)is true whenchosen_actionis notNone.- Parameters:
outcome (DecisionDispatchOutcome)
chosen_action (str | None)
merge_ran (bool)
- 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:
objectRecord 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:
objectDirected graph of value and compute nodes for one compile of a configured model.
Notes
add_edge(from_id, to_id)meansfrom_idmust be satisfied beforeto_id.- add_node(node)[source]¶
- Parameters:
node (DependencyNode)
- Return type:
None
- add_edge(from_id, to_id)[source]¶
Add dependency edge (
from_idbeforeto_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:
- property nodes: dict[str, DependencyNode]¶
- property edges: list[tuple[str, 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]
- class tg_model.execution.DependencyNode(node_id, kind, slot_id=None, metadata=None)[source]¶
Bases:
objectSingle 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:
StrEnumOutcome 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
whenguard returned false.
- class tg_model.execution.DispatchResult(outcome)[source]¶
Bases:
objectStructured 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:
objectOne 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:
objectSynchronous evaluation engine over a dependency graph.
Walks the topological order, evaluates ready compute nodes, and materializes results into the RunContext.
evaluateandevaluate_asyncintentionally duplicate the topological driver: bridging them through one coroutine would forceasyncio.run(or worse) fromevaluate, which breaks callers that already own an event loop. Shared helpers only cover non-async steps (see_bind_run_inputs/_finalize_run).- Parameters:
graph (DependencyGraph)
compute_handlers (dict[str, Any] | None)
- evaluate(ctx, inputs=None)[source]¶
Run one synchronous evaluation (external
computemust 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:
- Raises:
TypeError – Propagated from
assert_sync_external()when an async external is present.
See also
- async evaluate_async(ctx, *, configured_model, inputs=None)[source]¶
Evaluate with async external backends (await
computewhen 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:
See also
- class tg_model.execution.ForkJoinTraceStep(step_index, part_path, block_name)[source]¶
Bases:
objectRecord 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:
ExceptionRaised when graph compilation cannot resolve symbols, slots, or bindings.
- exception tg_model.execution.GraphValidationError(message, *, result)[source]¶
Bases:
ExceptionRaised when
validate_graph()fails before evaluation.Typical source:
tg_model.execution.configured_model.ConfiguredModel.evaluate()whenvalidate=Trueand static checks do not pass.Subclasses
Exception(notBaseException) so typicalexcept Exceptionhandlers catch it; use this type or inspectresultwhen you need to distinguish validation from other failures.- Parameters:
message (str)
result (ValidationResult)
- Return type:
None
- result¶
Structured failures from
validate_graph().- Type:
- class tg_model.execution.ItemFlowStep(step_index, source_port_path, target_port_path, item_kind, payload=None)[source]¶
Bases:
objectInter-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:
objectRecord 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:
EnumCompute 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:
ElementInstanceOwns 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:
name (str)
child (PartInstance)
- Return type:
None
- add_port(name, port)[source]¶
Register a port under
name(instantiation only).- Parameters:
name (str)
port (PortInstance)
- Return type:
None
- add_value_slot(name, slot)[source]¶
Register a value slot under
name(instantiation only).- Parameters:
name (str)
slot (ValueSlot)
- Return type:
None
- add_requirement_package(name, pkg)[source]¶
Register a composable requirement package under
name(instantiation only).- Parameters:
name (str)
- Return type:
None
- property children: list[PartInstance]¶
Shallow copy of child parts.
- property ports: list[PortInstance]¶
Shallow copy of owned ports.
- class tg_model.execution.PortInstance(*, stable_id, definition_type, definition_path, instance_path, metadata=None)[source]¶
Bases:
ElementInstanceConcrete port endpoint;
directioncomes 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:
objectResolved
referencesedge from a declaration to a citation node (provenance).- Parameters:
stable_id (str)
source (ElementInstance | PortInstance | ValueSlot)
citation (ElementInstance)
- stable_id¶
- source¶
- citation¶
- class tg_model.execution.RequirementPackageInstance(*, stable_id, definition_type, definition_path, instance_path, package_type, metadata=None)[source]¶
Bases:
ElementInstanceMaterialized 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_mfor 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:
name (str)
obj (ElementInstance | ValueSlot | RequirementPackageInstance)
- Return type:
None
- class tg_model.execution.RequirementSatisfactionResult(requirement_path, allocation_target_path, passed, evidence, check_name)[source]¶
Bases:
objectOutcome 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:
objectAggregated requirement acceptance outcomes for one run.
Use
check_countto detect the case where no acceptance checks ran (noexpr=requirements compiled into the graph for this configuration).all_passedis False whencheck_count == 0so 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:
objectPer-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 overConfiguredModelor 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
partuntilpop_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
SlotRecordforslot_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
valuetoslot_id(creates record if needed).- Parameters:
slot_id (str)
value (Any)
- Return type:
None
- realize(slot_id, value, provenance='computed')[source]¶
Write computed
valuetoslot_id.- Parameters:
slot_id (str)
value (Any)
provenance (Any)
- Return type:
None
- mark_pending(slot_id, note='')[source]¶
Mark
slot_idpending (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
SlotStateforslot_id(UNBOUNDif no record).- Raises:
RuntimeError – If a behavior effect scope forbids access to this slot.
- Parameters:
slot_id (str)
- Return type:
- 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
ConstraintResultrows recorded during evaluation.
- property all_passed: bool¶
True when every stored
ConstraintResulthaspassed(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
payloadfor the nextevent_nameonpart_path_string(seeemit_item()).Notes
Not restricted by behavior subtree scope (inter-part delivery).
- Parameters:
part_path_string (str)
event_name (str)
payload (Any)
- Return type:
None
- class tg_model.execution.RunResult(outputs=<factory>, constraint_results=<factory>, failures=<factory>)[source]¶
Bases:
objectAggregated 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:
objectRecord 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:
EnumLifecycle state for one
ValueSlotin aRunContext.- UNBOUND = 'unbound'¶
- BOUND_INPUT = 'bound_input'¶
- PENDING = 'pending'¶
- REALIZED = 'realized'¶
- FAILED = 'failed'¶
- BLOCKED = 'blocked'¶
- class tg_model.execution.ValidationResult(failures=<factory>)[source]¶
Bases:
objectAggregate result of
validate_graph().- Parameters:
failures (list[ValidationFailure])
- failures: list[ValidationFailure]¶
- property passed: bool¶
True when
failuresis empty.
- 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:
objectDescribes 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_passedforctx.- Returns:
False when there are zero requirement acceptance checks (not vacuously true).
- Return type:
bool
- Parameters:
ctx (RunContext | RunResult)
See also
- 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
traceinto JSON-friendly dict rows sorted bystep_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_graphso repeated calls andevaluate()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
DecisionTraceStepwhen provided.run_merge (bool, default True) – When False, skip automatic paired merge (advanced sequencing).
- Raises:
KeyError – If
decision_nameis not declared onpart.definition_type.- Returns:
outcomeisNO_ACTIONonly when no branch matched and there is nodefault_action.bool(result)is true iff an action ran.- Return type:
Notes
If the decision was declared with
merge_point=to amerge()node, also runs that merge’sthen_actionafter the branch action (unlessrun_merge=Falsefor manualdispatch_merge()— do not calldispatch_merge()again for the same merge when pairing is enabled, or the continuation runs twice).Branches with
guard is Nonematch 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
BehaviorStepon success.
- Returns:
NO_MATCH,GUARD_FAILED, or fired.- Return type:
- 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_joinblock: branches run one after another (fixed list order).- Raises:
KeyError – If
block_nameis not declared.v0 semantics are deterministic serial execution, not OS-level parallelism or –
arbitrary interleaving; fork/join name the logical activity structure. –
- Parameters:
ctx (RunContext)
part (PartInstance)
block_name (str)
trace (BehaviorTrace | None)
- Return type:
None
- tg_model.execution.dispatch_merge(ctx, part, merge_name, *, trace=None)[source]¶
Continue at a declared
merge: runs optionalthen_action(shared after branches).Call after exclusive branches (e.g. following
dispatch_decision()) to model a methodology Merge node. If nothen_actionwas declared, returnsNoneand only records the trace step whentraceis set.- Raises:
KeyError – If
merge_nameis not declared.- Parameters:
ctx (RunContext)
part (PartInstance)
merge_name (str)
trace (BehaviorTrace | None)
- Return type:
str | None
- tg_model.execution.dispatch_sequence(ctx, part, sequence_name, *, trace=None)[source]¶
Run a declared linear
sequenceof actions (methodology default simplicity rule).- Raises:
KeyError – If
sequence_nameis not declared.- Parameters:
ctx (RunContext)
part (PartInstance)
sequence_name (str)
trace (BehaviorTrace | None)
- Return type:
None
- tg_model.execution.emit_item(ctx, cm, source_port, item_kind, payload, *, trace=None)[source]¶
Send an item from
source_portacross structural connections.- Parameters:
ctx (RunContext) – Stages payloads per receiving part/event.
cm (ConfiguredModel) – Supplies
connectionsandhandle().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
ItemFlowSteprows.
- Returns:
One result per matched connection (may be empty).
- Return type:
list[DispatchResult]
Notes
For each matching
ConnectionBinding(same source port; optionalcarryingmust matchitem_kind), dispatchesitem_kindon the receiving part. Payload is staged viaRunContext.prime_item_payload()and cleared if dispatch does not fire.Bindings are visited in
cm.connectionsorder (deterministic for a frozen model).
- tg_model.execution.instantiate(root_type)[source]¶
Build a
ConfiguredModelfrom 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:
- Returns:
Frozen topology ready for
compile_graph().- Return type:
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_ordernames 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_passedsemantics for zero checks.- Return type:
- Parameters:
ctx (RunContext | RunResult)
- tg_model.execution.trace_events_chronological(trace)[source]¶
List
(part_path, event_name)for state-machine steps sorted bystep_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:
graph (DependencyGraph) – Output of
compile_graph().configured_model (ConfiguredModel, optional) – When provided, runs
ValidatableExternalComputevalidate_bindinghooks where implemented.
- Returns:
Non-passing result lists structured
ValidationFailurerows (never raises for soft checks).- Return type:
- 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_pathvsexpected_event_order.Optional final/initial discrete state (
ctxneeded 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
ctxfrom outside behavior effects when checking final state.For
expected_interaction_order, passroot(configured root part) so global ordering can be compared. Forexpected_item_kind_order, compares item flow kinds.