Triggering from your app
Read, cancel and follow runs
Read a run's status and output with runs.retrieve, find runs with runs.list, stop it with runs.cancel, retry a failed workflow from where it failed with runs.retryFromFailure, and follow a run and every run below it live with runs.subscribe.
On this page
Every call here takes a run ID, or anything with an id, such as a handle. A value that is not a run ID is refused before any request. A run in another environment than the key's answers NotFoundError, exactly like a run that does not exist.
Read a run#
// Run with: node runs.mjs <run id>import { runs } from '@bokjoy/sdk'; const run = await runs.retrieve(process.argv[2]);console.log(run.taskId, run.status, run.output); if (!run.isFinished) { const { status, cancelled } = await runs.cancel(run); console.log(status, cancelled);}# Run with: python runs.py <run id>import sys from bokjoy import runs run = runs.retrieve(sys.argv[1])print(run.task_id, run.status, run.output) if not run.is_finished: result = runs.cancel(run) print(result["status"], result["cancelled"])The run#
| Node | Python | Value |
|---|---|---|
id, taskId | id, task_id | The run and its task. |
status | status | delayed, queued, running, waiting, completed, failed or cancelled. |
payload | payload | The input it was triggered with. |
output | output | The result once completed, else null. |
error | error | Why it failed or was cancelled, else null. |
environment, deploymentId | environment, deployment_id | Where it runs, and the code it runs. |
idempotencyKey, parentId | idempotency_key, parent_id | Its key, and its parent for a child run. |
retryOf | retry_of | The failed workflow run it retries from failure, else null. |
source | source | Where it came from: api, schedule, child, or dashboard, test and replay for runs started from the console. A retry from failure is a replay. A hook run, which runs its parent's lifecycle hooks, is a hook. |
placement, machine | placement, machine | How it was placed and sized. |
capacityWait | capacity_wait | Set while no worker can hold it yet. |
retry | retry | Set while a failed run waits to retry: {attempt, at}, the attempt that starts next and when. |
delayedUntil | delayed_until | When a delayed run starts, kept once it has. Null for a run that was never delayed. |
debounce | debounce | For a debounced run, {key, mode, since, triggers}. Otherwise null. |
tags | tags | Its tags: the ones it was triggered with, then the ones it added. Empty without any. |
metadata | metadata | What its attempts set with ctx.metadata, or null when nothing was. Not in a page of runs.list. |
createdAt, updatedAt | created_at, updated_at | Timestamps. |
attempts | attempts | Each try, oldest first, without logs. See Runs and attempts. |
Status flags#
| Node | Python | True when the status is |
|---|---|---|
isFinished | is_finished | completed, failed or cancelled |
isCompleted | is_completed | The same as isFinished, Trigger.dev's name for it |
isSuccess | is_success | completed |
isFailed | is_failed | failed only, never cancelled |
isCancelled | is_cancelled | cancelled |
isQueued | is_queued | queued or delayed, as in Trigger.dev |
isExecuting | is_executing | running |
isWaiting | is_waiting | waiting |
The Python run is a frozen dataclass. For an attempt's logs, read the run over HTTP with GET /v1/runs/{id}.
Cancel a run#
runs.cancel cancels the run and every unfinished run below it, and returns {id, status, cancelled}. A running attempt is told to stop. cancelled is false when the run had already finished, which cancel leaves unchanged.
Cancelling a child that a workflow waits on fails the workflow. Work the code already did stays done: cancel stops code, it never undoes side effects.
Reschedule a delayed run#
runs.reschedule(run, {delay}) (Python: runs.reschedule(run, delay)) moves a delayed run to another time, earlier or later, and returns the run. delay takes what a trigger's delay takes. A time that has passed is a ValidationError, and a run that has already started, or was cancelled, is a ConflictError. To stop a delayed run, cancel it.
Retry a failed workflow from failure#
When a workflow run fails, fix the cause and deploy. Then runs.retryFromFailure starts a new run of the same task and payload, on the environment's current deployment, that reuses the steps that succeeded before the failure and runs the rest. For a batch, only the children that did not come back ok start again. The failed run stays as it is.
// Run with: node retry.mjs <failed workflow run id>import { runs } from '@bokjoy/sdk'; // After fixing what failed: a new run that keeps what succeeded.const retry = await runs.retryFromFailure(process.argv[2], { idempotencyKey: 'thumbnails-fix-1' });console.log(retry.id, retry.retryOf);console.log(retry.reusedSteps, retry.rerunFrom, retry.reusedResults);# Run with: python retry.py <failed workflow run id>import sys from bokjoy import runs # After fixing what failed: a new run that keeps what succeeded.retry = runs.retry_from_failure(sys.argv[1], idempotency_key="thumbnails-fix-1")print(retry.id, retry.retry_of)print(retry.reused_steps, retry.rerun_from, retry.reused_results)It returns a handle of the new run, which you can poll, with what it reused:
| Node | Python | Value |
|---|---|---|
retryOf | retry_of | The failed run. |
reusedSteps | reused_steps | Its steps the new run starts with: every step before the first that did not succeed. |
rerunFrom | rerun_from | The index of the first step that runs again, or null when every step succeeded and the workflow failed after its last. |
reusedResults | reused_results | When that step is a batch, how many of its children came back ok and keep their results. |
A retry under the same idempotencyKey for the same run returns the run it started, as any key does. That holds for a retry that was cancelled too: you get the cancelled run back, and nothing starts. To retry again after a cancel, use another key. Without one, every call starts a new retry. Only a failed workflow run can be retried from failure, and anything else is a ConflictError. A plain task has no steps to reuse, so start it again with tasks.trigger. Workflows says what is reused, step by step.
The name is not Trigger.dev's runs.replay, which starts a run again from the start. Bok Joy's console calls that Replay run.
Follow a run live#
runs.subscribe follows a run and all its descendants as they change, until they all finish:
// Run with: node subscribe.mjs <run id>import { runs } from '@bokjoy/sdk'; for await (const message of runs.subscribe(process.argv[2])) { if (message.type === 'snapshot') { console.log(`${message.runs.length} runs, settled: ${message.settled}`); } else if (message.type === 'event') { const { kind, run_id, data } = message; if (kind === 'run.status') console.log(run_id, data.status); if (kind === 'milestone') console.log(data.name, data.progress); } else { console.log('end:', message.reason); }}# Run with: python subscribe.py <run id>import sys from bokjoy import runs for message in runs.subscribe(sys.argv[1]): if message["type"] == "snapshot": print(len(message["runs"]), "runs, settled:", message["settled"]) elif message["type"] == "event": data = message["data"] if message["kind"] == "run.status": print(message["run_id"], data["status"]) if message["kind"] == "milestone": print(data["name"], data["progress"]) else: print("end:", message["reason"])The subscription yields three kinds of message:
type | When | Fields |
|---|---|---|
snapshot | First | runs: the tree's runs with their status, attempts, metadata and newest 20 milestones. settled, truncated, cursor. |
event | Each change, in commit order | kind, run_id, attempt_id, data, seq, at. |
end | Once the whole tree has finished | reason, cursor. The iteration then stops. |
Event kind | data |
|---|---|
run.created | A new run in the tree: task, kind, parent_id, status, origin (submit, schedule, call or trigger). |
run.status | status, previous, error. |
attempt.started | epoch, pool, worker_id, status. |
attempt.status | epoch, status, previous, executor, elapsed_ms. |
metadata | op (set or append), key, value. |
milestone | name, progress, detail. |
update.refused | An update from the task that the control plane refused: its type, seq and reason. |
replay.drift | A workflow replayed a wait for children with changed arguments and kept the recorded results: index, type (call or batch), key, task, and changed, the fields that differ (input, items, machine, concurrency_key). Once per step. |
trigger.reused | A trigger with a default key took a child of the same task as it is, though its input differs: key, task, run_id (the child it took) and input_differs. It happens in a retry from failure whose fix added a trigger of that task before its others. |
The subscription reconnects by itself after a dropped connection and resumes after the last event it delivered, so nothing is missed or repeated. It gives up after 60 seconds without a connection (Node: reconnectForMs, Python: reconnect_for in seconds). To resume later, pass the last cursor you saw as cursor.
A snapshot holds at most 500 runs. Events of a finished tree are kept for 30 days by default. The run itself, its output and its logs stay until run retention deletes its whole tree: on the hosted alpha, 30 days after a completed tree goes quiet, and 90 days after a failed or cancelled one.
Only follow runs from your backend: the stream authenticates with your API key.
List runs#
runs.list returns one page of runs in the key's environment, newest first, children included:
import { runs } from '@bokjoy/sdk'; // The newest report run of one organization, and its progress.const { data } = await runs.list({ task: 'reports.build', tag: 'org_42', limit: 1 });const latest = data[0];console.log(latest.id, latest.status, latest.tags.join(',')); const { metadata } = await runs.retrieve(latest);console.log(`${metadata.done} of ${metadata.total}`); // Every failed run of the last day, one page at a time.let failed = 0;let page = await runs.list({ status: 'failed', period: '1d' });for (;;) { failed += page.data.length; if (!page.pagination.next) break; page = await runs.list({ status: 'failed', period: '1d', after: page.pagination.next });}console.log(failed, 'failed');from bokjoy import runs # The newest report run of one organization, and its progress.latest = runs.list(task="reports.build", tag="org_42", limit=1).data[0]print(latest.id, latest.status, ",".join(latest.tags)) metadata = runs.retrieve(latest).metadataprint(f"{metadata['done']} of {metadata['total']}") # Every failed run of the last day, one page at a time.failed = sum(1 for _ in runs.list(status="failed", period="1d").auto_paging_iter())print(failed, "failed")| Node | Python | Keeps runs |
|---|---|---|
status | status | With any of these statuses: one, or a list. |
task | task | Of any of these tasks. |
tag | tag | With any of these tags. A tag is matched exactly, and one with a comma in it cannot be filtered on. |
from, to | since, until | Created at or after from, and before to: a Date or an RFC 3339 time (Python: a datetime, naive read as UTC, or the text). |
period | period | Created within this long before now: 30m, 6h, 1d, 7d. Not with from. |
limit | limit | How many in a page: 1 to 200, default 50. |
after, before | after, before | The page older than pagination.next, or newer than pagination.previous. Not both. |
Filters combine: a run must pass each one you give. A value the API would refuse, such as an unknown status, is a ValidationError.
The page is {data, pagination: {next, previous}}. Each run in data is a run as runs.retrieve reads it, without its attempts, metadata, payload, output and error, plus startedAt, when its first attempt started, and finishedAt, when it finished (Python: started_at, finished_at). next is null on the last page. To read a run's payload, output, error or metadata, retrieve it.
The list leaves out hook runs, so a script that cancels a task's runs never cancels its hooks. Pass source: 'hook' to list them. A list that takes longer than 10 seconds is stopped with an error: narrow it by status, task, tag or time.
In Python the page also has next_page() and previous_page(), and auto_paging_iter() yields every run of this page and every older one.
From the CLI, durable-compute list --tag org_42 lists runs by tag. Repeat --tag for runs with any of several. Over HTTP the route is GET /v1/runs.