xmachines-workflow 6.0.0

The record protocol of a statechart run, as serde types: chunks of events, time and work results in, events, snapshots and rejections out, faults as data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! A run, hosted: [`hosted`] stamps each chunk with the time, journals it,
//! applies it, and gives its records to a [`Sink`], with a clock that writes
//! the time when a timer is due and a worker that does the work the machine
//! waits for, in one of three writer orders ([`Order`]). Everything it needs
//! is passed in: the [`Clock`], the [`Journal`] and the [`Handlers`]. It
//! reads no clock of its own, spawns no task, and needs no executor's
//! features: one future, one loop, no queue, no deadlock.
//!
//! The journal's entries are the JSON of xmachines-js's hosts
//! ([`JournalEntry`]): a journal one host wrote reopens on the other.

use std::collections::BTreeSet;
use std::fmt;
use std::future::{poll_fn, Future};
use std::sync::{Arc, Mutex, PoisonError};
use std::task::{Context, Poll, Waker};

use futures_core::Stream;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use xmachines_runtime::{EventType, Machine};

use crate::input::{is_event, Chunk, Control, Input, Outcome};
use crate::journal::{ChunkEntry, HostedCheckpoint, JournalEntry, SnapshotEntry, StartEntry};
use crate::record::{Checkpoint, Fault, FaultCode, Record};
use crate::step::{Applied, Checkpoints, Options, Run, Stepper};
use crate::work::{Action, Invoke, Work, WorkId};

/// The wall's time, and a wait until a time of it: what stamps each chunk
/// and arms the timers of a hosted run. One trait, since a wait means
/// nothing without the clock it is measured on.
pub trait Clock {
    /// The wall's time now, in whole milliseconds since the epoch.
    fn now(&self) -> u64;
    /// A future that is ready once [`Clock::now`] has reached `at`. A host
    /// drops it to cancel the wait.
    fn sleep_until(&self, at: u64) -> impl Future<Output = ()>;
}

/// An append-only log of a run's entries, as little of one as a host needs:
/// a durable stream, a table, a file, or memory. `append` stores the entries
/// given together, all or none, once its future is ready.
pub trait Journal {
    /// Why an append or a read failed.
    type Error: fmt::Display;
    /// The code of the fault an error stops the host with:
    /// `WORKFLOW_JOURNAL_FAILED` by default; `WORKFLOW_JOURNAL_FENCED` of a
    /// journal that refused a writer behind another, as a holder whose lease
    /// was lost.
    fn code(error: &Self::Error) -> FaultCode {
        let _ = error;
        FaultCode::WorkflowJournalFailed
    }
    /// Whether the journal keeps what it is given: a host takes no
    /// checkpoint of one that keeps nothing ([`NoJournal`]).
    fn keeps(&self) -> bool {
        true
    }
    /// What the journal holds, in order: none of a new run.
    fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>>;
    /// Stores `entries`, all or none.
    fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>>;
}

/// A journal in memory, which stores each append at once: what a test, a
/// demo or a page that keeps nothing hosts a run on, and a journal the order
/// [`Order::JournalSync`] takes.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MemoryJournal {
    /// The entries, in order.
    pub entries: Vec<JournalEntry>,
}

impl Journal for MemoryJournal {
    type Error = std::convert::Infallible;

    fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
        std::future::ready(Ok(self.entries.clone()))
    }

    fn append(&mut self, entries: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
        self.entries.extend_from_slice(entries);
        std::future::ready(Ok(()))
    }
}

/// No journal: a run that keeps nothing, as a local view.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoJournal;

impl Journal for NoJournal {
    type Error = std::convert::Infallible;

    fn keeps(&self) -> bool {
        false
    }

    fn read(&mut self) -> impl Future<Output = Result<Vec<JournalEntry>, Self::Error>> {
        std::future::ready(Ok(Vec::new()))
    }

    fn append(&mut self, _: &[JournalEntry]) -> impl Future<Output = Result<(), Self::Error>> {
        std::future::ready(Ok(()))
    }
}

/// What a handler of work is told beside the work: its id, its actor, and
/// the run it is of. A host action is done at least once: a handler that
/// must do it once dedupes by the run and the id.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HandlerContext {
    /// The work's id.
    pub id: String,
    /// The address of the actor whose work it is.
    pub actor: String,
    /// The run's id.
    pub run: String,
}

/// The work a host does for its runs: invoked work, which gives an output
/// or fails with an error, and host actions, which are done or fail. Each
/// handler closes over what it needs; a future dropped is the work aborted.
pub trait Handlers {
    /// Does invoked work: `Ok` of its output, settled `resolved`, or `Err` of
    /// its error, settled `rejected`.
    fn invoke(&self, work: Invoke, context: HandlerContext) -> impl Future<Output = Result<Value, Value>>;
    /// Does a host action: `Ok` once it is done, settled `done`, or `Err` of
    /// why it failed, which the host reports as `WORKFLOW_HOST_ACTION_FAILED`
    /// and tries again after a wait, while the run still lists the action:
    /// 100 ms the first time, doubling each time after, to 30 s.
    fn action(&self, work: Action, context: HandlerContext) -> impl Future<Output = Result<(), String>>;
}

/// No handlers: work stays pending until something else settles it.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoHandlers;

impl Handlers for NoHandlers {
    fn invoke(&self, _: Invoke, _: HandlerContext) -> impl Future<Output = Result<Value, Value>> {
        std::future::pending()
    }

    fn action(&self, _: Action, _: HandlerContext) -> impl Future<Output = Result<(), String>> {
        std::future::pending()
    }
}

/// Where a hosted run's records and faults go.
pub trait Sink {
    /// A record of the run, in order.
    fn record(&mut self, record: &Record);
    /// A fault the run went on after: a chunk that is no input, a result of
    /// the other kind of work, a host action that failed.
    fn fault(&mut self, fault: &Fault) {
        let _ = fault;
    }
}

impl<F: FnMut(&Record)> Sink for F {
    fn record(&mut self, record: &Record) {
        self(record);
    }
}

/// The order a host writes a run in. Each gives the same journal and the
/// same records.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Order {
    /// A chunk applies at once, its records go to the sink, and the journal
    /// follows. For a local UI: the sink may be ahead of the journal, and a
    /// crash loses what was not in it yet, which nothing but the sink saw.
    #[default]
    ApplyFirst,
    /// A chunk applies once it is in the journal. For a server of an async
    /// log: the sink is never ahead, and nothing acknowledged is lost.
    JournalFirst,
    /// A chunk is appended to a synchronous log, then applies, at once. A
    /// journal whose append is not ready at once is `WORKFLOW_JOURNAL_FAILED`.
    JournalSync,
}

/// The options of [`hosted`].
#[derive(Debug, Clone, Default)]
pub struct HostOptions {
    /// The order the host writes the run in.
    pub order: Order,
    /// The run's id, which its journal's start holds: `root` by default.
    pub run: Option<String>,
    /// The machine's version: a journal or a checkpoint of another is
    /// refused.
    pub version: Option<String>,
    /// The root actor's id, its input, its bound of timers and of steps, as
    /// [`Options`] has them. Its `time` is the clock's, its `from` is
    /// [`HostOptions::from`], and its `checkpoint` is
    /// [`HostOptions::checkpoint`]'s.
    pub options: Options,
    /// How often the journal takes a checkpoint, by `seq`: every 64 chunks
    /// by default, of a journal that keeps them, and never of one that keeps
    /// nothing, as a local view.
    pub checkpoint: Option<Checkpoints>,
    /// The checkpoint to reopen the run of, when the journal holds nothing,
    /// as [`Hosted::checkpoint`] gave it: the run starts as its start says.
    /// One of another run or version is `WORKFLOW_INVALID_SNAPSHOT` either
    /// way; of a journal that holds the run, the run reopens of the journal,
    /// and the sink is told the checkpoint was not read.
    pub from: Option<HostedCheckpoint>,
    /// The loop yields to its executor once each this many chunks, so a run
    /// that feeds itself can't starve the executor: 128 by default.
    pub breathe: Option<u64>,
}

/// What a hosted run left when its source ended: its last `seq`, and a
/// checkpoint of it, with its start, which reopens it.
#[derive(Debug, Clone, PartialEq)]
pub struct Hosted {
    /// The number of the last chunk read.
    pub seq: u64,
    /// The run as a checkpoint now, with how it started.
    pub checkpoint: HostedCheckpoint,
}

/// How often a journal takes a checkpoint, of no `checkpoint`.
const CHECKPOINT: u64 = 64;
/// How often the loop yields, of no `breathe`.
const BREATHE: u64 = 128;

/// Where a chunk came from: the caller's source, or the host's own clock
/// and worker, whose chunks are dropped when they change nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Origin {
    User,
    Feedback,
}

/// The result of a handler, as the host reads it.
enum Settled {
    Work { id: String, outcome: Outcome, data: Option<Value> },
    Failed { id: String, message: String },
}

/// How long a host action that failed waits before it is tried again, the
/// first time: it doubles each time after, to [`RETRY_MAX`].
const RETRY: u64 = 100;
/// The longest wait before a host action that failed is tried again.
const RETRY_MAX: u64 = 30_000;

/// A journal's error as the host's fault, of the journal's code.
fn journal_failed<J: Journal>(error: &J::Error, seq: u64) -> Fault {
    Fault::new(J::code(error), format!("The journal failed: {error}"), seq)
}

/// Does `work` by `handlers`, for run `run`: what the loop holds of each
/// piece of work in flight. One concrete future, no box of a trait object, so
/// the host's future is `Send` when the handlers' are.
async fn settle<H: Handlers>(handlers: &H, work: Work, run: String) -> Settled {
    match work {
        Work::Invoke(invoke) => {
            let id = invoke.id.clone();
            let context = HandlerContext { id: id.clone(), actor: invoke.actor.clone(), run };
            match handlers.invoke(invoke, context).await {
                Ok(output) => Settled::Work { id, outcome: Outcome::Resolved, data: Some(output) },
                Err(error) => Settled::Work { id, outcome: Outcome::Rejected, data: Some(error) },
            }
        }
        Work::Action(action) => {
            let id = action.id.clone();
            let context = HandlerContext { id: id.clone(), actor: action.actor.clone(), run };
            match handlers.action(action, context).await {
                Ok(()) => Settled::Work { id, outcome: Outcome::Done, data: None },
                Err(message) => Settled::Failed { id, message },
            }
        }
    }
}

/// The work the run waits for that has no handler running yet, each marked
/// started; and the ids it no longer waits for are dropped from `started`.
fn to_start<C, E>(run: &Run<C, E>, started: &mut BTreeSet<String>) -> (BTreeSet<String>, Vec<Work>)
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    let work = &run.last().work;
    let waiting: BTreeSet<String> = work.iter().map(|w| w.id().to_owned()).collect();
    started.retain(|id| waiting.contains(id));
    let new = work.iter().cloned().map(Work::from).filter(|w| started.insert(w.id().to_owned())).collect();
    (waiting, new)
}

/// Polls `future` once, as the order [`Order::JournalSync`] reads an append:
/// ready at once, or a journal that is not synchronous.
fn now_or_never<F: Future>(future: F) -> Option<F::Output> {
    let mut future = std::pin::pin!(future);
    match future.as_mut().poll(&mut Context::from_waker(Waker::noop())) {
        Poll::Ready(output) => Some(output),
        Poll::Pending => None,
    }
}

/// Hosts a run of `machine`: stamps each chunk `inputs` gives with the time
/// of `clock`, journals it in `journal`, applies it, and gives its records to
/// `sink`, in the order of `options`. The clock writes the time when a timer
/// is due, and the worker does the work the machine waits for by `handlers`
/// and writes back its result, each stamped too. Gives the run as it was
/// when `inputs` ended, or the fault it could not go on from.
///
/// - One way in: the order of entry is the order of the run. A caller writes
///   events alone: a chunk of the caller's with a control input is a fault of
///   no chunk, `WORKFLOW_INVALID_INPUT`, and is dropped. Time is the host's
///   to stamp, and never goes back.
/// - A run behind its deadlines, as one reopened after a day, is caught up
///   with chunks of time alone, each firing at most `maxTimers` timers,
///   before an event applies.
/// - A time or a work result of the host's own that changes nothing, a race
///   lost, takes no `seq` and is dropped. A late result of work aborted is
///   dropped, not a fault.
/// - The journal's first entry is the run's start; then each chunk that took
///   a `seq`, faulted ones too; and every `checkpoint` chunks a checkpoint.
///   A journal that holds entries reopens the run: its last checkpoint, then
///   the chunks after it, applied with nothing given to the sink and no work
///   started; then the work pending starts, once, by the ids it had. One
///   that does not start with its start, skips a chunk, holds one twice, or
///   is of another run or version is `WORKFLOW_INVALID_JOURNAL`.
/// - A journal that fails stops the host, `WORKFLOW_JOURNAL_FAILED`: what it
///   applied may not be in the journal.
///
/// When `inputs` ends the host stops at once: the timer and the work in
/// flight are dropped. Drop the future to stop it sooner.
pub async fn hosted<C, E, S, K, J, H, O>(
    machine: Arc<Machine<C, E>>,
    options: HostOptions,
    inputs: S,
    clock: &K,
    journal: &mut J,
    handlers: &H,
    sink: &mut O,
) -> Result<Hosted, Fault>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
    S: Stream<Item = Chunk<Value>>,
    K: Clock,
    J: Journal,
    H: Handlers,
    O: Sink,
{
    let order = options.order;
    let run_id = options.run.clone().unwrap_or_else(|| "root".to_owned());
    let breathe = options.breathe.unwrap_or(BREATHE).max(1);
    let fallback = if journal.keeps() { Checkpoints::Every(CHECKPOINT) } else { Checkpoints::Never };
    let checkpoints = options.checkpoint.unwrap_or(fallback);
    let entries = journal.read().await.map_err(|e| journal_failed::<J>(&e, 0))?;
    if let Some(from) = &options.from {
        // A checkpoint is of this run and this version, whether the journal reads it or not.
        check_start(&from.start, &run_id, options.version.as_deref(), FaultCode::WorkflowInvalidSnapshot)?;
        if options.options.input.is_some() {
            return Err(Fault::new(
                FaultCode::WorkflowInvalidSnapshot,
                "A checkpoint carries the input its run started of: give from or input, not both.",
                from.seq,
            ));
        }
        if !entries.is_empty() {
            sink.fault(&Fault::new(
                FaultCode::WorkflowInvalidSnapshot,
                "The journal holds the run: the checkpoint given as from is not read, and the run reopens of the journal.",
                0,
            ));
        }
    }
    let mut last_stamp = 0u64;
    let mut stamp = |clock: &K| {
        last_stamp = last_stamp.max(clock.now());
        last_stamp
    };

    // The run: reopened of its journal, or new, or of a checkpoint.
    let (mut run, start, opening) = if entries.is_empty() {
        let (start, run_options) = match &options.from {
            None => {
                let time = stamp(clock);
                let o = &options.options;
                let max_timers = o.max_timers.unwrap_or(xmachines_runtime::work::DEFAULT_MAX_TIMERS as u64);
                let start = StartEntry {
                    run: run_id.clone(),
                    actor: o.actor.clone().unwrap_or_else(|| "root".to_owned()),
                    version: options.version.clone(),
                    input: o.input.clone(),
                    time: time as i64,
                    max_timers,
                };
                let run_options = Options {
                    actor: Some(start.actor.clone()),
                    time: Some(time as i64),
                    input: o.input.clone(),
                    checkpoint: Some(checkpoints),
                    max_timers: Some(max_timers),
                    max_steps: o.max_steps,
                    from: None,
                };
                (start, run_options)
            }
            Some(from) => {
                let run_options = Options {
                    actor: Some(from.start.actor.clone()),
                    checkpoint: Some(checkpoints),
                    max_timers: Some(from.start.max_timers),
                    max_steps: options.options.max_steps,
                    from: Some(Checkpoint { seq: from.seq, snapshot: from.snapshot.clone() }),
                    ..Options::default()
                };
                (from.start.clone(), run_options)
            }
        };
        let (run, opening) = Run::open(machine, run_options)?;
        let mut first = vec![JournalEntry::Start(start.clone())];
        if let Some(from) = &options.from {
            first.push(JournalEntry::Snapshot(SnapshotEntry {
                epoch: None,
                positions: None,
                published: None,
                seq: from.seq,
                snapshot: from.snapshot.clone(),
            }));
        }
        journal.append(&first).await.map_err(|e| journal_failed::<J>(&e, 0))?;
        (run, start, opening)
    } else {
        let (run, start) = replay(machine, &entries, &run_id, options.version.as_deref(), checkpoints, &options)?;
        let opening = vec![run.record()];
        (run, start, opening)
    };
    for record in &opening {
        sink.record(record);
    }

    let mut inputs = std::pin::pin!(inputs);
    let mut started: BTreeSet<String> = BTreeSet::new();
    // Each container's element type is the one concrete future of its kind, so the host's future
    // is `Send` when the clock's and the handlers' futures are.
    let mut pending = Vec::new();
    // The retries' one concrete future, the clock's wait.
    let mut retries = none_of(|| (String::new(), Box::pin(clock.sleep_until(0))));
    let mut attempts: std::collections::BTreeMap<String, u32> = std::collections::BTreeMap::new();
    let mut timer = None;
    // A deadline a chunk of time did not move: a timer that never fires, which waits for a change.
    let mut stuck: Option<u64> = None;
    let mut in_a_row = 0u64;
    // Starts the work the run waits for that has no handler, and drops the handlers, and the retries,
    // of work it no longer waits for: their work is aborted.
    macro_rules! reconcile {
        () => {{
            let (waiting, new) = to_start(&run, &mut started);
            pending.retain(|(id, _)| waiting.contains(id));
            retries.retain(|(id, _)| waiting.contains(id));
            attempts.retain(|id, _| waiting.contains(id));
            for work in new {
                let id = work.id().to_owned();
                pending.push((id, Box::pin(settle(handlers, work, run_id.clone()))));
            }
        }};
    }
    reconcile!();

    loop {
        // The timer of the next deadline, armed again when it moves; never of a stuck one.
        let deadline = run.last().deadline.filter(|d| Some(*d) != stuck);
        if timer.as_ref().map(|(at, _)| *at) != deadline {
            timer = deadline.map(|at| (at, Box::pin(clock.sleep_until(at))));
        }
        let next = poll_fn(|cx| {
            // Work that settled, then the retries of host actions, then the timer, then the caller.
            for at in 0..pending.len() {
                if let Poll::Ready(settled) = pending[at].1.as_mut().poll(cx) {
                    drop(pending.swap_remove(at));
                    return Poll::Ready(Some(Next::Settled(settled)));
                }
            }
            for at in 0..retries.len() {
                if retries[at].1.as_mut().poll(cx).is_ready() {
                    let (id, _) = retries.swap_remove(at);
                    return Poll::Ready(Some(Next::Retry(id)));
                }
            }
            if let Some((_, sleep)) = timer.as_mut() {
                if sleep.as_mut().poll(cx).is_ready() {
                    timer = None;
                    return Poll::Ready(Some(Next::Time));
                }
            }
            match inputs.as_mut().poll_next(cx) {
                Poll::Ready(Some(chunk)) => Poll::Ready(Some(Next::Chunk(chunk))),
                Poll::Ready(None) => Poll::Ready(None),
                Poll::Pending => Poll::Pending,
            }
        })
        .await;
        let Some(next) = next else { break };
        let fired = matches!(next, Next::Time).then(|| run.last().deadline).flatten();
        let (inputs_of, origin) = match next {
            Next::Chunk(chunk) => {
                let batch = chunk.into_batch();
                if !batch.iter().all(is_event) {
                    sink.fault(&Fault::new(
                        FaultCode::WorkflowInvalidInput,
                        "A caller writes events alone: time and work results are the host's.",
                        0,
                    ));
                    continue;
                }
                (batch, Origin::User)
            }
            Next::Time => (Vec::new(), Origin::Feedback),
            Next::Settled(Settled::Work { id, outcome, data }) => {
                started.remove(&id);
                attempts.remove(&id);
                let control = Control::Work { id, outcome, data, extra: serde_json::Map::new() };
                (vec![serde_json::to_value(control).unwrap_or_default()], Origin::Feedback)
            }
            Next::Settled(Settled::Failed { id, message }) => {
                // Tried again after a wait that doubles each time, while the run still lists it. A fault
                // of no chunk: the chunk that took the action had its outcome.
                let attempt = attempts.entry(id.clone()).or_insert(0);
                let wait = RETRY.saturating_mul(1 << (*attempt).min(16)).min(RETRY_MAX);
                *attempt += 1;
                retries.push((id.clone(), Box::pin(clock.sleep_until(clock.now().saturating_add(wait)))));
                sink.fault(&Fault::new(
                    FaultCode::WorkflowHostActionFailed,
                    format!("The host action {id} failed, and is tried again in {wait} ms: {message}"),
                    0,
                ));
                continue;
            }
            Next::Retry(id) => {
                started.remove(&id);
                reconcile!();
                continue;
            }
        };
        let now = stamp(clock);
        let mut chunk = Vec::with_capacity(inputs_of.len() + 1);
        chunk.push(serde_json::to_value(Control::<Value>::time(now as i64)).unwrap_or_default());
        chunk.extend(inputs_of);
        if stale(&run, &chunk, origin) {
            continue;
        }
        // A run behind its deadlines catches up with chunks of time alone before an event applies.
        if chunk.iter().any(is_event) {
            let mut caught = None;
            while let Some(deadline) = run.last().deadline {
                if deadline > now || caught.is_some_and(|last| deadline <= last) {
                    break;
                }
                caught = Some(deadline);
                let time = vec![chunk[0].clone()];
                apply_one(&mut run, time, order, journal, sink).await?;
            }
        }
        apply_one(&mut run, chunk, order, journal, sink).await?;
        // A timer whose chunk of time left its deadline where it was never fires: it waits for a change.
        stuck = match (fired, run.last().deadline) {
            (Some(was), Some(is)) if was == is => Some(is),
            _ => None,
        };
        reconcile!();
        in_a_row += 1;
        if in_a_row.is_multiple_of(breathe) {
            yield_now().await;
        }
    }
    Ok(Hosted {
        seq: run.seq(),
        checkpoint: HostedCheckpoint { seq: run.seq(), snapshot: run.checkpoint().snapshot, start },
    })
}

/// What the loop takes next.
enum Next {
    Chunk(Chunk<Value>),
    Time,
    Settled(Settled),
    /// The wait of a host action that failed is over.
    Retry(String),
}

/// Appends `entries` to `journal`, at once of the order `journal-sync`: a
/// journal that does not append at once is `WORKFLOW_JOURNAL_FAILED` then.
async fn write<J: Journal>(journal: &mut J, entries: &[JournalEntry], sync: bool, seq: u64) -> Result<(), Fault> {
    if sync {
        return match now_or_never(journal.append(entries)) {
            Some(appended) => appended.map_err(|e| journal_failed::<J>(&e, seq)),
            None => Err(Fault::new(
                FaultCode::WorkflowJournalFailed,
                "The order journal-sync takes a journal that appends at once.",
                seq,
            )),
        };
    }
    journal.append(entries).await.map_err(|e| journal_failed::<J>(&e, seq))
}

/// An empty list of what `make` gives, which is never called: it names the
/// type of an element that has no name, as a clock's wait.
fn none_of<T>(_make: impl FnOnce() -> T) -> Vec<T> {
    Vec::new()
}

/// Refuses a start of another run or version, or one that is no start of a
/// run, with `code`.
fn check_start(start: &StartEntry, run: &str, version: Option<&str>, code: FaultCode) -> Result<(), Fault> {
    if start.max_timers < 1 {
        return Err(Fault::new(code, "The start has no bound of timers.", 0));
    }
    if start.time < 0 {
        return Err(Fault::new(code, format!("The start is at {}: a time is 0 or more.", start.time), 0));
    }
    if start.version.as_deref() != version {
        return Err(Fault::new(
            code,
            format!("The run is of version {:?} of the machine, not {version:?}.", start.version),
            0,
        ));
    }
    if start.run != run {
        return Err(Fault::new(code, format!("The run is {}, not {run}.", start.run), 0));
    }
    Ok(())
}

/// Reopens a run of its journal's `entries`: its start, then its last
/// checkpoint, then each chunk after it, applied in order, with nothing
/// given out and no work started.
fn replay<C, E>(
    machine: Arc<Machine<C, E>>,
    entries: &[JournalEntry],
    run_id: &str,
    version: Option<&str>,
    checkpoints: Checkpoints,
    options: &HostOptions,
) -> Result<(Run<C, E>, StartEntry), Fault>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    let invalid = |message: String, seq: u64| Fault::new(FaultCode::WorkflowInvalidJournal, message, seq);
    let Some(JournalEntry::Start(start)) = entries.first() else {
        return Err(invalid(
            "The journal does not start with its start: a store that drops its oldest entries is no journal.".into(),
            0,
        ));
    };
    check_start(start, run_id, version, FaultCode::WorkflowInvalidJournal)?;
    let from = entries.iter().rev().find_map(|entry| match entry {
        JournalEntry::Snapshot(snapshot) => Some(Checkpoint { seq: snapshot.seq, snapshot: snapshot.snapshot.clone() }),
        _ => None,
    });
    let reopened = from.is_some();
    let run_options = Options {
        actor: Some(start.actor.clone()),
        time: (!reopened).then_some(start.time),
        input: if reopened { None } else { start.input.clone() },
        checkpoint: Some(checkpoints),
        max_timers: Some(start.max_timers),
        max_steps: options.options.max_steps,
        from,
    };
    let (mut run, _) = Run::open(machine, run_options)?;
    let mut seen = BTreeSet::new();
    for entry in entries {
        let JournalEntry::Chunk(chunk) = entry else { continue };
        // Two chunks of one seq are two writers of one run: the journal is no run's.
        if !seen.insert(chunk.seq) {
            return Err(invalid(
                format!("The journal holds chunk {} twice: two writers wrote the run.", chunk.seq),
                chunk.seq,
            ));
        }
        if chunk.seq <= run.seq() {
            continue;
        }
        if chunk.seq != run.seq() + 1 {
            return Err(invalid(format!("The journal skips from chunk {} to {}.", run.seq(), chunk.seq), chunk.seq));
        }
        let batch = chunk.chunk.iter().map(|input| serde_json::to_value(input).unwrap_or_default()).collect();
        match run.step(&Chunk::Batch(batch)) {
            Ok(Applied::Applied { .. } | Applied::Rejected { .. }) => {}
            Err(fault) if fault.code.is_recoverable() => {}
            Err(fault) => return Err(fault),
        }
    }
    Ok((run, start.clone()))
}

/// Whether a chunk of the host's own clock or worker changes nothing, read
/// against the run as it is: time alone, of a run whose deadline is not due
/// by it, or the result of work the run no longer waits for. A race lost: it
/// takes no `seq`, as in `@xmachines/run`'s host.
fn stale<C, E>(run: &Run<C, E>, chunk: &[Value], origin: Origin) -> bool
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    if origin != Origin::Feedback {
        return false;
    }
    let last = run.last();
    let work: Vec<&str> = chunk.iter().filter(|i| i["kind"] == "work").filter_map(|i| i["id"].as_str()).collect();
    if work.is_empty() {
        let now = chunk[0]["now"].as_u64().unwrap_or_default();
        return last.deadline.is_none_or(|deadline| deadline > now);
    }
    work.len() == chunk.len() - 1 && work.iter().all(|id| !last.work.iter().any(|w| w.id() == *id))
}

/// Applies one stamped chunk under the run's next `seq`, journaled in
/// `order`, its records given to `sink`, and its checkpoint journaled when
/// its snapshot holds the state. A fault the run goes on after goes to the
/// sink; any other is the host's.
async fn apply_one<C, E, J: Journal, O: Sink>(
    run: &mut Run<C, E>,
    chunk: Vec<Value>,
    order: Order,
    journal: &mut J,
    sink: &mut O,
) -> Result<(), Fault>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    let seq = run.seq() + 1;
    let inputs = chunk
        .iter()
        .map(|input| Input::from_value(input.clone()))
        .collect::<Result<_, _>>()
        .map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("Chunk {seq}: {e}."), seq))?;
    let entry = JournalEntry::Chunk(ChunkEntry { seq, chunk: inputs, source: None, epoch: None });
    if order != Order::ApplyFirst {
        write(journal, std::slice::from_ref(&entry), order == Order::JournalSync, seq).await?;
    }
    let mut records = Vec::new();
    let applied = run.apply(Chunk::Batch(chunk), &mut records);
    if order == Order::ApplyFirst {
        records.iter().for_each(|record| sink.record(record));
        write(journal, std::slice::from_ref(&entry), false, seq).await?;
    }
    if let Some(Record::Snapshot { seq, snapshot }) = records.last() {
        if snapshot.state.is_some() {
            let checkpoint = JournalEntry::Snapshot(SnapshotEntry {
                epoch: None,
                positions: None,
                published: None,
                seq: *seq,
                snapshot: (**snapshot).clone(),
            });
            write(journal, std::slice::from_ref(&checkpoint), order == Order::JournalSync, *seq).await?;
        }
    }
    if order != Order::ApplyFirst {
        records.iter().for_each(|record| sink.record(record));
    }
    match applied {
        Ok(_) => Ok(()),
        Err(fault) if fault.code.is_recoverable() => {
            sink.fault(&fault);
            Ok(())
        }
        Err(fault) => Err(fault),
    }
}

/// A future that is pending once, then ready: the loop yields to its
/// executor, so a run that feeds itself can't starve it.
async fn yield_now() {
    let mut yielded = false;
    poll_fn(|cx| {
        if yielded {
            Poll::Ready(())
        } else {
            yielded = true;
            cx.waker().wake_by_ref();
            Poll::Pending
        }
    })
    .await;
}

/// A clock a test moves by hand: the twin of a fake timer. Its time moves
/// only by [`ManualClock::set`] and [`ManualClock::advance`], which wake the
/// waits due by then. Clones share one clock.
#[derive(Debug, Clone, Default)]
pub struct ManualClock {
    state: Arc<Mutex<ManualState>>,
}

#[derive(Debug, Default)]
struct ManualState {
    now: u64,
    /// The next wait's id.
    next: u64,
    /// Each armed wait not yet due, by its id: when it is due, and its waker.
    waiting: std::collections::BTreeMap<u64, (u64, Waker)>,
}

impl ManualClock {
    /// A clock at `now`.
    pub fn new(now: u64) -> Self {
        Self { state: Arc::new(Mutex::new(ManualState { now, ..ManualState::default() })) }
    }

    /// Moves the clock to `now`, if it is ahead, and wakes each wait due by
    /// then.
    pub fn set(&self, now: u64) {
        let due: Vec<Waker> = {
            let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
            state.now = state.now.max(now);
            let now = state.now;
            let (due, waiting) = std::mem::take(&mut state.waiting).into_iter().partition(|(_, (at, _))| *at <= now);
            state.waiting = waiting;
            due.into_values().map(|(_, waker)| waker).collect()
        };
        due.into_iter().for_each(Waker::wake);
    }

    /// Moves the clock on by `ms`.
    pub fn advance(&self, ms: u64) {
        let now = self.now();
        self.set(now + ms);
    }

    /// How many waits are armed and not yet due: one for each wait polled
    /// and not yet done, woken or dropped.
    pub fn waiting(&self) -> usize {
        self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.len()
    }
}

impl Clock for ManualClock {
    fn now(&self) -> u64 {
        self.state.lock().unwrap_or_else(PoisonError::into_inner).now
    }

    fn sleep_until(&self, at: u64) -> impl Future<Output = ()> {
        let id = {
            let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
            state.next += 1;
            state.next
        };
        ManualSleep { state: Arc::clone(&self.state), at, id }
    }
}

/// A wait of a [`ManualClock`]: one entry of its clock while it is armed,
/// its waker replaced when it is polled again, and gone once it is due,
/// woken or dropped.
#[derive(Debug)]
struct ManualSleep {
    state: Arc<Mutex<ManualState>>,
    at: u64,
    id: u64,
}

impl Future for ManualSleep {
    type Output = ();

    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
        if state.now >= self.at {
            state.waiting.remove(&self.id);
            return Poll::Ready(());
        }
        match state.waiting.get_mut(&self.id) {
            Some((_, waker)) => waker.clone_from(cx.waker()),
            None => {
                state.waiting.insert(self.id, (self.at, cx.waker().clone()));
            }
        }
        Poll::Pending
    }
}

impl Drop for ManualSleep {
    fn drop(&mut self) {
        self.state.lock().unwrap_or_else(PoisonError::into_inner).waiting.remove(&self.id);
    }
}