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