Skip to main content

cfd_craft/
output.rs

1//! Checkpoints and run archives: publication, integrity and restart.
2//!
3//! A run archive is a new directory with `case.json`, `summary.json`,
4//! `geometry.json` and `probes.csv`, optionally `fields.json` and
5//! `checkpoint.json`, then `manifest.json` (artifact hashes, omissions and
6//! identities) and finally `complete.json`, the manifest hash written last.
7//! Every file is written to a temporary name, synced and renamed. Integrity
8//! ([`read_verified`]) and the numerical verdict in the summary are separate
9//! questions: a complete archive can hold an incomplete run.
10//!
11//! A checkpoint wraps a [`State`] with the case's physics hash and a payload
12//! checksum. [`read_checkpoint`] accepts it only for a case with the same
13//! physics hash. See the
14//! [result contract](https://github.com/dietmarwo/CFD-craft/blob/main/docs/result-contract.md)
15//! for the file contract.
16//!
17//! ```
18//! # let json = r#"{"schema_version": "cfd-craft.case/0.1", "name": "tiny",
19//! #   "domain": {"size_m": [4.0, 1.0, 1.0]}, "grid": {"cells": [8, 2, 2]},
20//! #   "boundaries": {"x": "open", "y": "periodic", "z": "periodic"},
21//! #   "flow": {"kind": "prescribed_uniform", "velocity_m_s": [1.0, 0.0, 0.0]},
22//! #   "constituents": [{"id": "tracer", "diffusivity_m2_s": 0.01}],
23//! #   "sources": [{"kind": "point", "id": "S0", "constituent": "tracer",
24//! #                "point_m": [0.5, 0.5, 0.5], "rate_kg_s": 1e-6}],
25//! #   "numerics": {"transport": "linear_upwind", "max_time_step_s": 1.0,
26//! #     "advective_cfl_max": 0.4, "pressure_relative_tolerance": 1e-10,
27//! #     "pressure_max_iterations": 100, "steady_residual_tolerance": 1e-5,
28//! #     "steady_monitor_tolerance": 1e-3, "monitor_window": 10},
29//! #   "run": {"mode": "steady", "end_time_s": 1.0, "max_steps": 5,
30//! #     "wall_time_limit_s": 30.0, "threads": 1, "memory_limit_mib": 64},
31//! #   "output": {"fields": false, "checkpoint": false, "max_total_mib": 4}}"#;
32//! use cfd_craft::{case::Case, output, solver::{self, Control}};
33//!
34//! let case: Case = serde_json::from_str(json).unwrap();
35//! let partial = solver::run(&case, &Control::new(30.0), None)?;
36//!
37//! let path = std::env::temp_dir().join(format!("cfd-craft-doc-{}.json", std::process::id()));
38//! std::fs::write(&path, output::checkpoint_bytes(&case, &partial.state)?).unwrap();
39//! // The same physics with a larger step budget accepts the checkpoint ...
40//! let mut longer = case.clone();
41//! longer.run.max_steps = 50;
42//! let state = output::read_checkpoint(&longer, &path)?;
43//! assert_eq!(state.steps, 5);
44//! // ... changed physics does not.
45//! let mut other = longer.clone();
46//! other.constituents[0].diffusivity_m2_s = 0.02;
47//! assert!(output::read_checkpoint(&other, &path).unwrap_err().starts_with("CFD-E060"));
48//! std::fs::remove_file(&path).unwrap();
49//! # Ok::<(), String>(())
50//! ```
51use crate::{
52    Result,
53    case::{Case, hash_bytes},
54    grid::Grid,
55    solver::{RunResult, State, Summary, validate_state},
56};
57use serde::{Deserialize, Serialize};
58use std::{
59    collections::BTreeMap,
60    fs::{self, File, OpenOptions},
61    io::Write,
62    path::Path,
63};
64#[derive(Serialize, Deserialize)]
65#[serde(deny_unknown_fields)]
66struct Checkpoint {
67    schema_version: String,
68    physics_sha256: String,
69    payload_sha256: String,
70    payload: String,
71}
72/// Writes `bytes` to `path` through a new `<path>.partial` file that is
73/// synced and then renamed over `path`. Fails if the temporary file already
74/// exists.
75pub fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
76    let tmp = path.with_extension("partial");
77    let mut f = OpenOptions::new()
78        .create_new(true)
79        .write(true)
80        .open(&tmp)
81        .map_err(|e| e.to_string())?;
82    f.write_all(bytes)
83        .and_then(|()| f.sync_all())
84        .map_err(|e| e.to_string())?;
85    fs::rename(tmp, path).map_err(|e| e.to_string())
86}
87/// The JSON bytes of a checkpoint (`cfd-craft.checkpoint/0.1`) of state `s`
88/// for case `c`: the serialized state as a payload, its SHA-256 and the
89/// case's physics hash.
90pub fn checkpoint_bytes(c: &Case, s: &State) -> Result<Vec<u8>> {
91    let payload = serde_json::to_string(s).map_err(|e| e.to_string())?;
92    serde_json::to_vec(&Checkpoint {
93        schema_version: "cfd-craft.checkpoint/0.1".into(),
94        physics_sha256: c.physics_hash(),
95        payload_sha256: hash_bytes(payload.as_bytes()),
96        payload,
97    })
98    .map_err(|e| e.to_string())
99}
100/// Reads and verifies a checkpoint for case `c` and returns its state, ready
101/// for [`solver::run`](crate::solver::run).
102///
103/// # Errors
104///
105/// `CFD-E065` when the file cannot be read or parsed or is larger than half
106/// of `run.memory_limit_mib`; `CFD-E060` for another schema version, another
107/// physics hash or a payload checksum mismatch; the state checks of
108/// [`validate_state`] (`CFD-E050`, `CFD-E051`); and `CFD-E066` when the state
109/// lies beyond `run.max_steps` or, in transient mode, `run.end_time_s`.
110pub fn read_checkpoint(c: &Case, path: &Path) -> Result<State> {
111    let unreadable = |e: String| format!("CFD-E065: checkpoint {}: {e}", path.display());
112    let bytes = fs::read(path).map_err(|e| unreadable(e.to_string()))?;
113    if bytes.len() > c.run.memory_limit_mib.saturating_mul(1048576) / 2 {
114        return Err(unreadable(
115            "larger than half of run.memory_limit_mib, the import budget".into(),
116        ));
117    }
118    let v: Checkpoint = serde_json::from_slice(&bytes).map_err(|e| unreadable(e.to_string()))?;
119    if v.schema_version != "cfd-craft.checkpoint/0.1"
120        || v.physics_sha256 != c.physics_hash()
121        || hash_bytes(v.payload.as_bytes()) != v.payload_sha256
122    {
123        return Err("CFD-E060: checkpoint identity or checksum mismatch".into());
124    }
125    let s: State = serde_json::from_str(&v.payload).map_err(|e| unreadable(e.to_string()))?;
126    let g = Grid::build(c)?;
127    validate_state(c, &g, &s)?;
128    if s.steps > c.run.max_steps
129        || (c.run.mode == crate::case::Mode::Transient
130            && s.time_s > c.run.end_time_s * (1.0 + 1e-12))
131    {
132        return Err(
133            "CFD-E066: the checkpoint lies beyond run.max_steps or run.end_time_s of the case"
134                .into(),
135        );
136    }
137    Ok(s)
138}
139/// Creates the run directory. A missing parent or an existing destination (including a
140/// dangling symlink) is an error, so the solve never starts without a place for its results.
141pub fn create_run_dir(out: &Path) -> Result<()> {
142    if fs::symlink_metadata(out).is_ok() {
143        return Err(format!("CFD-E062: output {} already exists", out.display()));
144    }
145    fs::create_dir(out).map_err(|e| match e.kind() {
146        std::io::ErrorKind::NotFound => format!(
147            "CFD-E063: the parent directory of output {} does not exist",
148            out.display()
149        ),
150        _ => format!("CFD-E063: cannot create output {}: {e}", out.display()),
151    })
152}
153
154/// Writes the artifacts into the run directory made by [`create_run_dir`]. The small
155/// artifacts are always written; fields and checkpoint are omitted, and listed in the
156/// manifest, when they would exceed the output budget. Returns the omitted names.
157///
158/// `input_sha256` is the hash of the raw input file. The manifest also
159/// records the SHA-256 of the running executable and the summary's
160/// `source_sha256` and `build_version`; an application other than the CLI
161/// should first replace those two summary fields with its own build identity.
162pub fn write_run(c: &Case, r: &RunResult, out: &Path, input_sha256: &str) -> Result<Vec<String>> {
163    let budget = c.output.max_total_mib.saturating_mul(1048576);
164    let mut files = BTreeMap::new();
165    let mut omitted = BTreeMap::new();
166    let mut total = 0usize;
167    let mut put = |name: &str, bytes: Vec<u8>, optional: bool| -> Result<()> {
168        let next = total
169            .checked_add(bytes.len())
170            .ok_or("output length overflow")?;
171        if optional && next > budget {
172            omitted.insert(
173                name.to_string(),
174                format!(
175                    "CFD-E061: {} bytes would exceed the output budget of {} MiB",
176                    bytes.len(),
177                    c.output.max_total_mib
178                ),
179            );
180            return Ok(());
181        }
182        total = next;
183        atomic_write(&out.join(name), &bytes)?;
184        files.insert(name.to_string(), hash_bytes(&bytes));
185        Ok(())
186    };
187    put("case.json", serde_json::to_vec_pretty(c).unwrap(), false)?;
188    put(
189        "summary.json",
190        serde_json::to_vec_pretty(&r.summary).unwrap(),
191        false,
192    )?;
193    put(
194        "geometry.json",
195        serde_json::to_vec_pretty(&r.geometry).unwrap(),
196        false,
197    )?;
198    let mut probes = String::from("constituent,receptor,concentration_kg_m3\n");
199    for s in &r.summary.constituents {
200        for (name, value) in &s.receptors_kg_m3 {
201            // JSON-quoted strings are valid CSV quoted fields except escaped quotes; identifiers exclude controls in check.
202            probes.push_str(&format!("{},{},{:.17e}\n", csv(&s.id), csv(name), value));
203        }
204    }
205    put("probes.csv", probes.into_bytes(), false)?;
206    if c.output.fields {
207        put("fields.json", serde_json::to_vec(&r.state).unwrap(), true)?;
208    }
209    if c.output.checkpoint {
210        put("checkpoint.json", checkpoint_bytes(c, &r.state)?, true)?;
211    }
212    let executable = std::env::current_exe().map_err(|e| e.to_string())?;
213    let executable_sha256 = hash_bytes(&fs::read(executable).map_err(|e| e.to_string())?);
214    let omitted_names: Vec<String> = omitted.keys().cloned().collect();
215    let manifest = serde_json::to_vec_pretty(&serde_json::json!({
216        "schema_version":MANIFEST_SCHEMA,"files":files,"omitted":omitted,
217        "input_case_sha256":input_sha256,
218        "source_sha256":r.summary.source_sha256,"version":r.summary.build_version,
219        "initial_state_sha256":r.summary.initial_state_sha256,
220        "executable_sha256":executable_sha256,
221        "bytes_before_manifest":total,"threads":c.run.threads,
222        "architecture":std::env::consts::ARCH,"os":std::env::consts::OS
223    }))
224    .unwrap();
225    atomic_write(&out.join("manifest.json"), &manifest)?;
226    atomic_write(
227        &out.join("complete.json"),
228        &serde_json::to_vec(&serde_json::json!({"manifest_sha256":hash_bytes(&manifest)})).unwrap(),
229    )?;
230    File::open(out)
231        .and_then(|f| f.sync_all())
232        .map_err(|e| e.to_string())?;
233    Ok(omitted_names)
234}
235const MANIFEST_SCHEMA: &str = "cfd-craft.manifest/0.1";
236const ARTIFACTS: [&str; 6] = [
237    "summary.json",
238    "case.json",
239    "geometry.json",
240    "probes.csv",
241    "fields.json",
242    "checkpoint.json",
243];
244fn csv(s: &str) -> String {
245    format!("\"{}\"", s.replace('"', "\"\""))
246}
247fn read_regular(path: &Path) -> Result<Vec<u8>> {
248    let meta = fs::symlink_metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
249    if !meta.file_type().is_file() {
250        return Err(format!("{}: not a regular file", path.display()));
251    }
252    fs::read(path).map_err(|e| format!("{}: {e}", path.display()))
253}
254/// A verified archive: its summary and the artifacts the manifest lists as omitted.
255pub struct Verified {
256    /// The archived summary. Its `termination` and `assessment` still have
257    /// to be inspected: integrity says nothing about convergence.
258    pub summary: Summary,
259    /// Names of the artifacts omitted over the output budget (CFD-E061).
260    pub omitted: Vec<String>,
261}
262
263/// Verifies a run directory: completion marker, manifest, every listed artifact, no
264/// unlisted entries, the artifacts the case requested, and the identities that the
265/// summary, case and manifest share.
266///
267/// Errors are not coded here; the CLI reports them as CFD-E064. The hashes are
268/// unkeyed: they establish consistency, not authorship.
269pub fn read_verified(out: &Path) -> Result<Verified> {
270    let marker: serde_json::Value =
271        serde_json::from_slice(&read_regular(&out.join("complete.json"))?)
272            .map_err(|e| format!("complete.json: {e}"))?;
273    let m = read_regular(&out.join("manifest.json"))?;
274    if marker["manifest_sha256"].as_str() != Some(&hash_bytes(&m)) {
275        return Err("manifest checksum mismatch".into());
276    }
277    let manifest: serde_json::Value =
278        serde_json::from_slice(&m).map_err(|e| format!("manifest.json: {e}"))?;
279    if manifest["schema_version"] != MANIFEST_SCHEMA {
280        return Err("manifest.json: unsupported schema_version".into());
281    }
282    let files = manifest["files"]
283        .as_object()
284        .ok_or("invalid manifest files")?;
285    let omitted = manifest
286        .get("omitted")
287        .and_then(|v| v.as_object())
288        .cloned()
289        .unwrap_or_default();
290    for name in ["summary.json", "case.json", "geometry.json", "probes.csv"] {
291        if !files.contains_key(name) {
292            return Err(format!("manifest lacks required artifact {name}"));
293        }
294    }
295    for (name, sha) in files {
296        if !ARTIFACTS.contains(&name.as_str()) {
297            return Err(format!("unknown artifact name {name}"));
298        }
299        if sha.as_str() != Some(&hash_bytes(&read_regular(&out.join(name))?)) {
300            return Err(format!("{name}: checksum mismatch"));
301        }
302    }
303    for entry in fs::read_dir(out).map_err(|e| e.to_string())? {
304        let name = entry.map_err(|e| e.to_string())?.file_name();
305        let name = name.to_string_lossy();
306        if name != "manifest.json" && name != "complete.json" && !files.contains_key(&*name) {
307            return Err(format!("unlisted entry {name} in the run directory"));
308        }
309    }
310    let case: Case = serde_json::from_slice(&read_regular(&out.join("case.json"))?)
311        .map_err(|e| format!("case.json: {e}"))?;
312    for (wanted, name) in [
313        (case.output.fields, "fields.json"),
314        (case.output.checkpoint, "checkpoint.json"),
315    ] {
316        if wanted && !files.contains_key(name) && !omitted.contains_key(name) {
317            return Err(format!("{name} was requested by the case but is missing"));
318        }
319    }
320    let summary: Summary = serde_json::from_slice(&read_regular(&out.join("summary.json"))?)
321        .map_err(|e| format!("summary.json: {e}"))?;
322    if summary.case_sha256 != hash_bytes(&serde_json::to_vec(&case).unwrap())
323        || summary.physics_sha256 != case.physics_hash()
324    {
325        return Err("summary.json does not describe case.json".into());
326    }
327    if manifest["initial_state_sha256"] != summary.initial_state_sha256.as_str()
328        || manifest["source_sha256"] != summary.source_sha256.as_str()
329    {
330        return Err("manifest.json and summary.json disagree on identity".into());
331    }
332    Ok(Verified {
333        summary,
334        omitted: omitted.keys().cloned().collect(),
335    })
336}