Skip to main content

datumesh_http/
publish.rs

1//! Publishing stored cells as the mesh (`datumesh-mesh publish-stored`): a JSON lines file of
2//! stored functions and their cells, signed with the mesh's key, put in the store.
3//!
4//! Each line is one of:
5//!
6//! * a descriptor (since 0.3.1, CONTRACT-1.7a H1): `{"descriptor": <function descriptor>}`: the
7//!   descriptor is put with `put_descriptor` and binds nothing. Only a stored function is
8//!   accepted (`code.lang` = `stored`, `code.body` = `""`, `inputs` = `[]`); any other is refused
9//!   at its line. A class later in the file (or in a later run) may name its hash as a method;
10//! * a function: `{"function": "<ns>/<name>", "signature": {...}, "bound": "<instant>"}`: the
11//!   descriptor `{"code": {"body": "", "lang": "stored"}, "inputs": [], "signature": ...}`
12//!   is put and the name bound to it from `bound` (unless it already is);
13//! * a formula function: `{"formula": "<ns>/<name>", "source": "<formula>", "signature":
14//!   {...}, "bound": "<instant>"}`: defined with `datumesh_formula::definition::define_function`
15//!   (its callees as bound at `bound`) and published (`put_descriptor`, `bind_name` from
16//!   `bound`) unless the name is already bound to that function; its cells are evaluated on
17//!   demand by the mesh;
18//! * a class (since 0.2.2, spec-0.5.0, 16.2): `{"class": "<ns>/<name>", "descriptor": {...as
19//!   written...}, "bound": "<instant>"}`: defined with the formula crate's `define_class` (core's
20//!   rules: the class is under one of the mesh's own namespaces, else `E_CLASS_OWNER`; the method
21//!   functions are those bound as of `bound`), `put_class`, and `bind_class` from `bound` unless the
22//!   name is already bound to that class hash. Method functions come first in the file (or in an
23//!   earlier one), `bound` later than theirs. A line with both `class` and `descriptor` is a class
24//!   line;
25//! * a cell: `{"cell": {"fn": "<ns>/<name>", "args": {<name>: <typed scalar>}}, "value": <typed
26//!   scalar> or {"blob": "<file>", "media_type": "<type>"}, "tx"?, "asof"?, "issued"?, "licence",
27//!   "summary"}`: a blob's file (relative to the JSON lines file) is put with `put_blob` and the
28//!   value is `<sha256>:<length>:<media type>`; the receipt is signed with the mesh's key
29//!   (`computed_by` the mesh host, `publisher` the cell's namespace, `valid` its valid-time
30//!   arguments; `issued` defaults to the later of `asof` and the key's start) and stored with
31//!   `put_receipt` and `put_version`. `tx` and `asof` default to the run's clock now (since
32//!   0.3.1, H4), each independently. A `source` object (since 0.4.0, spec-0.6.0 C2: `name`, `url`,
33//!   `retrieved`, and optionally `sha256` and `takeover`, nothing else) marks the value as relayed: the
34//!   receipt signs it, and its trust is `relayed`; its rules are the receipt's (`retrieved` no later
35//!   than `issued`, a publisher that does not relay itself, `https://` URLs), refused at the line.
36//!
37//! The function of a cell is the one its name is bound to as of the cell's `tx`. Re-running a
38//! file changes nothing (a cell line without `tx` whose latest version states the same thing is
39//! skipped, since 0.3.1): descriptors and blobs are content-addressed, signing is deterministic
40//! (the same receipt, the same hash), and a version already there is skipped. The key is never
41//! logged.
42//!
43//! Rule A (since 0.3.0, CONTRACT-1.8b H1): no binding starts earlier than the mesh clock. The
44//! start of a binding (a name's, a class's, or a class method's `N/m`) is its `bound`, or the
45//! clock's now when `bound` is left out, and a start earlier than now is refused with
46//! [`PublishErrorKind::StartBeforeNow`]. A `--backfill` run ([`PublishOptions::backfill`]) lifts
47//! the start check, and is refused ([`PublishErrorKind::Backfill`]) when a name it would bind has
48//! a binding, or when a namespace of such a name has any binding (store 0.4.2's
49//! `has_bindings_under`). A run that writes appends one line to the log: `{"at": …, "namespaces":
50//! […], "starts": […]}`, a JCS object.
51//!
52//! No partial writes (since 0.3.1, CONTRACT-1.7a H2): the file is read in two passes. The first
53//! plans every write the second one makes, and checks each as the store will: a bind is refused
54//! when its start is not later than the latest binding of its name (the store's, or one planned
55//! earlier in the file, W1b), when the name is of the other kind (a class or a function), or when
56//! its namespace is suspended; a cell's function must be bound as of its `tx` (counting the
57//! earlier binds of the file), its blob must be readable, `tx <= asof <= issued`, and a version
58//! at or after its `tx` must be this receipt. Receipts are signed in the first pass (signing is
59//! deterministic), so their hashes are known. A file that the first pass refuses writes nothing.
60
61use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
62use std::io::{BufRead, Write};
63use std::path::{Path, PathBuf};
64use std::sync::atomic::{AtomicBool, Ordering};
65use std::sync::Arc;
66
67use datumesh_core::json::{self, Value};
68use datumesh_core::{
69    sha256_hex, Arg, Args, Cell, ClassDescriptor, FunctionDescriptor, KeyNormalisation, Receipt, ReceiptBuilder,
70    Scalar, SigningKey, Source, Type,
71};
72use datumesh_engine::{Clock, SystemClock};
73use datumesh_formula::definition::{Callee, Callees, ClassCallee};
74use datumesh_store::{Binding, CellWrite, FunctionTest, Namespace, Store};
75
76use crate::testrun::{self, run_test, Overlay, Ran, RowWrite, TestSpec};
77
78use crate::config::ConfigError;
79
80/// The end of time: a binding as of it is the latest one.
81const END: &str = "9999-12-31T23:59:59.999999Z";
82
83/// Cell lines planned together, and cell writes per `put_cells` call (CONTRACT-perf H1, H2).
84const CHUNK: usize = 1_000;
85
86/// The environment variable of the publish lanes (CONTRACT-perf H5), read once per run.
87const LANES_VAR: &str = "DATUMESH_PUBLISH_LANES";
88
89/// The lanes of a run (CONTRACT-perf H5): `DATUMESH_PUBLISH_LANES` (a positive integer), else
90/// `min(4, available_parallelism)`, at least 1. An invalid value refuses the run before any write.
91fn publish_lanes() -> Result<usize, PublishError> {
92    let bad = |detail: String| PublishError::at(0, ConfigError::new(LANES_VAR, detail).to_string());
93    match std::env::var(LANES_VAR) {
94        Err(std::env::VarError::NotPresent) => Ok(std::thread::available_parallelism().map_or(1, |n| n.get()).min(4)),
95        Ok(v) => match v.parse::<usize>() {
96            Ok(n) if n > 0 => Ok(n),
97            _ => Err(bad(format!("must be a positive integer, not {v:?}"))),
98        },
99        Err(e) => Err(bad(e.to_string())),
100    }
101}
102
103/// What a run put.
104#[non_exhaustive]
105#[derive(Clone, Debug, Default, PartialEq, Eq)]
106pub struct Published {
107    /// Functions newly bound (stored and formula).
108    pub functions: usize,
109    /// Classes newly bound (since 0.2.2).
110    pub classes: usize,
111    /// Cell lines read.
112    pub cells: usize,
113    /// Receipts stored (new or already there).
114    pub receipts: usize,
115    /// Versions newly added.
116    pub versions: usize,
117    /// Blobs put (new or already there).
118    pub blobs: usize,
119    /// Blob bytes put.
120    pub blob_bytes: u64,
121    /// Descriptors newly put by descriptor lines (since 0.3.1); a re-run counts 0.
122    pub descriptors: u64,
123}
124
125/// How a run reads the clock and whether it backfills (CONTRACT-1.8b H1).
126#[derive(Clone)]
127pub struct PublishOptions {
128    /// The mesh clock: the start of a binding left out is its now, and a start earlier than it is
129    /// refused (rule A).
130    pub clock: Arc<dyn Clock + Send + Sync>,
131    /// The operator log of a `--backfill` run (`DATUMESH_BACKFILL_LOG`). `Some` lifts the start
132    /// check, for a file whose names and namespaces have no bindings yet, and appends a line to
133    /// the log for each run that writes.
134    pub backfill: Option<PathBuf>,
135}
136
137impl PublishOptions {
138    /// The system clock, and no backfill.
139    pub fn system() -> PublishOptions {
140        PublishOptions { clock: Arc::new(SystemClock), backfill: None }
141    }
142}
143
144/// Why a line (or the file, at line 0) was refused.
145#[non_exhaustive]
146#[derive(Clone, Debug, PartialEq, Eq)]
147pub enum PublishErrorKind {
148    /// Any other refusal: [`PublishError::detail`] says what.
149    Line,
150    /// A binding's start is earlier than the mesh clock (rule A).
151    StartBeforeNow {
152        /// The name (or class name, or method name) that would bind.
153        name: String,
154        /// Its start.
155        start: String,
156        /// The mesh clock.
157        now: String,
158    },
159    /// A `--backfill` run that would write over a binding, or under a namespace with one.
160    Backfill(String),
161    /// `import-vectors`: a name the vectors would bind is under a namespace the mesh owns.
162    OwnedVectorName(String),
163    /// The public rule (D8, Build 2 Part 3, `publish_stored_checked`): a computed function's tests
164    /// do not cover the derived cases or every branch. The text lists what is missing.
165    TestsMissing(String),
166    /// The public rule: a test of a computed function fails. The text names the case and the
167    /// numbers.
168    TestsFailing(String),
169}
170
171impl std::fmt::Display for PublishErrorKind {
172    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173        match self {
174            PublishErrorKind::Line => f.write_str("refused"),
175            PublishErrorKind::StartBeforeNow { name, start, now } => {
176                write!(f, "binding start {start} of {name} is earlier than the mesh clock {now} (rule A)")
177            }
178            PublishErrorKind::Backfill(why) => write!(f, "--backfill refused: {why}"),
179            PublishErrorKind::OwnedVectorName(name) => {
180                write!(f, "{name} is under a namespace the mesh owns: import-vectors does not bind it")
181            }
182            PublishErrorKind::TestsMissing(text) => write!(f, "E_TESTS_MISSING: {text}"),
183            PublishErrorKind::TestsFailing(text) => write!(f, "E_TESTS_FAILING: {text}"),
184        }
185    }
186}
187
188/// Why a run stopped: the line, what was wrong, and its typed kind.
189#[derive(Clone, Debug, PartialEq, Eq)]
190pub struct PublishError {
191    /// The line number (1-based; 0 for the file).
192    pub line: usize,
193    /// Why, in words.
194    pub detail: String,
195    /// Why, typed.
196    pub kind: PublishErrorKind,
197}
198
199impl PublishError {
200    fn at(line: usize, detail: impl Into<String>) -> PublishError {
201        PublishError { line, detail: detail.into(), kind: PublishErrorKind::Line }
202    }
203
204    pub(crate) fn typed(line: usize, kind: PublishErrorKind) -> PublishError {
205        PublishError { line, detail: kind.to_string(), kind }
206    }
207}
208
209impl std::fmt::Display for PublishError {
210    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
211        write!(f, "line {}: {}", self.line, self.detail)
212    }
213}
214
215impl std::error::Error for PublishError {}
216
217fn s(v: &str) -> Value {
218    Value::String(v.to_string())
219}
220
221/// The namespace of a name: the name minus its last `/` segment.
222fn namespace_of(name: &str) -> &str {
223    name.rsplit_once('/').map(|(ns, _)| ns).unwrap_or("")
224}
225
226/// The host of a name: its first segment.
227fn host_of(name: &str) -> &str {
228    name.split('/').next().unwrap_or("")
229}
230
231/// The definer of a class `name`: its own namespace when the mesh owns the name's host, else the
232/// mesh's host (which no class name under another host has, so core answers `E_CLASS_OWNER`).
233fn definer<'a>(name: &'a str, host: &'a str, owned: &[String]) -> &'a str {
234    let host_of_name = name.split('/').next().unwrap_or("");
235    if owned.iter().any(|o| o == host_of_name) {
236        namespace_of(name)
237    } else {
238        host
239    }
240}
241
242/// The start of a line's binding: its `bound`, or the clock's now when it is left out.
243fn bound_of(v: &Value, line: usize, now: &str) -> Result<String, PublishError> {
244    match v.get("bound") {
245        None => Ok(now.to_string()),
246        Some(b) => b.as_str().map(str::to_string).ok_or_else(|| PublishError::at(line, "bound is not an instant")),
247    }
248}
249
250/// The bindings and versions a pass one has planned so far: the file's own, which are seen before
251/// the store's.
252#[derive(Default)]
253struct Simulation {
254    /// Function name to the (tx, function hash) of each bind the file would make.
255    functions: BTreeMap<String, Vec<(String, String)>>,
256    /// Class name to the (tx, class hash) of each class bind the file would make.
257    classes: BTreeMap<String, Vec<(String, String)>>,
258    /// Canonical bytes by function hash, of the descriptors the file would store.
259    descriptors: BTreeMap<String, Vec<u8>>,
260    /// Canonical bytes by class hash, of the classes the file would store.
261    class_bytes: BTreeMap<String, Vec<u8>>,
262    /// Cell id to the (tx, receipt hash) of each version the file would add, in tx order.
263    versions: BTreeMap<String, Vec<(String, String)>>,
264}
265
266impl Simulation {
267    /// The latest of `binds`' entries for `name` with tx <= `at`.
268    fn latest(binds: &BTreeMap<String, Vec<(String, String)>>, name: &str, at: &str) -> Option<(String, String)> {
269        binds.get(name)?.iter().filter(|(t, _)| t.as_str() <= at).max_by(|a, b| a.0.cmp(&b.0)).cloned()
270    }
271}
272
273/// The callees of a definition: the store's bindings, and with `sim` the file's own over them.
274struct Callers<'a, S: Store + ?Sized> {
275    store: &'a S,
276    sim: Option<&'a Simulation>,
277}
278
279impl<S: Store + ?Sized> Callers<'_, S> {
280    fn function_bytes(&self, hash: &str) -> Result<Option<Vec<u8>>, String> {
281        if let Some(b) = self.sim.and_then(|s| s.descriptors.get(hash)) {
282            return Ok(Some(b.clone()));
283        }
284        Ok(self.store.descriptor(hash).map(|b| b.into_owned()))
285    }
286
287    fn class_bytes(&self, hash: &str) -> Result<Option<Vec<u8>>, String> {
288        if let Some(b) = self.sim.and_then(|s| s.class_bytes.get(hash)) {
289            return Ok(Some(b.clone()));
290        }
291        self.store.class(hash).map_err(|e| e.to_string())
292    }
293}
294
295impl<S: Store + ?Sized> Callees for Callers<'_, S> {
296    /// The name a class hash is bound to, for a body's `super` and an inherited method's definer (K5): the store's
297    /// names as of now, else the file's own class binds.
298    fn class_name(&self, class_hash: &str) -> Result<Option<String>, String> {
299        let names = self
300            .store
301            .class_names_bound_to(class_hash, datumesh_formula::definition::LATEST)
302            .map_err(|e| e.to_string())?;
303        if let Some(n) = names.into_iter().next() {
304            return Ok(Some(n));
305        }
306        Ok(self.sim.and_then(|s| {
307            s.classes.iter().find(|(_, v)| v.iter().any(|(_, h)| h == class_hash)).map(|(n, _)| n.clone())
308        }))
309    }
310
311    fn callee(&self, name: &str, at: &str) -> Result<Option<Callee>, String> {
312        let stored = self.store.resolve_binding(name, at).map_err(|e| e.to_string())?;
313        let simmed = self.sim.and_then(|s| Simulation::latest(&s.functions, name, at));
314        let (fn_hash, start) = match (stored, simmed) {
315            (Some(b), Some((t, h))) if t >= b.tx => (h, t),
316            (Some(b), _) => (b.fn_hash, b.tx),
317            (None, Some((t, h))) => (h, t),
318            (None, None) => return Ok(None),
319        };
320        let bytes = self.function_bytes(&fn_hash)?.ok_or_else(|| format!("descriptor {fn_hash} is not stored"))?;
321        let descriptor = json::parse(&bytes).map_err(|e| e.to_string())?;
322        Ok(Some(Callee { fn_hash, start, descriptor }))
323    }
324
325    fn bound_class(&self, name: &str, at: &str) -> Result<Option<ClassCallee>, String> {
326        let stored = self.store.resolve_class_binding(name, at).map_err(|e| e.to_string())?;
327        let simmed = self.sim.and_then(|s| Simulation::latest(&s.classes, name, at));
328        let (class_hash, start) = match (stored, simmed) {
329            (Some(b), Some((t, h))) if t >= b.tx => (h, t),
330            (Some(b), _) => (b.class_hash, b.tx),
331            (None, Some((t, h))) => (h, t),
332            (None, None) => return Ok(None),
333        };
334        let bytes = self.class_bytes(&class_hash)?.ok_or_else(|| format!("class {class_hash} is not stored"))?;
335        let descriptor = ClassDescriptor::from_json(&bytes).map_err(|e| e.to_string())?;
336        Ok(Some(ClassCallee { class_hash, start, descriptor }))
337    }
338
339    fn class_descriptor(&self, class_hash: &str) -> Result<Option<ClassDescriptor>, String> {
340        let Some(bytes) = self.class_bytes(class_hash)? else { return Ok(None) };
341        ClassDescriptor::from_json(&bytes).map(Some).map_err(|e| e.to_string())
342    }
343
344    fn function_descriptor(&self, fn_hash: &str) -> Result<Option<Value>, String> {
345        let Some(bytes) = self.function_bytes(fn_hash)? else { return Ok(None) };
346        json::parse(&bytes).map(Some).map_err(|e| e.to_string())
347    }
348}
349
350/// What a run reads from the store again and again, kept for the run (CONTRACT-perf H1). The
351/// store does not change during the first pass, so each answer is the same whenever it is asked,
352/// and a failed read is kept as its message, which is what the check that asks it reports. A
353/// prefetch that fails keeps nothing: each line then asks for itself and fails at its own line.
354#[derive(Default)]
355struct Reads {
356    bindings: HashMap<(String, String), Result<Option<Binding>, String>>,
357    descriptors: HashMap<String, Option<Vec<u8>>>,
358    namespaces: HashMap<String, Result<Option<Namespace>, String>>,
359    /// The store's latest version of a cell (tx, receipt hash), prefetched per chunk.
360    latest_of: HashMap<String, Option<(String, String)>>,
361    /// The store's receipt, prefetched for the latest receipts a skip check reads.
362    receipt_of: HashMap<String, Option<Vec<u8>>>,
363}
364
365impl Reads {
366    fn binding<S: Store + ?Sized>(&mut self, store: &S, name: &str, at: &str) -> Result<Option<Binding>, String> {
367        let key = (name.to_string(), at.to_string());
368        if let Some(r) = self.bindings.get(&key) {
369            return r.clone();
370        }
371        let r = store.resolve_binding(name, at).map_err(|e| e.to_string());
372        self.bindings.insert(key, r.clone());
373        r
374    }
375
376    fn descriptor<S: Store + ?Sized>(&mut self, store: &S, hash: &str) -> Option<Vec<u8>> {
377        if let Some(b) = self.descriptors.get(hash) {
378            return b.clone();
379        }
380        let b = store.descriptor(hash).map(|b| b.into_owned());
381        self.descriptors.insert(hash.to_string(), b.clone());
382        b
383    }
384
385    fn namespace<S: Store + ?Sized>(&mut self, store: &S, host: &str) -> Result<Option<Namespace>, String> {
386        if let Some(r) = self.namespaces.get(host) {
387            return r.clone();
388        }
389        let r = store.namespace(host).map_err(|e| e.to_string());
390        self.namespaces.insert(host.to_string(), r.clone());
391        r
392    }
393
394    /// The store's latest version of `id`: prefetched, else asked now.
395    fn latest<S: Store + ?Sized>(&mut self, store: &S, id: &str) -> Result<Option<(String, String)>, String> {
396        if let Some(l) = self.latest_of.get(id) {
397            return Ok(l.clone());
398        }
399        store.latest(id).map(|v| v.map(|v| (v.tx, v.receipt_hash))).map_err(|e| e.to_string())
400    }
401
402    /// The stored receipt `hash`, as `receipt` answers: prefetched, else asked now.
403    fn receipt<S: Store + ?Sized>(&mut self, store: &S, hash: &str) -> Option<Vec<u8>> {
404        if let Some(b) = self.receipt_of.get(hash) {
405            return b.clone();
406        }
407        store.receipt(hash).map(|b| b.into_owned())
408    }
409
410    /// A `latest_many` a page at a time, for the ids not read yet.
411    fn prefetch_latest<S: Store + ?Sized>(&mut self, store: &S, ids: &[&str]) {
412        let mut seen = HashSet::new();
413        let missing: Vec<&str> =
414            ids.iter().copied().filter(|id| !self.latest_of.contains_key(*id) && seen.insert(*id)).collect();
415        // A page of ids a statement (CONTRACT-0.5.1 H2: the job never asks the store for more than a page at a time).
416        for page in missing.chunks(crate::catalog_build::PAGE) {
417            if let Ok(found) = store.latest_many(page) {
418                for (id, v) in page.iter().zip(found) {
419                    self.latest_of.insert(id.to_string(), v.map(|v| (v.tx, v.receipt_hash)));
420                }
421            }
422        }
423    }
424
425    /// A `receipts_many` a page at a time, for the hashes not read yet.
426    fn prefetch_receipts<S: Store + ?Sized>(&mut self, store: &S, hashes: &[&str]) {
427        let mut seen = HashSet::new();
428        let missing: Vec<&str> =
429            hashes.iter().copied().filter(|h| !self.receipt_of.contains_key(*h) && seen.insert(*h)).collect();
430        for page in missing.chunks(crate::catalog_build::PAGE) {
431            if let Ok(found) = store.receipts_many(page) {
432                for (h, b) in page.iter().zip(found) {
433                    self.receipt_of.insert(h.to_string(), b);
434                }
435            }
436        }
437    }
438}
439
440/// `f` over `items` on up to `available_parallelism()` threads; the results in item order.
441fn parallel_owned<T: Send, R: Send>(items: Vec<T>, f: impl Fn(T) -> R + Sync) -> Vec<R> {
442    let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len());
443    if threads <= 1 {
444        return items.into_iter().map(f).collect();
445    }
446    let size = items.len().div_ceil(threads);
447    let mut parts: Vec<Vec<T>> = Vec::with_capacity(threads);
448    let mut rest = items.into_iter();
449    loop {
450        let part: Vec<T> = rest.by_ref().take(size).collect();
451        if part.is_empty() {
452            break;
453        }
454        parts.push(part);
455    }
456    std::thread::scope(|s| {
457        let handles: Vec<_> = parts
458            .into_iter()
459            .map(|part| {
460                let f = &f;
461                s.spawn(move || part.into_iter().map(f).collect::<Vec<R>>())
462            })
463            .collect();
464        handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))).collect()
465    })
466}
467
468/// The function hash `name` means at the end of time: the file's own over the store's.
469fn current_function<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
470    if let Some((_, h)) = Simulation::latest(&sim.functions, name, END) {
471        return Ok(Some(h));
472    }
473    store.resolve_name(name, END).map_err(|e| e.to_string())
474}
475
476/// The class hash `name` means at the end of time: the file's own over the store's.
477fn current_class<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<Option<String>, String> {
478    if let Some((_, h)) = Simulation::latest(&sim.classes, name, END) {
479        return Ok(Some(h));
480    }
481    store.resolve_class(name, END).map_err(|e| e.to_string())
482}
483
484/// Whether the key `k` of a class is an argument of the function `fd` of its type (K9): a scalar key's type, or a class-typed
485/// key's `string` argument that holds the class's keys.
486fn key_matches(cd: &ClassDescriptor, fd: &FunctionDescriptor, k: &str) -> bool {
487    let (Some(ck), Some(arg)) = (cd.keys.get(k), fd.signature.args.get(k)) else { return false };
488    match ck {
489        datumesh_core::ClassKey::Scalar { ty, .. } => arg.ty == *ty,
490        datumesh_core::ClassKey::Class(c) => {
491            arg.ty == Type::String
492                && fd.arg_extras.get(k).and_then(|x| x.classes.as_ref()).is_some_and(|cs| cs.iter().any(|x| x == c))
493        }
494        _ => false,
495    }
496}
497
498/// The function hash `name` means as of `at`, counting the file's earlier binds.
499fn function_at<S: Store + ?Sized>(
500    reads: &mut Reads,
501    store: &S,
502    sim: &Simulation,
503    name: &str,
504    at: &str,
505) -> Result<Option<String>, String> {
506    let stored = reads.binding(store, name, at)?;
507    let simmed = Simulation::latest(&sim.functions, name, at);
508    Ok(match (stored, simmed) {
509        (Some(b), Some((t, h))) if t >= b.tx => Some(h),
510        (Some(b), _) => Some(b.fn_hash),
511        (None, Some((_, h))) => Some(h),
512        (None, None) => None,
513    })
514}
515
516/// The latest binding tx of `name` (a class's, or a function's), the store's or the file's.
517fn latest_bind<S: Store + ?Sized>(
518    store: &S,
519    sim: &Simulation,
520    name: &str,
521    class: bool,
522) -> Result<Option<String>, String> {
523    let stored: Option<String> = if class {
524        store.resolve_class_binding(name, END).map_err(|e| e.to_string())?.map(|b| b.tx)
525    } else {
526        store.resolve_binding(name, END).map_err(|e| e.to_string())?.map(|b| b.tx)
527    };
528    let binds = if class { &sim.classes } else { &sim.functions };
529    let planned = binds.get(name).and_then(|v| v.iter().map(|(t, _)| t.clone()).max());
530    Ok(match (stored, planned) {
531        (Some(a), Some(b)) => Some(a.max(b)),
532        (a, b) => a.or(b),
533    })
534}
535
536/// Whether `name` is bound as the other kind: a function for a class, a class for a function.
537fn bound_as_other<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str, class: bool) -> Result<bool, String> {
538    if class {
539        Ok(store.resolve_binding(name, END).map_err(|e| e.to_string())?.is_some() || sim.functions.contains_key(name))
540    } else {
541        Ok(store.resolve_class_binding(name, END).map_err(|e| e.to_string())?.is_some()
542            || sim.classes.contains_key(name))
543    }
544}
545
546/// The latest version of a cell, the store's or the file's: its tx and receipt hash.
547fn cell_latest<S: Store + ?Sized>(
548    reads: &mut Reads,
549    store: &S,
550    sim: &Simulation,
551    id: &str,
552) -> Result<Option<(String, String)>, String> {
553    let stored = reads.latest(store, id)?;
554    let planned = sim.versions.get(id).and_then(|v| v.last().cloned());
555    Ok(match (stored, planned) {
556        (Some(a), Some(b)) => Some(if b.0 > a.0 { b } else { a }),
557        (a, b) => a.or(b),
558    })
559}
560
561/// The receipt hash of a cell's version as of `at`, the store's or the file's.
562fn cell_version_asof<S: Store + ?Sized>(
563    store: &S,
564    sim: &Simulation,
565    id: &str,
566    at: &str,
567) -> Result<Option<String>, String> {
568    let stored = store.version_asof(id, at).map_err(|e| e.to_string())?.map(|v| (v.tx, v.receipt_hash));
569    let planned = sim.versions.get(id).and_then(|v| v.iter().rev().find(|(t, _)| t.as_str() <= at).cloned());
570    let latest = match (stored, planned) {
571        (Some(a), Some(b)) => Some(if b.0 > a.0 { b } else { a }),
572        (a, b) => a.or(b),
573    };
574    Ok(latest.map(|x| x.1))
575}
576
577/// The descriptor bytes of a function hash: the file's own, else the store's (memoized).
578fn function_bytes_of<S: Store + ?Sized>(
579    reads: &mut Reads,
580    store: &S,
581    sim: &Simulation,
582    hash: &str,
583) -> Result<Option<Vec<u8>>, String> {
584    if let Some(b) = sim.descriptors.get(hash) {
585        return Ok(Some(b.clone()));
586    }
587    Ok(reads.descriptor(store, hash))
588}
589
590/// Whether a namespace is suspended (the store refuses binds and class puts under it).
591fn suspended<S: Store + ?Sized>(reads: &mut Reads, store: &S, host: &str, line: usize) -> Result<(), PublishError> {
592    match reads.namespace(store, host) {
593        Ok(Some(n)) if n.suspended_at.is_some() => {
594            Err(PublishError::at(line, format!("{host} is suspended: no new bindings or classes under it")))
595        }
596        Ok(_) => Ok(()),
597        Err(e) => Err(PublishError::at(line, e)),
598    }
599}
600
601/// A binding a run would make: the line that makes it and its name.
602struct Bind {
603    line: usize,
604    name: String,
605}
606
607/// What a run writes, for the backfill log: the namespaces and starts of its binds.
608#[derive(Default)]
609struct Written {
610    namespaces: BTreeSet<String>,
611    starts: BTreeSet<String>,
612}
613
614impl Written {
615    fn bound(&mut self, name: &str, start: &str) {
616        self.namespaces.insert(namespace_of(name).to_string());
617        self.starts.insert(start.to_string());
618    }
619}
620
621/// The per-run values both passes use.
622struct Ctx<'a> {
623    host: &'a str,
624    owned: &'a [String],
625    /// The start of the mesh's key.
626    key_from: &'a str,
627    /// The clock's now, read once for the run.
628    now: &'a str,
629    /// The directory of the file (blobs are relative to it).
630    base: &'a Path,
631    /// The catalogue job's run (C1): the one run that may write under `<host>/catalog`.
632    job: bool,
633    /// Blobs given in memory, by the file name a cell line gives (the job's rule text); read before the directory.
634    blobs: &'a BTreeMap<String, Vec<u8>>,
635}
636
637/// One write the second pass makes, planned (and checked) by the first.
638enum Op {
639    /// A descriptor line: put; counted when newly put.
640    Descriptor { hash: String, bytes: Vec<u8>, counted: bool },
641    /// A function (stored or formula): put its descriptor, and bind the name when `bind`.
642    Function { name: String, start: String, hash: String, bytes: Vec<u8>, bind: bool },
643    /// A class: put it, and bind it (its methods with it, in the store) when `bind`. `methods` are the
644    /// methods' names and function hashes, bound under their names with the class.
645    Class { name: String, start: String, hash: String, bytes: Vec<u8>, bind: bool, methods: Vec<(String, String)> },
646    /// A cell: its blob, its receipt, and the version when `version`.
647    Cell { tx: String, id: String, receipt: Vec<u8>, blob: Option<Vec<u8>>, version: bool },
648    /// A name closed (R2): the store ends its binding (and a class's methods') at `at`.
649    Close { name: String, at: String },
650    /// A catalogue line (R5): the entry, and its dictionaries (`publisher`, signed by the run's key).
651    Catalog {
652        entry: datumesh_store::CatalogEntry,
653        dictionaries: Vec<(String, Vec<datumesh_store::KeyValue>)>,
654        open_keys: Vec<String>,
655        extends: Option<String>,
656        facets: datumesh_store::Facets,
657        /// The entry's `source_name` (R8), as the line gives it.
658        source_name: Option<String>,
659    },
660}
661
662/// The lines of a file, numbered, without the blank ones.
663fn read_lines(path: &Path) -> Result<Vec<(usize, String)>, PublishError> {
664    let file = std::fs::File::open(path).map_err(|e| PublishError::at(0, format!("{}: {e}", path.display())))?;
665    let mut out = Vec::new();
666    for (i, line) in std::io::BufReader::new(file).lines().enumerate() {
667        let n = i + 1;
668        let line = line.map_err(|e| PublishError::at(n, e.to_string()))?;
669        if !line.trim().is_empty() {
670            out.push((n, line));
671        }
672    }
673    Ok(out)
674}
675
676/// The dictionary values the file's cells have for the string arguments (CONTRACT-build2-part2-read
677/// R3): each distinct (function, key, value) that no dictionary has yet is stored with an empty label
678/// (the value stands for itself). A dictionary's label is never replaced by a cell's.
679fn index_cell_values<S: Store + ?Sized>(store: &S, ops: &[Op]) -> Result<(), String> {
680    let mut seen = BTreeSet::new();
681    for op in ops {
682        if let Op::Cell { receipt, .. } = op {
683            if let Ok(r) = datumesh_core::Receipt::from_json(receipt) {
684                cell_string_values(&r, &mut seen);
685            }
686        }
687    }
688    store_cell_values(store, seen)
689}
690
691/// The (function, key, value) of each string argument of a receipt's cell, into `out`.
692pub(crate) fn cell_string_values(r: &datumesh_core::Receipt, out: &mut BTreeSet<(String, String, String)>) {
693    let cell = r.cell();
694    for (key, arg) in &cell.args {
695        if let datumesh_core::Arg::Value(datumesh_core::Scalar::String(v)) = arg {
696            if !v.is_empty() && v.len() <= 1024 {
697                out.insert((cell.function_name(), key.clone(), v.clone()));
698            }
699        }
700    }
701}
702
703/// The most distinct values a string key of a function takes from its cells before the key is open
704/// (`DATUMESH_DICTIONARY_MAX`, CONTRACT-0.4.9 H7): read from the process environment when it is needed; 1000 when
705/// unset or not a positive integer.
706pub(crate) fn dictionary_limit() -> u64 {
707    std::env::var("DATUMESH_DICTIONARY_MAX")
708        .ok()
709        .and_then(|v| v.trim().parse::<u64>().ok())
710        .filter(|n| *n >= 1)
711        .unwrap_or(1000)
712}
713
714/// Stores the values of [`cell_string_values`] that no dictionary has yet (R3), by the rule of CONTRACT-0.4.9 H7:
715/// for each (function, key) the new values are added only while the key would have at most
716/// [`dictionary_limit`] values; a publish that would take it past the limit adds none of them and marks the key
717/// open. An open key takes no automatic values again; the values it has stay.
718pub(crate) fn store_cell_values<S: Store + ?Sized>(
719    store: &S,
720    seen: BTreeSet<(String, String, String)>,
721) -> Result<(), String> {
722    let mut groups: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
723    for (owner, key, value) in seen {
724        groups.entry((owner, key)).or_default().push(value);
725    }
726    let limit = dictionary_limit();
727    for ((owner, key), values) in groups {
728        if store.key_is_open(&owner, &key).map_err(|e| e.to_string())? {
729            continue;
730        }
731        let fresh: Vec<String> =
732            values.into_iter().filter(|v| !crate::find::has_value(store, &owner, &key, v)).collect();
733        if fresh.is_empty() {
734            continue;
735        }
736        let have = store.key_value_count(&owner, &key).map_err(|e| e.to_string())?;
737        if have + fresh.len() as u64 > limit {
738            store.mark_key_open(&owner, &key).map_err(|e| e.to_string())?;
739            continue;
740        }
741        let kvs: Vec<datumesh_store::KeyValue> = fresh
742            .into_iter()
743            .map(|value| datumesh_store::KeyValue { value, label: String::new(), aliases: Vec::new() })
744            .collect();
745        store.upsert_key_values(&owner, &key, &kvs).map_err(|e| e.to_string())?;
746    }
747    Ok(())
748}
749
750/// The function a test row is named by when it is written (CONTRACT-0.4.9 H1): a file's own test names the
751/// function its `test` member names; a held test is the group's function.
752fn row_name(own: Option<usize>, spec: &TestSpec, group: &str) -> String {
753    match own {
754        Some(_) => spec.function.clone(),
755        None => group.to_string(),
756    }
757}
758
759/// Whether a line is a cell line: none of the other kinds (the dispatch order of `plan_line`).
760fn is_cell_line(v: &Value) -> bool {
761    v.get("class").and_then(Value::as_str).is_none()
762        && v.get("descriptor").is_none()
763        && v.get("function").and_then(Value::as_str).is_none()
764        && v.get("formula").and_then(Value::as_str).is_none()
765        && v.get("cell").is_some()
766}
767
768/// A cell line prepared for signing: everything its receipt takes, checked up to there.
769struct Pending {
770    line: usize,
771    ns: String,
772    cell: Cell,
773    /// The value; `None` for a withdrawal.
774    value: Option<Scalar>,
775    /// The reason of a withdrawal (R1), which takes the value's place.
776    withdrawn: Option<String>,
777    valid: Args,
778    tx: String,
779    asof: String,
780    issued: String,
781    has_tx: bool,
782    licence: String,
783    summary: String,
784    blob: Option<Vec<u8>>,
785    /// The `source` of a relayed value (spec-0.6.0, 8.1), as the line gives it.
786    source: Option<Source>,
787}
788
789/// The `source` object of a cell line (spec-0.6.0, C2): exactly `name`, `url` and `retrieved`, with
790/// `sha256` and `takeover` optional, all strings. Its rules (a DNS name, an instant, an `https://`
791/// takeover, a publisher that does not relay itself) are the receipt's, checked when it is signed.
792fn source_of_line(v: &Value) -> Result<Source, String> {
793    let Value::Object(m) = v else { return Err("source is an object".into()) };
794    for (k, x) in m {
795        if !matches!(k.as_str(), "name" | "url" | "retrieved" | "sha256" | "takeover") {
796            return Err(format!("source has no member {k}"));
797        }
798        if !matches!(x, Value::String(_)) {
799            return Err(format!("source.{k} is a string"));
800        }
801    }
802    let text = |k: &str| -> Result<&str, String> {
803        v.get(k).and_then(Value::as_str).ok_or_else(|| format!("source has no {k}"))
804    };
805    let mut out = Source::new(text("name")?, text("url")?, text("retrieved")?);
806    if let Some(h) = v.get("sha256").and_then(Value::as_str) {
807        out = out.with_sha256(h);
808    }
809    if let Some(t) = v.get("takeover").and_then(Value::as_str) {
810        out = out.with_takeover(t);
811    }
812    Ok(out)
813}
814
815impl Pending {
816    /// Signs the receipt (deterministic) and takes its hash and cell id. Runs on any thread.
817    fn sign(self, key: &SigningKey, host: &str) -> Result<Signed, PublishError> {
818        let line = self.line;
819        let err = move |d: String| PublishError::at(line, d);
820        let b = ReceiptBuilder::new()
821            .cell(self.cell.clone())
822            .valid(self.valid)
823            .asof(self.asof.as_str())
824            .tx(self.tx.as_str())
825            .issued(self.issued.as_str())
826            .publisher(self.ns.as_str())
827            .signer_host(host)
828            .licence(self.licence.as_str())
829            .summary(self.summary.as_str());
830        let b = match self.source {
831            Some(s) => b.source(s),
832            None => b,
833        };
834        if let Some(reason) = &self.withdrawn {
835            // A withdrawal is signed as a receipt is (SPEC 8.1, R1); its canonical bytes are the stored receipt.
836            let w = b.withdrawn(reason).sign_withdrawal(key).map_err(|e| err(e.to_string()))?;
837            let id = self.cell.id();
838            return Ok(Signed {
839                line,
840                has_tx: self.has_tx,
841                tx: self.tx,
842                id,
843                hash: w.hash().to_string(),
844                receipt: w.canonical().to_vec(),
845                blob: None,
846            });
847        }
848        let Some(value) = self.value else { return Err(err("a cell without value".into())) };
849        let r = b.value(value).sign(key).map_err(|e| err(e.to_string()))?;
850        let receipt = receipt_json(&r);
851        let hash = Receipt::from_json(&receipt).map_err(|e| err(e.to_string()))?.hash().to_string();
852        let id = self.cell.id();
853        Ok(Signed { line, has_tx: self.has_tx, tx: self.tx, id, hash, receipt, blob: self.blob })
854    }
855}
856
857/// A cell line signed: what its checks and its write take.
858struct Signed {
859    line: usize,
860    has_tx: bool,
861    tx: String,
862    id: String,
863    hash: String,
864    receipt: Vec<u8>,
865    blob: Option<Vec<u8>>,
866}
867
868/// Pass one: plans the writes of the lines and checks each as the store will (CONTRACT-1.7a H2).
869struct Planner<'a, S: Store + ?Sized> {
870    store: &'a S,
871    key: &'a SigningKey,
872    ctx: Ctx<'a>,
873    backfill: bool,
874    sim: Simulation,
875    reads: Reads,
876    ops: Vec<Op>,
877    binds: Vec<Bind>,
878    /// The test lines of the file, with their lines (Build 2 Part 3).
879    tests: Vec<(usize, TestSpec)>,
880    /// The computed functions the file defines: (line, name, function hash).
881    formulas: Vec<(usize, String, String)>,
882}
883
884impl<S: Store + ?Sized> Planner<'_, S> {
885    fn callers(&self) -> Callers<'_, S> {
886        Callers { store: self.store, sim: Some(&self.sim) }
887    }
888
889    /// Plans the lines in file order. Cell lines are planned in chunks of up to `CHUNK`
890    /// consecutive ones; any other line ends a chunk (CONTRACT-perf H1).
891    fn run(&mut self, lines: &[(usize, String)]) -> Result<(), PublishError> {
892        let mut cells: Vec<(usize, Value)> = Vec::new();
893        for (n, text) in lines {
894            let n = *n;
895            match json::parse(text.as_bytes()).map_err(|e| PublishError::at(n, e.to_string())) {
896                Ok(v) if is_cell_line(&v) => {
897                    // The reserved paths (CONTRACT-0.4.9 H8), as for any other line.
898                    if let Some(name) = v.get("cell").and_then(|c| c.get("fn")).and_then(Value::as_str) {
899                        crate::reserved::check_for(self.ctx.host, name, None, self.ctx.job)
900                            .map_err(|e| PublishError::at(n, e))?;
901                    }
902                    cells.push((n, v));
903                    if cells.len() == CHUNK {
904                        self.plan_cells(std::mem::take(&mut cells))?;
905                    }
906                }
907                other => {
908                    // The cells before this line are checked first: a failure of either is the
909                    // file's first.
910                    self.plan_cells(std::mem::take(&mut cells))?;
911                    self.plan_line(n, &other?)?;
912                }
913            }
914        }
915        self.plan_cells(cells)
916    }
917
918    /// One line that is not a cell (the dispatch of the lines before cells, as it was).
919    fn plan_line(&mut self, n: usize, v: &Value) -> Result<(), PublishError> {
920        let err = |d: String| PublishError::at(n, d);
921        // The reserved paths (CONTRACT-0.4.9 H8): a name a line gives is checked before anything else of it. The
922        // file is written by the mesh's own key, which takes no key namespace's name.
923        let named =
924            v.get("class").or_else(|| v.get("function")).or_else(|| v.get("formula")).or_else(|| v.get("catalog"));
925        if let Some(name) = named.and_then(Value::as_str) {
926            crate::reserved::check_for(self.ctx.host, name, None, self.ctx.job).map_err(err)?;
927        }
928        if let Some(name) = v.get("class").and_then(Value::as_str) {
929            self.class_line(n, name, v)?;
930        } else if let Some(d) = v.get("descriptor") {
931            self.descriptor_line(n, d)?;
932        } else if let Some(name) = v.get("function").and_then(Value::as_str) {
933            let sig = v.get("signature").ok_or_else(|| err("a function without a signature".into()))?;
934            let start = bound_of(v, n, self.ctx.now)?;
935            let fd = FunctionDescriptor::from_value(&stored_value(sig)).map_err(|e| err(e.to_string()))?;
936            self.function(n, name, start, fd.hash(), fd.canonical())?;
937        } else if let Some(name) = v.get("close").and_then(Value::as_str) {
938            if v.as_object().is_some_and(|m| m.len() != 1) {
939                return Err(err(
940                    "a close line takes only close: the name's binding ends at the clock of the write".into()
941                ));
942            }
943            self.close_line(n, name)?;
944        } else if v.get("catalog").is_some() {
945            self.catalog_line(n, v)?;
946        } else if let Some(name) = v.get("formula").and_then(Value::as_str) {
947            let source =
948                v.get("source").and_then(Value::as_str).ok_or_else(|| err("a formula without source".into()))?;
949            let sig = v.get("signature").ok_or_else(|| err("a formula without a signature".into()))?;
950            let start = bound_of(v, n, self.ctx.now)?;
951            let def = datumesh_formula::definition::define_function(
952                name,
953                source,
954                sig,
955                &Default::default(),
956                &self.callers(),
957                &start,
958            )
959            .map_err(|e| err(format!("define {name}: {e}")))?;
960            let hash = def.fn_hash.clone();
961            self.function(n, name, start, def.fn_hash, def.bytes)?;
962            self.formulas.push((n, name.to_string(), hash));
963        } else if v.get("test").is_some() {
964            let spec = testrun::parse_test(v).map_err(err)?;
965            self.tests.push((n, spec));
966        } else {
967            return Err(err("neither a function nor a cell".into()));
968        }
969        Ok(())
970    }
971
972    /// `{"close": <full name>}` (R2, SPEC 9.7): the name's binding ends at the run's clock, and a class closes its
973    /// methods with it (the store's rule). Refused as `E_NAME_UNBOUND` when the name is not bound, and as
974    /// `E_TIME_ORDER` when the clock is not later than the name's latest binding (a close is not backdated).
975    fn close_line(&mut self, n: usize, name: &str) -> Result<(), PublishError> {
976        let err = |d: String| PublishError::at(n, d);
977        let class = current_class(self.store, &self.sim, name).map_err(err)?.is_some();
978        let bound = class || current_function(self.store, &self.sim, name).map_err(err)?.is_some();
979        if !bound {
980            return Err(err(format!("E_NAME_UNBOUND: {name} is not bound, so it cannot be closed")));
981        }
982        if let Some(tx) = latest_bind(self.store, &self.sim, name, class).map_err(err)? {
983            if self.ctx.now <= tx.as_str() {
984                return Err(err(format!(
985                    "E_TIME_ORDER: the close of {name} at {} is not later than its binding at {tx}",
986                    self.ctx.now
987                )));
988            }
989        }
990        self.ops.push(Op::Close { name: name.to_string(), at: self.ctx.now.to_string() });
991        Ok(())
992    }
993
994    /// `{"catalog": <name>, "kind", "label", "description", "args", "examples", "dictionary"}` (R5):
995    /// the publisher's text for a function or class bound in this file or the store, under a host
996    /// this mesh owns. Checked here, so a refused line writes nothing.
997    fn catalog_line(&mut self, n: usize, v: &Value) -> Result<(), PublishError> {
998        let err = |d: String| PublishError::at(n, d);
999        let d = crate::catalog::parse(v, "catalog").map_err(err)?;
1000        let host = host_of(&d.name);
1001        if host != self.ctx.host && !self.ctx.owned.iter().any(|o| o == host) {
1002            return Err(err(format!("{} is not under a host this mesh owns", d.name)));
1003        }
1004        let hash = match d.kind {
1005            datumesh_store::CatalogKind::Class => current_class(self.store, &self.sim, &d.name).map_err(err)?,
1006            _ => current_function(self.store, &self.sim, &d.name).map_err(err)?,
1007        };
1008        if hash.is_none() {
1009            return Err(err(format!("{} is bound nowhere", d.name)));
1010        }
1011        if let (Some(class), Some(fh)) = (&d.extends, &hash) {
1012            self.check_extension(class, fh).map_err(err)?;
1013        }
1014        let entry = d.entry(hash, datumesh_store::CatalogSource::Publisher, Some(self.key.key_id().to_string()));
1015        self.ops.push(Op::Catalog {
1016            entry,
1017            dictionaries: d.dictionary,
1018            open_keys: d.open_keys,
1019            extends: d.extends,
1020            facets: d.facets,
1021            source_name: d.source_name,
1022        });
1023        Ok(())
1024    }
1025
1026    /// `{"descriptor": ...}`: a stored function's descriptor, put and bound to nothing.
1027    fn descriptor_line(&mut self, n: usize, d: &Value) -> Result<(), PublishError> {
1028        let fd = FunctionDescriptor::from_value(d).map_err(|e| PublishError::at(n, e.to_string()))?;
1029        if fd.lang != "stored" || !fd.body.is_empty() || !fd.inputs.is_empty() {
1030            return Err(PublishError::at(
1031                n,
1032                "a descriptor line takes a stored function only: code.lang stored, code.body empty, no inputs",
1033            ));
1034        }
1035        let (hash, bytes) = (fd.hash(), fd.canonical());
1036        self.sim.descriptors.insert(hash.clone(), bytes.clone());
1037        self.ops.push(Op::Descriptor { hash, bytes, counted: true });
1038        Ok(())
1039    }
1040
1041    /// A function's descriptor (stored or formula): put, and bound when its name does not mean it.
1042    fn function(
1043        &mut self,
1044        n: usize,
1045        name: &str,
1046        start: String,
1047        hash: String,
1048        bytes: Vec<u8>,
1049    ) -> Result<(), PublishError> {
1050        self.sim.descriptors.insert(hash.clone(), bytes.clone());
1051        let current = current_function(self.store, &self.sim, name).map_err(|e| PublishError::at(n, e))?;
1052        let bind = current.as_deref() != Some(hash.as_str());
1053        if bind {
1054            self.check_bind(n, name, &start, false)?;
1055            self.sim.functions.entry(name.to_string()).or_default().push((start.clone(), hash.clone()));
1056        }
1057        self.ops.push(Op::Function { name: name.to_string(), start, hash, bytes, bind });
1058        Ok(())
1059    }
1060
1061    /// The methods of a class line written inline (CONTRACT-classes-round K7): `{"stored": <signature>}` and
1062    /// `{"formula": <source>, "signature": <signature>}`, each defined as the function `<class>/<m>` (a formula's `this` is the
1063    /// class, checked against the class's draft). Returns the class descriptor with each inline method's function hash in
1064    /// place of what was written; a function hash is kept as it is. The functions are planned here and bound by the class
1065    /// (`bind_class`, one transaction), not by themselves. The formula methods' reads of each other with `this` must not form
1066    /// a cycle (16.3): a cycle is refused at the class line.
1067    fn inline_methods(
1068        &mut self,
1069        n: usize,
1070        class: &str,
1071        descriptor: &Value,
1072        start: &str,
1073    ) -> Result<Value, PublishError> {
1074        let err = |d: String| PublishError::at(n, d);
1075        let Some(Value::Object(written)) = descriptor.get("methods") else { return Ok(descriptor.clone()) };
1076        if !written.iter().any(|(_, v)| matches!(v, Value::Object(_))) {
1077            return Ok(descriptor.clone());
1078        }
1079        let mut hashes: BTreeMap<String, String> = BTreeMap::new();
1080        let mut sigs: Vec<(String, Value)> = Vec::new();
1081        let mut formulas: Vec<(String, String, Value)> = Vec::new();
1082        let mut stored: Vec<(String, String, Vec<u8>)> = Vec::new();
1083        for (m, v) in written {
1084            let fq = format!("{class}/{m}");
1085            match v {
1086                Value::String(h) => {
1087                    let bytes = function_bytes_of(&mut self.reads, self.store, &self.sim, h)
1088                        .map_err(err)?
1089                        .ok_or_else(|| err(format!("{fq}: no descriptor {h}")))?;
1090                    let d = json::parse(&bytes).map_err(|e| err(e.to_string()))?;
1091                    sigs.push((m.clone(), d.get("signature").cloned().unwrap_or(Value::Null)));
1092                    hashes.insert(m.clone(), h.clone());
1093                }
1094                Value::Object(o) => {
1095                    let get = |k: &str| o.iter().find(|(x, _)| x == k).map(|(_, y)| y);
1096                    match (get("stored"), get("formula"), get("signature")) {
1097                        (Some(sig), None, None) => {
1098                            let fd = FunctionDescriptor::from_value(&stored_value(sig)).map_err(|e| err(format!("{fq}: {e}")))?;
1099                            hashes.insert(m.clone(), fd.hash());
1100                            sigs.push((m.clone(), sig.clone()));
1101                            stored.push((fq, fd.hash(), fd.canonical()));
1102                        }
1103                        (None, Some(Value::String(src)), Some(sig)) => {
1104                            sigs.push((m.clone(), sig.clone()));
1105                            formulas.push((m.clone(), src.clone(), sig.clone()));
1106                        }
1107                        _ => {
1108                            return Err(err(format!(
1109                                "{fq}: a method is a function hash, {{\"stored\": <signature>}} or {{\"formula\": <source>, \"signature\": <signature>}}"
1110                            )))
1111                        }
1112                    }
1113                }
1114                _ => return Err(err(format!("{fq}: a method is a function hash or an inline definition"))),
1115            }
1116        }
1117        for (fq, hash, bytes) in stored {
1118            self.sim.descriptors.insert(hash.clone(), bytes.clone());
1119            self.ops.push(Op::Function { name: fq, start: start.to_string(), hash, bytes, bind: false });
1120        }
1121        // The class's keys are the flattened ones (16.2): the parent's first, then the class's own.
1122        let mut keys: Vec<(String, Value)> = Vec::new();
1123        let mut order: Vec<Value> = Vec::new();
1124        if let Some(p) = descriptor.get("parent").and_then(Value::as_str) {
1125            let bytes = self
1126                .callers()
1127                .class_bytes(p)
1128                .map_err(err)?
1129                .ok_or_else(|| err(format!("{class}: the parent {p} is not stored")))?;
1130            let pv = json::parse(&bytes).map_err(|e| err(e.to_string()))?;
1131            if let Some(Value::Object(ks)) = pv.get("keys") {
1132                keys.extend(ks.iter().cloned());
1133            }
1134            if let Some(Value::Array(os)) = pv.get("order") {
1135                order.extend(os.iter().cloned());
1136            }
1137        }
1138        if let Some(Value::Object(ks)) = descriptor.get("keys") {
1139            for (k, v) in ks {
1140                if !keys.iter().any(|(x, _)| x == k) {
1141                    keys.push((k.clone(), v.clone()));
1142                }
1143            }
1144        }
1145        if let Some(Value::Array(os)) = descriptor.get("order") {
1146            for o in os {
1147                if !order.iter().any(|x| x.as_str() == o.as_str()) {
1148                    order.push(o.clone());
1149                }
1150            }
1151        }
1152        let mut draft_members = vec![
1153            ("keys".to_string(), Value::Object(keys)),
1154            ("order".to_string(), Value::Array(order)),
1155            ("methods".to_string(), Value::Object(sigs)),
1156        ];
1157        if let Some(p) = descriptor.get("parent") {
1158            draft_members.push(("parent".to_string(), p.clone()));
1159        }
1160        let draft = datumesh_formula::definition::ClassDraft::from_value(&Value::Object(draft_members))
1161            .map_err(|e| err(format!("{class}: {e}")))?;
1162        let defined = {
1163            let callers = self.callers();
1164            let mut defined = Vec::with_capacity(formulas.len());
1165            for (m, src, sig) in &formulas {
1166                let fq = format!("{class}/{m}");
1167                let def =
1168                    datumesh_formula::definition::define_method_in_draft(class, &draft, &fq, src, sig, &callers, start)
1169                        .map_err(|e| err(format!("define {fq}: {e}")))?;
1170                defined.push((m.clone(), def));
1171            }
1172            defined
1173        };
1174        // Each formula method after the formula methods it reads with `this` (16.3): a cycle is refused.
1175        let names: BTreeSet<String> = defined.iter().map(|(m, _)| m.clone()).collect();
1176        let reads: BTreeMap<String, BTreeSet<String>> = defined
1177            .iter()
1178            .map(|(m, d)| {
1179                let prefix = format!("{class}/");
1180                let rs = d
1181                    .callees
1182                    .keys()
1183                    .filter_map(|c| c.strip_prefix(prefix.as_str()))
1184                    .filter(|x| names.contains(*x))
1185                    .map(str::to_string)
1186                    .collect();
1187                (m.clone(), rs)
1188            })
1189            .collect();
1190        let mut done: BTreeSet<String> = BTreeSet::new();
1191        let mut order: Vec<String> = Vec::new();
1192        while order.len() < defined.len() {
1193            let next = defined
1194                .iter()
1195                .map(|(m, _)| m)
1196                .find(|m| !done.contains(*m) && reads.get(*m).is_none_or(|rs| rs.iter().all(|r| done.contains(r))));
1197            match next {
1198                Some(m) => {
1199                    done.insert(m.clone());
1200                    order.push(m.clone());
1201                }
1202                None => {
1203                    let left: Vec<&str> =
1204                        defined.iter().map(|(m, _)| m.as_str()).filter(|m| !done.contains(*m)).collect();
1205                    return Err(err(format!(
1206                        "{class}: methods read each other with this ({}): refused (16.3)",
1207                        left.join(", ")
1208                    )));
1209                }
1210            }
1211        }
1212        let mut defined: BTreeMap<String, datumesh_formula::definition::Definition> = defined.into_iter().collect();
1213        for m in order {
1214            let def = defined.remove(&m).ok_or_else(|| err(format!("{class}/{m}: not defined")))?;
1215            let fq = format!("{class}/{m}");
1216            self.sim.descriptors.insert(def.fn_hash.clone(), def.bytes.clone());
1217            self.ops.push(Op::Function {
1218                name: fq.clone(),
1219                start: start.to_string(),
1220                hash: def.fn_hash.clone(),
1221                bytes: def.bytes.clone(),
1222                bind: false,
1223            });
1224            self.formulas.push((n, fq, def.fn_hash.clone()));
1225            hashes.insert(m, def.fn_hash);
1226        }
1227        let methods: Vec<(String, Value)> = written
1228            .iter()
1229            .map(|(m, _)| (m.clone(), Value::String(hashes.get(m).cloned().unwrap_or_default())))
1230            .collect();
1231        let mut out = descriptor.clone();
1232        if let Value::Object(members) = &mut out {
1233            for (k, v) in members.iter_mut() {
1234                if k == "methods" {
1235                    *v = Value::Object(methods.clone());
1236                }
1237            }
1238        }
1239        Ok(out)
1240    }
1241
1242    /// `extends` of a function's catalogue entry (K9, the classes round): the class is bound, and the function takes its keys
1243    /// first, in class order, with their types (the extension-method rule of 16.3). Else refused.
1244    fn check_extension(&mut self, class: &str, fn_hash: &str) -> Result<(), String> {
1245        let chash = current_class(self.store, &self.sim, class)?
1246            .ok_or_else(|| format!("extends {class}: no class of that name is bound on this mesh"))?;
1247        let cbytes = match self.sim.class_bytes.get(&chash) {
1248            Some(b) => b.clone(),
1249            None => self
1250                .store
1251                .class(&chash)
1252                .map_err(|e| e.to_string())?
1253                .ok_or_else(|| format!("class {chash} is not stored"))?,
1254        };
1255        let cd = ClassDescriptor::from_json(&cbytes).map_err(|e| e.to_string())?;
1256        let fbytes = function_bytes_of(&mut self.reads, self.store, &self.sim, fn_hash)?
1257            .ok_or_else(|| format!("no descriptor {fn_hash}"))?;
1258        let fd = FunctionDescriptor::from_json(&fbytes).map_err(|e| e.to_string())?;
1259        let order = fd.order.clone().unwrap_or_default();
1260        let keys_match = order.len() >= cd.order.len()
1261            && order[..cd.order.len()] == cd.order[..]
1262            && cd.order.iter().all(|k| key_matches(&cd, &fd, k));
1263        if !keys_match {
1264            return Err(format!(
1265                "extends {class}: the function does not take the keys of {class} first, with their types"
1266            ));
1267        }
1268        Ok(())
1269    }
1270
1271    fn class_line(&mut self, n: usize, name: &str, v: &Value) -> Result<(), PublishError> {
1272        let err = |d: String| PublishError::at(n, d);
1273        let written = v.get("descriptor").ok_or_else(|| err("a class without descriptor".into()))?;
1274        let start = bound_of(v, n, self.ctx.now)?;
1275        let descriptor = &self.inline_methods(n, name, written, &start)?;
1276        let def = datumesh_formula::definition::define_class(
1277            name,
1278            &descriptor.to_jcs(),
1279            definer(name, self.ctx.host, self.ctx.owned),
1280            &self.callers(),
1281            &start,
1282        )
1283        .map_err(|e| err(format!("define {name}: {e}")))?;
1284        // put_class refuses under a suspended steward namespace, whether or not the name binds. A
1285        // namespace row is a host's (9.9), so the steward namespace's host is asked: a steward with
1286        // a path (datumesh.com/scripture) is not a host and Store::namespace refuses it.
1287        suspended(&mut self.reads, self.store, host_of(&def.descriptor.steward.namespace), n)?;
1288        let hash = def.class_hash.clone();
1289        let methods: Vec<(String, String)> =
1290            def.descriptor.methods.iter().map(|(m, fh)| (format!("{name}/{m}"), fh.clone())).collect();
1291        let bind = current_class(self.store, &self.sim, name).map_err(err)?.as_deref() != Some(hash.as_str());
1292        if bind {
1293            self.check_bind(n, name, &start, true)?;
1294            // bind_class binds every method in the same transaction (the store's rule).
1295            for (mname, _) in &methods {
1296                self.check_bind(n, mname, &start, false)?;
1297            }
1298            self.sim.classes.entry(name.to_string()).or_default().push((start.clone(), hash.clone()));
1299            for (mname, fh) in &methods {
1300                self.sim.functions.entry(mname.clone()).or_default().push((start.clone(), fh.clone()));
1301            }
1302        }
1303        self.sim.class_bytes.insert(hash.clone(), def.bytes.clone());
1304        self.ops.push(Op::Class { name: name.to_string(), start, hash, bytes: def.bytes, bind, methods });
1305        Ok(())
1306    }
1307
1308    /// One bind a line would make: rule A, the other kind, the namespace, and the latest binding.
1309    fn check_bind(&mut self, line: usize, name: &str, start: &str, class: bool) -> Result<(), PublishError> {
1310        if !self.backfill && start < self.ctx.now {
1311            return Err(PublishError::typed(
1312                line,
1313                PublishErrorKind::StartBeforeNow { name: name.into(), start: start.into(), now: self.ctx.now.into() },
1314            ));
1315        }
1316        let err = |d: String| PublishError::at(line, d);
1317        if bound_as_other(self.store, &self.sim, name, class).map_err(err)? {
1318            let kind = if class { "function" } else { "class" };
1319            return Err(err(format!("{name} is bound as a {kind}: one namespace of names")));
1320        }
1321        suspended(&mut self.reads, self.store, host_of(name), line)?;
1322        if let Some(latest) = latest_bind(self.store, &self.sim, name, class).map_err(err)? {
1323            if start <= latest.as_str() {
1324                return Err(err(format!("{name} is bound from {latest}: a bind at {start} is not later")));
1325            }
1326        }
1327        self.binds.push(Bind { line, name: name.into() });
1328        Ok(())
1329    }
1330
1331    /// Plans the cell lines of a chunk (CONTRACT-perf H1): each is prepared in file order up to its
1332    /// receipt; the receipts are signed on threads; the store is read once for the chunk; then each
1333    /// is checked in file order. The first failure is the chunk's, and a line that fails before
1334    /// signing is reported after the lines before it are checked.
1335    fn plan_cells(&mut self, lines: Vec<(usize, Value)>) -> Result<(), PublishError> {
1336        if lines.is_empty() {
1337            return Ok(());
1338        }
1339        let mut pending = Vec::with_capacity(lines.len());
1340        let mut failed = None;
1341        for (n, v) in &lines {
1342            match self.prepare_cell(*n, v) {
1343                Ok(p) => pending.push(p),
1344                Err(e) => {
1345                    failed = Some(e);
1346                    break;
1347                }
1348            }
1349        }
1350        let (key, host) = (self.key, self.ctx.host);
1351        let signed = parallel_owned(pending, |p| p.sign(key, host));
1352        let ids: Vec<&str> = signed.iter().flatten().map(|s| s.id.as_str()).collect();
1353        self.reads.prefetch_latest(self.store, &ids);
1354        let hashes: Vec<String> = signed
1355            .iter()
1356            .flatten()
1357            .filter(|s| !s.has_tx)
1358            .filter_map(|s| self.reads.latest_of.get(&s.id).cloned().flatten())
1359            .map(|(_, h)| h)
1360            .collect();
1361        let hashes: Vec<&str> = hashes.iter().map(String::as_str).collect();
1362        self.reads.prefetch_receipts(self.store, &hashes);
1363        for s in signed {
1364            self.check_cell(s?)?;
1365        }
1366        match failed {
1367            Some(e) => Err(e),
1368            None => Ok(()),
1369        }
1370    }
1371
1372    /// A cell line up to its receipt, as the checks of a line take them in order: the fields, the
1373    /// instants, the function as of `tx`, the descriptor, the arguments and the value (and its blob).
1374    fn prepare_cell(&mut self, n: usize, v: &Value) -> Result<Pending, PublishError> {
1375        let err = |d: String| PublishError::at(n, d);
1376        let cell_v = v.get("cell").ok_or_else(|| err("a cell without fn".into()))?;
1377        let name = cell_v.get("fn").and_then(Value::as_str).ok_or_else(|| err("a cell without fn".into()))?;
1378        let (ns, f) = name.rsplit_once('/').ok_or_else(|| err(format!("{name}: not a function name")))?;
1379        let field = |k: &str| v.get(k).and_then(Value::as_str).map(str::to_string);
1380        let required = |k: &str| field(k).ok_or_else(|| err(format!("no {k}")));
1381        let (licence, summary) = (required("licence")?, required("summary")?);
1382        // tx and asof default to the run's clock now, each on its own (H4).
1383        let asof = field("asof").unwrap_or_else(|| self.ctx.now.to_string());
1384        let has_tx = field("tx").is_some();
1385        let tx = field("tx").unwrap_or_else(|| self.ctx.now.to_string());
1386        if tx > asof {
1387            return Err(err(format!("tx {tx} is after asof {asof} (SPEC 8)")));
1388        }
1389        let issued = field("issued").unwrap_or_else(|| std::cmp::max(asof.clone(), self.ctx.key_from.to_string()));
1390        if asof > issued {
1391            return Err(err(format!("asof {asof} is after issued {issued} (SPEC 8)")));
1392        }
1393        let fn_hash = function_at(&mut self.reads, self.store, &self.sim, name, &tx)
1394            .map_err(err)?
1395            .ok_or_else(|| err(format!("{name} is not bound as of {tx}")))?;
1396        let d = function_bytes_of(&mut self.reads, self.store, &self.sim, &fn_hash)
1397            .map_err(err)?
1398            .ok_or_else(|| err(format!("no descriptor {fn_hash}")))?;
1399        let d = FunctionDescriptor::from_json(&d).map_err(|e| err(e.to_string()))?;
1400        let mut args = Args::new();
1401        for (k, a) in cell_v.get("args").and_then(Value::as_object).ok_or_else(|| err("a cell without args".into()))? {
1402            args.insert(k.clone(), Arg::Value(Scalar::from_json(&a.to_jcs()).map_err(|e| err(format!("{k}: {e}")))?));
1403        }
1404        // A label argument (`label_fold`, K8) is stored folded: a value that is not its own folding is refused.
1405        for (k, a) in &args {
1406            let rule = d.arg_extras.get(k).and_then(|x| x.key_normalisation);
1407            if let (true, Arg::Value(Scalar::String(text))) = (matches!(rule, Some(KeyNormalisation::LabelFold)), a) {
1408                if datumesh_core::fold_label(text) != *text {
1409                    return Err(err(format!("E_KEY_NORMALISATION: {k}: {text:?} is not folded (label_fold)")));
1410                }
1411            }
1412        }
1413        let valid: Args = args
1414            .iter()
1415            .filter(|(k, _)| d.signature.args.get(*k).is_some_and(|x| x.valid))
1416            .map(|(k, a)| (k.clone(), a.clone()))
1417            .collect();
1418        let source = match v.get("source") {
1419            Some(sv) => Some(source_of_line(sv).map_err(err)?),
1420            None => None,
1421        };
1422        // A withdrawal (R1, SPEC 8.1): `withdrawn` is the reason, in place of `value`; a line has one or the other.
1423        let withdrawn = match v.get("withdrawn") {
1424            None => None,
1425            Some(Value::String(reason)) => Some(reason.clone()),
1426            Some(_) => return Err(err("E_SCHEMA: withdrawn is a non-empty string: the reason".into())),
1427        };
1428        if withdrawn.is_some() && v.get("value").is_some() {
1429            return Err(err("E_SCHEMA: a cell line has withdrawn or value, not both".into()));
1430        }
1431        let (value, blob) = if withdrawn.is_some() {
1432            (None, None)
1433        } else {
1434            let value_v = v.get("value").ok_or_else(|| err("a cell without value".into()))?;
1435            let (scalar, blob) = match value_v.get("blob").and_then(Value::as_str) {
1436                Some(file) => {
1437                    let media = value_v.get("media_type").and_then(Value::as_str).unwrap_or("application/octet-stream");
1438                    let bytes = match self.ctx.blobs.get(file) {
1439                        Some(b) => b.clone(),
1440                        None => std::fs::read(self.ctx.base.join(file)).map_err(|e| err(format!("{file}: {e}")))?,
1441                    };
1442                    let sha = sha256_hex(&bytes);
1443                    let scalar = Scalar::from_lexical(Type::Blob, &format!("{sha}:{}:{media}", bytes.len()))
1444                        .map_err(|e| err(e.to_string()))?;
1445                    (scalar, Some(bytes))
1446                }
1447                None => (Scalar::from_json(&value_v.to_jcs()).map_err(|e| err(e.to_string()))?, None),
1448            };
1449            // A lookup returns an object's key, never the empty string (R1, D116 as amended: no withdrawal by "").
1450            if let Scalar::String(text) = &scalar {
1451                if text.is_empty() && lookup_method(self.store, &self.sim, name).map_err(err)? {
1452                    return Err(err(format!(
1453                        "E_KEY_NORMALISATION: {name} is a lookup, and its value is not the empty string"
1454                    )));
1455                }
1456            }
1457            (Some(scalar), blob)
1458        };
1459        let cell = Cell { ns: ns.to_string(), fn_name: f.to_string(), fn_hash, args };
1460        Ok(Pending {
1461            line: n,
1462            ns: ns.to_string(),
1463            cell,
1464            value,
1465            withdrawn,
1466            valid,
1467            tx,
1468            asof,
1469            issued,
1470            has_tx,
1471            licence,
1472            summary,
1473            blob,
1474            source,
1475        })
1476    }
1477
1478    /// The checks of a signed cell line, in file order: the skip rule of a line without `tx`, then
1479    /// the version rule. Its write is planned.
1480    fn check_cell(&mut self, s: Signed) -> Result<(), PublishError> {
1481        let line = s.line;
1482        let err = |d: String| PublishError::at(line, d);
1483        // A line without tx takes the run's clock, so a re-run at a later clock would sign the same
1484        // fact again as a new version. Re-running a file changes nothing: when the cell's latest
1485        // version is the store's and states the same thing (type, value, valid, licence, summary),
1486        // the line is skipped. A changed value is a new version, a correction.
1487        if !s.has_tx {
1488            if let Some((_, latest)) = cell_latest(&mut self.reads, self.store, &self.sim, &s.id).map_err(err)? {
1489                if let Some(old) = self.reads.receipt(self.store, &latest) {
1490                    let old = json::parse(&old).map_err(|e| err(e.to_string()))?;
1491                    let new = json::parse(&s.receipt).map_err(|e| err(e.to_string()))?;
1492                    if ["type", "value", "withdrawn", "valid", "licence", "summary"]
1493                        .iter()
1494                        .all(|k| old.get(k) == new.get(k))
1495                    {
1496                        return Ok(());
1497                    }
1498                }
1499            }
1500        }
1501        let version = match cell_latest(&mut self.reads, self.store, &self.sim, &s.id).map_err(err)? {
1502            Some((latest_tx, _)) if latest_tx.as_str() >= s.tx.as_str() => {
1503                if cell_version_asof(self.store, &self.sim, &s.id, &s.tx).map_err(err)?.as_deref()
1504                    != Some(s.hash.as_str())
1505                {
1506                    return Err(err(format!("{} has a version at or after {} that is not this receipt", s.id, s.tx)));
1507                }
1508                false
1509            }
1510            _ => {
1511                self.sim.versions.entry(s.id.clone()).or_default().push((s.tx.clone(), s.hash.clone()));
1512                true
1513            }
1514        };
1515        self.ops.push(Op::Cell { tx: s.tx, id: s.id, receipt: s.receipt, blob: s.blob, version });
1516        Ok(())
1517    }
1518}
1519
1520/// Whether `name` is the lookup method of its class (`<class>/<m>`, D93), as the class `name`'s prefix means now.
1521fn lookup_method<S: Store + ?Sized>(store: &S, sim: &Simulation, name: &str) -> Result<bool, String> {
1522    let Some((class, method)) = name.rsplit_once('/') else { return Ok(false) };
1523    let Some(hash) = current_class(store, sim, class)? else { return Ok(false) };
1524    let Some(bytes) = store.class(&hash).map_err(|e| e.to_string())? else { return Ok(false) };
1525    let cd = ClassDescriptor::from_json(&bytes).map_err(|e| e.to_string())?;
1526    Ok(cd.lookup.as_deref() == Some(method))
1527}
1528
1529/// The stored descriptor of a function line's signature.
1530fn stored_value(signature: &Value) -> Value {
1531    Value::Object(vec![
1532        ("code".into(), Value::Object(vec![("body".into(), s("")), ("lang".into(), s("stored"))])),
1533        ("inputs".into(), Value::Array(vec![])),
1534        ("signature".into(), signature.clone()),
1535    ])
1536}
1537
1538/// The backfill's checks (since 0.3.0 with store 0.4.2): no name the file binds has a binding, and
1539/// no namespace of one has any binding (`has_bindings_under`).
1540fn backfill_check<S: Store + ?Sized>(store: &S, binds: &[Bind]) -> Result<(), PublishError> {
1541    for b in binds {
1542        let refuse = |why: String| PublishError::typed(b.line, PublishErrorKind::Backfill(why));
1543        if store.resolve_binding(&b.name, END).map_err(|e| PublishError::at(b.line, e.to_string()))?.is_some() {
1544            return Err(refuse(format!("{} has a binding", b.name)));
1545        }
1546        let ns = namespace_of(&b.name);
1547        if store.has_bindings_under(ns).map_err(|e| PublishError::at(b.line, e.to_string()))? {
1548            return Err(refuse(format!("{ns} has bindings")));
1549        }
1550    }
1551    Ok(())
1552}
1553
1554/// Appends a run's line to the backfill log (created with mode 0600).
1555fn append_log(log: &Path, written: &Written) -> Result<(), String> {
1556    let line = Value::Object(vec![
1557        ("at".into(), s(&SystemClock.now())),
1558        ("namespaces".into(), Value::Array(written.namespaces.iter().map(|n| s(n)).collect())),
1559        ("starts".into(), Value::Array(written.starts.iter().map(|t| s(t)).collect())),
1560    ])
1561    .to_jcs();
1562    let mut opts = std::fs::OpenOptions::new();
1563    opts.create(true).append(true);
1564    #[cfg(unix)]
1565    {
1566        use std::os::unix::fs::OpenOptionsExt;
1567        opts.mode(0o600);
1568    }
1569    let mut f = opts.open(log).map_err(|e| format!("{}: {e}", log.display()))?;
1570    let mut bytes = line;
1571    bytes.push(b'\n');
1572    f.write_all(&bytes).map_err(|e| format!("{}: {e}", log.display()))
1573}
1574
1575/// Pass two: the writes the first pass planned, in order. Nothing here can refuse a planned
1576/// write, so a refused file has written nothing. Consecutive cell writes go in `put_cells` calls
1577/// of up to `CHUNK` on `lanes` lanes, their blobs put first (CONTRACT-perf H2, H5).
1578fn write<S: Store + ?Sized>(
1579    store: &S,
1580    ops: &[Op],
1581    cells: impl Fn(&S, &[Op], &mut Published) -> Result<(), String>,
1582) -> Result<(Published, Written), PublishError> {
1583    let mut out = Published::default();
1584    let mut written = Written::default();
1585    let err = |d: String| PublishError::at(0, d);
1586    let mut i = 0;
1587    while i < ops.len() {
1588        match &ops[i] {
1589            Op::Descriptor { hash, bytes, counted } => {
1590                let existed = store.descriptor(hash).is_some();
1591                store.put_descriptor(bytes).map_err(|e| err(e.to_string()))?;
1592                if *counted && !existed {
1593                    out.descriptors += 1;
1594                }
1595            }
1596            Op::Function { name, start, hash, bytes, bind } => {
1597                store.put_descriptor(bytes).map_err(|e| err(e.to_string()))?;
1598                if *bind {
1599                    store.bind_name(name, hash, start).map_err(|e| err(format!("bind {name}: {e}")))?;
1600                    out.functions += 1;
1601                    written.bound(name, start);
1602                }
1603            }
1604            Op::Class { name, start, hash, bytes, bind, methods } => {
1605                store.put_class(bytes).map_err(|e| err(e.to_string()))?;
1606                if *bind {
1607                    store.bind_class(name, hash, start).map_err(|e| err(format!("bind {name}: {e}")))?;
1608                    out.classes += 1;
1609                    written.bound(name, start);
1610                    for (m, _) in methods {
1611                        written.bound(m, start);
1612                    }
1613                }
1614            }
1615            Op::Close { name, at } => {
1616                store.close_binding(name, at).map_err(|e| err(format!("close {name}: {e}")))?;
1617            }
1618            Op::Catalog { entry, dictionaries, open_keys, extends, facets, source_name } => {
1619                crate::catalog::store_publisher(
1620                    store,
1621                    entry,
1622                    dictionaries,
1623                    open_keys,
1624                    extends.as_deref(),
1625                    facets,
1626                    source_name.as_deref(),
1627                )
1628                .map_err(err)?;
1629            }
1630            Op::Cell { .. } => {
1631                let mut j = i;
1632                while j < ops.len() && j - i < CHUNK && matches!(ops[j], Op::Cell { .. }) {
1633                    j += 1;
1634                }
1635                cells(store, &ops[i..j], &mut out).map_err(err)?;
1636                i = j;
1637                continue;
1638            }
1639        }
1640        i += 1;
1641    }
1642    Ok((out, written))
1643}
1644
1645/// A run of cell writes (up to `CHUNK`) on one lane: their blobs first, then the receipts and
1646/// versions in file order in `put_cells` calls of up to `CHUNK` (CONTRACT-perf H2). No `Sync`
1647/// bound: this is what [`publish_stored_with`] runs.
1648fn write_cells_one_lane<S: Store + ?Sized>(store: &S, group: &[Op], out: &mut Published) -> Result<(), String> {
1649    let items = put_blobs_and_items(store, group, out)?;
1650    let failed = AtomicBool::new(false);
1651    let ks: Vec<usize> = (0..items.len()).collect();
1652    if let Some((_, detail)) = put_lane(store, &items, &ks, &failed) {
1653        return Err(detail);
1654    }
1655    count_cells(group, &items, out);
1656    Ok(())
1657}
1658
1659/// A run of cell writes (up to `CHUNK`): their blobs first, then their receipts and versions on
1660/// `lanes` lanes (CONTRACT-perf H5). A cell's id picks its lane (its first hex digit, mod `lanes`),
1661/// so all writes of one cell share a lane, in file order. A lane's `put_cells` calls take up to
1662/// `CHUNK` of its items. When one fails, no lane starts another call, and the error returned is
1663/// that of the earliest failing item in file order. With one lane, as [`write_cells_one_lane`].
1664fn write_cells<S: Store + Sync + ?Sized>(
1665    store: &S,
1666    group: &[Op],
1667    lanes: usize,
1668    out: &mut Published,
1669) -> Result<(), String> {
1670    if lanes <= 1 {
1671        return write_cells_one_lane(store, group, out);
1672    }
1673    let items = put_blobs_and_items(store, group, out)?;
1674    let mut by_lane: Vec<Vec<usize>> = vec![Vec::new(); lanes];
1675    for (k, op) in group.iter().enumerate() {
1676        if let Op::Cell { id, .. } = op {
1677            by_lane[lane_of(id, lanes)].push(k);
1678        }
1679    }
1680    let failed = AtomicBool::new(false);
1681    let failures: Vec<(usize, String)> = std::thread::scope(|scope| {
1682        let handles: Vec<_> = by_lane
1683            .iter()
1684            .map(|ks| {
1685                let (items, failed) = (&items, &failed);
1686                scope.spawn(move || put_lane(store, items, ks, failed))
1687            })
1688            .collect();
1689        handles.into_iter().filter_map(|h| h.join().unwrap_or_else(|p| std::panic::resume_unwind(p))).collect()
1690    });
1691    if let Some((_, detail)) = failures.into_iter().min_by_key(|(k, _)| *k) {
1692        return Err(detail);
1693    }
1694    count_cells(group, &items, out);
1695    Ok(())
1696}
1697
1698/// The blobs of a run, put in order (counted in `out`), and the run's cell writes.
1699fn put_blobs_and_items<'a, S: Store + ?Sized>(
1700    store: &S,
1701    group: &'a [Op],
1702    out: &mut Published,
1703) -> Result<Vec<CellItem<'a>>, String> {
1704    for op in group {
1705        if let Op::Cell { blob: Some(bytes), .. } = op {
1706            store.put_blob(bytes).map_err(|e| e.to_string())?;
1707            out.blobs += 1;
1708            out.blob_bytes += bytes.len() as u64;
1709        }
1710    }
1711    Ok(group
1712        .iter()
1713        .filter_map(|op| match op {
1714            Op::Cell { tx, id, receipt, version, .. } => {
1715                Some((receipt.as_slice(), if *version { Some((id.as_str(), tx.as_str())) } else { None }))
1716            }
1717            _ => None,
1718        })
1719        .collect())
1720}
1721
1722/// Counts a written run of cells in `out`.
1723fn count_cells(group: &[Op], items: &[CellItem<'_>], out: &mut Published) {
1724    out.cells += group.len();
1725    out.receipts += group.len();
1726    out.versions += items.iter().filter(|(_, v)| v.is_some()).count();
1727}
1728
1729/// The lane of a cell id: its first hex digit, mod `lanes` (CONTRACT-perf H5).
1730fn lane_of(id: &str, lanes: usize) -> usize {
1731    id.bytes().next().and_then(|b| (b as char).to_digit(16)).unwrap_or(0) as usize % lanes
1732}
1733
1734/// A cell write of a run: its receipt's bytes and its version (cell id, tx), if any.
1735type CellItem<'a> = (&'a [u8], Option<(&'a str, &'a str)>);
1736
1737/// One lane's writes: its items (indices into `items`, in file order) in `put_cells` calls of up to
1738/// `CHUNK`. Returns the index of the first item of the call that failed, and its error. No call
1739/// starts once `failed` is set.
1740fn put_lane<S: Store + ?Sized>(
1741    store: &S,
1742    items: &[CellItem<'_>],
1743    ks: &[usize],
1744    failed: &AtomicBool,
1745) -> Option<(usize, String)> {
1746    for call in ks.chunks(CHUNK) {
1747        if failed.load(Ordering::SeqCst) {
1748            return None;
1749        }
1750        let writes: Vec<CellWrite<'_>> = call.iter().map(|&k| CellWrite::new(items[k].0, items[k].1)).collect();
1751        if let Err(e) = store.put_cells(&writes) {
1752            failed.store(true, Ordering::SeqCst);
1753            return Some((call[0], e.to_string()));
1754        }
1755    }
1756    None
1757}
1758
1759/// The receipt JSON of a signed receipt: its payload's members and `sig`.
1760pub fn receipt_json(r: &datumesh_core::Receipt) -> Vec<u8> {
1761    let mut members = vec![("sig".to_string(), Value::String(r.sig().to_string()))];
1762    if let Ok(Value::Object(m)) = json::parse(r.payload()) {
1763        members.extend(m);
1764    }
1765    Value::Object(members).to_jcs()
1766}
1767
1768/// Publishes the file at `path` into `store` as the mesh `host` signing with `key` (see the
1769/// module documentation). The mesh's own namespaces are `host` alone: see [`publish_stored_in`].
1770/// The clock is the system clock, and there is no backfill. The cells are written on one lane;
1771/// see [`publish_stored_lanes`] for the parallel lanes.
1772pub fn publish_stored<S: Store + ?Sized>(
1773    store: &S,
1774    key: &SigningKey,
1775    host: &str,
1776    path: &Path,
1777) -> Result<Published, PublishError> {
1778    publish_stored_in(store, key, host, &[host.to_string()], path)
1779}
1780
1781/// As [`publish_stored`], for a mesh that owns the namespaces (hosts) `owned` (`Config::namespaces`):
1782/// a class line is accepted for a class under one of them, and refused with `E_CLASS_OWNER` (in the
1783/// [`PublishError::detail`]) under any other. Since 0.2.2. The system clock, and no backfill.
1784pub fn publish_stored_in<S: Store + ?Sized>(
1785    store: &S,
1786    key: &SigningKey,
1787    host: &str,
1788    owned: &[String],
1789    path: &Path,
1790) -> Result<Published, PublishError> {
1791    publish_stored_with(store, key, host, owned, path, &PublishOptions::system())
1792}
1793
1794/// As [`publish_stored_in`], with the run's clock and backfill (CONTRACT-1.8b H1, rule A). The
1795/// cells are written in file order on one lane, as in 0.3.2 (CONTRACT-perf H2).
1796///
1797/// Errors: a line refused by its checks, or a binding whose start is earlier than the clock
1798/// ([`PublishErrorKind::StartBeforeNow`]), or a backfill refused ([`PublishErrorKind::Backfill`]).
1799/// Nothing is written when the first pass refuses (CONTRACT-1.7a H2).
1800pub fn publish_stored_with<S: Store + ?Sized>(
1801    store: &S,
1802    key: &SigningKey,
1803    host: &str,
1804    owned: &[String],
1805    path: &Path,
1806    opts: &PublishOptions,
1807) -> Result<Published, PublishError> {
1808    publish_planned(store, key, host, owned, path, opts, false, |s, ops| {
1809        write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
1810    })
1811}
1812
1813/// As [`publish_stored_with`], with the public rule (Build 2 Part 3, D8: datumesh-http always
1814/// enforces it; `publish-stored` calls this). A file that defines a computed function (formula)
1815/// is refused unless the tests of the function (the file's, and those already held for the same
1816/// function hash) exercise every derived edge case and every branch, and all of the file's tests
1817/// pass: [`PublishErrorKind::TestsMissing`] at the function's line, [`PublishErrorKind::TestsFailing`]
1818/// at the failing test's line. Stored functions are exempt. Nothing is written when refused.
1819pub fn publish_stored_checked<S: Store + ?Sized>(
1820    store: &S,
1821    key: &SigningKey,
1822    host: &str,
1823    owned: &[String],
1824    path: &Path,
1825    opts: &PublishOptions,
1826) -> Result<Published, PublishError> {
1827    publish_planned(store, key, host, owned, path, opts, true, |s, ops| {
1828        write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
1829    })
1830}
1831
1832/// As [`publish_stored_with`], with the cells written on parallel lanes (CONTRACT-perf H5, H6):
1833/// `DATUMESH_PUBLISH_LANES` (a positive integer) if set, else `min(4, available_parallelism())`.
1834/// The same receipts, versions and rows as one lane; only the order of the inserts across
1835/// different cells differs. The variable is read once per run, before the file is read.
1836pub fn publish_stored_lanes<S: Store + Sync + ?Sized>(
1837    store: &S,
1838    key: &SigningKey,
1839    host: &str,
1840    owned: &[String],
1841    path: &Path,
1842    opts: &PublishOptions,
1843) -> Result<Published, PublishError> {
1844    let lanes = publish_lanes()?;
1845    publish_planned(store, key, host, owned, path, opts, false, |s, ops| {
1846        write(s, ops, |s, g, out| write_cells(s, g, lanes, out))
1847    })
1848}
1849
1850/// The planned writes of a run as the tests see them (see [`Overlay`]).
1851fn overlay_of(ops: &[Op]) -> Result<Overlay, PublishError> {
1852    let mut overlay = Overlay::default();
1853    for op in ops {
1854        match op {
1855            Op::Function { name, start, hash, bytes, bind } => {
1856                overlay.descriptors.insert(hash.clone(), bytes.clone());
1857                if *bind {
1858                    overlay.functions.entry(name.clone()).or_default().push((start.clone(), hash.clone()));
1859                }
1860            }
1861            Op::Descriptor { hash, bytes, .. } => {
1862                overlay.descriptors.insert(hash.clone(), bytes.clone());
1863            }
1864            Op::Cell { receipt, .. } => {
1865                overlay.cell(receipt).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
1866            }
1867            Op::Class { start, bind, methods, .. } => {
1868                // the methods a class binds with it, as the store binds them (bind_class)
1869                if *bind {
1870                    for (m, fh) in methods {
1871                        overlay.functions.entry(m.clone()).or_default().push((start.clone(), fh.clone()));
1872                    }
1873                }
1874            }
1875            Op::Catalog { .. } | Op::Close { .. } => {}
1876        }
1877    }
1878    Ok(overlay)
1879}
1880
1881/// The tests of a file, run over the store and the file's planned writes (Build 2 Part 3, E5;
1882/// CONTRACT-build2-part5 F2). For a computed function the file defines (`formulas`), the public rule:
1883/// `checked` refuses the file when a test fails or the tests leave a derived case or a branch arm
1884/// unexercised. For a stored function, the tests of the file are run and stored with their results
1885/// (a cell that is not stored is `error`), and the file is never refused for them (spec 7.2: a stored
1886/// function's tests are source-conformance tests). Returns the rows of the tests to hold (the file's
1887/// and the held ones of those functions).
1888#[allow(clippy::too_many_arguments)]
1889pub(crate) fn check_tests<S: Store + ?Sized>(
1890    store: &S,
1891    overlay: &Overlay,
1892    tests: &[(usize, TestSpec)],
1893    formulas: &[(usize, String, String)],
1894    host: &str,
1895    now: &str,
1896    checked: bool,
1897) -> Result<Vec<RowWrite>, PublishError> {
1898    let mut file_tests: Vec<(usize, TestSpec, String)> = Vec::new();
1899    for (n, spec) in tests {
1900        let at = spec.asof.clone().unwrap_or_else(|| now.to_string());
1901        match testrun::binding_of(store, overlay, &spec.function, &at) {
1902            Ok(Some((hash, _))) => file_tests.push((*n, spec.clone(), hash)),
1903            Ok(None) => {
1904                return Err(PublishError::at(
1905                    *n,
1906                    format!("a test of {}: no function of that name is bound", spec.function),
1907                ))
1908            }
1909            Err(e) => return Err(PublishError::at(*n, e)),
1910        }
1911    }
1912    // The functions to run: the file's computed functions, then the stored functions of its tests.
1913    let mut groups: Vec<(usize, String, String)> = formulas.to_vec();
1914    for (n, spec, hash) in &file_tests {
1915        if !groups.iter().any(|g| &g.2 == hash) {
1916            groups.push((*n, spec.function.clone(), hash.clone()));
1917        }
1918    }
1919    let mut rows = Vec::new();
1920    for (line, name, hash) in &groups {
1921        let own: Vec<(usize, TestSpec)> =
1922            file_tests.iter().filter(|t| &t.2 == hash).map(|t| (t.0, t.1.clone())).collect();
1923        // The held tests of this function, read once (as 0.4.8 read them, before the function is built).
1924        let all_held = testrun::held_of_name(store, hash, name, now).map_err(|e| PublishError::at(*line, e))?;
1925        if !checked && own.is_empty() && all_held.is_empty() {
1926            continue;
1927        }
1928        let mut run = testrun::Run::new(store, overlay, now);
1929        let built = run.built(name, hash).map_err(|e| PublishError::at(*line, format!("{name}: {}", e.0)))?;
1930        // A computed function this file does not define keeps its behaviour: its tests are neither
1931        // checked nor stored here (as before stored functions' tests were held).
1932        if built.compiled.is_some() && !formulas.iter().any(|f| &f.2 == hash) {
1933            continue;
1934        }
1935        // A computed function's held tests are all run (its coverage is of all of them); a stored function's
1936        // only where they read a cell this file writes (CONTRACT-0.4.9 H6).
1937        let written: BTreeSet<&str> = overlay.cells.iter().filter(|c| &c.name == name).map(|c| c.id.as_str()).collect();
1938        let held: Vec<(FunctionTest, TestSpec, String)> = all_held
1939            .into_iter()
1940            .filter(|(_, _, cell)| built.compiled.is_some() || written.contains(cell.as_str()))
1941            .collect();
1942        let mut specs: Vec<(Option<usize>, TestSpec)> = own.into_iter().map(|(n, s)| (Some(n), s)).collect();
1943        for (_, spec, _) in held {
1944            if !specs.iter().any(|(_, s)| s.case == spec.case) {
1945                specs.push((None, spec));
1946            }
1947        }
1948        let ran: Vec<Ran> = specs.iter().map(|(_, s)| run_test(store, overlay, now, s)).collect();
1949        let Some(compiled) = built.compiled.as_ref() else {
1950            // A stored function: its tests are stored and counted; it has no branch arms, and its failing tests are
1951            // counterexamples, never a refusal (stored functions stay exempt from the public rule).
1952            for ((own_n, spec), r) in specs.iter().zip(&ran) {
1953                let (result, detail) = testrun::result_of(spec, r);
1954                rows.push(RowWrite {
1955                    fn_hash: hash.clone(),
1956                    case: spec.case.clone(),
1957                    jcs: spec.jcs.clone(),
1958                    signed_by: host.to_string(),
1959                    result,
1960                    detail,
1961                    branches_total: 0,
1962                    branches_covered: 0,
1963                    fn_name: row_name(*own_n, spec, name),
1964                });
1965            }
1966            continue;
1967        };
1968        if checked {
1969            let mut failing: Vec<(usize, String)> = Vec::new();
1970            for ((n, spec), r) in specs.iter().zip(&ran) {
1971                if let Some(n) = n {
1972                    let (result, detail) = testrun::result_of(spec, r);
1973                    if result != "pass" {
1974                        failing.push((*n, format!("{name}: test {} {detail}", spec.case)));
1975                    }
1976                }
1977            }
1978            failing.sort_by_key(|f| f.0);
1979            if let Some((n, detail)) = failing.into_iter().next() {
1980                return Err(PublishError::typed(n, PublishErrorKind::TestsFailing(detail)));
1981            }
1982            let refs: Vec<&Ran> = ran.iter().collect();
1983            let cov = testrun::coverage_of(compiled, &built.function.signature, &refs);
1984            if !cov.uncovered.is_empty() || !cov.unexercised.is_empty() {
1985                let mut text = format!("{name} is missing tests:");
1986                if !cov.uncovered.is_empty() {
1987                    let cases: Vec<&str> = cov.uncovered.iter().map(|c| c.0.as_str()).collect();
1988                    text += &format!(" uncovered cases {};", cases.join(", "));
1989                }
1990                if !cov.unexercised.is_empty() {
1991                    text += &format!(" unexercised branches {}", cov.unexercised.join(", "));
1992                }
1993                return Err(PublishError::typed(
1994                    *line,
1995                    PublishErrorKind::TestsMissing(text.trim_end_matches(';').to_string()),
1996                ));
1997            }
1998        }
1999        let refs: Vec<&Ran> = ran.iter().collect();
2000        let cov = testrun::coverage_of(compiled, &built.function.signature, &refs);
2001        for ((own_n, spec), r) in specs.iter().zip(&ran) {
2002            let (result, detail) = testrun::result_of(spec, r);
2003            rows.push(RowWrite {
2004                fn_hash: hash.clone(),
2005                case: spec.case.clone(),
2006                jcs: spec.jcs.clone(),
2007                signed_by: host.to_string(),
2008                result,
2009                detail,
2010                branches_total: cov.branches,
2011                branches_covered: cov.covered,
2012                fn_name: row_name(*own_n, spec, name),
2013            });
2014        }
2015    }
2016    Ok(rows)
2017}
2018
2019/// As [`publish_stored_lanes`], with the public rule (see [`publish_stored_checked`]): the path of
2020/// `datumesh-mesh publish-stored` (D8).
2021pub fn publish_stored_checked_lanes<S: Store + Sync + ?Sized>(
2022    store: &S,
2023    key: &SigningKey,
2024    host: &str,
2025    owned: &[String],
2026    path: &Path,
2027    opts: &PublishOptions,
2028) -> Result<Published, PublishError> {
2029    let lanes = publish_lanes()?;
2030    publish_planned(store, key, host, owned, path, opts, true, |s, ops| {
2031        write(s, ops, |s, g, out| write_cells(s, g, lanes, out))
2032    })
2033}
2034
2035/// The first pass (the planner) and the second pass (`write_ops`) of a publish of a file.
2036#[allow(clippy::too_many_arguments)]
2037fn publish_planned<S: Store + ?Sized>(
2038    store: &S,
2039    key: &SigningKey,
2040    host: &str,
2041    owned: &[String],
2042    path: &Path,
2043    opts: &PublishOptions,
2044    checked: bool,
2045    write_ops: impl FnOnce(&S, &[Op]) -> Result<(Published, Written), PublishError>,
2046) -> Result<Published, PublishError> {
2047    let lines = read_lines(path)?;
2048    let base = path.parent().unwrap_or(Path::new("."));
2049    planned_lines(store, key, host, owned, lines, base, &BTreeMap::new(), false, opts, checked, write_ops)
2050}
2051
2052/// The catalogue job's run (C5, `catalog_build`): the lines it writes, with its blobs in memory, as one publish with the
2053/// job flag (C1). Stored cells, the public rule as checked by [`publish_stored_with`].
2054pub(crate) fn publish_job<S: Store + ?Sized>(
2055    store: &S,
2056    key: &SigningKey,
2057    host: &str,
2058    owned: &[String],
2059    lines: Vec<String>,
2060    blobs: &BTreeMap<String, Vec<u8>>,
2061    opts: &PublishOptions,
2062) -> Result<Published, PublishError> {
2063    let numbered: Vec<(usize, String)> = lines.into_iter().enumerate().map(|(i, l)| (i + 1, l)).collect();
2064    planned_lines(store, key, host, owned, numbered, Path::new("."), blobs, true, opts, false, |s, ops| {
2065        write(s, ops, |s, g, out| write_cells_one_lane(s, g, out))
2066    })
2067}
2068
2069/// The planning and writing of numbered lines (see [`publish_planned`]).
2070#[allow(clippy::too_many_arguments)]
2071fn planned_lines<S: Store + ?Sized>(
2072    store: &S,
2073    key: &SigningKey,
2074    host: &str,
2075    owned: &[String],
2076    lines: Vec<(usize, String)>,
2077    base: &Path,
2078    blobs: &BTreeMap<String, Vec<u8>>,
2079    job: bool,
2080    opts: &PublishOptions,
2081    checked: bool,
2082    write_ops: impl FnOnce(&S, &[Op]) -> Result<(Published, Written), PublishError>,
2083) -> Result<Published, PublishError> {
2084    // The key's start: the earliest `issued`.
2085    let key_from = store
2086        .namespace(host)
2087        .ok()
2088        .flatten()
2089        .and_then(|n| json::parse(&n.keydoc).ok())
2090        .and_then(|d| match d.get("keys") {
2091            Some(Value::Array(ks)) => ks
2092                .iter()
2093                .find(|k| k.get("id").and_then(Value::as_str) == Some(key.key_id()))
2094                .and_then(|k| k.get("valid_from").and_then(Value::as_str).map(str::to_string)),
2095            _ => None,
2096        })
2097        .ok_or_else(|| {
2098            PublishError::at(0, format!("the key {} is not in {host}'s key document in the store", key.key_id()))
2099        })?;
2100    let now = opts.clock.now();
2101    let ctx = Ctx { host, owned, key_from: &key_from, now: &now, base, job, blobs };
2102    let mut planner = Planner {
2103        store,
2104        key,
2105        ctx,
2106        backfill: opts.backfill.is_some(),
2107        sim: Simulation::default(),
2108        reads: Reads::default(),
2109        ops: Vec::new(),
2110        binds: Vec::new(),
2111        tests: Vec::new(),
2112        formulas: Vec::new(),
2113    };
2114    planner.run(&lines)?;
2115    let Planner { ops, binds, tests, formulas, .. } = planner;
2116    if opts.backfill.is_some() {
2117        backfill_check(store, &binds)?;
2118    }
2119    // The tests of the file's computed functions, run over the store and the file's own writes:
2120    // refused before anything is written (Build 2 Part 3, D8).
2121    let overlay = overlay_of(&ops)?;
2122    let rows = check_tests(store, &overlay, &tests, &formulas, host, &now, checked)?;
2123    let (out, written) = write_ops(store, &ops)?;
2124    index_cell_values(store, &ops).map_err(|e| PublishError::at(0, format!("catalogue: {e}")))?;
2125    testrun::apply_rows(store, &rows, &now).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2126    let rebound: Vec<String> = ops
2127        .iter()
2128        .filter_map(|op| match op {
2129            Op::Function { name, bind: true, .. } => Some(name.clone()),
2130            _ => None,
2131        })
2132        .collect();
2133    testrun::rerun_readers(store, &rebound, &now).map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2134    // The stored functions' tests read the cells this file writes, and the names it rebinds.
2135    let rebound: BTreeSet<String> = rebound.into_iter().collect();
2136    let written_cells: Vec<(String, String)> = overlay.cells.iter().map(|c| (c.name.clone(), c.id.clone())).collect();
2137    testrun::rerun_stored_tests(store, &rebound, &written_cells, &now)
2138        .map_err(|e| PublishError::at(0, format!("tests: {e}")))?;
2139    if let Some(log) = &opts.backfill {
2140        if out.functions + out.classes + out.versions > 0 {
2141            append_log(log, &written).map_err(|e| PublishError::at(0, format!("backfill log: {e}")))?;
2142        }
2143    }
2144    Ok(out)
2145}