Skip to main content

durable_workflow/
replay_clock.rs

1//! Additive business time, independent of cancellation's monotonic budget clock.
2
3use super::{
4    durable_event_sequence, is_internal_timer_event, is_recorded_signal_wait_event,
5    recorded_commands, DurableOperationHandle, Error, HistoryEvent, ParallelGroupMetadata,
6    QueryContext, RecordedCommand, Result, Value, WorkflowContext, WorkflowIdentity, WorkflowState,
7};
8use chrono::{DateTime, Utc};
9use std::{
10    cell::{Cell, RefCell},
11    collections::HashMap,
12    sync::{Arc, Mutex, Weak},
13};
14
15mod condition;
16mod condition_timeout;
17mod parallel;
18mod parallel_activity;
19mod parallel_child;
20mod parallel_timer;
21
22#[derive(Clone, Copy)]
23pub(super) enum GroupFailure {
24    Legacy(u64),
25    FirstRecorded(u64),
26}
27
28impl GroupFailure {
29    fn sequence(self) -> u64 {
30        match self {
31            Self::Legacy(sequence) | Self::FirstRecorded(sequence) => sequence,
32        }
33    }
34}
35
36thread_local! {
37    static ACTIVE: RefCell<Option<Weak<Mutex<WorkflowState>>>> = const { RefCell::new(None) };
38    static QUERY_REPLAY: Cell<bool> = const { Cell::new(false) };
39}
40
41pub(super) struct Guard(Option<Weak<Mutex<WorkflowState>>>, bool);
42
43impl Guard {
44    pub(super) fn enter(context: &WorkflowContext) -> Self {
45        Self::scope(Some(Arc::downgrade(&context.state)), false)
46    }
47
48    pub(super) fn query(context: &WorkflowContext) -> Self {
49        Self::scope(Some(Arc::downgrade(&context.state)), true)
50    }
51
52    pub(super) fn unavailable() -> Self {
53        Self::scope(None, false)
54    }
55
56    fn scope(context: Option<Weak<Mutex<WorkflowState>>>, query: bool) -> Self {
57        Self(
58            ACTIVE.with(|active| active.replace(context)),
59            QUERY_REPLAY.with(|active| active.replace(query)),
60        )
61    }
62}
63
64impl Drop for Guard {
65    fn drop(&mut self) {
66        ACTIVE.with(|active| active.replace(self.0.take()));
67        QUERY_REPLAY.with(|active| active.set(self.1));
68    }
69}
70
71pub(super) fn observation_mode(context: &WorkflowContext) -> Option<bool> {
72    let active = ACTIVE.with(|active| active.borrow().as_ref().and_then(Weak::upgrade))?;
73    Arc::ptr_eq(&active, &context.state).then(|| QUERY_REPLAY.with(Cell::get))
74}
75
76fn unavailable() -> Error {
77    Error::ReplayClockUnavailable
78}
79
80fn parse(value: Option<&Value>) -> Option<DateTime<Utc>> {
81    DateTime::parse_from_rfc3339(value?.as_str()?)
82        .ok()
83        .map(|time| time.with_timezone(&Utc))
84}
85
86fn recorded_time(event: &HistoryEvent, reused: bool) -> Option<DateTime<Utc>> {
87    if reused && event.payload.get("reused_recorded_at").is_some() {
88        return parse(event.payload.get("reused_recorded_at"));
89    }
90    // A present but invalid field cannot borrow another event's time.
91    parse(
92        event
93            .raw
94            .get("timestamp")
95            .or_else(|| event.raw.get("recorded_at")),
96    )
97}
98
99fn boundary_time(event: &HistoryEvent, query: bool) -> Option<DateTime<Utc>> {
100    let internal = event.event_type == "TimerFired" && is_internal_timer_event(event);
101    if internal {
102        // Core query replay requires the explicit condition resolution. Its
103        // executor-only fired-time branch does not grant callback authority.
104        return if query {
105            None
106        } else {
107            parse(event.raw.get("recorded_at"))
108        };
109    }
110    recorded_time(
111        event,
112        matches!(
113            event.event_type.as_str(),
114            "ActivityCompleted" | "TimerFired" | "SignalApplied"
115        ),
116    )
117}
118
119fn start_time(history: &[HistoryEvent]) -> Option<DateTime<Utc>> {
120    let mut starts = history
121        .iter()
122        .filter(|event| event.event_type == "WorkflowStarted");
123    let start = starts.next()?;
124    if starts.next().is_some() || start.payload["recovery_kind"] != "redrive" {
125        // Ordinary Core entry uses run.started_at, not the history insertion
126        // time. The current worker task has no authoritative carrier for it.
127        return None;
128    }
129    parse(start.payload.get("replayed_started_at"))
130}
131
132/// `WorkerReplayClock` v1, the workflow task's entry instant (Server #1132/#1156).
133const ENTRY_SCHEMA: &str = "durable-workflow.worker-replay-clock/v1";
134
135/// A validated `replay_clock` carrier from one workflow task claim.
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137pub(super) struct Entry {
138    started_at: DateTime<Utc>,
139    redrive: bool,
140}
141
142/// `YYYY-MM-DDTHH:MM:SS.ffffffZ`, exactly as the v1 schema pattern requires.
143fn strict_entry_time(text: &str) -> Option<DateTime<Utc>> {
144    let bytes = text.as_bytes();
145    let shape = bytes.len() == 27
146        && bytes.iter().enumerate().all(|(index, byte)| match index {
147            4 | 7 => *byte == b'-',
148            10 => *byte == b'T',
149            13 | 16 => *byte == b':',
150            19 => *byte == b'.',
151            26 => *byte == b'Z',
152            _ => byte.is_ascii_digit(),
153        });
154    let time = DateTime::parse_from_rfc3339(text).ok().filter(|_| shape)?;
155    // chrono admits a leap second as nanoseconds >= 1s; the carrier cannot.
156    (time.timestamp_subsec_nanos() < 1_000_000_000).then(|| time.with_timezone(&Utc))
157}
158
159/// Read the task's `replay_clock`. Anything other than a complete v1 object
160/// for this task's run is absent: the SDK never substitutes another time.
161pub(super) fn entry(task: &Value) -> Option<Entry> {
162    entry_for(
163        task.get("replay_clock"),
164        task.get("run_id").and_then(Value::as_str),
165    )
166}
167
168/// Validate one carrier against the run it is replayed for. The v1 schema
169/// has `additionalProperties: false`, so an extra key also makes it absent.
170pub(super) fn entry_for(carrier: Option<&Value>, run_id: Option<&str>) -> Option<Entry> {
171    const KEYS: [&str; 4] = ["schema", "workflow_run_id", "started_at", "source"];
172    let carrier = carrier?.as_object()?;
173    let run_id = run_id.filter(|id| !id.is_empty())?;
174    if carrier.len() != KEYS.len()
175        || !KEYS.iter().all(|key| carrier.contains_key(*key))
176        || carrier.get("schema").and_then(Value::as_str) != Some(ENTRY_SCHEMA)
177        || carrier.get("workflow_run_id").and_then(Value::as_str) != Some(run_id)
178    {
179        return None;
180    }
181    let redrive = match carrier.get("source").and_then(Value::as_str)? {
182        "run_started_at" => false,
183        "redrive_replayed_started_at" => true,
184        _ => return None,
185    };
186    Some(Entry {
187        started_at: strict_entry_time(carrier.get("started_at")?.as_str()?)?,
188        redrive,
189    })
190}
191
192/// A JSON `null` field is absent.
193fn present(value: Option<&Value>) -> bool {
194    value.is_some_and(|value| !value.is_null())
195}
196
197/// How a query or update-validation task attests the run's entry instant.
198/// Server 3.30.0 (server#1338) and later always send the `replay_clock`
199/// key on those tasks: the v1 object when the start is provable, explicit
200/// `null` when it is not. An older Server omits the key, so the entry its
201/// workflow tasks carried is unknown to the rebuild.
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub(super) enum Attestation {
204    /// No key: the rebuild cannot know the entry its workflow tasks had.
205    Unattested,
206    /// Explicit `null`, or an object this SDK refuses for its own shape,
207    /// schema, time or source (as it refused the same object on the run's
208    /// workflow tasks): no entry was carried.
209    Unprovable,
210    Entry(Entry),
211}
212
213pub(super) fn attestation(task: &Value) -> Attestation {
214    let carrier = match task.get("replay_clock") {
215        None => return Attestation::Unattested,
216        Some(Value::Null) => return Attestation::Unprovable,
217        Some(carrier) => carrier,
218    };
219    // Judge the object by itself first, against the run it names. Only a
220    // refusal that depends on the object alone matches the workflow task.
221    let named = carrier.get("workflow_run_id").and_then(Value::as_str);
222    if entry_for(Some(carrier), named).is_none() {
223        return Attestation::Unprovable;
224    }
225    // A missing or different task run depends on this task, not the object:
226    // the run's workflow tasks may have accepted it, so fail closed.
227    entry(task).map_or(Attestation::Unattested, Attestation::Entry)
228}
229
230/// Whether this history declares a redrive start, whether or not it is proved.
231fn declares_redrive(history: &[HistoryEvent]) -> bool {
232    history.iter().any(|event| match event.event_type.as_str() {
233        "WorkflowStarted" => {
234            event.payload["recovery_kind"] == "redrive"
235                || present(event.payload.get("replayed_started_at"))
236                || present(event.payload.get("resume_step_sequence"))
237        }
238        "StartAccepted" => event.payload["outcome"] == "redriven",
239        _ => false,
240    })
241}
242
243#[derive(Debug)]
244pub(super) struct Clock {
245    time: Option<DateTime<Utc>>,
246    boundaries: HashMap<u64, usize>,
247    parallel_activities: parallel::Members,
248    parallel_timers: parallel::Members,
249    parallel_children: parallel::Members,
250    /// No boundary, inline or durable, has been consumed yet.
251    at_entry: bool,
252    /// A rebuild whose task did not attest the entry instant.
253    entry_unattested: bool,
254    /// Workflow code read the clock at an unattested entry, so the rebuilt
255    /// state may differ from what the workflow task computed.
256    unattested_entry_read: bool,
257}
258
259enum BoundaryKind {
260    Activity,
261    Timer,
262    Child,
263    Signal,
264    Condition,
265}
266
267fn supported_boundary(command: &RecordedCommand) -> Option<(u64, BoundaryKind)> {
268    match command {
269        RecordedCommand::Activity {
270            sequence,
271            outcome: Some(_),
272            parallel_group_path,
273            ..
274        } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
275            Some((*sequence, BoundaryKind::Activity))
276        }
277        RecordedCommand::Timer {
278            sequence,
279            fired: true,
280            parallel_group_path,
281            ..
282        } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
283            Some((*sequence, BoundaryKind::Timer))
284        }
285        RecordedCommand::ChildWorkflow {
286            sequence,
287            outcome: Some(_),
288            parallel_group_path,
289            ..
290        } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
291            Some((*sequence, BoundaryKind::Child))
292        }
293        RecordedCommand::SignalWait {
294            sequence,
295            value: Some(_),
296            parallel_group_path,
297            ..
298        } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
299            Some((*sequence, BoundaryKind::Signal))
300        }
301        RecordedCommand::ConditionWait {
302            sequence,
303            result: Some(_),
304            parallel_group_path,
305            ..
306        } if parallel_group_path.as_ref().is_none_or(Vec::is_empty) => {
307            Some((*sequence, BoundaryKind::Condition))
308        }
309        _ => None,
310    }
311}
312
313fn signal_boundary(history: &[HistoryEvent], indices: &[usize], sequence: u64) -> Option<usize> {
314    let (opened, timers, applied) = match indices {
315        [opened, applied] => (opened, &[][..], applied),
316        [opened, _, _, applied] => (opened, &indices[1..3], applied),
317        _ => return None,
318    };
319    let open = &history[*opened];
320    let apply = &history[*applied];
321    if open.event_type != "SignalWaitOpened"
322        || apply.event_type != "SignalApplied"
323        || apply.payload.get("value").is_none_or(Value::is_null)
324    {
325        return None;
326    }
327    let events: Vec<_> = indices.iter().map(|&index| &history[index]).collect();
328    if super::recorded_parallel_group_path(&events, sequence)
329        .ok()?
330        .is_some_and(|path| !path.is_empty())
331    {
332        return None;
333    }
334    for event in &events {
335        if event.payload.get("sequence").and_then(Value::as_u64) != Some(sequence)
336            || event
337                .payload
338                .get("workflow_sequence")
339                .is_some_and(|value| value.as_u64() != Some(sequence))
340        {
341            return None;
342        }
343    }
344    for key in ["signal_wait_id", "signal_name"] {
345        let identity = open
346            .payload
347            .get(key)?
348            .as_str()
349            .filter(|value| !value.is_empty())?;
350        if events
351            .iter()
352            .any(|event| event.payload.get(key).and_then(Value::as_str) != Some(identity))
353        {
354            return None;
355        }
356    }
357    signal_timeout(open, apply, history, timers)?;
358    Some(*applied)
359}
360
361fn signal_timeout(
362    open: &HistoryEvent,
363    apply: &HistoryEvent,
364    history: &[HistoryEvent],
365    timers: &[usize],
366) -> Option<()> {
367    let timeout = open.payload.get("timeout_seconds").filter(|v| !v.is_null());
368    let seconds = match timeout {
369        Some(value) => Some(value.as_u64()?),
370        None => None,
371    };
372    if apply
373        .payload
374        .get("timeout_seconds")
375        .filter(|value| !value.is_null())
376        .is_some_and(|value| Some(value) != timeout)
377    {
378        return None;
379    }
380    let [scheduled, cancelled] = timers else {
381        // A signal already pending at the call can win even a zero timeout,
382        // without ever scheduling a timer. The persisted apply is authority.
383        return timers.is_empty().then_some(());
384    };
385    let schedule = &history[*scheduled];
386    let cancel = &history[*cancelled];
387    if seconds? == 0
388        || schedule.event_type != "TimerScheduled"
389        || cancel.event_type != "TimerCancelled"
390        || parse(cancel.payload.get("cancelled_at")).is_none()
391        || cancel
392            .payload
393            .get("cancellation_scope")
394            .is_some_and(|v| !v.is_null())
395    {
396        return None;
397    }
398    for event in [schedule, cancel] {
399        if event.payload["timer_kind"] != "signal_timeout"
400            || event.payload.get("delay_seconds").and_then(Value::as_u64) != seconds
401        {
402            return None;
403        }
404    }
405    let timer_id = schedule
406        .payload
407        .get("timer_id")?
408        .as_str()
409        .filter(|v| !v.is_empty())?;
410    if cancel.payload.get("timer_id").and_then(Value::as_str) != Some(timer_id)
411        || parse(schedule.payload.get("fire_at")).is_none()
412        || cancel.payload.get("fire_at") != schedule.payload.get("fire_at")
413    {
414        return None;
415    }
416    Some(())
417}
418
419fn child_boundary(history: &[HistoryEvent], indices: &[usize]) -> Option<usize> {
420    child_lifecycle(history, indices)?
421}
422
423fn child_lifecycle(history: &[HistoryEvent], indices: &[usize]) -> Option<Option<usize>> {
424    // One call has one schedule, an optional start, then at most one resolution.
425    // Legacy replay can accept duplicate payloads, but their time is ambiguous.
426    let (&scheduled, terminal) = match indices {
427        [scheduled] => (scheduled, None),
428        [scheduled, started] if history[*started].event_type == "ChildRunStarted" => {
429            (scheduled, None)
430        }
431        [scheduled, terminal] => (scheduled, Some(*terminal)),
432        [scheduled, started, terminal] if history[*started].event_type == "ChildRunStarted" => {
433            (scheduled, Some(*terminal))
434        }
435        _ => return None,
436    };
437    let schedule = &history[scheduled];
438    if schedule.event_type != "ChildWorkflowScheduled"
439        || terminal.is_some_and(|terminal| {
440            !matches!(
441                history[terminal].event_type.as_str(),
442                "ChildRunCompleted" | "ChildRunFailed" | "ChildRunCancelled" | "ChildRunTerminated"
443            )
444        })
445    {
446        return None;
447    }
448    for key in [
449        "child_call_id",
450        "child_workflow_instance_id",
451        "child_workflow_run_id",
452        "child_workflow_type",
453    ] {
454        let identity = schedule
455            .payload
456            .get(key)?
457            .as_str()
458            .filter(|id| !id.is_empty())?;
459        if indices
460            .iter()
461            .any(|&index| history[index].payload.get(key).and_then(Value::as_str) != Some(identity))
462        {
463            // Changed-run retry/continuation needs its own lineage algorithm.
464            // Missing identities keep legacy result handling, without time.
465            return None;
466        }
467    }
468    Some(terminal)
469}
470
471impl Clock {
472    pub(super) fn new(history: &[HistoryEvent], commands: &[RecordedCommand]) -> Self {
473        let supported: HashMap<_, _> = commands.iter().filter_map(supported_boundary).collect();
474        let mut boundaries = HashMap::new();
475        let mut children: HashMap<u64, Vec<usize>> = HashMap::new();
476        let mut signals: HashMap<u64, Vec<usize>> = HashMap::new();
477        let mut conditions: HashMap<u64, Vec<usize>> = HashMap::new();
478        let mut signal_timers: HashMap<&str, Vec<usize>> = HashMap::new();
479        for (index, event) in history.iter().enumerate() {
480            if event.event_type.starts_with("Timer") {
481                if let Some(wait) = event.payload.get("signal_wait_id").and_then(Value::as_str) {
482                    signal_timers.entry(wait).or_default().push(index);
483                }
484            }
485            let Some(sequence) = durable_event_sequence(event) else {
486                continue;
487            };
488            let matched = match supported.get(&sequence) {
489                Some(BoundaryKind::Activity) => matches!(
490                    event.event_type.as_str(),
491                    "ActivityCompleted"
492                        | "ActivityFailed"
493                        | "ActivityTimedOut"
494                        | "ActivityCancelled"
495                ),
496                Some(BoundaryKind::Timer) => {
497                    event.event_type == "TimerFired" && !is_internal_timer_event(event)
498                }
499                Some(BoundaryKind::Child) => {
500                    if event.event_type == "ChildWorkflowScheduled"
501                        || event.event_type.starts_with("ChildRun")
502                    {
503                        children.entry(sequence).or_default().push(index);
504                    }
505                    false
506                }
507                Some(BoundaryKind::Signal) => {
508                    if is_recorded_signal_wait_event(event) || event.event_type.starts_with("Timer")
509                    {
510                        signals.entry(sequence).or_default().push(index);
511                    }
512                    false
513                }
514                Some(BoundaryKind::Condition) => {
515                    if super::is_recorded_condition_wait_event(event) {
516                        conditions.entry(sequence).or_default().push(index);
517                    }
518                    false
519                }
520                None => false,
521            };
522            if matched {
523                boundaries.entry(sequence).or_insert(index);
524            }
525        }
526        for (sequence, indices) in children {
527            if let Some(index) = child_boundary(history, &indices) {
528                boundaries.insert(sequence, index);
529            }
530        }
531        for (sequence, mut indices) in signals {
532            // A timer with a conflicting/missing counter must not disappear
533            // from its wait's evidence just because it uses another bucket.
534            let related: Vec<_> = indices
535                .iter()
536                .filter_map(|&index| history[index].payload.get("signal_wait_id")?.as_str())
537                .filter_map(|wait| signal_timers.get(wait))
538                .flatten()
539                .copied()
540                .collect();
541            indices.extend(related);
542            indices.sort_unstable();
543            indices.dedup();
544            if let Some(index) = signal_boundary(history, &indices, sequence) {
545                boundaries.insert(sequence, index);
546            }
547        }
548        let condition_timeouts = condition_timeout::Index::new(history);
549        boundaries.extend(conditions.into_iter().filter_map(|(sequence, indices)| {
550            condition::boundary(history, &indices, sequence)
551                .or_else(|| condition_timeouts.boundary(history, &indices, sequence))
552                .map(|index| (sequence, index))
553        }));
554        // Index identities once. Timestamps are read only when that boundary
555        // is actually consumed, never by scanning ahead from the accessor.
556        Self {
557            time: start_time(history),
558            boundaries,
559            parallel_activities: parallel_activity::members(history, commands),
560            parallel_timers: parallel_timer::members(history, commands),
561            parallel_children: parallel_child::members(history, commands),
562            at_entry: true,
563            entry_unattested: false,
564            unattested_entry_read: false,
565        }
566    }
567
568    pub(super) fn unavailable(&mut self) {
569        self.time = None;
570        self.at_entry = false;
571    }
572
573    /// Ordinary entry time from a validated task carrier, before any
574    /// boundary is consumed. Its source must match the history's start kind.
575    /// A redrive anchor already proved from history is kept as it was.
576    fn adopt_entry(&mut self, history: &[HistoryEvent], entry: Entry) {
577        // An anchor a start event records itself, even one this history
578        // cannot prove, must equal the carrier's.
579        // An unparsable recorded anchor also refuses the carrier.
580        let disagrees = history.iter().any(|event| {
581            event.event_type == "WorkflowStarted"
582                && event
583                    .payload
584                    .get("replayed_started_at")
585                    .filter(|value| !value.is_null())
586                    .is_some_and(|recorded| parse(Some(recorded)) != Some(entry.started_at))
587        });
588        if self.time.is_none() && entry.redrive == declares_redrive(history) && !disagrees {
589            self.time = Some(entry.started_at);
590        }
591    }
592}
593
594impl WorkflowState {
595    /// Apply this claim's `replay_clock` carrier. Call it once, after
596    /// construction and before the workflow body runs.
597    pub(super) fn adopt_replay_entry(&mut self, entry: Option<Entry>) {
598        if let Some(entry) = entry {
599            self.replay_clock.adopt_entry(&self.history_events, entry);
600        }
601    }
602
603    /// Apply a query rebuild's attestation. Call it once, after construction
604    /// and before the workflow body runs.
605    pub(super) fn attest_replay_entry(&mut self, attestation: Attestation) {
606        match attestation {
607            Attestation::Unattested => self.replay_clock.entry_unattested = true,
608            Attestation::Unprovable => {}
609            Attestation::Entry(entry) => self.adopt_replay_entry(Some(entry)),
610        }
611    }
612
613    /// Whether the rebuilt body read the clock at an unattested entry. Its
614    /// state is then not proved to match the workflow task's, whatever the
615    /// body did with the unavailable result.
616    pub(super) fn read_unattested_replay_entry(&self) -> bool {
617        self.replay_clock.unattested_entry_read
618    }
619
620    pub(super) fn consume_replay_sequence(
621        &mut self,
622        sequence: u64,
623        path: &[ParallelGroupMetadata],
624    ) {
625        if path.is_empty() {
626            self.observe_replay_sequence(sequence);
627        } else {
628            self.replay_clock.unavailable();
629        }
630        self.advance_cancellation_sequence(sequence, path);
631    }
632
633    pub(super) fn consume_unproven_boundary(&mut self, path: &[ParallelGroupMetadata]) {
634        if path.is_empty() {
635            self.observation_pending = false;
636        }
637        self.replay_clock.unavailable();
638        self.unavailable_cancellation_boundary(path);
639    }
640
641    pub(super) fn consume_replay_group(&mut self, sequences: &[u64], failed: Option<GroupFailure>) {
642        self.observation_pending = false;
643        // Core's query group-send branch supplies no aggregate time. Do not
644        // transfer executor authority into reconstructed query execution.
645        self.replay_clock.at_entry = false;
646        self.replay_clock.time = if QUERY_REPLAY.with(Cell::get) {
647            None
648        } else {
649            self.replay_clock
650                .parallel_activities
651                .consumed_time(&self.history_events, sequences, failed)
652                .or_else(|| {
653                    self.replay_clock.parallel_timers.consumed_time(
654                        &self.history_events,
655                        sequences,
656                        failed,
657                    )
658                })
659                .or_else(|| {
660                    self.replay_clock.parallel_children.consumed_time(
661                        &self.history_events,
662                        sequences,
663                        failed,
664                    )
665                })
666        };
667        self.advance_cancellation_sequences(sequences, failed.map(GroupFailure::sequence));
668    }
669
670    pub(super) fn consume_replay_selection(&mut self, group: &str) {
671        self.observation_pending = false;
672        self.replay_clock.unavailable();
673        self.advance_cancellation_selection(group);
674    }
675
676    pub(super) fn consume_replay_receipt(&mut self, group: &str, sequence: u64) {
677        self.observation_pending = false;
678        self.replay_clock.unavailable();
679        self.advance_cancellation_receipt(group, sequence);
680    }
681
682    pub(super) fn consume_replay_handle(&mut self, handle: &DurableOperationHandle, failed: bool) {
683        self.observation_pending = false;
684        self.replay_clock.unavailable();
685        self.advance_cancellation_handle(handle, failed);
686    }
687
688    pub(super) fn replay_time(&self) -> Result<DateTime<Utc>> {
689        // Cancellation keeps its existing separate semantics. This first
690        // cohort does not claim business-clock correlation for its callbacks.
691        if self.cancellation_clock.is_some() {
692            return Err(unavailable());
693        }
694        self.replay_clock.time.ok_or_else(unavailable)
695    }
696
697    /// Workflow code's read, which records an unattested entry read.
698    fn read_replay_time(&mut self) -> Result<DateTime<Utc>> {
699        let time = self.replay_time();
700        if time.is_err()
701            && self.cancellation_clock.is_none()
702            && self.replay_clock.at_entry
703            && self.replay_clock.entry_unattested
704        {
705            self.replay_clock.unattested_entry_read = true;
706        }
707        time
708    }
709
710    pub(super) fn observe_replay_sequence(&mut self, sequence: u64) {
711        self.observation_pending = false;
712        self.replay_clock.at_entry = false;
713        self.replay_clock.time = self
714            .replay_clock
715            .boundaries
716            .get(&sequence)
717            .and_then(|index| self.history_events.get(*index))
718            .and_then(|event| boundary_time(event, QUERY_REPLAY.with(Cell::get)));
719    }
720}
721
722impl WorkflowContext {
723    /// Recorded business time at the last supported consumed replay boundary.
724    ///
725    /// Repeated reads at an unchanged prefix are equal. This never reads wall
726    /// time, creates a command, or selects an unconsumed future event. Missing
727    /// or invalid evidence returns [`Error::ReplayClockUnavailable`]. The clock
728    /// is available only while this workflow's handler/future is executing.
729    ///
730    /// Before any boundary is consumed, the clock is the workflow task's
731    /// Server-provided `replay_clock` entry instant (`WorkerReplayClock` v1):
732    /// the run's own start, or a redrive successor's original start. It is
733    /// pinned to the run's stored rows, so every replay reads the same value.
734    /// A task without a valid carrier keeps entry unavailable, except for the
735    /// explicit redrive start anchor proved from history. Step times come
736    /// from history; only the entry value comes from the task's carrier.
737    ///
738    /// A replayed-instance query or update validator rebuilds the body with its own task's
739    /// `replay_clock` attestation. When the query task omits that key (a
740    /// Server before 3.30.0, without #1338) and the body reads this clock at
741    /// entry, the query fails with `query_workflow_state_unavailable`, even if the body
742    /// tolerated the unavailable result: its rebuilt state is not proved to
743    /// match the workflow task's. An explicit `null` keeps entry unavailable,
744    /// as on the run's workflow tasks. Offline replay takes the carrier
745    /// through [`crate::testing::WorkflowHistory::replay_clock`]. An
746    /// unhandled [`Error::ReplayClockUnavailable`] fails the workflow like
747    /// any error.
748    ///
749    /// Supported boundaries are correlated scalar activity, timer, child, signal
750    /// and condition results, and persisted Activity, Timer and Child all
751    /// groups. Inline metadata and local completions, and other grouped
752    /// families remain unavailable.
753    /// Cancellation's existing budget clock is unchanged.
754    /// Migrate business decisions through normal workflow versioning. Event
755    /// timestamps do not provide a total order; retain stream/counter identity.
756    pub fn replay_now(&self) -> Result<DateTime<Utc>> {
757        let active = ACTIVE.with(|active| active.borrow().as_ref().and_then(Weak::upgrade));
758        if !active.is_some_and(|active| Arc::ptr_eq(&active, &self.state)) {
759            return Err(unavailable());
760        }
761        self.state
762            .lock()
763            .map_err(|_| Error::WorkflowStatePoisoned)?
764            .read_replay_time()
765    }
766}
767
768impl QueryContext {
769    /// Recorded time of this immutable, engine-correlated callback prefix.
770    ///
771    /// Missing, invalid or unproved boundary evidence is explicitly unavailable.
772    /// Reading this accessor does not change the snapshot or append history.
773    pub fn replay_now(&self) -> Result<DateTime<Utc>> {
774        self.replay_time.ok_or_else(unavailable)
775    }
776}
777
778pub(super) fn snapshot_time(history: &[HistoryEvent], codec: &str) -> Option<DateTime<Utc>> {
779    let event = history.last()?;
780    if super::settled_at_run_close(event) {
781        return None;
782    }
783    if event.event_type == "WorkflowStarted" {
784        return start_time(history);
785    }
786    if !matches!(
787        event.event_type.as_str(),
788        "ActivityCompleted"
789            | "ActivityFailed"
790            | "ActivityTimedOut"
791            | "ActivityCancelled"
792            | "TimerFired"
793            | "ChildRunCompleted"
794            | "ChildRunFailed"
795            | "ChildRunCancelled"
796            | "ChildRunTerminated"
797            | "SignalApplied"
798            | "ConditionWaitSatisfied"
799            | "ConditionWaitTimedOut"
800    ) {
801        return None;
802    }
803    let commands = recorded_commands(
804        history,
805        codec,
806        WorkflowIdentity {
807            workflow_id: None,
808            run_id: None,
809        },
810    )
811    .ok()?;
812    Clock::new(history, &commands)
813        .boundaries
814        .get(&durable_event_sequence(event)?)
815        .and_then(|index| history.get(*index))
816        .and_then(|event| boundary_time(event, true))
817}
818
819pub(super) fn update_time(history: &[HistoryEvent], update_id: &str) -> Option<DateTime<Utc>> {
820    let mut events = history.iter().filter(|event| {
821        event.event_type == "UpdateAccepted"
822            && event.payload["update_id"].as_str() == Some(update_id)
823    });
824    let event = events.next()?;
825    if events.next().is_some() {
826        return None;
827    }
828    recorded_time(event, true)
829}
830
831#[cfg(test)]
832mod tests;