Skip to main content

datumesh_http/
publish.rs

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