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"]): returns run_input[params["key"]].
  • "add" (requires []): sums params.get("value", 0) and all values in dep_outputs.values().
  • "multiply" (requires []): multiplies params.get("factor", 1) across all values in dep_outputs.values().
  • "fail" (requires []): raises RuntimeError(params.get("message", "step failed")).

Implement WorkflowService and handle_request with the following behavior:

  1. WorkflowService.__init__(self, actions=None): Use DEFAULT_ACTIONS when actions is None, otherwise use the supplied ActionTable.
  2. WorkflowService.create_workflow(self, definition) -> str:
    • Validate definition before storing an immutable deep copy, returning sequential identifiers "wf-1", "wf-2", and so on.
    • Top-level definition must be a dict containing a non-empty list "steps" and an optional str "name". Each step must be a dict with a non-empty str "id", a registered str "action", an optional dict "params" (default {}), and an optional List[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 on definition or 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).
  3. WorkflowService.execute_workflow(self, workflow_id, run_input) -> dict:
    • Raise NotFound for an unknown workflow_id, and raise ValidationError (code "invalid_input") if run_input is not a dict.
    • Execute every step only after all of its dependencies have completed, regardless of step listing order, passing defensive copies of params, run_input, and upstream dep_outputs so 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 a set, NaN, or Infinity), 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.
  4. 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, else 422), run service.execute_workflow(<id>, body.get("input", {})), and return (200, run_result).
    • Return 404 for unknown routes or NotFound, 405 when method != "POST" on a valid route, 400 on malformed JSON syntax, and 422 {"errors": [...]} on ValidationError or non-object /runs payloads.

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^4 steps and 0 <= E <= 5 * 10^4 dependency 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_workflow returns.
  • Standard library only (json, copy, collections, http.server); no external web frameworks.

Step-by-step walkthrough

  1. 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 i depends on step i - 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 ActionTable registry (read_input, add, multiply, fail) rather than arbitrary user code or raw external URLs, avoiding untrusted-code sandboxing.
    • Execution mode: execute_workflow runs 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).
  2. 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 responses
    

    Notice the HTTP distinction: 400 Bad Request means the bytes cannot even be parsed as JSON, 422 Unprocessable Entity means valid JSON failed our schema/graph rules, and 200 OK on /runs means the server executed the run as asked (even if a step inside the workflow failed, which is reported in run["status"]).

  3. Validate step shapes and cross-step references at creation time

    Validate everything static inside create_workflow so execute_workflow never 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:

    1. Container check: definition is a dict with only allowed keys (name, steps) and a non-empty steps list.
    2. Per-step check (_check_step): each step is a dict with a non-empty string id, allowed keys (id, action, params, depends_on), a registered string action (checking isinstance(action, str) before action in actions avoids TypeError: unhashable type: 'list'), all required params, and a list of distinct string depends_on IDs.
    3. Cross-step reference check: every step["id"] is unique, and every ID in depends_on exists in seen.
    4. 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
    
  4. 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):

    1. Put every step with indegree == 0 into a ready queue (preserving definition order for determinism).
    2. Pop a ready step, append it to order, and subtract 1 from the indegree of each child that depends on it; whenever a child hits 0, push it onto ready.
    3. When ready is empty, compare len(order) against len(steps). Any step involved in a cycle (or waiting on a cycle) never reaches indegree == 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
    
  5. Execute in topological order and isolate step failures

    Because create_workflow already saved order and deep-copied definition, execute_workflow simply walks step_id in workflow["order"]. Every dependency dep is guaranteed to be in results already:

    • Transitive skipping: if any dep has results[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, and dep_outputs to the action function so a step that mutates a list in place (for example dep_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) in try ... except Exception so runtime errors, non-JSON return values (like Python sets), and NaN floats 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}
    
  6. 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, while serve() wires it to Python's HTTPServer in ~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")]}
    
  7. 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_quota fails -> apply_quota skipped -> independent audit_tag succeeds with 42), and p <-> q cycle rejection (422).
    • Random DAG cross-check against brute force: generate 150 random 1–5 step graphs (with self-loops and cycles) and check create_workflow against a brute-force itertools.permutations oracle.
    • Audit checklist for generated code:
      1. Hallucinated APIs or flags: run the test suite right away; never assume generated imports or parameters exist.
      2. Over-broad exception handlers: keep try ... except Exception scoped strictly around fn(...) and json.dumps(...) so defects in our own scheduler still surface loudly.
      3. Dead or untested branches: verify every validation branch inside _check_step has a dedicated failing test (non-dict step, empty ID, unknown key, non-dict params, non-string action, missing required param, bad depends_on, duplicate depends_on).
      4. Silent fallbacks: step.get("depends_on", []) is safe only because STEP_FIELDS already rejected misspellings like "depend_on".
  8. 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 the seen set scans the V steps and E dependency references once. Kahn's algorithm initializes V dictionary entries, pushes each step into the queue at most once, and decrements indegree once per edge in O(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 precomputed order visits each of the V steps once and checks its incoming edges (E checks total across the run), while deep-copying run_input per 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 params and depends_on defaults both to empty containers; [c (needs b), b (needs a), a] still runs a -> b -> c.
  • Self-loops and multi-step cycles: "depends_on": ["a"] on step a starts with indegree["a"] == 1, never enters ready, 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 by isinstance(action, str) instead of raising TypeError.
  • Transitive failure propagation: In boom -> after -> after2, boom fails, after becomes "skipped", and after2 also becomes "skipped" because "skipped" != "succeeded", while unrelated steps still run.
  • Non-JSON action outputs (set, NaN, Infinity): Checked inside _run_step via json.dumps(output, allow_nan=False) so bad outputs fail only that step instead of crashing response serialization with a 500.
  • Caller and sibling mutations: Deep-copying definition on creation and deep-copying dep_outputs before 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 returns 422, unknown routes or workflow IDs return 404, and non-POST methods return 405.

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 visited set: Treating any previously visited node as a cycle falsely rejects valid diamond DAGs (a -> b -> d and a -> c -> d visit d twice!), whereas skipping visited nodes misses real back-edges unless you track a 3-state unvisited / visiting / done marker.
  • 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 None into actions expecting numbers or dicts, masking the root failure under noisy secondary exceptions.
  • Wrapping the whole run in one try block (or none at all): Either aborts independent healthy branches on the first error or crashes the HTTP handler with a 500.
  • 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), and DONE detects cycles in O(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 (> 1000 steps), whereas Kahn's iterative queue avoids recursion and maps directly onto parallel execution.
  • Declarative schema validation (e.g., pydantic or jsonschema): In production Python services, typed models replace manual isinstance boilerplate 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}/runs create a run record with status = "pending", enqueue run_id onto a background task queue, and immediately return 202 Accepted with {"run_id": "run-1", "status": "pending"} and a Location: /runs/run-1 header. Background workers pull run_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 expose GET /runs/{run_id} for caller polling (with exponential backoff or an optional completion webhook) plus POST /runs/{run_id}/cancel and a per-run timeout.
  • How can ready steps with no mutual dependencies execute concurrently, and how does concurrency affect step failure behavior? Kahn's ready queue already identifies every step whose dependencies are satisfied, so instead of running one step per loop iteration, submit all currently ready steps to a ThreadPoolExecutor (or asyncio task group) and push newly unlocked children whenever a future completes. Failure semantics now have in-flight concurrency: when step b fails, sibling step c may 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-Key header) and atomically store (idempotency_key, request_hash) -> run_id when creating the run. If the caller resends the same key and payload, return the existing run_id and its current/final state without starting a second execution; if the same key arrives with a different payload, reject it with 409 Conflict or 422. For external side effects inside steps (like charging a card or sending an email), pass a deterministic step token f"{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), and step_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 -> running before invoking the action, running -> succeeded with output_json afterward). After a crash, a recovery worker claims runs whose lease_expires_at has 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

Similar questions

More Furtherai interview questions

All 6 Furtherai questions →