Run Infrastructure
Starting a Run
Workflows can be triggered in two ways:
| Method | Where | Who |
|---|---|---|
| Run panel | Inside the Agent Builder editor (▶ button) | Editors testing drafts |
| REST API | POST /api/v1/agent-workflows/{id}/run | Applications, automations |
Run request body:
{
"input": "Summarize the following ticket: ...",
"state": {}
}input is the text the first node receives (also kept as state['trigger_input']). state is optional: its keys are in the run's state before the first node runs, readable as state['key'] or state.get('key') in any expression. For example, "state": {"customer": "acme"} makes state['customer'] return acme. trigger_input is always set from input and can't be overridden.
Input length limit: input is capped at 50,000 characters. Requests exceeding this limit are rejected with HTTP 422 before the workflow executes.
Rate Limiting
To protect shared infrastructure, a sliding-window rate limit is enforced per user:
| Limit | Window | Behavior when exceeded |
|---|---|---|
| 20 runs | 1 minute | The run endpoint returns a run_error SSE event immediately; no workflow executes |
The limit is tracked in Redis. If Redis is unavailable the check is skipped (fail-open). Operators can adjust the limit with the WORKFLOW_RUN_RATE_LIMIT_PER_MINUTE environment variable (set to 0 to disable).
Run States
| State | Meaning |
|---|---|
running | Actively executing nodes |
waiting_decision | Paused at a review-mode agent node or a user_approval node; an inbox task exists and awaits a reviewer's decision |
ready_to_resume | The reviewer has decided (or the review timed out with auto_proceed); the server resumes the run on its own within moments |
completed | All paths reached an end node |
failed | An unhandled error occurred; run terminated |
rejected | A reviewer rejected the run at a pause point; terminated without completing |
cancelled | POST /runs/{run_id}/cancel was honored |
SSE Event Streaming
While a run is in progress, output is streamed in real time using Server-Sent Events (SSE). The run endpoint (POST /api/v1/agent-workflows/{id}/run) returns a streaming response directly — no separate stream connection is needed:
POST /api/v1/agent-workflows/{workflow_id}/run
Authorization: Bearer <token>
Accept: text/event-stream
Content-Type: application/json
{"input": "Summarize this ticket: ..."}The response includes an X-Run-Id header with the run's ID, available as soon as the response starts — before any node has necessarily completed (unlike learning the run ID from a node_paused event, which only happens if the run actually pauses). Capture it if you need to reattach to this run later via GET /runs/{run_id}/stream (e.g. after a dropped connection) or cancel it via POST /runs/{run_id}/cancel.
Each line in the response is a JSON-encoded event:
data: {"event": "node_start", "node_id": "classify_1", "node_type": "classify", "label": "Classify Ticket"}
data: {"event": "node_output", "node_id": "classify_1", "text": "billing"}
data: {"event": "node_complete", "node_id": "classify_1", "output": "billing", "latency_ms": 412}
data: {"event": "node_start", "node_id": "agent_billing", "node_type": "agent", "label": "Billing Agent"}
data: {"event": "node_output", "node_id": "agent_billing", "text": "Your invoice shows"}
data: {"event": "node_output", "node_id": "agent_billing", "text": " a discrepancy in..."}
data: {"event": "node_complete", "node_id": "agent_billing", "output": "Your invoice shows a discrepancy in...", "latency_ms": 1823}
data: {"event": "run_complete", "final_output": "Your invoice shows a discrepancy in...", "total_ms": 2401}
Event types:
| Event | When emitted | Key fields |
|---|---|---|
node_start | When a node begins executing | node_id, node_type, label |
node_output | For each LLM token or partial output | node_id, text |
node_complete | When a node finishes | node_id, output, latency_ms |
node_error | When a node fails (guardrails, timeout, etc.) | node_id, error |
node_paused | When a user_approval node pauses the run | node_id, run_id, task_id, review_group, expires_at |
run_complete | When all nodes finish | final_output, total_ms |
run_error | Unhandled error or rate limit exceeded | error |
run_cancelled | The run honored a POST /runs/{run_id}/cancel request | message |
node_complete is always emitted before node_paused or node_error on the same node. This guarantees the run timeline has a complete record for every node that executed, even when the run halts.
In the editor, the Run panel connects to this stream automatically and renders token output in real time, with a node execution timeline on the side.
Heartbeat
To keep long-running streams alive through reverse proxies and load balancers (which close idle connections, after 120 seconds on hrida.ai), the server sends an SSE comment line whenever the stream has been silent for SSE_HEARTBEAT_INTERVAL_SECONDS (default 15):
: heartbeat
Heartbeats go out during a silent stretch, such as a slow LLM call or a classify or guardrails node that streams no tokens, so a proxy never sees an idle connection. Both the run stream and the resume stream after an approval send them. SSE comment lines (starting with :) are ignored by SSE parsers but reset the idle timer at the network layer. No action is needed on the client side; EventSource and fetch handle them automatically.
Connection drop detection
If the SSE connection drops mid-run (network interruption, proxy timeout, closed tab), the editor's Run panel shows a "Connection lost — Reconnect" banner. The run continues on the server regardless: it executes in a background task, not in the HTTP response, so a disconnect only stops the stream. The run still completes, fails or pauses, and its status and timeline are recorded as usual.
Clicking Reconnect reattaches to the same run via GET /runs/{run_id}/stream, using the run ID from the initial X-Run-Id response header. It never starts a new run. Events from before the drop are not replayed: the stream continues from wherever the run currently is, then ends with the run's final event (run_complete, run_error, run_cancelled or node_paused). Listeners on another API replica receive the run's events through Redis. If no process is publishing the run any more, the stream reports how the run ended, taken from its record.
What GET /runs/{run_id}/stream does depends on the run's status:
| Status | Result |
|---|---|
running | Reattaches to the live run |
ready_to_resume | Resumes a paused run after its inbox decision (see Pause & resume) |
| anything else | HTTP 409, because there's nothing to stream; read the result from GET /runs/{run_id} |
Resilience & Fault Handling
Production workflows call external, occasionally-unreliable dependencies — LLM providers, MCP servers, knowledge bases. These mechanisms keep a single flaky dependency from taking down an entire run.
Per-node error handling: on_error
Every node accepts an on_error config field:
| Value | Behavior |
|---|---|
halt (default, or unset) | A node failure aborts the run — no further nodes execute |
skip | The failure is still fully reported (node_error SSE event, recorded in the run timeline), but the node completes with empty output and the rest of the graph continues to run |
Use skip on nodes whose output other branches don't depend on — e.g. a best-effort logging/notification step that shouldn't take down the main path if it fails.
A guardrails node's failures count as node failures here: a FAIL verdict, an empty reply, or a failed LLM call. With skip, the run continues past the gate and the content it checked goes on to the next node, while the node_error event still records why it failed. Use that only for advisory checks; leave real safety gates on the default halt.
Circuit breakers
LLM providers, mcp servers, file_search, and knowledge-base retrieval (used by Skill knowledge injection) are each tracked by an independent circuit breaker, keyed per provider/server/knowledge-base (an LLM provider's key is its type plus base URL):
- Opens after 5 consecutive failures for that key. For an LLM provider, a failure is a connection error, a timeout, or an answer the provider is responsible for: a server error (
5xx), a rate limit (429) or a request timeout (408). Errors caused by the request or the configuration (400,401,403,404) don't count: switching providers would hide them. - Auto-resets to half-open after 60 seconds, so a recovered dependency is retried automatically without manual intervention.
- LLM provider breaker state is shared across worker pods via Redis in a Tier-2 deployment — one pod tripping the breaker is immediately visible to the others, instead of each pod having to independently accumulate its own 5 failures.
- While open, the node doesn't hang or crash the run: LLM calls go to a fallback provider when there is one (see below); other node types complete with a clear
circuit open — too many recent failuresoutput. - Admins see each provider's state in the catalog's LLM Providers tab: Healthy, Failing or Down.
Retry with backoff
Transient LLM errors — rate limiting, timeouts, 503/529, "overloaded" — on the main agent / classify / guardrails dispatch path are retried automatically: up to 3 attempts, with exponential backoff (2s, then 4s). Only failures caught before any real output reached the stream are retried — once a response has started streaming to the client, a failure mid-stream is surfaced as-is rather than retried (retrying would mean duplicating or discarding output the client already received).
LLM fallback provider
A node's LLM call switches to another provider when its own is down, instead of failing:
- For a node with its own provider (a per-node LLM override): first the run's default provider (the space's or the catalog's).
- Then the catalog's fallback provider: the one marked Fallback in the catalog's LLM Providers tab, with its own first allowed model.
The call switches:
- at once, without calling the provider, while the provider's circuit breaker is open;
- on the failing call itself, when the provider fails on its side (connection error, timeout,
5xx,429,408) before any text reached the caller. Text already streamed is never repeated, so a failure after it is reported instead.
Each provider is tried at most once per call, skipping any whose own breaker is open, and a provider at the same address as the one that failed is skipped (it would fail with it). When a call is answered by a fallback, the node's node_complete event carries a warning naming both providers, so the run shows it. Without a usable fallback, the error is reported as before and the retry with backoff applies.
When a call switches, the node's prompt is sent to the fallback provider. Mark as fallback only a provider you may send that data to.
Workflow-level auto-escalation
A workflow that fails repeatedly can automatically raise an inbox task instead of failing silently forever. Configure it via two keys stored on the workflow graph (alongside the graph's existing metadata):
| Key | Meaning |
|---|---|
_auto_escalate_after_failures | Number of consecutive failed runs that triggers escalation |
_auto_escalate_group | Space role or admin group the escalation task is assigned to (default: lifecycle_manager) |
The check runs at the end of every failed run. It fires exactly once per failure streak — the moment the consecutive-failure count first reaches the threshold — so a chronically-broken workflow doesn't spam a new inbox task on every subsequent run after that.
Workflow-level timeout ceiling
Inside a run, each LLM node is bounded by LLM_NODE_TIMEOUT_SECONDS (default 120 s; per node: llm.timeout_seconds), which covers every step of an agent loop, and each agent node takes at most AGENT_MAX_TOOL_ROUNDS tool steps (default 8, at most 25; per node: max_tool_rounds) before its answer-only last call.
Every run is bounded by WORKFLOW_MAX_TIMEOUT_SECONDS (default 600s) as a last-resort guard against a stuck while_loop or hung call. Hitting this ceiling is tracked as its own OTel metric, distinct from an ordinary node failure — see Logging & Tracing → Metrics for hridaai.workflow.timeout_ceiling_hits.total.
Pause & Resume
How pause works
When execution reaches a user_approval node (or a review-mode agent), the run's status becomes waiting_decision and the runtime:
- Creates an inbox task for the reviewer.
- Emits a
node_pausedSSE event withnode_id,run_id,task_id,assigned_groupandexpires_at. - Suspends execution and ends the stream. No further nodes run until a decision is made.
The reviewer sees the task in Dashboard > Inbox (or in any configured notification channel). The task shows the message text and the previous node's output.
Deciding via inbox
The reviewer clicks Approve, Modify, Reject or Delegate in the inbox UI, optionally with a comment (required for Reject).
Internally this calls:
POST /api/v1/inbox/{task_id}/decide
{
"decision": "approve",
"notes": "Looks good"
}comment is accepted as another name for notes.
What happens after the decision
- Approve / Modify: the run's status becomes
ready_to_resume, and the server resumes it straight away in the background. Nobody needs to have the run open.GET /api/v1/agent-workflows/runs/{run_id}/streamattaches to the resumed run, or starts the resume if it hasn't begun yet. The decision and comment are in state asapproval_decision(approveormodify) andapproval_comment. With Modify, the next node receives the reviewer's edited text. - Reject: if the approval node has an edge labelled
reject, the run resumes down it, withapproval_decision=reject. Otherwise the run ends with statusrejected, and no later node runs. - Delegate: nothing changes for the run; the task moves to the chosen colleague, still pending.
Edges out of a user_approval node labelled approve, modify or reject are followed only for that decision; see user_approval.
A periodic check (every 30 seconds) also resumes any run still in ready_to_resume. That covers a review that timed out with auto_proceed, which continues as an approval, and a resume that couldn't start at decision time. Each run is resumed once, however many servers try. A resumed run executes in the background like any other, so it also survives a dropped stream and can be reattached.
Execution Mode (Review Nodes)
agent nodes support an execution_mode config field:
| Mode | Behavior |
|---|---|
auto (default) | Node executes immediately; output moves to the next node |
review | Node output is held and an inbox task is created for a reviewer to approve before the workflow continues |
review mode is different from user_approval node: it pauses on the output of an existing node, whereas user_approval is a dedicated step you insert explicitly in the graph.
Run History and Analytics
All runs are stored with their full state, timeline, and cost metadata.
Viewing runs in the editor
Click the Runs tab in the right panel of the editor to see the run history for the current workflow, including status, latency, and token cost.
Per-workflow analytics API
These endpoints are accessible to any agent_developer role — no admin access required:
List runs:
GET /api/v1/agent-analytics/workflows/{workflow_id}/runs
?status=completed # filter by status
&limit=25 # page size (max 200)
&offset=0 # pagination offset
&start_ts=1700000000 # Unix timestamp filter
&end_ts=1800000000Response:
{
"items": [
{
"id": "run_abc123",
"workflow_id": "wf_xyz",
"status": "completed",
"started_at": 1700001000,
"ended_at": 1700001003,
"duration_ms": 3186,
"triggered_by": "user_id",
"error_message": null,
"prompt_tokens": 512,
"completion_tokens": 128,
"total_tokens": 640,
"cost_usd": 0.0012
}
],
"total": 42
}Aggregate summary:
GET /api/v1/agent-analytics/workflows/{workflow_id}/summary
?start_ts=1700000000
&end_ts=1800000000Response:
{
"total_runs": 42,
"completed_runs": 38,
"failed_runs": 3,
"paused_runs": 1,
"success_rate": 0.9048,
"avg_duration_ms": 3186.0,
"p95_duration_ms": 7842.0,
"total_prompt_tokens": 21504,
"total_completion_tokens": 5376,
"total_cost_usd": 0.0504
}For admin-level analytics across all workflows, catalogs, and node types, see the Admin > Analytics section of the documentation.
For structured logs, distributed traces, and OTel metrics for runs and nodes, see Logging & Tracing.
Cancelling a Run
POST /api/v1/agent-workflows/runs/{run_id}/cancelSame access rule as the run-status endpoints: only the run's owner or an admin. Returns 404 if the run doesn't exist, 409 if it's already in a terminal state (completed/failed/rejected/cancelled — nothing to cancel), 503 if Redis is unavailable (cancellation isn't silently accepted as a no-op).
This requests cancellation — it doesn't cancel synchronously. The endpoint sets a Redis flag (hrida:cancel:{run_id}); the process actually executing the run (the API process for a direct/SSE run, or a Tier-2 worker pod) checks that flag on a timer — the same cadence as the WORKFLOW_MAX_TIMEOUT_SECONDS guard, throttled to once every WORKFLOW_CANCEL_CHECK_INTERVAL_SECONDS (default 2s) — and marks the run cancelled itself once it sees the flag. In practice this means a cancel typically takes effect within a couple of seconds, not instantly mid-node.
A run sitting in waiting_decision or ready_to_resume has no execution loop to check the flag, so cancel ends it directly: its status becomes cancelled immediately, and its pending inbox tasks are marked cancelled too, so reviewers aren't left with a task for a run that's gone.
Test Cases
From the editor's Test Cases panel, you can save named input fixtures and replay them on demand:
- Click + New Test Case and give it a name.
- Paste or type the input value.
- Click Run on the test case to execute the workflow with that input.
Test cases are stored against the workflow (not a specific version) and can be run against any draft or published version. They are useful for regression testing after edits.
Mock outputs. A test case can carry mock_outputs — a map of node ID to text. A mocked node isn't executed; its mock text is used as the node's output and handled exactly like a real result: it's stored in state, passed to the next node as input, routes a classify node to the matching edge, and halts the run when a guardrails mock starts with FAIL. Mocks apply to agent, classify, guardrails, mcp and sub_workflow nodes; mocks for other node types are ignored.
No external side effects. Test-case runs never contact an MCP server, start another workflow, or create inbox tasks:
- An
mcporsub_workflownode without a mock outputs[mock mode: <type> node skipped — add a mock output for "<node id>" to simulate it]and the run continues. - A
user_approvalnode doesn't pause — it is treated as approved and passes the previous node's output on. - An LLM node in
reviewexecution mode runs asautoinstead of pausing for a reviewer. - Tools that change things outside the run aren't called:
emit_event,send_message,create_meeting,trigger_workflow,api_callerand API Builder operations other thanGET, and every Workspace tool. The model gets a note instead (see Built-in Tools → In workflow test cases). Before 1.2.0 these calls ran for real in test cases.
Distributed Execution (Tier-2)
For production deployments handling many concurrent workflow runs, hrida-ai-studio supports a distributed worker model built on Redis Streams.
How it works
API server → Redis Stream (XADD) → Worker node 1
→ Worker node 2
→ Worker node N
When a workflow run is started, the API server enqueues a job into a Redis Stream (hrida:workflow_jobs). Worker nodes run as separate processes (or containers) and compete to claim jobs. Each worker:
- Claims a job from the stream with
XREADGROUP. - Acknowledges it immediately with
XACKto prevent double-processing. - Executes the workflow graph.
- Checkpoints progress to the database after each node completes.
- On success: marks the run
completed. - On crash: the checkpoint allows another worker to resume from the last completed node.
Crash recovery
Each node's output is saved to the workflow_run table as it completes. If a worker crashes mid-run, a background recovery task (XAUTOCLAIM) detects the orphaned job and re-queues it. The new worker resumes from the last checkpoint — only nodes after the checkpoint are re-executed.
Dead-letter queue
Jobs that fail repeatedly (more than the configured retry limit) are moved to hrida:workflow_jobs_dlq. Admins can inspect dead-letter runs in the database and re-queue them manually if needed.
Per-catalog queue partitioning
In multi-tenant deployments, each LLM catalog can have its own queue partition (e.g. hrida:workflow_jobs:{catalog_id}). This prevents a high-volume catalog from starving others and allows per-catalog worker pools.
Per-node LLM timeout
Each agent node has a hard timeout enforced by asyncio.timeout(). If an LLM call takes longer than the configured limit (default: 120 seconds), the node fails with a timeout error and the run is marked failed. The timeout is configurable per node in the node properties panel under Advanced → LLM Timeout (s).
Scaling out
Add more workers by starting additional worker processes (or replicas in Kubernetes). Workers are stateless — they read from Redis, write to Postgres, and share nothing else. No coordination layer is required.
# Start a worker (one per process/container)
python -m hrida_ai_studio.worker.hrida_workflow_workerOr with the start script:
./backend/worker/start_worker.shWorker count can be scaled independently of the API server. A typical production setup runs 2–4 API server replicas and 4–8 workers.
Configuration
| Environment variable | Default | Description |
|---|---|---|
REDIS_URL | redis://localhost:6379/0 | Redis connection for the job stream |
WORKER_CONCURRENCY | 5 | Max concurrent runs per worker process |
WORKER_HEALTH_PORT | 8081 | Port for the worker health endpoint |
MAX_WORKFLOW_DELIVERY_ATTEMPTS | 3 | Max delivery attempts before a job goes to the dead-letter queue |
WORKFLOW_STALE_MESSAGE_MS | 300000 | Milliseconds a claimed job may sit idle before another worker reclaims it (crash recovery) |
WORKFLOW_QUEUE_PARTITION_BY_CATALOG | false | Use a separate queue partition per LLM catalog |
WORKFLOW_MAX_TIMEOUT_SECONDS | 600 | Upper bound on a workflow run's total timeout |