Operational apps

Operational apps: flows

How to write the logic of an operational app: the input envelope, the Python client, idempotency, retries, files, and executions.

Updated: 2026-11-17

In this guide

What a flow is

A flow is the code that holds your business logic: computing differences, matching a statement, calling a provider, creating cases. The app definition carries no formulas or rules; it only says when each flow starts.

A flow starts for three reasons:

  • A record action declares flowId.
  • A collection action declares flowId.
  • A file slot declares flowId and someone confirms an upload.

A flow is a Temporal workflow that runs on a Quantum worker. In the package you bind it in one of two ways:

  • workflowType + taskQueue: the workflow name and the queue of the worker that runs it. When the package is installed, Quantum registers the flow as an automation of your organization and fills in automationId for you.
  • automationId: an automation that already exists in your organization.

In both cases every run is a normal execution of the organization: it is billed and shows up in Executions.

The input envelope

Every flow receives a single JSON object with this shape:

{
  "schema": "qac.operational-flow-input",
  "orgId": "org_8f2c",
  "organizationId": "org_8f2c",
  "environment": "prod",
  "appId": "returns",
  "flowId": "issue-refund",
  "outboxId": "3b1f0c9e-52a7-4d1e-9c55-0a6d7e21f4b8",
  "trigger": { "kind": "action", "actionId": "approve", "recordId": "7c1d6a52-1f0e-4b7a-9a43-2f8f0f3f9b10" },
  "input": { "note": "Defective product confirmed" },
  "actor": { "userId": "user_41", "email": "ana@example.com" },
  "settings": { "refundProvider": "sandbox" },
  "record": {
    "recordId": "7c1d6a52-1f0e-4b7a-9a43-2f8f0f3f9b10",
    "recordTypeId": "returns.request",
    "state": "approved",
    "version": 2,
    "data": { "orderNumber": "A-1042", "storeId": "store-01", "amount": 129900 }
  },
  "files": []
}
  • trigger.kind is action or file. With file you get slotId, fileIds and, if the slot belongs to a record, recordId.
  • input is the data the user sent with the action, already validated against the declared input.
  • actor is the person who triggered the flow.
  • settings is the app configuration in that environment, read when the flow starts.
  • record is the full record as it is when the flow starts (with the action's change already applied), or null if the trigger has no record.
  • files describes the trigger's files: the uploaded file, or the fileIds sent with a collection action. A record action does not bring that record's files.
  • outboxId identifies this start. It is the same value across every retry.

If the flow binding declares input, those keys arrive at the top level of the object, underneath the standard keys. When the flow is started through an automation, the object also includes that automation's default values and its usual fields (executionId, automationId, userId, email).

The Python client

The qac package includes the client a flow uses to register results. Use it from activities, not from workflow code: it makes HTTP calls and waits between retries.

from qac.operational import OperationalFlowInput, SystemOfRecordsClient, record_id

envelope = OperationalFlowInput.parse(flow_input)
client = SystemOfRecordsClient.from_flow_input(envelope)

from_flow_input points the client at the organization, environment, and app of the envelope. The connection to Quantum comes from the worker environment; your code does not handle credentials.

Create or update records

result = client.upsert_records([
    {
        "recordTypeId": "returns.request",
        "recordId": record_id("returns.request", "A-1042"),
        "data": {"orderNumber": "A-1042", "storeId": "store-01", "amount": 129900},
    },
])
# result["counts"]   -> {"created": 1, "updated": 0, "unchanged": 0, "rejected": 0}
# result["rejected"] -> records that failed validation, with their error
  • record_id(...) builds a stable identifier from the business identity. The same parts always give the same id.
  • mode="upsert" (the default) creates the record or merges the fields you send into the ones it already has. Fields you do not mention keep their value. If nothing changes, the result is unchanged.
  • mode="create" never touches a record that already exists. Use it when people may have acted on it.
  • state is optional. On create, the record is born in the lifecycle's initial state. On update, the state change must be an allowed transition.
  • Each record is validated against its schema. An invalid one comes back as rejected with the reason; the rest are written.
  • Flows can write readOnly fields. Those fields exist precisely for values the system computes and a person must not edit.
  • The client sends batches of 500 records.

Change a record's state

client.transition(
    envelope.record["recordId"],
    state="refunded",
    data={"refundReference": "RF-20391"},
    reason="Refund issued",
)

data is merged into the current data. The transition must be allowed by the lifecycle. Repeating the same call when the record is already in that state does not fail.

Write dataset rows

client.write_dataset_rows(
    None,  # uses the app from the envelope
    "refunds-by-day",
    [{"day": "2026-11-17", "storeId": "store-01", "refunds": 4, "amount": 389700}],
    replace=False,
)
  • Each row is validated against the dataset fields. Undeclared fields are not accepted and key fields are required.
  • A row with the same key replaces the previous one.
  • With replace=True the dataset ends up with only the rows of this call.
  • The client sends batches of 500 rows. If one row is invalid, none of its batch is written.

Read the settings

envelope.settings already carries the configuration. If you need the full definition, client.get_app() returns it.

Report the result

client.report_flow_result(envelope.outbox_id, "completed", output={"refundReference": "RF-20391"})

The status is completed or failed. output is a small summary (100 KB at most): large results go into records, datasets, or files. With failed, send the reason in error.

Always report. Without this step the start stays in dispatched and the app cannot tell whether the flow finished.

Ready-made activities

If you prefer not to write activities for this, qac.operational_activities ships three Temporal activities that take an object with flowInput: sor_upsert_records, sor_write_dataset_rows, and sor_report_flow_result.

A complete flow

from datetime import timedelta

from temporalio import activity, workflow
from temporalio.exceptions import ActivityError, ApplicationError

with workflow.unsafe.imports_passed_through():
    from qac.operational import OperationalFlowInput, SystemOfRecordsClient
    from qac.operational_activities import sor_report_flow_result


@activity.defn(name="issue_refund")
def issue_refund(flow_input: dict) -> dict:
    envelope = OperationalFlowInput.parse(flow_input)
    client = SystemOfRecordsClient.from_flow_input(envelope)
    record = envelope.record
    # Call your payment provider here. Use outbox_id as the idempotency key.
    reference = "RF-" + envelope.outbox_id[:8]
    client.transition(
        record["recordId"],
        state="refunded",
        data={"refundReference": reference},
        reason="Refund issued",
    )
    return {"refundReference": reference}


@workflow.defn(name="ReturnsRefundWorkflow")
class ReturnsRefundWorkflow:
    @workflow.run
    async def run(self, flow_input: dict) -> dict:
        output, status, error = None, "completed", None
        try:
            output = await workflow.execute_activity(
                issue_refund, flow_input, start_to_close_timeout=timedelta(minutes=5)
            )
        except ActivityError as exc:
            status, error = "failed", str(exc.cause or exc)
        await workflow.execute_activity(
            sor_report_flow_result,
            {"flowInput": flow_input, "status": status, "output": output, "error": error},
            start_to_close_timeout=timedelta(minutes=1),
        )
        if status == "failed":
            raise ApplicationError(error)
        return output

Idempotency and retries

Always assume your flow can run more than once. Quantum gives you three guarantees and asks one thing of you.

What Quantum guarantees:

  • One start per action. The start is stored in the same operation as the record change, with an identifier derived from the action, the record, and its version. Repeating the request does not create a second start.
  • One workflow per start. The workflow identifier is derived from the outboxId. If the dispatch is retried, Temporal rejects the duplicate.
  • One start per file. Confirming the same upload twice starts the flow only once.

If the flow cannot be started (for example, the worker does not respond), Quantum retries with growing waits, up to eight times. It does not retry when the problem will not fix itself: the app is suspended, the automation does not exist, or billing does not allow the run.

What is on you:

  • Idempotent writes. Give every record a deterministic recordId with record_id(...). That way an activity retry updates the same record instead of duplicating it.
  • Idempotent external effects. If you call a provider, use outbox_id as the idempotency key.

On collection actions, the client can send idempotencyKey in the request body. Without that key, every request is a new run.

The Python client retries network errors, 5xx responses, and the 408, 425, and 429 codes on its own, up to four attempts. Any other error raises SystemOfRecordsError with the status and the response body. A 409 means the record changed while you were writing: let the activity fail and Temporal retry it.

Reading uploaded files

Each item in files carries what you need to read the file:

{
  "fileId": "0d3a4b1e-8a55-4c0b-b1d2-6f3e0a9c7d21",
  "slotId": "returns-file",
  "bucket": "example-bucket",
  "key": "operational-apps/org_8f2c/prod/returns/files/returns-file/0d3a4b1e-8a55-4c0b-b1d2-6f3e0a9c7d21/returns.csv",
  "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
  "fileName": "returns.csv",
  "contentType": "text/csv"
}
import hashlib

import boto3

source = envelope.files_for_slot("returns-file")[0]
body = boto3.client("s3").get_object(Bucket=source.bucket, Key=source.key)["Body"].read()
if hashlib.sha256(body).hexdigest() != source.sha256:
    raise ValueError("The file does not match the recorded checksum")

Only confirmed files reach a flow, that is, those whose size and SHA-256 checksum Quantum has already verified. sha256 comes in hexadecimal.

What a run looks like

  • In the app: when the action runs or the file is uploaded, the screen shows that the flow is in progress. The notice for a record action goes away when the record changes again, which is how the result arrives.
  • In Executions: the run appears with the name of the flow's automation and the user who triggered it. The execution identifier is the outboxId.
  • In the record history: every write from the flow is recorded with the fields it changed and, for transitions, the reason you sent.
  • Through the API: you can query the status of a start with its outboxId.
curl "$QAC_API/operational-apps/returns/flows/3b1f0c9e-52a7-4d1e-9c55-0a6d7e21f4b8" \
  -H "Authorization: Bearer $QAC_TOKEN"
{
  "outboxId": "3b1f0c9e-52a7-4d1e-9c55-0a6d7e21f4b8",
  "flowId": "issue-refund",
  "status": "completed",
  "startedAt": "2026-11-17T15:04:05.120Z",
  "completedAt": "2026-11-17T15:04:19.871Z",
  "executionId": "3b1f0c9e-52a7-4d1e-9c55-0a6d7e21f4b8",
  "environment": "prod"
}

status goes through pending (queued), dispatched (workflow started), and completed or failed (result reported, or start impossible). With failed you get error. When you read a record with GET /operational-records/{recordId}, the lastFlow field carries this same information for the last flow started on that record.

If the flow never starts after the retries, the run is marked as failed in Executions.