A dependency graph answers a practical question: what must finish before this task can begin? A report cannot be published before its checks finish, a package cannot be assembled before its inputs exist, and a data export should not run before its source snapshot is ready. A directed acyclic graph, or DAG, is a directed graph with no directed cycle. Writing these relationships down is easy. Preserving their meaning when a graph contains a typo, an accidental cycle, or several equally valid orders takes more care.
This guide uses DeepSeek as a review partner for a small Python dependency planner. The planner itself uses the standard library and runs entirely offline. You will define a predecessor-based input contract, reject undeclared tasks, build deterministic readiness waves, and retain a concrete cycle witness when planning fails. The central example is a fictional publishing workflow. Nothing in the lab runs a command, sends a request, publishes a document, or executes a task named in the graph.
The distinction matters when reviewing AI-assisted code. A plausible sequence can hide a reversed edge or a missing prerequisite. A model can propose useful counterexamples, but the graph contract and executable tests decide whether the proposal is correct. The prompts below are templates, not recorded DeepSeek responses. No live model calls, speed comparisons, or claims about model accuracy were made for this tutorial.
1. Define a small, explicit dependency contract
Our input is a dictionary from a task identifier to its immediate predecessors. The entry for publish lists review and test because both must finish first. The entry for draft is empty because drafting has no predecessor in this particular model. These are fictional task names that identify nodes. They are not Python functions, shell commands, filenames, or instructions for the assistant to execute.
The contract deliberately accepts only an ordinary built-in dictionary. Each value must be an ordinary list or tuple of task identifiers. A task identifier is an exact built-in string, starts with a lowercase ASCII letter, and contains only lowercase ASCII letters, digits, or underscores after that. Its maximum length is forty characters. The boundary excludes custom containers, string subclasses, generators, sets, and clever objects with surprising iteration behavior. Those restrictions suit this teaching example; they are application choices rather than requirements of graph theory.
Every predecessor must also appear as a dictionary key. Repeated predecessors in one list are errors. An empty graph is valid and produces an empty plan. The lab limits input to sixty-four declared tasks and 256 predecessor entries. These modest caps make exhaustive small examples and manual review comfortable. They are not recommended production capacity limits and do not turn the function into a general security boundary for hostile Python objects.
Some systems intentionally allow an undeclared predecessor to become a new root. Our workflow does not: writing reveiw instead of review should produce an error rather than introduce an imaginary task. That policy should be decided before asking a model for implementation help. Otherwise, a model can choose a convenient library default that silently changes the meaning of the user’s workflow.
Likewise, duplicate edges may be mathematically harmless while still indicating a configuration mistake. Rejecting them makes an accidental copy-and-paste visible at the boundary. Another application could remove duplicates and issue a warning, but that would be a different contract with different expected tests. Avoid treating either policy as universally correct. State which information you want to preserve and which inputs you want authors to correct.
Finally, an edge means that the predecessor’s required result must be available before its dependent is eligible. It does not describe a duration, a deadline, a retry policy, a permission, or an optional suggestion. If your workflow needs several meanings, represent them explicitly instead of squeezing every relationship into the same unlabelled arrow. A graph that combines advice and hard prerequisites cannot support a trustworthy execution decision.
2. Make edge direction impossible to misunderstand
Read publish: [review, test] as “publish waits for review and test.” In a conventional drawing, the arrows therefore travel from review to publish and from test to publish. The dictionary stores incoming prerequisites, even though a diagram often invites you to read outgoing arrows. This difference is a common source of code that looks reasonable and returns an order that is exactly backwards.
Use a two-node example before reviewing a larger graph. If build depends on fetch, the only valid order is fetch followed by build. Write the expected result in the test before implementing the function. A diamond alone can be less revealing because its symmetry makes names easy to swap without noticing the error. The two-node example isolates the relationship with no unrelated structure.
Our four-node diamond is more realistic. Drafting releases two independent checks, review and test. Publishing waits for both checks. The dependency between draft and publish is already implied by the paths through those checks. Adding draft directly to publish’s predecessor list would be redundant for this graph, but it would not create a cycle or change the resulting waves. The lab permits such redundant edges because it validates consistency rather than minimizing a graph.
An independent task belongs in the input even when no other task points to it. If a standalone archive check has no predecessors and no dependents, it still appears once in the plan. A common incorrect implementation discovers nodes only by traversing edges and consequently loses isolated work. Explicit keys make task membership auditable and give the empty-list case a clear meaning.
from dependency_plan import plan_waves
graph = {
"publish": ["review", "test"],
"test": ["draft"],
"draft": [],
"review": ["draft"],
}
print(plan_waves(graph))
# (('draft',), ('review', 'test'), ('publish',))

3. Choose deterministic waves, not an arbitrary valid order
A dependency graph can have several valid topological orders. In the diamond, review may appear before test or after it because neither check depends on the other. Our planner groups both into one readiness wave and sorts their names within that wave. The result is three immutable tuples: drafting first, the two checks second, and publishing third. This makes a dry-run plan easier to compare in a code review.
The exact policy is important: take all currently ready tasks, sort them, record the whole group, mark that entire group as logically processed inside the planner, and repeat. Sorting dictionary keys at the start is useful for a stable snapshot, but sorting every ready group is what makes the visible tie rule explicit. We do not claim that the standard library’s incidental insertion order is a business priority.
These waves are layers of dependency readiness. In this lab, every task in a wave has all of its predecessors in earlier waves. A wave is not a claim that those tasks have equal duration, can safely share resources, or should all start together. If review and test both write to the same temporary directory, the graph alone cannot tell you whether concurrent execution is safe.
Flattening our waves produces a valid sequential topological order, but it is not necessarily the globally lexicographically smallest valid order. Consider independent roots a and z, with b depending only on a. The wave policy returns a and z together, then b. A different scheduler could finish a, immediately run b, and leave z until later. Both sequences obey the dependencies. The lab promises one clear wave policy, not every possible ordering preference.
Deterministic presentation is especially useful when an assistant proposes graph edits. Reordering keys or rearranging a predecessor list should not create a distracting plan diff. Adding a dependency can change the plan, but some changed edges leave the waves unchanged. Compare predecessor sets as well so reviewers can see changed constraints even when the presentation stays identical. The broader issue of explicit tie rules is covered in our guide to deterministic Python sorting, but here the dependency relationship remains the primary ordering rule.
4. Run the complete standard-library planner
The implementation below is the complete dependency_plan.py module from the downloadable lab. It uses two public exception types. InvalidGraph means the input failed our data contract. DependencyCycle means the contract was valid but the relationships contained a directed cycle. Keeping these outcomes separate lets an interface offer a useful correction: fix an identifier or shape in the first case, and investigate contradictory prerequisites in the second.
The snapshot function checks types before sorting or set membership can use a malformed value. It counts predecessor entries, rejects unknown names and duplicates, and copies each accepted list into a sorted tuple. It leaves the caller’s dictionary and lists unchanged. The returned plan contains only tuples and validated strings, so later edits to the original lists cannot retroactively change a completed result.
That copy is not an atomic snapshot under concurrent mutation. The caller must keep the dictionary and its predecessor lists unchanged throughout the call. If another thread or callback can alter the graph while validation runs, synchronization or a separately frozen input is required. A type check and a tuple conversion do not solve ownership of mutable data. State that assumption in the API rather than hiding it in a comment after a failure.
The planner constructs a TopologicalSorter from the validated snapshot and calls prepare before collecting any waves. If a cycle is found, it converts the library exception into our domain exception, preserving one closed cycle witness and the original exception as its cause. The function returns no partial plan. This full-graph gate is appropriate for a preflight report that promises the entire declared workflow can be ordered.
"""Validate a small predecessor graph and compute a deterministic dry-run plan."""
import re
from graphlib import CycleError, TopologicalSorter
MAX_TASKS = 64
MAX_EDGES = 256
_TASK_ID = re.compile(r"[a-z][a-z0-9_]{0,39}")
class InvalidGraph(ValueError):
"""The input violates the graph's deliberately narrow data contract."""
class DependencyCycle(ValueError):
"""The graph contains a cycle; .cycle is one closed tuple witness."""
def __init__(self, cycle):
self.cycle = tuple(cycle)
super().__init__("dependency cycle: " + " -> ".join(self.cycle))
def _valid_id(value):
return type(value) is str and _TASK_ID.fullmatch(value) is not None
def _snapshot(graph):
if type(graph) is not dict:
raise InvalidGraph("graph must be a built-in dict")
if len(graph) > MAX_TASKS:
raise InvalidGraph(f"graph has more than {MAX_TASKS} tasks")
if any(not _valid_id(task) for task in graph):
raise InvalidGraph("task IDs must match [a-z][a-z0-9_]{0,39}")
snapshot = {}
edges = 0
for task in sorted(graph):
predecessors = graph[task]
if type(predecessors) not in (list, tuple):
raise InvalidGraph(f"{task}: predecessors must be a built-in list or tuple")
edges += len(predecessors)
if edges > MAX_EDGES:
raise InvalidGraph(f"graph has more than {MAX_EDGES} edges")
seen = set()
for predecessor in predecessors:
if not _valid_id(predecessor):
raise InvalidGraph(f"{task}: invalid predecessor ID")
if predecessor not in graph:
raise InvalidGraph(f"{task}: undeclared predecessor {predecessor}")
if predecessor in seen:
raise InvalidGraph(f"{task}: duplicate predecessor {predecessor}")
seen.add(predecessor)
snapshot[task] = tuple(sorted(seen))
return snapshot
def plan_waves(graph):
"""Return sorted, immutable waves for task -> immediate predecessors.
InvalidGraph reports an invalid input contract; DependencyCycle reports a
cycle. No partial plan is returned. The caller must not mutate the graph or
its predecessor lists during this call. This function executes no tasks and
provides no thread-safety or concurrent-execution guarantee.
"""
snapshot = _snapshot(graph)
sorter = TopologicalSorter(snapshot)
try:
sorter.prepare()
except CycleError as exc:
raise DependencyCycle(exc.args[1]) from exc
waves = []
while sorter.is_active():
wave = tuple(sorted(sorter.get_ready()))
waves.append(wave)
sorter.done(*wave)
return tuple(waves)
Save the module, put the following demonstration beside it, and run it with Python. The example has no dependencies outside the standard library. The printed diamond plan should have draft in its first wave, review and test in its second, and publish in its third. The demonstration also shows a disconnected graph, an empty graph, an unknown predecessor, and a cycle next to an otherwise independent root.
"""Run with python demo.py. This is an offline plan, not a task runner."""
from dependency_plan import DependencyCycle, InvalidGraph, plan_waves
DIAMOND = {
"publish": ["review", "test"],
"test": ["draft"],
"draft": [],
"review": ["draft"],
}
CYCLE_WITH_ROOT = {"root": [], "a": ["b"], "b": ["a"]}
def main():
print("Diamond:", plan_waves(DIAMOND))
print("Disconnected:", plan_waves({"z": [], "a": [], "b": ["a"]}))
print("Empty:", plan_waves({}))
try:
plan_waves({"publish": ["missing"]})
except InvalidGraph as exc:
print("InvalidGraph:", exc)
try:
plan_waves(CYCLE_WITH_ROOT)
except DependencyCycle as exc:
print("DependencyCycle:", exc.cycle)
print("No partial plan returned, including the unrelated root")
if __name__ == "__main__":
main()
The reader download contains the implementation, demonstration, author tests, and a README with the exact run commands and scope. Use the download when you want the complete runnable files rather than copying individual blocks. The source shown here is checked against those files, so a successful test run should exercise the same algorithm you are reading.
Download the original Python dependency-graph lab, with the implementation, examples, tests and reader README. No third-party packages or credentials are needed.
Our verification ran the lab under CPython 3.12.14 and 3.13.5, both normally and with optimization enabled. Optimization testing is useful here because input validation must not depend on removable assert statements. The implementation raises ordinary exceptions for invalid data. These are local test results for the included code; they do not establish compatibility with every Python implementation, a future release, or an application-specific scheduler.
5. Treat a cycle witness as evidence, not an automatic repair
A directed cycle means a chain of prerequisites returns to its own starting point. If a waits for b and b waits for a, neither can be the first completed task. A self-dependency has the same problem with one node. The error’s cycle tuple repeats its first node at the end so the loop is explicit. Adjacent nodes in that witness follow the predecessor-to-dependent arrow direction used by the diagram.
There can be several cycles in one graph. Our exception preserves one witness supplied by graphlib; it does not enumerate all cycles, promise the shortest cycle, or guarantee a canonical representation across Python versions. A test should verify that the witness is closed and every reported edge exists. Asserting one exact starting node would over-specify a diagnostic detail that our API has not promised.
Now add a root with no prerequisites beside a two-node cycle. That root could be processed independently in some applications. Our planner still rejects the whole request, because its output is a complete preflight plan. Returning the root alone with a success label would hide the blocked work. If your product needs partial progress, expose that as a different result with an explicit list of unresolved nodes and a documented downstream policy.

Deleting a random edge is not a safe fix. The cycle might reveal an unnecessary review dependency, or it might show that one task contains two different stages that need to be separated. For example, a review task may both inspect a draft and approve a published result. Splitting those responsibilities could restore the intended ordering without removing a real requirement. The graph tells you where the contradiction is; a person who understands the workflow decides what it should mean.
Ask for evidence when a model proposes a repair. Which original requirement justifies changing this predecessor list? Which task becomes eligible earlier? What check proves that a required approval still precedes publication? A repair that merely makes the exception disappear can weaken a workflow. Preserve the failing graph and its witness as a regression fixture before accepting an intentional policy change.
6. Test graph properties as well as attractive examples
Start with small examples whose answers are obvious without running the implementation. The empty dictionary should return an empty tuple. One isolated task should produce one single-task wave. A chain should produce one task per wave. The diamond should put both checks together. Reversing the two-node dependency should reverse the expected order. These examples create a readable foundation for the more systematic checks.
Then verify membership. Flatten the output, confirm its length equals the number of declared tasks, confirm no task repeats, and confirm its set equals the input keys. This catches implementations that drop isolated nodes, invent undeclared nodes, duplicate a shared predecessor, or accidentally stop after the first ready group. Membership is necessary even when a few visible dependency edges appear in the right order.
Next verify precedence. Map each output task to its wave number. For every task and every predecessor, the predecessor’s wave number must be strictly smaller. Checking only a flattened order can miss the stronger wave contract, because two dependent tasks could appear in the same wave but happen to be listed in a superficially valid sequence. The wave index expresses exactly the promise made to the reader.
Readiness completeness needs its own check. At each step, independently calculate every remaining task whose predecessor set is contained in the already completed set. That whole sorted set must equal the emitted wave. A planner that emits one ready task at a time can satisfy membership and precedence while violating our grouping policy. An independent test oracle should state this set relationship directly instead of calling TopologicalSorter again.
Input-order invariance is another property. Shuffle dictionary insertion order and predecessor-list order while preserving the same relationships. The plan should remain identical. This test distinguishes semantic graph changes from changes in presentation. Keep the random seed or permutation enumeration reproducible so a failure can be replayed rather than disappearing into an unrecorded run.
Boundary tests should challenge the exact contract. Try a graph that is a list, a dependency value that is a bare string, an uppercase task name, a forty-one-character identifier, a boolean key, a custom string subclass, an unknown predecessor, a repeated predecessor, and inputs at and just beyond the node and edge caps. Do not accept a broad “raises something” assertion: a surprising TypeError may indicate validation happened too late.
Cycles deserve several shapes: a self-loop, two nodes, a longer loop, a loop with an independent root, and a graph containing more than one loop. Check that planning raises DependencyCycle rather than returning an incomplete tuple. Validate the reported witness against the original relationships without assuming which loop the library discovers first. A disconnected valid component must not turn a failed whole-graph preflight into a successful result.
The included suite also uses systematic small-graph checks and deliberately defective implementation copies. Those checks are useful because a test suite can pass simply by sharing the same misconception as its implementation. Removing a required guard or weakening the ready-group policy should be noticed. A caught mutation is evidence about that particular fault, not proof that every possible mistake will be detected.
Keep expected outcomes separate from the model’s explanation. If DeepSeek proposes a new edge-case test, first write down what the graph contract requires and why. Then run the test locally. Our property-based testing workflow explores the same habit of checking general relationships; the lab here stays within the standard library and does not require Hypothesis.
7. Give DeepSeek a bounded review task
A useful review prompt includes the representation, rejection rules, exact output policy, and a small example with a manually established answer. Without those constraints, an assistant may supply a generic topological sort that accepts implicit nodes, silently deduplicates edges, or returns a different but valid order. Those choices might be appropriate elsewhere while failing the contract you actually need.
The first prompt below asks for counterexamples and contract mismatches before code changes. This keeps the review focused on observable behavior. Provide a short module or relevant excerpt that you are authorized to share, and replace private project names with synthetic identifiers where practical. Graph structure can reveal internal workflows even when there are no credentials in the file. Our data-minimization guide covers that preparation step in more detail.
Review this Python dependency planner against the contract below.
Do not rewrite it yet. Return concrete mismatches or say none found.
Input: built-in dict, task ID to built-in list/tuple of predecessors.
IDs: exact strings matching [a-z][a-z0-9_]{0,39}.
All predecessors must be declared. Reject duplicates.
Limits: 64 tasks and 256 predecessor entries. Empty input is valid.
Output: tuple of all-ready waves, sorted within each wave.
Reject a cycle before returning a complete plan.
No task execution, concurrent mutation or scheduling guarantee.
For each finding: give the smallest input, the contract's expected
outcome, the code path, and a test that would distinguish the defect.
Do not claim to have run tests unless you actually have execution tools.
The second review stage is to challenge tests. Ask for one graph that would pass membership and precedence checks while violating readiness completeness, or one mutation the current suite would miss. This is a more specific request than “make the tests comprehensive.” It invites a falsifiable example. You can then decide whether the proposed example belongs inside the accepted input contract.
Do not use a model response as evidence that a cycle repair is semantically correct. Supply the relevant fictional requirements and ask the model to list alternative interpretations, each with the prerequisite it would change and the consequence of that change. The reviewer can help organize choices; it cannot infer an organization’s approval policy from a cycle alone. Keep proposed repairs separate from approved requirements and test fixtures.
When you accept an implementation change, rerun the full suite and compare the public behavior. Does the empty case still work? Do error types remain consistent? Does a cycle still fail before output? Does reordering the same graph preserve waves? A neat refactor can accidentally broaden input types or change a rejection into silent normalization. Reviewing the diff against these questions is more useful than judging whether the new code is shorter.
No API integration is necessary to understand the lab. If you automate review later, current DeepSeek documentation describes how chat messages produce model responses, but your application still owns input selection, result validation, permissions, and execution. Keep a proposed graph edit as data until it has passed your review process. A suggested node called deploy or publish must not become an executable action merely because a model included it in a plan.
8. Know what changes when a plan becomes a scheduler
Our call to done is a bookkeeping step inside a dry run. It says that the planner has finished placing that wave, not that a real task succeeded. Reusing the loop as an execution engine without changing this meaning is a serious design mistake. A scheduler must decide what completion means and only release dependents when the required result has actually been established.
Suppose review fails while test succeeds. Publishing must remain blocked if both successful checks are required. Marking the failed review as done simply to keep a loop moving would release publication prematurely. On the other hand, never marking it done can leave a naive scheduler waiting forever. Failure handling requires explicit terminal outcomes and a policy for downstream tasks, separate from the mechanics of ordering.
Cancellation adds more questions. Can an already running task be interrupted? Does cancelling an upstream task cancel all dependents or mark them skipped? Can a retry reuse an earlier result? A dependency edge does not answer any of these. Our Python state-machine tutorial is relevant when designing those lifecycle decisions, but the planner in this article intentionally contains no retry or cancellation engine.
Whole-wave execution also introduces a barrier. Imagine that a and z are initially ready, a finishes quickly, and b depends only on a. A real readiness-driven scheduler can start b while z continues. A runner that waits for the entire first wave to finish delays b unnecessarily. The printed wave plan is still valid, but it should not be mistaken for an optimal schedule or an estimate of elapsed time.
Resources form another independent constraint. Two ready tasks might need the same exclusive database migration lock, a limited connection pool, or a rate-limited service. A correct dependency graph can therefore offer more ready work than the environment can safely run. Concurrency limits, deadlines, fairness, and resource ownership belong in the execution design. The asyncio concurrency guide covers some of those runtime concerns without changing the graph contract.
Persistence is also absent. If the process exits, this module has no durable record of task results, no reconciliation with external effects, and no protection against two workers claiming the same task. Adding a database does not automatically solve those problems; the transition that records success and the side effect being recorded need a deliberate consistency strategy. Treat the lab as a small reasoning and validation component inside a larger system.
9. Review graph changes by their consequences
A useful graph diff lists added tasks, removed tasks, added prerequisites, and removed prerequisites. Reordering entries is noise under our contract. Adding a prerequisite can push a task into a later wave or introduce a cycle. Removing one can make a task eligible earlier. Those consequences give reviewers a better summary than a large dictionary diff with rearranged lines and no explanation.
For the publishing diamond, imagine removing test from publish’s predecessor list while retaining the test task. The graph may still be acyclic and all tasks may still appear in the output. Yet publication now depends only on review; the intended test requirement is gone. With this small graph, both checks happen to share a wave, which can hide the policy weakening in one printed plan. The original edge requirement must therefore remain a direct assertion.
This is a useful limit of outcome-only testing. An extra task added before test could expose the weakened prerequisite by moving test later, but you should not need a lucky graph shape to preserve a known requirement. Test structural requirements as well as plan properties. A valid topological order proves consistency with the supplied edges; it cannot prove that the author supplied the right edges in the first place.
Keep an approved graph and its expectations in version control or another reviewable record. When an intentional requirement changes, update the graph, its explanation, and its tests together. Avoid automatically overwriting expected plans with whatever a new implementation emits. Snapshot updates are decisions about changed behavior, even when the output is a short tuple rather than a complicated user interface.
A preflight report can make this process practical. Show the declared task count, edge count, sorted waves, and any validation error or cycle witness. Label it “dry-run plan” so readers do not confuse a diagram with execution evidence. If the input is rejected, preserve enough of the submitted graph to reproduce the problem without leaking private task names into public logs.
10. Practical questions and next exercises
Why not sort the task names alphabetically?
Alphabetical sorting ignores prerequisites. In a graph where build depends on fetch, it would put build first. Our planner uses lexical order only to break ties among tasks that are ready in the same wave. The distinction is easy to test with names deliberately chosen to disagree with dependency order. Friendly example names should not be allowed to hide an algorithm that has no graph logic.
Does a dependency graph have to be a tree?
No. The diamond has a shared predecessor and a task with two prerequisites. A tree-oriented traversal can duplicate shared work or assume a single parent. The membership and precedence tests are designed to catch those mistakes. Start with a graph representation that permits multiple predecessors rather than trying to infer dependency semantics from a folder hierarchy or nested list.
Should invalid input be normalized automatically?
Only when that is an explicit policy. Lowercasing a task name could merge two identifiers that the input author intended to distinguish. Removing a duplicate may conceal a generated configuration defect. Creating an unknown predecessor can make a typo appear valid. This lab rejects those cases so the correction happens where the requirement is known, before planning turns it into an apparently authoritative sequence.
What should I build as an exercise?
Add a read-only graph comparison function that reports changed predecessor sets while ignoring insertion order. Test it with the publishing diamond and a version that adds a final archive task. Then add a report that identifies every task affected downstream by a changed prerequisite. Keep both exercises free of task execution so you can evaluate graph reasoning without also designing a scheduler.
A second exercise is to write an independent readiness oracle using sets, then enumerate small graphs and compare outcomes. Include cyclic graphs and verify that the oracle and planner agree about the existence of a complete plan. The point is not to accumulate a huge test number. It is to turn each promised behavior into a check that would notice a plausible implementation error.
The reusable workflow is straightforward: define what an edge means, validate the declared task set, establish a tie policy, reject contradictions before returning a complete plan, and test both structure and output. DeepSeek can help propose questions and counterexamples along the way. The durable result is a graph contract and executable evidence that you can inspect without relying on the model’s confidence.
Sources & References
Primary documentation checked October 6, 2026. The workflow, examples, diagrams and lab are original. The Python references establish library behavior; the teaching contract and whole-graph rejection policy are choices made in this article.
- Python 3.13: graphlib and TopologicalSorter — predecessor representation, ready/done behavior and cycle witnesses
- Python 3.13: Sorting Techniques — explicit sorting behavior
- Python 3.13: re — full-string identifier validation
- Python 3.13: unittest — test cases, exception assertions and discovery
- Python 3.13: optimization command-line option — why validation must not depend on assert statements
- DeepSeek: Chat Completions API — message-based model responses for an optional review integration
