Chapter 10 / 20 min read
Dependency Resolution and Execution Planning
TaskStep, dependency checks, all(), ready steps, topological ordering, missing dependencies and cycles.
Dependency resolution and execution planning
The next engineering problem is not arithmetic. It is deciding which task step is allowed to run.
After considering a brief server-health example, we keep the implementation path focused on the existing calculator tools.
1. What is a dependency?
Consider three operations:
- Add 10 and 20.
- Multiply the result of Step 1 by 5.
- Divide the result of Step 2 by 2.
Step 2 depends on Step 1. Step 3 depends on Step 2.
Step 1: Addition
|
v
Step 2: Multiplication
|
v
Step 3: Division
A step must not execute until every prerequisite it depends on has completed successfully.
Now consider a slightly larger plan:
Step 1: Addition Step 2: Multiplication
\ /
\ /
v v
Step 3: Division
|
v
Step 4: Addition
Some steps can be independent and ready at the same time. The planner should discover those steps rather than forcing every task into a single fixed sequence.
2. Represent a task step
We can represent a planned operation with a Pydantic model:
from pydantic import BaseModel, ConfigDict, Field
from models.enums import StepStatus
class StrictInput(BaseModel):
model_config = ConfigDict(
extra="forbid",
strict=True,
)
class TaskStep(StrictInput):
step_id: int = Field(
description="The unique identifier for the step."
)
tool_name: str = Field(
description="The name of the tool to be executed for this step."
)
arguments: dict = Field(
description="The arguments required for the tool execution."
)
depends_on: list[int] = Field(
default_factory=list,
description="Step IDs that must complete before this step.",
)
status: StepStatus = Field(
default=StepStatus.PENDING
)
The original draft used default=[] for the dependency list. default_factory=list is the safer Pydantic pattern because each instance receives its own list.
The model creates a consistent structure:
step = TaskStep(
step_id=1,
tool_name="multiply_numbers",
arguments={"a": 250, "b": 40},
)
print(step)
print(step.status)
print(step.status.value)
print(step.model_dump())
The recorded output showed status=StepStatus.PENDING and a dictionary representation containing all five fields.
3. Find the dependency steps
The first function we wanted was are_dependencies_satisfied. It accepts the current step and the complete list of task steps, then returns a Boolean.
from models.enums import StepStatus
from models.schemas import TaskStep
def are_dependencies_satisfied(
current_step: TaskStep,
task_steps: list[TaskStep],
) -> bool:
dependency_ids = current_step.depends_on
dependency_steps = [
step
for step in task_steps
if step.step_id in dependency_ids
]
return all(
dependency.status == StepStatus.COMPLETED
for dependency in dependency_steps
)
An early test compared against StepStatus.SUCCESS and raised an AttributeError, because the enum uses COMPLETED to represent a finished step. Updating the comparison to StepStatus.COMPLETED corrected the test.
What does the list comprehension do?
dependency_steps = [
step
for step in task_steps
if step.step_id in dependency_ids
]
It filters the full task-step list and keeps only the objects whose IDs appear in the current step's depends_on list.
What does all() do?
all(iterable) returns True only when every item in the iterable is truthy.
all([
True,
True,
]) # True
all([
True,
False,
]) # False
Here, the expression checks whether every prerequisite step has completed.
The original test outcomes were:
Test 1 - No dependencies: True
Test 2 - Dependency completed: True
Test 3 - Dependency pending: False
Test 4 - Dependency failed: False
Test 5 - Dependency blocked: False
A subtle point: Python's all([]) is True. That is useful here. A step with no dependencies is ready because there is no prerequisite that can block it.
A robustness improvement
The simple implementation assumes every dependency ID exists. A production planner should reject missing dependency IDs before scheduling. Otherwise, the list comprehension can omit an unknown ID and all() may incorrectly treat the remaining list as satisfied. We can add explicit plan validation as a separate preflight check.
4. Find ready steps
The next function filters pending steps and checks their dependencies:
def get_ready_steps(
task_steps: list[TaskStep],
) -> list[int]:
ready_steps = []
for step in task_steps:
if step.status != StepStatus.PENDING:
continue
if not step.depends_on:
ready_steps.append(step.step_id)
else:
dependencies_completed = are_dependencies_satisfied(
step,
task_steps,
)
if dependencies_completed:
ready_steps.append(step.step_id)
return ready_steps
The continue statement skips a step that is not pending. We do not want to schedule a step that has already completed, failed or been blocked.
A step with no dependencies is immediately ready. A step with dependencies is ready only if the dependency check returns True.
5. A simpler planner representation
The learning session also separated the dependency graph from the Pydantic objects:
task_dependencies = {
1: [],
2: [],
3: [1, 2],
4: [3],
5: [2],
}
This means:
- Steps 1 and 2 have no prerequisites.
- Step 3 requires Steps 1 and 2.
- Step 4 requires Step 3.
- Step 5 requires Step 2.
If Steps 1 and 2 have already completed:
completed_steps = {1, 2}
available = get_available_steps(
task_dependencies,
completed_steps,
)
print(available)
The observed expected result was:
Available steps for execution: [3, 5]
The helper function was:
def get_available_steps(
task_dependencies: dict[int, list[int]],
completed_steps: set[int],
) -> list[int]:
available_steps = []
for step_id, dependencies in task_dependencies.items():
if step_id in completed_steps:
continue
if all(
dep in completed_steps
for dep in dependencies
):
available_steps.append(step_id)
return available_steps
The set gives fast membership checks for completed step IDs. The all() expression ensures that every prerequisite is already in that set.
6. Build a full execution order
The first attempt calculated only one batch of available steps. That was insufficient: after one batch is considered complete, the planner must calculate the next batch using the newly completed IDs.
The improved function uses a loop:
def get_execution_order(
task_steps: list[TaskStep],
) -> list[int]:
execution_order = []
completed_steps = set()
task_dependencies = {
step.step_id: step.depends_on
for step in task_steps
}
while len(completed_steps) < len(task_dependencies):
available_steps = get_available_steps(
task_dependencies,
completed_steps,
)
if not available_steps:
raise ValueError(
"Unable to resolve dependencies..."
)
print(
"Available steps for execution:",
available_steps,
)
completed_steps.update(available_steps)
execution_order.extend(available_steps)
print(
"Execution order so far:",
execution_order,
)
return execution_order
This is a planning simulation. The set named completed_steps here means “already accounted for by the topological planning algorithm”; it does not mean the real tools have executed. The actual executor must update step status only after real execution.
7. Why does the loop detect cycles?
Suppose Step 3 depends on Step 4, while Step 4 depends on Step 3:
task_steps = [
TaskStep(
step_id=1,
tool_name="calculate_addition",
arguments={},
),
TaskStep(
step_id=2,
tool_name="multiply_numbers",
arguments={},
),
TaskStep(
step_id=3,
tool_name="divide_numbers",
arguments={},
depends_on=[4],
),
TaskStep(
step_id=4,
tool_name="calculate_addition",
arguments={},
depends_on=[3],
),
]
Steps 1 and 2 can be planned. Steps 3 and 4 cannot: each waits for the other. Eventually, the planner finds no available steps while some IDs remain unfinished. It raises:
ValueError: Unable to resolve dependencies...
That is how a topological planner detects a cycle or another impossible dependency configuration.
8. The observed planner output and debugging
The planner test produced [1, 2] as the first ready batch and [3, 5] as a later batch. A separate test introduced a cycle between Steps 3 and 4 and correctly reached the no-progress error.
The debugging path included:
- An import error when a module was run directly from inside the
orchestrationfolder. Running the test from the project root preserves the package import context. - A status-name error caused by using
StepStatus.SUCCESSwhen the step enum definedCOMPLETED. - A planner that calculated only one batch; it needed a
whileloop. - A cycle test that proved the planner must fail rather than silently return a partial order.
9. Planning is not execution
The planner answers: “In what order could these steps run, assuming their dependencies succeed?”
The executor answers: “Did the tool actually run, and did it succeed?”
A real orchestrator must connect both. It must not mark a dependency as completed merely because it appeared in a planned order. The next chapter covers step execution and result storage.