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
12 changes: 12 additions & 0 deletions .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -818,6 +818,18 @@ jobs:
QUEUE_CONNECTION: redis
XDEBUG_MODE: off

- name: Run bounded deadline close cost cases
run: >-
vendor/bin/phpunit tests/Unit/V2/CompletionWriteFamilyBudgetTest.php
tests/Unit/V2/IdempotentProjectionUpsertTest.php
--testsuite unit
--filter '/DeadlineClose|BoundedClose|ChildIsCharged|OrdinaryClose|SettlementPass|KeyOrder/'
--fail-on-warning --log-junit build/test-results/pr-deadline-close-cost.xml
env:
DB_CONNECTION: mysql
QUEUE_CONNECTION: redis
XDEBUG_MODE: off

- name: Run scoped Activity fencing and original stop receipt cases
run: >-
vendor/bin/phpunit tests/Feature/V2/V2ScopedActivityCancellationTest.php
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,18 @@
[worker interceptors](docs/worker-interceptors.md).
([Durable Workflow #226](https://github.com/durable-workflow/.github/issues/226))

- A bounded deadline close charges each item the history events and rows it
writes. A child closed by its parent's policy is charged its whole close,
including its open work, accepted updates and own children, and an accepted
update is charged both its events. A close or settlement transaction now
stays within the event and row limits. Two exceptions remain: a single item
larger than the whole budget is taken alone, and a timed-out child's close
still resumes its live parent in the same transaction. An ordinary
deadline close that fails records its error and attempt on the run's
workflow task and backs off like a failing settlement, so it no longer
starves other expired runs. On MySQL, a run projection no longer rewrites lineage rows whose JSON
differs only in key order. (#1290)

## 2.41.0 - 2026-11-25

- Experimental state machines: `MachineCatalog` registers the definitions
Expand Down
96 changes: 73 additions & 23 deletions docs/architecture/completion-budget.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,16 +272,41 @@ That close is the server's own work on stored state, not the worker's, so it
runs outside the worker's meter (`HistoryTransactionMeter::unmetered()`) and
before the early check. A budget refusal therefore never prevents a close.

The close is bounded instead. An ordinary run, one without opted-in
timeout cleanup, closes in a single transaction only when its open work fits
one batch. The batch is the completion budget's events less one (for the
terminal event), and at most a fifth of its rows, since a cancelled activity
writes its execution, its task, its event and the run's position. With the
defaults that is 4,000 open activities, timers and tasks. A larger close is
fenced and continued:

1. One transaction cancels the first batch of open work, in the order and
with the history the single close writes: open activities with their tasks
The close is bounded instead. Each of its transactions may write at most the
completion budget's history events (`history_transaction_size`) and rows
(`completion_rows`). Every kind of work is charged what it writes, including
its projections (`DeadlineCloseBudget`):

| Work | Events | Rows |
| --- | ---: | ---: |
| The close itself: failure, run, `WorkflowTimedOut`, task, projections | 1 | 10 |
| A pass that does not close the run: task, run, projections | 0 | 6 |
| A cancelled activity with its task | 1 | 7 |
| A cancelled timer | 1 | 6 |
| Another open task | 0 | 2 |
| A failed accepted update, with `MessageCursorAdvanced` | 2 | 11 |
| A child closed by `terminate` or `request_cancel`, before its own work | 3 | 19 |
| A child asked to cancel (`request_cancellation`) | 3 | 17 |

A child's termination runs that child's whole close in the parent's
transaction. It is therefore charged its own open activities, timers and
tasks, its accepted updates, and in turn the children its own policy closes.
When the timed-out run is itself a child, its close also resumes its live
parent: the parent's child resolution and its workflow task, or a retry run
of the child. Those writes are fixed per close and are not charged.
The unit tests check every row of this table against the statements each
item writes, both in the close and in a pass that takes it alone, on SQLite
and MySQL. A run projection no longer rewrites a stored row whose JSON
differs only in key order. MySQL reorders JSON keys, so every projection
used to rewrite each of a run's lineage rows, one more row per child link in
every pass.

An ordinary run, one without opted-in timeout cleanup, closes in a single
transaction only when its open work and the close fit the budget, or when no
open work is left. A larger close is fenced and continued:

1. One transaction cancels the open work that fits, in the order and with
the history the single close writes: open activities with their tasks
and `ActivityCancelled`, then pending timers with `TimerCancelled`, then
other open tasks. The run stays open and expired. Its workflow task is
released to Ready, and the completion answers `completed: false` with
Expand All @@ -291,13 +316,13 @@ fenced and continued:
add open work between batches. An activity that finishes between batches
records its outcome as it would have before the close began, and later
batches skip it.
3. The watchdog continues the close without a worker. Each pass takes one
batch. When the rest fits, the existing close times the run out with the
3. The watchdog continues the close without a worker. Each pass takes what
fits. When the rest fits, the existing close times the run out with the
same `WorkflowTimedOut` and failure.
4. The cascade after the terminal event is bounded the same way. In order,
it fails the accepted updates and then applies parent-close policy to
open children. The close transaction takes what is left of its batch,
and each child's terminate or cancellation is that child's own write.
open children, in link order. The close transaction takes what is left
of its budget.
5. If work remains, the run already reads Failed, with its `WorkflowTimedOut`
recorded, while its accepted updates and children are settled over later
passes. Its closing task is held: Leased by `deadline-close-settlement`
Expand All @@ -311,10 +336,10 @@ fenced and continued:
6. The watchdog finds due held tasks among the open tasks, by status and
owner. It applies its connection, queue, namespace, instance and run
scope before its scan limit, oldest due first. That set does not grow
with retained closed runs. Each pass settles one more batch, updates
before children and children in link order, skipping any child the run
already recorded a policy outcome for. When nothing is left, the task is
Completed and the marker becomes `settled`.
with retained closed runs. Each pass settles what fits its budget,
updates before children and children in link order, skipping any child
the run already recorded a policy outcome for. When nothing is left, the
task is Completed and the marker becomes `settled`.
7. A pass that fails rolls back. In a separate transaction, it records the
error as the held task's `last_error`, adds one to `attempt_count` and to
the payload's `deadline_close_settlement_failures`, and backs the task off
Expand All @@ -327,11 +352,36 @@ fenced and continued:
(`deadline_close_settlement`) shows its state, failed attempts, last error
and next attempt.

Every pass removes at least one open item, so a close always finishes, within
one pass per batch. The history of a batched close is the history the single
close writes, so a run closed by an earlier version and a run closed in
batches replay the same way. Setting both limits to 0 restores the single
transaction.
Every pass, a batch of open work or a settlement pass, takes at least its
first item even when that item alone is larger than the budget, so a close
always finishes. Such an item is taken alone. Only a child with very large
open work of its own can be one, since its terminate is a single command on
that child; with the default limits, a child would need about 5,000 open
items. The close transaction itself takes cascade work only when it fits.
The history of a batched close is the history the single close writes, so a
run closed by an earlier version and a run closed in batches replay the same
way. Setting both limits to 0 restores the single transaction.

**A failing ordinary close.** When the watchdog's close of an ordinary
expired run fails, it rolls back. In a separate transaction the watchdog
records the error as that workflow task's `last_error`, adds one to its
`attempt_count` and to the payload's `deadline_close_failures`, and moves its
`available_at` out by the settlement's backoff (10 seconds, doubling per
failure up to an hour). The watchdog does not select the run again until the
task is due. Closes that keep failing therefore no longer stay at the front of
the oldest-deadline scan and starve the other expired runs in scope.
The run stays open and expired, and an expired run accepts no workflow
command, so the backoff only spaces out the retries. A task held for a
settlement or under a live lease is never changed.

**No operator release.** There is deliberately no command that releases a
held settlement without finishing it. The settlement fails accepted updates
and applies parent-close policy. Releasing it would leave those updates
accepted with callers waiting forever, and leave children running that the
policy closes. A settlement pass that fails is retried with backoff, and it
stays visible in metrics, queue visibility and run describe with its last
error. Once the cause is fixed, the next due pass settles it, at most an
hour later.

**Selection of expired runs.** Expired runs are taken oldest deadline first,
then by id. The watchdog used to skip an expired run with
Expand Down
227 changes: 227 additions & 0 deletions src/V2/Support/DeadlineCloseBudget.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
<?php

declare(strict_types=1);

namespace Workflow\V2\Support;

/**
* The history events and rows one transaction of a bounded deadline close
* may write (#1116, #1290): the completion budget's event limit and its row
* limit, each 0 for no bound.
*
* Every kind of work the close does is charged what it writes, with its
* projections: a cancelled activity or timer, an accepted update failed with
* its cursor event, and a child's whole policy outcome, which is that
* child's own terminate with its open work, its accepted updates and its own
* children. The fixed writes of the close or of a pass are reserved first.
*
* Work is taken while it fits. A pass that must make progress takes its
* first item even when that item alone is larger than the budget, so every
* pass removes at least one item and the close always finishes.
*/
final class DeadlineCloseBudget
{
/**
* A cancelled activity: its execution and task, ActivityCancelled with the
* run position it advances, its timeline entry, and its wait's status and
* task status.
*
* @var array{int, int}
*/
public const ACTIVITY = [1, 7];

/**
* A cancelled timer: the timer, TimerCancelled with the run position, its
* timeline entry, its wait and its timer entry.
*
* @var array{int, int}
*/
public const TIMER = [1, 6];

/**
* Another open task cancelled, with its wait's task status.
*
* @var array{int, int}
*/
public const TASK = [0, 2];

/**
* A failed accepted update: its failure, UpdateCompleted and the
* MessageCursorAdvanced it may need, each with its run position and
* timeline entry, and the update, command and cursor rows.
*
* @var array{int, int}
*/
public const UPDATE = [2, 11];

/**
* A child closed by terminate or request_cancel, before its own work: its
* command, requested and terminal events with their run positions, its
* failure, run, summary, lineage and timeline rows, and the parent's
* ParentClosePolicyApplied.
*
* @var array{int, int}
*/
public const CHILD = [3, 19];

/**
* A child asked for cooperative cancellation (request_cancellation): the
* request's command and event, its resume task and projections, the
* parent's ParentClosePolicyApplied, and the parent's cancellation origin,
* which only the first request writes but each is charged. The child
* stays open, so nothing cascades.
*
* @var array{int, int}
*/
public const CANCELLATION_REQUEST = [3, 17];

/**
* The close's own writes: its failure, the run, WorkflowTimedOut with the
* run position, the closing task and the run's projections.
*
* @var array{int, int}
*/
public const CLOSE = [1, 10];

/**
* A pass that does not close the run: its task, the run and the run's
* projections.
*
* @var array{int, int}
*/
public const PASS = [0, 6];

private bool $taken = false;

private bool $progress = false;

private function __construct(
private ?int $events,
private ?int $rows,
) {
}

/**
* The budget of one close or settlement transaction, or null when both
* limits are disabled and the close takes everything at once.
*/
public static function forTransaction(): ?self
{
$events = StructuralLimits::historyTransactionSizeLimit();
$rows = StructuralLimits::completionRowsLimit();
if ($events <= 0 && $rows <= 0) {
return null;
}

return new self($events > 0 ? $events : null, $rows > 0 ? $rows : null);
}

/**
* No bound: everything fits.
*/
public static function unlimited(): self
{
return new self(null, null);
}

public function unbounded(): bool
{
return $this->events === null && $this->rows === null;
}

/**
* Make this a pass that must make progress: its first item is taken even
* when it alone does not fit.
*/
public function progressing(): self
{
$this->progress = true;

return $this;
}

/**
* Charge fixed writes the transaction makes whatever it takes.
*
* @param array{int, int} $cost
*/
public function reserve(array $cost, int $count = 1): void
{
if ($this->events !== null) {
$this->events -= $cost[0] * $count;
}
if ($this->rows !== null) {
$this->rows -= $cost[1] * $count;
}
}

/**
* @param array{int, int} $cost
*/
public function fits(array $cost, int $count = 1): bool
{
return ($this->events === null || $this->events >= $cost[0] * $count)
&& ($this->rows === null || $this->rows >= $cost[1] * $count);
}

/**
* Charge one item if it fits, or if it is the first item of a pass that
* must make progress.
*
* @param array{int, int} $cost
*/
public function take(array $cost): bool
{
if (! $this->fits($cost) && ! ($this->progress && ! $this->taken)) {
return false;
}
$this->reserve($cost);
$this->taken = true;

return true;
}

/**
* How many items of one cost fit, at least one for the first item of a
* pass that must make progress. Nothing is charged; see {@see self::charge()}.
*
* @param array{int, int} $cost
*/
public function room(array $cost): int
{
$room = PHP_INT_MAX;
foreach ([[$this->events, $cost[0]], [$this->rows, $cost[1]]] as [$left, $each]) {
if ($left !== null && $each > 0) {
$room = min($room, intdiv(max(0, $left), $each));
}
}

return $this->progress && ! $this->taken ? max(1, $room) : $room;
}

/**
* Charge items taken after {@see self::room()}.
*
* @param array{int, int} $cost
*/
public function charge(array $cost, int $count): void
{
if ($count <= 0) {
return;
}
$this->reserve($cost, $count);
$this->taken = true;
}

/**
* Add two costs.
*
* @param array{int, int} $cost
* @param array{int, int} $other
* @return array{int, int}
*/
public static function plus(array $cost, array $other, int $count = 1): array
{
return [$cost[0] + $other[0] * $count, $cost[1] + $other[1] * $count];
}
}
Loading