Skip to main content

scientific_workflow/task/
model.rs

1//! Application-owned scientific model contract.
2
3use serde::de::DeserializeOwned;
4
5use crate::observation::advanced::ObservationPlan;
6use crate::state::advanced::{SystemState, SystemStateSchema};
7
8use super::result::TaskResult;
9
10/// A stateful scientific workload initialized from config-supplied constants.
11///
12/// # Direct state ownership
13///
14/// The implementing model **must directly own** the [`SystemState`] returned
15/// by [`ScientificModel::state`] for its entire execution. Rust traits cannot
16/// express field-level structural ownership, so this requirement is semantic;
17/// the task runtime enforces the observable parts by requiring a stable state
18/// address and the exact schema allocation supplied to [`Self::initialize`].
19/// Returning a temporary, swapping the state owner, or changing schemas is a
20/// contract violation.
21///
22/// The `#[scientific_workflow::model("key")]` attribute only registers the
23/// implementation under a manifest key. It does not generate, wrap, proxy, or
24/// provide access to model state. The model defines an ordinary `SystemState`
25/// field, initializes its concrete payloads, and returns a direct borrow of
26/// that field from [`Self::state`]. Coupled fields remain ordinary typed tuple
27/// borrows through [`SystemState::borrow_payloads`] and
28/// [`SystemState::borrow_payloads_mut`]; no field-access macro is involved.
29///
30/// A successful [`Self::step`] represents exactly one scientifically
31/// observable transition and must strictly advance the state's iteration.
32/// Workflow observes the initial state, every successful step, and the final
33/// state automatically. Implementations do not report progress or invoke the
34/// observation plan themselves.
35pub trait ScientificModel: Send + Sized + 'static {
36    /// One complete set of model constants supplied by config.
37    ///
38    /// Constants need not implement [`Send`] or [`Sync`]: Study and Runtime
39    /// independently decode and consume their equivalent owned instances on
40    /// the thread performing that operation. The model itself remains `Send`,
41    /// and [`TaskResult`] errors remain `Send + Sync` for worker handoff.
42    type Constants: DeserializeOwned + 'static;
43
44    /// Defines the scientific observations recorded for this model.
45    ///
46    /// The default records every declared state field at every iteration.
47    /// Implementations may derive stream selection and sampling cadence from
48    /// model constants. This function is called once with Study's preflight
49    /// constants instance; Study binds and retains the resulting plan for
50    /// execution, then drops that instance. It must not perform external side
51    /// effects.
52    fn observation_plan(_constants: &Self::Constants) -> TaskResult<ObservationPlan> {
53        Ok(ObservationPlan::all_fields())
54    }
55
56    /// Builds a fully initialized model from a fresh decode of the same
57    /// resolved constants value and the selected, centrally loaded state
58    /// schema.
59    ///
60    /// The returned model must already contain a usable, fully populated state
61    /// created from this exact `schema` allocation. No state observation occurs
62    /// until this method succeeds.
63    fn initialize(constants: Self::Constants, schema: &SystemStateSchema) -> TaskResult<Self>;
64
65    /// Borrows the model's directly owned canonical state.
66    ///
67    /// This method must be side-effect free and must return the same state
68    /// owner and schema allocation throughout execution.
69    fn state(&self) -> &SystemState;
70
71    /// Reports whether no further scientific transition is required.
72    ///
73    /// This method must be side-effect free. Once it returns `true` during one
74    /// execution, Workflow performs the final observation without calling
75    /// [`Self::step`] again.
76    fn is_complete(&self) -> bool;
77
78    /// Performs exactly one scientifically observable transition.
79    ///
80    /// Success must strictly increase [`SystemState::time`]'s iteration while
81    /// preserving the state owner and schema. Failure must not claim a
82    /// completed transition: Workflow emits neither a successful-step snapshot
83    /// nor a successful-step observation for an error result.
84    fn step(&mut self) -> TaskResult;
85
86    /// Optionally reports the expected final iteration for inferred progress.
87    ///
88    /// The default is unknown. A reported target must be at least the current
89    /// iteration. Once present during an execution, it must never decrease or
90    /// disappear. This method must be side-effect free.
91    fn target_iteration(&self) -> Option<u64> {
92        None
93    }
94}