Handle a function step that fails or times out
Handle a failed function step in pipeline code when the function step calls a service that can be slow or down, and the run must go on, call the function step again or stop with a reason. In this guide you point the function step post_summary of intake at a webhook that answers slowly, see the function step time out while the run finishes, and then make intake call the function step again with a key that lets the webhook drop the repeat. At the end, codeband run prints ✗ post_summary#0 function step failed: TimeoutError: the function step did not finish within its timeout, then ✓ post_summary#1 function step and no code change, and the webhook prints ignored a repeat. If something goes wrong on the way, see Troubleshooting at the end of this page.
Before you start
Section titled “Before you start”- You built
intakein the tutorial Build a pipeline that files tickets, and your terminal is in its folderpy-factory. Run each command there. codeband devdoesn’t run. If it still runs from the tutorial, press Ctrl-C in its terminal.- jq for the check at the end, as
jq --versionshows.
How a function step fails
Section titled “How a function step fails”A function step fails when its function raises an exception or runs longer than its timeout. The engine records the failure in the run journal in place of a value, so the function step doesn’t run again in this run. Every later invocation, the next run replay of the pipeline function, raises cb.FunctionStepFailedError at the call of the function step.
| In the function step | The run journal records | The call in pipeline code | codeband run prints |
|---|---|---|---|
| The function returns | The value | Returns the value | ✓ post_summary#0 function step |
| The function raises | The type and the message of the exception | Raises cb.FunctionStepFailedError, with the exception’s type in type |
✗ post_summary#0 function step failed: URLError: … |
| The function runs longer than the timeout | The type TimeoutError and the function step did not finish within its timeout |
Raises cb.FunctionStepFailedError with the type TimeoutError |
✗ post_summary#0 function step failed: TimeoutError: the function step did not finish within its timeout |
| The code server stops before the engine records a value | Nothing | Runs the function step again in the next invocation | One line, after the function step ran again |
codeband doesn’t stop a function step that times out. Its function runs on in the background of the code server, so its side effect, such as a request to a webhook, can still happen after the function step failed.
Your pipeline code decides whether the run goes on, calls the function step again, stops or fails after a function step fails.
| The run should | Pipeline code | The run |
|---|---|---|
| Go on without the function step’s value | Catches cb.FunctionStepFailedError, as intake does with contextlib.suppress |
Goes on to its next step |
| Call the function step again | Calls the function step again in a loop, as step 5 shows. Each call is a new step with its own step ID, such as post_summary#1 |
Goes on after the first call that succeeds |
| Stop with a reason | Catches cb.FunctionStepFailedError and raises cb.Stop |
Ends stopped, and codeband run exits with code 3 |
| Fail | Doesn’t catch it | Ends failed with pipeline_error, and codeband run exits with code 1, as Troubleshooting shows |
-
Choose the function step’s timeout
A function step’s timeout limits how long its function runs, 5 minutes by default.
post_summaryinpy_factory/function_steps.pysets 10 seconds:py_factory/function_steps.py @cb.function_step(timeout=timedelta(seconds=10))def post_summary(text: str) -> bool:Set a timeout on each function step that waits for another service, longer than the time the function step takes when the service works. The function step’s timeout limits the whole function. A client’s timeout, such as
timeout=5ofurlopeninpost_summary, limits each wait for the network: a server that sends one byte every 2 seconds keepsurlopenreading for as long as it sends. A shell step has a timeout of its own, which the engine enforces by stopping the program. -
Start a webhook that answers slowly
Save this file as
/tmp/webhook.py. It prints the first line of every summary it gets. It answers a new summary with one byte every 2 seconds, so the answer takes 20 seconds and each wait is shorter than the 5 seconds ofurlopen. It answers a summary that it got before at once, and it ignores a request whose key it got before./tmp/webhook.py """A webhook that prints each summary it gets. It answers a new summary in 20 seconds and a repeated one at once."""import jsonimport timefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServertexts: set[str] = set()keys: set[str] = set()class Webhook(BaseHTTPRequestHandler):def do_POST(self) -> None:text = json.loads(self.rfile.read(int(self.headers["Content-Length"])))["text"]slow = text not in textstexts.add(text)key = self.headers.get("Idempotency-Key")if key is None:print(f"received: {text.splitlines()[0]}", flush=True)elif key in keys:print(f"ignored a repeat: {text.splitlines()[0]} (key {key})", flush=True)else:keys.add(key)print(f"received: {text.splitlines()[0]} (key {key})", flush=True)# One byte every 2 seconds: each wait is shorter than the 5 seconds that post_summary's urlopen waits.self.send_response(200)self.send_header("Content-Length", "10")self.end_headers()for _ in range(10):self.wfile.write(b".")if slow:time.sleep(2)def log_message(self, *args: object) -> None:passprint("Listening on http://127.0.0.1:8090/", flush=True)ThreadingHTTPServer(("127.0.0.1", 8090), Webhook).serve_forever()Open a second terminal, change to the folder
py-factoryand start the webhook with the Python of the factory:Terminal window uv run python /tmp/webhook.pyIt prints
Listening on http://127.0.0.1:8090/and keeps running. -
Start codeband with the webhook
Open a third terminal, change to the folder
py-factoryand start the daemon and the code server, with the webhook’s URL inPY_FACTORY_WEBHOOK:Terminal window PY_FACTORY_WEBHOOK=http://127.0.0.1:8090/ uv run codeband devIt logs the same lines as in the tutorial,
Loaded pipelines comp=codeserver pipelines=[intake]andListeningamong them, and keeps running. Function steps run in the code server, sopost_summaryreads the URL from the code server’s environment. -
Run
intakeand see the function step time outIn the first terminal, start a run.
codeband devserves your factory under the name of its folder,py-factory, so the pipeline ispy-factory/intake:Terminal window mkdir -p /tmp/py-factory-ticketsuv run codeband run py-factory/intake --tickets /tmp/py-factory-tickets \--input '{"title": "Release 1.2", "body": "- Fix the crash on start\n- Add a dark mode"}'post_summarywaits 10 seconds for the webhook, then the function step fails.codeband runprints the failure, thenno code changeand the files of the two new tickets, and exits with code 0. Your run ID is different:Output Started run nkapj812dw✓ received_at#0 function step✗ post_summary#0 function step failed: TimeoutError: the function step did not finish within its timeoutno code changenew ticket: Fix the crash on start: /tmp/py-factory-tickets/nkapj812dw/01-fix-the-crash-on-start.mdnew ticket: Add a dark mode: /tmp/py-factory-tickets/nkapj812dw/02-add-a-dark-mode.mdThe next invocation raised
cb.FunctionStepFailedErrorat the call ofpost_summary.contextlib.suppress(cb.FunctionStepFailedError)inintakecaught it, so the run finished with its tickets.The terminal of the webhook prints one line, with the time that
received_atrecorded:Output received: Release 1.2: 2 tickets at 2026-11-25 20:05:12 UTCThe summary reached the webhook although the function step failed. A second call of the function step sends it again.
-
Call the function step again with a key that stays the same
A function step runs at least once. It runs again when pipeline code calls it again after a failure, and when the code server stops after the function step sent its request and before the engine recorded the value. Make each repeat send the same key, so that the receiver can drop it. Build the key from recorded values or from the function step’s arguments, never from the clock or a random number inside the function step: a repeat would get a new key.
In
py_factory/function_steps.py, replace the functionpost_summarywith this version, which sends its argumentkeyin the headerIdempotency-Key. The highlighted lines changed:py_factory/function_steps.py @cb.function_step(timeout=timedelta(seconds=10))def post_summary(text: str, key: str) -> bool:"""Send the text as JSON to the webhook, with the key in a header. Return False when no webhook is set."""url = os.environ.get(WEBHOOK_ENV, "")if not url:return Falsebody = json.dumps({"text": text}).encode()headers = {"Content-Type": "application/json", "Idempotency-Key": key}request = urllib.request.Request(url, data=body, headers=headers, method="POST")with urllib.request.urlopen(request, timeout=5) as response:response.read()return TrueIn
py_factory/pipeline.py, replace the comment and thewithblock before thereturnwith the highlighted lines:py_factory/pipeline.py received = received_at()# Call post_summary at most three times. Every call sends the same key, so the webhook can drop a repeat.for _ in range(3):with contextlib.suppress(cb.FunctionStepFailedError):post_summary(_summary(plan, received), key=received.isoformat())breakreturn cb.RunResult(tickets=[_new_ticket(plan, t) for t in plan.tickets])The key is the time that
received_atrecorded. It is the same in every call and on every invocation of the run, and differs in the next run. A call that fails leads to the next one, and the first call that succeeds ends the loop. After three failed calls, the run goes on without a summary.Commit the change, so the run names the commit of the code it ran:
Terminal window git commit -am "Send the summary at most three times with the same key"codeband devloaded the factory again when you saved the file, so the code server runs the new code. Start the same run as in step 4 in the first terminal. The summary holds the time that the new run recorded, so the webhook gets a new summary and answers slowly. The first call times out, and the second one succeeds:Output Started run yd4k470gk9✓ received_at#0 function step✗ post_summary#0 function step failed: TimeoutError: the function step did not finish within its timeout✓ post_summary#1 function stepno code changenew ticket: Fix the crash on start: /tmp/py-factory-tickets/yd4k470gk9/01-fix-the-crash-on-start.mdnew ticket: Add a dark mode: /tmp/py-factory-tickets/yd4k470gk9/02-add-a-dark-mode.mdThe webhook got the summary twice, once from each call, and ignored the second one:
Output received: Release 1.2: 2 tickets at 2026-11-25 20:06:39 UTC (key 2026-11-25T20:06:39.111161+00:00)ignored a repeat: Release 1.2: 2 tickets at 2026-11-25 20:06:39 UTC (key 2026-11-25T20:06:39.111161+00:00)
Check that it worked
Section titled “Check that it worked”The run journal holds one record for each call. Print the records of post_summary:
jq -c '.stepFinished // empty | select(.stepId | startswith("post_summary"))' \ ~/.local/state/codeband/store/runs/RUN_ID/journal.jsonlPut the run ID that codeband run printed in step 5 in place of RUN_ID. The command prints two lines, the error of the first call and the value of the second:
{"stepId":"post_summary#0","functionStep":{"error":{"type":"TimeoutError","message":"the function step did not finish within its timeout"}}}{"stepId":"post_summary#1","functionStep":{"value":"true"}}Each call has its own step ID, so a later invocation of this run raises cb.FunctionStepFailedError again for post_summary#0 and returns true for post_summary#1, without a request to the webhook.
Make other side effects safe to repeat
Section titled “Make other side effects safe to repeat”A key helps only when the receiver drops a request with a key it has seen. The way to make a repeat harmless depends on what the function step changes.
| The function step | Make a repeat harmless by |
|---|---|
| Writes files | Naming them after a recorded value, such as the time that received_at recorded, so a repeat overwrites the same files |
| Calls a service that accepts an idempotency key | Sending a key built from recorded values or from the function step’s arguments, as step 5 does |
| Creates something with a name, such as a record in another service | Looking for it first, and returning what exists instead of creating a second one |
New tickets need none of this: a pipeline returns them in its run result, and codeband delivers them once, when the run ends.
Clean up
Section titled “Clean up”Press Ctrl-C in the terminals of the webhook and of codeband dev, and run rm /tmp/webhook.py. To return intake to the version of the tutorial, run git revert --no-edit HEAD.
Troubleshooting
Section titled “Troubleshooting”For an error that this page doesn’t cover, see Run problems.
failed: pipeline_error: … FunctionStepFailedError: function step post_summary#0 failed: …
Section titled “failed: pipeline_error: … FunctionStepFailedError: function step post_summary#0 failed: …”Pipeline code called a function step that failed and didn’t catch cb.FunctionStepFailedError, so the run fails and codeband run exits with code 1. The message is the traceback. Its last line names the function step, the exception’s type and its message:
✗ post_summary#0 function step failed: TimeoutError: the function step did not finish within its timeoutfailed: pipeline_error: Traceback (most recent call last): … File "…/py-factory/py_factory/pipeline.py", line 32, in intake post_summary(_summary(plan, received)) …codeband._model.FunctionStepFailedError: function step post_summary#0 failed: TimeoutError: the function step did not finish within its timeoutCatch the error around the call, as intake does, and commit. codeband dev loads the changed code when you save the file. Then start a new run: a run that failed stays failed.
✗ post_summary#0 function step failed: URLError: <urlopen error [Errno 61] Connection refused>
Section titled “✗ post_summary#0 function step failed: URLError: <urlopen error [Errno 61] Connection refused>”The webhook doesn’t run, so every call fails at once. With the loop of step 5, codeband run prints the line for post_summary#0, post_summary#1 and post_summary#2, then no code change. On Linux, the number is 111. Start the webhook as in step 2.
codeband run prints ✓ post_summary#0 function step, and the webhook prints nothing
Section titled “codeband run prints ✓ post_summary#0 function step, and the webhook prints nothing”codeband dev started without PY_FACTORY_WEBHOOK, so post_summary sent nothing and returned False. Stop codeband dev with Ctrl-C and start it with the command of step 3.
codeband run prints no line for post_summary#1
Section titled “codeband run prints no line for post_summary#1”The code server still runs the code from before step 5. Save the file of step 5: codeband dev then loads the factory again. If you started codeband dev with --reload=false, stop it with Ctrl-C and start it again.
Related
Section titled “Related”- Run replay explains why a function step runs at least once, and how a later invocation returns its recorded value or error.
- Step explains where a function step runs and what happens when it times out.
- Python SDK lists the
timeoutof@cb.function_stepand the fields ofcb.FunctionStepFailedError. - Run a program in the target repository shows how a shell step reports a failure in its value instead of raising an error.