---
title: Testing and debugging
description: "Validate a workflow, run it on representative inputs, and use logs and outputs to decide what to change before activation."
---

Validate a workflow, run it on representative inputs, and use logs and outputs to decide what to change before activation.

## Testing

`andon workspace validate` sends the local source to the platform, which checks the
manifest, source policy, declarations, imports, and statically recognizable DSL
and executable-body errors with the SDK version deployments run on. It never
imports workspace modules or saves the source, and it needs a login. The
manifest's `sdk_version`, the installed `andon-ai`, and the platform must be on
the same SDK minor: `andon workspace validate` fails when the installed
SDK and the manifest differ, the platform rejects a manifest on another minor
than its own or ahead of its release, and commands warn while the installed SDK
or the manifest is behind the platform's minor. Each message names the
upgrade or the `sdk_version` to set. Bare names
in `@step` and `@tool` bodies must resolve under Python lexical scoping,
workspace imports must resolve inside the deployed source tree, wildcard and
platform-internal imports are rejected, SDK imports and module-qualified
references such as `agents.core.Agent` must stay within the public modules
(`andon_dsl.workflows`, `.agents`, `.tools`, `.tools.toolsets`, `.resources`,
`.integrations` and `.errors`) and the names in their `__all__`, and direct SDK
calls must exist on the sandbox runtime surface.

`andon workspace validate` checks workflow grammar and source-known call binding without
executing workspace code. `andon deployments create` runs those same checks, then imports
the published snapshot, resolves types and constants, and compiles the
workflow source. Deployment also checks step argument types and captured
values, constructor call binding, provable field omissions, and the
importability of types needed during execution. It does not execute step
bodies. Errors identify the file, module, workflow function, line, and column.
Use a deployed trial run to check value-dependent validation and behavior
that requires actual workflow inputs.

Unit tests live under `andon/tests/` and target the pure pieces (`logic/`,
validators, schemas). Call a step's original Python function through `.fn`.
Keep run fixtures in repo-root `inputs/` (start from
`inputs/sample_input.template.json`); they stay outside the deployed artifact.

Running an agent outside a workflow run raises. To unit-test a step or tool
that runs one, replace the agent's `run` with `unittest.mock.AsyncMock`:

```python
from unittest.mock import AsyncMock, patch

from andon.logic import email


async def test_summarize_returns_the_agent_summary() -> None:
    expected = EmailSummary(...)
    with patch.object(email.summarizer, "run", AsyncMock(return_value=expected)) as run:
        summary = await email.summarize.fn(message)
    assert summary == expected
    run.assert_awaited_once()
```

The patch replaces `run` on the agent object, so it applies wherever the
agent is imported.

Dependencies have two declarations with one truth: what deployed step
bodies may import is exactly the manifest's sandbox table:

```toml
[sandbox]
packages = ["pandas"]
```

That is one list per workspace, installed into the compile session and every
run's step session. `pyproject.toml` only serves the local test loop
and must carry a superset of those packages so tests exercise the same
libraries. Adding a package to `pyproject.toml` alone does nothing for
deployed runs.

Sandbox packages must publish wheels compatible with the sandbox's Python
interpreter and Linux platform. Source-only distributions fail provisioning;
the sandbox does not build packages from source. Shared validation and
serialization dependencies are pinned to the tested worker versions, and
conflicting package requirements also fail provisioning.

## Inspecting runs and downloading outputs

`andon runs watch <run_id>` reports status transitions. `andon runs show
<run_id>` reads the outcome and identifies the failing invocation when one was
recorded. Use `andon nodes list --run <run_id>` for node status, timing and
credits. Use `andon invocations list --run <run_id> --node <node_key>` to page
through a node's executions, including concrete map elements and loop
iterations. Filter either list with `--status` and jump to another page with `--offset`.

`andon invocations show <invocation_id> --run <run_id>` shows recorded value
previews, workflow-code errors and traceback, and artifact references. It marks
availability independently of preview truncation. Retained runs stay inspectable
by node key if the compiled labels are unreadable. Quote an internal error's
`correlation_id` to support.

Use `andon inputs show --run <run_id>` or `andon outputs show --run <run_id>`
to read the recorded JSON. Add `--invocation <invocation_id>` for a concrete
execution. Append the chunks returned through `--cursor` in order before parsing
them as JSON. A recorded null is `null`. An unrecorded value is unavailable.
Use `inputs download` or `outputs download` with the same selectors for the
complete value in one transfer.

A step's input and output may each serialize to 16 MiB. Inputs are recorded
before dispatch. An oversized input is retained for diagnosis and fails with
HTTP 413 before the step body runs. Pass file references for larger inter-step
data. `andon files upload <path>` returns an Andon file reference to use in
`--input`.

Downloads verify the digest and refuse an existing destination unless you
pass `--overwrite`. The default filename is the stored filename for
`files download`, or `<run_id>-<value>.json` or
`<invocation_id>-<value>.json` for value downloads. Use `-` as the destination
to write verified raw bytes to stdout, including in JSON output mode.
Diagnostics go to stderr. If the pipe closes early, the download exits quietly.

```bash
andon outputs download --run <run_id> --invocation <invocation_id> - | jq '.jobs | length'
andon files download <file_ref> - > report.pdf
```

### Model and agent tool execution evidence

`andon logs list --run <run_id>` pages recorded model and tool calls. Filter by
`--node`, `--invocation`, or call `--kind`. With `--invocation`, the listing
also carries the workflow log lines and terminal error. Entries start with the
most recent activity. Use `--sort oldest` to read from the beginning. Keep the
same sort when selecting another page. Use `--offset` to skip to the
desired entry and `--limit` to choose the page size. `--kind log` lists only the
lines and `--kind error` only the error. Both need `--invocation`. To read a
long user-readable invocation error, follow the `Next:` command. Later
plain-text pages show the next part of the same message. With `--json`,
follow `message_content.next_cursor` and concatenate `message_content.text`
in order. Use
`andon logs show <log_id> --run <run_id>` for recorded instructions, messages,
settings, request parameters, tool arguments and results, and usage. Model
messages appear latest first. Follow the cursor to continue the JSON. A model
call above the long-context pricing threshold carries `andon.long_context.*`
attributes with trimming advice.

A call that failed lists `failed: <kind>`, and `failure` in `--json`, with the
kinds a run error uses: `user_readable` when the run's input or a declared
usage limit caused it, such as a prompt over the model's capacity or a prompt
or response the provider refused on content grounds; `workflow_code` when your
tool code raised; `internal` when Andon or the model provider failed. A
`user_readable` failure also lists what to change, `failed: user_readable: <message>`
and `failure_message` in `--json`, as its run error states it, whether or not the
run failed on that call. If the message is shortened, `logs show` includes the
complete `failure_message` in its chunked JSON content. Any other call that
returned lists without a failure, even when its result goes unused, such as a
response cut off by the output token limit or a tool's retry request; the span
holds the result. A model call that raised holds the instructions and input
messages it sent, but no output or provider error; a refused response is
recorded as it returned. A request refused before sending records no input; its
failure message gives its token counts. A call that failed and was retried lists once
per attempt. A call cut short because its step or run stopped lists without a
failure or output.

Direct step-body calls to `ctx.parse_document`, `ctx.search_document`,
`ctx.read_pages`, and connections are not listed. `ctx.structured_extract`
appears as its inner model call. Use recorded step values and artifacts to
inspect operations outside the listed calls.

The API checks organization/run ownership; authors use their normal Andon
credentials. A call appears a few seconds after it finishes and is kept for 30
days. Capture settings and secret scrubbing affect recorded contents; missing
spans or fields are not proof that no call occurred. Paging a running workflow
can repeat or omit records; refresh from the first page after the run settles.
A resumed run can have multiple traces. The span handle identifies the recorded
trace and span.

### Log lines from workflow code

Records your workflow code emits through Python's `logging` at `INFO` and above
while a step runs are kept with that step: the level, the logger name, the
message, and the traceback of `logger.exception`. Each map element keeps its
own. They are sent when the step, or an agent's tool call, returns or raises.
A step that fails can lose its last lines; its error and traceback remain. A
step keeps its latest 199 lines, after a line that counts any earlier ones
it dropped. A logged exception caused by a failed Andon
platform call keeps your frames and says the platform call failed, without the
platform's own detail. `print` output and `DEBUG` records are not
kept.

```python
import logging

logger = logging.getLogger(__name__)

@step
def price(invoice: Invoice) -> Line:
    logger.info("Pricing invoice %s", invoice.number)
    ...
```

Read them with `andon logs list --run <run_id> --invocation <invocation_id>`,
beside the invocation's model and tool calls, or in the console: open the
run's Steps, select the step, and open Logs.

## Error taxonomy

| Raise | Means | Effect |
|---|---|---|
| `AgentRetryError` | model can repair this call/output | feedback to the model, bounded by `Agent(retries=)` |
| `StepRetryError` | transient failure, safe to re-run the step | consumes `@step(retry=Retry(retries=N))` budget (platform-transient failures do too, automatically) |
| `UserReadableError` | the person who started the run supplied something the workflow cannot use | run fails; the run shows the message verbatim, with no exception type or traceback |
| any other exception, such as `ValueError` | a bug or an unexpected state | run fails; the run shows the exception type, message, and workspace traceback, or, when raised from or while handling an Andon platform failure, an internal error with a correlation ID |

Platform tools and connections that reject a call from step code fail the step
with correction guidance. This includes undeclared connections, unsupported
connection operations, invalid arguments and rejected queries. A step or tool
return value that cannot be serialized also fails with guidance naming its
owner. These failures show as "Needs fixing" with no exception type or
traceback; fix the call or return value rather than catching the error.

Raise `UserReadableError` for one purpose: to reject what the person who
started the run supplied, when the workflow can judge it only after the run
starts. An uploaded document that turns out not to be a 10-K or 10-Q is the
typical case. The run fails with error kind `user_readable`, which the console
labels "Needs fixing", and shows the message verbatim, so write it for that
person and say what to supply:
`raise UserReadableError("Upload an issuer's Form 10-K or 10-Q filing.")`.
The message never carries another exception's text, a traceback, or a provider
payload.

Raise an ordinary exception for a bug or an unexpected state. The run then
fails with error kind `workflow_code`, which the console labels "Code error",
and shows the workflow's author the exception type, message, and workspace
traceback. An exception raised from an Andon platform failure, or while handling
one, fails the run with error kind `internal` instead, since the platform
failed: the run shows a correlation ID and is refunded.

The platform raises `UserReadableError` when a run breaks a contract its user
can fix, such as a disabled tool or a document over a size limit; the message
surfaces verbatim. Workflow code does not catch it as a fallback signal.

When the workflow should continue or branch on an outcome, or the outcome is a
legitimate "no", return a typed result instead of failing. Represent expected
recoverable outcomes in the agent's output type (usually a discriminated
union), then branch on that typed result in the workflow.

Run input is checked against the input type's JSON Schema when the run is
created, and a mismatch is returned to the caller at once, with no run created.
The check includes the format of a field typed `AnyUrl` or one of its
subtypes such as `HttpUrl`, `date`, `datetime`, `time`, `timedelta`, `UUID`,
`IPv4Address` or `IPv6Address`; an `EmailStr` is checked only for an `@`. Type
a field as `HttpUrl` or `date` where you can: a `str` field with a validator,
and any other formatted type such as `UUID4` or `IPvAnyAddress`, is only
checked once the run starts. Give alternative inputs as a tagged union
(`Field(discriminator=...)`): a mismatch is then reported for the field inside
the arm the tag selects, where an untagged union of models reports only that
the value matches none of them.

Input that passes the schema and that the input type still rejects fails the
run when it starts, with a user-readable message that lists each failure and
its field location. The text of a `ValueError` or `AssertionError` raised by a
Pydantic validator on the input type is shown as written, so address it to the
person starting the run:
`raise ValueError("Provide either a filing PDF or a filing URL.")`. A rule
that can be checked from the input value alone and that the type's shape cannot
express belongs in these validators, which reject the run before its first
step.

A response to `wait_for_review` or `wait_for_event` is checked against the
response type's JSON Schema when it is submitted, and a mismatch is returned to
the responder at once. The event is then `submitted` until the run resumes and
the response type accepts it. A response that passes the schema but fails a
Pydantic validator on the response type does not fail the run. The wait reopens
with its deadline unchanged and shows the responder the validator's message, in
the review form and in `andon signals show`, so address it to the person
responding. Until a new response arrives the signal's `needs_correction` is
true, and `andon signals list --needs-correction` lists such signals (with
`--kind review`, only reviews). The responder sees that message only after the
run has resumed, so express a rule in the type's shape where you can: a
required field, a `Literal`, a `Field` constraint, or a tagged union such as
`Approve | Reject`.

Workflow field/key/index lookup failures, non-list or unequal-length mapped
arguments, incompatible comparisons, and rejected returns
fail the run with an actionable message. Messages retain safe path structure
and name the consuming operation when its authored binding is known. Literal
indexes and keys appear as `[…]`: a compiled literal may have come from a
private module constant. Workflow inputs and loop state use descriptive labels;
messages omit evaluated data and available dictionary keys. Handle optional or
missing data inside a `@step`, supply equally sized lists
for mapped arguments, and return a value accepted by the return annotation.

## Building and improving with execution evidence

1. **Define and measure success.** Keep representative inputs and expected
   outcomes under repo-root `inputs/`. Specify the quality, cost and latency
   measures before changing code; verify references against source evidence or
   requirements. Start with a few contrasting cases and reserve held-out cases.
2. **Inspect and isolate a task.** Run the current implementation against an
   explicit deployment. Use `andon runs show <run_id>`, `invocations show`,
   `inputs download`, `outputs download`, and `logs list` as described above
   to locate the first wrong result or expensive operation. Per-step credits
   and timestamps are in `runs show <run_id> --json`. Group observed problems
   into concrete tasks with inputs, expected behavior and a success check;
   these boundaries can differ from the current steps. Reconsider orchestration
   when the structure itself causes the failure.
3. **Trial one hypothesis, then integrate.** Test pure helpers in `andon/tests/`.
   For runtime work, declare a temporary `@workflow` calling the production step,
   save, validate, and build the revision, then run `andon runs start <trial>` with
   `--deployment <id>` and `--input-file inputs/<case>.json`. Adapt retained
   input to the trial's declared schema:
   one positional argument is recorded as its value; keyword or multiple
   arguments are recorded by parameter name. Supply required artifacts. Trials
   use the declared connections and perform real external writes: verify a test
   destination before including a writing step, or omit it from the trial. Hold
   scoring and other settings fixed, compare the baseline, and repeat when model
   variability could explain the difference. Check held-out cases and the
   complete workflow, recording
   deployment IDs, outcomes, credits and elapsed time. Remove trial workflows
   and their manifest entries, rebuild, and verify that final candidate before
   `andon deployments activate <id> --expected-active-deployment <active_id>`.

Use `andon deployments diff <base> <candidate>` to review the source change.
Keep workflow-specific measures and helpers in the workspace. If an experiment
reveals a platform limitation, report the concrete evidence and missing capability
to the user; do not infer a missing capability from a truncated preview or trace.
