Fault-Tolerant Task Dispatcher with Retry Limit and Dependencies
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a job queue where failed jobs retry up to a limit, then go to a dead-letter list, and failures cascade to jobs that depend on them.
Task Dispatcher Simulation
A dispatcher hands out jobs to workers. Workers can finish a job or report that it failed. A job that fails too many times is shelved permanently, and any job that needs a shelved job is shelved with it.
You are given a limit max_attempts and a script of operations to run in order. Return what each operation produces.
Operations
Operation i has the name operations[i] and the argument list arguments[i].
| Operation | Arguments | Effect |
|---|---|---|
"submit" | [job_id, payload] or [job_id, payload, deps] | Registers a new job. deps is a list of job IDs that must be completed first. It may be missing or null, which means no dependencies. |
"reserve" | [] | Gives the next eligible job to a worker (see below). |
"complete" | [job_id] | Marks a currently reserved job as finished. |
"fail" | [job_id] | Reports that a currently reserved job failed. |
"dead_letters" | [] | Reports every shelved job so far. |
Job life cycle
Each job starts with 0 failed attempts and is waiting. It can become reserved, complete, or shelved (permanently dead).
Queue order. The dispatcher keeps one waiting line. A job joins the back of the line when it is submitted, whether or not its dependencies are satisfied. A job whose retry is granted also rejoins the back of the line.
Eligibility. A waiting job is eligible only if every ID in its deps belongs to a job that is complete. A dependency ID may refer to a job that has not been submitted yet. In that case the dependency is not satisfied until that job is submitted and completed.
reserve. Scan the line from front to back and take the first waiting job that is eligible. Remove it from the line, mark it reserved, and output [job_id, payload]. Jobs that are skipped because they are not eligible keep their place in line. If no job is eligible, output null.
complete. If job_id is currently reserved, it becomes complete. Otherwise (unknown ID, or any other state) nothing happens.
fail. If job_id is currently reserved, increase its attempt count by one.
- If the new count is less than
max_attempts, the job goes back to waiting at the back of the line. - Otherwise the job is shelved.
If job_id is not currently reserved, nothing happens.
Shelving and cascading. When a job is shelved, every job that lists it in deps and is not already shelved or complete is shelved too, and so on through chains of dependents. The shelving order is breadth-first: the failing job first, then its direct dependents in the order they were submitted, then their dependents, and so on. A shelved job never runs again.
Also, if a job is submitted and any of its deps is already shelved, the new job is shelved immediately (and the cascade applies to jobs that were already waiting on this ID).
dead_letters. Output a list of all shelved job IDs in the order they were shelved.
Output
Return a list with one entry per operation:
submit,complete,fail:null(None).reserve:[job_id, payload]ornull.dead_letters: a list of job IDs (possibly empty).
Constraints
1 <= max_attempts.- Job IDs are strings and are unique among
submitoperations. operationsandargumentshave the same length.- A job never depends on itself, and dependencies are acyclic.
completeandfailmay name unknown jobs or jobs that are not reserved. These are silently ignored.- Payloads are opaque values returned exactly as submitted.
Examples
Example 1
Input: simulate_job_dispatcher(2, ['submit', 'submit', 'reserve', 'fail', 'reserve', 'fail', 'dead_letters', 'reserve'], [['cover', 'cover page'], ['bind', 'bind booklet', ['cover']], [], ['cover'], [], ['cover'], [], []])
Output: [None, None, ['cover', 'cover page'], None, ['cover', 'cover page'], None, ['cover', 'bind'], None]
Example 2
Input: simulate_job_dispatcher(3, ['submit', 'submit', 'reserve', 'reserve', 'complete', 'reserve', 'complete', 'dead_letters'], [['a', 'A'], ['b', 'B', ['a']], [], [], ['a'], [], ['b'], []])
Output: [None, None, ['a', 'A'], None, None, ['b', 'B'], None, []]
Example 3
Input: simulate_job_dispatcher(2, ['submit', 'submit', 'reserve', 'fail', 'reserve', 'complete', 'reserve', 'complete', 'dead_letters'], [['first', 'x', ['later']], ['later', 'y'], [], ['later'], [], ['later'], [], ['first'], []])
Output: [None, None, ['later', 'y'], None, ['later', 'y'], None, ['first', 'x'], None, []]
Hints
Hint 1
Track a state per job (waiting, reserved, complete, shelved) plus an attempt counter, and keep a separate list of the order in which jobs were shelved.
Hint 2
Keep a reverse map from each dependency ID to the jobs that list it, and fill it at submit time even when the dependency does not exist yet. Then a shelving event can walk straight to the affected jobs.
Hint 3
Do not remove shelved jobs from the waiting line. Leave them in place and check each job's current state during the front-to-back scan in reserve. Use a breadth-first queue for the cascade so the shelving order matches the statement.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Simulate the dispatcher directly with a small state machine per job.
Data kept
jobs: for each ID, its payload, dependency list, attempt count, and state (queued,reserved,complete,poison).dependents: a reverse map from a dependency ID to the jobs that list it. It is filled at submit time, even if the dependency has not been submitted yet.queue: a deque of IDs in line order.shelved: the IDs in the order they were shelved.
Operations
submitrecords the job, appends it to the back of the line, and registers it independents. If any dependency is already shelved, the job is shelved immediately.reservescans the line front to back for the first job that isqueuedand whose dependencies are allcomplete. It removes that job from its position, marks itreserved, and returns[id, payload]. Skipped jobs keep their positions. If none qualifies, it returnsNone.completemoves a reserved job tocomplete. Any other state is ignored.failincrements the attempt counter of a reserved job. If the counter is still belowmax_attempts, the job returns toqueuedat the back of the line. Otherwise it is shelved.- Shelving runs a breadth-first search from the job through
dependents. Each job not already shelved or complete is marked shelved and appended toshelved. BFS gives the specified order, handles chains of any depth, and avoids recursion limits. dead_lettersreturns a copy ofshelved.
Why it is correct
Eligibility is evaluated at the moment of each reserve from the current states, so a dependency that is not yet submitted, not yet complete, or shelved is handled uniformly. A shelved job is never queued, so it is never handed out even though its ID may still sit in the line. The reverse map ensures that every job that could never succeed is shelved at the moment its prerequisite is shelved, including prerequisites submitted after their dependents.
Complexity
Let n be the number of jobs and E the number of dependency edges.
submitcostsO(d)forddependencies.reservescans the line,O(n·d)in the worst case.completeisO(1).failisO(1)for a retry. A shelving cascade touches each affected job and edge once, so all cascades together costO(n + E)over the whole run.- Space is
O(n + E).
Reference solution
from collections import deque
from typing import List
def simulate_job_dispatcher(max_attempts: int, operations: List[str], arguments: List[List[object]]) -> List[object]:
jobs = {}
dependents = {}
queue = deque()
shelved = []
results = []
def shelve(job_id):
pending = deque([job_id])
while pending:
current = pending.popleft()
job = jobs.get(current)
if job is None or job["state"] in ("poison", "complete"):
continue
job["state"] = "poison"
shelved.append(current)
for child in dependents.get(current, []):
child_job = jobs.get(child)
if child_job is not None and child_job["state"] not in ("poison", "complete"):
pending.append(child)
def eligible(job):
return all(jobs.get(dep, {}).get("state") == "complete" for dep in job["depends"])
for operation, args in zip(operations, arguments):
if operation == "submit":
job_id = args[0]
payload = args[1]
deps = list(args[2]) if len(args) >= 3 and args[2] is not None else []
jobs[job_id] = {
"payload": payload,
"depends": deps,
"attempts": 0,
"state": "queued",
}
queue.append(job_id)
for dep in deps:
dependents.setdefault(dep, []).append(job_id)
if any(jobs.get(dep, {}).get("state") == "poison" for dep in deps):
shelve(job_id)
results.append(None)
elif operation == "reserve":
selected = None
for index in range(len(queue)):
job = jobs.get(queue[index])
if job is not None and job["state"] == "queued" and eligible(job):
selected = index
break
if selected is None:
results.append(None)
else:
queue.rotate(-selected)
job_id = queue.popleft()
queue.rotate(selected)
job = jobs[job_id]
job["state"] = "reserved"
results.append([job_id, job["payload"]])
elif operation == "complete":
job = jobs.get(args[0])
if job is not None and job["state"] == "reserved":
job["state"] = "complete"
results.append(None)
elif operation == "fail":
job_id = args[0]
job = jobs.get(job_id)
if job is not None and job["state"] == "reserved":
job["attempts"] += 1
if job["attempts"] >= max_attempts:
shelve(job_id)
else:
job["state"] = "queued"
queue.append(job_id)
results.append(None)
elif operation == "dead_letters":
results.append(list(shelved))
return results