Pipeline
A pipeline is a function in your code that takes a run input and ends the run with a run result, with nothing, or with a stop. A run result is a code change, new tickets or both. On the way it asks for steps: function steps, shell steps, agent steps of agents and human steps. codeband records each step and its value in the run journal.
A pipeline is ordinary code in the language of its SDK, not a configuration file or a graph that you draw. Branches, loops, retries and error handling are the language’s own if, for and try, and you test a pipeline with the test tools you already use. Because codeband records every step, a run continues after the daemon restarts, waits days for a person without a running process, and can be forked later at any agent step.
A pipeline in code
Section titled “A pipeline in code”The example factory py-factory defines the pipeline intake. It takes a request for work and ends the run with one new ticket per Markdown bullet of the request’s body. Its parameters title, body and max_tickets are the fields of its run input.
"""The pipelines of this factory. pyproject.toml lists them under [tool.codeband]."""
import contextlibfrom datetime import datetime
import codeband as cb
from py_factory.function_steps import post_summary, received_atfrom py_factory.models import Plan, Ticketfrom py_factory.planning import plan_tickets
@cb.pipelinedef intake(title: str, body: str, max_tickets: int = 5) -> cb.RunResult | None: """Plan one ticket per Markdown bullet of the body of a request for work, as a person writes it.
The run stops when the body has no bullet or more than max_tickets. It ends with the tickets in its run result and no code change, and the daemon delivers the tickets. """ plan = plan_tickets(title, body) if not plan.tickets: raise cb.Stop("the request has no tickets: write each one as a '- ' bullet")
if len(plan.tickets) > max_tickets: raise cb.Stop(f"the request has {len(plan.tickets)} tickets, more than {max_tickets}: split it")
received = received_at()
# The run still ends with its tickets when the summary fails to send. The run journal keeps the function step's # error. with contextlib.suppress(cb.FunctionStepFailedError): post_summary(_summary(plan, received))
return cb.RunResult(tickets=[_new_ticket(plan, t) for t in plan.tickets])
def _new_ticket(plan: Plan, ticket: Ticket) -> cb.NewTicket: return cb.NewTicket(title=ticket.title, body=f"Part of the request {plan.title}.", tags=[ticket.kind, ticket.size])
def _summary(plan: Plan, received: datetime) -> str: lines = [f"{plan.title}: {len(plan.tickets)} tickets at {received:%Y-%m-%d %H:%M:%S} UTC"] lines += [f"- {t.kind}, {t.size}: {t.title}" for t in plan.tickets]
return "\n".join(lines)The pipeline’s name is the function’s name, intake, and a run request names the pipeline by it. The docstring is the pipeline’s description. plan_tickets is plain pipeline code, and received_at and post_summary are function steps. The Python SDK reference lists the decorator, its rules and its error messages.
A pipeline can name a sandbox definition of codeband.toml, as in @cb.pipeline(sandbox="go") in Python. Every agent step and every shell step of its runs then runs in a new sandbox from that definition, such as a container. A pipeline that names none uses the definition default, which is of kind host unless the file defines it: a process on the daemon’s machine without isolation.
The run input
Section titled “The run input”The run input is a JSON object with named, typed fields, and the fields are the parameters of the pipeline function: each parameter’s name, type and default are those of one field. A parameter without a default is a required field, and a pipeline function without parameters takes the empty object. The code server turns the fields into a JSON Schema. A trigger sends the input as JSON: codeband run takes it with --input, and {} when you leave the flag out.
codeband run py-factory/intake --input '{"title": "Release 1.2", "body": "- Fix the crash on start\n- Add a dark mode"}'A field with a default, such as max_tickets, can be left out. A missing field without a default, a field of the wrong type and a field that is no parameter are errors that name the field. The code server checks the input against the fields before the daemon records the run, so a wrong input starts no run. codeband run prints the error and exits with code 1:
codeband run py-factory/intake --input '{"body": "- Fix the crash on start"}'start run: run request rejected: the pipeline does not accept the input: 1 validation error for intaketitle Field required [type=missing, input_value={'body': '- Fix the crash on start'}, input_type=dict] For further information visit https://errors.pydantic.dev/2.14/v/missingThe input is part of the run request, and the first entry of the run journal records it.
A pipeline that starts from a ticket has a field named ticket with the SDK’s ticket type: an ID, a title, a body in Markdown without the title, tags and an optional URL. Every trigger of a ticket system fills that field, so the same pipeline runs with the ticket system of whoever starts it. A hint for a field, such as Annotated[int, Field(description="How many review cycles the run may take.")] in Python, is the field’s description in the JSON Schema, and the start form of the web interface shows it.
A run fork can start a new run from a recorded agent step with a changed input.
How a pipeline ends a run
Section titled “How a pipeline ends a run”The value that the pipeline function returns, or the error it raises, decides how the run ends. The final line and the exit code are those of codeband run.
| The pipeline | The run ends | Final line | Exit code |
|---|---|---|---|
| Returns a run result with a code change: a commit, a title and a description | With a code change, which the engine delivers to its run result destination, a patch file or a pull request | Where the code change went: the path of the patch file or the URL of the pull request | 0 |
| Returns a run result with new tickets and no code change | With no code change and its new tickets, which the engine delivers to their run result destination, such as ticket files | no code change, then new ticket: TITLE: PATH for each new ticket |
0 |
| Returns nothing, or a run result without a code change and without tickets | With no code change | no code change |
0 |
| Raises a stop with a reason | Stopped, on purpose | stopped: REASON |
3 |
| Raises another error and does not catch it | Failed, with the kind pipeline_error and the traceback |
failed: pipeline_error: … |
1 |
A run result with both parts ends with the line of the code change, then a line for each new ticket. In Python, a run result is cb.RunResult with a cb.CodeChange and a list of cb.NewTicket, a stop is raise cb.Stop(reason), and nothing is None. intake changes no code and returns its tickets, so its run ends with no code change and a line for each new ticket. A code change whose files equal the run’s start commit also ends the run with no code change.
A stop is for an input that the pipeline cannot work on, or a state that a person must fix. A request whose body has no bullet stops intake before it runs any function step:
codeband run py-factory/intake --input '{"title": "Release 1.2", "body": "Fix the crash on start"}'Started run gwswq0daf1stopped: the request has no tickets: write each one as a '- ' bulletRun lists every way a run ends, cancellations and code changes that the engine could not deliver among them.
Branches and loops are code
Section titled “Branches and loops are code”The pipeline function decides which step comes next with the code of its language. intake branches twice with if and cb.Stop. It catches the error of a failed function step with contextlib.suppress(cb.FunctionStepFailedError), so a summary that cannot be sent doesn’t fail the run. A pipeline that retries an agent wraps the agent step in a loop and catches cb.AgentStepFailedError.
Each call of a step inside a loop is a new step with its own counter. A loop that asks the agent writer for three agent steps records writer#0, writer#1 and writer#2. The Step page explains step IDs.
codeband infers a preview graph from these branches and loops before any run. codeband graph prints it, and Run explains it.
Parallel agent steps
Section titled “Parallel agent steps”A pipeline function is synchronous: it waits for each step before it goes on. To run agent steps of an agent at the same time, it starts each one, which gives back a handle at once, and then gathers the handles, which waits until every agent step has ended. Such an agent step is a parallel agent step. The engine runs all of them at once, each attempt in its own workspace, with no limit on their number. Only agent steps start this way.
import codeband as cb
from py_factory.hello import WriterInput, writer
@cb.pipelinedef write_hello_twice(instruction: str) -> cb.RunResult | None: """Run two agent steps of the writer at the same time and end the run with the cheaper one.""" task = WriterInput(instruction=instruction) first, second = cb.gather(writer.start(task), writer.start(task)) cheaper = min(first, second, key=lambda agent_step: agent_step.cost_usd)
change = cb.CodeChange(commit=cheaper.commit, title=cheaper.output.title, description=cheaper.output.summary) return cb.RunResult(code_change=change)In Python, agent.start() returns a cb.Handle, and cb.gather() returns the agent steps. The two agent steps of write_hello_twice are writer#0 and writer#1.
| Question | Rule |
|---|---|
| Where does a parallel agent step start? | At the run head as it is when the pipeline starts the agent step, unless pipeline code names another commit |
| Does it move the run head? | Never, also when its agent may write. writer#0 and writer#1 both start at the run’s start commit, and neither sees the code of the other |
| In which order does the gather return the agent steps? | In the order of the handles that it got, not in the order in which the agent steps ended |
| What if an agent step fails? | The gather waits until every agent step has ended, then raises the error of the first failed agent step in the order of its handles, such as cb.AgentStepFailedError in Python |
| What if the pipeline ends before it gathers? | A pipeline that returns, stops or raises while an agent step that it started has no step output waits for that agent step first. The run ends after every agent step that it started has ended |
| Which stage does it belong to? | The stage where the pipeline started it, also when it ends after the run entered another stage |
| What if the run fails or someone cancels it? | The engine stops the agent steps that still run. Their attempts end with the attempt failure kind cancelled, then the run ends |
codeband never merges the code of parallel agent steps on its own. The pipeline picks one agent step and goes on from its end commit, as write_hello_twice does, or it runs an explicit merge function step. To start the next agent step at the commit of the picked one, pipeline code names that commit, such as writer.using(at=cheaper.commit).do(...) in Python.
In the preview graph, two or more agent steps that the pipeline starts in a row are one parallel node, which holds an agent step node for each of them. A single started agent step is an agent step node, and the gather is no node.
Rules for your pipeline code
Section titled “Rules for your pipeline code”Give the same steps in the same order on every run replay
Section titled “Give the same steps in the same order on every run replay”codeband moves a run forward by run replay: it runs the pipeline function again from the start, and each recorded step returns its recorded value. Plain code between the steps runs again on every run replay, so it must decide the same way each time for the same input and the same recorded values. plan_tickets follows this rule. Run replay explains what happens when code breaks it.
Put the clock, files and the network in steps
Section titled “Put the clock, files and the network in steps”A value that can change between run replays, such as the time, belongs in a function step, which records it once. received_at reads the clock in a function step, so every run replay of intake sees the same time. Writes to files and calls to other services also belong in function steps, so a run replay doesn’t repeat them.
The factory
Section titled “The factory”A factory is the folder that holds your pipelines, the agents they use and the settings that list them. It can be a git repository of its own or a folder inside another repository. For the Python SDK, it is a Python project:
Directorypy-factory/
- pyproject.toml
Directorypy_factory/
- models.py
- pipeline.py the pipeline intake
- planning.py
- function_steps.py
- program.py the pipeline run_program
- feature.py the pipeline ship_feature and its agents
- planner.md
- builder.md
- reviewer.md
- hello.py the pipeline write_hello and the agent writer
- writer.md
Directorytests/
- …
The settings list each pipeline as module:function. Only a listed pipeline exists for codeband, so a helper that is never listed cannot start a run.
[tool.codeband]pipelines = [ "py_factory.pipeline:intake", "py_factory.program:run_program", "py_factory.feature:ship_feature", "py_factory.hello:write_hello",]The [tool.codeband] settings reference has the rules for each entry. A run that names a pipeline the factory doesn’t list starts no run, and codeband run prints start run: run request rejected: the factory has no pipeline 'NAME'.
The factory code server loads it
Section titled “The factory code server loads it”The factory code server of the SDK, the code server for short, loads the factory and runs its pipeline code and function steps for the daemon. For the Python SDK, start it in the factory folder:
uv run codeband codeserverIts first log record names the pipelines it loaded:
Nov 24 17:30:53.289 INF Loaded pipelines comp=codeserver pipelines="[intake run_program ship_feature write_hello]" folder=/home/ada/src/py-factoryWe recommend uv run codeband dev while you write pipelines: it starts the code server, the daemon and the web interface together in one terminal. Use codeband codeserver and codeband daemon as separate processes when you want to stop and start them one at a time, or to serve several factories from one daemon.
The code server loads the factory once, when it starts. codeband dev starts it again when you change a file of the factory, which is a factory reload. A factory that doesn’t load, for example because pyproject.toml has no pipelines list, keeps the code server running. It starts no run, and its runs in progress wait until it loads. Run problems has the fixes.
The code server describes the factory to the daemon in the factory manifest: its pipelines, agents, function steps and preview graphs, the folder of the factory, its git commit and whether it has uncommitted changes. The first journal entry of each run records the folder, the commit and whether the factory had uncommitted changes. We recommend keeping the factory in git and committing before you start runs that you want to compare later, so that each run names the exact code it ran.
One code server loads one factory. One daemon serves several factories, each in its own code server, under the names that the [factories.NAME] tables of codeband.toml give them. codeband dev serves the one factory in its working folder, under the name of that folder. Every command and every page of the web interface names a pipeline after its factory, such as py-factory/intake. Architecture shows how the parts fit together.
Factory reload
Section titled “Factory reload”codeband dev loads the factory again when a file of the working folder changes, appears or goes away, unless git ignores the file. This is a factory reload. codeband dev checks the files twice a second. In a folder outside a git repository every file counts, except those in __pycache__, in node_modules and in folders whose name starts with a dot. --reload=false turns the factory reload off, and you then load changed pipeline code with a new start of codeband dev.
| In a factory reload | What happens |
|---|---|
| The code server | Stops as on Ctrl-C, with SIGTERM and a kill 10 seconds later. Then the code server command starts again and loads the factory. For about a second no code server answers, and a codeband run in that second fails with code server unavailable |
| A run in progress | Makes its next invocation on the changed code |
| A function step that the stop cuts off | Runs again in the next invocation, so make its side effect safe to repeat |
| Code that does not load | The code server logs The factory does not load with the reason and keeps running. The runs of the factory wait, and the next change of a file starts a new factory reload, after which they invoke the code server at once |
| A code server that exits on its own | The daemon and the web interface keep running, and the next change of a file starts the code server again |
A change to codeband.toml or to the installed dependencies |
Is no factory reload. Stop codeband dev and start it again |
codeband dev logs Reloading the factory when a factory reload starts. The new code server then logs its process ID and the pipelines it loaded, as at the start:
Nov 30 15:49:43.539 INF Reloading the factory comp=daemonNov 30 15:49:43.718 INF Started code server comp=daemon command=~/src/py-factory/.venv/bin/codeband-codeserver pid=82610Nov 30 15:49:43.987 INF Loaded pipelines comp=codeserver pipelines="[intake run_program ship_feature write_hello]" folder=~/src/py-factoryNov 30 15:49:44.002 INF Serving pipelines comp=codeserver address=unix:~/.local/state/codeband/codeserver.sockA code server that exits on its own leaves this record. Its err holds the exit status or the signal, and is <nil> for exit code 0:
Nov 30 15:47:14.487 WRN The code server exited, so the next change of a file starts it again comp=daemon err="signal: killed"codeband daemon and codeband codeserver do not reload. A code server that you started with codeband codeserver loads changed code when you start it again.
Related
Section titled “Related”- Test a pipeline without a daemon calls
intakefrom pytest, where its function steps run as plain functions. - Build a pipeline that files tickets writes
intakefrom an empty folder, step by step. - Step explains function steps and shell steps, the steps a pipeline asks for, and their step IDs.
- Run replay explains how codeband runs a pipeline again and the rules that keep a run replay right.
- Run follows a run from its run request to how it ends.
- The Python SDK reference lists
@cb.pipeline,cb.RunResult,cb.Ticket,cb.Stopand the code server’s flags.