diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index ff5f4a67c..e5fc147f2 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -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 diff --git a/CHANGELOG.md b/CHANGELOG.md index c87fd5b9c..165548887 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/docs/architecture/completion-budget.md b/docs/architecture/completion-budget.md index c6f9b10e2..9f7260be3 100644 --- a/docs/architecture/completion-budget.md +++ b/docs/architecture/completion-budget.md @@ -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 @@ -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` @@ -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 @@ -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 diff --git a/src/V2/Support/DeadlineCloseBudget.php b/src/V2/Support/DeadlineCloseBudget.php new file mode 100644 index 000000000..21f5a6f7e --- /dev/null +++ b/src/V2/Support/DeadlineCloseBudget.php @@ -0,0 +1,227 @@ + 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]; + } +} diff --git a/src/V2/Support/DeadlineCloseSettlement.php b/src/V2/Support/DeadlineCloseSettlement.php index 8aae1200d..c87683ea3 100644 --- a/src/V2/Support/DeadlineCloseSettlement.php +++ b/src/V2/Support/DeadlineCloseSettlement.php @@ -16,8 +16,8 @@ /** * The cascade after a bounded deadline close's terminal event (#1116): the * accepted updates it fails and the children its parent-close policy acts - * on. Each transaction takes at most one batch, updates first and then - * children, in the order a single close takes them. + * on. Each transaction takes what fits its {@see DeadlineCloseBudget}, + * updates first and then children, in the order a single close takes them. * * While work is left, the run already reads Failed and its closing workflow * task is held: Leased by {@see self::OWNER} with no lease expiry, so no @@ -39,6 +39,12 @@ final class DeadlineCloseSettlement public const FAILURES = 'deadline_close_settlement_failures'; + /** + * Failed ordinary deadline closes on the run's open workflow task, before + * the run reads Failed (#1290). + */ + public const CLOSE_FAILURES = 'deadline_close_failures'; + public const PENDING = 'pending'; public const SETTLED = 'settled'; @@ -74,16 +80,23 @@ public static function hold(WorkflowTask $task): void } /** - * Settle at most $budget updates and children. Returns true when nothing - * is left, completing the held task; otherwise the task stays held. + * Settle the updates and children that fit one transaction's budget, at + * least one of them. Returns true when nothing is left, completing the + * held task; otherwise the task stays held. */ - public static function settle(WorkflowRun $run, WorkflowTask $task, int $budget): bool + public static function settle(WorkflowRun $run, WorkflowTask $task, ?DeadlineCloseBudget $budget = null): bool { - $budget -= PendingUpdateCloser::closeForTerminalRun($run, $task, $budget); + $budget ??= DeadlineCloseBudget::forTransaction() ?? DeadlineCloseBudget::unlimited(); + $budget->progressing() + ->reserve(DeadlineCloseBudget::PASS); + $budget->charge( + DeadlineCloseBudget::UPDATE, + PendingUpdateCloser::closeForTerminalRun($run, $task, $budget->room(DeadlineCloseBudget::UPDATE)), + ); $settled = false; if (! PendingUpdateCloser::hasAccepted($run)) { $childrenSettled = true; - ParentClosePolicyEnforcer::enforce($run, max(0, $budget), $childrenSettled); + ParentClosePolicyEnforcer::enforce($run, $budget, $childrenSettled); $settled = $childrenSettled; } @@ -140,6 +153,52 @@ public static function recordFailure(string $taskId, Throwable $error): void }); } + /** + * Record a failed ordinary deadline close, after it rolled back, on the + * open workflow task the watchdog closed the run with (#1290): the error, + * one more attempt, and the settlement's backoff before the watchdog + * selects the run again. The run stays open and expired, and an expired + * run accepts no workflow command, so the backoff only spaces out the + * retries. Without it a close that keeps failing stays at the front of + * the oldest-deadline scan and starves every other expired run in scope. + * A task held for a settlement or under a live lease is left alone. + */ + public static function recordCloseFailure(string $taskId, Throwable $error): void + { + ConfiguredV2Models::connection()->transaction(static function () use ($taskId, $error): void { + /** @var WorkflowTask|null $task */ + $task = ConfiguredV2Models::query('task_model', WorkflowTask::class) + ->lockForUpdate() + ->find($taskId); + if ($task === null + || $task->task_type !== TaskType::Workflow + || self::holds($task) + || ! in_array($task->status, [TaskStatus::Ready, TaskStatus::Leased], true) + || ($task->status === TaskStatus::Leased + && ($task->lease_expires_at === null || $task->lease_expires_at->isFuture()))) { + return; + } + $failures = self::closeFailures($task) + 1; + $task->forceFill([ + 'attempt_count' => (int) $task->attempt_count + 1, + 'last_error' => mb_substr($error->getMessage(), 0, 4000), + 'available_at' => now() + ->addSeconds(self::backoffSeconds($failures)), + 'payload' => [ + ...(is_array($task->payload) ? $task->payload : []), + self::CLOSE_FAILURES => $failures, + ], + ])->save(); + }); + } + + public static function closeFailures(WorkflowTask $task): int + { + $failures = is_array($task->payload) ? ($task->payload[self::CLOSE_FAILURES] ?? 0) : 0; + + return is_int($failures) ? $failures : 0; + } + public static function backoffSeconds(int $failures): int { return (int) min(self::BACKOFF_MAX_SECONDS, self::BACKOFF_BASE_SECONDS * (2 ** min(30, max(0, $failures - 1)))); diff --git a/src/V2/Support/IdempotentProjectionUpsert.php b/src/V2/Support/IdempotentProjectionUpsert.php index c0987715b..749345852 100644 --- a/src/V2/Support/IdempotentProjectionUpsert.php +++ b/src/V2/Support/IdempotentProjectionUpsert.php @@ -58,8 +58,9 @@ public static function upsert( try { if ($existing !== null) { - $existing->fill($values) - ->save(); + $existing->fill($values); + self::keepEquivalentJson($existing); + $existing->save(); return $existing; } @@ -108,6 +109,52 @@ public static function upsert( } } + /** + * Keep a stored JSON value that differs from the projected one only in + * the order of its object keys. MySQL stores JSON with its keys reordered, + * so the decoded arrays never compare equal and every projection of a run + * rewrote each of its rows, one write per row whatever changed (#1290). + */ + private static function keepEquivalentJson(Model $row): void + { + $attributes = $row->getAttributes(); + $kept = false; + foreach (array_keys($row->getDirty()) as $column) { + $original = $row->getRawOriginal($column); + $projected = $attributes[$column] ?? null; + if (! is_string($original) || ! is_string($projected) + || ! $row->hasCast($column, ['array', 'json', 'object', 'collection'])) { + continue; + } + try { + $equivalent = self::canonicalJson(json_decode($original, true, 512, JSON_THROW_ON_ERROR)) + === self::canonicalJson(json_decode($projected, true, 512, JSON_THROW_ON_ERROR)); + } catch (\JsonException) { + continue; + } + if ($equivalent) { + $attributes[$column] = $original; + $kept = true; + } + } + if ($kept) { + $row->setRawAttributes($attributes); + } + } + + private static function canonicalJson(mixed $value): mixed + { + if (! is_array($value)) { + return $value; + } + $value = array_map(self::canonicalJson(...), $value); + if (! array_is_list($value)) { + ksort($value, SORT_STRING); + } + + return $value; + } + /** * @template TModel of Model * @param class-string $model diff --git a/src/V2/Support/ParentClosePolicyEnforcer.php b/src/V2/Support/ParentClosePolicyEnforcer.php index 1d6a1bf40..f76a515e2 100644 --- a/src/V2/Support/ParentClosePolicyEnforcer.php +++ b/src/V2/Support/ParentClosePolicyEnforcer.php @@ -7,8 +7,12 @@ use Illuminate\Support\Facades\Log; use LogicException; use Workflow\V2\CommandContext; +use Workflow\V2\Enums\ActivityStatus; use Workflow\V2\Enums\HistoryEventType; use Workflow\V2\Enums\ParentClosePolicy; +use Workflow\V2\Enums\TaskStatus; +use Workflow\V2\Enums\TimerStatus; +use Workflow\V2\Enums\UpdateStatus; use Workflow\V2\Models\WorkflowHistoryEvent; use Workflow\V2\Models\WorkflowLink; use Workflow\V2\Models\WorkflowRun; @@ -35,40 +39,47 @@ final class ParentClosePolicyEnforcer * * @return list Instance IDs of children that had policy applied */ - public static function enforce(WorkflowRun $run, ?int $limit = null, ?bool &$complete = null): array - { + public static function enforce( + WorkflowRun $run, + ?DeadlineCloseBudget $budget = null, + ?bool &$complete = null, + ): array { $complete = true; return $run->getConnection() - ->transaction(static function () use ($run, $limit, &$complete): array { + ->transaction(static function () use ($run, $budget, &$complete): array { /** @var WorkflowRun $lockedRun */ $lockedRun = ConfiguredV2Models::query('run_model', WorkflowRun::class) ->lockForUpdate() ->findOrFail($run->id); - return self::enforceLocked($lockedRun, $limit, $complete); + return self::enforceLocked($lockedRun, $budget, $complete); }, 3); } /** * Apply policies while the caller holds the parent run's write lock. * - * With a limit (a bounded deadline close, #1116), at most that many - * children are acted on, in link order. A child this run already - * recorded a policy outcome for is skipped, so a later transaction - * continues where this one stopped; $complete reports whether any - * child is left. + * With a budget (a bounded deadline close, #1116), children are acted on + * in link order while each one's whole outcome fits what is left of the + * budget (#1290): a terminated or cancelled child is charged its own + * close with its open work, accepted updates and the children its own + * policy closes. A child this run already recorded a policy outcome for + * is skipped, so a later transaction continues where this one stopped; + * $complete reports whether any child is left. * * @internal * @return list */ - public static function enforceLocked(WorkflowRun $run, ?int $limit = null, bool &$complete = true): array - { + public static function enforceLocked( + WorkflowRun $run, + ?DeadlineCloseBudget $budget = null, + bool &$complete = true, + ): array { $appliedTo = []; - $acted = 0; $complete = true; // Children this run already recorded a policy outcome for, read once. - $settled = $limit === null ? [] : array_flip(array_filter( + $settled = $budget === null ? [] : array_flip(array_filter( $run->historyEvents() ->whereIn('event_type', [ HistoryEventType::ParentClosePolicyApplied->value, @@ -93,14 +104,12 @@ public static function enforceLocked(WorkflowRun $run, ?int $limit = null, bool continue; } - if ($limit !== null && $acted >= $limit) { + if ($budget !== null && ! $budget->take(self::cost($childRun, $policy, $budget))) { $complete = false; break; } - ++$acted; - if (self::applyTarget($run, $target, $childRun, $policy)) { $appliedTo[] = $target['child_instance_id']; } @@ -109,6 +118,84 @@ public static function enforceLocked(WorkflowRun $run, ?int $limit = null, bool return $appliedTo; } + /** + * What one child's policy outcome writes in the parent's transaction. A + * cancellation request leaves the child open. A terminate or + * request_cancel runs the child's whole close: its open tasks, activities + * and timers, its accepted updates, and in turn the open children its own + * policy closes. Counting stops once the total no longer fits $budget, + * since the child is then taken only as a pass's first item. + * + * @param array{int, int} $total the cost counted so far + * @return array{int, int} + */ + private static function cost( + WorkflowRun $childRun, + ParentClosePolicy $policy, + DeadlineCloseBudget $budget, + array $total = [0, 0], + ): array { + if ($policy === ParentClosePolicy::RequestCancellation) { + return DeadlineCloseBudget::plus($total, DeadlineCloseBudget::CANCELLATION_REQUEST); + } + $total = DeadlineCloseBudget::plus($total, DeadlineCloseBudget::CHILD); + if ($budget->unbounded()) { + return $total; + } + + $open = ConfiguredV2Models::query('run_model', WorkflowRun::class) + ->whereKey($childRun->id) + ->withCount([ + 'tasks as open_tasks' => static fn ($tasks) => $tasks->whereIn( + 'status', + [TaskStatus::Ready->value, TaskStatus::Leased->value], + ), + 'activityExecutions as open_activities' => static fn ($activities) => $activities->whereIn( + 'status', + [ActivityStatus::Pending->value, ActivityStatus::Running->value], + ), + 'timers as open_timers' => static fn ($timers) => $timers->where( + 'status', + TimerStatus::Pending->value, + ), + 'updates as accepted_updates' => static fn ($updates) => $updates->where( + 'status', + UpdateStatus::Accepted->value, + ), + ]) + ->toBase() + ->first(); + $activities = (int) ($open->open_activities ?? 0); + // An activity's cost includes its task. + $total = DeadlineCloseBudget::plus($total, DeadlineCloseBudget::ACTIVITY, $activities); + $total = DeadlineCloseBudget::plus( + $total, + DeadlineCloseBudget::TASK, + max(0, (int) ($open->open_tasks ?? 0) - $activities), + ); + $total = DeadlineCloseBudget::plus($total, DeadlineCloseBudget::TIMER, (int) ($open->open_timers ?? 0)); + $total = DeadlineCloseBudget::plus( + $total, + DeadlineCloseBudget::UPDATE, + (int) ($open->accepted_updates ?? 0), + ); + + foreach (self::targets($childRun) as $target) { + if (! $budget->fits($total)) { + break; + } + $grandchildPolicy = ParentClosePolicy::tryFrom($target['policy']); + $grandchild = $target['child_run']; + if ($grandchildPolicy === null || $grandchildPolicy === ParentClosePolicy::Abandon + || ! $grandchild instanceof WorkflowRun || ChildSupervision::isTerminal($grandchild)) { + continue; + } + $total = self::cost($grandchild, $grandchildPolicy, $budget, $total); + } + + return $total; + } + /** * @param array{link_id: string, sequence: int|null, child_instance_id: string, origin_run_id: string} $target */ diff --git a/src/V2/Support/WorkflowExecutor.php b/src/V2/Support/WorkflowExecutor.php index e323acbc6..afbba8aaa 100644 --- a/src/V2/Support/WorkflowExecutor.php +++ b/src/V2/Support/WorkflowExecutor.php @@ -77,8 +77,6 @@ final class WorkflowExecutor */ public const DEADLINE_CLOSING = 'closing'; - private const DEADLINE_CLOSE_ROWS_PER_ITEM = 5; - /** * The workflow object running the current task. When workflow code fails * without an activity step, its cursor is the step where it failed. @@ -189,27 +187,6 @@ public function closeExpiredDeadline(WorkflowRun $run, WorkflowTask $task): stri return self::DEADLINE_CLOSED; } - /** - * Open work items one deadline close transaction may cancel: the - * completion budget's events less the terminal event, and a fifth of its - * rows (a cancelled activity writes its execution, task, event and run - * position). Null when both limits are disabled, which closes at once. - */ - public static function deadlineCloseBatchSize(): ?int - { - $bounds = []; - $events = StructuralLimits::historyTransactionSizeLimit(); - if ($events > 0) { - $bounds[] = max(1, $events - 1); - } - $rows = StructuralLimits::completionRowsLimit(); - if ($rows > 0) { - $bounds[] = max(1, intdiv($rows, self::DEADLINE_CLOSE_ROWS_PER_ITEM)); - } - - return $bounds === [] ? null : min($bounds); - } - /** * Finish portable cleanup with the original cancellation outcome. * The caller holds the task and run locks before accepting a terminal command. @@ -371,21 +348,23 @@ public function deliverPortableCancellation( * Cancel one bounded batch of an oversized ordinary run's open work, as * {@see self::timeoutRun()} would: open activities with their tasks and * cancellation history, then pending timers with theirs, then other open - * tasks. Returns false, writing nothing, when the open work fits one - * close or the run's close belongs to opted-in timeout cleanup. + * tasks. Returns false, writing nothing, when the open work and the close + * fit one transaction's budget, which then holds what is left for the + * terminal cascade, or when the run's close belongs to opted-in timeout + * cleanup. */ private function cancelOpenWorkBatchBeforeDeadlineClose( WorkflowRun $run, WorkflowTask $task, - ?int &$cascadeBudget = null, + ?DeadlineCloseBudget &$cascadeBudget = null, ): bool { $cascadeBudget = null; if (CooperativeCancellationDelivery::context($run)?->isTimeout() === true || ($run->timeout_cleanup_work_deadline_at !== null && $run->cancellation_request_command_id === null)) { return false; } - $batch = self::deadlineCloseBatchSize(); - if ($batch === null) { + $budget = DeadlineCloseBudget::forTransaction(); + if ($budget === null) { return false; } @@ -421,12 +400,27 @@ private function cancelOpenWorkBatchBeforeDeadlineClose( true )) ->values(); + // An activity's cost includes one task; any further task is charged + // as another open task. + $activityCost = static fn (ActivityExecution $execution): array => DeadlineCloseBudget::plus( + DeadlineCloseBudget::ACTIVITY, + DeadlineCloseBudget::TASK, + max(0, $tasksByActivity->get($execution->id, collect())->count() - 1), + ); - $openWork = $openActivities->count() + $openTimers->count() + $otherTasks->count(); - if ($openWork <= $batch) { + $openWork = DeadlineCloseBudget::CLOSE; + foreach ($openActivities as $execution) { + $openWork = DeadlineCloseBudget::plus($openWork, $activityCost($execution)); + } + $openWork = DeadlineCloseBudget::plus($openWork, DeadlineCloseBudget::TIMER, $openTimers->count()); + $openWork = DeadlineCloseBudget::plus($openWork, DeadlineCloseBudget::TASK, $otherTasks->count()); + if ($budget->fits($openWork) + || ($openActivities->isEmpty() && $openTimers->isEmpty() && $otherTasks->isEmpty())) { // The terminal cascade (accepted updates, then children) gets - // what is left of this transaction's batch, at least one item. - $cascadeBudget = max(1, $batch - $openWork); + // what is left of this transaction's budget. With no open work + // left, the run closes even under a budget smaller than the close. + $budget->reserve($openWork); + $cascadeBudget = $budget; return false; } @@ -440,8 +434,14 @@ private function cancelOpenWorkBatchBeforeDeadlineClose( ])->save(); }; + // Every batch takes at least one item, so the close always finishes. + $budget->progressing() + ->reserve(DeadlineCloseBudget::PASS); + $full = false; foreach ($openActivities as $execution) { - if ($batch-- <= 0) { + if (! $budget->take($activityCost($execution))) { + $full = true; + break; } $activityTasks = $tasksByActivity->get($execution->id, collect()); @@ -452,8 +452,10 @@ private function cancelOpenWorkBatchBeforeDeadlineClose( ])->save(); ActivityCancellation::record($run, $execution, $activityTasks->last()); } - foreach ($openTimers as $timer) { - if ($batch-- <= 0) { + foreach ($full ? [] : $openTimers as $timer) { + if (! $budget->take(DeadlineCloseBudget::TIMER)) { + $full = true; + break; } $timer->forceFill([ @@ -461,8 +463,8 @@ private function cancelOpenWorkBatchBeforeDeadlineClose( ])->save(); TimerCancellation::record($run, $timer); } - foreach ($otherTasks as $openTask) { - if ($batch-- <= 0) { + foreach ($full ? [] : $otherTasks as $openTask) { + if (! $budget->take(DeadlineCloseBudget::TASK)) { break; } $cancelTask($openTask); @@ -5168,7 +5170,7 @@ private function timeoutRun( WorkflowRun $run, WorkflowTask $task, ?array $timeoutCleanup = null, - ?int $cascadeBudget = null, + ?DeadlineCloseBudget $cascadeBudget = null, ): void { $now = now(); @@ -5308,12 +5310,14 @@ private function timeoutRun( ] : []), ], $task); - // A bounded close (#1116) fails at most its remaining budget of - // accepted updates and acts on children only once none is left. - $updatesClosed = PendingUpdateCloser::closeForTerminalRun($run, $task, $cascadeBudget); - if ($cascadeBudget !== null) { - $cascadeBudget -= $updatesClosed; - } + // A bounded close (#1116) fails the accepted updates that fit what is + // left of its budget and acts on children only once none is left. + $updatesClosed = PendingUpdateCloser::closeForTerminalRun( + $run, + $task, + $cascadeBudget?->room(DeadlineCloseBudget::UPDATE), + ); + $cascadeBudget?->charge(DeadlineCloseBudget::UPDATE, $updatesClosed); $updatesLeft = $cascadeBudget !== null && PendingUpdateCloser::hasAccepted($run); // Mark current task completed. @@ -5336,11 +5340,7 @@ private function timeoutRun( // Apply parent-close policy to open children. $childrenSettled = true; if (! $updatesLeft) { - ParentClosePolicyEnforcer::enforce( - $run, - $cascadeBudget === null ? null : max(0, $cascadeBudget), - $childrenSettled - ); + ParentClosePolicyEnforcer::enforce($run, $cascadeBudget, $childrenSettled); } if ($updatesLeft || ! $childrenSettled) { // The run reads Failed; the watchdog continues the cascade from diff --git a/src/V2/TaskWatchdog.php b/src/V2/TaskWatchdog.php index be44d4674..0578be11c 100644 --- a/src/V2/TaskWatchdog.php +++ b/src/V2/TaskWatchdog.php @@ -730,12 +730,24 @@ private static function deadlineExpiredRunQuery( // expired, no longer hides it (#1116). Runs with pending // cancellation or timeout cleanup keep their own close and // are not selected for it, so they cannot fill the scan. + // A close that failed waits out its backoff (#1290). $ordinary->whereNull('cancellation_request_command_id') ->whereNull('timeout_cleanup_work_deadline_at') ->whereDoesntHave('tasks', static function ($task) use ($now): void { $task->where('task_type', TaskType::Workflow->value) - ->where('status', TaskStatus::Leased->value) - ->where('lease_expires_at', '>', $now); + ->where(static function ($deferred) use ($now): void { + $deferred->where(static function ($leased) use ($now): void { + $leased->where('status', TaskStatus::Leased->value) + ->where('lease_expires_at', '>', $now); + })->orWhere(static function ($backoff) use ($now): void { + $backoff->whereIn('status', [ + TaskStatus::Ready->value, + TaskStatus::Leased->value, + ]) + ->where('available_at', '>', $now) + ->whereNotNull('payload->' . DeadlineCloseSettlement::CLOSE_FAILURES); + }); + }); }); })->orWhere(static function ($cancellation) use ($now): void { $cancellation->whereNotNull('cancellation_request_command_id') @@ -825,7 +837,7 @@ private static function continueDeadlineCloseSettlement(string $runId, string $t if ($run === null || $task === null || ! DeadlineCloseSettlement::holds($task)) { return; } - DeadlineCloseSettlement::settle($run, $task, WorkflowExecutor::deadlineCloseBatchSize() ?? PHP_INT_MAX); + DeadlineCloseSettlement::settle($run, $task); self::historyProjectionRole()->projectRun( $run->fresh(['instance', 'tasks', 'activityExecutions', 'timers', 'failures', 'historyEvents']) ); @@ -876,14 +888,17 @@ private static function createDeadlineExpiredTask(string $runId): array { $cancellationEnforced = false; $acquiringTask = false; + $closingTaskId = null; try { $task = ConfiguredV2Models::connection()->transaction(static function () use ( $runId, &$cancellationEnforced, &$acquiringTask, + &$closingTaskId, ): ?WorkflowTask { $cancellationEnforced = false; + $closingTaskId = null; /** @var WorkflowRun|null $run */ $run = WorkflowRun::query() @@ -965,6 +980,7 @@ private static function createDeadlineExpiredTask(string $runId): array // needs no workflow code, so an unclaimed or abandoned // task must not hold it open (#1116). The close is // bounded: an oversized one cancels a batch per pass. + $closingTaskId = $existingWorkflowTask->id; $cancellationEnforced = app(WorkflowExecutor::class) ->closeExpiredDeadline($run, $existingWorkflowTask) !== WorkflowExecutor::DEADLINE_NOT_EXPIRED; @@ -1019,6 +1035,14 @@ private static function createDeadlineExpiredTask(string $runId): array ]; } report($throwable); + if (is_string($closingTaskId)) { + // The ordinary close failed and rolled back: back it off. + try { + DeadlineCloseSettlement::recordCloseFailure($closingTaskId, $throwable); + } catch (Throwable $recording) { + report($recording); + } + } return [ 'task' => null, diff --git a/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php b/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php index 88c5f4a55..7e7e9a389 100644 --- a/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php +++ b/tests/Feature/V2/V2EmbeddedReplayRegressionCorpusTest.php @@ -603,6 +603,98 @@ public function testLegacyDeadlineCloseCorpusClosesAnUnclaimedRun(): void ); } + /** + * A terminate-policy child's whole terminate is charged to the deadline + * close that runs it (#1290): under a 20-row limit the close records the + * parent's timeout alone and the settlement terminates the child, with + * the single close's history. + */ + public function testDeadlineCloseCorpusChargesAChildItsTerminate(): void + { + $path = self::FIXTURE_DIR . '/deadline-close-child-charged-its-terminate.json'; + if (! is_file($path)) { + $this->markTestSkipped('The deadline close child cascade evidence is absent from the baseline.'); + } + $fixture = json_decode((string) file_get_contents($path), true, flags: JSON_THROW_ON_ERROR); + $scenario = $fixture['deadline_close_child_cascade']; + config([ + 'queue.default' => 'database', + ]); + Queue::fake(); + $this->travelTo(now()->startOfSecond()); + $parent = WorkflowStub::make($fixture['workflow']['type'], $fixture['id']); + $parent->start(...[ + ...$fixture['workflow']['arguments'], + new StartOptions(executionTimeoutSeconds: $scenario['execution_timeout_seconds']), + ]); + $parentRunId = $parent->runId(); + $this->runReadyTaskOfType($parentRunId, TaskType::Workflow); + $childRunId = (string) WorkflowLink::query()->where('parent_workflow_run_id', $parentRunId) + ->where('link_type', 'child_workflow') + ->value('child_workflow_run_id'); + $this->runReadyTaskOfType($childRunId, TaskType::Workflow); + $this->travel($scenario['execution_timeout_seconds'] + 1)->seconds(); + config([ + 'workflows.v2.structural_limits.history_transaction_size' => 0, + 'workflows.v2.structural_limits.completion_rows' => $scenario['completion_rows'], + ]); + $history = static fn (string $runId): array => WorkflowHistoryEvent::query() + ->where('workflow_run_id', $runId) + ->where('event_type', '!=', HistoryEventType::StartAccepted->value) + ->orderBy('sequence') + ->pluck('event_type') + ->map(static fn (HistoryEventType $type): string => $type->value) + ->all(); + + // Which top-level transaction wrote each of the parent's close events. + $transaction = 0; + $writtenIn = []; + $recording = true; + Event::listen( + \Illuminate\Database\Events\TransactionBeginning::class, + static function ($began) use (&$transaction, &$recording): void { + if ($recording && $began->connection->transactionLevel() === 1) { + ++$transaction; + } + } + ); + DB::listen(static function (QueryExecuted $query) use (&$transaction, &$writtenIn, &$recording): void { + if (! $recording || ! str_contains(strtolower($query->sql), 'insert into') + || ! str_contains($query->sql, 'workflow_history_events')) { + return; + } + foreach (['WorkflowTimedOut', 'ParentClosePolicyApplied'] as $type) { + if (in_array($type, $query->bindings, true)) { + $writtenIn[$type] = $transaction; + } + } + }); + + // The watchdog closes the parent, first giving it a workflow task if + // it has none, and continues the held settlement. + try { + for ($passes = 0; $passes < 3 && count($writtenIn) < 2; ++$passes) { + TaskWatchdog::runPass(runIds: [$parentRunId]); + } + } finally { + $recording = false; + } + + $this->assertSame(RunStatus::Failed, WorkflowRun::query()->findOrFail($parentRunId)->status); + $this->assertSame($scenario['parent_history_after_settlement'], $history($parentRunId)); + // The close did not terminate the child: its terminate does not fit + // what the close leaves of the limit, so a settlement pass took it. + $this->assertCount(2, $writtenIn); + $this->assertGreaterThan($writtenIn['WorkflowTimedOut'], $writtenIn['ParentClosePolicyApplied']); + $this->assertSame(RunStatus::Terminated, WorkflowRun::query()->findOrFail($childRunId)->status); + $this->assertSame( + $scenario['child_terminal_event'], + $history($childRunId)[array_key_last($history($childRunId))] + ); + $this->assertSame(0, WorkflowTask::query()->where('workflow_run_id', $parentRunId) + ->whereIn('status', [TaskStatus::Ready->value, TaskStatus::Leased->value])->count()); + } + /** * An all() whose member is over payload_size_bytes is refused before its * first member is written (#1232): the run's history is exactly the diff --git a/tests/Fixtures/V2/ReplayRegression/deadline-close-child-charged-its-terminate.json b/tests/Fixtures/V2/ReplayRegression/deadline-close-child-charged-its-terminate.json new file mode 100644 index 000000000..162c9b129 --- /dev/null +++ b/tests/Fixtures/V2/ReplayRegression/deadline-close-child-charged-its-terminate.json @@ -0,0 +1,42 @@ +{ + "$schema": "https://raw.githubusercontent.com/durable-workflow/.github/main/regression-corpus/evidence-schema.json", + "fixture_schema": "durable-workflow.replay-regression/v1", + "id": "deadline-close-child-charged-its-terminate", + "protocol_version": "1.20", + "bindings": ["php"], + "consumers": ["workflow-fiber-runner"], + "workflow": { + "type": "Tests\\Fixtures\\V2\\TestParentWithClosePolicyWorkflow", + "arguments": ["terminate"], + "payload_codec": "avro" + }, + "history": [ + { + "sequence": 1, + "event_type": "WorkflowStarted", + "payload": {}, + "recorded_at": "2026-11-25T00:00:00.000000Z" + } + ], + "expected": { + "completed": false, + "result": null, + "commands": [ + {"type": "start_child_workflow"} + ] + }, + "deadline_close_child_cascade": { + "issue": "durable-workflow/workflow#1290", + "execution_timeout_seconds": 60, + "completion_rows": 20, + "parent_history_after_settlement": [ + "WorkflowStarted", + "ChildWorkflowScheduled", + "ChildRunStarted", + "WorkflowTimedOut", + "ParentClosePolicyApplied" + ], + "child_terminal_event": "WorkflowTerminated", + "note": "A parent with a terminate-policy child times out under a 20-row limit. The close writes 10 rows of its own; the child's terminate writes 19 more in the parent's transaction. Before #1290 the child counted as one item, so the close terminated it in its own transaction. Now the close leaves it to the settlement, whose first pass takes it alone in a later transaction. The parent's history is the single close's." + } +} diff --git a/tests/Unit/V2/CompletionWriteFamilyBudgetTest.php b/tests/Unit/V2/CompletionWriteFamilyBudgetTest.php index 80392aab0..89d782c13 100644 --- a/tests/Unit/V2/CompletionWriteFamilyBudgetTest.php +++ b/tests/Unit/V2/CompletionWriteFamilyBudgetTest.php @@ -32,11 +32,11 @@ use Workflow\V2\Models\WorkflowTimer; use Workflow\V2\Models\WorkflowUpdate; use Workflow\V2\Support\CompletionRowEstimate; +use Workflow\V2\Support\DeadlineCloseBudget; use Workflow\V2\Support\DeadlineCloseSettlement; use Workflow\V2\Support\HistoryTransactionMeter; use Workflow\V2\Support\MemoPayload; use Workflow\V2\Support\NamespaceScope; -use Workflow\V2\Support\WorkflowExecutor; use Workflow\V2\TaskWatchdog; /** @@ -438,16 +438,11 @@ public function testAnOversizedDeadlineCloseFinishesInBoundedBatchesWithTheSingl ->complete($single['task']->id, [$this->startTimer()]); $this->assertSame('run_timed_out', $singleResult['reason']); - // A batch of two open items per close transaction. + // Two open items per close transaction: a batch pass writes six rows + // of its own, a cancelled activity seven more and a timer six. config([ - 'workflows.v2.structural_limits.history_transaction_size' => 1, - 'workflows.v2.structural_limits.completion_rows' => 10, + 'workflows.v2.structural_limits.completion_rows' => 20, ]); - $this->assertSame(1, WorkflowExecutor::deadlineCloseBatchSize()); - config([ - 'workflows.v2.structural_limits.history_transaction_size' => 0, - ]); - $this->assertSame(2, WorkflowExecutor::deadlineCloseBatchSize()); $batched = $this->createExpiredRunWithOpenWork(activities: 3, timers: 4); $first = $this->bridge() @@ -474,7 +469,7 @@ public function testAnOversizedDeadlineCloseFinishesInBoundedBatchesWithTheSingl } // Seven open items, two per transaction: three more passes, the last - // of which closes the run. + // of which cancels the seventh with the close. $this->assertSame(3, $passes); $this->assertSame(RunStatus::Failed, $batched['run']->fresh()->status); $this->assertSame('timed_out', $batched['run']->fresh()->closed_reason); @@ -491,14 +486,18 @@ public function testAnOversizedDeadlineCloseFinishesInBoundedBatchesWithTheSingl /** * The terminal cascade of a bounded close is bounded too: accepted updates - * and then children are settled at most one batch per transaction, and - * the watchdog continues from the closing task's marker. The run's + * and then children are settled as far as one transaction's budget allows, + * and the watchdog continues from the closing task's marker. The run's * history equals a single close's. * - * 200 children and 300 updates over batches of 100 take five bounded - * transactions. (A thousand children work the same way, but each child's - * termination is a full command on that child, which makes a thousand of - * them, twice, take ten minutes on SQLite.) + * With a limit of 201 events, the close writes its WorkflowTimedOut and + * fails 100 updates, each with UpdateCompleted and MessageCursorAdvanced + * (#1290: the batch used to count one event per update and wrote about + * twice the limit). Each pass then fails 100 updates or terminates 67 + * children, each of which writes three events. (A thousand children work + * the same way, but each child's termination is a full command on that + * child, which makes a thousand of them, twice, take ten minutes on + * SQLite.) */ public function testABoundedCloseSettlesUpdatesAndChildrenAcrossPassesWithTheSingleCloseHistory(): void { @@ -518,20 +517,21 @@ public function testABoundedCloseSettlesUpdatesAndChildrenAcrossPassesWithTheSin $this->assertNull($single['task']->fresh()->payload['deadline_close_settlement'] ?? null); $batched = $this->createExpiredParent(children: 200, updates: 300); - // 100 items per close transaction. config([ - 'workflows.v2.structural_limits.completion_rows' => 500, + 'workflows.v2.structural_limits.history_transaction_size' => 201, ]); - $this->assertSame(100, WorkflowExecutor::deadlineCloseBatchSize()); - $closed = $this->bridge() - ->complete($batched['task']->id, [$this->startTimer()]); + $writes = $this->transactionWrites(function () use ($batched, &$closed): void { + $closed = $this->bridge() + ->complete($batched['task']->id, [$this->startTimer()]); + }); $this->assertSame('run_timed_out', $closed['reason']); $this->assertSame(RunStatus::Failed, $batched['run']->fresh()->status); // The close took the first 100 updates and left the rest. $this->assertSame(200, $this->acceptedUpdates($batched['run'])); $this->assertSame(200, $this->openChildren($batched['run'])); + $this->assertSame(201, max(array_column($writes, 'events'))); $this->assertSame('pending', $batched['task']->fresh()->payload['deadline_close_settlement'] ?? null); // The run already reads Failed while its closing task is held for // the settlement: Leased by the settlement owner, with no expiry. @@ -546,20 +546,23 @@ public function testABoundedCloseSettlesUpdatesAndChildrenAcrossPassesWithTheSin $this->assertTrue(DeadlineCloseSettlement::holds($batched['task']->fresh())); $passes = 0; + $settled = []; while (($batched['task']->fresh()->payload['deadline_close_settlement'] ?? null) === 'pending' && $passes < 20) { $updates = $this->acceptedUpdates($batched['run']); $children = $this->openChildren($batched['run']); - TaskWatchdog::runPass(runIds: [$batched['run']->id]); + $writes = $this->transactionWrites(static function () use ($batched): void { + TaskWatchdog::runPass(runIds: [$batched['run']->id]); + }); ++$passes; - // No pass settles more than one batch. - $this->assertLessThanOrEqual( - 100, - $updates - $this->acceptedUpdates($batched['run']) + $children - $this->openChildren($batched['run']) - ); + // No transaction writes more history than the limit. + $this->assertLessThanOrEqual(201, max(array_column($writes, 'events'))); + $settled[] = [ + $updates - $this->acceptedUpdates($batched['run']), + $children - $this->openChildren($batched['run']), + ]; } - // 200 updates and 200 children left, 100 per pass. - $this->assertSame(4, $passes); + $this->assertSame([[100, 0], [100, 0], [0, 67], [0, 67], [0, 66]], $settled); $this->assertSame('settled', $batched['task']->fresh()->payload['deadline_close_settlement']); $this->assertSame(TaskStatus::Completed, $batched['task']->fresh()->status); $this->assertSame(0, $this->openChildren($batched['run'])); @@ -625,7 +628,7 @@ public function testAStaleWorkerFailureLeavesTheSettlementHoldIntact(): void ->addMinute(), ]); } - // Ten items per close transaction. + // Seven timers per batch, the rest of the cascade over later passes. config([ 'workflows.v2.structural_limits.completion_rows' => 50, ]); @@ -660,7 +663,7 @@ public function testAStaleWorkerFailureLeavesTheSettlementHoldIntact(): void $this->assertStringContainsString('held for a deadline close settlement', $refused->getMessage()); } - for ($passes = 0; DeadlineCloseSettlement::holds($parent['task']->fresh()) && $passes < 10; ++$passes) { + for ($passes = 0; DeadlineCloseSettlement::holds($parent['task']->fresh()) && $passes < 20; ++$passes) { TaskWatchdog::runPass(runIds: [$parent['run']->id]); } $this->assertSame(TaskStatus::Completed, $parent['task']->fresh()->status); @@ -713,8 +716,9 @@ public function testAFailingSettlementPassBacksOffAndIsRetried(): void $parent['task']->forceFill([ 'namespace' => 'default', ])->save(); + // The close and each pass fail ten updates, eleven rows each. config([ - 'workflows.v2.structural_limits.completion_rows' => 50, + 'workflows.v2.structural_limits.completion_rows' => 120, ]); $this->assertSame( 'run_timed_out', @@ -781,6 +785,268 @@ static function () use (&$failing): void { ); } + /** + * @return iterable + */ + public static function deadlineCloseItems(): iterable + { + yield 'open activity' => ['activity', DeadlineCloseBudget::ACTIVITY]; + yield 'pending timer' => ['timer', DeadlineCloseBudget::TIMER]; + yield 'other open task' => ['task', DeadlineCloseBudget::TASK]; + yield 'accepted update' => ['update', DeadlineCloseBudget::UPDATE]; + yield 'terminated child' => ['terminate', DeadlineCloseBudget::CHILD]; + yield 'cancelled child' => ['request_cancel', DeadlineCloseBudget::CHILD]; + yield 'child asked to cancel' => ['request_cancellation', DeadlineCloseBudget::CANCELLATION_REQUEST]; + yield 'child with an open task' => [ + 'child task', + DeadlineCloseBudget::plus(DeadlineCloseBudget::CHILD, DeadlineCloseBudget::TASK), + ]; + yield 'child with an open activity' => [ + 'child activity', + DeadlineCloseBudget::plus(DeadlineCloseBudget::CHILD, DeadlineCloseBudget::ACTIVITY), + ]; + yield 'child with an accepted update' => [ + 'child update', + DeadlineCloseBudget::plus(DeadlineCloseBudget::CHILD, DeadlineCloseBudget::UPDATE), + ]; + yield 'child with a terminated child' => [ + 'grandchild', + DeadlineCloseBudget::plus(DeadlineCloseBudget::CHILD, DeadlineCloseBudget::CHILD), + ]; + } + + /** + * Workflow #1290: the bounded close charges each kind of work at least the + * history events and rows it writes, with its projections, both in the + * close and in a pass that takes it alone, so a statement added to any of + * them shows up here before it can push a close past its limits. + * + * @param array{int, int} $charged + */ + #[DataProvider('deadlineCloseItems')] + public function testEachDeadlineCloseItemIsChargedWhatItWrites(string $item, array $charged): void + { + Queue::fake(); + Carbon::setTestNow(now()->startOfSecond()); + + $without = $this->deadlineCloseWrites(null, alone: false); + $with = $this->deadlineCloseWrites($item, alone: false); + $alone = $this->deadlineCloseWrites($item, alone: true); + + $message = json_encode([ + 'close' => $without, + 'close with the item' => $with, + 'pass with the item alone' => $alone, + ], JSON_THROW_ON_ERROR); + foreach ([0, 1] as $dimension) { + $this->assertLessThanOrEqual(DeadlineCloseBudget::CLOSE[$dimension], $without[$dimension], $message); + $this->assertLessThanOrEqual($charged[$dimension], $with[$dimension] - $without[$dimension], $message); + $this->assertLessThanOrEqual( + DeadlineCloseBudget::PASS[$dimension] + $charged[$dimension], + $alone[$dimension], + $message, + ); + } + // The charge is what the item writes, not a blanket allowance. + $this->assertGreaterThanOrEqual($charged[1] - 1, $with[1] - $without[1], $message); + } + + /** + * @return iterable + */ + public static function deadlineCloseLimits(): iterable + { + yield 'event limit' => [12, 0]; + yield 'row limit' => [0, 70]; + yield 'both limits' => [12, 70]; + } + + /** + * No transaction of a bounded close writes more history events or rows + * than the limits, whatever mix of open work, accepted updates and + * children it settles (#1290), and the batched close writes the single + * close's history. + */ + #[DataProvider('deadlineCloseLimits')] + public function testEveryTransactionOfABoundedCloseStaysWithinTheLimits(int $events, int $rows): void + { + Queue::fake(); + Carbon::setTestNow(now()->startOfSecond()); + config([ + 'workflows.v2.structural_limits.history_transaction_size' => 0, + 'workflows.v2.structural_limits.completion_rows' => 0, + ]); + $single = $this->createMixedExpiredParent(); + $this->assertSame( + 'run_timed_out', + $this->bridge() + ->complete($single['task']->id, [$this->startTimer()])['reason'] + ); + + $batched = $this->createMixedExpiredParent(); + config([ + 'workflows.v2.structural_limits.history_transaction_size' => $events, + 'workflows.v2.structural_limits.completion_rows' => $rows, + ]); + $transactions = $this->transactionWrites(function () use ($batched): void { + $this->bridge() + ->complete($batched['task']->id, [$this->startTimer()]); + for ($passes = 0; $passes < 40 && ($batched['run']->fresh()->status === RunStatus::Waiting + || DeadlineCloseSettlement::holds($batched['task']->fresh())); ++$passes) { + TaskWatchdog::runPass(runIds: [$batched['run']->id]); + } + }); + + $this->assertSame(TaskStatus::Completed, $batched['task']->fresh()->status); + // The abandoned child and the one asked to cancel stay open. + $this->assertSame(2, $this->openChildren($single['run'])); + $this->assertSame(2, $this->openChildren($batched['run'])); + $this->assertSame(0, $this->acceptedUpdates($batched['run'])); + $this->assertSame($this->closeHistory($single['run']), $this->closeHistory($batched['run'])); + $this->assertGreaterThan(5, count($transactions)); + foreach ($transactions as $transaction) { + if ($events > 0) { + $this->assertLessThanOrEqual($events, $transaction['events']); + } + if ($rows > 0) { + $this->assertLessThanOrEqual($rows, $transaction['rows']); + } + } + } + + /** + * Workflow #1290: a child's termination runs that child's whole close in + * the parent's transaction, so it is charged that close, not one item. A + * child with five open activities writes 8 events and 54 rows: two fit + * the 110 rows the close leaves of a 120-row limit, and two more fit the + * next pass. Counted as one item each, all four landed in the close. + */ + public function testAChildIsChargedItsWholeTerminate(): void + { + Queue::fake(); + Carbon::setTestNow(now()->startOfSecond()); + config([ + 'workflows.v2.structural_limits.history_transaction_size' => 0, + 'workflows.v2.structural_limits.completion_rows' => 0, + ]); + $parent = $this->createExpiredParent(children: 4, updates: 0); + $runs = [$parent['run']]; + foreach (WorkflowLink::query()->where('parent_workflow_run_id', $parent['run']->id)->get() as $link) { + $runs[] = $child = WorkflowRun::query()->findOrFail($link->child_workflow_run_id); + $this->seedOpenWork($child, activities: 5, timers: 0); + } + $this->projectRuns($runs); + config([ + 'workflows.v2.structural_limits.completion_rows' => 120, + ]); + + $close = $this->transactionWrites(function () use ($parent): void { + $this->assertSame( + 'run_timed_out', + $this->bridge() + ->complete($parent['task']->id, [$this->startTimer()])['reason'] + ); + }); + + $this->assertSame(2, $this->openChildren($parent['run'])); + $this->assertTrue(DeadlineCloseSettlement::holds($parent['task']->fresh())); + $this->assertLessThanOrEqual(120, max(array_column($close, 'rows'))); + + $pass = $this->transactionWrites(static function () use ($parent): void { + TaskWatchdog::runPass(runIds: [$parent['run']->id]); + }); + + $this->assertSame(0, $this->openChildren($parent['run'])); + $this->assertSame(TaskStatus::Completed, $parent['task']->fresh()->status); + $this->assertLessThanOrEqual(120, max(array_column($pass, 'rows'))); + $this->assertSame( + 0, + ActivityExecution::query() + ->whereIn('status', [ActivityStatus::Pending->value, ActivityStatus::Running->value]) + ->count(), + ); + } + + /** + * Workflow #1290: an ordinary deadline close that fails rolls back, then + * records its error, one more attempt and the settlement's backoff on the + * run's workflow task. The run is skipped until due, so closes that keep + * failing no longer fill the oldest-deadline scan and starve the rest, + * and it is retried until it closes. + */ + public function testAFailingOrdinaryCloseBacksOffAndCannotStarveOtherCloses(): void + { + Carbon::setTestNow(now()->startOfSecond()); + config([ + 'workflows.v2.task_repair.scan_limit' => 3, + ]); + $failing = []; + $tasks = []; + foreach (range(1, 3) as $index) { + $run = $this->createWaitingRun(); + $run->forceFill([ + 'execution_deadline_at' => now() + ->subHours(2), + ])->save(); + $failing[] = $run->id; + $tasks[] = $this->createTask($run, TaskStatus::Ready); + } + $healthy = $this->createWaitingRun(); + $healthy->forceFill([ + 'execution_deadline_at' => now() + ->subMinute(), + ])->save(); + $this->createTask($healthy, TaskStatus::Ready); + $broken = true; + \Illuminate\Support\Facades\Event::listen( + 'eloquent.creating: ' . \Workflow\V2\Models\WorkflowFailure::class, + static function ($failure) use (&$broken, $failing): void { + if ($broken && in_array($failure->workflow_run_id, $failing, true)) { + throw new \RuntimeException('forced close failure'); + } + } + ); + + $first = TaskWatchdog::runPass(); + + $this->assertSame(3, $first['deadline_expired_candidates']); + $this->assertCount(3, $first['deadline_expired_failures']); + $this->assertSame(RunStatus::Waiting, $healthy->fresh()->status); + foreach ($tasks as $task) { + $task = $task->fresh(); + $this->assertSame(TaskStatus::Ready, $task->status); + $this->assertSame('forced close failure', $task->last_error); + $this->assertSame(1, $task->attempt_count); + $this->assertSame(1, DeadlineCloseSettlement::closeFailures($task)); + $this->assertSame(now()->addSeconds(10)->toJSON(), $task->available_at->toJSON()); + } + + // The failing runs wait out their backoff; the next pass closes the + // healthy run behind them. + $second = TaskWatchdog::runPass(); + + $this->assertSame(1, $second['deadline_expired_candidates']); + $this->assertSame(RunStatus::Failed, $healthy->fresh()->status); + $this->assertSame(1, DeadlineCloseSettlement::closeFailures($tasks[0]->fresh())); + + // Due again and still failing: the backoff doubles. + Carbon::setTestNow(now()->addSeconds(11)); + TaskWatchdog::runPass(); + $this->assertSame(2, DeadlineCloseSettlement::closeFailures($tasks[0]->fresh())); + $this->assertSame(2, $tasks[0]->fresh()->attempt_count); + $this->assertSame(now()->addSeconds(20)->toJSON(), $tasks[0]->fresh()->available_at->toJSON()); + + // Once due and healthy, the retry closes every run. + $broken = false; + Carbon::setTestNow(now()->addSeconds(21)); + TaskWatchdog::runPass(); + + foreach ($failing as $index => $runId) { + $this->assertSame(RunStatus::Failed, WorkflowRun::query()->findOrFail($runId)->status); + $this->assertSame(TaskStatus::Completed, $tasks[$index]->fresh()->status); + } + } + public function testADeleteOfAKeyWrittenEarlierInTheCompletionCountsItsRow(): void { $run = $this->createWaitingRun(); @@ -801,6 +1067,208 @@ public function testADeleteOfAKeyWrittenEarlierInTheCompletionCountsItsRow(): vo ); } + /** + * The history events and rows each top-level transaction (or statement + * outside one) writes while $work runs, read from the statements + * themselves. Writes to Laravel's cache tables are not workflow storage: + * long-poll wake signals land there only when the application uses the + * database cache store on the same connection. + * + * @return list + */ + private function transactionWrites(callable $work): array + { + $writes = []; + $index = -1; + $recording = true; + \Illuminate\Support\Facades\Event::listen( + \Illuminate\Database\Events\TransactionBeginning::class, + static function ($began) use (&$writes, &$index, &$recording): void { + if ($recording && $began->connection->transactionLevel() === 1) { + $writes[++$index] = [ + 'events' => 0, + 'rows' => 0, + ]; + } + } + ); + DB::listen(static function ($query) use (&$writes, &$index, &$recording): void { + $rows = $recording ? HistoryTransactionMeter::statementRows($query->sql) : 0; + if ($rows === 0 || preg_match( + '/^\s*(insert\s+into|update|delete\s+from)\s+[`"]?\w*cache(_locks)?[`"]?\s/i', + $query->sql, + ) === 1) { + return; + } + if ($query->connection->transactionLevel() === 0) { + $writes[++$index] = [ + 'events' => 0, + 'rows' => 0, + ]; + } + $writes[$index]['rows'] += $rows; + if (preg_match('/^\s*insert\s+into\s+[`"]?\w*workflow_history_events[`"]?\s/i', $query->sql) === 1) { + $writes[$index]['events'] += $rows; + } + }); + try { + $work(); + } finally { + $recording = false; + } + + return array_values(array_filter( + $writes, + static fn (array $transaction): bool => $transaction['rows'] > 0, + )); + } + + /** + * The events and rows of a deadline close of a projected run with one + * item of a kind, or none: the unbounded close's transaction, or with + * $alone the pass that takes the item alone under a one-row limit. + * + * @return array{int, int} + */ + private function deadlineCloseWrites(?string $item, bool $alone): array + { + config([ + 'workflows.v2.structural_limits.history_transaction_size' => 0, + 'workflows.v2.structural_limits.completion_rows' => 0, + ]); + $run = $this->createWaitingRun(); + $run->forceFill([ + 'execution_deadline_at' => now() + ->subMinute(), + ])->save(); + $runs = [$run]; + match ($item) { + null => null, + 'activity' => $this->seedOpenWork($run, activities: 1, timers: 0), + 'timer' => $this->seedOpenWork($run, activities: 0, timers: 1), + 'task' => $this->createTask($run, TaskStatus::Ready) + ->forceFill([ + 'task_type' => TaskType::Activity->value, + ])->save(), + 'update' => $this->acceptUpdate($run, 1), + 'terminate', 'request_cancel', 'request_cancellation' => $this->linkOpenChild($run, 1, $item), + default => $this->linkOpenChild($run, 1, 'terminate'), + }; + $childId = WorkflowLink::query()->where('parent_workflow_run_id', $run->id)->value('child_workflow_run_id'); + if (is_string($childId)) { + $child = WorkflowRun::query()->findOrFail($childId); + $runs[] = $child; + match ($item) { + 'child task' => $this->createTask($child, TaskStatus::Ready), + 'child activity' => $this->seedOpenWork($child, activities: 1, timers: 0), + 'child update' => $this->acceptUpdate($child, 1), + 'grandchild' => $this->linkOpenChild($child, 1, 'terminate'), + default => null, + }; + $grandchildId = WorkflowLink::query()->where('parent_workflow_run_id', $child->id) + ->value('child_workflow_run_id'); + if (is_string($grandchildId)) { + $runs[] = WorkflowRun::query()->findOrFail($grandchildId); + } + } + $task = $this->createLeasedTask($run->refresh()); + $this->projectRuns($runs); + if ($alone) { + config([ + 'workflows.v2.structural_limits.completion_rows' => 1, + ]); + } + + $writes = $this->transactionWrites(function () use ($task, &$result): void { + $result = $this->bridge() + ->complete($task->id, [$this->startTimer()]); + }); + if ($alone && in_array($item, ['activity', 'timer', 'task'], true)) { + // The first batch takes the open item alone. + $this->assertSame('run_deadline_closing', $result['reason']); + } elseif ($alone) { + // Nothing of the cascade fits the close; the first settlement + // pass takes the item alone. + $this->assertSame('run_timed_out', $result['reason']); + $this->assertTrue(DeadlineCloseSettlement::holds($task->fresh())); + $writes = $this->transactionWrites(static function () use ($run): void { + TaskWatchdog::runPass(runIds: [$run->id]); + }); + $this->assertSame(TaskStatus::Completed, $task->fresh()->status); + } else { + $this->assertSame('run_timed_out', $result['reason']); + } + $largest = collect($writes) + ->sortByDesc('rows') + ->first(); + + return [$largest['events'], $largest['rows']]; + } + + /** + * Project runs as their last workflow task would have, so a close + * updates existing projections instead of creating them all. + * + * @param list $runs + */ + private function projectRuns(array $runs): void + { + $projections = $this->app->make(\Workflow\V2\Contracts\HistoryProjectionRole::class); + foreach ($runs as $run) { + $projections->projectRun( + $run->fresh(['instance', 'tasks', 'activityExecutions', 'timers', 'failures', 'historyEvents']) + ); + } + } + + /** + * An expired parent with every kind of close work: open activities, + * timers and another task, accepted updates, and children closed by + * terminate and request_cancel with their own open work, updates and + * children, a child asked to cancel, and an abandoned child. + * + * @return array{run: WorkflowRun, task: WorkflowTask} + */ + private function createMixedExpiredParent(): array + { + $parent = $this->createExpiredParent(children: 0, updates: 7); + $run = $parent['run']; + $this->seedOpenWork($run, activities: 6, timers: 4); + $this->createTask($run, TaskStatus::Ready) + ->forceFill([ + 'task_type' => TaskType::Activity->value, + ])->save(); + foreach ([ + 'terminate', + 'request_cancel', + 'terminate', + 'request_cancellation', + 'abandon', + 'terminate', + ] as $sequence => $policy) { + $this->linkOpenChild($run, 100 + $sequence, $policy); + } + $children = WorkflowLink::query() + ->where('parent_workflow_run_id', $run->id) + ->orderBy('sequence') + ->get() + ->map(static fn (WorkflowLink $link): WorkflowRun => WorkflowRun::query()->findOrFail( + $link->child_workflow_run_id + )) + ->all(); + $this->seedOpenWork($children[0], activities: 2, timers: 1); + $this->acceptUpdate($children[1], 1); + $this->acceptUpdate($children[1], 2); + $this->linkOpenChild($children[2], 1, 'terminate'); + $this->createTask($children[5], TaskStatus::Ready); + $this->projectRuns([$run, ...$children]); + + return [ + 'run' => $run->refresh(), + 'task' => $parent['task'], + ]; + } + /** * @return array{run_ids: list, queries: list}>, rows: list} */ diff --git a/tests/Unit/V2/IdempotentProjectionUpsertTest.php b/tests/Unit/V2/IdempotentProjectionUpsertTest.php index 4a2301a86..647d870b0 100644 --- a/tests/Unit/V2/IdempotentProjectionUpsertTest.php +++ b/tests/Unit/V2/IdempotentProjectionUpsertTest.php @@ -141,6 +141,65 @@ public function testPrefetchedRowRetainsModelHooksWithoutAnotherSelect(): void str_starts_with(strtolower($query['query']), 'select'))); } + /** + * MySQL stores JSON with its object keys reordered. A projected payload + * that differs from the stored one only in key order is not written again + * (#1290); a real change, including a reordered list, still is. + */ + public function testPrefetchedRowKeepsAPayloadThatDiffersOnlyInKeyOrder(): void + { + $run = $this->seedRun(); + $id = hash('sha256', $run->id . '|reordered'); + $payload = [ + 'status' => 'waiting', + 'nested' => [ + 'zeta' => 1, + 'alpha' => [3, 1, 2], + ], + 'id' => 'one', + ]; + IdempotentProjectionUpsert::upsert(WorkflowTimelineEntry::class, [ + 'id' => $id, + ], [ + ...$this->timelineAttributes($run, 'reordered', 'summary'), + 'payload' => $payload, + ]); + // What MySQL hands back for the stored payload. + WorkflowTimelineEntry::query()->whereKey($id)->toBase()->update([ + 'payload' => '{"id": "one", "nested": {"zeta": 1, "alpha": [3, 1, 2]}, "status": "waiting"}', + ]); + $connection = (new WorkflowTimelineEntry())->getConnection(); + $connection->flushQueryLog(); + $connection->enableQueryLog(); + + try { + IdempotentProjectionUpsert::upsert(WorkflowTimelineEntry::class, [ + 'id' => $id, + ], [ + 'payload' => $payload, + ], WorkflowTimelineEntry::query()->findOrFail($id)); + $unchanged = $connection->getQueryLog(); + $connection->flushQueryLog(); + $payload['nested']['alpha'] = [1, 2, 3]; + IdempotentProjectionUpsert::upsert(WorkflowTimelineEntry::class, [ + 'id' => $id, + ], [ + 'payload' => $payload, + ], WorkflowTimelineEntry::query()->findOrFail($id)); + $changed = $connection->getQueryLog(); + } finally { + $connection->disableQueryLog(); + } + + $writes = static fn (array $queries): array => array_values(array_filter( + $queries, + static fn (array $query): bool => str_starts_with(strtolower($query['query']), 'update'), + )); + $this->assertSame([], $writes($unchanged)); + $this->assertCount(1, $writes($changed)); + $this->assertSame([1, 2, 3], WorkflowTimelineEntry::query()->findOrFail($id)->payload['nested']['alpha']); + } + public function testRejectsPrefetchedRowWithDifferentIdentity(): void { $run = $this->seedRun();