Skip to main content

tilo_actions/
executor.rs

1//! Applying, replaying, and dispatching actions.
2//!
3//! Three entry points, one commit discipline: [`apply_local`] runs an
4//! action on the local replica, minting a fresh envelope (the origin);
5//! [`replay`] decodes an envelope's action and applies it, reproducing
6//! the *identical* change on any replica at the same base state (peers);
7//! [`dispatch`] is the locus-aware front API — `ClientLocal` applies
8//! and hands to the transport for replication; `ServerPreferred` submits to
9//! an authoritative host and fails closed when none answers.
10//!
11//! The commit discipline is what makes replay deterministic: every
12//! apply pins the Automerge actor id (from the envelope's [`ActionId`])
13//! and the commit time, then restores the doc's previous actor. A fresh
14//! actor id per action means its single change is `seq == 1` on every
15//! replica, so the change hash is content-addressed identical everywhere.
16
17use automerge::ActorId;
18use automerge::transaction::{CommitOptions, Transactable};
19
20use crate::action::{Action, ActionError, ActionId, Doc, EncodedAction, ExecutionLocus};
21use crate::context::{ActionContext, CONTINUATION_PREFIX, ChangeKind};
22use crate::entry::{Described, Did};
23use crate::envelope::ActionEnvelope;
24use crate::registry::ActionRegistry;
25
26thread_local! {
27    static REPLAYING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
28    static INVOKING: std::cell::RefCell<Option<ActionContext>> = const { std::cell::RefCell::new(None) };
29    static OPEN_STEP: std::cell::Cell<Option<ActionId>> = const { std::cell::Cell::new(None) };
30}
31
32/// Whether the executor is reproducing an existing action rather than
33/// admitting a new invocation. Replay must reproduce document writes without
34/// issuing host-local approvals or other outside effects again.
35pub fn is_replaying() -> bool {
36    REPLAYING.with(std::cell::Cell::get)
37}
38
39struct ReplayScope(bool);
40
41impl ReplayScope {
42    fn enter() -> Self {
43        Self(REPLAYING.with(|replaying| replaying.replace(true)))
44    }
45}
46
47impl Drop for ReplayScope {
48    fn drop(&mut self) {
49        REPLAYING.with(|replaying| replaying.set(self.0));
50    }
51}
52
53/// Call `work` with [`is_replaying`] saying `replaying`: an app's model module
54/// applies its verb as the device that called it does, reproducing or
55/// admitting.
56pub fn replaying_as<T>(replaying: bool, work: impl FnOnce() -> T) -> T {
57    let outer = REPLAYING.with(|current| current.replace(replaying));
58    let _restore = ReplayScope(outer);
59    work()
60}
61
62/// Open the undo step the changes committed on this thread join until the
63/// next one opens: every action applied meanwhile records it as its
64/// [`gesture`](ActionContext::gesture), so the document's history takes them
65/// back as one step. The host's history opens one at every step boundary;
66/// `None` closes it.
67pub fn open_step(step: Option<ActionId>) {
68    OPEN_STEP.with(|open| open.set(step));
69}
70
71/// The undo step open on this thread, if any (see [`open_step`]).
72pub fn current_step() -> Option<ActionId> {
73    OPEN_STEP.with(std::cell::Cell::get)
74}
75
76/// The document key prefix of a step's undo marker, followed by the step's
77/// change hash: `true` once taken back, a negative attempt count while its
78/// undo waits for an outside consequence to settle, a positive one while its
79/// redo does.
80pub const UNDONE_KEY: &str = "tilo:undone:";
81
82thread_local! {
83    /// The steps the action applying now undoes or redoes, and whether it
84    /// queued an outside consequence that settles them.
85    static COMPENSATING: std::cell::RefCell<Option<(Vec<String>, bool)>> =
86        const { std::cell::RefCell::new(None) };
87}
88
89/// The undo or redo of the steps `marks` (their change hashes) applying its
90/// compensating action on this thread: an outside consequence the action
91/// queues reads them ([`await_compensation`]), and the step counts as taken
92/// back (or brought back) only once that consequence settles
93/// ([`settle_compensation`]).
94pub struct CompensatingScope(Option<(Vec<String>, bool)>);
95
96impl CompensatingScope {
97    #[must_use]
98    pub fn enter(marks: Vec<String>) -> Self {
99        Self(COMPENSATING.with(|current| current.replace(Some((marks, false)))))
100    }
101
102    /// Whether the action queued an outside consequence that will settle
103    /// the steps.
104    #[must_use]
105    pub fn awaited(&self) -> bool {
106        COMPENSATING.with(|current| {
107            current
108                .borrow()
109                .as_ref()
110                .is_some_and(|(_, awaited)| *awaited)
111        })
112    }
113}
114
115impl Drop for CompensatingScope {
116    fn drop(&mut self) {
117        COMPENSATING.with(|current| *current.borrow_mut() = self.0.take());
118    }
119}
120
121/// The steps an outside consequence queued now settles, recording that
122/// their undo or redo waits for it; empty outside a compensation.
123#[must_use]
124pub fn await_compensation() -> Vec<String> {
125    COMPENSATING.with(|current| {
126        current
127            .borrow_mut()
128            .as_mut()
129            .map(|(marks, awaited)| {
130                *awaited = true;
131                marks.clone()
132            })
133            .unwrap_or_default()
134    })
135}
136
137/// Mark the step `hash` as waiting for the outside consequence its undo (or,
138/// with `redo`, its redo) queued: the next attempt's marker, negative for an
139/// undo, positive for a redo. The step stays as it was until
140/// [`settle_compensation`] completes it.
141pub fn await_settlement(doc: &mut Doc, hash: &str, redo: bool) -> Result<(), ActionError> {
142    use automerge::ReadDoc as _;
143    let key = format!("{UNDONE_KEY}{hash}");
144    let before = doc
145        .get(automerge::ROOT, &key)?
146        .and_then(|(value, _)| value.as_i64())
147        .filter(|attempt| (*attempt > 0) == redo && *attempt != 0)
148        .unwrap_or(0);
149    let attempt = if redo {
150        before.checked_add(1)
151    } else {
152        before.checked_sub(1)
153    }
154    .ok_or_else(|| ActionError::Refused("settlement attempts exceed the budget".into()))?;
155    doc.put(automerge::ROOT, key, attempt)?;
156    Ok(())
157}
158
159/// Mark the undo (or redo) of the step `hash` complete: its outside
160/// consequence settled.
161pub fn settle_compensation(doc: &mut Doc, hash: &str) -> Result<(), ActionError> {
162    use automerge::ReadDoc as _;
163    let key = format!("{UNDONE_KEY}{hash}");
164    let pending = doc
165        .get(automerge::ROOT, &key)?
166        .and_then(|(value, _)| value.as_i64())
167        .filter(|attempt| *attempt != 0)
168        .ok_or_else(|| ActionError::Refused("history compensation is not pending".into()))?;
169    if pending < 0 {
170        doc.put(automerge::ROOT, key, true)?;
171    } else {
172        doc.delete(automerge::ROOT, key)?;
173    }
174    Ok(())
175}
176
177/// The context of the action whose [`Action::apply`] is running on this
178/// thread: who invoked it and in which work group (an agent run). Pinned by
179/// the envelope like the actor and the time, so a replica replaying the
180/// action reads the same value. `None` outside an apply, or for an action
181/// dispatched with no context.
182///
183/// An action whose meaning depends on its author — "undo my last step" —
184/// reads it here; any other action must not.
185pub fn invoking_context() -> Option<ActionContext> {
186    INVOKING.with(|current| current.borrow().clone())
187}
188
189/// What `read` makes of the [`invoking_context`], without copying it: it
190/// carries the action's arguments, which may be large.
191pub fn reading_invoking_context<T>(read: impl FnOnce(Option<&ActionContext>) -> T) -> T {
192    INVOKING.with(|current| read(current.borrow().as_ref()))
193}
194
195/// Call `work` with `context` as the [`invoking_context`]: an operation the
196/// app carries out itself (a write into a part of a chain) keeps the agent
197/// session and purpose its invocation came with.
198pub fn with_invoking_context<T>(context: Option<ActionContext>, work: impl FnOnce() -> T) -> T {
199    let _invoking = InvokingScope::enter(context);
200    work()
201}
202
203/// Sets [`invoking_context`] for one apply and restores the outer value.
204struct InvokingScope(Option<ActionContext>);
205
206impl InvokingScope {
207    fn enter(context: Option<ActionContext>) -> Self {
208        Self(INVOKING.with(|current| current.replace(context)))
209    }
210}
211
212impl Drop for InvokingScope {
213    fn drop(&mut self) {
214        let outer = self.0.take();
215        INVOKING.with(|current| *current.borrow_mut() = outer);
216    }
217}
218
219/// Where an envelope reads what the action did from.
220enum Before {
221    /// The document before the action applies: the description and the
222    /// compensation are read from it.
223    Doc,
224    /// The document with the action's writes as its open transaction: the
225    /// description is the one read before its first write, and it records no
226    /// compensation, which only the state before it could compute.
227    Written(Option<Box<Described>>),
228}
229
230/// Build an envelope for `action` at the doc's current heads, without
231/// applying — used by [`dispatch`] so a `ServerPreferred` action can be
232/// submitted before (or instead of) local apply.
233fn envelope_for(
234    doc: &mut Doc,
235    action: &dyn Action,
236    encoded: EncodedAction,
237    actor: Option<&[u8]>,
238    context: Option<ActionContext>,
239    before: Before,
240) -> Result<ActionEnvelope, ActionError> {
241    let pinned = (ActionId::new(), tilo_clock::unix_now_i64());
242    envelope_pinned(doc, action, encoded, actor, context, before, pinned)
243}
244
245/// The envelope [`apply_local_with_context`] writes for `action` at the
246/// doc's current heads, under the invocation id and origin time (seconds
247/// since the Unix epoch) the caller pins rather than fresh ones: a device
248/// applying an app's verb from its package mints both from the request, so
249/// every holder given the same request writes the same change.
250///
251/// # Errors
252///
253/// See [`apply_local`].
254pub fn envelope_at(
255    doc: &mut Doc,
256    action: &dyn Action,
257    encoded: EncodedAction,
258    (actor, context): (&[u8], ActionContext),
259    pinned: (ActionId, i64),
260) -> Result<ActionEnvelope, ActionError> {
261    envelope_pinned(
262        doc,
263        action,
264        encoded,
265        Some(actor),
266        Some(context),
267        Before::Doc,
268        pinned,
269    )
270}
271
272fn envelope_pinned(
273    doc: &mut Doc,
274    action: &dyn Action,
275    encoded: EncodedAction,
276    actor: Option<&[u8]>,
277    context: Option<ActionContext>,
278    before: Before,
279    (id, timestamp): (ActionId, i64),
280) -> Result<ActionEnvelope, ActionError> {
281    let base = match before {
282        Before::Doc => doc.get_heads(),
283        Before::Written(_) => doc.committed_heads(),
284    };
285    // The action declares what it is; a context may only say a content
286    // action is nobody's step this time (a record's first-run seed).
287    let change = action.change_kind();
288    let mut context = context.unwrap_or_default();
289    if change != ChangeKind::Content {
290        context.change = change;
291    }
292    context.kind = Some(action.action_kind());
293    if action.incoming_message()
294        && !context
295            .facets
296            .iter()
297            .any(|facet| facet.key == crate::INCOMING_MESSAGE_FACET)
298    {
299        context.facets.push(crate::ActionFacet::new(
300            crate::INCOMING_MESSAGE_FACET,
301            "true",
302        ));
303    }
304    if let Some(readers) = action.readers() {
305        context
306            .facets
307            .retain(|facet| facet.key != crate::READERS_FACET);
308        context.facets.push(crate::ActionFacet::new(
309            crate::READERS_FACET,
310            crate::contract::readers_facet(&readers),
311        ));
312    }
313    if context.gesture.is_none() {
314        context.gesture = current_step();
315    }
316    // What history records the step did: described by the value itself from
317    // the document before it applies, else as the published action the API
318    // resolved, else as the verb its encoded form names.
319    let app = context.app.as_ref().map(|app| app.id.clone());
320    // The value describes itself as it will apply: under its invoker.
321    let (own, written) = match before {
322        Before::Doc => {
323            let _invoking = InvokingScope::enter(Some(context.clone()));
324            (action.describe(doc), false)
325        }
326        Before::Written(described) => (described.map(|described| *described), true),
327    };
328    let described = own
329        .or_else(|| context.described())
330        .or_else(|| Described::from_encoded(&encoded, app.as_deref()));
331    if let Some(mut described) = described {
332        if let Some(app) = app {
333            name_app(&mut described.what, &app);
334        }
335        context = context.with_described(described);
336    }
337    // Caller-supplied descriptive context cannot choose executable history.
338    // Compute it from the actual decoded action at its canonical before state,
339    // under the actor the change commits as: what the action mints (the
340    // entry a compensation names) depends on it.
341    let actor = actor.filter(|a| !a.is_empty()).map(<[u8]>::to_vec);
342    let committing = actor
343        .clone()
344        .map_or_else(|| ActorId::from(id.actor_bytes().to_vec()), ActorId::from);
345    let compensation = if written {
346        None
347    } else {
348        inverse_as(doc, action, committing)
349    };
350    // A person setting the same item again with the same verb, right after
351    // they last did, continues that run: undo takes it back and History
352    // lists it as one ([`crate::run`]).
353    if compensation.is_none()
354        && let Some(actor) = actor.as_deref()
355        && let Some(gesture) = crate::run::continued_gesture(doc, actor, &context, timestamp)
356    {
357        context.gesture = Some(gesture);
358    }
359    // Only what undo adds is bounded hard: the action itself is recorded
360    // when it fits the budget, and travels in the envelope anyway.
361    if let Some(compensation) = &compensation
362        && serde_json::to_vec(compensation)
363            .map_err(ActionError::Encode)?
364            .len()
365            > crate::context::COMPENSATION_BUDGET
366    {
367        return Err(ActionError::Refused(
368            "document compensation exceeds the history budget".into(),
369        ));
370    }
371    context.action = Some(recorded_form(&encoded)?);
372    context.compensation = compensation;
373    let context = Some(context);
374    Ok(ActionEnvelope {
375        id,
376        action: encoded,
377        base_heads: base.iter().map(|h| h.0).collect(),
378        timestamp,
379        locus: action.locus(),
380        actor,
381        context,
382    })
383}
384
385/// The action's [`inverse_encoded`](Action::inverse_encoded) at `doc`, as
386/// the change written by `actor` records it: what the action mints depends
387/// on its writer.
388pub fn inverse_as(doc: &mut Doc, action: &dyn Action, actor: ActorId) -> Option<EncodedAction> {
389    let previous = doc.get_actor().clone();
390    doc.set_actor(actor);
391    let inverse = action.inverse_encoded(doc);
392    doc.set_actor(previous);
393    inverse
394}
395
396/// Fill the app of every verb in `what` that does not name one.
397fn name_app(what: &mut Did, app: &str) {
398    match what {
399        Did::Verb(verb) if verb.action.app.is_empty() => app.clone_into(&mut verb.action.app),
400        Did::Group(group) => {
401            for member in &mut group.members {
402                name_app(member, app);
403            }
404        }
405        _ => {}
406    }
407}
408
409/// Apply `action` to `doc` under the envelope's pinned actor id +
410/// timestamp, then restore the doc's previous actor. The single mutation
411/// path shared by [`apply_local`], [`replay`], and [`dispatch`] so
412/// origin and peers all commit the byte-identical change.
413///
414/// # Why a no-op action must not be committed
415///
416/// Each dispatch pins a *fresh* random actor id. That id only becomes a
417/// permanent document actor if the action writes an op — automerge
418/// introduces the actor at the transaction's first op and prunes it
419/// again if the transaction is empty. But
420/// [`AutoCommit::commit_with`](automerge::AutoCommit::commit_with)
421/// *always* opens a transaction, so committing a no-op would introduce
422/// the fresh actor into the document's actor table, mirror it into the
423/// patch-log actor table, then immediately prune it from the document —
424/// leaving the patch log referencing an actor the document no longer
425/// has. Because pinned ids are random, each sorts into an arbitrary
426/// slot, and automerge-0.8's `migrate_actors` (which reconciles the
427/// patch log's actor table on the *next* transaction and only knows how
428/// to *insert*, never remove) hits that stranded "ghost" and panics with
429/// `PatchLogMismatch`. Stacking several dispatches on one document with
430/// nothing draining the patch log between them is exactly where this surfaces.
431///
432/// A no-op action (a change-guarded write whose value already held, a
433/// toggle whose precondition was already satisfied) is ordinary and must
434/// be safe. We detect the empty result via
435/// [`pending_ops`](Transactable::pending_ops) and abandon it without
436/// committing — see [`abort_pinned_change`]. Only a change-producing
437/// action is committed, under the pinned actor + timestamp, exactly as before.
438fn apply_under_envelope(
439    doc: &mut Doc,
440    action: &dyn Action,
441    env: &ActionEnvelope,
442    content: Option<&tilo_content::ContentStore>,
443) -> Result<Option<crate::entry::ActionItem>, ActionError> {
444    let prev_actor = doc.get_actor().clone();
445    // `get_heads`/`set_actor` both close any open transaction, so we
446    // start from a clean commit boundary and the action's ops land in
447    // their own change under the pinned actor.
448    doc.set_actor(env.actor());
449    let applied = {
450        let _invoking = InvokingScope::enter(env.context.clone());
451        action.apply(doc)
452    };
453    if let Err(e) = applied {
454        abort_pinned_change(doc, prev_actor);
455        return Err(e);
456    }
457    let mut made = None;
458    if doc.pending_ops() > 0 {
459        // The action produced ops: commit as the pinned actor's single
460        // change under the pinned timestamp, content-addressed identical on
461        // origin and every replaying replica. A step that said what it did
462        // but named no item made one the document before it lacked: the item
463        // it made is what the change is about, and is read now that it is
464        // written. Only the origin reads it: a replica replays the change
465        // under the entry it was recorded with, so a change older than this
466        // rule keeps the words it was written with.
467        made = env
468            .context
469            .as_ref()
470            .filter(|context| !is_replaying() && context.what.is_some() && context.item.is_none())
471            .and_then(|_| action.made(doc));
472        commit_pinned(doc, env, made.as_ref());
473        doc.set_actor(prev_actor);
474        crate::content::keep(env, content);
475    } else {
476        // No ops: a genuine no-op. Do not `commit_with` (it would pin then
477        // prune this action's fresh actor and desync the patch log — see the
478        // function docs). Leave the document exactly as the action found it.
479        abort_pinned_change(doc, prev_actor);
480    }
481    Ok(made)
482}
483
484/// Commit the doc's open transaction as `env`'s change: under its pinned
485/// time, with the message its context writes. `made` is the item the action
486/// made that its description could not name, which the message names.
487fn commit_pinned(doc: &mut Doc, env: &ActionEnvelope, made: Option<&crate::entry::ActionItem>) {
488    let named = made.and_then(|item| {
489        let context = env.context.as_ref()?;
490        Some(
491            context
492                .clone()
493                .with_described(context.described()?.on(item.id.clone(), item.label.clone())),
494        )
495    });
496    let context = named.as_ref().or(env.context.as_ref());
497    let mut options = CommitOptions::default().with_time(env.timestamp);
498    if let Some(message) = context.and_then(|context| entry_message(doc, &env.actor(), context)) {
499        options = options.with_message(message);
500    }
501    doc.commit_with(options);
502}
503
504/// `env` with the item `made` its change names, when it described one it
505/// could not name before it applied: what a caller that replicates or
506/// answers the change reads, as the change itself records it.
507fn named(mut env: ActionEnvelope, made: Option<crate::entry::ActionItem>) -> ActionEnvelope {
508    if let Some(item) = made
509        && let Some(context) = env.context.as_ref()
510        && let Some(described) = context.described()
511    {
512        env.context = Some(
513            context
514                .clone()
515                .with_described(described.on(item.id, item.label)),
516        );
517    }
518    env
519}
520
521/// The message `context` is written with by `actor` on `doc`: as the
522/// continuation of the actor's last whole entry when the change differs from
523/// it only in its gesture and action payload, else whole. Changes of others
524/// in between do not matter. A function of the document, so a replaying device writes the
525/// same message, hence the same change.
526#[must_use]
527pub fn entry_message(doc: &Doc, actor: &ActorId, context: &ActionContext) -> Option<String> {
528    if context.gesture.is_some() && context.compensation.is_none() {
529        let document = doc.committed_document();
530        let continuation = document
531            .hash_of_actor_seq(actor, document.applied_seq(actor))
532            .and_then(|last| context.continuation_of(&opening_entry(document, last)?));
533        if continuation.is_some() {
534            return continuation;
535        }
536    }
537    context.change_message()
538}
539
540/// How deep [`entry_of`] follows its writer's continuations back to the
541/// entry they continue. A writer writes its entry whole again past it, so a
542/// change read on its own costs at most this many steps back.
543const MAX_CONTINUATIONS: usize = 256;
544
545/// How many continuations [`entry_of`] remembers the first entry of.
546const CONTINUATIONS_KEPT: usize = 8;
547
548thread_local! {
549    /// The continuations [`entry_of`] read last, each with the whole entry
550    /// it continues and how many changes back that entry is. A keystroke's
551    /// change continues the one before it, so its entry is found one step
552    /// back instead of by walking the whole gesture again. A change's hash
553    /// names its content and history, so what is kept for it holds on any
554    /// document.
555    static CONTINUATIONS: std::cell::RefCell<std::collections::VecDeque<(automerge::ChangeHash, ActionContext, usize)>> =
556        const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
557}
558
559#[cfg(test)]
560thread_local! {
561    /// Changes [`entry_of`] stepped back over, for the test that pins it.
562    static STEPS_BACK: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
563}
564
565/// The entry of the change `hash`: its message's, or for a continuation its
566/// writer's last whole entry with the continuation's gesture and action
567/// (found by following its writer's earlier changes).
568#[must_use]
569pub fn entry_of(doc: &automerge::Automerge, hash: automerge::ChangeHash) -> Option<ActionContext> {
570    let entry = opening_entry(doc, hash)?;
571    match doc.get_change_meta_by_hash(&hash)?.message.as_deref() {
572        Some(message) if message.starts_with(CONTINUATION_PREFIX) => {
573            ActionContext::continued(message, &entry)
574        }
575        _ => Some(entry),
576    }
577}
578
579/// The whole entry of the change `hash`: its own, or for a continuation its
580/// writer's last whole entry, which a continuation is written and read
581/// against.
582fn opening_entry(doc: &automerge::Automerge, hash: automerge::ChangeHash) -> Option<ActionContext> {
583    let meta = doc.get_change_meta_by_hash(&hash)?;
584    let message = meta.message.as_deref()?;
585    if let Some(entry) = ActionContext::from_change_message(message) {
586        return Some(entry);
587    }
588    if !message.starts_with(CONTINUATION_PREFIX) {
589        return None;
590    }
591    let (first, depth) = first_entry(doc, &meta)?;
592    CONTINUATIONS.with_borrow_mut(|kept| {
593        if !kept.iter().any(|(kept, ..)| *kept == hash) {
594            if kept.len() >= CONTINUATIONS_KEPT {
595                kept.pop_front();
596            }
597            kept.push_back((hash, first.clone(), depth));
598        }
599    });
600    Some(first)
601}
602
603/// The whole entry the continuation `meta` continues, and how many of its
604/// writer's changes back it is: none when it is more than
605/// [`MAX_CONTINUATIONS`] back.
606fn first_entry(
607    doc: &automerge::Automerge,
608    meta: &automerge::ChangeMetadata<'_>,
609) -> Option<(ActionContext, usize)> {
610    for depth in 1..=MAX_CONTINUATIONS {
611        #[cfg(test)]
612        STEPS_BACK.with(|steps| steps.set(steps.get().saturating_add(1)));
613        let seq = meta.seq.checked_sub(u64::try_from(depth).ok()?)?;
614        let earlier = doc.get_change_meta_by_hash(&doc.hash_of_actor_seq(&meta.actor, seq)?)?;
615        let text = earlier.message.as_deref()?;
616        if let Some(first) = ActionContext::from_change_message(text) {
617            return Some((first, depth));
618        }
619        if !text.starts_with(CONTINUATION_PREFIX) {
620            return None;
621        }
622        let kept = CONTINUATIONS.with_borrow(|kept| {
623            kept.iter()
624                .find(|(hash, ..)| *hash == earlier.hash)
625                .map(|(_, first, back)| (first.clone(), *back))
626        });
627        if let Some((first, back)) = kept {
628            let depth = depth.checked_add(back)?;
629            return (depth <= MAX_CONTINUATIONS).then_some((first, depth));
630        }
631    }
632    None
633}
634
635#[cfg(test)]
636#[path = "executor_entry_tests.rs"]
637mod entry_tests;
638
639/// The entries of a document's changes read in causal order, each
640/// continuation folded into its writer's last whole entry as it is read.
641#[derive(Default)]
642pub struct EntryReader {
643    firsts: std::collections::HashMap<ActorId, ActionContext>,
644}
645
646impl EntryReader {
647    /// The entry of a change by `actor` with `message`, read after every
648    /// change before it.
649    pub fn read(&mut self, actor: &ActorId, message: Option<&str>) -> Option<ActionContext> {
650        let message = message?;
651        if let Some(entry) = ActionContext::from_change_message(message) {
652            self.firsts.insert(actor.clone(), entry.clone());
653            return Some(entry);
654        }
655        ActionContext::continued(message, self.firsts.get(actor)?)
656    }
657}
658
659/// Abandon a dispatch that produced no committed change, leaving the
660/// document — and the `AutoCommit` patch log — as consistent as a
661/// dispatch that never ran. Used for both the no-op result and the
662/// mid-apply error path.
663///
664/// The hazard: if the action opened a transaction under its
665/// freshly-pinned actor but that transaction is discarded (an errored
666/// write, or a mutation producing no op), automerge prunes the now-unused
667/// actor from the document while the patch log still names it — the
668/// stranded "ghost" that makes the next apply's `migrate_actors` panic
669/// with `PatchLogMismatch`.
670/// [`rollback`](automerge::AutoCommit::rollback) discards the open
671/// transaction; [`reset_diff_cursor`](automerge::AutoCommit::reset_diff_cursor)
672/// then reinstalls a fresh patch log seeded from the document's current
673/// actor table, so no ghost can survive either way.
674///
675/// The reset only discards an *incremental diff index* (a rendering
676/// optimization nothing in Tilo currently arms on an app document);
677/// document content and history are untouched, so replay stays
678/// byte-identical. Runs only on this abandon path — a change-producing
679/// dispatch keeps its patch log intact.
680fn abort_pinned_change(doc: &mut Doc, prev_actor: ActorId) {
681    doc.rollback();
682    doc.reset_diff_cursor();
683    doc.set_actor(prev_actor);
684}
685
686/// Apply `action` to the local replica and return its replayable
687/// envelope. `encoded` is the serialized form carried to peers — must
688/// encode the *same* action.
689///
690/// # Errors
691///
692/// Returns whatever [`Action::apply`] returns
693/// for `action` — typically [`ActionError::Automerge`] for a document
694/// write failure, or [`ActionError::Refused`] if the app declined the action.
695pub fn apply_local(
696    doc: &mut Doc,
697    action: &dyn Action,
698    encoded: EncodedAction,
699) -> Result<ActionEnvelope, ActionError> {
700    apply_local_by(doc, action, encoded, None)
701}
702
703/// [`apply_local`], attributing the resulting change to `actor`: the
704/// Automerge change commits under *their* actor so the workspace's history
705/// names them the way it names a typing person. `None` keeps the
706/// [`ActionId`]-derived actor, as before.
707///
708/// # Errors
709///
710/// See [`apply_local`].
711pub fn apply_local_by(
712    doc: &mut Doc,
713    action: &dyn Action,
714    encoded: EncodedAction,
715    actor: Option<&[u8]>,
716) -> Result<ActionEnvelope, ActionError> {
717    apply_steps(doc, action, encoded, (actor, None), &mut |_| {})
718}
719
720/// Apply `action` as the change of `actor` described by `context`, or, for a value that stands
721/// for several steps ([`Action::steps`]), each of its steps as a change of its own, newest first:
722/// the one way every action is applied here. `each` is handed every envelope as it is applied;
723/// the last is returned. A step that fails leaves the steps before it applied.
724fn apply_steps(
725    doc: &mut Doc,
726    action: &dyn Action,
727    encoded: EncodedAction,
728    (actor, context): (Option<&[u8]>, Option<ActionContext>),
729    each: &mut dyn FnMut(&ActionEnvelope),
730) -> Result<ActionEnvelope, ActionError> {
731    // Read under the invocation that asks, as its steps then apply: whose steps they are
732    // depends on who invokes.
733    let steps = {
734        let _invoking = InvokingScope::enter(context.clone());
735        action.steps(doc).filter(|steps| !steps.is_empty())
736    };
737    let Some(steps) = steps else {
738        let env = envelope_for(doc, action, encoded, actor, context, Before::Doc)?;
739        let made = apply_under_envelope(doc, action, &env, None)?;
740        let env = named(env, made);
741        each(&env);
742        return Ok(env);
743    };
744    // The steps are one move of the person's: one gesture, which undo and redo take as one
745    // step, and one group, which History lists as one.
746    let mut context = context.unwrap_or_default();
747    let asked = {
748        let _invoking = InvokingScope::enter(Some(context.clone()));
749        action.describe(doc)
750    };
751    let op = match asked.map(|asked| asked.what) {
752        Some(Did::History(step)) => step.op,
753        _ => crate::HistoryOp::Undo,
754    };
755    let gesture = *context.gesture.get_or_insert_with(ActionId::new);
756    context.group.get_or_insert_with(|| crate::WorkGroup {
757        id: gesture.0.to_string(),
758        label: None,
759        kind: crate::context::history_group(&op),
760        declared_id: None,
761        session: None,
762    });
763    let context = Some(context);
764    let mut last = None;
765    for (step, payload) in steps {
766        let encoded = EncodedAction {
767            type_id: encoded.type_id.clone(),
768            payload,
769        };
770        let env = envelope_for(
771            doc,
772            step.as_ref(),
773            encoded,
774            actor,
775            context.clone(),
776            Before::Doc,
777        )?;
778        let made = apply_under_envelope(doc, step.as_ref(), &env, None)?;
779        let env = named(env, made);
780        each(&env);
781        last = Some(env);
782    }
783    last.ok_or_else(|| ActionError::Refused("no step to apply".into()))
784}
785
786/// [`apply_local`], with semantic provenance embedded in the resulting
787/// durable change. Use this at framework/action-API boundaries where the
788/// resource and human action label are already known.
789///
790/// # Errors
791///
792/// See [`apply_local`].
793pub fn apply_local_with_context(
794    doc: &mut Doc,
795    action: &dyn Action,
796    encoded: EncodedAction,
797    actor: Option<&[u8]>,
798    context: ActionContext,
799) -> Result<ActionEnvelope, ActionError> {
800    apply_steps(doc, action, encoded, (actor, Some(context)), &mut |_| {})
801}
802
803/// Commit what `action` already wrote, the doc's open transaction under
804/// `actor`, as its change recorded with `context`, and return its replayable
805/// envelope: the change [`apply_local_with_context`] would have made, without
806/// applying it again. `described` is what the action said it does, read from
807/// the document before its first write.
808///
809/// The open transaction must hold the action's writes and nothing else,
810/// written as [`Action::apply`] writes them, and the action must record no
811/// compensation: a peer replays the action and checks that it makes exactly
812/// this change ([`verify_change`]).
813///
814/// # Errors
815///
816/// [`ActionError::Refused`] when the doc writes as another actor or holds no
817/// open writes, or the action is too large to record.
818pub fn commit_written(
819    doc: &mut Doc,
820    action: &dyn Action,
821    encoded: EncodedAction,
822    actor: &[u8],
823    context: ActionContext,
824    described: Option<Described>,
825) -> Result<ActionEnvelope, ActionError> {
826    if doc.get_actor().to_bytes() != actor || doc.pending_ops() == 0 {
827        return Err(ActionError::Refused(
828            "the document holds no writes of this actor to commit".into(),
829        ));
830    }
831    let env = envelope_for(
832        doc,
833        action,
834        encoded,
835        Some(actor),
836        Some(context),
837        Before::Written(described.map(Box::new)),
838    )?;
839    commit_pinned(doc, &env, None);
840    Ok(env)
841}
842
843/// Replay an envelope received from a peer: decode its action via
844/// `registry` and apply under the envelope's pinned actor + timestamp.
845/// Applied at the envelope's `base_heads`, this reproduces the identical document.
846///
847/// # Errors
848///
849/// Returns [`ActionError::UnknownType`] or [`ActionError::Decode`] if
850/// `registry` can't decode `env.action`, or any error [`apply_local`]
851/// documents once decoding succeeds.
852pub fn replay(
853    doc: &mut Doc,
854    env: &ActionEnvelope,
855    registry: &ActionRegistry,
856) -> Result<(), ActionError> {
857    let action = registry.decode(&env.action)?;
858    replay_decoded(doc, env, action.as_ref(), registry.content())
859}
860
861/// [`replay`] of `action`, the envelope's action already decoded: what a
862/// device replays an app's verb with when the app's own code is the model
863/// module its package carries rather than a type in this process.
864///
865/// # Errors
866///
867/// See [`replay`].
868pub fn replay_decoded(
869    doc: &mut Doc,
870    env: &ActionEnvelope,
871    action: &dyn Action,
872    content: Option<&tilo_content::ContentStore>,
873) -> Result<(), ActionError> {
874    let _replaying = ReplayScope::enter();
875    let base_heads = env.base_change_hashes();
876    if doc.get_heads() == base_heads {
877        validate_compensation(doc, action, env)?;
878        return apply_under_envelope(doc, action, env, content).map(drop);
879    }
880
881    // The live replica may already contain concurrent work made after the
882    // envelope's authoring point. Applying directly to that newer state makes
883    // an action's reads (guards, list positions, expected values, and so on)
884    // order-dependent and can produce a different change from the origin.
885    // Recreate the action on the exact recorded base, under the envelope's
886    // pinned actor/time, then merge that content-addressed change into live.
887    // `fork_at` fails closed when the dependencies have not arrived yet; the
888    // transport can retry once it has the missing base changes.
889    let mut replay_base = doc.fork_at(&base_heads)?;
890    validate_compensation(&mut replay_base, action, env)?;
891    apply_under_envelope(&mut replay_base, action, env, content).map(drop)?;
892    merge_replayed(doc, &mut replay_base)?;
893    Ok(())
894}
895
896/// Merge `replayed`, made at the envelope's base, into `doc` as it stands, dropping the patch
897/// events the merge logs: an [`automerge::AutoCommit`] logs one per applied operation and never
898/// drops them, and nothing reads them unless the document's owner armed a diff cursor.
899#[expect(
900    clippy::disallowed_methods,
901    reason = "the action layer's one merge, dropping what it logs"
902)]
903fn merge_replayed(
904    doc: &mut Doc,
905    replayed: &mut Doc,
906) -> Result<Vec<automerge::ChangeHash>, automerge::AutomergeError> {
907    let merged = doc.merge(replayed);
908    if doc.diff_cursor().is_empty() {
909        doc.reset_diff_cursor();
910    }
911    merged
912}
913
914/// What replaying a received change showed.
915#[derive(Clone, Debug, PartialEq, Eq)]
916pub enum Verified {
917    /// The action the change records reproduces exactly this change.
918    Reproduced,
919    /// The change records no action to replay (a framework change: a
920    /// record's genesis, a checkpoint, a merge).
921    NothingRecorded,
922    /// The change records an action this replica cannot decode: the app is
923    /// not installed here, so another device has to verify it.
924    UnknownAction(String),
925    /// The recorded action names content (its large parts) that is not in
926    /// this device's content store yet: the change is held until it is.
927    ContentMissing(String),
928}
929
930/// The action as its change records it: itself when the change documents it
931/// whole, else with its large parts kept, sealed, in the content store of
932/// the window that records it ([`crate::content::register`]). Built once, on
933/// the device that invokes the action. An action too large even then is
934/// refused, and so is one whose parts no store would keep: a change never
935/// commits without the action it ran.
936pub fn recorded_form(action: &EncodedAction) -> Result<EncodedAction, ActionError> {
937    if recorded_size(action) <= crate::context::WHOLE_ACTION_BUDGET {
938        return Ok(action.clone());
939    }
940    let recorded = action.with_content_parts(crate::content::CONTENT_PART_THRESHOLD)?;
941    if recorded_size(&recorded) > crate::context::HISTORY_BUDGET {
942        return Err(ActionError::Refused(
943            "the action is too large to record, even with its large parts kept as content".into(),
944        ));
945    }
946    Ok(recorded)
947}
948
949/// What an entry's action takes in the change that keeps it: its type and its
950/// payload, inline.
951fn recorded_size(action: &EncodedAction) -> usize {
952    action.type_id.len().saturating_add(action.payload.len())
953}
954
955/// Replay the action the change `hash` records on the document it was
956/// authored against, and check that it produces exactly that change: same
957/// operations, same actor, time and message, so the same hash. This is what
958/// a device that has the app does with every change it receives, beside the
959/// server's grant check: an author granted an action who wrote something else
960/// inside its storage units is caught here.
961pub fn verify_change(
962    doc: &mut Doc,
963    hash: automerge::ChangeHash,
964    registry: &ActionRegistry,
965) -> Result<Verified, ActionError> {
966    let change = doc
967        .get_change_meta_by_hash(&hash)
968        .ok_or_else(|| ActionError::Refused("the change is not in the document".into()))?
969        .into_owned();
970    let Some(context) = entry_of(doc.committed_document(), hash) else {
971        return Ok(Verified::NothingRecorded);
972    };
973    let Some(recorded) = context.action.as_ref() else {
974        return Ok(Verified::NothingRecorded);
975    };
976    if !registry.contains(&recorded.type_id) {
977        return Ok(Verified::UnknownAction(recorded.type_id.clone()));
978    }
979    let action = match registry.resolve(recorded)? {
980        Ok(action) => action,
981        Err(missing) => return Ok(Verified::ContentMissing(missing.0)),
982    };
983    let env = ActionEnvelope {
984        id: ActionId::new(),
985        action,
986        base_heads: change.deps.iter().map(|head| head.0).collect(),
987        timestamp: change.timestamp,
988        locus: ExecutionLocus::ClientLocal,
989        actor: Some(change.actor.to_bytes().to_vec()),
990        context: Some(context),
991    };
992    let mut original = doc.fork_at(&change.deps)?;
993    replay(&mut original, &env, registry)?;
994    if original.get_heads() != [hash] {
995        return Err(ActionError::Refused(
996            "the change is not what its recorded action produces".into(),
997        ));
998    }
999    Ok(Verified::Reproduced)
1000}
1001
1002/// Decode a recorded inverse only after reproducing its original change.
1003/// Descriptive CRDT metadata alone cannot install executable history.
1004pub fn verified_compensation(
1005    doc: &mut Doc,
1006    hash: automerge::ChangeHash,
1007    registry: &ActionRegistry,
1008) -> Result<Option<Box<dyn Action>>, ActionError> {
1009    doc.get_change_meta_by_hash(&hash)
1010        .ok_or_else(|| ActionError::Refused("history change is unavailable".into()))?;
1011    let inverse = entry_of(doc.committed_document(), hash).and_then(|context| context.compensation);
1012    let Some(inverse) = inverse else {
1013        return Ok(None);
1014    };
1015    match verify_change(doc, hash, registry)? {
1016        Verified::Reproduced => registry.decode(&inverse).map(Some),
1017        Verified::NothingRecorded | Verified::UnknownAction(_) | Verified::ContentMissing(_) => {
1018            Err(ActionError::Refused(
1019                "recorded history action does not reproduce its change".into(),
1020            ))
1021        }
1022    }
1023}
1024
1025fn validate_compensation(
1026    doc: &mut Doc,
1027    action: &dyn Action,
1028    env: &ActionEnvelope,
1029) -> Result<(), ActionError> {
1030    let Some(context) = env.context.as_ref() else {
1031        return Ok(());
1032    };
1033    let Some(recorded) = context.action.as_ref() else {
1034        return Ok(());
1035    };
1036    if recorded.recorded_parts_of(&env.action).is_none()
1037        || inverse_as(doc, action, env.actor()) != context.compensation
1038    {
1039        return Err(ActionError::Refused(
1040            "recorded compensation differs from the action's canonical before state".into(),
1041        ));
1042    }
1043    Ok(())
1044}
1045
1046/// A host's answer to a `ServerPreferred` submission.
1047#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1048pub enum HostDecision {
1049    /// A host accepted the action; it will execute authoritatively and
1050    /// broadcast the change. The caller must NOT apply locally.
1051    AcceptedByHost,
1052    /// No authoritative host is reachable. The caller must not apply locally.
1053    Unavailable,
1054}
1055
1056/// The transport an action is handed to after (or instead of) local
1057/// execution — the boundary between the pure action model and whatever
1058/// moves bytes (in-process broker, compositor socket, Iroh). The
1059/// model never imports a transport, only calls this trait.
1060pub trait ActionTransport {
1061    /// Replicate a locally-applied action to peers so they can [`replay`] it.
1062    fn replicate(&mut self, env: &ActionEnvelope);
1063
1064    /// Submit a `ServerPreferred` action to a host for authoritative
1065    /// execution. Default is unavailable, so a local-only transport fails
1066    /// closed for host-authoritative actions.
1067    fn submit_to_host(&mut self, _env: &ActionEnvelope) -> HostDecision {
1068        HostDecision::Unavailable
1069    }
1070}
1071
1072/// What [`dispatch`] did with an action.
1073#[derive(Clone, Debug, PartialEq, Eq)]
1074pub enum Dispatched {
1075    /// `ClientLocal`: applied to the local replica and replicated.
1076    AppliedLocal(ActionEnvelope),
1077    /// `ServerPreferred` accepted by a host: NOT applied locally — the host
1078    /// executes and broadcasts the change.
1079    SubmittedToHost(ActionEnvelope),
1080}
1081
1082impl Dispatched {
1083    /// The envelope produced, regardless of variant.
1084    pub fn envelope(&self) -> &ActionEnvelope {
1085        match self {
1086            Dispatched::AppliedLocal(e) | Dispatched::SubmittedToHost(e) => e,
1087        }
1088    }
1089
1090    /// Whether the local `doc` was mutated by this dispatch (false only when
1091    /// a host accepted the action).
1092    pub fn mutated_local(&self) -> bool {
1093        !matches!(self, Dispatched::SubmittedToHost(_))
1094    }
1095}
1096
1097/// The locus-aware front API, routing `action` per
1098/// its [`ExecutionLocus`]: `ClientLocal` →
1099/// [`apply_local`] then `transport.replicate`; `ServerPreferred` →
1100/// `transport.submit_to_host`, refusing when no authoritative host is
1101/// reachable. The envelope's id/timestamp are fixed before submission.
1102///
1103/// # Errors
1104///
1105/// See [`apply_local`].
1106pub fn dispatch(
1107    doc: &mut Doc,
1108    action: &dyn Action,
1109    encoded: EncodedAction,
1110    transport: &mut dyn ActionTransport,
1111) -> Result<Dispatched, ActionError> {
1112    dispatch_by(doc, action, encoded, transport, None)
1113}
1114
1115/// [`dispatch`], attributing the resulting change to `actor` — the
1116/// executor owns the commit boundary, so it's the only place that
1117/// chooses which actor a change commits under, rather than each app remembering.
1118///
1119/// # Errors
1120///
1121/// See [`apply_local`].
1122pub fn dispatch_by(
1123    doc: &mut Doc,
1124    action: &dyn Action,
1125    encoded: EncodedAction,
1126    transport: &mut dyn ActionTransport,
1127    actor: Option<&[u8]>,
1128) -> Result<Dispatched, ActionError> {
1129    dispatch_by_maybe_context(doc, action, encoded, transport, actor, None)
1130}
1131
1132/// [`dispatch`], carrying semantic provenance into the replicated envelope
1133/// and the committed CRDT change.
1134///
1135/// # Errors
1136///
1137/// See [`dispatch`].
1138pub fn dispatch_with_context(
1139    doc: &mut Doc,
1140    action: &dyn Action,
1141    encoded: EncodedAction,
1142    transport: &mut dyn ActionTransport,
1143    context: ActionContext,
1144) -> Result<Dispatched, ActionError> {
1145    dispatch_by_maybe_context(doc, action, encoded, transport, None, Some(context))
1146}
1147
1148/// Attributed variant of [`dispatch_with_context`].
1149///
1150/// # Errors
1151///
1152/// See [`dispatch`].
1153pub fn dispatch_by_with_context(
1154    doc: &mut Doc,
1155    action: &dyn Action,
1156    encoded: EncodedAction,
1157    transport: &mut dyn ActionTransport,
1158    actor: Option<&[u8]>,
1159    context: ActionContext,
1160) -> Result<Dispatched, ActionError> {
1161    dispatch_by_maybe_context(doc, action, encoded, transport, actor, Some(context))
1162}
1163
1164fn dispatch_by_maybe_context(
1165    doc: &mut Doc,
1166    action: &dyn Action,
1167    encoded: EncodedAction,
1168    transport: &mut dyn ActionTransport,
1169    actor: Option<&[u8]>,
1170    context: Option<ActionContext>,
1171) -> Result<Dispatched, ActionError> {
1172    // A change names the app its record belongs to, and a caller that names none is a caller
1173    // that would be decided against an app guessed from a type id: never a decision. The typed
1174    // replica a system write goes through names one before it may apply at all
1175    // (`tilo_resource::Replica::in_app`); an app that writes its own record does too.
1176    match action.locus() {
1177        ExecutionLocus::ClientLocal => {
1178            apply_steps(doc, action, encoded, (actor, context), &mut |env| {
1179                transport.replicate(env);
1180            })
1181            .map(Dispatched::AppliedLocal)
1182        }
1183        ExecutionLocus::ServerPreferred => {
1184            let env = envelope_for(doc, action, encoded, actor, context, Before::Doc)?;
1185            match transport.submit_to_host(&env) {
1186                HostDecision::AcceptedByHost => Ok(Dispatched::SubmittedToHost(env)),
1187                HostDecision::Unavailable => Err(ActionError::Refused(
1188                    "this action requires an authoritative host, but none is reachable".into(),
1189                )),
1190            }
1191        }
1192    }
1193}
1194
1195/// A transport that only replicates locally (no host); records every
1196/// replicated envelope for a caller/test to inspect. The default the
1197/// toolkit installs when a session has no peer/host wiring yet.
1198#[derive(Default)]
1199pub struct LocalTransport {
1200    pub replicated: Vec<ActionEnvelope>,
1201}
1202
1203impl LocalTransport {
1204    pub fn new() -> Self {
1205        Self::default()
1206    }
1207}
1208
1209impl ActionTransport for LocalTransport {
1210    fn replicate(&mut self, env: &ActionEnvelope) {
1211        self.replicated.push(env.clone());
1212    }
1213    // submit_to_host uses the trait default: Unavailable.
1214}