diff --git a/docs/polyglot/php.md b/docs/polyglot/php.md index d607359d11b..c341f675214 100644 --- a/docs/polyglot/php.md +++ b/docs/polyglot/php.md @@ -324,6 +324,26 @@ same parser as the embedded package. The [PHP SDK duration reference](https://php.durable-workflow.com/build/workflows-activities/#durations) lists every unit. +## Replay-safe workflow time {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` returns replay-safe UTC business time as a +`DateTimeImmutable`. At ordinary entry it is the run's start (for a redrive successor, the original run's start) from the task's +`replay_clock` (Server 3.6.0 and later). After each supported consumed durable +step (activities, timers, child workflows, condition waits, validated groups) +it is that step's recorded time. Repeated reads between durable steps return +the same value, and every replay returns the same values. + +Where the SDK cannot prove the time, it throws +`DurableWorkflow\Exception\ReplayClockUnavailable`. That includes side effects, +version markers and local activities, which stay unavailable until Core defines +a persisted time for them. A clock read right after such a step is not portable +across runners or mixed fleets; see +[Clock reads after inline steps are not portable](./python.md#inline-step-clock-reads). +Query and update handlers read history snapshots and never rebuild the workflow +body. See the +[cross-SDK clock semantics](./python.md#advancing-replay-clock) for the full +list, release status and the upgrade note. + ## Entry compatibility and recovery {#entry-compatibility-and-recovery} **Released support.** PHP SDK 2.5.4 introduced the entry safeguard below, with routing and recovery support in Server 2.9.9. These are minimum feature versions; install current stable releases for security fixes. diff --git a/docs/polyglot/polling-patterns.md b/docs/polyglot/polling-patterns.md index 3663720d460..1b050970976 100644 --- a/docs/polyglot/polling-patterns.md +++ b/docs/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ Register `PollDemo` and `check_status` in the same [Python worker](./python.md), The two examples were exercised on published Server **2.9.7 / Core 2.7.2**, with normally installed Python **2.6.1** and test input `[2, 1]`. Both completed two real checks across two runs. Continue-as-new resets run history, adds run/link overhead and preserves the original execution deadline. It does not provide an unlimited lifetime. -Use relative durable waits here. Python's advancing clock and replay-stable history-budget reads remain separate [clock](https://github.com/durable-workflow/.github/issues/215) and [budget](https://github.com/durable-workflow/workflow/issues/859) work. This recipe does not branch on `ctx.now()` or recomputed history length. Do not treat `DW_MAX_HISTORY_EVENTS` as an enforced automatic rollover: [Server #504](https://github.com/durable-workflow/server/issues/504) tracks that gap. +Use relative durable waits here. `ctx.replay_now()` (Python SDK 2.15.0+) advances with consumed durable steps, and from Python SDK 2.24.0 it also has a value at entry (see [Advancing replay clock](./python.md#advancing-replay-clock)); replay-stable history-budget reads remain separate [budget](https://github.com/durable-workflow/workflow/issues/859) work. This recipe does not branch on `ctx.now()` or recomputed history length. Do not treat `DW_MAX_HISTORY_EVENTS` as an enforced automatic rollover: [Server #504](https://github.com/durable-workflow/server/issues/504) tracks that gap. ## Interrupt and reconcile {#interrupt-and-reconcile} diff --git a/docs/polyglot/python.md b/docs/polyglot/python.md index 50b6a9ff1fe..85efd843329 100644 --- a/docs/polyglot/python.md +++ b/docs/polyglot/python.md @@ -851,6 +851,7 @@ The `WorkflowContext` passed to `run` provides deterministic operations: | `ctx.upsert_search_attributes(attrs)` | Update search attributes | | `ctx.continue_as_new(*args)` | Restart the workflow with new input | | `ctx.now()` | Persisted workflow-start time, fixed for this run | +| `ctx.replay_now()` | Advancing replay-safe UTC time: the run's start at entry, then each consumed durable step's recorded time | | `ctx.random()` | Seeded random generator | | `ctx.uuid4()` | Deterministic UUID | | `ctx.logger` | Logger that is silent during replay | @@ -921,6 +922,100 @@ UTC timestamps with monotonic values, or subtract monotonic readings from different processes or hosts. `ctx.now()` subtraction measures neither active processing time nor elapsed wall time in Python. +#### Advancing replay clock {#advancing-replay-clock} + +`ctx.replay_now()` is an additive UTC clock that moves with consumed history. +The Rust (`WorkflowContext::replay_now()`) and PHP service-mode +(`WorkflowContext::replayNow()`) SDKs provide the same clock. + +- At ordinary workflow entry, before any durable step, it returns the run's canonical start (for a redrive successor, the original run's start). Server 3.6.0 and later sends that instant on each workflow + task as `replay_clock`. History insertion, dispatch and lease times are never + used instead. +- After a supported durable step it returns that step's recorded time: + activities, timers and child workflows in every SDK, signal and condition + waits where the SDK supports them, and validated groups. +- Repeated reads between durable steps return the same value, and every replay of the run returns the same values. The clock is not guaranteed to be monotonic: a later proved boundary can carry an earlier recorded time. + +A deadline loop around a durable timer therefore terminates, and the +difference between reads after two durable steps measures their recorded +elapsed time: + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +Where the SDK cannot prove the time, `ctx.replay_now()` raises +`ReplayClockUnavailable` rather than using any other time: + +- at entry on a task without the carrier: Servers before 3.6.0, or a run whose + start Server cannot prove; +- after inline and local operations, such as side effects, version markers, + memo and search-attribute updates, and local activities. These stay + unavailable until Core defines a persisted time for those steps; +- after other group modes and in cancellation scopes; +- in query handlers: always in PHP, and in Python and Rust unless the queried history ends at a supported scalar boundary (grouped boundaries give no query time). + +An unhandled `ReplayClockUnavailable` fails the workflow like any other +exception. + +##### Clock reads after inline steps are not portable {#inline-step-clock-reads} + +Inline steps are side effects, version markers, memo and search-attribute +updates, and local activities. Until Core defines a persisted time for them, a +clock read immediately after one is not portable across runners or mixed +fleets: + +- The service-mode SDKs (Python, Rust and the PHP SDK) report the clock as + unavailable there. +- On the embedded engine, `Workflow::now()` moves to the step's recorded time. +- On the external-worker runner (the embedded package's worker-protocol + `WorkflowFiberRunner`, which external PHP workers use through the bridge), + side effects, memo and search-attribute updates, and version markers behave + alike: a first execution keeps the previous boundary time, while a replay + reads the step's recorded time. For version markers this divergence is kept + deliberately: superseding the pinned `repeated-version-legacy-clock-boundaries` + replay fixture would change the replay output of runs already in flight. +- The read therefore differs whenever the first execution ran on the + external-worker runner, including in a fleet of only external workers, and + whenever a run may move between runners, because embedded and external first + executions read different times. + +Do not rely on a clock read immediately after an inline step: read the clock +after the next durable step. + +Python and Rust rebuild the workflow from history to answer a query or a +pre-accept update validation. If the rebuilt workflow reads the clock at entry +and the task has no `replay_clock`, which Servers before 3.30.0 never send +on those tasks, the query or validation fails rather than +answering with state the workflow task never computed. The PHP SDK never +rebuilds the workflow body for queries or updates. + +Offline replay (`replay()`, `Replayer.replay()`, `replay_history()`) takes the task's object as `replay_clock_entry`. The in-memory `WorkflowEnvironment` supplies no carrier, so entry reads there are unavailable. + +**Release status.** The entry value (all three SDKs) and the query and validation rule (Python and Rust) ship in Python SDK 2.24.0, Rust SDK 4.25.0 and PHP SDK 3.32.0 and need Server 3.6.0 or later. The +carrier on query and validation tasks ships in Server 3.30.0. The embedded +package's worker-protocol runner (`WorkflowFiberRunner`) accepts the carrier +from Workflow 2.42.0: once the code that builds the runner passes it, +`Workflow::now()` at entry returns the run's canonical start. +Earlier SDK releases report entry as unavailable. + +**Upgrading.** A running workflow whose code branches on the entry read being +unavailable, for example by catching `ReplayClockUnavailable`, takes the other branch on replay after the upgrade, during a rolling deploy that mixes old and new workers, or after a Server upgrade to 3.6.0. Put such code behind `ctx.get_version(...)` +or drain those runs first. `ctx.now()` keeps its fixed start time, so runs that +read it replay unchanged. + #### Clock differences across SDKs These APIs are deterministic where provided, but they do not share one clock: @@ -928,16 +1023,17 @@ These APIs are deterministic where provided, but they do not share one clock: | Authoring surface | Repeated calls and durable steps | Continue-as-new successor | | --- | --- | --- | | Python `ctx.now()` | Fixed to this run's persisted start time, including after a timer or activity. | Uses the successor run's start anchor. | +| Python `ctx.replay_now()` | Starts at the run's start and advances to each supported consumed step's recorded time. See [Advancing replay clock](#advancing-replay-clock). | Starts at the successor run's own start. | | Embedded PHP `Workflow::now()` | Starts at the run's start time and advances to the recorded event time consumed by replay. See [workflow time](../features/timers.md#reading-deterministic-time). | Starts with the new run, then advances through that run's consumed events. | -| PHP service-mode SDK | No general public workflow `now()` helper. Use durable operations or recorded activity/side-effect values. | Pass application timing state explicitly when it must survive the handoff. | -| Rust service-mode SDK | No general public `WorkflowContext::now()` helper. A `side_effect` can record a small wall-clock snapshot; it is not an advancing clock. | A side effect in the new run is a new operation; pass earlier timing state explicitly if needed. | +| PHP service-mode `WorkflowContext::replayNow()` | Same semantics as Python `ctx.replay_now()`. | Starts at the successor run's own start. | +| Rust service-mode `WorkflowContext::replay_now()` | Same semantics as Python `ctx.replay_now()`. | Starts at the successor run's own start. | -The embedded PHP behavior is present in -[published Core](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php); -the separate [PHP SDK context](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -and [Rust SDK context](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -have their own APIs. Port the durable operation and deadline policy rather than -assuming that a clock helper has identical semantics in every SDK. +The service-mode clocks share one contract. Embedded `Workflow::now()` also moves to the recorded time of an inline step such as a +side effect, where the service-mode clocks report the time as unavailable, so +such a read is not portable (see +[Clock reads after inline steps are not portable](#inline-step-clock-reads)). Port +the durable operation and deadline policy rather than assuming that every clock +helper behaves identically. #### Order emitted events with sequence values @@ -949,6 +1045,8 @@ workflow-local counter. Pair a run-local counter with `run_id`; carry it through continue-as-new explicitly if the application needs one logical sequence. Independent streams or runs do not gain a global order from their timestamps. +Repeated `ctx.replay_now()` reads between durable steps also return one value, so do not use it to order events either. + ### Activity Retries and Timeouts Use `ActivityRetryPolicy` and timeout keyword arguments on `ctx.schedule_activity(...)` diff --git a/docs/polyglot/rust.md b/docs/polyglot/rust.md index cf6fcb19cbd..b5f0956b1a3 100644 --- a/docs/polyglot/rust.md +++ b/docs/polyglot/rust.md @@ -893,6 +893,25 @@ Keep durable command order independent of this observation state and log deliver See the [published logging guide](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging), [WorkflowLogger API](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html) and [WorkflowReplayState API](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html). [Registry lifecycle/deadline controls](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853) and [four-process logging acceptance](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262) were recorded on the named native Server 3.10.0 linux/amd64 tuple. Other bindings and broader replay/producer qualification retain their own scope. +## Replay-safe workflow time {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` returns replay-safe UTC business time as +`Result>`. At ordinary entry it is the run's start (for a redrive successor, the original run's start) from the task's `replay_clock` (Server 3.6.0 and later). After each supported consumed +durable step (activities, timers, child workflows, signal and condition waits, +validated groups) it is that step's recorded time. Repeated reads between +durable steps return the same value, and every replay returns the same values. + +Where the SDK cannot prove the time, it returns `Error::ReplayClockUnavailable`. +That includes inline and local operations (side effects, version markers, local +activities, memos), which stay unavailable until Core defines a persisted time +for them. A clock read right after such a step is not portable across runners or +mixed fleets; see +[Clock reads after inline steps are not portable](./python.md#inline-step-clock-reads). +Offline replay supplies a carrier with +`WorkflowHistory::replay_clock(carrier)`. See the +[cross-SDK clock semantics](./python.md#advancing-replay-clock) for the full +list, the query and validation rule, release status and the upgrade note. + ## Rust determinism rules {#rust-determinism-rules} A replay must produce the same durable commands in the same order for the recorded input and history. Rust's ordinary collections, clocks and concurrency primitives do not automatically preserve that contract: @@ -900,7 +919,7 @@ A replay must produce the same durable commands in the same order for the record | Pattern in workflow code | Durable replacement | | --- | --- | | Scheduling while iterating a `HashMap` | Sort keys first or use a `BTreeMap`. | -| System-clock reads, `thread_rng` or a new UUID | Record a snapshot with `ctx.side_effect(...)`, or use an activity. | +| System-clock reads, `thread_rng` or a new UUID | `ctx.replay_now()` for business time; record other values with `ctx.side_effect(...)`, or use an activity. | | `tokio::time::sleep` or `std::thread::sleep` | `ctx.sleep(...)` or `ctx.start_timer(...)`. | | `tokio::select!` or racing ordinary futures | `ctx.select(...)` or `ctx.select_keyed(...)`. | | Untracked concurrent durable calls | `ctx.parallel(...)` with stable input ordering. | diff --git a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md index a8de63d3eea..4df7061c25a 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -332,6 +332,28 @@ im eingebetteten Paket umgerechnet werden. Die [Dauerreferenz des PHP SDK](https://php.durable-workflow.com/build/workflows-activities/#durations) listet alle Einheiten auf. +## Replay-sichere Workflow-Zeit {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` liefert replay-sichere UTC-Geschäftszeit als +`DateTimeImmutable`. Beim normalen Einstieg ist es der Start des Runs (bei einem Redrive-Nachfolger der Start des ursprünglichen Runs) aus dem +`replay_clock` der Aufgabe (Server 3.6.0 und neuer). Nach jedem unterstützten +verarbeiteten dauerhaften Schritt (Aktivitäten, Timer, Child-Workflows, +Bedingungswartevorgänge, validierte Gruppen) ist es dessen aufgezeichnete Zeit. +Wiederholte Lesevorgänge zwischen dauerhaften Schritten liefern denselben Wert, +und jedes Replay liefert dieselben Werte. + +Wo das SDK die Zeit nicht nachweisen kann, wirft es +`DurableWorkflow\Exception\ReplayClockUnavailable`. Das umfasst Seiteneffekte, +Versionsmarker und lokale Aktivitäten, die nicht verfügbar bleiben, bis Core +für sie eine gespeicherte Zeit festlegt. Eine Uhrlesung direkt nach einem +solchen Schritt ist weder zwischen Runnern noch in gemischten Flotten portabel; +siehe +[Uhrlesungen nach Inline-Schritten sind nicht portabel](./python.md#inline-step-clock-reads). +Query- und Update-Handler lesen +Historien-Snapshots und bauen den Workflow-Körper nie neu auf. Die vollständige +Liste, den Release-Status und den Upgrade-Hinweis finden Sie in der +[SDK-übergreifenden Uhrsemantik](./python.md#advancing-replay-clock). + ## Kompatibilität am Einstieg und Wiederherstellung {#entry-compatibility-and-recovery} **Veröffentlichte Unterstützung.** PHP SDK 2.5.4 hat den nachfolgenden Einstiegsschutz eingeführt, ergänzt durch Routing und Wiederherstellung in Server 2.9.9. Dies sind die Mindestversionen für diese Funktionen. Installieren Sie aktuelle stabile Versionen, um Sicherheitskorrekturen zu erhalten. diff --git a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md index 8e92fbc1d81..4c7552b14ca 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ Registrieren Sie `PollDemo` und `check_status` im selben [Python-Worker](./pytho Beide Beispiele wurden mit den veröffentlichten Versionen Server **2.9.7 / Core 2.7.2**, regulär installiertem Python **2.6.1** und der Testeingabe `[2, 1]` ausgeführt. Beide führten zwei echte Prüfungen in zwei Läufen aus. Continue-as-new beginnt eine neue Laufhistorie, erzeugt zusätzlichen Lauf- und Verknüpfungsaufwand und behält die ursprüngliche Ausführungsfrist bei. Es ermöglicht keine unbegrenzte Lebensdauer. -Verwenden Sie hier relative dauerhafte Wartezeiten. Eine fortschreitende Python-Uhr und bei der Wiedergabe stabile Abfragen des Historienbudgets bleiben getrennte Arbeiten an [Uhr](https://github.com/durable-workflow/.github/issues/215) und [Budget](https://github.com/durable-workflow/workflow/issues/859). Dieses Rezept verzweigt nicht anhand von `ctx.now()` oder einer neu berechneten Historienlänge. Betrachten Sie `DW_MAX_HISTORY_EVENTS` nicht als erzwungenen automatischen Laufwechsel: [Server #504](https://github.com/durable-workflow/server/issues/504) verfolgt diese Lücke. +Verwenden Sie hier relative dauerhafte Wartezeiten. `ctx.replay_now()` (Python-SDK 2.15.0+) schreitet mit verarbeiteten dauerhaften Schritten fort und hat ab Python-SDK 2.24.0 auch beim Einstieg einen Wert (siehe [Fortschreitende Replay-Uhr](./python.md#advancing-replay-clock)); bei der Wiedergabe stabile Abfragen des Historienbudgets bleiben getrennte Arbeit am [Budget](https://github.com/durable-workflow/workflow/issues/859). Dieses Rezept verzweigt nicht anhand von `ctx.now()` oder einer neu berechneten Historienlänge. Betrachten Sie `DW_MAX_HISTORY_EVENTS` nicht als erzwungenen automatischen Laufwechsel: [Server #504](https://github.com/durable-workflow/server/issues/504) verfolgt diese Lücke. ## Unterbrechen und Auswirkungen abgleichen {#interrupt-and-reconcile} diff --git a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/python.md b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/python.md index 1bd43863598..3655a690f9c 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/python.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/python.md @@ -784,6 +784,7 @@ Der an `run` übergebene `WorkflowContext` bietet deterministische Operationen: | `ctx.upsert_search_attributes(attrs)` | Suchattribute aktualisieren | | `ctx.continue_as_new(*args)` | Workflow mit neuer Eingabe neu starten | | `ctx.now()` | Gespeicherte Workflow-Startzeit, während dieses Runs fest | +| `ctx.replay_now()` | Fortschreitende replay-sichere UTC-Zeit: beim Einstieg der Start des Runs, danach die aufgezeichnete Zeit jedes verarbeiteten dauerhaften Schritts | | `ctx.random()` | Zufallsgenerator mit festgelegtem Startwert | | `ctx.uuid4()` | Deterministische UUID | | `ctx.logger` | Beim Replay stummer Logger | @@ -859,6 +860,109 @@ Werten und subtrahieren Sie keine monotonen Messwerte verschiedener Prozesse oder Hosts. Die Differenz von `ctx.now()`-Werten misst in Python weder aktive Verarbeitungszeit noch verstrichene Wanduhrzeit. +#### Fortschreitende Replay-Uhr {#advancing-replay-clock} + +`ctx.replay_now()` ist eine zusätzliche UTC-Uhr, die mit der verarbeiteten +Historie fortschreitet. Die SDKs für Rust (`WorkflowContext::replay_now()`) und +PHP im Service-Modus (`WorkflowContext::replayNow()`) bieten dieselbe Uhr. + +- Beim normalen Workflow-Einstieg, vor jedem dauerhaften Schritt, liefert sie + den kanonischen Start des Runs (bei einem Redrive-Nachfolger den Start des ursprünglichen Runs). Server 3.6.0 und neuer sendet diesen + Zeitpunkt mit jeder Workflow-Aufgabe als `replay_clock`. Einfüge-, Dispatch- + und Lease-Zeiten der Historie werden nie stattdessen verwendet. +- Nach einem unterstützten dauerhaften Schritt liefert sie dessen aufgezeichnete + Zeit: Aktivitäten, Timer und Child-Workflows in jedem SDK, Signal- und + Bedingungswartevorgänge, wo das SDK sie unterstützt, sowie validierte Gruppen. +- Wiederholte Lesevorgänge zwischen dauerhaften Schritten liefern denselben + Wert, und jedes Replay des Runs liefert dieselben Werte. Die Uhr ist nicht garantiert monoton: Eine spätere nachgewiesene Grenze kann eine frühere aufgezeichnete Zeit tragen. + +Eine Fristschleife um einen dauerhaften Timer endet daher, und die Differenz +zwischen Lesevorgängen nach zwei dauerhaften Schritten misst deren +aufgezeichnete verstrichene Zeit: + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +Wo das SDK die Zeit nicht nachweisen kann, löst `ctx.replay_now()` +`ReplayClockUnavailable` aus, statt eine andere Zeit zu verwenden: + +- beim Einstieg mit einer Aufgabe ohne Träger: Server vor 3.6.0 oder ein Run, + dessen Start der Server nicht nachweisen kann; +- nach Inline- und lokalen Operationen wie Seiteneffekten, Versionsmarkern, + Memo- und Suchattribut-Aktualisierungen sowie lokalen Aktivitäten. Diese + bleiben nicht verfügbar, bis Core für diese Schritte eine gespeicherte Zeit + festlegt; +- nach anderen Gruppenmodi und in Abbruchbereichen; +- in Query-Handlern: in PHP immer, in Python und Rust, sofern die abgefragte Historie nicht an einer unterstützten skalaren Grenze endet (gruppierte Grenzen liefern keine Query-Zeit). + +Ein nicht behandeltes `ReplayClockUnavailable` lässt den Workflow wie jede +andere Ausnahme fehlschlagen. + +##### Uhrlesungen nach Inline-Schritten sind nicht portabel {#inline-step-clock-reads} + +Inline-Schritte sind Seiteneffekte, Versionsmarker, Memo- und +Suchattribut-Aktualisierungen sowie lokale Aktivitäten. Bis Core für sie eine +gespeicherte Zeit festlegt, ist eine Uhrlesung unmittelbar nach einem solchen +Schritt weder zwischen Runnern noch in gemischten Flotten portabel: + +- Die SDKs im Service-Modus (Python, Rust und das PHP SDK) melden die Uhr dort + als nicht verfügbar. +- In der eingebetteten Engine springt `Workflow::now()` zur aufgezeichneten Zeit + des Schritts. +- Im External-Worker-Runner (dem Worker-Protokoll-`WorkflowFiberRunner` des + eingebetteten Pakets, den externe PHP-Worker über die Bridge verwenden) + verhalten sich Seiteneffekte, Memo- und Suchattribut-Aktualisierungen sowie + Versionsmarker gleich: Eine erste Ausführung behält die vorherige Grenzzeit, + während ein Replay die aufgezeichnete Zeit des Schritts liest. Bei + Versionsmarkern wird diese Abweichung bewusst beibehalten: Die gepinnte + Replay-Fixture `repeated-version-legacy-clock-boundaries` abzulösen, würde die + Replay-Ausgabe bereits laufender Runs ändern. +- Die Lesung weicht daher immer ab, wenn die erste Ausführung im + External-Worker-Runner lief, auch in einer Flotte nur aus externen Workern, + und immer dann, wenn ein Run zwischen Runnern wechseln kann, weil eingebettete + und externe erste Ausführungen unterschiedliche Zeiten lesen. + +Verlassen Sie sich nicht auf eine Uhrlesung unmittelbar nach einem +Inline-Schritt: Lesen Sie die Uhr nach dem nächsten dauerhaften Schritt. + +Python und Rust bauen den Workflow aus der Historie neu auf, um eine Query oder +eine Update-Validierung vor der Annahme zu beantworten. Liest der neu +aufgebaute Workflow die Uhr beim Einstieg und hat die Aufgabe kein +`replay_clock` – Server vor 3.30.0 senden es bei diesen +Aufgaben nie –, schlägt die Query oder Validierung fehl, statt mit einem Zustand +zu antworten, den die Workflow-Aufgabe nie berechnet hat. Das PHP-SDK baut den +Workflow-Körper für Queries oder Updates nie neu auf. + +Offline-Replay (`replay()`, `Replayer.replay()`, `replay_history()`) übernimmt das Objekt der Aufgabe als `replay_clock_entry`. Das In-Memory-`WorkflowEnvironment` liefert keinen Träger, daher sind Einstiegslesevorgänge dort nicht verfügbar. + +**Release-Status.** Der Einstiegswert (alle drei SDKs) und die Regel für Queries und Validierungen (Python und Rust) erscheinen in Python-SDK 2.24.0, Rust-SDK 4.25.0 und +PHP-SDK 3.32.0 und benötigen Server 3.6.0 oder neuer. Der Träger bei Query- und +Validierungsaufgaben erscheint in Server 3.30.0. Der Worker-Protokoll-Runner des +eingebetteten Pakets (`WorkflowFiberRunner`) akzeptiert den Träger ab Workflow +2.42.0: Sobald der Code, der den Runner erstellt, ihn übergibt, liefert +`Workflow::now()` beim Einstieg den kanonischen Start des Laufs. Frühere SDK-Releases +melden den Einstieg als nicht verfügbar. + +**Upgrade.** Ein laufender Workflow, dessen Code davon abhängig verzweigt, dass +der Einstiegswert nicht verfügbar ist – etwa indem er `ReplayClockUnavailable` +abfängt –, nimmt nach dem Upgrade, während eines Rolling Deployments mit alten und neuen Workern oder nach einem Server-Upgrade auf 3.6.0 beim Replay den anderen Zweig. Stellen Sie +solchen Code hinter `ctx.get_version(...)` oder lassen Sie diese Runs vorher +auslaufen. `ctx.now()` behält seine feste Startzeit, sodass Runs, die es lesen, +unverändert wiedergegeben werden. + #### Unterschiede zwischen den SDK-Uhren {#clock-differences-across-sdks} Diese APIs sind, soweit vorhanden, deterministisch, teilen aber keine gemeinsame Uhr: @@ -866,16 +970,17 @@ Diese APIs sind, soweit vorhanden, deterministisch, teilen aber keine gemeinsame | Autorenschnittstelle | Wiederholte Aufrufe und dauerhafte Schritte | Continue-as-new-Nachfolger | | --- | --- | --- | | Python `ctx.now()` | Bleibt auf der gespeicherten Startzeit dieses Runs, auch nach einem Timer oder einer Aktivität. | Verwendet den Startanker des Nachfolger-Runs. | +| Python `ctx.replay_now()` | Beginnt beim Start des Runs und schreitet zur aufgezeichneten Zeit jedes unterstützten verarbeiteten Schritts fort. Siehe [Fortschreitende Replay-Uhr](#advancing-replay-clock). | Beginnt beim eigenen Start des Nachfolger-Runs. | | Embedded PHP `Workflow::now()` | Beginnt mit der Run-Startzeit und schreitet zur aufgezeichneten Ereigniszeit fort, die das Replay verarbeitet hat. Siehe [Workflow-Zeit](../features/timers.md#reading-deterministic-time). | Beginnt mit dem neuen Run und schreitet durch dessen verarbeitete Ereignisse fort. | -| PHP-SDK im Service-Modus | Kein allgemeiner öffentlicher Workflow-Helfer `now()`. Verwenden Sie dauerhafte Operationen oder aufgezeichnete Aktivitäts-/Seiteneffektwerte. | Übergeben Sie Anwendungszeitdaten ausdrücklich, wenn sie die Übergabe überleben müssen. | -| Rust-SDK im Service-Modus | Kein allgemeiner öffentlicher Helfer `WorkflowContext::now()`. Ein `side_effect` kann eine kleine Wanduhrmomentaufnahme speichern; sie ist keine fortschreitende Uhr. | Ein Seiteneffekt im neuen Run ist eine neue Operation; übergeben Sie bei Bedarf frühere Zeitdaten ausdrücklich. | +| PHP im Service-Modus `WorkflowContext::replayNow()` | Dieselbe Semantik wie Python `ctx.replay_now()`. | Beginnt beim eigenen Start des Nachfolger-Runs. | +| Rust im Service-Modus `WorkflowContext::replay_now()` | Dieselbe Semantik wie Python `ctx.replay_now()`. | Beginnt beim eigenen Start des Nachfolger-Runs. | -Das Embedded-PHP-Verhalten ist im -[veröffentlichten Core](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php) -vorhanden. Der separate [PHP-SDK-Kontext](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -und [Rust-SDK-Kontext](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -haben eigene APIs. Übertragen Sie die dauerhafte Operation und Fristenregel, -statt für jeden SDK-Uhrhelfer dieselbe Semantik anzunehmen. +Die Uhren im Service-Modus teilen einen Vertrag. Das eingebettete `Workflow::now()` springt außerdem zur aufgezeichneten Zeit eines +Inline-Schritts wie eines Seiteneffekts, wo die Uhren im Service-Modus die Zeit +als nicht verfügbar melden; eine solche Lesung ist daher nicht portabel (siehe +[Uhrlesungen nach Inline-Schritten sind nicht portabel](#inline-step-clock-reads)). +Übertragen Sie die dauerhafte Operation und +Fristenregel, statt anzunehmen, dass sich jeder Uhrhelfer gleich verhält. #### Ausgegebene Ereignisse mit Sequenzwerten ordnen {#order-emitted-events-with-sequence-values} @@ -889,6 +994,8 @@ die Anwendung eine logische Sequenz benötigt. Zeitstempel geben unabhängigen Streams oder Runs keine globale Reihenfolge. +Wiederholte Lesevorgänge von `ctx.replay_now()` zwischen dauerhaften Schritten liefern ebenfalls einen einzigen Wert; verwenden Sie es daher auch nicht zum Ordnen von Ereignissen. + ### Aktivitätswiederholungen und -Timeouts {#activity-retries-and-timeouts} Verwenden Sie `ActivityRetryPolicy` und Timeout-Schlüsselwortargumente an diff --git a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md index 337d5814eae..028ffe02ce4 100644 --- a/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/de/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -907,6 +907,28 @@ Halten Sie die dauerhafte Befehlsreihenfolge unabhängig von diesem Beobachtungs Siehe den [veröffentlichten Logging-Guide](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging), die [WorkflowLogger-API](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html) und die [WorkflowReplayState-API](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html). [Registry-Lifecycle-/Deadline-Kontrollen](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853) und [Logging-Abnahme mit vier Prozessen](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262) wurden auf dem benannten Tupel mit native Server 3.10.0 unter linux/amd64 erfasst. Andere Bindings und weitergehende Replay-/Producer-Qualifikation behalten ihren eigenen Umfang. +## Replay-sichere Workflow-Zeit {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` liefert replay-sichere UTC-Geschäftszeit als +`Result>`. Beim normalen Einstieg ist es der Start des Runs (bei einem Redrive-Nachfolger der Start des ursprünglichen Runs) aus dem `replay_clock` der Aufgabe (Server 3.6.0 und neuer). Nach jedem +unterstützten verarbeiteten dauerhaften Schritt (Aktivitäten, Timer, +Child-Workflows, Signal- und Bedingungswartevorgänge, validierte Gruppen) ist +es dessen aufgezeichnete Zeit. Wiederholte Lesevorgänge zwischen dauerhaften +Schritten liefern denselben Wert, und jedes Replay liefert dieselben Werte. + +Wo das SDK die Zeit nicht nachweisen kann, liefert es +`Error::ReplayClockUnavailable`. Das umfasst Inline- und lokale Operationen +(Seiteneffekte, Versionsmarker, lokale Aktivitäten, Memos), die nicht verfügbar +bleiben, bis Core für sie eine gespeicherte Zeit festlegt. Eine Uhrlesung +direkt nach einem solchen Schritt ist weder zwischen Runnern noch in gemischten +Flotten portabel; siehe +[Uhrlesungen nach Inline-Schritten sind nicht portabel](./python.md#inline-step-clock-reads). +Offline-Replay +übergibt einen Träger mit `WorkflowHistory::replay_clock(carrier)`. Die +vollständige Liste, die Regel für Queries und Validierungen, den Release-Status +und den Upgrade-Hinweis finden Sie in der +[SDK-übergreifenden Uhrsemantik](./python.md#advancing-replay-clock). + ## Rust-Regeln für Determinismus {#rust-determinism-rules} Ein Replay muss für aufgezeichnete Eingabe und Historie dieselben dauerhaften Befehle in derselben Reihenfolge erzeugen. Gewöhnliche Rust-Sammlungen, Uhren und Nebenläufigkeitsprimitive erhalten diesen Vertrag nicht automatisch: @@ -914,7 +936,7 @@ Ein Replay muss für aufgezeichnete Eingabe und Historie dieselben dauerhaften B | Muster im Workflow-Code | Dauerhafter Ersatz | | --- | --- | | Beim Durchlaufen einer `HashMap` planen | Schlüssel vorher sortieren oder eine `BTreeMap` verwenden. | -| Systemzeit, `thread_rng` oder neue UUID lesen | Snapshot mit `ctx.side_effect(...)` aufzeichnen oder eine Activity verwenden. | +| Systemzeit, `thread_rng` oder neue UUID lesen | `ctx.replay_now()` für Geschäftszeit; andere Werte mit `ctx.side_effect(...)` aufzeichnen oder eine Aktivität verwenden. | | `tokio::time::sleep` oder `std::thread::sleep` | `ctx.sleep(...)` oder `ctx.start_timer(...)`. | | `tokio::select!` oder gewöhnliche Futures gegeneinander starten | `ctx.select(...)` oder `ctx.select_keyed(...)`. | | Nicht verfolgte parallele dauerhafte Aufrufe | `ctx.parallel(...)` mit stabiler Eingabereihenfolge. | diff --git a/i18n/de/source-hashes.json b/i18n/de/source-hashes.json index 3e58ba988e9..d6604d94ee5 100644 --- a/i18n/de/source-hashes.json +++ b/i18n/de/source-hashes.json @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", - "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", + "polyglot/php.md": "30bee275e7691445566784511af53809fa1045c27c4fcc067fa2da0b6cfb1898", + "polyglot/polling-patterns.md": "19b971e63c3ae65d213250472a1f468a2d5d7a6e1b71dccfc8ae2ac54681ba67", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", - "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", + "polyglot/python.md": "dbef23a26f6dcb75cb37f8b0fe716913a33aa483c35e3bc718caf207464cf4b7", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", + "polyglot/rust.md": "8c5612748e0ea83423d20f912072242c1b2a149e7e3e9a26e28ef7175c818622", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md index 68104c5908d..c1f971f8c7b 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -332,6 +332,28 @@ analizador que el paquete integrado. La [referencia de duraciones del PHP SDK](https://php.durable-workflow.com/build/workflows-activities/#durations) enumera todas las unidades. +## Hora del workflow segura para replay {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` devuelve la hora de negocio UTC segura para +replay como `DateTimeImmutable`. En la entrada normal es el inicio del run (para un sucesor de redrive, el inicio del run original) tomado del `replay_clock` de la tarea (Server 3.6.0 y posteriores). Después de +cada paso duradero consumido compatible (actividades, temporizadores, workflows +hijos, esperas de condiciones, grupos validados) es la hora registrada de ese +paso. Las lecturas repetidas entre pasos duraderos devuelven el mismo valor, y +cada replay devuelve los mismos valores. + +Cuando el SDK no puede demostrar la hora, lanza +`DurableWorkflow\Exception\ReplayClockUnavailable`. Eso incluye efectos +secundarios, marcadores de versión y actividades locales, que siguen sin estar +disponibles hasta que Core defina una hora persistida para ellos. Una lectura +del reloj justo después de uno de esos pasos no es portable entre runners ni en +flotas mixtas; consulta +[Las lecturas del reloj tras pasos en línea no son portables](./python.md#inline-step-clock-reads). +Los handlers +de consultas y actualizaciones leen instantáneas del historial y nunca +reconstruyen el cuerpo del workflow. Consulta la +[semántica del reloj entre SDK](./python.md#advancing-replay-clock) para ver la +lista completa, el estado de publicación y la nota de actualización. + ## Compatibilidad de entrada y recuperación {#entry-compatibility-and-recovery} **Soporte publicado.** El SDK PHP 2.5.4 incorporó la protección de entrada descrita a continuación, con enrutamiento y recuperación en Server 2.9.9. Son las versiones mínimas para estas funciones; instale las versiones estables actuales para recibir correcciones de seguridad. diff --git a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md index 8faceaa2dbe..7bd5455635c 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ Registre `PollDemo` y `check_status` en el mismo [worker Python](./python.md), y Ambos ejemplos se ejecutaron en las versiones publicadas Server **2.9.7 / Core 2.7.2**, con Python **2.6.1** instalado normalmente y la entrada de prueba `[2, 1]`. Ambos completaron dos consultas reales en dos ejecuciones. Continue-as-new reinicia el historial de la ejecución, añade costes de ejecución y enlace, y conserva el plazo original de la ejecución lógica. No proporciona una duración ilimitada. -Use esperas duraderas relativas. El avance del reloj de Python y las lecturas del presupuesto de historial estables durante la reproducción siguen siendo trabajos separados sobre [reloj](https://github.com/durable-workflow/.github/issues/215) y [presupuesto](https://github.com/durable-workflow/workflow/issues/859). Esta receta no toma decisiones mediante `ctx.now()` ni una longitud de historial recalculada. No considere `DW_MAX_HISTORY_EVENTS` una transición automática aplicada obligatoriamente: [Server #504](https://github.com/durable-workflow/server/issues/504) sigue esa carencia. +Use esperas duraderas relativas. `ctx.replay_now()` (SDK de Python 2.15.0+) avanza con los pasos duraderos consumidos y, a partir del SDK de Python 2.24.0, también tiene un valor en la entrada (consulta [Reloj de replay que avanza](./python.md#advancing-replay-clock)); las lecturas del presupuesto de historial estables durante la reproducción siguen siendo un trabajo separado sobre el [presupuesto](https://github.com/durable-workflow/workflow/issues/859). Esta receta no toma decisiones mediante `ctx.now()` ni una longitud de historial recalculada. No considere `DW_MAX_HISTORY_EVENTS` una transición automática aplicada obligatoriamente: [Server #504](https://github.com/durable-workflow/server/issues/504) sigue esa carencia. ## Interrumpa y reconcilie {#interrupt-and-reconcile} diff --git a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/python.md b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/python.md index 7a8b34d693c..980fa6ed8fc 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/python.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/python.md @@ -766,6 +766,7 @@ Los helpers locales síncronos no pueden esperar. `workflow.query_state()` recha | `ctx.upsert_search_attributes(attrs)` | Actualiza atributos de búsqueda | | `ctx.continue_as_new(*args)` | Reinicia el workflow con otra entrada | | `ctx.now()` | Hora de inicio persistida del workflow, fija durante este run | +| `ctx.replay_now()` | Hora UTC segura para replay que avanza: el inicio del run en la entrada y después la hora registrada de cada paso duradero consumido | | `ctx.random()` | Generador aleatorio con semilla | | `ctx.uuid4()` | UUID determinista | | `ctx.logger` | Logger silencioso durante la reproducción | @@ -836,6 +837,108 @@ registrado. Nunca compares marcas UTC con valores monotónicos ni restes lecturas monotónicas de procesos o equipos diferentes. Restar `ctx.now()` no mide ni el tiempo de procesamiento activo ni el tiempo real transcurrido en Python. +#### Reloj de replay que avanza {#advancing-replay-clock} + +`ctx.replay_now()` es un reloj UTC adicional que avanza con el historial +consumido. Los SDK de Rust (`WorkflowContext::replay_now()`) y de PHP en modo +servicio (`WorkflowContext::replayNow()`) ofrecen el mismo reloj. + +- En la entrada normal del workflow, antes de cualquier paso duradero, devuelve + el inicio canónico del run (para un sucesor de redrive, el inicio del run original). Server 3.6.0 y versiones posteriores envían ese + instante en cada tarea de workflow como `replay_clock`. Nunca se usan en su + lugar las horas de inserción en el historial, de despacho ni de lease. +- Después de un paso duradero compatible devuelve la hora registrada de ese + paso: actividades, temporizadores y workflows hijos en todos los SDK, esperas + de señales y condiciones donde el SDK las admite, y grupos validados. +- Las lecturas repetidas entre pasos duraderos devuelven el mismo valor, y cada replay del run devuelve los mismos valores. No se garantiza que el reloj sea monótono: un límite demostrado posterior puede llevar una hora registrada anterior. + +Por eso un bucle con plazo alrededor de un temporizador duradero termina, y la +diferencia entre lecturas después de dos pasos duraderos mide el tiempo +transcurrido registrado entre ellos: + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +Cuando el SDK no puede demostrar la hora, `ctx.replay_now()` lanza +`ReplayClockUnavailable` en lugar de usar cualquier otra hora: + +- en la entrada con una tarea sin portador: Servers anteriores a 3.6.0, o un run + cuyo inicio Server no puede demostrar; +- después de operaciones en línea y locales, como efectos secundarios, + marcadores de versión, actualizaciones de memo y de atributos de búsqueda, y + actividades locales. Siguen sin estar disponibles hasta que Core defina una + hora persistida para esos pasos; +- después de otros modos de grupo y en ámbitos de cancelación; +- en handlers de consulta: siempre en PHP, y en Python y Rust salvo que el historial consultado termine en un límite escalar compatible (los límites agrupados no dan hora de consulta). + +Un `ReplayClockUnavailable` no gestionado hace fallar el workflow como +cualquier otra excepción. + +##### Las lecturas del reloj tras pasos en línea no son portables {#inline-step-clock-reads} + +Los pasos en línea son los efectos secundarios, los marcadores de versión, las +actualizaciones de memo y de atributos de búsqueda, y las actividades locales. +Hasta que Core defina una hora persistida para ellos, una lectura del reloj +inmediatamente después de uno de ellos no es portable entre runners ni en +flotas mixtas: + +- Los SDK en modo servicio (Python, Rust y el SDK de PHP) informan ahí el reloj + como no disponible. +- En el motor integrado, `Workflow::now()` pasa a la hora registrada del paso. +- En el runner de workers externos (el `WorkflowFiberRunner` del protocolo de + workers del paquete integrado, que los workers PHP externos usan a través del + bridge), los efectos secundarios, las actualizaciones de memo y de atributos + de búsqueda y los marcadores de versión se comportan igual: una primera + ejecución conserva la hora del límite anterior, mientras que un replay lee la + hora registrada del paso. En los marcadores de versión esta divergencia se + mantiene a propósito: sustituir el fixture de replay fijado + `repeated-version-legacy-clock-boundaries` cambiaría la salida del replay de + los runs que ya están en curso. +- Por eso la lectura difiere siempre que la primera ejecución se hizo en el + runner de workers externos, incluso en una flota formada solo por workers + externos, y siempre que un run pueda pasar de un runner a otro, porque las + primeras ejecuciones integradas y externas leen horas distintas. + +No dependas de una lectura del reloj inmediatamente después de un paso en +línea: lee el reloj después del siguiente paso duradero. + +Python y Rust reconstruyen el workflow a partir del historial para responder a +una consulta o a una validación de actualización previa a la aceptación. Si el +workflow reconstruido lee el reloj en la entrada y la tarea no tiene +`replay_clock` (los Servers anteriores a 3.30.0 nunca lo +envían en esas tareas), la consulta o la validación falla en lugar de responder +con un estado que la tarea de workflow nunca calculó. El SDK de PHP nunca +reconstruye el cuerpo del workflow para consultas ni actualizaciones. + +El replay sin conexión (`replay()`, `Replayer.replay()`, `replay_history()`) recibe el objeto de la tarea como `replay_clock_entry`. El `WorkflowEnvironment` en memoria no proporciona portador, así que allí las lecturas en la entrada no están disponibles. + +**Estado de publicación.** El valor de entrada (los tres SDK) y la regla para consultas y validaciones (Python y Rust) llegan en el SDK de Python 2.24.0, el SDK de Rust 4.25.0 y el SDK de PHP 3.32.0 +y requieren Server 3.6.0 o posterior. El portador en las tareas de consulta y +validación llega en Server 3.30.0. El runner del protocolo de workers del paquete +integrado (`WorkflowFiberRunner`) acepta el portador a partir de Workflow 2.42.0: +cuando el código que construye el runner se lo pasa, `Workflow::now()` en la +entrada devuelve el inicio canónico de la ejecución. Las versiones anteriores de +los SDK informan la entrada como no disponible. + +**Actualización.** Un workflow en ejecución cuyo código se ramifica según si la +lectura de entrada no está disponible, por ejemplo capturando +`ReplayClockUnavailable`, toma la otra rama en el replay después de la actualización, durante un despliegue gradual que mezcla workers antiguos y nuevos, o tras actualizar Server a 3.6.0. Pon ese código detrás de `ctx.get_version(...)` o deja que esos +runs terminen antes. `ctx.now()` conserva su hora de inicio fija, así que los +runs que lo leen se reproducen sin cambios. + #### Diferencias entre los relojes de los SDK {#clock-differences-across-sdks} Estas API son deterministas cuando existen, pero no comparten un único reloj: @@ -843,16 +946,17 @@ Estas API son deterministas cuando existen, pero no comparten un único reloj: | Interfaz de autoría | Llamadas repetidas y pasos duraderos | Sucesor de continue-as-new | | --- | --- | --- | | Python `ctx.now()` | Fija la hora de inicio persistida de este run, incluso después de un temporizador o actividad. | Usa el ancla inicial del run sucesor. | +| Python `ctx.replay_now()` | Empieza en el inicio del run y avanza a la hora registrada de cada paso consumido compatible. Consulta [Reloj de replay que avanza](#advancing-replay-clock). | Empieza en el inicio propio del run sucesor. | | PHP integrado `Workflow::now()` | Parte de la hora inicial del run y avanza a la hora registrada del evento consumido durante la reproducción. Consulta [tiempo del workflow](../features/timers.md#reading-deterministic-time). | Parte del nuevo run y avanza por sus propios eventos consumidos. | -| SDK PHP en modo servicio | No hay un ayudante público general `now()` para workflows. Usa operaciones duraderas o valores registrados de actividades o efectos secundarios. | Pasa explícitamente el estado temporal de la aplicación si debe sobrevivir al traspaso. | -| SDK Rust en modo servicio | No hay un ayudante público general `WorkflowContext::now()`. Un `side_effect` puede registrar una pequeña instantánea del reloj de pared; no es un reloj que avance. | Un efecto secundario en el nuevo run es otra operación; pasa explícitamente el estado temporal anterior si hace falta. | +| PHP en modo servicio `WorkflowContext::replayNow()` | La misma semántica que Python `ctx.replay_now()`. | Empieza en el inicio propio del run sucesor. | +| Rust en modo servicio `WorkflowContext::replay_now()` | La misma semántica que Python `ctx.replay_now()`. | Empieza en el inicio propio del run sucesor. | -El comportamiento de PHP integrado existe en el -[Core publicado](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php). -Los contextos independientes del [SDK PHP](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -y del [SDK Rust](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -tienen sus propias API. Porta la operación duradera y la política de plazos -sin suponer que un ayudante de reloj significa lo mismo en todos los SDK. +Los relojes del modo servicio comparten un contrato. `Workflow::now()` integrado también pasa a la hora registrada de un paso en línea +como un efecto secundario, donde los relojes del modo servicio informan la hora +como no disponible, así que esa lectura no es portable (consulta +[Las lecturas del reloj tras pasos en línea no son portables](#inline-step-clock-reads)). +Traslada la operación duradera y la política de plazos en +lugar de suponer que todos los helpers de reloj se comportan igual. #### Ordena eventos emitidos mediante secuencias {#order-emitted-events-with-sequence-values} @@ -866,6 +970,8 @@ necesita una secuencia lógica única. Los streams o runs independientes no obtienen un orden global a partir de sus marcas temporales. +Las lecturas repetidas de `ctx.replay_now()` entre pasos duraderos también devuelven un único valor, así que tampoco lo uses para ordenar eventos. + ### Reintentos y plazos de actividades {#activity-retries-and-timeouts} Usa `ActivityRetryPolicy` y argumentos de plazo en `ctx.schedule_activity(...)` diff --git a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md index 7591522824d..504d835336b 100644 --- a/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/es/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -736,6 +736,28 @@ Mantenga el orden de comandos durables independiente de este estado de observaci Consulte la [guía de logging publicada](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging), la [API WorkflowLogger](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html) y la [API WorkflowReplayState](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html). Los [controles de ciclo de vida/deadline desde el registro](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853) y la [aceptación de logging con cuatro procesos](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262) se registraron en la tupla nombrada native Server 3.10.0 linux/amd64. Los demás bindings y la cualificación más amplia de replay/productor mantienen su propio alcance. +## Hora del workflow segura para replay {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` devuelve la hora de negocio UTC segura para +replay como `Result>`. En la entrada normal es el inicio del run (para un sucesor de redrive, el inicio del run original) tomado del `replay_clock` de la tarea (Server 3.6.0 y posteriores). Después de +cada paso duradero consumido compatible (actividades, temporizadores, workflows +hijos, esperas de señales y condiciones, grupos validados) es la hora registrada +de ese paso. Las lecturas repetidas entre pasos duraderos devuelven el mismo +valor, y cada replay devuelve los mismos valores. + +Cuando el SDK no puede demostrar la hora, devuelve +`Error::ReplayClockUnavailable`. Eso incluye las operaciones en línea y locales +(efectos secundarios, marcadores de versión, actividades locales, memos), que +siguen sin estar disponibles hasta que Core defina una hora persistida para +ellas. Una lectura del reloj justo después de uno de esos pasos no es portable +entre runners ni en flotas mixtas; consulta +[Las lecturas del reloj tras pasos en línea no son portables](./python.md#inline-step-clock-reads). +El replay sin conexión proporciona un portador con +`WorkflowHistory::replay_clock(carrier)`. Consulta la +[semántica del reloj entre SDK](./python.md#advancing-replay-clock) para ver la +lista completa, la regla para consultas y validaciones, el estado de publicación +y la nota de actualización. + ## Reglas de determinismo de Rust {#rust-determinism-rules} Una reproducción debe generar los mismos comandos duraderos, en el mismo orden, para la entrada y el historial registrados. Las colecciones, relojes y primitivas de concurrencia normales de Rust no mantienen automáticamente ese contrato: @@ -743,7 +765,7 @@ Una reproducción debe generar los mismos comandos duraderos, en el mismo orden, | Patrón en el código del workflow | Sustitución duradera | | --- | --- | | Programar mientras se recorre un `HashMap` | Ordene primero las claves o use un `BTreeMap`. | -| Leer el reloj, `thread_rng` o un UUID nuevo | Registre una instantánea con `ctx.side_effect(...)` o use una actividad. | +| Leer el reloj, `thread_rng` o un UUID nuevo | `ctx.replay_now()` para la hora de negocio; registra otros valores con `ctx.side_effect(...)` o usa una actividad. | | `tokio::time::sleep` o `std::thread::sleep` | `ctx.sleep(...)` o `ctx.start_timer(...)`. | | `tokio::select!` o carreras de futuros normales | `ctx.select(...)` o `ctx.select_keyed(...)`. | | Llamadas duraderas concurrentes sin seguimiento | `ctx.parallel(...)` con un orden estable de entrada. | diff --git a/i18n/es/source-hashes.json b/i18n/es/source-hashes.json index 3e58ba988e9..d6604d94ee5 100644 --- a/i18n/es/source-hashes.json +++ b/i18n/es/source-hashes.json @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", - "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", + "polyglot/php.md": "30bee275e7691445566784511af53809fa1045c27c4fcc067fa2da0b6cfb1898", + "polyglot/polling-patterns.md": "19b971e63c3ae65d213250472a1f468a2d5d7a6e1b71dccfc8ae2ac54681ba67", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", - "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", + "polyglot/python.md": "dbef23a26f6dcb75cb37f8b0fe716913a33aa483c35e3bc718caf207464cf4b7", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", + "polyglot/rust.md": "8c5612748e0ea83423d20f912072242c1b2a149e7e3e9a26e28ef7175c818622", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md index 677e7910fad..2346fe00873 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -336,6 +336,27 @@ analyseur que le paquet embarqué. La [référence des durées du SDK PHP](https://php.durable-workflow.com/build/workflows-activities/#durations) répertorie toutes les unités. +## Heure du workflow sûre pour le replay {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` renvoie l'heure métier UTC sûre pour le replay +sous la forme d'un `DateTimeImmutable`. À l'entrée ordinaire, c'est le début du run (pour un successeur de redrive, le début du run d'origine) issu du `replay_clock` de la tâche (Server 3.6.0 et ultérieur). Après chaque +étape durable consommée prise en charge (activités, temporisateurs, workflows +enfants, attentes de conditions, groupes validés), c'est l'heure enregistrée de +cette étape. Les lectures répétées entre étapes durables renvoient la même +valeur, et chaque replay renvoie les mêmes valeurs. + +Lorsque le SDK ne peut pas prouver l'heure, il lève +`DurableWorkflow\Exception\ReplayClockUnavailable`. Cela inclut les effets de +bord, les marqueurs de version et les activités locales, qui restent +indisponibles jusqu'à ce que Core définisse une heure persistée pour eux. Une +lecture d'horloge juste après une telle étape n'est portable ni entre runners +ni dans des flottes mixtes ; voir +[Les lectures d'horloge après une étape en ligne ne sont pas portables](./python.md#inline-step-clock-reads). +Les gestionnaires de requêtes et de mises à jour lisent des instantanés de +l'historique et ne reconstruisent jamais le corps du workflow. Consultez la +[sémantique d'horloge commune aux SDK](./python.md#advancing-replay-clock) pour +la liste complète, l'état de publication et la note de mise à niveau. + ## Compatibilité à l’entrée et récupération {#entry-compatibility-and-recovery} **Prise en charge publiée.** Le SDK PHP 2.5.4 a introduit la protection d’entrée ci-dessous, avec le routage et la récupération dans Server 2.9.9. Ce sont les versions minimales pour ces fonctions. Installez les versions stables actuelles pour bénéficier des correctifs de sécurité. diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md index 67a05783a32..cea5a6d873e 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ Enregistrez `PollDemo` et `check_status` dans le même [worker Python](./python. Les deux exemples ont été exécutés sur les versions publiées Server **2.9.7 / Core 2.7.2**, avec Python **2.6.1** installé normalement et l’entrée de test `[2, 1]`. Chacun a effectué deux vérifications réelles dans deux exécutions. Continue-as-new recommence l’historique, ajoute le coût d’une exécution et de son lien, et conserve l’échéance d’origine de l’exécution logique. Il n’accorde pas une durée de vie illimitée. -Utilisez ici des attentes durables relatives. L’avancement de l’horloge Python et les lectures du budget d’historique stables pendant la relecture restent des travaux distincts sur [l’horloge](https://github.com/durable-workflow/.github/issues/215) et le [budget](https://github.com/durable-workflow/workflow/issues/859). Cette recette ne branche pas selon `ctx.now()` ni une longueur d’historique recalculée. Ne considérez pas `DW_MAX_HISTORY_EVENTS` comme une transition automatique imposée : [Server #504](https://github.com/durable-workflow/server/issues/504) suit cette lacune. +Utilisez ici des attentes durables relatives. `ctx.replay_now()` (SDK Python 2.15.0+) avance avec les étapes durables consommées et, à partir du SDK Python 2.24.0, a aussi une valeur à l'entrée (voir [Horloge de replay qui avance](./python.md#advancing-replay-clock)) ; les lectures du budget d’historique stables pendant la relecture restent un travail distinct sur le [budget](https://github.com/durable-workflow/workflow/issues/859). Cette recette ne branche pas selon `ctx.now()` ni une longueur d’historique recalculée. Ne considérez pas `DW_MAX_HISTORY_EVENTS` comme une transition automatique imposée : [Server #504](https://github.com/durable-workflow/server/issues/504) suit cette lacune. ## Interrompre et réconcilier {#interrupt-and-reconcile} diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/python.md b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/python.md index 54040c7173c..7e195a35112 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/python.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/python.md @@ -783,6 +783,7 @@ Le `WorkflowContext` transmis à `run` fournit des opérations déterministes : | `ctx.upsert_search_attributes(attrs)` | Mettre à jour les attributs de recherche | | `ctx.continue_as_new(*args)` | Redémarrer le workflow avec de nouvelles entrées | | `ctx.now()` | Heure de début persistée du workflow, fixe pour ce run | +| `ctx.replay_now()` | Heure UTC sûre pour le replay qui avance : le début du run à l'entrée, puis l'heure enregistrée de chaque étape durable consommée | | `ctx.random()` | Générateur pseudoaléatoire à graine fixée | | `ctx.uuid4()` | UUID déterministe | | `ctx.logger` | Logger silencieux pendant la relecture | @@ -858,6 +859,112 @@ pas des mesures monotones de processus ou d'hôtes différents. La soustraction de `ctx.now()` ne mesure en Python ni le temps de traitement actif ni le temps mural écoulé. +#### Horloge de replay qui avance {#advancing-replay-clock} + +`ctx.replay_now()` est une horloge UTC supplémentaire qui avance avec +l'historique consommé. Les SDK Rust (`WorkflowContext::replay_now()`) et PHP en +mode service (`WorkflowContext::replayNow()`) fournissent la même horloge. + +- À l'entrée ordinaire du workflow, avant toute étape durable, elle renvoie le + début canonique du run (pour un successeur de redrive, le début du run d'origine). Server 3.6.0 et versions ultérieures envoient cet + instant avec chaque tâche de workflow sous la forme `replay_clock`. Les heures + d'insertion dans l'historique, de distribution et de bail ne sont jamais + utilisées à la place. +- Après une étape durable prise en charge, elle renvoie l'heure enregistrée de + cette étape : activités, temporisateurs et workflows enfants dans chaque SDK, + attentes de signaux et de conditions là où le SDK les prend en charge, et + groupes validés. +- Les lectures répétées entre étapes durables renvoient la même valeur, et chaque replay du run renvoie les mêmes valeurs. L'horloge n'est pas garantie monotone : une limite prouvée ultérieure peut porter une heure enregistrée antérieure. + +Une boucle à échéance autour d'un temporisateur durable se termine donc, et +l'écart entre des lectures effectuées après deux étapes durables mesure leur +temps écoulé enregistré : + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +Lorsque le SDK ne peut pas prouver l'heure, `ctx.replay_now()` lève +`ReplayClockUnavailable` au lieu d'utiliser une autre heure : + +- à l'entrée avec une tâche sans porteur : Servers antérieurs à 3.6.0, ou run + dont Server ne peut pas prouver le début ; +- après des opérations en ligne et locales, comme les effets de bord, les + marqueurs de version, les mises à jour de mémo et d'attributs de recherche, + et les activités locales. Elles restent indisponibles jusqu'à ce que Core + définisse une heure persistée pour ces étapes ; +- après d'autres modes de groupe et dans les portées d'annulation ; +- dans les gestionnaires de requête : toujours en PHP, et en Python et Rust sauf si l'historique interrogé se termine sur une limite scalaire prise en charge (les limites groupées ne donnent pas d'heure de requête). + +Une `ReplayClockUnavailable` non gérée fait échouer le workflow comme toute +autre exception. + +##### Les lectures d'horloge après une étape en ligne ne sont pas portables {#inline-step-clock-reads} + +Les étapes en ligne sont les effets de bord, les marqueurs de version, les mises +à jour de mémo et d'attributs de recherche, et les activités locales. Tant que +Core ne définit pas d'heure persistée pour elles, une lecture d'horloge +immédiatement après l'une d'elles n'est portable ni entre runners ni dans des +flottes mixtes : + +- Les SDK en mode service (Python, Rust et le SDK PHP) y signalent l'horloge + comme indisponible. +- Dans le moteur intégré, `Workflow::now()` passe à l'heure enregistrée de + l'étape. +- Dans le runner des workers externes (le `WorkflowFiberRunner` du protocole + worker du paquet intégré, que les workers PHP externes utilisent via le + bridge), les effets de bord, les mises à jour de mémo et d'attributs de + recherche et les marqueurs de version se comportent de la même façon : une + première exécution conserve l'heure de la limite précédente, tandis qu'une + relecture lit l'heure enregistrée de l'étape. Pour les marqueurs de version, + cette divergence est conservée délibérément : remplacer la fixture de + relecture épinglée `repeated-version-legacy-clock-boundaries` modifierait la + sortie de relecture des runs déjà en cours. +- La lecture diffère donc chaque fois que la première exécution a eu lieu dans + le runner des workers externes, y compris dans une flotte composée uniquement + de workers externes, et chaque fois qu'un run peut passer d'un runner à + l'autre, car les premières exécutions intégrées et externes lisent des heures + différentes. + +Ne vous fiez pas à une lecture d'horloge immédiatement après une étape en +ligne : lisez l'horloge après l'étape durable suivante. + +Python et Rust reconstruisent le workflow à partir de l'historique pour +répondre à une requête ou à une validation de mise à jour avant acceptation. Si +le workflow reconstruit lit l'horloge à l'entrée et que la tâche n'a pas de +`replay_clock` (les Servers antérieurs à 3.30.0 ne +l'envoient jamais sur ces tâches), la requête ou la validation échoue au lieu de +répondre avec un état que la tâche de workflow n'a jamais calculé. Le SDK PHP ne +reconstruit jamais le corps du workflow pour les requêtes ou les mises à jour. + +Le replay hors ligne (`replay()`, `Replayer.replay()`, `replay_history()`) reçoit l'objet de la tâche sous la forme `replay_clock_entry`. Le `WorkflowEnvironment` en mémoire ne fournit pas de porteur ; les lectures d'entrée y sont donc indisponibles. + +**État de publication.** La valeur d'entrée (les trois SDK) et la règle pour les requêtes et les validations (Python et Rust) arrivent dans le SDK Python 2.24.0, le SDK Rust 4.25.0 et +le SDK PHP 3.32.0 et nécessitent Server 3.6.0 ou ultérieur. Le porteur sur les tâches de +requête et de validation arrive dans Server 3.30.0. Le runner du protocole worker +du paquet embarqué (`WorkflowFiberRunner`) accepte le porteur à partir de +Workflow 2.42.0 : dès que le code qui construit le runner le lui transmet, +`Workflow::now()` à l'entrée renvoie le début canonique de l'exécution. Les +versions antérieures des SDK signalent l'entrée comme indisponible. + +**Mise à niveau.** Un workflow en cours dont le code bifurque selon que la +lecture d'entrée est indisponible, par exemple en interceptant +`ReplayClockUnavailable`, prend l'autre branche au replay après la mise à niveau, pendant un déploiement progressif qui mélange anciens et nouveaux workers, ou après une mise à niveau de Server vers 3.6.0. Placez ce code derrière `ctx.get_version(...)` ou laissez ces runs se +terminer d'abord. `ctx.now()` conserve son heure de début fixe : les runs qui le +lisent sont rejoués sans changement. + #### Différences d'horloge entre SDK {#clock-differences-across-sdks} Ces API sont déterministes lorsqu'elles existent, mais ne partagent pas une même horloge : @@ -865,16 +972,17 @@ Ces API sont déterministes lorsqu'elles existent, mais ne partagent pas une mê | Surface d'écriture | Appels répétés et étapes durables | Successeur continue-as-new | | --- | --- | --- | | Python `ctx.now()` | Fixe l'heure de début persistée de ce run, même après un temporisateur ou une activité. | Utilise l'ancrage initial du run successeur. | +| Python `ctx.replay_now()` | Commence au début du run et avance jusqu'à l'heure enregistrée de chaque étape consommée prise en charge. Voir [Horloge de replay qui avance](#advancing-replay-clock). | Commence au début propre du run successeur. | | PHP intégré `Workflow::now()` | Commence à l'heure de début du run et avance vers l'heure enregistrée de l'événement consommé par la relecture. Voir [temps du workflow](../features/timers.md#reading-deterministic-time). | Commence avec le nouveau run, puis avance au fil de ses propres événements consommés. | -| SDK PHP en mode service | Pas d'aide publique générale `now()` pour le workflow. Utilisez des opérations durables ou les valeurs enregistrées d'activités ou d'effets de bord. | Transmettez explicitement l'état temporel de l'application s'il doit survivre au passage. | -| SDK Rust en mode service | Pas d'aide publique générale `WorkflowContext::now()`. Un `side_effect` peut enregistrer un petit instantané de l'horloge murale, sans constituer une horloge qui avance. | Un effet de bord dans le nouveau run est une nouvelle opération ; transmettez explicitement l'état temporel antérieur si nécessaire. | +| PHP en mode service `WorkflowContext::replayNow()` | Même sémantique que Python `ctx.replay_now()`. | Commence au début propre du run successeur. | +| Rust en mode service `WorkflowContext::replay_now()` | Même sémantique que Python `ctx.replay_now()`. | Commence au début propre du run successeur. | -Le comportement PHP intégré existe dans le -[Core publié](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php). -Les contextes distincts du [SDK PHP](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -et du [SDK Rust](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -ont leurs propres API. Portez l'opération durable et la politique d'échéance -sans supposer qu'une aide d'horloge possède la même sémantique dans chaque SDK. +Les horloges du mode service partagent un contrat. `Workflow::now()` intégré passe aussi à l'heure enregistrée d'une étape en ligne comme un effet +de bord, là où les horloges du mode service signalent l'heure comme +indisponible ; une telle lecture n'est donc pas portable (voir +[Les lectures d'horloge après une étape en ligne ne sont pas portables](#inline-step-clock-reads)). +Transposez l'opération durable et la politique d'échéance plutôt +que de supposer que chaque assistant d'horloge se comporte de la même façon. #### Ordonner les événements émis avec des séquences {#order-emitted-events-with-sequence-values} @@ -888,6 +996,8 @@ a besoin d'une séquence logique unique. Les horodatages ne donnent pas d'ordre global aux streams ou runs indépendants. +Les lectures répétées de `ctx.replay_now()` entre étapes durables renvoient elles aussi une seule valeur ; ne l'utilisez donc pas non plus pour ordonner des événements. + ### Tentatives et délais d'activité {#activity-retries-and-timeouts} Utilisez `ActivityRetryPolicy` et les arguments nommés de délai de diff --git a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md index 9d6dbaa2e35..9034ce21d7a 100644 --- a/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/fr/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -902,6 +902,27 @@ Gardez l’ordre des commandes durables indépendant de cet état d’observatio Consultez le [guide de journalisation publié](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging), l’[API WorkflowLogger](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html) et l’[API WorkflowReplayState](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html). Les [contrôles cycle de vie/deadline depuis le registre](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853) et l’[acceptation de journalisation avec quatre processus](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262) ont été enregistrés sur le tuple nommé native Server 3.10.0 linux/amd64. Les autres bindings et qualifications plus larges de replay/producteur gardent leur propre périmètre. +## Heure du workflow sûre pour le replay {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` renvoie l'heure métier UTC sûre pour le replay +sous la forme `Result>`. À l'entrée ordinaire, c'est le début du run (pour un successeur de redrive, le début du run d'origine) issu du `replay_clock` de la tâche (Server 3.6.0 et ultérieur). Après chaque +étape durable consommée prise en charge (activités, temporisateurs, workflows +enfants, attentes de signaux et de conditions, groupes validés), c'est l'heure +enregistrée de cette étape. Les lectures répétées entre étapes durables +renvoient la même valeur, et chaque replay renvoie les mêmes valeurs. + +Lorsque le SDK ne peut pas prouver l'heure, il renvoie +`Error::ReplayClockUnavailable`. Cela inclut les opérations en ligne et locales +(effets de bord, marqueurs de version, activités locales, mémos), qui restent +indisponibles jusqu'à ce que Core définisse une heure persistée pour elles. Une +lecture d'horloge juste après une telle étape n'est portable ni entre runners +ni dans des flottes mixtes ; voir +[Les lectures d'horloge après une étape en ligne ne sont pas portables](./python.md#inline-step-clock-reads). +Le replay hors ligne fournit un porteur avec `WorkflowHistory::replay_clock(carrier)`. +Consultez la [sémantique d'horloge commune aux SDK](./python.md#advancing-replay-clock) +pour la liste complète, la règle des requêtes et validations, l'état de +publication et la note de mise à niveau. + ## Règles de déterminisme Rust {#rust-determinism-rules} Une relecture doit produire les mêmes commandes durables dans le même ordre pour l’entrée et l’historique enregistrés. Les collections, horloges et primitives de concurrence ordinaires de Rust ne préservent pas automatiquement ce contrat : @@ -909,7 +930,7 @@ Une relecture doit produire les mêmes commandes durables dans le même ordre po | Motif dans le code du workflow | Remplacement durable | | --- | --- | | Planifier en parcourant un `HashMap` | Trier les clés d’abord ou utiliser un `BTreeMap`. | -| Lire l’horloge, `thread_rng` ou un nouvel UUID | Enregistrer un instantané avec `ctx.side_effect(...)` ou utiliser une activité. | +| Lire l’horloge, `thread_rng` ou un nouvel UUID | `ctx.replay_now()` pour l'heure métier ; enregistrez les autres valeurs avec `ctx.side_effect(...)` ou utilisez une activité. | | `tokio::time::sleep` ou `std::thread::sleep` | `ctx.sleep(...)` ou `ctx.start_timer(...)`. | | `tokio::select!` ou mise en concurrence de futures ordinaires | `ctx.select(...)` ou `ctx.select_keyed(...)`. | | Appels durables concurrents non suivis | `ctx.parallel(...)` avec un ordre d’entrée stable. | diff --git a/i18n/fr/source-hashes.json b/i18n/fr/source-hashes.json index 3e58ba988e9..d6604d94ee5 100644 --- a/i18n/fr/source-hashes.json +++ b/i18n/fr/source-hashes.json @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", - "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", + "polyglot/php.md": "30bee275e7691445566784511af53809fa1045c27c4fcc067fa2da0b6cfb1898", + "polyglot/polling-patterns.md": "19b971e63c3ae65d213250472a1f468a2d5d7a6e1b71dccfc8ae2ac54681ba67", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", - "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", + "polyglot/python.md": "dbef23a26f6dcb75cb37f8b0fe716913a33aa483c35e3bc718caf207464cf4b7", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", + "polyglot/rust.md": "8c5612748e0ea83423d20f912072242c1b2a149e7e3e9a26e28ef7175c818622", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md index 481bea4c4d2..4bce020f833 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -239,6 +239,26 @@ $receipt = $ctx->activity('payments.capture', [$orderId], [ (`^2.72.6|^3.8.4`)が必須の依存関係として追加されたため、期間は組み込みパッケージと同じパーサーで変換されます。 すべての単位は [PHP SDK の期間指定リファレンス](https://php.durable-workflow.com/build/workflows-activities/#durations)に記載されています。 +## リプレイ安全なワークフロー時刻 {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` は、リプレイ安全な UTC のビジネス時刻を +`DateTimeImmutable` として返します。通常のエントリーでは、タスクの +`replay_clock`(Server 3.6.0 以降)に含まれる実行の開始時刻(再駆動の後続実行では元の実行の開始時刻)です。サポートされる +消費済み永続ステップ(アクティビティ、タイマー、子ワークフロー、条件待機、 +検証済みグループ)の後は、そのステップの記録時刻です。永続ステップの間で繰り返し +読み取っても同じ値が返り、どのリプレイでも同じ値が返ります。 + +SDK が時刻を証明できない場合は +`DurableWorkflow\Exception\ReplayClockUnavailable` を送出します。これには +サイドエフェクト、バージョンマーカー、ローカルアクティビティが含まれ、Core が +永続化された時刻を定義するまで利用できません。こうしたステップの直後の時計の +読み取りは、ランナー間や混在フリートで移植可能ではありません +([インラインステップ直後の時計の読み取りは移植可能ではない](./python.md#inline-step-clock-reads)を参照)。 +クエリハンドラーと更新ハンドラーは +履歴のスナップショットを読み、ワークフロー本体を再構築しません。完全な一覧、 +リリース状況、アップグレードの注意点は +[SDK 共通の時計セマンティクス](./python.md#advancing-replay-clock)を参照してください。 + ## エントリの互換性と復旧 {#entry-compatibility-and-recovery} **公開済みのサポートです。** PHP SDK 2.5.4 で以下のエントリ保護が導入され、Server 2.9.9 でルーティングと復旧がサポートされました。これらは機能の最小対応バージョンです。セキュリティ修正を含む最新の安定版をインストールしてください。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md index 4b19e131df0..6eeee9f8645 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ class PollDemo: 両方の例を公開済みの Server **2.9.7 / Core 2.7.2** と通常インストールした Python **2.6.1**、テスト入力 `[2, 1]` で実行しました。どちらも2つの run にまたがって2回の実際の確認を完了しました。Continue-as-new は run の履歴を新しくし、run とリンクのコストを追加しますが、実行全体の元の期限は維持します。寿命が無制限になるわけではありません。 -ここでは相対的な永続待機を使用します。Python の進む時計と、リプレイ時にも安定した履歴予算の読み取りは、それぞれ[時計](https://github.com/durable-workflow/.github/issues/215)と[予算](https://github.com/durable-workflow/workflow/issues/859)の別の課題です。このレシピは `ctx.now()` や再計算した履歴長で分岐しません。`DW_MAX_HISTORY_EVENTS` を強制的な自動切り替えとして扱わないでください。この不足は [Server #504](https://github.com/durable-workflow/server/issues/504) で追跡しています。 +ここでは相対的な永続待機を使用します。`ctx.replay_now()`(Python SDK 2.15.0 以降)は消費した永続ステップとともに進み、Python SDK 2.24.0 からはエントリーでも値を持ちます([進行するリプレイ時計](./python.md#advancing-replay-clock)を参照)。リプレイ時にも安定した履歴予算の読み取りは、引き続き[予算](https://github.com/durable-workflow/workflow/issues/859)の別の課題です。このレシピは `ctx.now()` や再計算した履歴長で分岐しません。`DW_MAX_HISTORY_EVENTS` を強制的な自動切り替えとして扱わないでください。この不足は [Server #504](https://github.com/durable-workflow/server/issues/504) で追跡しています。 ## 中断して外部状態を照合する {#interrupt-and-reconcile} diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/python.md b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/python.md index f2d20aafab2..c74e8d6ac0c 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/python.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/python.md @@ -627,6 +627,7 @@ Server がルーティングするクエリでは、Worker は元のクエリ期 | `ctx.upsert_search_attributes(attrs)` | 検索属性を更新する | | `ctx.continue_as_new(*args)` | 新しい入力でワークフローを再開する | | `ctx.now()` | 永続化されたワークフロー開始時刻。この実行中は固定 | +| `ctx.replay_now()` | 進行するリプレイ安全な UTC 時刻。エントリーでは実行の開始時刻、その後は消費した各永続ステップの記録時刻 | | `ctx.random()` | シード付き乱数生成器 | | `ctx.uuid4()` | 決定的な UUID | | `ctx.logger` | リプレイ中は出力しないロガー | @@ -695,6 +696,102 @@ continue-as-new に引き継ぐ必要がある場合は、Server の元の実行 異なるプロセスやホストの単調時計の値を引き算したりしないでください。 Python で `ctx.now()` 同士を引いても、実処理時間や実時間での経過時間にはなりません。 +#### 進行するリプレイ時計 {#advancing-replay-clock} + +`ctx.replay_now()` は、消費した履歴とともに進む追加の UTC 時計です。Rust +(`WorkflowContext::replay_now()`) と PHP サービスモード +(`WorkflowContext::replayNow()`) の SDK も同じ時計を提供します。 + +- 通常のワークフローエントリーでは、永続ステップの前に実行の正規の開始時刻(再駆動の後続実行では元の実行の開始時刻)を + 返します。Server 3.6.0 以降は、この時刻を各ワークフロータスクに + `replay_clock` として送ります。履歴の挿入時刻、ディスパッチ時刻、リース時刻が + 代わりに使われることはありません。 +- サポートされる永続ステップの後は、そのステップの記録時刻を返します。対象は + すべての SDK のアクティビティ、タイマー、子ワークフローに加え、SDK が対応する + シグナル待機と条件待機、および検証済みグループです。 +- 永続ステップの間で繰り返し読み取っても同じ値が返り、実行のどのリプレイでも同じ値が返ります。この時計の単調性は保証されません。後で証明された境界が、より早い記録時刻を持つことがあります。 + +そのため、永続タイマーを囲む期限ループは終了し、2 つの永続ステップの後の +読み取り値の差は、記録された経過時間を表します。 + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +SDK が時刻を証明できない場合、`ctx.replay_now()` は他の時刻を使わずに +`ReplayClockUnavailable` を送出します。 + +- キャリアのないタスクでのエントリー: 3.6.0 より前の Server、または Server が + 開始時刻を証明できない実行。 +- サイドエフェクト、バージョンマーカー、メモと検索属性の更新、ローカル + アクティビティなどのインライン操作とローカル操作の後。Core がこれらのステップの永続化された時刻を + 定義するまで利用できません。 +- その他のグループモードの後、キャンセルスコープ内。 +- クエリハンドラー内: PHP では常に利用できません。Python と Rust では、クエリ対象の履歴がサポートされるスカラー境界で終わる場合を除き利用できません(グループ化された境界ではクエリ時刻は得られません)。 + +処理されない `ReplayClockUnavailable` は、他の例外と同様にワークフローを +失敗させます。 + +##### インラインステップ直後の時計の読み取りは移植可能ではない {#inline-step-clock-reads} + +インラインステップとは、サイドエフェクト、バージョンマーカー、メモと検索属性の +更新、ローカルアクティビティです。Core がこれらの永続化された時刻を定義するまで、 +これらの直後に時計を読み取った結果は、ランナー間や混在フリートで移植可能では +ありません。 + +- サービスモードの SDK(Python、Rust、PHP SDK)は、その位置で時計を利用不可として + 報告します。 +- 組み込みエンジンでは、`Workflow::now()` はそのステップの記録時刻に移ります。 +- 外部ワーカーランナー(組み込みパッケージのワーカープロトコル用 + `WorkflowFiberRunner` で、外部 PHP ワーカーがブリッジ経由で使用します)では、 + サイドエフェクト、メモと検索属性の更新、バージョンマーカーはすべて同じように + 動作します。初回実行では直前の境界の時刻を保ち、リプレイではそのステップの + 記録時刻を読み取ります。バージョンマーカーについては、この差異を意図的に + 残しています。固定されたリプレイフィクスチャ + `repeated-version-legacy-clock-boundaries` を置き換えると、すでに進行中の実行の + リプレイ出力が変わるためです。 +- そのため、初回実行が外部ワーカーランナーで行われた場合(外部ワーカーだけの + フリートを含む)や、実行がランナー間を移動する可能性がある場合には、読み取り + 結果が食い違います。組み込みと外部の初回実行は異なる時刻を読み取るためです。 + +インラインステップの直後の時計の読み取りに依存しないでください。時計は次の +永続ステップの後で読み取ってください。 + +Python と Rust は、クエリや受け入れ前の更新検証に応答するために履歴から +ワークフローを再構築します。再構築したワークフローがエントリーで時計を読み、 +タスクに `replay_clock` がない場合(3.30.0 より前の Server は +これらのタスクに送りません)、クエリや検証は、ワークフロータスクが計算して +いない状態で応答する代わりに失敗します。PHP SDK は、クエリや更新のために +ワークフロー本体を再構築しません。 + +オフラインリプレイ(`replay()`、`Replayer.replay()`、`replay_history()`)は、タスクのオブジェクトを `replay_clock_entry` として受け取ります。メモリ内の `WorkflowEnvironment` はキャリアを提供しないため、そこではエントリーの読み取りは利用できません。 + +**リリース状況。** エントリー値(3 つの SDK すべて)と、クエリおよび検証のルール(Python と Rust)は、Python SDK 2.24.0、 +Rust SDK 4.25.0、PHP SDK 3.32.0 で提供され、Server 3.6.0 以降が必要です。クエリと検証の +タスクに載るキャリアは、Server 3.30.0 で提供されます。組み込みパッケージの +Worker プロトコルランナー(`WorkflowFiberRunner`)は Workflow 2.42.0 からキャリアを +受け取ります。ランナーを構築するコードがキャリアを渡すと、エントリーでの +`Workflow::now()` は実行の正規の開始時刻を返します。それより前の SDK +リリースは、エントリーを利用不可として報告します。 + +**アップグレード。** エントリーの読み取りが利用不可かどうかで分岐するコードを +持つ実行中のワークフロー(たとえば `ReplayClockUnavailable` を捕捉するもの)は、 +アップグレード後、新旧のワーカーが混在するローリングデプロイ中、または Server を 3.6.0 にアップグレードした後のリプレイで別の分岐を通ります。そのようなコードは +`ctx.get_version(...)` の背後に置くか、先にそれらの実行を完了させてください。 +`ctx.now()` は固定の開始時刻を保つため、それを読む実行は変わらずリプレイされます。 + #### SDK 間の時計の違い {#clock-differences-across-sdks} これらの API は、提供されている場合には決定的ですが、共通の時計ではありません。 @@ -702,16 +799,18 @@ Python で `ctx.now()` 同士を引いても、実処理時間や実時間での | 記述インターフェース | 繰り返し呼び出しと永続的なステップ | continue-as-new の後続実行 | | --- | --- | --- | | Python `ctx.now()` | タイマーやアクティビティの後も、この実行の永続化された開始時刻に固定されます。 | 後続実行の開始時刻を基準にします。 | +| Python `ctx.replay_now()` | 実行の開始時刻から始まり、サポートされる消費済みステップごとの記録時刻へ進みます。[進行するリプレイ時計](#advancing-replay-clock)を参照してください。 | 後続実行自身の開始時刻から始まります。 | | 組み込み PHP `Workflow::now()` | 実行の開始時刻から始まり、リプレイが消費したイベントの記録時刻へ進みます。[ワークフロー時刻](../features/timers.md#reading-deterministic-time)を参照してください。 | 新しい実行から始まり、その実行で消費したイベントに沿って進みます。 | -| サービスモードの PHP SDK | 汎用の公開ワークフローヘルパー `now()` はありません。永続的な操作か、記録済みのアクティビティ/副作用の値を使います。 | 引き継ぎ後も必要なアプリケーションの時刻状態は、明示的に渡します。 | -| サービスモードの Rust SDK | 汎用の公開ヘルパー `WorkflowContext::now()` はありません。`side_effect` で小さな実時間時計のスナップショットを記録できますが、進む時計ではありません。 | 新しい実行の副作用は新しい操作です。以前の時刻状態が必要なら明示的に渡します。 | +| PHP サービスモード `WorkflowContext::replayNow()` | Python の `ctx.replay_now()` と同じセマンティクスです。 | 後続実行自身の開始時刻から始まります。 | +| Rust サービスモード `WorkflowContext::replay_now()` | Python の `ctx.replay_now()` と同じセマンティクスです。 | 後続実行自身の開始時刻から始まります。 | -組み込み PHP の動作は -[公開済み Core](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php) -にあります。別の [PHP SDK コンテキスト](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -と [Rust SDK コンテキスト](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -には独自の API があります。すべての SDK で時計ヘルパーの意味が同じだと仮定せず、 -永続的な操作と期限ポリシーを移植してください。 +サービスモードの時計は 1 つの契約を共有します。組み込み版の +`Workflow::now()` は、サイドエフェクトなどのインラインステップの +記録時刻にも移りますが、サービスモードの時計はその時刻を利用不可として報告します。 +そのため、この読み取りは移植可能ではありません +([インラインステップ直後の時計の読み取りは移植可能ではない](#inline-step-clock-reads)を参照)。 +すべての時計ヘルパーが同じように動作すると仮定せず、永続操作と期限ポリシーを +移植してください。 #### 発行イベントをシーケンス値で順序付けする {#order-emitted-events-with-sequence-values} @@ -725,6 +824,8 @@ continue-as-new で明示的に引き継ぎます。独立したストリーム 全体的な順序が得られるわけではありません。 +永続ステップの間で `ctx.replay_now()` を繰り返し読み取っても 1 つの値しか返らないため、これもイベントの順序付けには使わないでください。 + ### アクティビティの再試行とタイムアウト {#activity-retries-and-timeouts} アクティビティ呼び出しに、既定の単一試行とは異なる再試行上限や期限が必要な場合、`ctx.schedule_activity(...)` の `ActivityRetryPolicy` とタイムアウトのキーワード引数を使います。 diff --git a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md index 50a15cf9ab7..97e855b34aa 100644 --- a/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/ja/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -661,6 +661,26 @@ Rust SDK 4.17.0 はワークフローコードからの観測に `ctx.logger().i [公開済みロギングガイド](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging)、[WorkflowLogger API](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html)、[WorkflowReplayState API](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html)を参照してください。[registry からの lifecycle/deadline 検証](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853)と[4プロセスのロギング受入検証](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262)は、明記された native Server 3.10.0 linux/amd64 の組合せで記録されました。他の binding や、より広い replay/producer の適格性は別の範囲です。 +## リプレイ安全なワークフロー時刻 {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` は、リプレイ安全な UTC のビジネス時刻を +`Result>` として返します。通常のエントリーでは、タスクの +`replay_clock`(Server 3.6.0 以降)に含まれる実行の開始時刻(再駆動の後続実行では元の実行の開始時刻)です。サポートされる +消費済み永続ステップ(アクティビティ、タイマー、子ワークフロー、シグナル待機と +条件待機、検証済みグループ)の後は、そのステップの記録時刻です。永続ステップの +間で繰り返し読み取っても同じ値が返り、どのリプレイでも同じ値が返ります。 + +SDK が時刻を証明できない場合は `Error::ReplayClockUnavailable` を返します。 +これにはインライン操作とローカル操作(サイドエフェクト、バージョンマーカー、 +ローカルアクティビティ、メモ)が含まれ、Core が永続化された時刻を定義するまで +利用できません。こうしたステップの直後の時計の読み取りは、ランナー間や混在 +フリートで移植可能ではありません +([インラインステップ直後の時計の読み取りは移植可能ではない](./python.md#inline-step-clock-reads)を参照)。 +オフラインリプレイでは +`WorkflowHistory::replay_clock(carrier)` でキャリアを渡します。完全な一覧、 +クエリと検証のルール、リリース状況、アップグレードの注意点は +[SDK 共通の時計セマンティクス](./python.md#advancing-replay-clock)を参照してください。 + ## Rust の決定性ルール {#rust-determinism-rules} リプレイでは、記録済みの入力と履歴に対して、同じ順序で同じ永続コマンドを生成する必要があります。Rust の通常のコレクション、時計、並行処理のプリミティブは、この契約を自動では保ちません。 @@ -668,7 +688,7 @@ Rust SDK 4.17.0 はワークフローコードからの観測に `ctx.logger().i | ワークフローコードのパターン | 永続的な代替手段 | | --- | --- | | `HashMap` を走査しながらスケジュール | 先にキーをソートするか、`BTreeMap` を使用します。 | -| システム時刻、`thread_rng`、新しい UUID | `ctx.side_effect(...)` でスナップショットを記録するか、アクティビティを使用します。 | +| システム時刻、`thread_rng`、新しい UUID | ビジネス時刻には `ctx.replay_now()` を使い、その他の値は `ctx.side_effect(...)` で記録するか、アクティビティを使用します。 | | `tokio::time::sleep` または `std::thread::sleep` | `ctx.sleep(...)` または `ctx.start_timer(...)`。 | | `tokio::select!` または通常の future の競合 | `ctx.select(...)` または `ctx.select_keyed(...)`。 | | 追跡されない並行の永続呼び出し | 安定した入力順序で `ctx.parallel(...)`。 | diff --git a/i18n/ja/source-hashes.json b/i18n/ja/source-hashes.json index 3e58ba988e9..d6604d94ee5 100644 --- a/i18n/ja/source-hashes.json +++ b/i18n/ja/source-hashes.json @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", - "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", + "polyglot/php.md": "30bee275e7691445566784511af53809fa1045c27c4fcc067fa2da0b6cfb1898", + "polyglot/polling-patterns.md": "19b971e63c3ae65d213250472a1f468a2d5d7a6e1b71dccfc8ae2ac54681ba67", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", - "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", + "polyglot/python.md": "dbef23a26f6dcb75cb37f8b0fe716913a33aa483c35e3bc718caf207464cf4b7", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", + "polyglot/rust.md": "8c5612748e0ea83423d20f912072242c1b2a149e7e3e9a26e28ef7175c818622", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md index 966538739be..30a7c8afe65 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -334,6 +334,28 @@ mesmo parser do pacote embarcado. A [referência de durações do SDK PHP](https://php.durable-workflow.com/build/workflows-activities/#durations) lista todas as unidades. +## Horário do workflow seguro para replay {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` retorna o horário de negócio UTC seguro para +replay como `DateTimeImmutable`. Na entrada normal, é o início do run (para um sucessor de redrive, o início do run original) vindo do +`replay_clock` da tarefa (Server 3.6.0 e posteriores). Depois de cada passo +durável consumido compatível (atividades, temporizadores, workflows filhos, +esperas de condições, grupos validados), é o horário registrado desse passo. +Leituras repetidas entre passos duráveis retornam o mesmo valor, e cada replay +retorna os mesmos valores. + +Quando o SDK não consegue comprovar o horário, ele lança +`DurableWorkflow\Exception\ReplayClockUnavailable`. Isso inclui efeitos +colaterais, marcadores de versão e atividades locais, que continuam +indisponíveis até que o Core defina um horário persistido para eles. Uma +leitura do relógio logo depois de um desses passos não é portável entre runners +nem em frotas mistas; veja +[Leituras do relógio após passos inline não são portáveis](./python.md#inline-step-clock-reads). +Handlers de consultas e atualizações leem snapshots do histórico e nunca reconstroem o +corpo do workflow. Veja a +[semântica de relógio entre SDKs](./python.md#advancing-replay-clock) para a +lista completa, o status de lançamento e a nota de atualização. + ## Compatibilidade de entrada e recuperação {#entry-compatibility-and-recovery} **Suporte publicado.** O SDK PHP 2.5.4 introduziu a proteção de entrada abaixo, com roteamento e recuperação no Server 2.9.9. Essas são as versões mínimas para esses recursos; instale as versões estáveis atuais para receber correções de segurança. diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md index 77c531dc383..76a738dc8b7 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ Registre `PollDemo` e `check_status` no mesmo [worker Python](./python.md), depo Os dois exemplos foram executados nas versões publicadas Server **2.9.7 / Core 2.7.2**, com Python **2.6.1** instalado normalmente e entrada de teste `[2, 1]`. Ambos concluíram duas consultas reais em duas execuções. Continue-as-new reinicia o histórico da execução, acrescenta custos de execução e vínculo e preserva o prazo original da execução lógica. Isso não oferece duração ilimitada. -Use esperas duráveis relativas. O avanço do relógio Python e as leituras de orçamento do histórico estáveis durante a reprodução continuam sendo trabalhos separados de [relógio](https://github.com/durable-workflow/.github/issues/215) e [orçamento](https://github.com/durable-workflow/workflow/issues/859). Esta receita não decide com base em `ctx.now()` nem no tamanho recalculado do histórico. Não trate `DW_MAX_HISTORY_EVENTS` como uma transição automática obrigatória: [Server #504](https://github.com/durable-workflow/server/issues/504) acompanha essa lacuna. +Use esperas duráveis relativas. `ctx.replay_now()` (SDK Python 2.15.0+) avança com os passos duráveis consumidos e, a partir do SDK Python 2.24.0, também tem um valor na entrada (veja [Relógio de replay que avança](./python.md#advancing-replay-clock)); as leituras de orçamento do histórico estáveis durante a reprodução continuam sendo um trabalho separado de [orçamento](https://github.com/durable-workflow/workflow/issues/859). Esta receita não decide com base em `ctx.now()` nem no tamanho recalculado do histórico. Não trate `DW_MAX_HISTORY_EVENTS` como uma transição automática obrigatória: [Server #504](https://github.com/durable-workflow/server/issues/504) acompanha essa lacuna. ## Interrompa e reconcilie {#interrupt-and-reconcile} diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/python.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/python.md index 29fde00f888..0afc09e9a32 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/python.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/python.md @@ -785,6 +785,7 @@ O `WorkflowContext` passado a `run` fornece operações determinísticas: | `ctx.upsert_search_attributes(attrs)` | Atualiza atributos de busca | | `ctx.continue_as_new(*args)` | Reinicia o workflow com nova entrada | | `ctx.now()` | Horário de início persistido do workflow, fixo durante este run | +| `ctx.replay_now()` | Horário UTC seguro para replay que avança: o início do run na entrada e depois o horário registrado de cada passo durável consumido | | `ctx.random()` | Gerador aleatório com semente | | `ctx.uuid4()` | UUID determinístico | | `ctx.logger` | Logger silencioso durante replay | @@ -858,6 +859,107 @@ registrado. Nunca compare horários UTC com valores monotônicos nem subtraia leituras monotônicas de processos ou hosts diferentes. Subtrair `ctx.now()` não mede tempo de processamento ativo nem tempo de parede decorrido em Python. +#### Relógio de replay que avança {#advancing-replay-clock} + +`ctx.replay_now()` é um relógio UTC adicional que avança com o histórico +consumido. Os SDKs de Rust (`WorkflowContext::replay_now()`) e de PHP no modo +de serviço (`WorkflowContext::replayNow()`) oferecem o mesmo relógio. + +- Na entrada normal do workflow, antes de qualquer passo durável, ele retorna o + início canônico do run (para um sucessor de redrive, o início do run original). O Server 3.6.0 e versões posteriores enviam esse + instante em cada tarefa de workflow como `replay_clock`. Os horários de + inserção no histórico, de despacho e de lease nunca são usados no lugar dele. +- Depois de um passo durável compatível, ele retorna o horário registrado desse + passo: atividades, temporizadores e workflows filhos em todos os SDKs, esperas + de sinais e condições onde o SDK as suporta, e grupos validados. +- Leituras repetidas entre passos duráveis retornam o mesmo valor, e cada replay do run retorna os mesmos valores. Não há garantia de que o relógio seja monotônico: um limite comprovado posterior pode trazer um horário registrado anterior. + +Por isso, um loop com prazo em torno de um temporizador durável termina, e a +diferença entre leituras feitas após dois passos duráveis mede o tempo +decorrido registrado entre eles: + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +Quando o SDK não consegue comprovar o horário, `ctx.replay_now()` lança +`ReplayClockUnavailable` em vez de usar qualquer outro horário: + +- na entrada com uma tarefa sem portador: Servers anteriores ao 3.6.0, ou um + run cujo início o Server não consegue comprovar; +- depois de operações inline e locais, como efeitos colaterais, marcadores de + versão, atualizações de memo e de atributos de pesquisa, e atividades locais. + Elas continuam indisponíveis até que o Core defina um horário persistido para + esses passos; +- depois de outros modos de grupo e em escopos de cancelamento; +- em handlers de consulta: sempre no PHP, e no Python e no Rust a menos que o histórico consultado termine em um limite escalar compatível (limites agrupados não fornecem horário de consulta). + +Um `ReplayClockUnavailable` não tratado faz o workflow falhar como qualquer +outra exceção. + +##### Leituras do relógio após passos inline não são portáveis {#inline-step-clock-reads} + +Passos inline são efeitos colaterais, marcadores de versão, atualizações de memo +e de atributos de pesquisa, e atividades locais. Até que o Core defina um +horário persistido para eles, uma leitura do relógio logo depois de um deles não +é portável entre runners nem em frotas mistas: + +- Os SDKs do modo de serviço (Python, Rust e o SDK de PHP) informam o relógio + como indisponível nesse ponto. +- No motor embutido, `Workflow::now()` passa para o horário registrado do passo. +- No runner de workers externos (o `WorkflowFiberRunner` do protocolo de workers + do pacote embutido, que workers PHP externos usam por meio do bridge), efeitos + colaterais, atualizações de memo e de atributos de pesquisa e marcadores de + versão se comportam da mesma forma: uma primeira execução mantém o horário do + limite anterior, enquanto um replay lê o horário registrado do passo. Nos + marcadores de versão, essa divergência é mantida de propósito: substituir o + fixture de replay fixado `repeated-version-legacy-clock-boundaries` mudaria a + saída do replay de runs que já estão em andamento. +- Por isso, a leitura diverge sempre que a primeira execução rodou no runner de + workers externos, inclusive em uma frota só de workers externos, e sempre que + um run puder passar de um runner para outro, porque primeiras execuções + embutidas e externas leem horários diferentes. + +Não dependa de uma leitura do relógio logo depois de um passo inline: leia o +relógio depois do próximo passo durável. + +Python e Rust reconstroem o workflow a partir do histórico para responder a uma +consulta ou a uma validação de atualização antes da aceitação. Se o workflow +reconstruído ler o relógio na entrada e a tarefa não tiver `replay_clock` (os +Servers anteriores à 3.30.0 nunca o enviam nessas tarefas), a +consulta ou a validação falha em vez de responder com um estado que a tarefa de +workflow nunca calculou. O SDK de PHP nunca reconstrói o corpo do workflow para +consultas ou atualizações. + +O replay offline (`replay()`, `Replayer.replay()`, `replay_history()`) recebe o objeto da tarefa como `replay_clock_entry`. O `WorkflowEnvironment` em memória não fornece portador, então leituras na entrada ficam indisponíveis nele. + +**Status de lançamento.** O valor de entrada (os três SDKs) e a regra para consultas e validações (Python e Rust) chegam no SDK Python 2.24.0, no SDK Rust 4.25.0 e no SDK PHP 3.32.0 e exigem +Server 3.6.0 ou posterior. O portador nas tarefas de consulta e validação chega +no Server 3.30.0. O runner do protocolo de workers do pacote embarcado +(`WorkflowFiberRunner`) aceita o portador a partir do Workflow 2.42.0: quando o +código que constrói o runner o repassa, `Workflow::now()` na entrada retorna o +início canônico da execução. Versões anteriores dos SDKs informam a entrada +como indisponível. + +**Atualização.** Um workflow em execução cujo código se ramifica conforme a +leitura de entrada esteja indisponível, por exemplo capturando +`ReplayClockUnavailable`, segue o outro ramo no replay depois da atualização, durante um deploy gradual que mistura workers antigos e novos, ou depois de atualizar o Server para 3.6.0. +Coloque esse código atrás de `ctx.get_version(...)` ou deixe esses runs +terminarem antes. `ctx.now()` mantém seu horário de início fixo, então os runs +que o leem fazem replay sem mudanças. + #### Diferenças entre os relógios dos SDKs {#clock-differences-across-sdks} Essas APIs são determinísticas quando disponíveis, mas não compartilham um único relógio: @@ -865,16 +967,17 @@ Essas APIs são determinísticas quando disponíveis, mas não compartilham um | Superfície de autoria | Chamadas repetidas e etapas duráveis | Sucessor continue-as-new | | --- | --- | --- | | Python `ctx.now()` | Fixo no horário de início persistido deste run, inclusive depois de um temporizador ou atividade. | Usa a referência inicial do run sucessor. | +| Python `ctx.replay_now()` | Começa no início do run e avança para o horário registrado de cada passo consumido compatível. Veja [Relógio de replay que avança](#advancing-replay-clock). | Começa no início próprio do run sucessor. | | PHP embutido `Workflow::now()` | Começa no início do run e avança para o horário registrado do evento consumido pelo replay. Veja [tempo do workflow](../features/timers.md#reading-deterministic-time). | Começa com o novo run e avança pelos eventos consumidos desse run. | -| SDK PHP no modo serviço | Sem um helper público geral `now()` para workflows. Use operações duráveis ou valores registrados de atividades ou efeitos colaterais. | Passe explicitamente o estado temporal da aplicação se ele precisar sobreviver à transferência. | -| SDK Rust no modo serviço | Sem um helper público geral `WorkflowContext::now()`. Um `side_effect` pode registrar uma pequena leitura do relógio de parede; ele não é um relógio que avança. | Um efeito colateral no novo run é uma nova operação; passe explicitamente o estado temporal anterior se necessário. | +| PHP no modo de serviço `WorkflowContext::replayNow()` | A mesma semântica de Python `ctx.replay_now()`. | Começa no início próprio do run sucessor. | +| Rust no modo de serviço `WorkflowContext::replay_now()` | A mesma semântica de Python `ctx.replay_now()`. | Começa no início próprio do run sucessor. | -O comportamento do PHP embutido está no -[Core publicado](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php). -Os contextos separados do [SDK PHP](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -e do [SDK Rust](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -têm APIs próprias. Porte a operação durável e a política de prazos sem supor -que um helper de relógio tenha a mesma semântica em todos os SDKs. +Os relógios do modo de serviço compartilham um contrato. `Workflow::now()` embutido também passa para o horário registrado de um passo +inline, como um efeito colateral, onde os relógios do modo de serviço informam +o horário como indisponível, então essa leitura não é portável (veja +[Leituras do relógio após passos inline não são portáveis](#inline-step-clock-reads)). +Leve a operação durável e a política de prazo em +vez de presumir que todo helper de relógio se comporta igual. #### Ordene eventos emitidos com valores de sequência {#order-emitted-events-with-sequence-values} @@ -888,6 +991,8 @@ precisar de uma sequência lógica única. Streams ou runs independentes não ganham uma ordem global a partir de seus horários. +Leituras repetidas de `ctx.replay_now()` entre passos duráveis também retornam um único valor; portanto, também não o use para ordenar eventos. + ### Novas tentativas e timeouts de atividades {#activity-retries-and-timeouts} Use `ActivityRetryPolicy` e argumentos nomeados de timeout em diff --git a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md index 4739449457a..0c836c13356 100644 --- a/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/pt-BR/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -883,6 +883,27 @@ Mantenha a ordem de comandos duráveis independente desse estado de observação Veja o [guia publicado de logging](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging), a [API WorkflowLogger](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html) e a [API WorkflowReplayState](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html). Os [controles de lifecycle/deadline do registro](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853) e a [aceitação de logging com quatro processos](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262) foram registrados na tupla nomeada native Server 3.10.0 linux/amd64. Outros bindings e qualificações mais amplas de replay/produtor mantêm seus próprios escopos. +## Horário do workflow seguro para replay {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` retorna o horário de negócio UTC seguro para +replay como `Result>`. Na entrada normal, é o início do run (para um sucessor de redrive, o início do run original) vindo do `replay_clock` da tarefa (Server 3.6.0 e posteriores). Depois de cada passo +durável consumido compatível (atividades, temporizadores, workflows filhos, +esperas de sinais e condições, grupos validados), é o horário registrado desse +passo. Leituras repetidas entre passos duráveis retornam o mesmo valor, e cada +replay retorna os mesmos valores. + +Quando o SDK não consegue comprovar o horário, ele retorna +`Error::ReplayClockUnavailable`. Isso inclui operações inline e locais (efeitos +colaterais, marcadores de versão, atividades locais, memos), que continuam +indisponíveis até que o Core defina um horário persistido para elas. Uma +leitura do relógio logo depois de um desses passos não é portável entre runners +nem em frotas mistas; veja +[Leituras do relógio após passos inline não são portáveis](./python.md#inline-step-clock-reads). +O replay offline fornece um portador com `WorkflowHistory::replay_clock(carrier)`. Veja a +[semântica de relógio entre SDKs](./python.md#advancing-replay-clock) para a +lista completa, a regra de consultas e validações, o status de lançamento e a +nota de atualização. + ## Regras de determinismo do Rust {#rust-determinism-rules} Um replay deve produzir os mesmos comandos duráveis, na mesma ordem, para a entrada e o histórico registrados. Coleções, relógios e primitivas de concorrência comuns do Rust não preservam automaticamente esse contrato: @@ -890,7 +911,7 @@ Um replay deve produzir os mesmos comandos duráveis, na mesma ordem, para a ent | Padrão no código do workflow | Substituição durável | | --- | --- | | Agendar durante a iteração de um `HashMap` | Ordene as chaves antes ou use `BTreeMap`. | -| Relógio do sistema, `thread_rng` ou UUID novo | Registre um snapshot com `ctx.side_effect(...)` ou use uma atividade. | +| Relógio do sistema, `thread_rng` ou UUID novo | `ctx.replay_now()` para o horário de negócio; registre outros valores com `ctx.side_effect(...)` ou use uma atividade. | | `tokio::time::sleep` ou `std::thread::sleep` | `ctx.sleep(...)` ou `ctx.start_timer(...)`. | | `tokio::select!` ou disputa de futures comuns | `ctx.select(...)` ou `ctx.select_keyed(...)`. | | Chamadas duráveis concorrentes sem rastreamento | `ctx.parallel(...)` com ordem estável de entrada. | diff --git a/i18n/pt-BR/source-hashes.json b/i18n/pt-BR/source-hashes.json index 3e58ba988e9..d6604d94ee5 100644 --- a/i18n/pt-BR/source-hashes.json +++ b/i18n/pt-BR/source-hashes.json @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", - "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", + "polyglot/php.md": "30bee275e7691445566784511af53809fa1045c27c4fcc067fa2da0b6cfb1898", + "polyglot/polling-patterns.md": "19b971e63c3ae65d213250472a1f468a2d5d7a6e1b71dccfc8ae2ac54681ba67", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", - "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", + "polyglot/python.md": "dbef23a26f6dcb75cb37f8b0fe716913a33aa483c35e3bc718caf207464cf4b7", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", + "polyglot/rust.md": "8c5612748e0ea83423d20f912072242c1b2a149e7e3e9a26e28ef7175c818622", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md index 05d179770e6..9e8dff98b59 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -329,6 +329,26 @@ PHP SDK 3.9.0 додає `nesbot/carbon` (`^2.72.6|^3.8.4`) як обов'язк [Довідник тривалостей PHP SDK](https://php.durable-workflow.com/build/workflows-activities/#durations) перелічує всі одиниці. +## Безпечний для replay час workflow {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` повертає безпечний для replay бізнес-час UTC як +`DateTimeImmutable`. На звичайному вході це початок run (для наступника redrive — початок початкового run) з `replay_clock` +завдання (Server 3.6.0 і новіші). Після кожного підтримуваного спожитого +стійкого кроку (activity, timer, дочірні workflow, очікування умов, перевірені +групи) це записаний час цього кроку. Повторні читання між стійкими кроками +повертають те саме значення, а кожен replay повертає ті самі значення. + +Якщо SDK не може довести час, він викидає +`DurableWorkflow\Exception\ReplayClockUnavailable`. Це стосується побічних +ефектів, маркерів версій і локальних activity, які лишаються недоступними, доки +Core не визначить для них збережений час. Читання годинника одразу після +такого кроку не переноситься між runner і змішаними флотами; див. +[Читання годинника після вбудованих кроків не переносне](./python.md#inline-step-clock-reads). +Обробники query та оновлень читають +знімки історії й ніколи не відновлюють тіло workflow. Повний перелік, стан +випуску та примітку щодо оновлення див. у +[семантиці годинника для всіх SDK](./python.md#advancing-replay-clock). + ## Сумісність входу та відновлення {#entry-compatibility-and-recovery} **Підтримка в опублікованих випусках.** SDK PHP 2.5.4 запровадив наведений нижче захист входу, а Server 2.9.9 додав маршрутизацію та відновлення. Це мінімальні версії для цих можливостей. Установлюйте поточні стабільні випуски, щоб отримувати виправлення безпеки. diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md index 6606175875a..04efadd4931 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ class PollDemo: Обидва приклади виконано на опублікованих Server **2.9.7 / Core 2.7.2**, зі звичайно встановленим Python **2.6.1** та тестовим входом `[2, 1]`. Обидва виконали дві справжні перевірки у двох запусках. Continue-as-new починає нову історію запуску, додає витрати на запуск і зв'язок та зберігає початковий дедлайн виконання. Це не дає необмеженого часу життя. -Тут використовуйте відносні довговічні очікування. Просування годинника Python і стабільне під час відтворення читання бюджету історії залишаються окремими задачами про [годинник](https://github.com/durable-workflow/.github/issues/215) та [бюджет](https://github.com/durable-workflow/workflow/issues/859). Цей рецепт не розгалужується за `ctx.now()` чи повторно обчисленою довжиною історії. Не вважайте `DW_MAX_HISTORY_EVENTS` примусово застосовуваним автоматичним переходом: [Server #504](https://github.com/durable-workflow/server/issues/504) відстежує цю прогалину. +Тут використовуйте відносні довговічні очікування. `ctx.replay_now()` (Python SDK 2.15.0+) просувається разом зі спожитими стійкими кроками, а починаючи з Python SDK 2.24.0 має значення й на вході (див. [Годинник replay, що просувається](./python.md#advancing-replay-clock)); стабільне під час відтворення читання бюджету історії залишається окремою задачею про [бюджет](https://github.com/durable-workflow/workflow/issues/859). Цей рецепт не розгалужується за `ctx.now()` чи повторно обчисленою довжиною історії. Не вважайте `DW_MAX_HISTORY_EVENTS` примусово застосовуваним автоматичним переходом: [Server #504](https://github.com/durable-workflow/server/issues/504) відстежує цю прогалину. ## Переривайте та звіряйте наслідки {#interrupt-and-reconcile} diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/python.md b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/python.md index 02d7c9961a9..1f4173f11e8 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/python.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/python.md @@ -770,6 +770,7 @@ workflow, замість заявляти паритет валідаторів. | `ctx.upsert_search_attributes(attrs)` | Оновлення атрибутів пошуку | | `ctx.continue_as_new(*args)` | Перезапуск workflow з новим вводом | | `ctx.now()` | Збережений час початку workflow, фіксований для цього run | +| `ctx.replay_now()` | Безпечний для replay час UTC, що просувається: на вході — початок run, далі — записаний час кожного спожитого стійкого кроку | | `ctx.random()` | Генератор випадкових чисел зі сталим seed | | `ctx.uuid4()` | Детермінований UUID | | `ctx.logger` | Logger, що мовчить під час replay | @@ -844,6 +845,104 @@ class WaitWithoutClockLoop: `ctx.now()` у Python не вимірює ні активного часу обробки, ні реальної тривалості. +#### Годинник replay, що просувається {#advancing-replay-clock} + +`ctx.replay_now()` — це додатковий годинник UTC, який просувається разом зі +спожитою історією. SDK для Rust (`WorkflowContext::replay_now()`) і для PHP у +сервісному режимі (`WorkflowContext::replayNow()`) надають той самий годинник. + +- На звичайному вході у workflow, до будь-якого стійкого кроку, він повертає + канонічний початок run (для наступника redrive — початок початкового run). Server 3.6.0 і новіші надсилають цю мить із кожним + завданням workflow як `replay_clock`. Час вставлення в історію, диспетчеризації + чи lease ніколи не використовується замість нього. +- Після підтримуваного стійкого кроку він повертає записаний час цього кроку: + activity, timer і дочірні workflow у кожному SDK, очікування сигналів і умов + там, де SDK їх підтримує, а також перевірені групи. +- Повторні читання між стійкими кроками повертають те саме значення, а кожен replay цього run повертає ті самі значення. Монотонність годинника не гарантується: пізніша доведена межа може мати раніший записаний час. + +Тож цикл із крайнім терміном довкола стійкого timer завершується, а різниця між +читаннями після двох стійких кроків вимірює записаний час, що минув між ними: + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +Якщо SDK не може довести час, `ctx.replay_now()` викидає +`ReplayClockUnavailable` замість використання будь-якого іншого часу: + +- на вході із завданням без носія: Server до 3.6.0 або run, початок якого + Server не може довести; +- після вбудованих і локальних операцій, як-от побічні ефекти, маркери версій, + оновлення memo й атрибутів пошуку та локальні activity. Вони лишаються + недоступними, доки Core не визначить для цих кроків збережений час; +- після інших режимів груп і в областях скасування; +- в обробниках query: завжди в PHP, а в Python і Rust — якщо запитувана історія не закінчується на підтримуваній скалярній межі (згруповані межі не дають часу для query). + +Необроблений `ReplayClockUnavailable` спричиняє збій workflow, як і будь-який +інший виняток. + +##### Читання годинника після вбудованих кроків не переносне {#inline-step-clock-reads} + +Вбудовані кроки — це побічні ефекти, маркери версій, оновлення memo й атрибутів +пошуку та локальні activity. Доки Core не визначить для них збережений час, +читання годинника одразу після такого кроку не переноситься між runner і не +працює однаково в змішаних флотах: + +- SDK сервісного режиму (Python, Rust і PHP SDK) повідомляють, що годинник там + недоступний. +- У вбудованому рушії `Workflow::now()` переходить до записаного часу кроку. +- У runner зовнішніх worker (`WorkflowFiberRunner` протоколу worker із + вбудованого пакета, який зовнішні PHP worker використовують через bridge) + побічні ефекти, оновлення memo й атрибутів пошуку та маркери версій + поводяться однаково: перше виконання зберігає час попередньої межі, тоді як + replay читає записаний час кроку. Для маркерів версій цю розбіжність залишено + свідомо: заміна закріпленого replay-фікстура + `repeated-version-legacy-clock-boundaries` змінила б результат replay для run, + які вже виконуються. +- Тому результат читання відрізняється щоразу, коли перше виконання відбулося в + runner зовнішніх worker, зокрема у флоті лише із зовнішніх worker, і щоразу, + коли run може переходити між runner, бо перші виконання у вбудованому та + зовнішньому runner читають різний час. + +Не покладайтеся на читання годинника одразу після вбудованого кроку: читайте +годинник після наступного стійкого кроку. + +Python і Rust відновлюють workflow з історії, щоб відповісти на query або на +перевірку оновлення до прийняття. Якщо відновлений workflow читає годинник на +вході, а завдання не має `replay_clock` (Server до 3.30.0 +ніколи не надсилають його в цих завданнях), query чи перевірка завершується +помилкою замість відповіді станом, якого завдання workflow ніколи не обчислювало. +SDK для PHP ніколи не відновлює тіло workflow для query чи оновлень. + +Офлайн-replay (`replay()`, `Replayer.replay()`, `replay_history()`) приймає об'єкт завдання як `replay_clock_entry`. `WorkflowEnvironment` у пам'яті не надає носія, тож читання на вході там недоступні. + +**Стан випуску.** Значення на вході (усі три SDK) та правило для query і перевірок (Python і Rust) з'являються +в Python SDK 2.24.0, Rust SDK 4.25.0 і PHP SDK 3.32.0 і потребують Server 3.6.0 або +новішого. Носій у завданнях query та перевірки з'являється в Server 3.30.0. +Runner протоколу worker у вбудованому пакеті (`WorkflowFiberRunner`) приймає носій +починаючи з Workflow 2.42.0: щойно код, що створює runner, передає його, +`Workflow::now()` на вході повертає канонічний початок запуску. +Попередні випуски SDK повідомляють, що значення на вході недоступне. + +**Оновлення.** Запущений workflow, код якого розгалужується залежно від того, +чи недоступне читання на вході (наприклад, перехоплюючи +`ReplayClockUnavailable`), після оновлення, під час поступового розгортання зі старими й новими worker або після оновлення Server до 3.6.0 під час replay піде іншою гілкою. +Сховайте такий код за `ctx.get_version(...)` або спершу дочекайтеся завершення +цих run. `ctx.now()` зберігає фіксований час початку, тож run, які його читають, +відтворюються без змін. + #### Відмінності годинників SDK {#clock-differences-across-sdks} Ці API детерміновані, коли вони надаються, але не мають одного спільного годинника: @@ -851,16 +950,17 @@ class WaitWithoutClockLoop: | Інтерфейс написання | Повторні виклики та стійкі кроки | Наступник continue-as-new | | --- | --- | --- | | Python `ctx.now()` | Фіксований збережений час початку цього run, зокрема після timer чи activity. | Використовує початкову часову опору наступного run. | +| Python `ctx.replay_now()` | Починається з початку run і просувається до записаного часу кожного підтримуваного спожитого кроку. Див. [Годинник replay, що просувається](#advancing-replay-clock). | Починається з власного початку наступного run. | | Вбудований PHP `Workflow::now()` | Починає з часу початку run та просувається до записаного часу події, яку спожив replay. Дивіться [час workflow](../features/timers.md#reading-deterministic-time). | Починає з нового run, потім просувається через спожиті події цього run. | -| PHP SDK сервісного режиму | Загального публічного помічника `now()` для workflow немає. Використовуйте стійкі операції або записані результати activity чи побічних ефектів. | Явно передавайте часовий стан застосунку, якщо він має пережити передавання. | -| Rust SDK сервісного режиму | Загального публічного помічника `WorkflowContext::now()` немає. `side_effect` може записати невеликий знімок реального годинника, але не є годинником, що просувається. | Побічний ефект у новому run є новою операцією; за потреби явно передавайте попередній часовий стан. | +| PHP у сервісному режимі `WorkflowContext::replayNow()` | Та сама семантика, що й у Python `ctx.replay_now()`. | Починається з власного початку наступного run. | +| Rust у сервісному режимі `WorkflowContext::replay_now()` | Та сама семантика, що й у Python `ctx.replay_now()`. | Починається з власного початку наступного run. | -Поведінка вбудованого PHP наявна в -[опублікованому Core](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php). -Окремі контексти [PHP SDK](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -та [Rust SDK](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -мають власні API. Переносьте стійку операцію та політику строків замість -припущення однакової семантики помічника годинника в кожному SDK. +Годинники сервісного режиму мають спільний контракт. Вбудований `Workflow::now()` також переходить до записаного часу вбудованого кроку, як-от +побічного ефекту, де годинники сервісного режиму повідомляють, що час +недоступний, тож таке читання не переносне (див. +[Читання годинника після вбудованих кроків не переносне](#inline-step-clock-reads)). +Переносьте стійку операцію та політику крайніх термінів, а не +припускайте, що кожен помічник годинника поводиться однаково. #### Упорядковуйте створені події за послідовністю {#order-emitted-events-with-sequence-values} @@ -874,6 +974,8 @@ class WaitWithoutClockLoop: глобального порядку зі своїх часових позначок. +Повторні читання `ctx.replay_now()` між стійкими кроками також повертають одне значення, тож не використовуйте його і для впорядкування подій. + ### Повторні спроби й тайм-аути activity {#activity-retries-and-timeouts} Використовуйте `ActivityRetryPolicy` і параметри тайм-ауту diff --git a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md index 71b8a0f29ce..c200887c16c 100644 --- a/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/uk/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -892,6 +892,26 @@ Rust SDK 4.17.0 додає `ctx.logger().info("message")` для спостер Дивіться [опублікований посібник журналювання](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging), [API WorkflowLogger](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html) та [API WorkflowReplayState](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html). [Registry-перевірки lifecycle/deadline](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853) і [приймання журналювання з чотирма процесами](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262) записано на вказаному кортежі native Server 3.10.0 linux/amd64. Інші binding та ширша кваліфікація replay/producer зберігають окремі межі. +## Безпечний для replay час workflow {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` повертає безпечний для replay бізнес-час UTC як +`Result>`. На звичайному вході це початок run (для наступника redrive — початок початкового run) з `replay_clock` +завдання (Server 3.6.0 і новіші). Після кожного підтримуваного спожитого +стійкого кроку (activity, timer, дочірні workflow, очікування сигналів і умов, +перевірені групи) це записаний час цього кроку. Повторні читання між стійкими +кроками повертають те саме значення, а кожен replay повертає ті самі значення. + +Якщо SDK не може довести час, він повертає `Error::ReplayClockUnavailable`. Це +стосується вбудованих і локальних операцій (побічні ефекти, маркери версій, +локальні activity, memo), які лишаються недоступними, доки Core не визначить +для них збережений час. Читання годинника одразу після такого кроку не +переноситься між runner і змішаними флотами; див. +[Читання годинника після вбудованих кроків не переносне](./python.md#inline-step-clock-reads). +Офлайн-replay передає носій через +`WorkflowHistory::replay_clock(carrier)`. Повний перелік, правило для query і +перевірок, стан випуску та примітку щодо оновлення див. у +[семантиці годинника для всіх SDK](./python.md#advancing-replay-clock). + ## Правила детермінізму Rust {#rust-determinism-rules} Replay має створювати ті самі durable-команди в тому самому порядку для записаного входу й історії. Звичайні колекції, годинники та примітиви конкурентності Rust не зберігають цей контракт автоматично: @@ -899,7 +919,7 @@ Replay має створювати ті самі durable-команди в то | Шаблон у коді workflow | Durable-заміна | | --- | --- | | Планування під час обходу `HashMap` | Спочатку сортуйте ключі або використовуйте `BTreeMap`. | -| Системний годинник, `thread_rng` чи новий UUID | Записуйте знімок через `ctx.side_effect(...)` або використовуйте activity. | +| Системний годинник, `thread_rng` чи новий UUID | `ctx.replay_now()` для бізнес-часу; інші значення записуйте через `ctx.side_effect(...)` або використовуйте activity. | | `tokio::time::sleep` чи `std::thread::sleep` | `ctx.sleep(...)` або `ctx.start_timer(...)`. | | `tokio::select!` чи перегони звичайних future | `ctx.select(...)` або `ctx.select_keyed(...)`. | | Невідстежувані конкурентні durable-виклики | `ctx.parallel(...)` зі стабільним порядком входів. | diff --git a/i18n/uk/source-hashes.json b/i18n/uk/source-hashes.json index 3e58ba988e9..d6604d94ee5 100644 --- a/i18n/uk/source-hashes.json +++ b/i18n/uk/source-hashes.json @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", - "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", + "polyglot/php.md": "30bee275e7691445566784511af53809fa1045c27c4fcc067fa2da0b6cfb1898", + "polyglot/polling-patterns.md": "19b971e63c3ae65d213250472a1f468a2d5d7a6e1b71dccfc8ae2ac54681ba67", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", - "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", + "polyglot/python.md": "dbef23a26f6dcb75cb37f8b0fe716913a33aa483c35e3bc718caf207464cf4b7", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", + "polyglot/rust.md": "8c5612748e0ea83423d20f912072242c1b2a149e7e3e9a26e28ef7175c818622", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2", diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md index e8979efeefb..7499f182c5c 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/php.md @@ -236,6 +236,19 @@ $receipt = $ctx->activity('payments.capture', [$orderId], [ 至少需要一秒。更早的 SDK 版本只接受秒数。PHP SDK 3.9.0 将 `nesbot/carbon`(`^2.72.6|^3.8.4`)添加为必需依赖,因此时长使用与嵌入式包相同的解析器进行转换。 [PHP SDK 时长参考](https://php.durable-workflow.com/build/workflows-activities/#durations)列出了所有单位。 +## 对重放安全的工作流时间 {#replay-safe-workflow-time} + +`WorkflowContext::replayNow()` 以 `DateTimeImmutable` 返回对重放安全的 UTC +业务时间。在普通入口处,它是任务 `replay_clock`(Server 3.6.0 及更高版本)中的运行开始时间(对重新驱动的后继运行而言,是原始运行的开始时间)。在每个受支持的已消费持久步骤(活动、定时器、子工作流、条件等待、 +经过验证的组)之后,它是该步骤的记录时间。在持久步骤之间重复读取会返回同一个 +值,每次重放都会返回相同的值。 + +当 SDK 无法证明时间时,它会抛出 `DurableWorkflow\Exception\ReplayClockUnavailable`。 +这包括副作用、版本标记和本地活动,在 Core 为其定义持久化时间之前,它们保持 +不可用。紧接在这类步骤之后的时钟读取在不同运行器之间或混合集群中不可移植;参见 +[内联步骤之后的时钟读取不可移植](./python.md#inline-step-clock-reads)。查询处理器和更新处理器读取历史快照,从不重建工作流主体。完整列表、发布 +状态以及升级说明,请参见[跨 SDK 的时钟语义](./python.md#advancing-replay-clock)。 + ## 入口兼容性与恢复 {#entry-compatibility-and-recovery} **已发布支持。** PHP SDK 2.5.4 引入了下述入口保护,Server 2.9.9 提供了配套的路由和恢复支持。这些是相应功能的最低支持版本;请安装当前稳定版本以获取安全修复。 diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md index 0e3f7a166cd..46af81ece4f 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/polling-patterns.md @@ -268,7 +268,7 @@ class PollDemo: 两个示例均已在发布的 Server **2.9.7 / Core 2.7.2** 和正常安装的 Python **2.6.1** 上以测试输入 `[2, 1]` 执行。两者都在两次运行中完成两次真实检查。Continue-as-new 重置单次运行的历史,增加运行与链接开销,并保留整个执行最初的截止时间。它不会提供无限生命周期。 -这里使用相对持久等待。Python 的推进式时钟和重放稳定的历史预算读取,仍分别属于[时钟](https://github.com/durable-workflow/.github/issues/215)与[预算](https://github.com/durable-workflow/workflow/issues/859)任务。本示例不根据 `ctx.now()` 或重新计算的历史长度分支。不要把 `DW_MAX_HISTORY_EVENTS` 当作强制执行的自动切换机制:[Server #504](https://github.com/durable-workflow/server/issues/504) 正在跟踪这一缺口。 +这里使用相对持久等待。`ctx.replay_now()`(Python SDK 2.15.0+)会随已消费的持久步骤前进,从 Python SDK 2.24.0 起在入口处也有值(参见[会前进的重放时钟](./python.md#advancing-replay-clock));重放稳定的历史预算读取仍属于单独的[预算](https://github.com/durable-workflow/workflow/issues/859)任务。本示例不根据 `ctx.now()` 或重新计算的历史长度分支。不要把 `DW_MAX_HISTORY_EVENTS` 当作强制执行的自动切换机制:[Server #504](https://github.com/durable-workflow/server/issues/504) 正在跟踪这一缺口。 ## 中断并核对外部结果 {#interrupt-and-reconcile} diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/python.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/python.md index d995341691a..e797b07f526 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/python.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/python.md @@ -621,6 +621,7 @@ Python Worker 通过向 Server 返回查询任务结果来完成 Server 路由 | `ctx.upsert_search_attributes(attrs)` | 更新搜索属性 | | `ctx.continue_as_new(*args)` | 使用新输入重启工作流 | | `ctx.now()` | 持久化的工作流开始时间,在本次运行内固定 | +| `ctx.replay_now()` | 会前进的、对重放安全的 UTC 时间:入口处为运行的开始时间,之后为每个已消费持久步骤的记录时间 | | `ctx.random()` | 带种子的随机生成器 | | `ctx.uuid4()` | 确定性 UUID | | `ctx.logger` | 重放期间保持静默的日志器 | @@ -682,6 +683,88 @@ HTTP 或 `get_result()` 的等待超时只限制该本地请求,并不能替 绝不要将 UTC 时间戳与单调时钟值比较,也不要对不同进程或主机的单调时钟读数做差。 在 Python 中,对 `ctx.now()` 做差既不能测量有效处理时间,也不能测量实际经过的墙上时间。 +#### 会前进的重放时钟 {#advancing-replay-clock} + +`ctx.replay_now()` 是一个附加的 UTC 时钟,会随已消费的历史前进。Rust +(`WorkflowContext::replay_now()`)和服务模式 PHP +(`WorkflowContext::replayNow()`)SDK 提供相同的时钟。 + +- 在普通工作流入口处、任何持久步骤之前,它返回运行的规范开始时间(对重新驱动的后继运行而言,是原始运行的开始时间)。Server + 3.6.0 及更高版本会在每个工作流任务中以 `replay_clock` 发送该时刻。绝不会改用 + 历史插入时间、派发时间或租约时间。 +- 在受支持的持久步骤之后,它返回该步骤的记录时间:所有 SDK 中的活动、定时器和 + 子工作流,SDK 支持时的信号等待和条件等待,以及经过验证的组。 +- 在持久步骤之间重复读取会返回同一个值,该运行的每次重放都会返回相同的值。该时钟不保证单调:之后被证明的边界可能带有更早的记录时间。 + +因此,围绕持久定时器的截止时间循环会结束,两个持久步骤之后读取值的差可以衡量 +它们之间记录的经过时间: + +```python +from datetime import timedelta + +from durable_workflow import workflow + + +@workflow.defn(name="poll_until_deadline") +class PollUntilDeadline: + def run(self, ctx): + deadline = ctx.replay_now() + timedelta(minutes=10) + while ctx.replay_now() < deadline: + yield ctx.schedule_activity("check_status", []) + yield ctx.start_timer(60) + return "deadline reached" +``` + +当 SDK 无法证明时间时,`ctx.replay_now()` 会抛出 `ReplayClockUnavailable`, +而不会改用任何其他时间: + +- 在入口处且任务没有载体:早于 3.6.0 的 Server,或 Server 无法证明其开始时间的 + 运行; +- 在内联和本地操作之后,例如副作用、版本标记、备忘录和搜索属性更新以及本地 + 活动。在 Core 为这些 + 步骤定义持久化时间之前,它们保持不可用; +- 在其他组模式之后以及取消作用域中; +- 在查询处理器中:PHP 中始终不可用;Python 和 Rust 中,除非所查询的历史以受支持的标量边界结束(分组边界不提供查询时间)。 + +未处理的 `ReplayClockUnavailable` 会像其他任何异常一样使工作流失败。 + +##### 内联步骤之后的时钟读取不可移植 {#inline-step-clock-reads} + +内联步骤是指副作用、版本标记、备忘录和搜索属性更新以及本地活动。在 Core 为它们 +定义持久化时间之前,紧接在这类步骤之后读取时钟,在不同运行器之间或混合集群中 +不可移植: + +- 服务模式 SDK(Python、Rust 和 PHP SDK)在该位置会将时钟报告为不可用。 +- 在嵌入式引擎中,`Workflow::now()` 会移动到该步骤的记录时间。 +- 在外部 worker 运行器(嵌入式包的 worker 协议 `WorkflowFiberRunner`,外部 PHP + worker 通过桥接使用它)中,副作用、备忘录和搜索属性更新以及版本标记的行为 + 相同:首次执行保留上一个边界的时间,而重放读取该步骤的记录时间。对于版本标记, + 这一差异是有意保留的:替换已固定的重放夹具 + `repeated-version-legacy-clock-boundaries` 会改变正在运行中的运行的重放输出。 +- 因此,只要首次执行是在外部 worker 运行器上进行的(包括仅由外部 worker 组成的 + 集群),或者某个运行可能在运行器之间迁移,读取结果就会不同,因为嵌入式和外部 + 的首次执行读取的时间不同。 + +不要依赖紧接在内联步骤之后的时钟读取:请在下一个持久步骤之后再读取时钟。 + +Python 和 Rust 会根据历史重建工作流,以响应查询或接受前的更新验证。如果重建后的 +工作流在入口处读取时钟,而任务没有 `replay_clock`(3.30.0 之前的 +Server 从不在这些任务上发送它),查询或验证会失败,而不是用工作流任务从未计算过 +的状态作答。PHP SDK 从不为查询或更新重建工作流主体。 + +离线重放(`replay()`、`Replayer.replay()`、`replay_history()`)以 `replay_clock_entry` 接收任务的对象。内存中的 `WorkflowEnvironment` 不提供载体,因此其中的入口读取不可用。 + +**发布状态。** 入口值(全部三个 SDK)以及查询和验证规则(Python 和 Rust)在 Python SDK 2.24.0、Rust SDK 4.25.0 和 PHP SDK 3.32.0 中 +提供,并需要 Server 3.6.0 或更高版本。查询和验证任务上的载体在 Server 3.30.0 +中提供。嵌入式包的 Worker 协议运行器(`WorkflowFiberRunner`)从 Workflow 2.42.0 +起接受该载体:一旦构建运行器的代码传入它,入口处的 `Workflow::now()` 就会返回 +运行的规范开始时间。更早的 SDK 版本会将入口报告为不可用。 + +**升级。** 如果正在运行的工作流的代码根据入口读取是否不可用进行分支(例如捕获 +`ReplayClockUnavailable`),在升级后、新旧 worker 混合的滚动部署期间,或将 Server 升级到 3.6.0 之后,重放时会走另一个分支。请将此类代码放在 +`ctx.get_version(...)` 之后,或先让这些运行结束。`ctx.now()` 保持固定的开始 +时间,因此读取它的运行会原样重放。 + #### 各 SDK 的时钟差异 {#clock-differences-across-sdks} 这些 API 在提供时是确定性的,但并不共享同一个时钟: @@ -689,15 +772,15 @@ HTTP 或 `get_result()` 的等待超时只限制该本地请求,并不能替 | 编写接口 | 重复调用与持久步骤 | continue-as-new 后继运行 | | --- | --- | --- | | Python `ctx.now()` | 固定为本次运行的持久化开始时间,定时器或活动之后也不变。 | 使用后继运行的开始时间基准。 | +| Python `ctx.replay_now()` | 从运行的开始时间开始,并前进到每个受支持的已消费步骤的记录时间。参见[会前进的重放时钟](#advancing-replay-clock)。 | 从后继运行自己的开始时间开始。 | | 嵌入式 PHP `Workflow::now()` | 从运行开始时间起步,并推进到重放已消费事件的记录时间。参见[工作流时间](../features/timers.md#reading-deterministic-time)。 | 从新运行开始,随后沿该运行已消费的事件推进。 | -| 服务模式 PHP SDK | 没有通用的公开工作流 `now()` 辅助方法。使用持久操作或已记录的活动/副作用值。 | 需要跨交接保留应用时间状态时,必须明确传递。 | -| 服务模式 Rust SDK | 没有通用的公开 `WorkflowContext::now()` 辅助方法。`side_effect` 可以记录一个小型墙上时钟快照,但它不是会推进的时钟。 | 新运行中的副作用是新操作;需要时应明确传递先前的时间状态。 | +| 服务模式 PHP `WorkflowContext::replayNow()` | 与 Python `ctx.replay_now()` 语义相同。 | 从后继运行自己的开始时间开始。 | +| 服务模式 Rust `WorkflowContext::replay_now()` | 与 Python `ctx.replay_now()` 语义相同。 | 从后继运行自己的开始时间开始。 | -嵌入式 PHP 的行为已存在于 -[已发布的 Core](https://github.com/durable-workflow/workflow/blob/64efa176e4c37e5d6ae80e767ba3b41464024e53/src/V2/Support/WorkflowFiberContext.php)。 -独立的 [PHP SDK 上下文](https://github.com/durable-workflow/sdk-php/blob/2.5.2/src/Worker/WorkflowContext.php) -和 [Rust SDK 上下文](https://github.com/durable-workflow/sdk-rust/blob/3.5.5/src/lib.rs) -各有自己的 API。应迁移持久操作与期限策略,而不是假定每个 SDK 的时钟辅助方法都有相同语义。 +服务模式的时钟共享同一份契约。嵌入式 `Workflow::now()` 还会移动到 +副作用等内联步骤的记录时间,而服务模式的时钟会将该时间报告为不可用,因此这种 +读取不可移植(参见[内联步骤之后的时钟读取不可移植](#inline-step-clock-reads))。请移植持久 +操作和截止时间策略,而不要假设每个时钟辅助方法的行为都相同。 #### 使用序列值排列发出的事件 {#order-emitted-events-with-sequence-values} @@ -708,6 +791,8 @@ HTTP 或 `get_result()` 的等待超时只限制该本地请求,并不能替 continue-as-new 明确传递。独立流或运行不会因拥有时间戳而获得全局顺序。 +在持久步骤之间重复读取 `ctx.replay_now()` 也只会返回一个值,因此同样不要用它来排列事件。 + ### 活动重试与超时 {#activity-retries-and-timeouts} 某个活动调用需要不同于默认单次尝试行为的重试预算或截止时间时,在 `ctx.schedule_activity(...)` 上使用 `ActivityRetryPolicy` 和超时关键字参数: diff --git a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md index 4612db98f12..376f66991ca 100644 --- a/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md +++ b/i18n/zh-Hans/docusaurus-plugin-content-docs/current/polyglot/rust.md @@ -653,6 +653,22 @@ worker 重建 workflow 历史时,普通日志调用会再次执行。workflow 参见[已发布日志指南](https://github.com/durable-workflow/sdk-rust/blob/4.17.0/README.md#workflow-logging)、[WorkflowLogger API](https://rust.durable-workflow.com/durable_workflow/struct.WorkflowLogger.html) 和 [WorkflowReplayState API](https://rust.durable-workflow.com/durable_workflow/enum.WorkflowReplayState.html)。[registry lifecycle/deadline 控制](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868388853)与[四进程日志验收](https://github.com/durable-workflow/sdk-rust/pull/269#issuecomment-6868494262)记录于明确指定的 native Server 3.10.0 linux/amd64 组合。其他 binding 以及更广泛的 replay/producer 验收各自保留范围。 +## 对重放安全的工作流时间 {#replay-safe-workflow-time} + +`WorkflowContext::replay_now()` 以 `Result>` 返回对重放安全的 +UTC 业务时间。在普通入口处,它是任务 `replay_clock`(Server 3.6.0 及更高版本) +中的运行开始时间(对重新驱动的后继运行而言,是原始运行的开始时间)。在每个受支持的已消费持久步骤(活动、定时器、子工作流、信号 +等待和条件等待、经过验证的组)之后,它是该步骤的记录时间。在持久步骤之间重复 +读取会返回同一个值,每次重放都会返回相同的值。 + +当 SDK 无法证明时间时,它返回 `Error::ReplayClockUnavailable`。这包括内联和本地 +操作(副作用、版本标记、本地活动、备忘录),在 Core 为其定义持久化时间之前, +它们保持不可用。紧接在这类步骤之后的时钟读取在不同运行器之间或混合集群中不可 +移植;参见[内联步骤之后的时钟读取不可移植](./python.md#inline-step-clock-reads)。 +离线重放可通过 `WorkflowHistory::replay_clock(carrier)` 提供 +载体。完整列表、查询和验证规则、发布状态以及升级说明,请参见 +[跨 SDK 的时钟语义](./python.md#advancing-replay-clock)。 + ## Rust 确定性规则 {#rust-determinism-rules} 对于已记录的输入和历史,重放必须按相同顺序生成相同的持久命令。Rust 常规集合、时钟和并发原语不会自动保持这一约定: @@ -660,7 +676,7 @@ worker 重建 workflow 历史时,普通日志调用会再次执行。workflow | 工作流代码中的模式 | 持久替代方式 | | --- | --- | | 遍历 `HashMap` 时调度 | 先对键排序,或使用 `BTreeMap`。 | -| 读取系统时钟、`thread_rng` 或新 UUID | 用 `ctx.side_effect(...)` 记录快照,或使用活动。 | +| 读取系统时钟、`thread_rng` 或新 UUID | 业务时间使用 `ctx.replay_now()`;其他值用 `ctx.side_effect(...)` 记录,或使用活动。 | | `tokio::time::sleep` 或 `std::thread::sleep` | `ctx.sleep(...)` 或 `ctx.start_timer(...)`。 | | `tokio::select!` 或普通 future 竞争 | `ctx.select(...)` 或 `ctx.select_keyed(...)`。 | | 未跟踪的并发持久调用 | 使用输入顺序稳定的 `ctx.parallel(...)`。 | diff --git a/i18n/zh-Hans/source-hashes.json b/i18n/zh-Hans/source-hashes.json index 3e58ba988e9..d6604d94ee5 100644 --- a/i18n/zh-Hans/source-hashes.json +++ b/i18n/zh-Hans/source-hashes.json @@ -82,14 +82,14 @@ "polyglot/invocable-carrier.md": "00bcf878b7bac1be90718b73f0a626a99cf0e111414ac0854c6491d159798c01", "polyglot/invocable-php-handler.md": "3b678eb1d69fe32dfcfdc05d36b33e49e01b79d7216bd784f6a61a6f1c3c3a13", "polyglot/namespace-auth-workers.md": "fee5e52a18637814f60aeb419f7ebc99ce4927089dfb748073697a8218bd47bb", - "polyglot/php.md": "29562f37185945634acef20868bebb71bb5c3c67639f6eac0b85833dbfa55709", - "polyglot/polling-patterns.md": "81ba659bbf14de72f17c112b39fdb3e6d7c919badac50711fe08962890cdfbb6", + "polyglot/php.md": "30bee275e7691445566784511af53809fa1045c27c4fcc067fa2da0b6cfb1898", + "polyglot/polling-patterns.md": "19b971e63c3ae65d213250472a1f468a2d5d7a6e1b71dccfc8ae2ac54681ba67", "polyglot/portable-worker-affinity.md": "40973c6a31a76845b4f95e9a505e68ad76abd5174bbdccf37993cdebc8904959", "polyglot/prerelease-history-migration.md": "a57f05f492228a8a67791f9152648a1e5f80856325b78777cf63b6ef49b7413c", - "polyglot/python.md": "3553a4024ece4e8082023680e51c42d8a5fa1859a500bd275750e7bad3eed831", + "polyglot/python.md": "dbef23a26f6dcb75cb37f8b0fe716913a33aa483c35e3bc718caf207464cf4b7", "polyglot/runtime-migration.md": "5a78713bb8cb74aea58f6d5d826400d968a405f69c6ff17fdf2f7decb1d14b71", "polyglot/rust-cloud-quickstart.md": "2303434fc9302a81a8381ad4836423ef9952eb3201a4574c432254e3cb68c5f3", - "polyglot/rust.md": "b1eb343b6320f290036d133e2f6c37c3d8cba040ce2d4c0d28d254bed3a982e5", + "polyglot/rust.md": "8c5612748e0ea83423d20f912072242c1b2a149e7e3e9a26e28ef7175c818622", "polyglot/server-api-reference.md": "dab6924c622276373f69185295cb78b19a3a1c531db304e5106d0f02fdfe987c", "polyglot/server-config-reference.md": "36ecbb5b76246f9c8e434b79745c3fef3265d0606aae486247064e23e7a6bb64", "polyglot/server-role-topology.md": "3d048f0c6b5f179399622508f51e67fff8aa5a6d5b2492533fc720eeec2c27f2",