# Workflows in Pyck

Audience: Developer

How Pyck combines the Temporal workflow engine with the API, and how to build workflows

## Overview

Pyck combines the Temporal workflow engine with our CRUD+ API to build warehouse software. This document covers the workflow architecture, the integration points and the development patterns.

### How processes are defined and modeled

Logistics processes are defined as Temporal workflows, primarily in Go, as this is the Pyck SDK that is currently available, though Temporal itself supports multiple languages. The Pyck Go SDK is optional and serves as a convenience layer; workflows can also be implemented without it.

For Pyck-specific workflow concepts, see [Workflows (Concepts)](https://docs.pyck.cloud/dev/concepts/workflows.md). For details on authoring Temporal workflows, refer to the [Temporal Go SDK documentation](https://docs.temporal.io/develop/go).

## System architecture

### Key components

1. **Pyck Core Services**: Our CRUD+ microservices providing foundational warehouse functionality
2. **Temporal Service**: Durable execution service integrated within our core
3. **Database**: Persistent storage for both Pyck services and Temporal
4. **API Layer**: GraphQL API from Pyck services and gRPC API from Temporal
5. **External Workflows**: Custom workflow implementations that operate outside the core system
6. **Frontend Applications**: Mobile and web UIs that interact with the system

### Workflow architecture

```text
                         ┌─────────────────────────────────────────────┐
                         │              pyck Core                      │
                         │                                             │
                         │  ┌─────────────┐    ┌─────────────────┐     │
                         │  │             │    │                 │     │
                         │  │ Database    │◄───┤ Core Services   │     │
                         │  │             │    │                 │     │
                         │  └─────────────┘    └────────┬────────┘     │
                         │                             ▲               │
                         │                             │               │
                         │  ┌─────────────┐            │               │
                         │  │             │            │               │
                         │  │ Temporal    │────────────┘               │
                         │  │             │                            │
                         │  └─────────────┘                            │
                         │                                             │
                         └─────────────┬──────────────┬────────────────┘
                                       │              │
                                       ▼              ▼
                         ┌─────────────────┐    ┌────────────────┐
                         │                 │    │                │
                         │  GraphQL API    │    │  gRPC API      │
                         │                 │    │  (Temporal)    │
                         └────────┬────────┘    └────────┬───────┘
                                  │                      │
                                  ▼                      ▼
           ┌─────────────────────────────────────────────────────────────┐
           │                     External Systems                         │
           │                                                             │
           │  ┌─────────────────┐                  ┌─────────────────┐   │
           │  │                 │                  │                 │   │
           │  │ Workflows       │────────────────►│ Frontend Apps   │   │
           │  │                 │                  │                 │   │
           │  └─────────────────┘                  └─────────────────┘   │
           │                                                             │
           └─────────────────────────────────────────────────────────────┘
```

### What Temporal provides

Workflows never lose state, even when systems fail, and business logic continues despite network failures or API outages. Workflows can run for days, weeks or months. Temporal retries failed tasks automatically, with retry policies you configure for intermittent failures. It also keeps the complete history and the real-time status of every workflow execution.

### Per-tenant worker deployment

Pyck automatically provisions dedicated Temporal workers for each tenant during registration:

- **Automatic Setup**: When a tenant is registered via the `registerTenant` mutation, the system automatically creates a Kubernetes-based Temporal worker deployment for that tenant
- **Isolation**: Each tenant runs workflows in its own dedicated worker, ensuring workload isolation
- **Kubernetes Native**: Workers are deployed using the temporal-worker-controller as `TemporalWorkerDeployment` custom resources
- **Namespace Mapping**: Each tenant's worker connects to a Temporal namespace matching the tenant ID
- **Configuration**: Worker deployments include environment-specific settings for Temporal connection, Pyck gateway URL, and tenant credentials

## Workflow development

### Setup and configuration

1. **Project Structure**: A typical warehouse workflow project includes directories for workflow definitions, activity implementations, data models, API clients, worker service entry point, and tests.

2. **Dependencies**: Workflow projects require dependencies for the Temporal SDK and Pyck client libraries.

### Workflow registration

A workflow is triggered by subscriptions, also called workflow signals. A worker registers its workflows and their subscriptions with the Pyck GraphQL API (`registerWorkflow`, which requires a `workerID`) and keeps them alive:

1. **Temporal Registration**: Workflows and activities are registered with the Temporal worker.
2. **Subscription Registration**: When the worker starts, it registers its own workflows and their subscriptions with the Pyck API. Each subscription names an event topic, a signal type and an optional filter rule.
3. **Heartbeat**: The worker refreshes its subscriptions with a heartbeat (default every 5 minutes, `PYCK_WORKER_REGISTRATION_HEARTBEAT_INTERVAL`). A subscription expires after `PYCK_WORKFLOW_SUBSCRIPTION_TTL` (default 1 hour) without a heartbeat, and the workflow service then removes it.
4. **Stop**: On a clean stop, the worker calls `unregisterWorker`, which marks its subscriptions as stopped. Nothing is deleted: a stopped subscription keeps routing until its TTL lapses, unless another worker holds running subscriptions for the same workflow.

The subscriptions map workflows to specific event types in the system. For example, a workflow named "TemporalWorkflowPicking_OrderCreate" would be triggered by the "OrderCreate" event. See [Triggering a Workflow](https://docs.pyck.cloud/dev/concepts/workflows.md#triggering-a-workflow) for the user-facing view.

### Workflow ID generation

Workflow IDs in Pyck are generated deterministically. A workflow tied to a specific data entity can be identified by that entity, and a duplicate workflow for the same entity is prevented:

- **With pyck_data_id**: When `pyck_data_id` is present in the search attributes, it is used as the suffix for the workflow ID (e.g., `WorkflowName_<pyck_data_id>`)
- **Without pyck_data_id**: When no `pyck_data_id` is provided, a new UUID is generated as the suffix (e.g., `WorkflowName_<uuid>`)

### Workflow search attributes

Pyck uses Temporal search attributes to enable filtering, querying, and grouping of workflow executions. These search attributes are automatically configured when Pyck initializes:

#### Available search attributes

- **pyck_data_id**: Links the workflow to a specific data entity (e.g., order ID, shipment ID)
- **pyck_workflow_assignee**: The ID of the user assigned to the workflow
- **pyck_workflow_name**: The name of the workflow being executed
- **pyck_tenant_id**: The tenant context for multi-tenant deployments
- **pyck_data_type**: The type of data entity the workflow operates on
- **pyck_service**: The Pyck service that owns the workflow
- **pyck_group_by**: Custom grouping criteria for categorizing and filtering workflows
- **pyck_title**: Human-readable per-workflow display label shown in the UI (set via `workflowsdk.SetWorkflowTitle`)
- **pyck_group_title**: Human-readable label for the workflow group header (set via `workflowsdk.SetGroupTitle`, pairs with `pyck_group_by`)
- **pyck_sort_key**: Integer value used by the UI to impose a stable display order on workflow executions
- **pyck_transaction_id**: The ID of the transaction of the mutation that triggered the workflow (Keyword). The mutation returns it as `transactionID`, and `workflowExecutions(where: {transactionID: ...})` lists the executions it started
- **pyck_workflow_is_assignable**: Whether the workflow can be assigned to a user (Boolean). A workflow that never wrote it counts as assignable, so `isAssignable: true` also matches it. The SDK sets it with `workflowsdk.SetWorkflowIsAssignable`
- **pyck_workflow_targets**: The client surfaces the workflow is meant for (KeywordList of `WEB`, `MOBILE` or `SETUP`). The SDK sets it with `workflowsdk.SetWorkflowTargets`, and `workflowExecutions` filters on it with `targets` and `targetsNotIn`

#### Using search attributes

Search attributes can be used to query and filter workflows through the Temporal API:

```javascript
// Example: Find all picking workflows for a specific order
const workflows = await temporal.workflow.list({
  query: 'pyck_workflow_name="OrderPicking" AND pyck_data_id="order-123"'
});

// Example: Find all workflows assigned to a user
const userWorkflows = await temporal.workflow.list({
  query: 'pyck_workflow_assignee="user-456"'
});

// Example: Group workflows by custom criteria
const groupedWorkflows = await temporal.workflow.list({
  query: 'pyck_group_by="priority-high" AND pyck_service="picking"'
});

// Example: Order workflows by sort key
const orderedWorkflows = await temporal.workflow.list({
  query: 'pyck_sort_key >= 10 AND pyck_sort_key <= 99'
});
```

### Setting workflow display labels
  
The Pyck SDK exposes helpers to set per-workflow display metadata as Temporal search attributes. The UI uses these labels for workflow lists and group headers, and clients
can filter/sort directly on them through the GraphQL `workflowExecutions` query.

#### `SetWorkflowTitle`

Use `workflowsdk.SetWorkflowTitle` to write the `pyck_title` search attribute, which is the per-workflow display label shown in lists and dashboards.

  ```go
  import "github.com/pyck-ai/pyck/backend/workflowsdk"

  func MyWorkflow(ctx temporalworkflow.Context, input MyInput) error {
      // Set the display label so the UI can show a human-readable title
      // and so callers can query workflowExecutions(where: {title: ...}).
      if err := workflowsdk.SetWorkflowTitle(ctx, "SKU-123"); err != nil {
          return err
      }

      // ... rest of the workflow
      return nil
  }
  ```

- Passing an empty string clears the attribute so the frontend falls back to the workflow type name:

    ```go
    workflowsdk.SetWorkflowTitle(ctx, "") // unset
    ```

- The attribute is a Temporal **Keyword** type; both equality and prefix/suffix predicates are available via the GraphQL `title*` filters.
- `workflowsdk.GetWorkflowTitle(ctx)` reads the current value.

#### `SetGroupTitle`

Use `workflowsdk.SetGroupTitle` to write the `pyck_group_title` search attribute, which is the human-readable label for the workflow group header. It pairs with `pyck_group_by`
(the technical join key); set both together so the UI can group workflows under a shared label.

  ```go
  if err := workflowsdk.SetGroupBy(ctx, "order-42"); err != nil {
      return err
  }
  if err := workflowsdk.SetGroupTitle(ctx, "ORDER-42"); err != nil {
      return err
  }
  ```
  
- Passing an empty string clears the attribute so the frontend falls back to `"No Group"`.
- `workflowsdk.GetGroupTitle(ctx)` reads the current value.

#### `SetSortKey`

The `pyck_sort_key` search attribute can be set from within a workflow using the workflowsdk to control the display order of workflow executions in the UI:

  ```go
  import (
    "github.com/pyck-ai/pyck/backend/workflowsdk"
  )

  // Set a sort key to control display order
  func MyWorkflow(ctx workflow.Context) error {
    sortKey := int64(42)
    if err := workflowsdk.SetSortKey(ctx, &sortKey); err != nil {
      return err
    }

    // ... rest of workflow logic

    // Clear the sort key (falls back to default start-time ordering)
    if err := workflowsdk.SetSortKey(ctx, nil); err != nil {
      return err
    }
  
    return nil
  }

  // Read the current sort key
  func CheckSortKey(ctx workflow.Context) {
    sortKey := workflowsdk.GetSortKey(ctx)
    if sortKey != nil {
      // Sort key is set to *sortKey
    } else {
      // Sort key is not set, will use default ordering
    }
  }
  ```

The sort key is particularly useful when you need workflows to appear in a specific order in the UI, rather than relying solely on start time. Pass `nil` to `SetSortKey` to
unset the attribute and fall back to default start-time ordering.

#### Migration from `SetWorkflowMemo`

`workflowsdk.SetWorkflowMemo` and the associated `WorkflowMemo` struct (with `Title`, `Subtitle`, and `Data` fields) have been **removed**. Memo fields are opaque to
Temporal Visibility and cannot be indexed; search attributes are fully queryable.

**Before:**

  ```go
  workflowsdk.SetWorkflowMemo(ctx, workflowsdk.WorkflowMemo{
      Title:    "SKU-123",
      Subtitle: "order-uuid",
      Data:     map[string]any{"priority": "high"},
  })
  ```

**After:**

  ```go
  // The per-workflow title and the group label are now first-class search
  // attributes. Custom auxiliary data should move into the workflow input,
  // the workflow state, or pyck_group_by depending on its purpose.
  workflowsdk.SetWorkflowTitle(ctx, "SKU-123")
  workflowsdk.SetGroupBy(ctx, "order-uuid")
  workflowsdk.SetGroupTitle(ctx, "ORDER UUID")
  ```

The signal router also accepts `pyck_title` and `pyck_group_title` keys when propagating attributes from incoming signal payloads, alongside the existing
`pyck_workflow_assignee` and `pyck_group_by` keys.

### Workflow definition

Workflows in Temporal are defined as functions that orchestrate a series of activities. A typical picking workflow would include steps like:

- Fetching order details
- Allocating inventory
- Generating picking tasks
- Updating mobile app UI for picker
- Waiting for picking completion
- Processing results and updating inventory

### Frontend control points

Workflows control frontend behavior through a combination of:

1. **Activity Properties**: Each workflow activity can define UI properties that should be displayed
2. **Update Handlers**: Workflows wait for user input through Temporal update handlers
3. **NextActivityName**: Defining the next activity tells the frontend what screen to show

### Event triggering and signal routing

Workflows are triggered by events from the system through an advanced signal routing mechanism that differentiates between START and INTERMEDIATE signals:

1. **START Signals**: Create new workflow instances when triggered
2. **INTERMEDIATE Signals**: Forward signals to already running workflow instances

When an event occurs in the Pyck system:

- The system uses JetStream-based routing to determine which workflows should be triggered
- START signals will create new workflow instances. A start whose workflow ID is already running counts as a success and is recorded as `already_running`
- INTERMEDIATE signals will be forwarded to matching running workflows

For example, when an order is created in the system, the "OrderCreate" event is fired, which then triggers the "TemporalWorkflowPicking_OrderCreate" workflow.

**Important Breaking Change**: As of the latest version, running workflows cannot be reassigned on re-trigger. Attempting to start a workflow that is already running is recorded as `already_running` and the running execution does not see the event, so a re-trigger cannot start a duplicate execution. Workflows that need every update use Signal-With-Start.

### Custom events

Custom events allow workflows to be triggered by application-specific events sent via the `sendCustomEvent` GraphQL mutation. Since v0.26.0, custom events have their own dedicated namespace separate from CRUD events.

#### Event namespaces

Pyck publishes events on different NATS subjects based on their type:

- **CRUD Events**: `pyck.<tenant>.crud.<service>.<schema>.<entity>.<operation>`
  - The first segment is the NATS stream name (`PYCK_NATS_STREAM_NAME`, `pyck` in the examples) and `<entity>` is the ID of the entity. [Triggering a Workflow](https://docs.pyck.cloud/dev/concepts/workflows.md#what-happens-at-runtime) shows this subject for a created inventory item
  - Published automatically when entities are created, updated, or deleted
  - Examples: `create`, `update`, `delete` operations

- **Custom Events**: `pyck.<tenant>.custom.<type>.<entity>.<operation>`
  - Published via the `sendCustomEvent` mutation
  - Custom operation names supported (not limited to create/update/delete)
  - Examples: `approve`, `reject`, `low_stock_alert`, `milestone_reached`

The two event types use different subjects (`crud` and `custom`), so custom events cannot collide with entity CRUD events.

#### Subscribing to custom events

To register a workflow that triggers on custom events, use `CustomSignalTopic` from the workflowsdk:

```go
import (
    "github.com/pyck-ai/pyck/backend/workflowsdk"
)

// Subscribe to a specific custom event type and operation
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
    EventType:     "tour-creation",
    OperationName: "create",
})

// Subscribe to all operations for a custom event type
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
    EventType: "inventory-alert",
    // OperationName omitted = wildcard
})

// Subscribe with entity ID filtering
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
    EventType:     "order-approval",
    EntityID:      orderID,
    OperationName: "approve",
})
```

#### Custom event operations

Unlike CRUD events which only support `create`, `update`, and `delete` operations, custom events support any operation name chosen by the caller:

- **Standard Operations**: `create`, `update`, `delete` use their respective start policies
- **Custom Operations**: Any other operation (e.g., `approve`, `ping`, `alert`) uses the `update` policy
  - Allows one run per entity once the previous run has closed
  - Events arriving while a workflow runs are recorded as `already_running`

#### Tenant isolation

Custom events are tenant-scoped and workflows can only subscribe to their own tenant's events:

- Each tenant's custom events are published on subjects containing that tenant's ID
- Workflows attempting to subscribe to another tenant's custom events will be rejected
- An unset `TenantID` subscribes to every tenant the registering user can read; a `TenantID` of a tenant the user cannot read is rejected.

#### Breaking change: Namespace migration

:::danger
**Breaking Change (v0.26.0)**: Custom events now use a separate namespace from CRUD events.

Workflows that were subscribed to custom events using `SignalTopic` with `ServiceName: "management"` will **no longer receive those events**.
:::

**Migration Required**:

Before:

```go
// This no longer receives custom events
signal.NewStartSignal(workflowsdk.SignalTopic{
    ServiceName:   "management",
    SchemaName:    "tour-creation",
    OperationName: "create",
})
```

After:

```go
// Use CustomSignalTopic for custom events
signal.NewStartSignal(workflowsdk.CustomSignalTopic{
    EventType:     "tour-creation",
    OperationName: "create",
})
```

**Important**: Deploy the migrated workflows together with the Pyck platform update. Deployed earlier, they fail to register; deployed later, they miss events.

## User input communication flow

The communication between Temporal workflows and the frontend when waiting for user input follows a specific stateful pattern:

### 1. Workflow state management

Workflows maintain their state through a query mechanism that allows external systems to inspect their current state without affecting execution:

1. **Query Handler**: Each workflow exposes its current UI state through a query handler for "nextActivityProperties"
2. **Activity Definition**: The workflow defines what activity the user should perform next
3. **Update Handlers**: The workflow registers update handlers to receive the user input from the frontend
4. **Waiting for Input**: The workflow pauses execution while waiting for user input

### 2. Frontend interaction cycle

The frontend interacts with workflows through a well-defined cycle:

1. **Discover Workflows**: Frontend finds workflows assigned to the current user via the `workflowExecutions` GraphQL query, filtered by `assignee`
2. **Get Current Activity**: The system retrieves the current activity information from the workflow
3. **Render UI Components**: Frontend displays the appropriate UI based on the activity properties
4. **Collect User Input**: User interacts with the UI and provides the requested information
5. **Submit Input and Get Next Step**: When the user submits input, the frontend calls a single GraphQL mutation (`submitUserDataInput`) that:
   - Sends the user input to the workflow
   - Waits for the workflow to process the input
   - Returns the next activity in the same response

The frontend does not need to poll for the next activity after submitting user input. The single GraphQL mutation returns both the acknowledgment of the submitted data and the instructions for the next step.

### 3. GraphQL mutation synchronization

When the `submitUserDataInput` GraphQL mutation is called:

1. **Update Sending**: The GraphQL resolver sends the user input to the workflow as a Temporal update
2. **Synchronous Waiting**: The resolver waits until the update has completed and uses its result
3. **Response with Next Step**: The resolver does not poll the workflow state. Once the update has completed, the mutation returns the update's result (`result`) together with the workflow type, ID and run ID

### 4. Workflow processing

Inside the workflow, when it receives user input:

1. **Update Reception**: The workflow's update handler receives the user input
2. **State Update**: The workflow updates its activity state to indicate the current activity is passed
3. **Input Processing**: The workflow processes the input, often calling an activity
4. **Next Activity Definition**: The workflow defines the next activity for the user
5. **State Exposure**: The updated state becomes available to the GraphQL resolver

## BPMN to code translation

We use BPMN for visual workflow design and translate it to Temporal code:

1. **BPMN Process**: Designed with logistics team for business requirements
2. **Activities**: BPMN tasks become Temporal activities
3. **Gateways**: BPMN gateways become workflow conditions
4. **Events**: BPMN events map to Temporal signals/triggers

The workflow directory structure typically follows this pattern:

```text
processes/
  {priority}_{domain}/
    {id}_{event}/
      activities/      # Activity implementation
      domain/          # Data models
      workflows/       # Workflow definition
      {event}.bpmn     # Visual workflow design
```

## Reference implementation

For a practical example, see our reference implementation: <https://github.com/pyck-ai/pyck-customer-template>

## Best practices

| Topic | Practice |
| --- | --- |
| Idempotency | Make all activities idempotent so retries are reliable. |
| Deterministic workflows | Keep workflows deterministic by moving non-deterministic code to activities. |
| Error handling | Use retry policies that fit each failure type. |
| Testing | Write tests for workflows and activities. |
| Monitoring | Set up monitoring and alerting using Temporal metrics. |
| Versioning | Use versioning for workflow changes, so in-flight workflows keep working. |
