Skip to main content

yomi_core/vm/
persistent.rs

1//! Persistent data (the values of `persistent var`s and the passed stop points `seen`). A byte string separate from saves,
2//! shared by all saves.
3
4use serde::{Deserialize, Serialize};
5
6use super::save::{Compat, SavedSlice, SavedValue, type_signatures, unwrap, wrap};
7use super::{LoadError, LoadErrorKind};
8use super::{LoadPolicy, State, Vm};
9use crate::program::Program;
10use crate::registry::Kind;
11
12/// The marker of persistent data bytes (the first 4 bytes).
13const MAGIC: &[u8; 4] = b"YOMP";
14/// The format version. Version 2 added host-declared variables (`Kind::Persistent`) and packages' persistent slices,
15/// version 3 changed the value format to the same as save version 7 and added `struct` and `enum` declarations, and
16/// version 4 matched the value format to save version 8 (which added `map` nodes), and version 5 added the schema
17/// (`schema_version`, `var_types`) (versions 1 to 4 cannot be read).
18const FORMAT_VERSION: u32 = 5;
19
20/// The body of persistent data.
21#[derive(Serialize, Deserialize)]
22pub(super) struct PersistentBody {
23    /// The schema version of the scripts when saved.
24    schema_version: u32,
25    /// The `struct` and `enum` declarations when saved (type names and the shapes of declarations).
26    types: Vec<(String, String)>,
27    /// The types of `vars` then `host_vars` (same names, same order), as type strings.
28    var_types: Vec<(String, String)>,
29    /// `persistent var`s. Names are `module.variable`.
30    vars: Vec<(String, SavedValue)>,
31    /// Host-declared variables (`Kind::Persistent`). Names are `package.variable`.
32    host_vars: Vec<(String, SavedValue)>,
33    /// Packages' persistent slices (in registration order; those whose `Persistent` is `()` are not included).
34    slices: Vec<SavedSlice>,
35    /// Passed stop points (`module.label#id`, in ascending order).
36    seen: Vec<String>,
37}
38
39/// A report from reading persistent data. Compatibility of variables follows the same rules as save variables (only
40/// `persistent var`s apply).
41#[non_exhaustive]
42#[derive(Debug, Clone, PartialEq, Eq, Default)]
43pub struct PersistentReport {
44    /// Variables that were not in the persistent data and got default values (the declared initial values)
45    /// (`module.variable`).
46    pub added_vars: Vec<String>,
47    /// Variables that were removed from the scripts and discarded (`module.variable`).
48    pub removed_vars: Vec<String>,
49    /// Variables whose type changed and got default values (the declared initial values) (`module.variable`).
50    pub type_changed_vars: Vec<String>,
51    /// `struct`s and `enum`s whose declarations changed (`module.TypeName`; including types that contain changed types).
52    pub changed_types: Vec<String>,
53    /// Persistent slices of packages that are not registered, which were ignored (package names).
54    pub ignored_slices: Vec<String>,
55    /// Persistent slices that were not in the persistent data and got default values (package names).
56    pub defaulted_slices: Vec<String>,
57    /// Persistent slices whose versions differed and were migrated with `migrate_persistent` (package names).
58    pub migrated_slices: Vec<String>,
59    /// The schema version of the persistent data.
60    pub from_schema_version: u32,
61    /// The schema version of the scripts.
62    pub to_schema_version: u32,
63    /// Variables converted by `migrate` (`module.variable`; renamed variables have the new name).
64    pub migrated_vars: Vec<String>,
65    /// Variables whose `migrate` conversion failed and were reset to their initial values under `LoadPolicy::Lenient`.
66    pub migrate_failed_vars: Vec<String>,
67}
68
69/// The schema inside persistent data (see `save::embedded_schema`).
70pub(crate) fn embedded_schema(bytes: &[u8]) -> Result<crate::schema_file::Embedded, LoadError> {
71    let body = parse(bytes)?;
72    let mut var_types = body.var_types;
73    var_types.truncate(body.vars.len());
74    Ok(crate::schema_file::Embedded {
75        version: body.schema_version,
76        types: body.types,
77        var_types,
78    })
79}
80
81/// Reads persistent data bytes (checks the magic, version and checksum, and deserializes the body).
82pub(super) fn parse(bytes: &[u8]) -> Result<PersistentBody, LoadError> {
83    let body_bytes = unwrap(bytes, MAGIC, FORMAT_VERSION)?;
84    let body: PersistentBody = match postcard::from_bytes(body_bytes) {
85        Ok(b) => b,
86        Err(_) => {
87            return Err(LoadError {
88                kind: LoadErrorKind::Corrupt,
89            });
90        }
91    };
92    if !super::save::schema_consistent(&body.var_types, &body.vars, &body.host_vars) {
93        return Err(LoadError {
94            kind: LoadErrorKind::Corrupt,
95        });
96    }
97    // Check that the values are not broken (`NaN`, `±∞` and nesting that is too deep are broken)
98    if body
99        .vars
100        .iter()
101        .chain(body.host_vars.iter())
102        .any(|(_, v)| v.decode().is_none())
103    {
104        return Err(LoadError {
105            kind: LoadErrorKind::Corrupt,
106        });
107    }
108    Ok(body)
109}
110
111/// A backup of the VM's state so that `load_persistent` can roll back on failure.
112struct Backup {
113    globals: Vec<crate::value::Value>,
114    host_vars: Vec<crate::value::Value>,
115    persist: Vec<crate::package::SliceBox>,
116    seen: std::collections::BTreeSet<String>,
117    rng: super::rng::Rng,
118    pc: usize,
119    stack: Vec<crate::value::Value>,
120    current: Option<super::Yield>,
121    cur_src: Option<super::StopSrc>,
122    cap: Vec<Vec<String>>,
123    choice: super::ChoiceBuild,
124}
125
126impl<'a> Vm<'a> {
127    /// Makes the bytes of persistent data (values of `persistent var`s, host-declared `Kind::Persistent` variables, packages'
128    /// persistent slices, passed stop points).
129    ///
130    /// Can be called even when not stopped. Managing where it is stored (atomic writes and so on) is the host's job.
131    /// Persistent slices that cannot be serialized (a bug in the implementation of `Persistent`) are skipped.
132    pub fn save_persistent(&self) -> Vec<u8> {
133        let program = &self.program;
134        let var_types = program
135            .globals
136            .iter()
137            .filter(|g| g.persistent)
138            .map(|g| {
139                (
140                    format!("{}.{}", program.modules[g.module as usize], g.name),
141                    g.ty.name(),
142                )
143            })
144            .chain(
145                self.registry
146                    .vars()
147                    .iter()
148                    .filter(|d| d.kind == Kind::Persistent)
149                    .map(|d| (d.name.clone(), d.ty.name())),
150            )
151            .collect();
152        let body = PersistentBody {
153            schema_version: program.schema_version(),
154            types: type_signatures(program),
155            var_types,
156            vars: program
157                .globals
158                .iter()
159                .zip(&self.globals)
160                .filter(|(g, _)| g.persistent)
161                .map(|(g, v)| {
162                    (
163                        format!("{}.{}", program.modules[g.module as usize], g.name),
164                        SavedValue::from_value(v),
165                    )
166                })
167                .collect(),
168            host_vars: self
169                .registry
170                .vars()
171                .iter()
172                .zip(&self.host_vars)
173                .filter(|(d, _)| d.kind == Kind::Persistent)
174                .map(|(d, v)| (d.name.clone(), SavedValue::from_value(v)))
175                .collect(),
176            slices: self.save_slices(true).unwrap_or_default(),
177            seen: self.seen.iter().cloned().collect(),
178        };
179        let body = postcard::to_stdvec(&body).expect("メモリへの直列化は失敗しない");
180        wrap(MAGIC, FORMAT_VERSION, &body)
181    }
182
183    /// Reads persistent data. The values of `persistent var`s, host-declared variables, packages' persistent slices and passed
184    /// stop points are **replaced** (`persistent var`s that were not in the persistent data get their declared initial values;
185    /// missing persistent slices get default values). The save (`save var`s, position, history, random generator, state
186    /// slices) does not change.
187    ///
188    /// If stopped, the arguments of the stop point are rebuilt with the new `persistent var`s and `seen` (for scripts whose
189    /// `${expr}` or `if` read them). So loading a save and then persistent data gives the same state as putting the
190    /// persistent data first (`VmConfig::persistent_data`) and then loading the save. If they cannot be rebuilt (a runtime
191    /// error), returns a `LoadError` (`StopArgsFailed`) and the VM is unchanged.
192    ///
193    /// For broken bytes or an unknown version, `LoadError`, and the VM is unchanged.
194    pub fn load_persistent(&mut self, bytes: &[u8]) -> Result<PersistentReport, LoadError> {
195        let body = parse(bytes)?;
196        let State::Stopped { ordinal } = self.state else {
197            return self.apply_persistent(body);
198        };
199        let backup = Backup {
200            globals: self.globals.clone(),
201            host_vars: self.host_vars.clone(),
202            persist: self.persist.clone(),
203            seen: self.seen.clone(),
204            rng: self.rng.clone(),
205            pc: self.pc,
206            stack: self.stack.clone(),
207            current: self.current.clone(),
208            cur_src: self.cur_src.clone(),
209            cap: self.cap.clone(),
210            choice: self.choice.clone(),
211        };
212        let report = self.apply_persistent(body)?;
213        match self.rebuild_yield(ordinal)? {
214            Some(y) => {
215                self.install_current(y, ordinal);
216                self.sync_current_record();
217                Ok(report)
218            }
219            None => {
220                self.globals = backup.globals;
221                self.host_vars = backup.host_vars;
222                self.persist = backup.persist;
223                self.seen = backup.seen;
224                self.rng = backup.rng;
225                self.pc = backup.pc;
226                self.stack = backup.stack;
227                self.current = backup.current;
228                self.cur_src = backup.cur_src;
229                self.cap = backup.cap;
230                self.choice = backup.choice;
231                Err(LoadError {
232                    kind: LoadErrorKind::StopArgsFailed,
233                })
234            }
235        }
236    }
237
238    /// Puts the body of persistent data into the VM. `Err` if the persistent slices cannot be restored (the VM is unchanged).
239    pub(super) fn apply_persistent(
240        &mut self,
241        mut body: PersistentBody,
242    ) -> Result<PersistentReport, LoadError> {
243        let program_ref = self.program.clone();
244        let program: &Program = &program_ref;
245        let registry = self.registry;
246        self.total_valid = false;
247        // Do the parts that can fail (version and schema checks, restoring slices) first
248        super::save::check_schema_version(program, body.schema_version)?;
249        let migration = super::save::apply_migrations(
250            program,
251            registry,
252            &self.cfg,
253            body.schema_version,
254            true,
255            &body.types,
256            &mut body.vars,
257            &mut body.var_types,
258        )?;
259        let var_decls: &[(String, String)] =
260            if super::save::migrated_types(program, body.schema_version) {
261                &[]
262            } else {
263                &body.types
264            };
265        let diffs =
266            super::save::script_var_diffs(program, var_decls, &body.var_types, &body.vars, true)?;
267        if self.cfg.load_policy == LoadPolicy::Strict && !diffs.is_empty() {
268            return Err(LoadError {
269                kind: LoadErrorKind::SchemaMismatch(diffs),
270            });
271        }
272        let mismatched: std::collections::BTreeSet<String> =
273            diffs.into_iter().map(|d| d.name).collect();
274        let resolved = self.resolve_slices(&body.slices, true)?;
275        let compat = Compat::new(program, &body.types);
276        let mut report = PersistentReport {
277            from_schema_version: body.schema_version,
278            to_schema_version: program.schema_version(),
279            changed_types: compat.changed.iter().cloned().collect(),
280            migrated_vars: migration.migrated.clone(),
281            migrate_failed_vars: migration.failed.clone(),
282            ignored_slices: resolved.report.ignored,
283            defaulted_slices: resolved.report.defaulted,
284            migrated_slices: resolved.report.migrated,
285            ..PersistentReport::default()
286        };
287        self.install_slices(resolved.slices, true);
288        for (i, g) in program
289            .globals
290            .iter()
291            .enumerate()
292            .filter(|(_, g)| g.persistent)
293        {
294            let name = format!("{}.{}", program.modules[g.module as usize], g.name);
295            match body.vars.iter().find(|(n, _)| *n == name) {
296                Some((_, v)) if !mismatched.contains(&name) => {
297                    self.globals[i] = v.clone().into_value();
298                }
299                Some(_) => {
300                    self.globals[i] = g.init.clone();
301                    report.type_changed_vars.push(name);
302                }
303                None => {
304                    self.globals[i] = g.init.clone();
305                    if !migration.failed.contains(&name) {
306                        report.added_vars.push(name);
307                    }
308                }
309            }
310        }
311        // Host-declared variables (`Kind::Persistent`)
312        for (i, d) in registry
313            .vars()
314            .iter()
315            .enumerate()
316            .filter(|(_, d)| d.kind == Kind::Persistent)
317        {
318            match body.host_vars.iter().find(|(n, _)| *n == d.name) {
319                Some((_, v)) if compat.ok(&v.clone().into_value(), &d.ty) => {
320                    self.host_vars[i] = v.clone().into_value();
321                }
322                Some(_) => {
323                    self.host_vars[i] = d.init.clone();
324                    report.type_changed_vars.push(d.name.clone());
325                }
326                None => {
327                    self.host_vars[i] = d.init.clone();
328                    report.added_vars.push(d.name.clone());
329                }
330            }
331        }
332        report.removed_vars = body
333            .vars
334            .iter()
335            .filter(|(n, _)| {
336                !program.globals.iter().any(|g| {
337                    g.persistent
338                        && format!("{}.{}", program.modules[g.module as usize], g.name) == *n
339                })
340            })
341            .map(|(n, _)| n.clone())
342            .collect();
343        report.removed_vars.extend(
344            body.host_vars
345                .iter()
346                .filter(|(n, _)| {
347                    !registry
348                        .vars()
349                        .iter()
350                        .any(|d| d.kind == Kind::Persistent && d.name == *n)
351                })
352                .map(|(n, _)| n.clone()),
353        );
354        self.seen = body.seen.into_iter().collect();
355        Ok(report)
356    }
357}