Skip to content

How To Route with BranchPipe

Fernando Koch edited this page Mar 30, 2026 · 2 revisions

How To Route With BranchPipe

Purpose

Use BranchPipe when exactly one matching branch should execute.

This is the GraphK tool for routing-style control flow.

What Does BranchPipe Do?

graphk.BranchPipe contains multiple branch pipelines and multiple matcher tests.

At execution time it:

  1. resolves the active session and scoped context
  2. evaluates each branch matcher
  3. collects all matching branch indices
  4. selects one branch according to the selection policy
  5. executes only that branch

When Should You Use It?

Good use cases:

  • route one request to one handler
  • choose one workflow path based on state
  • dispatch to one pipeline based on scoped context
  • implement controlled alternatives where only one result path should run

Use BranchPipe when exactly one route should be chosen. Use MultiPipe when multiple routes should execute.

Selection Policies

Important constants:

  • BranchPipe.SELECT_FIRST
  • BranchPipe.SELECT_RANDOM

SELECT_FIRST

Use when:

  • matching order should determine the winner
  • routing must be deterministic

SELECT_RANDOM

Use when:

  • nondeterministic branch selection is intentional
  • or when randomness is explicitly seeded for testing/demo purposes

Minimal Example

import graphk


branch = graphk.BranchPipe(
    context=graphk.Context(route="alpha"),
    selection_policy=graphk.BranchPipe.SELECT_FIRST,
    nodes=[
        (
            graphk.Matcher(task="route", **{"@Pipeline/route": "alpha", "@Runner/mode": "strict"}),
            graphk.SequencePipe(nodes=[graphk.demo.RouteNode("A")]),
        ),
        (
            graphk.Matcher(task="route", **{"@Pipeline/route": "beta", "@Runner/mode": "strict"}),
            graphk.SequencePipe(nodes=[graphk.demo.RouteNode("B")]),
        ),
    ],
)

pipeline = graphk.SequencePipe(nodes=[branch])
session = graphk.Session(task="route")
runner = graphk.Runner(pipeline, session)

runner.start(context=graphk.Context(mode="strict"))
runner.run()

print(session.to_dict())

Why Are Branch Items Pipelines?

Each branch is expected to be a Pipeline, not just a raw node.

This gives each route its own composable execution space and allows:

  • one-node branches
  • multi-node branches
  • nested sub-workflows per route

Practical Use Cases

Request Routing

Choose handler A or B depending on route, task, mode, or user state.

Workflow Alternatives

Choose one of several processing strategies based on session values.

Controlled Experiments

Select one branch by deterministic priority or seeded randomness.

Common Mistakes

  • Do not put raw nodes directly into branch definitions; use branch pipelines.
  • Do not expect all matching branches to execute; BranchPipe selects only one.
  • Do not use SELECT_RANDOM unless nondeterministic behavior is actually desired.

Learn More

Recommended references:

Clone this wiki locally