> ## Documentation Index
> Fetch the complete documentation index at: https://docs.retab.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cancel Run

> Cancel a pending, running, or waiting workflow run.

Cancel a running or pending workflow run. Cancellation is delivered through Temporal, so the response can carry one of three states:

* `cancelled` — the run reached a cancelled terminal state.
* `cancellation_requested` — the cancel signal was accepted; the run will reach `cancelled` shortly. Re-poll [Get Run](/api-reference/workflows/runs/get) to observe the transition.
* `cancellation_failed` — Temporal rejected the cancel (e.g. the run already finished). The returned `run` reflects the actual current state.

The optional `command_id` is an idempotency key — replaying the same value never enqueues a second cancel.

<RequestExample>
  ```python Python theme={null}
  from retab import Retab

  client = Retab()

  result = client.workflows.runs.cancel(
      run_id="run_abc123",
      command_id="cmd_cancel_abc",  # optional dedup key
  )

  print(result.cancellation_status)
  print(result.run.lifecycle.status)
  ```

  ```typescript TypeScript theme={null}
  import { Retab } from "@retab/node";

  const client = new Retab({ apiKey: process.env.RETAB_API_KEY });

  const result = await client.workflows.runs.cancel("run_abc123", "cmd_cancel_abc");

  console.log(result.cancellationStatus);
  console.log(result.run.lifecycle.status);
  ```

  ```go Go theme={null}
  package main

  import (
  	"context"
  	"fmt"
  	"log"

  	retab "github.com/retab-dev/retab/clients/go"
  )

  func ptr[T any](v T) *T { return &v }

  func main() {
  	ctx := context.Background()

  	client, err := retab.NewClient("")
  	if err != nil {
  		log.Fatal(err)
  	}

  	result, err := client.Workflows.Runs.Cancel(ctx, "run_abc123", nil)
  	if err != nil {
  		log.Fatal(err)
  	}

  	fmt.Println(result.CancellationStatus)
  	fmt.Println(result.Run.Lifecycle.Status())
  }
  ```

  ```ruby Ruby theme={null}
  require 'retab'

  client = Retab::Client.new(api_key: ENV['RETAB_API_KEY'])

  result = client.workflows.runs.cancel(
    run_id: 'run_abc123',
    command_id: 'cmd_cancel_abc',
  )

  puts result.cancellation_status
  puts result.run.lifecycle.status
  ```

  ```rust Rust theme={null}
  use retab::models::CancelWorkflowRequest;
  use retab::resources::workflow_runs::CancelParams;
  use retab::Retab;

  #[tokio::main]
  async fn main() -> Result<(), Box<dyn std::error::Error>> {
      let client = Retab::new(std::env::var("RETAB_API_KEY")?);

      let result = client
          .workflows().runs()
          .cancel(
              "run_abc123",
              CancelParams {
                  body: Some(CancelWorkflowRequest {
                      command_id: Some("cmd_cancel_abc".into()),
                  }),
              },
          )
          .await?;

      println!("{:?}", result.cancellation_status);
      println!("{:?}", result.run.lifecycle);
      Ok(())
  }
  ```

  ```php PHP theme={null}
  <?php
  require 'vendor/autoload.php';

  use Retab\Client;

  $client = new Client(apiKey: getenv('RETAB_API_KEY'));

  $result = $client->workflows()->runs()->cancel(
      runId: 'run_abc123',
  );
  print_r($result);
  ```

  ```csharp C# theme={null}
  using Retab;
  using RetabClient = Retab.Retab;

  var apiKey = Environment.GetEnvironmentVariable("RETAB_API_KEY")!;
  var client = new RetabClient(apiKey);

  var result = await client.Workflows.Runs.CancelAsync("run_abc123", new WorkflowRunsCancelOptions());
  Console.WriteLine(result);
  ```

  ```java Java theme={null}
  import com.retab.RetabClient;

  public final class Example {
    public static void main(String[] args) throws Exception {
      RetabClient client = new RetabClient(System.getenv("RETAB_API_KEY"));

      var result = client.workflows().runs().cancel("run_abc123");
      System.out.println(result);
    }
  }
  ```

  ```curl cURL theme={null}
  curl -X 'POST' \
    'https://api.retab.com/v1/workflows/runs/run_abc123/cancel' \
    -H 'Content-Type: application/json' \
    -H 'Authorization: Bearer <your-api-key>' \
    -d '{"command_id": "cmd_cancel_abc"}'
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "run": {
      "id": "run_abc123",
      "workflow": {
        "workflow_id": "wf_abc123xyz",
        "version_id": "ver_abc123xyz"
      },
      "trigger": { "type": "api" },
      "lifecycle": {
        "status": "cancelled",
        "reason": "user requested cancellation"
      },
      "timing": {
        "created_at": "2026-05-01T14:30:00Z",
        "started_at": "2026-05-01T14:30:00Z",
        "completed_at": "2026-05-01T14:30:08Z"
      },
      "inputs": { "documents": {}, "json_data": {} }
    },
    "cancellation_status": "cancelled"
  }
  ```

  ```json 200 theme={null}
  {
    "run": {
      "id": "run_abc123",
      "workflow": {
        "workflow_id": "wf_abc123xyz",
        "version_id": "ver_abc123xyz"
      },
      "trigger": { "type": "api" },
      "lifecycle": { "status": "running" },
      "timing": {
        "created_at": "2026-05-01T14:30:00Z",
        "started_at": "2026-05-01T14:30:00Z",
        "completed_at": null
      },
      "inputs": { "documents": {}, "json_data": {} }
    },
    "cancellation_status": "cancellation_requested"
  }
  ```

  ```json 404 theme={null}
  {
    "detail": "Workflow run not found"
  }
  ```
</ResponseExample>


## OpenAPI

````yaml POST /v1/workflows/runs/{run_id}/cancel
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: https://api.retab.com
security: []
paths:
  /v1/workflows/runs/{run_id}/cancel:
    post:
      tags:
        - Workflows
        - Workflow Runs
      summary: Cancel Workflow Run
      description: Cancel a pending, running, or waiting workflow run.
      operationId: cancel_workflow_run
      parameters:
        - in: path
          name: run_id
          required: true
          schema:
            type: string
            title: Run Id
      requestBody:
        content:
          application/json:
            schema:
              anyOf:
                - $ref: '#/components/schemas/CancelWorkflowRequest'
                - type: 'null'
              title: Request
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/CancelWorkflowResponse'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    CancelWorkflowRequest:
      properties:
        command_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Command Id
          description: Optional idempotency key for deduplicating cancel commands
      type: object
      title: CancelWorkflowRequest
      description: Optional request payload for cancel workflow command idempotency.
    CancelWorkflowResponse:
      properties:
        run:
          $ref: '#/components/schemas/WorkflowRun'
        redis_available:
          type: boolean
          title: Redis Available
          description: Whether immediate cancellation signaling was available
          default: true
        cancellation_status:
          type: string
          enum:
            - cancelled
            - cancellation_requested
            - cancellation_failed
          title: Cancellation Status
          description: Cancellation delivery state from this request
          default: cancellation_requested
      type: object
      required:
        - run
      title: CancelWorkflowResponse
      description: Response for cancel workflow endpoint.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
          default: []
      type: object
      title: HTTPValidationError
    WorkflowRun:
      properties:
        id:
          type: string
          title: Id
          description: Unique ID for this run
        workflow_id:
          type: string
          title: Workflow Id
          description: ID of the workflow that was run
        workflow_version_id:
          type: string
          title: Workflow Version Id
          description: Content-addressed workflow version used for this run.
        trigger:
          $ref: '#/components/schemas/TriggerInfo'
          description: What started this run
        lifecycle:
          oneOf:
            - $ref: '#/components/schemas/PendingRun'
            - $ref: '#/components/schemas/RunningRun'
            - $ref: '#/components/schemas/AwaitingReviewRun'
            - $ref: '#/components/schemas/CompletedTerminal'
            - $ref: '#/components/schemas/ErrorTerminal'
            - $ref: '#/components/schemas/CancelledTerminal'
          title: Lifecycle
          description: Lifecycle state of the run.
          discriminator:
            propertyName: status
            mapping:
              awaiting_review:
                $ref: '#/components/schemas/AwaitingReviewRun'
              cancelled:
                $ref: '#/components/schemas/CancelledTerminal'
              completed:
                $ref: '#/components/schemas/CompletedTerminal'
              error:
                $ref: '#/components/schemas/ErrorTerminal'
              pending:
                $ref: '#/components/schemas/PendingRun'
              running:
                $ref: '#/components/schemas/RunningRun'
        timing:
          $ref: '#/components/schemas/RunTiming'
          description: All timing information
        inputs:
          $ref: '#/components/schemas/RunInputs'
          description: Input payloads supplied at run creation time
          default:
            documents: {}
            json_data: {}
        metadata:
          anyOf:
            - additionalProperties:
                type: string
              type: object
            - type: 'null'
          title: Metadata
          description: User-defined metadata associated with this workflow run.
      type: object
      required:
        - id
        - lifecycle
        - timing
        - trigger
        - workflow_id
        - workflow_version_id
      title: WorkflowRun
      description: A single execution of a workflow.
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
        input:
          title: Input
          default: null
        ctx:
          type: object
          title: Context
          default: {}
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    TriggerInfo:
      properties:
        type:
          type: string
          enum:
            - manual
            - api
            - schedule
            - webhook
            - email
            - custom
            - restart
          title: Type
          description: What started this run
      type: object
      required:
        - type
      title: TriggerInfo
      description: |-
        Public summary of what started a run: just the trigger category.

        The full per-variant detail (schedule_id, parent_run_id, sender, ...) is
        kept internally on `StoredWorkflowRun.trigger` but intentionally not
        exposed in the public API surface.
    PendingRun:
      properties:
        status:
          type: string
          const: pending
          title: Status
          default: pending
      type: object
      title: PendingRun
      description: The run has been created but execution has not started.
    RunningRun:
      properties:
        status:
          type: string
          const: running
          title: Status
          default: running
      type: object
      title: RunningRun
      description: The run is currently executing.
    AwaitingReviewRun:
      properties:
        status:
          type: string
          const: awaiting_review
          title: Status
          default: awaiting_review
        waiting_for_block_ids:
          items:
            type: string
          type: array
          title: Waiting For Block Ids
          description: Block IDs that are waiting for review
          default: []
      type: object
      title: AwaitingReviewRun
      description: The run is paused on at least one gated block.
    CompletedTerminal:
      properties:
        status:
          type: string
          const: completed
          title: Status
          default: completed
      type: object
      title: CompletedTerminal
      description: The run finished successfully.
    ErrorTerminal:
      properties:
        status:
          type: string
          const: error
          title: Status
          default: error
        message:
          type: string
          title: Message
          description: Human-readable error message
        stage:
          anyOf:
            - type: string
              enum:
                - input_collection
                - registry_lookup
                - document_fetch
                - execution
                - output_storage
                - routing
                - history_payload
            - type: 'null'
          title: Stage
          description: Which execution stage failed
        category:
          anyOf:
            - type: string
              enum:
                - transient
                - permanent
                - quota
            - type: 'null'
          title: Category
          description: Error category for retry decisions
        details:
          anyOf:
            - $ref: '#/components/schemas/ErrorDetails'
            - type: 'null'
          description: Detailed error context including stack trace
        failing_step_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Failing Step Id
          description: >-
            Step ID of the failing step, when the failure was attributable to a
            specific step
      type: object
      required:
        - message
      title: ErrorTerminal
      description: The run failed. All loose error fields are bundled here.
    CancelledTerminal:
      properties:
        status:
          type: string
          const: cancelled
          title: Status
          default: cancelled
        reason:
          anyOf:
            - type: string
            - type: 'null'
          title: Reason
          description: Human-readable reason, when known
      type: object
      title: CancelledTerminal
      description: The run was cancelled before reaching a natural terminal state.
    RunTiming:
      properties:
        created_at:
          type: string
          format: date-time
          title: Created At
          description: When the run record was created
        started_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Started At
          description: When the run started executing
        completed_at:
          anyOf:
            - type: string
              format: date-time
            - type: 'null'
          title: Completed At
          description: When the run finished executing
      type: object
      title: RunTiming
      description: |-
        Timing information for a run.

        Three event timestamps that consumers cannot reconstruct on their own.
        Wall-clock duration is a trivial `completed_at - started_at` subtraction
        done client-side; it is not stored or exposed.
    RunInputs:
      properties:
        documents:
          additionalProperties:
            $ref: '#/components/schemas/FileRef'
          type: object
          title: Documents
          description: start_document block ID -> input document reference
          default: {}
        json_data:
          additionalProperties: true
          type: object
          title: Json Data
          description: start-json block ID -> input JSON data
          default: {}
      type: object
      title: RunInputs
      description: Input payloads supplied at run creation time.
    ErrorDetails:
      properties:
        message:
          anyOf:
            - type: string
            - type: 'null'
          title: Message
          description: >-
            Human-readable error message. Free-text; the structured fields below
            are the machine-readable counterpart.
        stack_trace:
          anyOf:
            - type: string
            - type: 'null'
          title: Stack Trace
          description: Full stack trace
        block_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Block Id
          description: ID of the block that failed
        block_name:
          anyOf:
            - type: string
            - type: 'null'
          title: Block Name
          description: Name/label of the block that failed
        error_code:
          anyOf:
            - type: string
            - type: 'null'
          title: Error Code
          description: Error code if available
        context:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Context
          description: Additional context about the error
      type: object
      title: ErrorDetails
      description: |-
        Detailed error information for debugging.

        Captures stack traces and context about where and why an error occurred.
    FileRef:
      properties:
        id:
          type: string
          title: Id
          description: ID of the file
        filename:
          type: string
          title: Filename
          description: Filename of the file
        mime_type:
          type: string
          title: Mime Type
          description: MIME type of the file
      type: object
      required:
        - filename
        - id
        - mime_type
      title: FileRef
      description: Public/shared file reference used across SDK and customer-facing APIs.
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````