Skip to main content

vlo_kernel/
reduce.rs

1//! `reduce_step`: turn a reducer's `(state, commands)` into the transition write-set.
2//!
3//! The kernel does not trust the reducer. Every command is validated, every step id is
4//! checked for collision, and the run's own status is derived from the resulting step
5//! map rather than from anything the reducer claimed.
6
7use vlo_types::{
8    Command, EventInput, KernelState, Kind, ReduceStepInput, RunStatus, TaskUpdate, Transition,
9    INLINE_LIMIT_BYTES,
10};
11
12use crate::classify::{classify, Class};
13use crate::commands::Builder;
14use crate::error::{code, err, err_step, KResult};
15use crate::validate::validate_event;
16use crate::{canonical, hash, ids, steps};
17
18/// Build the write-set for one reducer call (see `docs/workflows.md`).
19///
20/// Validates the event, retires the trigger's step and banks its usage, applies each
21/// command in order, then derives the run status from the open steps. Errors:
22/// `invalid_event`, `run_closed`, `malformed_json` (reducer state), `unknown_step`, and
23/// the command codes (`invalid_command`, `duplicate_step_id`, `multiple_completions`,
24/// `commands_after_completion`).
25pub fn reduce_step(input: &ReduceStepInput) -> KResult<Transition> {
26    let event = validate_event(&input.event)?;
27    let run = &input.run;
28    if event.run_id != run.run_id {
29        return Err(err(
30            code::INVALID_EVENT,
31            format!("event run_id {} is not run {}", event.run_id, run.run_id),
32        ));
33    }
34    if run.status.is_terminal() {
35        return Err(err(
36            code::RUN_CLOSED,
37            format!("run is {:?}; no further events are accepted", run.status),
38        ));
39    }
40    // The reducer's state must be JSON: it is hashed and replayed.
41    canonical::parse(&input.reduction.state)?;
42
43    let class = classify(&event)?;
44    if !class.is_reduce() {
45        return Err(err_step(
46            code::INVALID_EVENT,
47            "this event is lifecycle-only; apply the transition from prepare_event",
48            &event.step_id,
49        ));
50    }
51
52    let mut kernel_state = input.kernel_state.clone();
53    apply_trigger(&mut kernel_state, class, &event)?;
54
55    let mut builder = Builder::new(run, kernel_state, event.ts_ms, &event.random);
56    builder.push_event(event.clone());
57    // A task result also settles its row: the journal closes it (status, lease) in the same
58    // write-set, so `expiredLeases` and the outbox never see a finished task again.
59    if class == Class::TaskResult {
60        builder.task_updates.push(TaskUpdate {
61            task_id: ids::task_id(&run.run_id, &event.step_id),
62            attempt: event.attempt,
63            status: event.status,
64            not_before_ms: None,
65        });
66    }
67
68    for command in &input.reduction.commands {
69        if builder.completion.is_some() {
70            return Err(completion_conflict(command));
71        }
72        builder.apply(command)?;
73    }
74
75    let run_status = finalize(&mut builder);
76    let state = input.reduction.state.clone();
77    let state_hash = hash::state_hash(&builder.kernel_state, &state)?;
78    let state_inline = state.len() <= INLINE_LIMIT_BYTES;
79    Ok(builder.finish(state, state_hash, state_inline, run_status))
80}
81
82/// Retire the step the trigger event belongs to and bank its usage. A signal or its
83/// `<id>:timeout` deadline also retires the other side of the race; `prepare_event`
84/// already did so in the kernel state it handed back, so this is a no-op on the happy
85/// path and a guarantee when the host folds from its own checkpoint.
86fn apply_trigger(kernel_state: &mut KernelState, class: Class, event: &EventInput) -> KResult<()> {
87    if class == Class::Started {
88        kernel_state.status = RunStatus::Running;
89    } else if steps::close_step(kernel_state, &event.step_id).is_none() {
90        return Err(err_step(
91            code::UNKNOWN_STEP,
92            "no open step with this id",
93            &event.step_id,
94        ));
95    }
96    match class {
97        Class::SignalDelivered => {
98            steps::cancel_race_loser(kernel_state, Kind::Signal, &event.step_id)
99        }
100        Class::TimerFired => steps::cancel_race_loser(kernel_state, Kind::Timer, &event.step_id),
101        _ => {}
102    }
103    if let Some(usage) = &event.usage {
104        kernel_state.usage_total.add(usage);
105    }
106    Ok(())
107}
108
109/// Settle the run status, closing anything still open once the reducer has completed.
110fn finalize(builder: &mut Builder<'_>) -> RunStatus {
111    if let Some(completion) = &builder.completion {
112        let status = completion.status;
113        let run_id = builder.run.run_id.clone();
114        let mut cancelled = steps::close_open_steps(&mut builder.kernel_state, &run_id);
115        builder.task_updates.append(&mut cancelled);
116        builder.kernel_state.status = status;
117        return status;
118    }
119    let status = if steps::has_open_signal(&builder.kernel_state)
120        && !steps::has_open_work(&builder.kernel_state)
121    {
122        RunStatus::AwaitingSignal
123    } else {
124        RunStatus::Running
125    };
126    builder.kernel_state.status = status;
127    status
128}
129
130fn completion_conflict(command: &Command) -> vlo_types::KernelError {
131    match command {
132        Command::Complete { .. } | Command::ContinueAsNew { .. } => err(
133            code::MULTIPLE_COMPLETIONS,
134            "a reduction may complete or continue a run at most once",
135        ),
136        _ => err(
137            code::COMMANDS_AFTER_COMPLETION,
138            "no command may follow complete / continue_as_new",
139        ),
140    }
141}