Search and contents

Orchestration Engine: Task, the five Workflow patterns, Gate, and Try/Catch

How engine/workflow.py, engine/gate.py and engine/try_catch.py implement the mechanism that every Task type's Workflow is built from, not any one Task type itself.

This is deliberately the generic machinery. A real Task (ingestion-time classification, anomaly narration, retrieval support and so on) is a Node Type composing these primitives, not a new mechanism per Task type.

1. Gate: the branching primitive

A Gate evaluates whatever data reaches it and resolves to one branch name. It is generalized along two axes: what does the evaluating, and how many branches come out. It stays agnostic about how a branch gets decided. evaluate is a caller-supplied Callable[[Any], str], and mode is only metadata recorded on the decision, for parity with the Activity Log.

from engine.gate import EvaluationMode, Gate

# rule/threshold
temp_gate = Gate(EvaluationMode.RULE, lambda temp: "alarm" if temp >= 90 else "normal")

# statistical/ML
confidence_gate = Gate(
    EvaluationMode.STATISTICAL, lambda score: "confident" if score >= 0.8 else "uncertain"
)

# LLM-judged - evaluate is free to close over an InferenceClient and run a real call
judge_gate = Gate(EvaluationMode.LLM, lambda draft: llm_judge(draft))

decision = temp_gate.decide(95)  # GateDecision(branch="alarm", mode=RULE, used_fallback=False)

Dynamic, data-driven branch counts (the document-type-classifier case) declare a closed branches set plus a mandatory fallback. This is the same per-type-plus-fallback shape that ChunkingRegistry in engine/chunking.py already uses. An evaluate result outside branches routes to fallback instead of raising:

gate = Gate(
    EvaluationMode.RULE,
    lambda doc_type: doc_type,
    branches=frozenset({"sop", "work-instruction", "generic"}),
    fallback="generic",
)
gate.decide("purchase-order")  # -> branch="generic", used_fallback=True

Constructing a Gate with branches but no fallback, or with a fallback outside branches, raises ValueError immediately. A misconfigured Gate fails at build time, not on the first data-driven edge case it meets in production.

Mandatory-Human Status is not a fourth mode. A Gate only ever decides a branch. What a branch leads to afterwards (proceed, loop back, flag Pending) is the caller's concern.

2. Workflow: the five patterns, and Task

engine/workflow.py implements Kindred's five Workflow patterns as plain runner functions:

  • run_prompt_chain
  • run_routing
  • run_parallelization
  • run_orchestrator_workers
  • run_evaluator_optimizer

It also provides a WorkflowRegistry that builds a Task for each pattern. A Task is a name, its WorkflowPattern and a zero-argument closure.

from engine.gate import EvaluationMode, Gate
from engine.workflow import WorkflowRegistry

registry = WorkflowRegistry()

task = registry.routing(
    "route-by-parity",
    4,
    gate=Gate(EvaluationMode.RULE, lambda n: "even" if n % 2 == 0 else "odd"),
    routes={"even": lambda n: f"{n} is even", "odd": lambda n: f"{n} is odd"},
)
result = task.execute()  # TaskResult(pattern=ROUTING, value="4 is even")

Task.execute() never needs to know which of the five patterns it is running. run already has every pattern-specific argument bound, because the Task is built by WorkflowRegistry's own per-pattern method and not constructed directly.

Pattern (registry method)What it does
Prompt Chaining (prompt_chaining) A sequence of custom function calls. Each step's output feeds the next.
Routing (routing) A Gate picks one branch, and only that branch's registered route runs. A branch with no registered route raises KeyError, so every branch the Gate can produce, its fallback included, needs its own route.
Parallelization (parallelization) Every step runs independently over the same input, concurrently (ThreadPoolExecutor), then aggregate combines the results. Results come back in the steps' own order regardless of completion order.
Orchestrator-Workers (orchestrator_workers) plan(data) dynamically produces a list of subtasks, worker runs once per subtask, and aggregate combines the results.
Evaluator-Optimizer (evaluator_optimizer) generate produces a candidate. A Gate decides proceed, or loops back with that candidate as the next input, bounded by max_iterations.

Evaluator-Optimizer always returns. It returns an EvaluatorOptimizerResult(value, converged, iterations) either way. Hitting the iteration cap without reaching proceed_branch still returns the last candidate, flagged converged=False, instead of raising. This is the mandatory Workflow-defined fallback that every Task guarantees: no Task is allowed an unbounded case with no defined behaviour.

3. Try/Catch: the two failure classes

TryCatch in engine/try_catch.py wraps a step callable with Try/Catch's retry policy. The step signals which of the two failure classes applies by raising UnresponsiveServiceFailure or PromptCausedFailure (engine/exceptions.py). Any other exception is a genuine bug and propagates uncaught.

from engine.exceptions import PromptCausedFailure, UnresponsiveServiceFailure
from engine.try_catch import Outcome, RetryPolicy, TryCatch


def call_target_system(data):
    ...
    raise UnresponsiveServiceFailure("target system unreachable")


try_catch = TryCatch(call_target_system, retry=RetryPolicy(max_attempts=3))
result = try_catch.run(payload)
result.outcome  # Outcome.GAVE_UP once max_attempts is exhausted
  • Unresponsive-service: retried identically, with no data modification between attempts, since a downed service doesn't respond differently to different input. Exhausting max_attempts produces the terminal Outcome.GAVE_UP.
  • Prompt-caused: an identical retry would only reproduce the same failure, so a caller-supplied repair(data, reason) -> modified_data produces each retry's data. Exhausting max_attempts produces Outcome.EXHAUSTED instead.
try_catch = TryCatch(
    rejects_until_short_enough,
    retry=RetryPolicy(max_attempts=5),
    repair=lambda draft, reason: draft[:-3],
)
result = try_catch.run("a-too-long-draft")
result.outcome  # Outcome.SUCCEEDED once repair gets it under the length bar, else EXHAUSTED

The result carries two fields that describe what happened:

  • AttemptResult.final_data is whatever the last attempt actually ran against: the original input for an unresponsive-service run (never modified), or repair's last output for a prompt-caused run.
  • failure_reasons holds one "{attempt}:{reason}" entry per failed attempt, the same shape as CallOutcome.failure_reasons in engine/inference.py.

Pitfalls

  • A step that can fail both ways raises the exception matching what actually went wrong, not always the same one. TryCatch decides GAVE_UP versus EXHAUSTED from whichever failure class the last attempt raised. A step that flips between the two across attempts still gets a sensible terminal state. A step that always raises the wrong class defeats the point of the distinction: it gets an unmodified retry against a genuinely prompt-caused failure, or a repair call against a genuinely downed service.
  • Omitting repair on a prompt-caused failure is legal but degenerate. Every retry then resends the same data. The retries are bounded, but have no better chance of succeeding than the first attempt. Supplying repair is what gives a retry a genuine second chance.
  • WorkflowRegistry's five patterns are a fixed, closed set, unlike ChunkingRegistry. There is no register() here. A new Workflow pattern is a design-time addition to engine/workflow.py itself, not a per-Node-Type runtime registration.

Release: v0.11.0