DAG Workflow Registration and Execution Service
Medium · Software Engineering Fundamentals · Machine Learning Engineer · Onsite
Problem Statement
Design and implement an in-memory workflow registration and DAG execution service (WorkflowService) together with a thin HTTP request dispatcher (handle_request). In a live coding session paired with an AI coding tool, you are evaluated on disciplined engineering — locking down a crisp specification and test checklist upfront, validating static invariants at registration time, isolating core domain logic from HTTP parsing, and auditing generated code against hand-computed expectations.
starter.py provides the built-in action registry DEFAULT_ACTIONS (ActionTable = Dict[str, Tuple[Callable[[dict, dict, dict], Any], List[str]]]), where each entry maps an action name to (callable_fn, required_param_names) and invokes callable_fn(params, run_input, dep_outputs) (dep_outputs maps each upstream dependency step ID to its output):
"read_input"(requires["key"]): returnsrun_input[params["key"]]."add"(requires[]): sumsparams.get("value", 0)and all values indep_outputs.values()."multiply"(requires[]): multipliesparams.get("factor", 1)across all values indep_outputs.values()."fail"(requires[]): raisesRuntimeError(params.get("message", "step failed")).
Implement WorkflowService and handle_request with the following behavior:
WorkflowService.__init__(self, actions=None): UseDEFAULT_ACTIONSwhenactions is None, otherwise use the suppliedActionTable.WorkflowService.create_workflow(self, definition) -> str:- Validate
definitionbefore storing an immutable deep copy, returning sequential identifiers"wf-1","wf-2", and so on. - Top-level
definitionmust be adictcontaining a non-emptylist"steps"and an optionalstr"name". Each step must be adictwith a non-emptystr"id", a registeredstr"action", an optionaldict"params"(default{}), and an optionalList[str]"depends_on"(default[], with no repeated step IDs inside"depends_on"). - Reject invalid definitions by raising
ValidationError(errors)where each error dictionary is{"code": str, "message": str, "step": Optional[str]}, using codes:"invalid_definition"(non-dict definition, non-string"name", or missing/empty/non-list"steps"),"invalid_step"(non-dict step, missing/empty/non-string"id", non-dict"params", non-list or non-string"depends_on", or duplicate entries inside"depends_on"),"unknown_field"(unrecognized key ondefinitionor on a step),"unknown_action"("action"is not a registered string action name),"missing_param"(any required parameter of"action"is absent from"params"),"duplicate_step_id"(two steps share the same"id"),"missing_dependency"("depends_on"names a step ID not present in"steps"),"cycle"(one or more steps form a self-loop or circular dependency chain).
- Validate
WorkflowService.execute_workflow(self, workflow_id, run_input) -> dict:- Raise
NotFoundfor an unknownworkflow_id, and raiseValidationError(code"invalid_input") ifrun_inputis not adict. - Execute every step only after all of its dependencies have completed, regardless of step listing order, passing defensive copies of
params,run_input, and upstreamdep_outputsso in-place mutations cannot leak across sibling branches or runs. - If an action raises an exception or produces a non-standard JSON value (rejected by
json.dumps(output, allow_nan=False), such as aset,NaN, orInfinity), record that step as{"status": "failed", "output": None, "error": "<ExcType>: <message>"}. Any step with at least one non-"succeeded"dependency (whether"failed"or"skipped") is not called and receives{"status": "skipped", "output": None, "error": ...}, while independent steps still run. - Assign sequential IDs
"run-1","run-2", ... and return{"run_id": ..., "workflow_id": workflow_id, "status": "succeeded" | "failed", "steps": {step_id: {"status": ..., "output": ..., "error": ...}}}, where overall"status"is"succeeded"only when every step succeeded.
- Raise
handle_request(service, method, path, body_text) -> Tuple[int, dict]:POST /workflows: parse JSON body (""treated as{}), register the workflow, and return(201, {"id": workflow_id}).POST /workflows/<id>/runs: parse JSON body (must be a JSON object, else422), runservice.execute_workflow(<id>, body.get("input", {})), and return(200, run_result).- Return
404for unknown routes orNotFound,405whenmethod != "POST"on a valid route,400on malformed JSON syntax, and422{"errors": [...]}onValidationErroror non-object/runspayloads.
Examples
Example 1
Input:
definition = {
"name": "invoice_total",
"steps": [
{"id": "grand_total", "action": "add", "params": {"value": 5}, "depends_on": ["subtotal_taxed", "shipping"]},
{"id": "subtotal_taxed", "action": "multiply", "params": {"factor": 2}, "depends_on": ["base"]},
{"id": "shipping", "action": "add", "params": {"value": 10}, "depends_on": ["base"]},
{"id": "base", "action": "read_input", "params": {"key": "amount"}},
],
}
wf_id = service.create_workflow(definition)
run = service.execute_workflow(wf_id, {"amount": 20})
Output:
wf_id = "wf-1"
run = {
"run_id": "run-1",
"workflow_id": "wf-1",
"status": "succeeded",
"steps": {
"base": {"status": "succeeded", "output": 20, "error": None},
"subtotal_taxed": {"status": "succeeded", "output": 40, "error": None},
"shipping": {"status": "succeeded", "output": 30, "error": None},
"grand_total": {"status": "succeeded", "output": 75, "error": None},
},
}
Walk-through: Even though "grand_total" is listed first and "base" last, topological sorting runs "base" (20), then "subtotal_taxed" (2 * 20 = 40) and "shipping" (10 + 20 = 30), and finally "grand_total" (5 + 40 + 30 = 75).
Example 2
Input (via handle_request):
1) POST /workflows
{"steps": [
{"id": "fetch_quota", "action": "fail", "params": {"message": "upstream timeout"}},
{"id": "apply_quota", "action": "multiply", "params": {"factor": 3}, "depends_on": ["fetch_quota"]},
{"id": "audit_tag", "action": "add", "params": {"value": 42}}
]}
2) POST /workflows/wf-1/runs
{"input": {}}
3) POST /workflows
{"steps": [
{"id": "p", "action": "add", "depends_on": ["q"]},
{"id": "q", "action": "add", "depends_on": ["p"]}
]}
Output:
1) (201, {"id": "wf-1"})
2) (200, {
"run_id": "run-1",
"workflow_id": "wf-1",
"status": "failed",
"steps": {
"fetch_quota": {"status": "failed", "output": None, "error": "RuntimeError: upstream timeout"},
"apply_quota": {"status": "skipped", "output": None, "error": "dependency did not succeed: fetch_quota"},
"audit_tag": {"status": "succeeded", "output": 42, "error": None},
},
})
3) (422, {"errors": [{"code": "cycle", "message": "...", "step": None}]})
Walk-through: Step "fetch_quota" fails without crashing the HTTP endpoint (200 OK, overall run "failed"), downstream "apply_quota" is skipped, unrelated "audit_tag" still finishes with 42, and the circular p <-> q definition is rejected upfront at creation time with HTTP 422 ("cycle").
Constraints
1 <= V <= 10^4steps and0 <= E <= 5 * 10^4dependency edges per valid workflow (O(V + E)registration and scheduling).- Stored workflows must remain immutable even if the caller mutates the input dictionary after
create_workflowreturns. - Standard library only (
json,copy,collections,http.server); no external web frameworks.
Step-by-step walkthrough
Clarify requirements and scope for 45 minutes
In an AI-assisted coding interview, the interviewer is evaluating your engineering discipline — Plan -> Implement -> Verify — rather than how fast you paste one giant prompt. Spend the first 3–4 minutes resolving ambiguities and trimming scope so everything finishes cleanly inside 45 minutes:
- Graph structure: A workflow is a DAG (directed acyclic graph: a network of steps connected by one-way dependencies with no circular loops). A simple linear pipeline is just the special case where step
idepends on stepi - 1. We execute one ready step at a time sequentially; parallel execution is a natural follow-up. - Action model: Steps invoke named functions from a fixed server-side
ActionTableregistry (read_input,add,multiply,fail) rather than arbitrary user code or raw external URLs, avoiding untrusted-code sandboxing. - Execution mode:
execute_workflowruns synchronously and returns the completed run record. - Failure policy: If a step raises an exception, mark that step
"failed", mark every downstream step that depends on it"skipped", and still run independent branches so the caller gets maximum diagnostic signal; overall run status becomes"failed". - Storage & mutability: Store workflows and runs in memory behind
WorkflowService, and make stored workflows immutable (editing requires creating a new workflow ID).
- Graph structure: A workflow is a DAG (directed acyclic graph: a network of steps connected by one-way dependencies with no circular loops). A simple linear pipeline is just the special case where step
Draft a concrete contract first and stress-test edge cases
Ask the coding tool for a one-page specification before any implementation, explicitly pausing code generation until the schema and edge cases are settled. Once it drafts the data structures and routes, flip its role to adversarial reviewer: have it enumerate malformed or cyclic payloads and map each one to a deterministic error code (retaining real hazards like
"depend_on"key typos, self-loops, or"params": [1], and trimming unnecessary complexity like forcing empty"params"objects when defaults exist).Lock down the JSON schema, HTTP status contract, and test matrix upfront:
Workflow JSON (Example 1 — out-of-order diamond): {"name": "invoice_total", "steps": [ {"id": "grand_total", "action": "add", "params": {"value": 5}, "depends_on": ["subtotal_taxed", "shipping"]}, {"id": "subtotal_taxed", "action": "multiply", "params": {"factor": 2}, "depends_on": ["base"]}, {"id": "shipping", "action": "add", "params": {"value": 10}, "depends_on": ["base"]}, {"id": "base", "action": "read_input", "params": {"key": "amount"}}]} HTTP Endpoints: POST /workflows -> 201 {"id": "wf-1"} | 400 invalid JSON | 422 validation errors POST /workflows/{id}/runs -> 200 {"run_id": ..., "status": "succeeded"|"failed", "steps": ...} 400 invalid JSON | 404 unknown id | 422 non-object body/input Pre-code Test Matrix: 1. Out-of-order diamond `invoice_total` (`amount=20` -> `base=20`, `subtotal_taxed=40`, `shipping=30`, `grand_total=75`) 2. Linear chains and sibling deep-copy isolation (mutating a shared upstream list in place) 3. Bad shapes, unknown keys/actions, missing required params, duplicate IDs, dangling dependencies 4. Cycles: self-loop (`a -> a`), 2-step loop (`p <-> q`), and multi-step cycle -> rejected at registration (`422`) 5. Step failure (`fetch_quota`) skips downstream `apply_quota`, still runs independent `audit_tag` (`42`), catches `NaN`/sets 6. Deep-copied immutability of stored definitions and `404` / `422` / `405` / `400` HTTP responsesNotice the HTTP distinction:
400 Bad Requestmeans the bytes cannot even be parsed as JSON,422 Unprocessable Entitymeans valid JSON failed our schema/graph rules, and200 OKon/runsmeans the server executed the run as asked (even if a step inside the workflow failed, which is reported inrun["status"]).Validate step shapes and cross-step references at creation time
Validate everything static inside
create_workflowsoexecute_workflownever trips over broken definitions. Running validation in four ordered stages keeps the code clean because each stage can rely on invariants proved by the previous stage:- Container check:
definitionis adictwith only allowed keys (name,steps) and a non-emptystepslist. - Per-step check (
_check_step): each step is adictwith a non-empty stringid, allowed keys (id,action,params,depends_on), a registered stringaction(checkingisinstance(action, str)beforeaction in actionsavoidsTypeError: unhashable type: 'list'), all requiredparams, and a list of distinct stringdepends_onIDs. - Cross-step reference check: every
step["id"]is unique, and every ID independs_onexists inseen. - Cycle check + ordering: run topological sort to confirm no circular dependencies exist and save the resulting execution order alongside the workflow.
def _check_step(step, actions: ActionTable) -> List[dict]: """Validate one step's local JSON shape, action name, and required parameters.""" if not isinstance(step, dict): return [_error("invalid_step", "each step must be an object")] step_id = step.get("id") if not isinstance(step_id, str) or not step_id: return [_error("invalid_step", "step id must be a non-empty string")] errors: List[dict] = [] for field in step: if field not in STEP_FIELDS: errors.append(_error("unknown_field", f"unknown field '{field}'", step_id)) action = step.get("action") params = step.get("params", {}) if not isinstance(params, dict): errors.append(_error("invalid_step", "params must be an object", step_id)) # Check isinstance(action, str) BEFORE `action in actions` so unhashable types like lists don't raise TypeError elif not isinstance(action, str) or action not in actions: errors.append(_error("unknown_action", f"unknown action {action!r}", step_id)) else: required_params = actions[action][1] for name in required_params: if name not in params: errors.append(_error("missing_param", f"action '{action}' needs param '{name}'", step_id)) deps = step.get("depends_on", []) if not isinstance(deps, list) or not all(isinstance(dep, str) for dep in deps): errors.append(_error("invalid_step", "depends_on must be a list of step ids", step_id)) # Rejecting duplicate dependency entries ensures len(deps) equals the true incoming edge count elif len(set(deps)) != len(deps): errors.append(_error("invalid_step", "depends_on lists a step twice", step_id)) return errors- Container check:
Sort dependencies and catch cycles with Kahn's algorithm
A topological sort orders the steps of a graph so every step appears strictly after all of its dependencies. Kahn's algorithm computes this using each step's indegree (the number of unmet dependencies it is still waiting on):
- Put every step with
indegree == 0into areadyqueue (preserving definition order for determinism). - Pop a ready step, append it to
order, and subtract1from theindegreeof each child that depends on it; whenever a child hits0, push it ontoready. - When
readyis empty, comparelen(order)againstlen(steps). Any step involved in a cycle (or waiting on a cycle) never reachesindegree == 0!
Valid diamond: a -> (b, c) -> d Graph with cycle: a -> b <-> c start: indegree = {a:0, b:1, c:1, d:2} start: indegree = {a:0, b:2, c:1} ready = [a] ready = [a] pop a -> b:0, c:0 -> ready = [b, c] pop a -> b drops 2->1 -> ready = [] pop b -> d:1 -> ready = [c] order = [a] (len 1 < 3!) pop c -> d:0 -> ready = [d] stuck = [b, c] -> raise "cycle" pop d -> order = [a, b, c, d]def topological_order(steps: List[dict]) -> List[str]: """Kahn's algorithm: return step IDs in dependency-safe order (omitting steps stuck in/after cycles).""" # indegree: {step_id: count of unfinished dependencies} # children: {dep_id: [step_ids waiting on dep_id]} indegree: Dict[str, int] = {} children: Dict[str, List[str]] = {} for step in steps: step_id = step["id"] indegree[step_id] = len(step.get("depends_on", [])) children[step_id] = [] for step in steps: step_id = step["id"] for dep in step.get("depends_on", []): children[dep].append(step_id) # Seed the FIFO queue in definition order so tie-breaking is completely deterministic ready = deque() for step in steps: step_id = step["id"] if indegree[step_id] == 0: ready.append(step_id) order: List[str] = [] while ready: step_id = ready.popleft() order.append(step_id) for child in children[step_id]: indegree[child] -= 1 if indegree[child] == 0: ready.append(child) return order- Put every step with
Execute in topological order and isolate step failures
Because
create_workflowalready savedorderand deep-copieddefinition,execute_workflowsimply walksstep_id in workflow["order"]. Every dependencydepis guaranteed to be inresultsalready:- Transitive skipping: if any
dephasresults[dep]["status"] != "succeeded"(whether"failed"or"skipped"), mark this step"skipped"without calling its action. - Defensive deep copies: pass fresh copies of
params,run_input, anddep_outputsto the action function so a step that mutates a list in place (for exampledep_outputs["a"].append(99)inside a diamond) cannot corrupt its sibling step or the stored workflow. - Contained error boundary: wrap only the action call and
json.dumps(output, allow_nan=False)intry ... except Exceptionso runtime errors, non-JSON return values (like Pythonsets), andNaNfloats fail only that step rather than crashing the whole HTTP request.
def _run_step(self, step: dict, run_input: dict, results: dict) -> dict: deps = step.get("depends_on", []) # Skip if any dependency failed or was itself skipped (cascades transitively down chains) blocked = [] for dep in deps: if results[dep]["status"] != "succeeded": blocked.append(dep) if blocked: return { "status": "skipped", "output": None, "error": "dependency did not succeed: " + ", ".join(blocked), } # Deep-copy params, run_input, and upstream outputs so sibling steps cannot mutate shared data dep_outputs = {} for dep in deps: dep_outputs[dep] = copy.deepcopy(results[dep]["output"]) fn = self.actions[step["action"]][0] params = copy.deepcopy(step.get("params", {})) try: output = fn(params, copy.deepcopy(run_input), dep_outputs) # Reject non-JSON types (like sets) and NaN/Infinity as step-level errors, not HTTP 500s json.dumps(output, allow_nan=False) except Exception as exc: return {"status": "failed", "output": None, "error": f"{type(exc).__name__}: {exc}"} return {"status": "succeeded", "output": output, "error": None}- Transitive skipping: if any
Keep the HTTP layer thin and testable without sockets
Splitting HTTP translation into a pure function
handle_request(service, method, path, body_text) -> (status_code, payload_dict)lets unit tests verify every route, method, JSON error, and status code directly in memory without spinning up sockets or ports, whileserve()wires it to Python'sHTTPServerin ~25 lines:def handle_request(service: WorkflowService, method: str, path: str, body_text: str) -> Tuple[int, dict]: """Thin HTTP adapter translating (method, path, body_text) -> (status_code, json_dict).""" parts = path.strip("/").split("/") is_create = parts == ["workflows"] is_execute = len(parts) == 3 and parts[0] == "workflows" and parts[2] == "runs" if not is_create and not is_execute: return 404, {"errors": [_error("not_found", "no such route")]} if method != "POST": return 405, {"errors": [_error("method_not_allowed", "use POST")]} try: body = json.loads(body_text) if body_text else {} except json.JSONDecodeError: return 400, {"errors": [_error("invalid_json", "body is not valid JSON")]} try: if is_create: return 201, {"id": service.create_workflow(body)} if not isinstance(body, dict): return 422, {"errors": [_error("invalid_body", "body must be an object")]} workflow_id = parts[1] return 200, service.execute_workflow(workflow_id, body.get("input", {})) except ValidationError as exc: return 422, {"errors": exc.errors} except NotFound as exc: return 404, {"errors": [_error("not_found", str(exc))]} except Exception: logging.exception("unhandled error for %s %s", method, path) return 500, {"errors": [_error("internal", "unexpected server error")]}Verify against independent expectations and audit generated code
Compute every expected test result by hand from your written contract, rather than copying whatever output generated code happens to print:
- Hand-computed graph traces: out-of-order diamond
invoice_total(amount=20->20,40,30,75), sibling list-mutation isolation, partial failure (fetch_quotafails ->apply_quotaskipped -> independentaudit_tagsucceeds with42), andp <-> qcycle rejection (422). - Random DAG cross-check against brute force: generate 150 random 1–5 step graphs (with self-loops and cycles) and check
create_workflowagainst a brute-forceitertools.permutationsoracle. - Audit checklist for generated code:
- Hallucinated APIs or flags: run the test suite right away; never assume generated imports or parameters exist.
- Over-broad exception handlers: keep
try ... except Exceptionscoped strictly aroundfn(...)andjson.dumps(...)so defects in our own scheduler still surface loudly. - Dead or untested branches: verify every validation branch inside
_check_stephas a dedicated failing test (non-dict step, empty ID, unknown key, non-dictparams, non-string action, missing required param, baddepends_on, duplicatedepends_on). - Silent fallbacks:
step.get("depends_on", [])is safe only becauseSTEP_FIELDSalready rejected misspellings like"depend_on".
- Hand-computed graph traces: out-of-order diamond
Complete solution
from typing import Any, Callable, Dict, List, Optional, Tuple from collections import deque import copy import json import logging # ActionTable maps action_name -> (callable_fn, required_param_names). # Each callable is invoked as fn(params, run_input, dep_outputs), where dep_outputs # maps {dependency_step_id: dependency_output}. ActionTable = Dict[str, Tuple[Callable[[dict, dict, dict], Any], List[str]]] # Whitelists of allowed JSON keys so typos like "depend_on" fail fast at creation time DEFINITION_FIELDS = {"name", "steps"} STEP_FIELDS = {"id", "action", "params", "depends_on"} def _read_input(params, run_input, dep_outputs): return run_input[params["key"]] def _add(params, run_input, dep_outputs): total = params.get("value", 0) for output in dep_outputs.values(): total += output return total def _multiply(params, run_input, dep_outputs): product = params.get("factor", 1) for output in dep_outputs.values(): product *= output return product def _fail(params, run_input, dep_outputs): raise RuntimeError(params.get("message", "step failed")) DEFAULT_ACTIONS: ActionTable = { "read_input": (_read_input, ["key"]), "add": (_add, []), "multiply": (_multiply, []), "fail": (_fail, []), } class ValidationError(Exception): """A request that can never succeed. errors: list of {"code", "message", "step"}.""" def __init__(self, errors: List[dict]): super().__init__(f"{len(errors)} validation error(s)") self.errors = errors class NotFound(Exception): pass def _error(code: str, message: str, step: Optional[str] = None) -> dict: return {"code": code, "message": message, "step": step} def _check_step(step, actions: ActionTable) -> List[dict]: """Validate one step's local JSON shape, action name, and required parameters.""" if not isinstance(step, dict): return [_error("invalid_step", "each step must be an object")] step_id = step.get("id") if not isinstance(step_id, str) or not step_id: return [_error("invalid_step", "step id must be a non-empty string")] errors: List[dict] = [] for field in step: if field not in STEP_FIELDS: errors.append(_error("unknown_field", f"unknown field '{field}'", step_id)) action = step.get("action") params = step.get("params", {}) if not isinstance(params, dict): errors.append(_error("invalid_step", "params must be an object", step_id)) # Check isinstance(action, str) BEFORE `action in actions` so unhashable types like lists don't raise TypeError elif not isinstance(action, str) or action not in actions: errors.append(_error("unknown_action", f"unknown action {action!r}", step_id)) else: required_params = actions[action][1] for name in required_params: if name not in params: errors.append(_error("missing_param", f"action '{action}' needs param '{name}'", step_id)) deps = step.get("depends_on", []) if not isinstance(deps, list) or not all(isinstance(dep, str) for dep in deps): errors.append(_error("invalid_step", "depends_on must be a list of step ids", step_id)) # Rejecting duplicate dependency entries ensures len(deps) equals the true incoming edge count elif len(set(deps)) != len(deps): errors.append(_error("invalid_step", "depends_on lists a step twice", step_id)) return errors def topological_order(steps: List[dict]) -> List[str]: """Kahn's algorithm: return step IDs in dependency-safe order (omitting steps stuck in/after cycles).""" # indegree: {step_id: count of unfinished dependencies} # children: {dep_id: [step_ids waiting on dep_id]} indegree: Dict[str, int] = {} children: Dict[str, List[str]] = {} for step in steps: step_id = step["id"] indegree[step_id] = len(step.get("depends_on", [])) children[step_id] = [] for step in steps: step_id = step["id"] for dep in step.get("depends_on", []): children[dep].append(step_id) # Seed the FIFO queue in definition order so tie-breaking is completely deterministic ready = deque() for step in steps: step_id = step["id"] if indegree[step_id] == 0: ready.append(step_id) order: List[str] = [] while ready: step_id = ready.popleft() order.append(step_id) for child in children[step_id]: indegree[child] -= 1 if indegree[child] == 0: ready.append(child) return order def validate_definition(definition, actions: ActionTable) -> Tuple[List[dict], List[str]]: """Validate a workflow definition in four stages and return (errors, execution_order).""" # Stage 1: Validate top-level container shape if not isinstance(definition, dict): return [_error("invalid_definition", "definition must be an object")], [] errors: List[dict] = [] for field in definition: if field not in DEFINITION_FIELDS: errors.append(_error("unknown_field", f"unknown field '{field}'")) if "name" in definition and not isinstance(definition["name"], str): errors.append(_error("invalid_definition", "name must be a string")) steps = definition.get("steps") if not isinstance(steps, list) or not steps: errors.append(_error("invalid_definition", "steps must be a non-empty list")) return errors, [] # Stage 2: Validate each individual step's shape before reading cross-step fields for step in steps: errors += _check_step(step, actions) if errors: return errors, [] # Stage 3: Check unique step IDs and verify every dependency references an existing step seen = set() for step in steps: step_id = step["id"] if step_id in seen: errors.append(_error("duplicate_step_id", f"step id '{step_id}' is used twice", step_id)) seen.add(step_id) for step in steps: step_id = step["id"] for dep in step.get("depends_on", []): if dep not in seen: errors.append(_error("missing_dependency", f"depends on unknown step '{dep}'", step_id)) if errors: return errors, [] # Stage 4: Compute topological order; if fewer than len(steps) finish, a cycle exists order = topological_order(steps) if len(order) < len(steps): placed = set(order) stuck = [] for step in steps: if step["id"] not in placed: stuck.append(step["id"]) message = "these steps can never run because of a dependency cycle: " + ", ".join(stuck) return [_error("cycle", message)], [] return [], order class WorkflowService: """Core workflow storage, validation, and execution logic (decoupled from HTTP).""" def __init__(self, actions: Optional[ActionTable] = None): self.actions = DEFAULT_ACTIONS if actions is None else actions # workflows: {workflow_id: {"definition": dict, "order": [step_id, ...]}} self.workflows: Dict[str, dict] = {} # runs: {run_id: run_summary_dict} self.runs: Dict[str, dict] = {} self._next_workflow = 1 self._next_run = 1 def create_workflow(self, definition) -> str: """Validate and store an immutable copy of `definition`; return its workflow ID.""" errors, order = validate_definition(definition, self.actions) if errors: raise ValidationError(errors) workflow_id = f"wf-{self._next_workflow}" self._next_workflow += 1 # Deep-copy so mutating the caller's dict later cannot corrupt a stored workflow self.workflows[workflow_id] = {"definition": copy.deepcopy(definition), "order": order} return workflow_id def execute_workflow(self, workflow_id: str, run_input) -> dict: """Execute steps in precomputed topological order, isolating step failures.""" workflow = self.workflows.get(workflow_id) if workflow is None: raise NotFound(f"workflow '{workflow_id}' not found") if not isinstance(run_input, dict): raise ValidationError([_error("invalid_input", "input must be an object")]) steps_by_id = {} for step in workflow["definition"]["steps"]: steps_by_id[step["id"]] = step # Walk `workflow["order"]` so every dependency is already in `results` before its children results: Dict[str, dict] = {} for step_id in workflow["order"]: results[step_id] = self._run_step(steps_by_id[step_id], run_input, results) status = "succeeded" for result in results.values(): if result["status"] != "succeeded": status = "failed" run_id = f"run-{self._next_run}" self._next_run += 1 run = {"run_id": run_id, "workflow_id": workflow_id, "status": status, "steps": results} self.runs[run_id] = run return run def _run_step(self, step: dict, run_input: dict, results: dict) -> dict: deps = step.get("depends_on", []) # Skip if any dependency failed or was itself skipped (cascades transitively down chains) blocked = [] for dep in deps: if results[dep]["status"] != "succeeded": blocked.append(dep) if blocked: return { "status": "skipped", "output": None, "error": "dependency did not succeed: " + ", ".join(blocked), } # Deep-copy params, run_input, and upstream outputs so sibling steps cannot mutate shared data dep_outputs = {} for dep in deps: dep_outputs[dep] = copy.deepcopy(results[dep]["output"]) fn = self.actions[step["action"]][0] params = copy.deepcopy(step.get("params", {})) try: output = fn(params, copy.deepcopy(run_input), dep_outputs) # Reject non-JSON types (like sets) and NaN/Infinity as step-level errors, not HTTP 500s json.dumps(output, allow_nan=False) except Exception as exc: return {"status": "failed", "output": None, "error": f"{type(exc).__name__}: {exc}"} return {"status": "succeeded", "output": output, "error": None} def handle_request(service: WorkflowService, method: str, path: str, body_text: str) -> Tuple[int, dict]: """Thin HTTP adapter translating (method, path, body_text) -> (status_code, json_dict). POST /workflows body: workflow definition -> 201 {"id": ...} POST /workflows/<id>/runs body: {"input": {...}} -> 200 run result """ parts = path.strip("/").split("/") is_create = parts == ["workflows"] is_execute = len(parts) == 3 and parts[0] == "workflows" and parts[2] == "runs" if not is_create and not is_execute: return 404, {"errors": [_error("not_found", "no such route")]} if method != "POST": return 405, {"errors": [_error("method_not_allowed", "use POST")]} try: body = json.loads(body_text) if body_text else {} except json.JSONDecodeError: return 400, {"errors": [_error("invalid_json", "body is not valid JSON")]} try: if is_create: return 201, {"id": service.create_workflow(body)} if not isinstance(body, dict): return 422, {"errors": [_error("invalid_body", "body must be an object")]} workflow_id = parts[1] return 200, service.execute_workflow(workflow_id, body.get("input", {})) except ValidationError as exc: return 422, {"errors": exc.errors} except NotFound as exc: return 404, {"errors": [_error("not_found", str(exc))]} except Exception: logging.exception("unhandled error for %s %s", method, path) return 500, {"errors": [_error("internal", "unexpected server error")]} def serve(port: int = 8000) -> None: """Run the service locally using Python's built-in single-threaded HTTPServer.""" from http.server import BaseHTTPRequestHandler, HTTPServer service = WorkflowService() class Handler(BaseHTTPRequestHandler): def _reply(self, method): length = int(self.headers.get("Content-Length", 0)) body_text = self.rfile.read(length).decode("utf-8") status, payload = handle_request(service, method, self.path, body_text) data = json.dumps(payload).encode("utf-8") self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_POST(self): self._reply("POST") def do_GET(self): self._reply("GET") HTTPServer(("127.0.0.1", port), Handler).serve_forever() if __name__ == "__main__": serve()✅ Submit now — all tests should pass.
Intuition & how it works
Think of a workflow service like a head chef reviewing a recipe card (create_workflow) before any cook touches a stove (execute_workflow). A workflow is a DAG (directed acyclic graph: a network of steps with one-way dependencies and zero circular loops). At creation time, we verify every step's JSON shape, action name, required parameters, and step references, and run Kahn's algorithm (a queue-based topological sort that produces a step order where every step appears strictly after all the steps it depends on, while detecting cycles whenever steps remain stuck with non-zero indegree, i.e., unfinished dependency count). When working with an AI coding assistant, you steer this in small, verifiable slices: write the contract and test list first, implement core domain logic decoupled from HTTP, and verify against hand-computed expectations.
Asking an AI assistant to generate the entire service and test suite in one shot fails because it typically tangles HTTP parsing with graph execution, writes tests that merely mirror its own bugs, and misses subtle validation holes (such as running steps in array order, ignoring typos like "depend_on", or crashing the server when one step raises an exception). Likewise, deferring validation until execute_workflow lets broken or cyclic workflows get stored and fail on every single run.
Walk through Example 1's 4-step diamond workflow base -> (subtotal_taxed, shipping) -> grand_total on run_input = {"amount": 20}:
- Creation (POST /workflows): Even though grand_total is listed first and base last, indegree starts at {grand_total: 2, subtotal_taxed: 1, shipping: 1, base: 0}. Step base enters the ready queue first; popping base drops subtotal_taxed and shipping to 0; popping both drops grand_total to 0, saving order = ["base", "subtotal_taxed", "shipping", "grand_total"] and returning 201 {"id": "wf-1"}.
- Execution (POST /workflows/wf-1/runs): Walking order, base reads 20, subtotal_taxed multiplies by 2 (40), shipping adds 10 (30), and grand_total receives fresh copies {"subtotal_taxed": 40, "shipping": 30} plus value = 5 to return 75 (status = "succeeded").
- Contained step failure (Example 2): When fetch_quota raises an exception, it is marked "failed", dependent apply_quota sees fetch_quota != "succeeded" and is marked "skipped", unrelated audit_tag still executes (42), and HTTP returns 200 OK with run["status"] == "failed".
Complexity
Let V be the number of steps in the workflow and E the number of dependency edges across depends_on lists.
- Create (
create_workflow) — Time O(V + E) plus definition size, Space O(V + E): Checking each step's fields and building theseenset scans theVsteps andEdependency references once. Kahn's algorithm initializesVdictionary entries, pushes each step into the queue at most once, and decrementsindegreeonce per edge inO(V + E)time;copy.deepcopy(definition)adds work and storage proportional to the JSON payload size. - Execute (
execute_workflow) — Time O(V + E) scheduling plus action work and defensive copies, Space O(V) plus output sizes: Walking the precomputedordervisits each of theVsteps once and checks its incoming edges (Echecks total across the run), while deep-copyingrun_inputper step (O(V * input_size)) and dependency outputs per edge (O(E * output_size)) isolates steps from in-place mutations.
Edge cases
- Single-step workflows and reversed step order: A 1-step workflow with omitted
paramsanddepends_ondefaults both to empty containers;[c (needs b), b (needs a), a]still runsa -> b -> c. - Self-loops and multi-step cycles:
"depends_on": ["a"]on stepastarts withindegree["a"] == 1, never entersready, and is rejected with error code"cycle"alongside any steps downstream of a cycle. - Misspelled fields and wrong JSON types: Typos like
"depend_on"fail fast as"unknown_field"instead of silently dropping dependencies; passing an unhashable list like"action": ["add"]is caught byisinstance(action, str)instead of raisingTypeError. - Transitive failure propagation: In
boom -> after -> after2,boomfails,afterbecomes"skipped", andafter2also becomes"skipped"because"skipped" != "succeeded", while unrelated steps still run. - Non-JSON action outputs (
set,NaN,Infinity): Checked inside_run_stepviajson.dumps(output, allow_nan=False)so bad outputs fail only that step instead of crashing response serialization with a500. - Caller and sibling mutations: Deep-copying
definitionon creation and deep-copyingdep_outputsbefore each step prevents callers or sibling branches from mutating shared lists or dicts. - HTTP status separation: Unparseable raw bytes return
400, valid JSON with wrong types or schema violations returns422, unknown routes or workflow IDs return404, and non-POSTmethods return405.
Common mistakes
- Validating actions, missing steps, or cycles at execution time: Accepts broken workflows into storage that can never succeed.
- Naive DFS cycle detection with a single
visitedset: Treating any previously visited node as a cycle falsely rejects valid diamond DAGs (a -> b -> danda -> c -> dvisitdtwice!), whereas skipping visited nodes misses real back-edges unless you track a 3-stateunvisited / visiting / donemarker. - Executing steps in array order: Breaks whenever a client lists a downstream step above one of its dependencies.
- Calling downstream steps after a dependency failed: Passes
Noneinto actions expecting numbers or dicts, masking the root failure under noisy secondary exceptions. - Wrapping the whole run in one
tryblock (or none at all): Either aborts independent healthy branches on the first error or crashes the HTTP handler with a500. - Generating tests from AI-written code instead of from the spec: Confirms whatever bugs the assistant just wrote instead of verifying intended behavior.
Alternative approaches
- Three-color Depth-First Search (DFS): Tracking
UNVISITED,VISITING(on the current recursion stack), andDONEdetects cycles inO(V + E)time and makes it easy to reconstruct the exact cycle path (b -> c -> d -> b), though recursive DFS can hit Python's recursion limit on deep chains (> 1000steps), whereas Kahn's iterative queue avoids recursion and maps directly onto parallel execution. - Declarative schema validation (e.g.,
pydanticorjsonschema): In production Python services, typed models replace manualisinstanceboilerplate for Stage 1 and Stage 2 shape checks while keeping Stage 3 and Stage 4 in custom graph validation code.
Follow-up questions
- How would you redesign execution to run in the background, returning a run identifier right away so callers can poll progress? Have
POST /workflows/{id}/runscreate a run record withstatus = "pending", enqueuerun_idonto a background task queue, and immediately return202 Acceptedwith{"run_id": "run-1", "status": "pending"}and aLocation: /runs/run-1header. Background workers pullrun_ids off the queue, run the exact same topological executor while updating each step's status (pending -> running -> succeeded | failed | skipped) in shared storage, and exposeGET /runs/{run_id}for caller polling (with exponential backoff or an optional completion webhook) plusPOST /runs/{run_id}/canceland a per-run timeout. - How can ready steps with no mutual dependencies execute concurrently, and how does concurrency affect step failure behavior? Kahn's
readyqueue already identifies every step whose dependencies are satisfied, so instead of running one step per loop iteration, submit all currently ready steps to aThreadPoolExecutor(orasynciotask group) and push newly unlocked children whenever a future completes. Failure semantics now have in-flight concurrency: when stepbfails, sibling stepcmay already be running mid-execution, so you must explicitly define whether in-flight siblings finish naturally (matching our "skip dependents only" rule) or receive a cooperative cancellation token, and tests must assert partial-order invariants (pos[dep] < pos[step]) rather than a single fixed call sequence. - If a caller times out and resends an execution request, how do you prevent side-effecting actions from running multiple times? Require an idempotency key (a unique caller-generated token per logical run request, passed via an
Idempotency-Keyheader) and atomically store(idempotency_key, request_hash) -> run_idwhen creating the run. If the caller resends the same key and payload, return the existingrun_idand its current/final state without starting a second execution; if the same key arrives with a different payload, reject it with409 Conflictor422. For external side effects inside steps (like charging a card or sending an email), pass a deterministic step tokenf"{run_id}:{step_id}"downstream so external APIs also deduplicate step retries. - What storage schema and recovery protocol would let an interrupted workflow run pick up where it left off after a server crash? Persist three relational tables:
workflows(id, definition_json, order_json, created_at),runs(id, workflow_id, input_json, status, lease_owner, lease_expires_at), andstep_runs(run_id, step_id, status, output_json, error, attempts). Workers maintain a lease (a short-lived database lock renewed by periodic heartbeats, e.g., every 10 seconds with a 30-second expiry) and commit each step transition (pending -> runningbefore invoking the action,running -> succeededwithoutput_jsonafterward). After a crash, a recovery worker claims runs whoselease_expires_athas passed, reloads already-"succeeded"step outputs without re-running them, and either retries any interrupted"running"step (if that action is marked idempotent) or marks it"failed"for human/compensating intervention.
Follow-up questions
- How would you redesign execution to run in the background, returning a run identifier right away so callers can poll progress?
- How can ready steps with no mutual dependencies execute concurrently, and how does concurrency affect step failure behavior?
- If a caller times out and resends an execution request, how do you prevent side-effecting actions from running multiple times?
- What storage schema and recovery protocol would let an interrupted workflow run pick up where it left off after a server crash?
Similar questions
- Prioritizing Minimal Releases With Product Around Core User Needs
- Analyzing Commercial Underwriting Workflows and Prioritizing AI Opportunities
- Combine Overlapping Closed Ranges Into Disjoint Sorted Blocks
- Applied AI Track Record, Career Timing, and Early-Stage Readiness
- AI System Deep Dive: Architecture Choices, Trade-offs, and Impact
- Dynamic Dynasty Succession Without an Initial Monarch
More Furtherai interview questions
- Prioritizing Minimal Releases With Product Around Core User Needs Medium
- Analyzing Commercial Underwriting Workflows and Prioritizing AI Opportunities Medium
- Combine Overlapping Closed Ranges Into Disjoint Sorted Blocks Medium Pro
- Applied AI Track Record, Career Timing, and Early-Stage Readiness Medium Pro
- AI System Deep Dive: Architecture Choices, Trade-offs, and Impact Medium Pro