When a dependency sorter stalls, labeling every remaining task “cyclic” can send people to repair the wrong part of a workflow. A task may have no path back to itself and still be blocked because one of its prerequisites belongs to a cycle upstream.
Commercial disclosure: UNITED UAV sells the UD100 delivery aircraft. Its listing supplies the aircraft context and product image below. The software scenario in this article is a hypothetical ground-side document-review tool for a delivery-aircraft integration. It is not a UD100 native feature, device protocol or operational approval procedure.
We will build a pure Python diagnostic that returns three things: a deterministic removable prefix, the tasks that actually belong to directed cycles, and the remaining tasks blocked downstream. The distinction makes an error report more actionable without pretending that sorting a graph executes its tasks or establishes that their outputs are correct.
Start with the meaning of a dependency edge
In this example, each task prepares or reviews an office document. A configuration outline might precede a document check, which might precede assembling a handoff package. The application stores each task together with its immediate prerequisites. An entry for handoff containing document_check means that document_check must come before handoff.
Draw the arrow from prerequisite to dependent. Reversing that arrow changes what “downstream” means and can make a correct algorithm produce an irrelevant diagnosis. Keep the orientation explicit at the adapter boundary rather than relying on the direction suggested by a variable name.
The Python graphlib documentation uses a mapping from nodes to their predecessors. It also allows progress on ready nodes after cycle detection has failed. Those are useful distinctions when deciding what a dependency failure means; our diagnostic uses its own implementation and output contract.
The UD100 listing distinguishes an optional descent-device configuration. A document tool might therefore need configuration-specific review tasks. That is a reason to preserve the selected configuration in a real application's evidence, not evidence that UD100 supplies the task graph invented here. All task names and dependencies below are authored examples.
Separate structural order from completion and approval
The diagnostic treats an edge as an ordering constraint. Removing a node from the graph means it can appear in a structurally valid sequence after its predecessors. It does not mean a reviewer has performed the work, a file exists, or a result has been accepted.
That distinction matters for task names such as inspection_report or configuration_review. A graph can contain those labels without containing any actual report or review evidence. Displaying the removable prefix as “completed” would turn a static analysis result into an unsupported workflow event.
A real executor needs separate state for queued, running, failed and completed work, plus an appropriate definition of completion. If a task fails during execution, its dependents may be blocked for a different reason from a structural cycle. The function here receives no runtime state and consequently makes no claim about those failures.
For the same reason, this article does not use the graph to approve a flight, a load, an installation or a delivery. The software boundary is narrower: given a declared document dependency graph, identify which structural obstruction prevents a complete ordering and which nodes merely inherit that obstruction.
Build a counterexample with a downstream victim
Consider four tasks. Outline has no prerequisites. Review requires checklist, while checklist requires review. Handoff requires review. Outline can be removed immediately. Review and checklist cannot start because each waits for the other, so they form a directed cycle.
Handoff also remains after elimination stops. However, it is not itself on a cycle: there is no path from handoff back to review or checklist. Its problem is inherited. Asking the owner of handoff to remove a local circular dependency would misdescribe the evidence.
Removing an arbitrary prerequisite from handoff would let the sorter produce a longer order while potentially discarding the document requirement that made the package meaningful. A diagnostic should explain the obstruction, leaving changes to the dependency contract to the people responsible for that contract.
The example also shows why reporting just one detected cycle is not the same as classifying all remaining tasks. A graph can have several independent cycles, paths joining cycles, and ordinary descendants. A useful report should state whether it contains a witness path, all cycle members, or a broader unresolved region.
Reject missing task identities before diagnosing cycles
The input contract is a dictionary from task identifiers to lists or tuples of prerequisite identifiers. Identifiers follow a small ASCII profile: a lowercase letter followed by up to sixty-three lowercase letters, digits or underscores. Human-readable labels can be stored separately from these comparison keys.
Every referenced identifier must also be declared as a dictionary key. A misspelled prerequisite is rejected rather than silently created as an independent task. That behavior is deliberate: inventing a node with no prerequisites can make a broken document contract look schedulable.
Repeated prerequisites are normalized into a set. They express the same ordering constraint, not multiple required completions. A self-reference remains present and is correctly treated as a cycle of length one. An empty dictionary is a valid empty graph and produces three empty results.
This validator runs after the input has become a Python dictionary. It cannot recover duplicate keys that a permissive JSON decoder has already overwritten. A JSON adapter requiring unique keys must reject them during decoding. Schema validation should preserve defects long enough to report them, rather than repairing them by losing information.
import re from heapq import heapify, heappop, heappush def dependency_report(predecessors): if type(predecessors) is not dict: raise TypeError("dictionary required") def valid_id(value): return (type(value) is str and re.fullmatch(r"[a-z][a-z0-9_]{0,63}", value) is not None) if any(not valid_id(node) for node in predecessors): raise ValueError("invalid task identifier") known = set(predecessors) parents = {} for node, values in predecessors.items(): if type(values) not in (list, tuple): raise TypeError("prerequisites must be a list or tuple") if any(not valid_id(value) for value in values): raise ValueError("invalid prerequisite identifier") deps = frozenset(values) if not deps <= known: raise ValueError("undeclared prerequisite") parents[node] = deps children = {node: set() for node in parents} for node, deps in parents.items(): for parent in deps: children[parent].add(node) degree = {node: len(deps) for node, deps in parents.items()} ready = [node for node, count in degree.items() if count == 0] heapify(ready) order = [] while ready: node = heappop(ready) order.append(node) for child in children[node]: degree[child] -= 1 if degree[child] == 0: heappush(ready, child) residual = known - set(order) cyclic = set() for start in residual: stack = list(children[start] & residual) seen = set() while stack: node = stack.pop() if node == start: cyclic.add(start) break if node not in seen: seen.add(node) stack.extend((children[node] & residual) - seen) return { "order": tuple(order), "cyclic": tuple(sorted(cyclic)), "blocked_descendants": tuple(sorted(residual - cyclic)), } Make the removable prefix deterministic
The first stage is Kahn elimination. Count each node's prerequisites, put zero-count nodes in a ready collection, remove one, and decrement the counts of its children. A child becomes ready when its remaining count reaches zero.
A heap makes the next choice deterministic: among currently ready identifiers, remove the lexicographically earliest one. The Python heapq documentation describes the min-heap operations used here. Only the ordinary min-heap interface is needed; the code does not rely on newer max-heap additions.
The child sets can be traversed in different orders without changing the result. All children made ready by one removal enter the heap before the next removal occurs. The heap then applies the same identifier ordering regardless of dictionary insertion order or set traversal order.
This is deterministic serialization of a partial order, not a priority policy. It does not minimize duration, choose an operator or allocate resources. Two independent reviews might run concurrently in another application. Their ordering here simply gives tests, exported reports and repeated diagnostics a stable representation of the same structural result.
Ask whether a positive-length path returns to its start
When elimination stops, restrict attention to the residual nodes. For each residual node, follow outgoing edges looking for a return to that starting node. Such a return establishes membership in a directed cycle. A self-edge satisfies the same rule without a special cycle-length exception.
The search begins with the starting node's children, rather than declaring the start reachable before traversing any edge. That detail distinguishes a positive-length path from the trivial zero-edge path from every node to itself. If the latter counted, every node would be incorrectly classified as cyclic.
The search is iterative and maintains visited nodes, so reaching another cycle does not cause an infinite traversal. A downstream victim can reach other nodes without ever returning to itself; it therefore remains outside the cyclic set even though it could not be eliminated.
Searching only the residual does not hide a relevant cycle. Nodes actually belonging to cycles never reach zero remaining indegree during elimination. Removed nodes cannot provide the missing return path that would make a residual node cyclic. The cycle's own edges keep its members in the residual throughout the process.
Read the worked report without changing its meaning
Run the following after the implementation. It checks the independent outline task, the two actual cycle members, the downstream handoff task and a self-cycle. The returned tuples are identifiers, not assertions that any document has been produced.
tasks = { "outline": [], "review": ["checklist"], "checklist": ["review"], "handoff": ["review"], } assert dependency_report(tasks) == { "order": ("outline",), "cyclic": ("checklist", "review"), "blocked_descendants": ("handoff",), } assert dependency_report({"review": ["review"]}) == { "order": (), "cyclic": ("review",), "blocked_descendants": (), } assert dependency_report({}) == { "order": (), "cyclic": (), "blocked_descendants": (), } For a finite declared graph, every residual non-cycle node is downstream of at least one cycle. To see why, trace a remaining predecessor backward. Every residual node still has a residual predecessor. Continuing through a finite set eventually repeats a node, establishing a cycle with a forward path to the original node.
That reasoning depends on the input contract. Unknown external prerequisites are rejected earlier; unresolved runtime approvals are not encoded here. Without those distinctions, “blocked descendant” could misleadingly combine structural defects with absent documents or incomplete external work.
Validate the classification with an independent oracle
Testing only another traversal that resembles the implementation risks repeating the same mistake. A different oracle can construct a Boolean reachability matrix, initially marking only actual directed edges, then calculate transitive closure. Do not initialize its diagonal as reachable merely because a node exists.
A true diagonal entry after closure identifies a positive-length return path and therefore a cycle member. Nodes reachable from those members, including the members themselves, form the expected residual. Subtract the cycle-member set to obtain the expected blocked descendants. Everything else should appear in the removable prefix.
For small graphs, also enumerate permutations of all nodes. Take the valid initial prefix of each permutation, stopping where a task's predecessors are not yet present. Among prefixes of maximum length, the lexicographically earliest one should match the function's deterministic order. This oracle explores possible orders rather than implementing another indegree reducer.
An exhaustive bounded suite can cover all 4,096 loop-free directed graphs on four labeled nodes, plus all 512 directed graphs on three labeled nodes when self-edges are allowed. These populations contain disconnected components, several cycles, paths between cycles and downstream victims. Separate invalid-input and duplicate-prerequisite checks exercise the representation boundary.
Keep cycle membership separate from cycle explanations
The function returns all identifiers belonging to at least one cycle. It does not group them into strongly connected components, return every cycle, or provide a witness path for each blocked task. A flat sorted tuple of cycle members should not be displayed as though its adjacent identifiers form an actual cycle.
For example, two disconnected cycles may produce four identifiers in one tuple. Connecting those four identifiers in the displayed order would invent edges. A UI needing an explanation path must obtain that path from an additional operation over the original graph and label what was actually established.
Similarly, a blocked task may be downstream of several separate cyclic components. Naming one upstream cause does not establish that fixing that cause will unblock the task. Another obstruction may remain. Preserve the complete graph when preparing a repair discussion rather than reducing the report to one chosen culprit.
For a larger dependency service, a strongly connected component algorithm is an appropriate alternative to repeated searches. This small implementation favors a directly inspectable membership criterion. Changing the algorithm should preserve the classification contract and be checked against the same independent reachability oracle.
Account for graph size and snapshot consistency
Building adjacency and performing heap-based elimination costs linear work in the number of edges plus logarithmic heap work per node. With fixed-size identifier comparisons, that stage is proportional to the edge count plus the node count times its logarithm.
The repeated residual searches are more expensive: in the worst case, each residual node explores the residual graph. Their work is proportional to the residual node count multiplied by the sum of residual nodes and edges. Keep that tradeoff explicit when adapting the example beyond a small document pipeline.
The function reads an in-memory graph and does not manage concurrent edits. An application should analyze a stable graph revision, preserve that revision with the report, and invalidate the diagnosis when dependencies change. Combining half of one revision with half of another could create a cycle that never existed in either complete revision.
Also limit graph size and input bytes at the application's intake boundary. Iterative traversal avoids Python recursion depth as a failure mode, but it does not remove memory or processing costs. A resource limit and a structural cycle are different outcomes and should remain different messages to the caller.
Repair the declared requirement rather than hiding the error
After a cycle report, a reviewer can inspect the edges between cyclic tasks and ask which requirement was intended. Perhaps review depends on a checklist template while checklist completion depends on review feedback, and those two different artifacts were represented by one identifier. Splitting the concepts may correct the model; arbitrarily deleting an edge may conceal it.
Keep the old graph revision and the decision behind any correction. Re-run diagnosis on the complete revised graph. A previously blocked descendant may become removable, but that observation still does not establish that its prerequisite documents have passed substantive review.
An error interface can show cyclic identifiers in one group and downstream blocked identifiers in another, with the stable graph revision alongside them. Use “structurally orderable” for the returned prefix and reserve completion language for evidence produced by a real executor or reviewer.
That gives a UD100-related document tool a useful, limited contract: explain why its declared review ordering cannot finish, avoid falsely accusing downstream tasks of circularity, and retain enough structure for a reviewed correction. The aircraft's operational capabilities remain questions for their own technical evidence.
AI assisted drafting and code review. The implementation and worked assertions were executed against the exhaustive synthetic graph populations and independent closure/permutation checks described above. No UD100 device interface, flight operation, customer review package or approval authority was exercised for this article.
