Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 28 additions & 2 deletions docs/constraints/workflow-constraints.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,35 @@ Here are some examples of things you shouldn't do inside of a workflow class:

## Logging from workflow code {#workflow-logging}

A worker reconstructs committed workflow history after activations and cold replacement, so ordinary application logging can repeat earlier messages. Use the replay-aware logger documented for your binding when available. Rust service mode provides the [Rust SDK 4.17 workflow logger](../polyglot/rust.md#workflow-logging); other bindings retain their separately documented contracts.
The engine replays a workflow from its history every time it wakes up, so an ordinary log call in workflow code is written again for every completed step. A workflow with 50 steps logs its opening line 50 times. Use the replay-aware logger instead. It writes only when the code runs for the first time. The embedded, PHP SDK and Rust loggers also add the run's identity to each line:

Logging is a process observation. Keep durable workflow commands independent of replay-state observations and log delivery. Even a replay-aware logger can repeat a message from an uncommitted attempt after a crash or retry; it is not an exactly-once outbox. Keep host handlers bounded and nonblocking so logging does not stall the worker. Put durable business effects behind the appropriate activity or recorded workflow operation instead.
- Embedded workflows (Workflow 2.42.0 or later): `$this->logger()` returns a PSR-3 logger that writes through the Laravel logger, or through the channel you pass, as in `$this->logger('workflow')`. Each line carries `workflow_instance_id`, `workflow_run_id`, `workflow_type` and `namespace`. `$this->replayState()` returns `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` or `Unavailable`), and `$this->isReplaying()` is its boolean form.
- PHP SDK: `$context->logger()` writes through the `Worker`'s PSR-3 logger. See the [PHP SDK guide](../polyglot/php.md#workflow-logging).
- Rust SDK: `ctx.logger()`. See the [Rust SDK 4.17 workflow logger](../polyglot/rust.md#workflow-logging).
- Python SDK: `ctx.logger`, which is silent during replay but adds no run identity.

```php
use function Workflow\V2\activity;
use Workflow\V2\Workflow;

final class ShipOrderWorkflow extends Workflow
{
public function handle(string $orderId): string
{
$this->logger()->info('Shipping started', ['order_id' => $orderId]);
$label = activity(PrintLabelActivity::class, $orderId);
$this->logger()->info('Label printed', ['label' => $label]);

return $label;
}
}
```

Queries and update validators never log, because they always replay.

In embedded workflows, the lines are written after the workflow task's database transaction commits, so a task that rolls back writes nothing. Code that parks on a pending `select()` handle without recording a step logs once, in the task that moves past the await. Lines from a live update handler are written when the update is applied. In the PHP SDK, lines are written after the Server accepts the workflow task; see the [PHP SDK guide](../polyglot/php.md#workflow-logging).

Logging is a process observation. Keep durable workflow commands independent of replay-state observations and log delivery. A replay-aware logger is not an exactly-once outbox: if an embedded or PHP SDK worker dies between the commit or acceptance and the write, those lines are lost, and the Rust logger can repeat a message from an uncommitted attempt after a crash or retry. Keep host handlers bounded and nonblocking so logging does not stall the worker. Put durable business effects behind the appropriate activity or recorded workflow operation instead.

## Boot-Time Guardrails

Expand Down
48 changes: 48 additions & 0 deletions docs/features/updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Each accepted update:
- Uses the declared durable update name in command history and webhook routing — `#[UpdateMethod('mark-approved')]` keeps the public callable name stable across PHP method renames.
- Rejects against historical or already-closed runs rather than silently mutating the current run.
- Rejects undeclared method names as `rejected_unknown_update` and contract-invalid arguments as `rejected_invalid_arguments` (with machine-readable `validation_errors`) before the handler runs.
- Rejects a request that your [update validator](#validate-updates-before-acceptance) refuses as `update_validator_rejected` before it is accepted.

Like queries, updates replay committed history first. Unlike queries, updates are allowed to mutate replay-safe workflow state and return a value.

Expand Down Expand Up @@ -111,6 +112,53 @@ $latest->closedAt(); // null until the lifecycle closes

`inspectUpdate()` does not wait for workflow execution. It reloads the stored durable lifecycle and returns the current `UpdateResult`.

## Validate updates before acceptance {#validate-updates-before-acceptance}

Without a validator, an update that breaks a business rule is accepted and then fails. It is recorded as a failed update, and the caller can't tell a bad request from a failed operation. Declare a validator to refuse the request before it is accepted. Validators require Workflow 2.42.0 or later.

```php
use Workflow\UpdateMethod;
use Workflow\UpdateValidator;
use Workflow\V2\Workflow;

final class CartWorkflow extends Workflow
{
private array $items = [];

#[UpdateMethod('add-item')]
public function addItem(string $item): array
{
$this->items[] = $item;

return $this->items;
}

#[UpdateValidator('add-item')]
public function validateAddItem(string $item): void
{
if (count($this->items) >= 10) {
throw new \RuntimeException('The cart is full.');
}
}
}
```

`#[UpdateValidator]` names the update by its durable name, or by its method name when the update has no alias. The validator takes the same arguments as the update. Before the update is accepted, the engine rebuilds the run's state from its history and calls only the validator:

- Returning normally lets the update be accepted and applied as usual.
- Throwing, or returning `false`, rejects the update with the reason `update_validator_rejected` and the outcome `rejected_invalid_arguments`. `rejectedByValidator()` is true, `rejectionMessage()` returns the exception message, and `validationErrors()` returns the errors of a Laravel `ValidationException`. `update()` throws a `LogicException` that includes the reason and the validator's message.
- A rejected update is never accepted, its handler never runs and the workflow isn't woken. Like every other rejection, it is recorded only as an `UpdateRejected` audit event, which replay ignores.

Validators are read-only. They can read the replayed workflow state, but any durable call (an activity, timer, child workflow, signal, side effect, `await`, `getVersion()`, `patched()`, continue-as-new, or memo or search-attribute upsert) throws `UpdateValidatorCommandException` and rejects the update. Changes a validator makes to the replayed state are discarded. A generator validator is rejected, because its body never runs.

Validators aren't recorded in history and never run during replay, so they don't affect determinism. They see the state from committed history: an update that was accepted but not yet applied isn't visible to them. The replay and the validator run while the update's admission holds the run's locks, so keep validators fast.

If the state can't be replayed, or the validator hits a database error, `UpdateValidationFailedException` is thrown and nothing is recorded. Webhook update routes answer it with a retryable `503` and `update_validation_failed`. Retry with the same request ID.

A keyed retry of a rejected update returns the retained rejection without running the validator again.

Worker interceptors wrap update validation through `executeUpdateValidation()`. They see the validator's decision but can't change it.

## Recover after an uncertain response {#recover-after-an-uncertain-response}

Durable admission, handler completion and an external business effect are
Expand Down
60 changes: 60 additions & 0 deletions docs/polyglot/php.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,66 @@ Remote workers register workflow, activity, query, and update handlers through
Use the generated [PHP SDK API reference](https://php.durable-workflow.com/api/)
for complete parameters and return types.

## Update validators {#update-validators}

PHP SDK 3.32.0 and later let a workflow refuse an update before it is accepted. Put `#[UpdateValidator]` on a method of the workflow class, next to its `#[Update]` handler. The low-level form is `Worker::registerUpdateValidator($workflowType, $updateName, $callable)`, called after `registerUpdate()`.

```php
use DurableWorkflow\Attribute\Update;
use DurableWorkflow\Attribute\UpdateValidator;
use DurableWorkflow\Worker\QueryContext;

final class OrderWorkflow
{
#[Update('approve')]
public function approve(QueryContext $context, int $amount): int
{
return $amount;
}

#[UpdateValidator('approve')]
public function validateApprove(QueryContext $context, int $amount): void
{
if ($amount <= 0) {
throw new \DomainException('The amount must be positive.');
}
}
}
```

The validator takes a `QueryContext` with the run's committed history, followed by the update's arguments. The worker advertises the validator to the Server and polls workflow and update-validation tasks together. Registration is refused with `update_validation_tasks_unavailable` when the Server doesn't advertise synchronous update validation. For each validation task, the worker runs only the validator:

- Returning normally approves the update, and the Server accepts it.
- Throwing, or returning `false`, rejects it with `update_validator_rejected`, the exception message and class, and any field errors from an `errors()` method on the exception. The update is never accepted and its handler never runs. The Server records the rejection only as an `UpdateRejected` audit event.
- Trying to schedule durable work is refused with `UpdateValidatorCommandRefused`, which rejects the update.

On the client, `updateWorkflow()` throws `UpdateFailed`. `rejectedByValidator()` identifies a validator rejection and `validationErrors()` returns its field errors. `validationFailed()` is true when the Server couldn't get a decision in time; nothing was accepted, so retry with the same request ID.

Validators never run during replay. Each validation sees only the history committed before its own task, so two validations running at the same time can both pass a check that only one of them should. A validator worker doesn't use carried workflow polls. Worker interceptors wrap update validation tasks through `executeUpdateValidation()`; they see the validator's decision but can't change it.

## Replay-aware workflow logging {#workflow-logging}

The worker replays a workflow from its history on every workflow task, so an ordinary log call in workflow code repeats once for every completed step. PHP SDK 3.32.0 and later provide `$context->logger()`. It returns a PSR-3 logger that writes through the logger you pass to the `Worker` (the named `logger` argument), and only when the code runs past the run's committed history:

```php
use DurableWorkflow\Worker\WorkflowContext;

function approve(WorkflowContext $context, string $orderId): string
{
$context->logger()->info('Approval started', ['order_id' => $orderId]);
$decision = $context->activity('review', [$orderId]);
$context->logger()->info('Review finished', ['decision' => $decision]);

return $decision;
}
```

Each line carries `namespace`, `workflow_type`, `workflow_id` and `workflow_run_id`. `$context->replayState()` returns `WorkflowReplayState::Replaying`, `Executing` or `Unavailable`, and `isReplaying()` is its boolean form. Use them for diagnostics only; never choose workflow commands from them.

Lines are written only after the Worker submits the workflow task that ran the code and the Server accepts it. A superseded replay, a speculative replay the Server declines and a refused completion write nothing. Code that parks on a pending child or operation handle without recording a step logs once, in the task that moves past the wait. A `logger()` call inside a side-effect closure writes nothing.

If the worker dies between the Server's acceptance and the write, those lines are lost. This is a process logger, not an outbox for business effects. Keep log handlers fast and non-blocking: a handler that waits on the network stalls the worker and can cost it the task lease. Logger failures are caught and never change the workflow's commands.

## Activity retry context and owning run {#activity-retry-context}

PHP SDK **3.6.1 or later** exposes `$context->retryInfo`, `$context->workflowId` and `$context->runId` in service-mode activities. Check `$context->retryInfo->isLastConfiguredAttempt() === true` for the final configured attempt of a bounded policy. `attemptNumber` preserves the original received attempt number.
Expand Down
41 changes: 41 additions & 0 deletions docs/polyglot/rust.md
Original file line number Diff line number Diff line change
Expand Up @@ -974,6 +974,47 @@ Workers register named handlers with `Worker::register_update`; use
directly. An update is a durable, result-bearing workflow mutation. It is
separate from fire-and-forget signals and read-only replayed queries.

### Update validators {#update-validators}

Rust SDK 4.25.0 and later let a worker refuse an update before it is
accepted. Register a validator with `Worker::register_update_validator`, after
the update handler of the same name:

```rust,ignore
worker.register_update("orders", "approve", |_ctx, args| async move { Ok(args) });
worker.register_update_validator("orders", "approve", |_ctx: QueryContext, args: Value| {
if args[0].as_u64() == Some(0) {
return Err(UpdateRejection::new("amount must be positive")
.with_validation_error("amount", "must be positive"));
}
Ok(())
});
```

`register_update_validator_avro_value` takes Avro values. A replayed-state validator,
`register_replayed_update_validator::<S>`, reads a detached copy of the
workflow's replayed state; it must use the same state type as the replayed
workflow. The worker advertises the validator, refuses registration when the
Server doesn't advertise synchronous update validation, and polls workflow and
update-validation tasks together. For each validation task, it runs only the
validator:

- `Ok(())` approves the update and the Server accepts it.
- An `UpdateRejection` rejects it with `update_validator_rejected`, the
message, type and validation errors. The update is never accepted and its
handler never runs. The Server records the rejection only as an
`UpdateRejected` audit event.
- A validator that adds a workflow command is refused with
`UpdateValidatorCommandRefused`, and a panic or replay failure reports
`update_validation_worker_failed`.

On the client, `Error::update_validator_rejection()` returns the rejection's
message, validation errors and IDs, and `Error::is_update_validation_failed()`
covers timeouts and worker failures. An ordinary failed update matches neither.
Validators never run during replay. Worker interceptors wrap update validation
tasks through `execute_update_validation_task`; they see the validator's decision
but can't change it.

## Payload envelope

Workflow input, signals, activities, queries, and results use the published
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,35 @@ Beispiele für Operationen, die nicht in den Workflow-Code gehören:

## Logging aus Workflow-Code {#workflow-logging}

Ein Worker rekonstruiert nach Aktivierungen und kaltem Austausch den persistierten Workflow-Verlauf. Gewöhnliches Anwendungslogging kann deshalb frühere Meldungen wiederholen. Verwenden Sie den für Ihr Binding dokumentierten replay-bewussten Logger, sofern verfügbar. Rust Service Mode bietet den [Workflow-Logger des Rust SDK 4.17](../polyglot/rust.md#workflow-logging); andere Bindings behalten ihre gesondert dokumentierten Verträge.
Die Engine spielt einen Workflow bei jedem Aufwachen aus seinem Verlauf erneut ab, daher wird ein gewöhnlicher Log-Aufruf im Workflow-Code für jeden abgeschlossenen Schritt erneut geschrieben. Ein Workflow mit 50 Schritten protokolliert seine erste Zeile 50-mal. Verwenden Sie stattdessen den replay-bewussten Logger. Er schreibt nur, wenn der Code zum ersten Mal ausgeführt wird. Die Logger für eingebettete Workflows, das PHP SDK und Rust ergänzen jede Zeile zusätzlich um die Identität des Laufs:

Logging ist eine Prozessbeobachtung. Halten Sie dauerhafte Workflow-Befehle unabhängig von Replay-Zustand und Log-Zustellung. Auch ein replay-bewusster Logger kann eine Meldung aus einem nicht persistierten Versuch nach Absturz oder Retry wiederholen; er ist keine Outbox mit Exactly-once-Garantie. Host-Handler müssen begrenzt und nicht blockierend bleiben, damit Logging den Worker nicht aufhält. Dauerhafte Geschäftseffekte gehören stattdessen in eine passende Activity oder aufgezeichnete Workflow-Operation.
- Eingebettete Workflows (Workflow 2.42.0 oder neuer): `$this->logger()` liefert einen PSR-3-Logger, der über den Laravel-Logger oder über den übergebenen Kanal schreibt, etwa `$this->logger('workflow')`. Jede Zeile enthält `workflow_instance_id`, `workflow_run_id`, `workflow_type` und `namespace`. `$this->replayState()` liefert `Workflow\V2\Enums\WorkflowReplayState` (`Replaying`, `Executing` oder `Unavailable`), und `$this->isReplaying()` ist die boolesche Form.
- PHP SDK: `$context->logger()` schreibt über den PSR-3-Logger des `Worker`. Siehe den [PHP-SDK-Leitfaden](../polyglot/php.md#workflow-logging).
- Rust SDK: `ctx.logger()`. Siehe den [Workflow-Logger des Rust SDK 4.17](../polyglot/rust.md#workflow-logging).
- Python SDK: `ctx.logger`, der während eines Replays schweigt, aber keine Identität des Laufs ergänzt.

```php
use function Workflow\V2\activity;
use Workflow\V2\Workflow;

final class ShipOrderWorkflow extends Workflow
{
public function handle(string $orderId): string
{
$this->logger()->info('Shipping started', ['order_id' => $orderId]);
$label = activity(PrintLabelActivity::class, $orderId);
$this->logger()->info('Label printed', ['label' => $label]);

return $label;
}
}
```

Abfragen und Update-Validatoren protokollieren nie, weil sie immer ein Replay sind.

In eingebetteten Workflows werden die Zeilen geschrieben, nachdem die Datenbanktransaktion des Workflow-Tasks committet wurde; ein Task, der zurückgerollt wird, schreibt also nichts. Code, der auf einem ausstehenden `select()`-Handle wartet, ohne einen Schritt aufzuzeichnen, protokolliert einmal, und zwar in dem Task, der über das Warten hinauskommt. Zeilen aus einem live ausgeführten Update-Handler werden geschrieben, wenn das Update angewendet wird. Im PHP SDK werden die Zeilen geschrieben, nachdem der Server den Workflow-Task angenommen hat; siehe den [PHP-SDK-Leitfaden](../polyglot/php.md#workflow-logging).

Logging ist eine Prozessbeobachtung. Halten Sie dauerhafte Workflow-Befehle unabhängig von Replay-Zustandsbeobachtungen und der Log-Zustellung. Ein replay-bewusster Logger ist kein Exactly-once-Outbox: Stirbt ein eingebetteter Worker oder ein Worker des PHP SDK zwischen dem Commit bzw. der Annahme und dem Schreiben, gehen diese Zeilen verloren, und der Rust-Logger kann eine Meldung aus einem nicht committeten Versuch nach einem Absturz oder Retry wiederholen. Halten Sie Host-Handler begrenzt und nicht blockierend, damit Logging den Worker nicht aufhält. Legen Sie dauerhafte Geschäftseffekte stattdessen in die passende Aktivität oder aufgezeichnete Workflow-Operation.

## Prüfungen beim Anwendungsstart {#boot-time-guardrails}

Expand Down
Loading