Sub topic 4
Checking the network before you calculate
This chapter assumes you can describe a project as tasks with durations and predecessors, and that you know what the forward and backward passes compute. The code uses basic Python: dictionaries, loops, and functions. Here you learn to test the network for structural faults before you run any pass.
Why validate first
The forward and backward passes trust their input. They don't stop and warn you when the network is wrong. Most of the time they return numbers that look reasonable and are wrong.
A few examples of what a faulty network does:
- A task with a forgotten successor looks like it can slip, because nothing downstream depends on it. Its float is too large.
- A task with a typo in a predecessor name either crashes the calculation or, in a tool that ignores unknown names, silently loses the dependency.
- A circular dependency has no earliest start at all. The forward pass cannot begin, or it loops forever.
- A disconnected piece of the plan is computed on its own, so it never affects the project end date.
Validating costs little compared with presenting a critical path built on a broken network.
What a valid network looks like
A network that is ready for calculation meets five conditions:
- Every predecessor named in a task refers to a task that exists.
- No task lists itself as a predecessor.
- The dependencies contain no cycle. A cycle is a chain of tasks that leads back to where it started, such as B needs D and D needs B.
- Every durations is a number that is zero or greater. Zero is legitimate for milestones.
- The network has the open ends you intend and no others.
The last condition needs some explanation.
Open ends
An open start is a task with no predecessors. An open end is a task with no successors. A normal project network has exactly one of each: a start and a finish. Tools often enforce this by adding a start milestone and a finish milestone.
Every extra open start or open end is a question for the planner. There are two common answers:
- It is intended. A task such as "order office chairs" really can start on day 0, and a deliverable such as "handover document" really is the last thing anyone does. Both are fine.
- It is a missing link. Someone forgot to say what the task feeds into or what it waits for. This is the dangerous case.
A missing successor is the worse of the two. The backward pass sets the latest finish of any task without successors to the project end date. The task then looks as if it has all the time in the world, and the forgotten dependency never shows up as a constraint.
A task that is both an open start and an open end is isolated. It touches nothing else in the network, so it can never be on the critical path. Either it is irrelevant to the project or a dependency is missing.
Detecting cycles
A cycle makes the calculation impossible. If B waits for D and D waits for B, neither can start first.
The standard detection method is a topological sort, using Kahn's algorithm:
- Count each task's incoming dependencies (its in-degree).
- Put every task with in-degree zero in a queue. These are the tasks that have nothing left to wait for.
- Take a task from the queue and add it to the ordered list. For each of its successors, reduce the in-degree by one. A successor that reaches zero joins the queue.
- When the queue is empty, compare the length of the ordered list with the number of tasks.
If the lists have the same length, the network has no cycle, and the ordered list is a valid order for the forward pass. If some tasks are missing, they could never reach in-degree zero. Each missing task is on a cycle or downstream of one.
That order is a bonus. The forward pass needs predecessors processed before successors. The first Topic Spine example relies on you listing tasks that way by hand. A topological sort produces that order for you.
The cycle check comes after the name and duration checks because it needs valid links to count in-degrees.
A validator in Python
The function below runs all the checks described above. It uses the same task format as the earlier examples: a dictionary mapping a task name to a tuple of duration and list of predecessors.
from collections import deque
def check_network(tasks):
errors, warnings = [], []
succs = {t: [] for t in tasks}
indegree = {t: 0 for t in tasks}
has_pred = {t: False for t in tasks}
for t, (dur, preds) in tasks.items():
if dur < 0:
errors.append(f"{t}: negative duration {dur}")
seen = set()
for p in preds:
if p == t:
errors.append(f"{t}: lists itself as a predecessor")
elif p not in tasks:
errors.append(f"{t}: unknown predecessor '{p}'")
elif p in seen:
warnings.append(f"{t}: predecessor '{p}' listed twice")
else:
seen.add(p)
succs[p].append(t)
indegree[t] += 1
has_pred[t] = True
# Kahn's algorithm: tasks that never reach in-degree 0 are stuck.
queue = deque(t for t in tasks if indegree[t] == 0)
order = []
while queue:
t = queue.popleft()
order.append(t)
for s in succs[t]:
indegree[s] -= 1
if indegree[s] == 0:
queue.append(s)
if len(order) < len(tasks):
stuck = [t for t in tasks if t not in order]
errors.append(
f"cycle: {', '.join(stuck)} cannot be ordered "
"(on a cycle or downstream of one)"
)
for t in tasks:
if not has_pred[t] and not succs[t]:
warnings.append(f"{t}: isolated, no predecessors and no successors")
starts = [t for t in tasks if not has_pred[t]]
ends = [t for t in tasks if not succs[t]]
if len(starts) > 1:
warnings.append(f"multiple start tasks: {', '.join(starts)}")
if len(ends) > 1:
warnings.append(f"multiple end tasks: {', '.join(ends)}")
return errors, warnings, order
def report(name, tasks):
errors, warnings, _ = check_network(tasks)
print(f"{name}: {len(errors)} errors, {len(warnings)} warnings")
for m in errors:
print("ERROR", m)
for m in warnings:
print("WARN", m)
good = {
"A": (3, []),
"B": (2, ["A"]),
"C": (4, ["A"]),
"D": (3, ["B", "C"]),
}
broken = {
"A": (3, []),
"B": (2, ["A", "D"]), # B waits for D ...
"C": (4, ["A"]),
"D": (3, ["B", "C"]), # ... and D waits for B: a cycle
"E": (2, ["Z"]), # Z does not exist
"F": (1, []), # not connected to anything
}
report("good", good)
report("broken", broken)Running it prints:
good: 0 errors, 0 warnings
broken: 2 errors, 3 warnings
ERROR E: unknown predecessor 'Z'
ERROR cycle: B, D cannot be ordered (on a cycle or downstream of one)
WARN F: isolated, no predecessors and no successors
WARN multiple start tasks: A, E, F
WARN multiple end tasks: E, FSeveral details are worth studying in this code:
- An invalid predecessor is skipped when edges are built. That keeps the cycle check from crashing on a task named
Z. - The
has_predflag records valid predecessors, so task E counts as an open start. Its only dependency was a typo. - The cycle error lists every stuck task, not only the ones on the cycle. If task G depended on D, G would be listed too. Look at the dependencies among the listed tasks to find the actual loop.
- The function returns
order. For a valid network, you can use it as the processing order for the forward pass.
Edge cases
Some faults pass these checks and still cause trouble.
Duplicate task names. A Python dictionary literal with a repeated key keeps the last value and discards the earlier one without a warning. If your tasks come from a spreadsheet or a project tool export, check for duplicate IDs before building the dictionary.
Redundant dependencies. If A precedes B, B precedes D, and A also precedes D directly, the link A to D is redundant. It does not change any date. It does clutter the network and can cause confusion when someone later removes B. It is a style problem, not an error.
Zero-duration tasks. Milestones have zero duration. They are valid, and they are a good way to give the network a single start and finish. A zero-duration task that is not a milestone is worth a question.
Unit mismatches. A network where one task is in days and another in weeks produces a path length that adds numbers with different meanings. The code cannot detect this. Convert every duration to one unit when you load the data.
Dependencies that are not finish-to-start. The checks here assume the common finish-to-start link. Other link types and lags are covered in a later chapter. The cycle and unknown-name checks still apply, but a start-to-start link needs care when you define which tasks count as an open end.
Common mistakes
- Fixing the warning but not the cause. Adding a link to remove an open-end warning just to silence it creates a false dependency. Ask what the task really feeds into.
- Using a successor list to detect open starts. A task with no predecessors can still have successors. Check predecessors for starts and successors for ends.
- Ignoring the stuck list after a cycle error. The error names all affected tasks. Some of them are only downstream of the loop and need no change once the loop is fixed.
Summary of the checks
| Check | Finds | Severity |
|---|---|---|
| Unknown predecessor name | Typos, deleted tasks | Error |
| Self-reference | A task that depends on itself | Error |
| Negative duration | Data entry mistakes | Error |
| Cycle (Kahn's algorithm) | Circular dependencies | Error |
| Isolated task | Missing links in both directions | Warning |
| Multiple open starts or ends | Possible missing links | Warning |
| Duplicate predecessor | Redundant entries | Warning |
Exercise
A network is P (2 days, no predecessors), Q (3 days, after P), R (1 day, after Q and S), S (2 days, after R). Which task names would the validator list in its cycle error, and why is P not listed?
Show answer
It lists R and S. P has in-degree 0, so it is ordered first. Q's only predecessor, P, is then ordered, so Q is ordered next. R needs both Q and S, and S needs R, so neither R nor S ever reaches in-degree 0. P and Q are ordered normally, so they are not stuck.
Exercise
A task "Print manuals" (4 days) follows "Final text" but has no successors, although the manuals must be finished before "Launch". What happens to its float in the backward pass, and what should you do?
Show answer
With no successors, its latest finish is set to the project end date, so its total float is far larger than the truth. It looks like it can slip without affecting the launch. Add the missing link from "Print manuals" to "Launch" and recalculate. Its float then drops, and it may lie on or near the critical path.