Skip to main content

datumesh_store/
pg.rs

1//! `PgStore`: the store on PostgreSQL.
2
3use std::borrow::Cow;
4use std::collections::{HashMap, HashSet};
5
6use crate::catalogue::{
7    args_json, as_i64, canonical_examples, check_catalog_entry, check_key_values, check_model, entry_fields,
8    entry_from_columns, entry_text, invalid, miss_text, rank, value_text, vector_literal, Words, SUMMARY_VALUES,
9};
10use crate::error::{Db, Error, Result};
11use crate::pg_unstable::Connector;
12use crate::pool::{Conn, Pool, PoolOptions, Pooled};
13use crate::slices::{check_entry, cmp_keys, is_hash, is_instant, version_slice, Constraint, Kind, Pattern};
14use crate::sql::Q;
15use crate::{
16    not_canonical_class, Binding, CatalogEntry, CatalogKind, CellWrite, ClassBinding, Dictionary, DictionaryValue,
17    EmbedRef, Embedding, FunctionTest, Hit, KeyValue, Namespace, PendingEmbedding, SliceMember, SliceValue, Store,
18    Summary, SummaryEntry, TestSummary, Version, FIND_MISSES_CAP,
19};
20use datumesh_core::lexical::{check_dns_name, check_function_name, check_hex, check_instant};
21use datumesh_core::{
22    json, keys_from_response, sha256_hex, verify, Cell, ClassDescriptor, ErrorCode, FunctionDescriptor, Keys, Manifest,
23    Receipt, Resolver, Scalar, Slice, Type,
24};
25
26/// The store on PostgreSQL, with a connection pool. `Send + Sync`: share one per process
27/// (behind an `Arc`); each call checks a connection out for its duration.
28///
29/// Every `put_*` is one transaction. [`Store`] methods return errors: a malformed argument
30/// is [`Error::Invalid`] (no query is made), a database failure [`Error::Database`]. The
31/// [`Resolver`] methods answer both with `None`; a database failure is logged with
32/// `tracing` (target `datumesh_store`, level `error`).
33pub struct PgStore {
34    pool: Pool,
35    /// Whether the `embeddings` table exists (the `vector` extension was available when the
36    /// schema was migrated), looked at when the store was opened.
37    vectors: bool,
38}
39
40impl std::fmt::Debug for PgStore {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("PgStore").finish_non_exhaustive()
43    }
44}
45
46impl PgStore {
47    /// Connects to a `postgres://` URL or `key=value` connection string with the default
48    /// [`PoolOptions`]: [`connect_with(url, PoolOptions::new())`](Self::connect_with).
49    pub fn connect(url: &str) -> Result<PgStore> {
50        PgStore::connect_with(url, PoolOptions::new())
51    }
52
53    /// Connects to a `postgres://` URL or `key=value` connection string, with a pool and TLS
54    /// roots as `options` say. One connection is opened at once, so a wrong URL, an
55    /// unreachable server or a refused certificate fails here; nothing else is done on it
56    /// (no statement is prepared, the schema is not looked at), so an empty database is fine
57    /// (create the schema with [`migrate::apply`](crate::migrate::apply)).
58    ///
59    /// TLS (rustls) is used as the URL's `sslmode` says: `disable` never, `prefer` (the
60    /// default) when the server offers it, `require` always. Whenever it is used, the
61    /// server's certificate and host name are verified, against the Mozilla roots plus the
62    /// roots added with [`PoolOptions::tls_root_certificates_pem`]; there is no way to
63    /// accept any certificate. So a server with `ssl=on` and a self-signed certificate (or
64    /// one from a private CA) fails even under the default `prefer`: add its CA, or connect
65    /// with `sslmode=disable`.
66    pub fn connect_with(url: &str, options: PoolOptions) -> Result<PgStore> {
67        let config = url.parse::<postgres::Config>().db()?;
68        let connector = Connector::new(config, &options)?;
69        PgStore::from_pool(Pool::new(Box::new(move || connector.connect()), options))
70    }
71
72    /// A store on `pool`, after opening one connection.
73    pub(crate) fn from_pool(pool: Pool) -> Result<PgStore> {
74        let mut store = PgStore { pool, vectors: false };
75        let vectors: bool = {
76            let mut c = store.pool.get()?;
77            c.client.query_one("SELECT to_regclass('embeddings') IS NOT NULL", &[]).db()?.try_get(0).db()?
78        };
79        store.vectors = vectors;
80        Ok(store)
81    }
82
83    /// `Ok` where vectors are stored and searched; otherwise [`Error::Unsupported`].
84    fn vectors_or_unsupported(&self) -> Result<()> {
85        if self.vectors {
86            Ok(())
87        } else {
88            Err(Error::Unsupported("vectors need PostgreSQL with the vector extension (migration 9)".into()))
89        }
90    }
91
92    /// A pooled connection, held until dropped (migrations hold one throughout).
93    pub(crate) fn conn(&self) -> Result<Pooled<'_>> {
94        self.pool.get()
95    }
96
97    /// Prepares every SQL statement the store uses against the live schema, on a fresh
98    /// connection's behalf (no cached statement is reused), and returns how many there are.
99    /// Fails with the first statement the schema cannot serve.
100    pub fn check_statements(&self) -> Result<usize> {
101        let mut c = self.pool.get()?;
102        for q in Q::ALL {
103            c.client.prepare_typed(q.sql(), q.types()).db()?;
104        }
105        Ok(Q::ALL.len())
106    }
107
108    /// A [`Resolver`] lookup: a failure (logged by `run`) becomes `None`.
109    fn resolve<T>(&self, op: &'static str, f: impl FnOnce(&mut Conn) -> Result<Option<T>>) -> Option<T> {
110        self.run(op, f).ok().flatten()
111    }
112
113    /// Runs `f` on a pooled connection; a database or pool failure is logged.
114    fn run<T>(&self, op: &'static str, f: impl FnOnce(&mut Conn) -> Result<T>) -> Result<T> {
115        let result = self.pool.get().and_then(|mut c| f(&mut c));
116        if let Err(e @ (Error::Database(_) | Error::PoolTimeout)) = &result {
117            tracing::error!(target: "datumesh_store", op, error = %e, "database failure");
118        }
119        result
120    }
121
122    /// Versions from rows of (tx, receipt_hash, asof).
123    fn version_rows(rows: &[postgres::Row], cell_id: &str) -> Result<Vec<Version>> {
124        rows.iter().map(|r| version_row(r, cell_id)).collect()
125    }
126
127    /// A version (and its receipt's bytes) from a query answering
128    /// (tx, receipt_hash, asof, bytes) for (cell_id, asof).
129    fn asof_with_receipt(
130        &self,
131        op: &'static str,
132        q: Q,
133        cell_id: &str,
134        asof: &str,
135    ) -> Result<Option<(Version, Vec<u8>)>> {
136        check_hex(cell_id, 64, "cell_id")?;
137        check_instant(asof, "asof")?;
138        self.run(op, |c| {
139            let st = c.stmt(q)?;
140            let Some(row) = c.client.query_opt(&st, &[&cell_id, &asof]).db()? else { return Ok(None) };
141            Ok(Some((version_row(&row, cell_id)?, row.try_get(3).db()?)))
142        })
143    }
144
145    /// A version from a query answering (tx, receipt_hash, asof) for (cell_id, asof).
146    fn asof_version(&self, op: &'static str, q: Q, cell_id: &str, asof: &str) -> Result<Option<Version>> {
147        check_hex(cell_id, 64, "cell_id")?;
148        check_instant(asof, "asof")?;
149        self.run(op, |c| {
150            let st = c.stmt(q)?;
151            let rows = c.client.query(&st, &[&cell_id, &asof]).db()?;
152            Ok(PgStore::version_rows(&rows, cell_id)?.pop())
153        })
154    }
155}
156
157fn version_row(r: &postgres::Row, cell_id: &str) -> Result<Version> {
158    Ok(Version {
159        cell_id: cell_id.to_string(),
160        tx: r.try_get(0).db()?,
161        receipt_hash: r.try_get(1).db()?,
162        asof: r.try_get(2).db()?,
163    })
164}
165
166/// A member from a row of (tx, receipt_hash, asof, bytes, ...).
167fn member_row(r: &postgres::Row, cell_id: &str) -> Result<SliceMember> {
168    Ok(SliceMember { version: version_row(r, cell_id)?, receipt: r.try_get(3).db()? })
169}
170
171/// A cell's arguments from the "name:type:value" items of the typed-argument index
172/// (`cell_args` holds every argument's type and lexical form).
173fn cell_args(items: Vec<String>) -> Result<datumesh_core::Args> {
174    let bad =
175        |what: &str| Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")));
176    let mut args = datumesh_core::Args::new();
177    for a in items {
178        let mut parts = a.splitn(3, ':');
179        let (Some(name), Some(t), Some(v)) = (parts.next(), parts.next(), parts.next()) else {
180            return Err(bad("argument"));
181        };
182        let ty = Type::from_name(t).ok_or_else(|| bad("type"))?;
183        args.insert(name.to_string(), datumesh_core::Arg::Value(Scalar::from_lexical(ty, v)?));
184    }
185    Ok(args)
186}
187
188/// A member's value and cell from a row of (tx, receipt_hash, asof, value_type, value, ns,
189/// fn, fn_hash, "name:type:value" of each argument, ...): the cell is rebuilt from the
190/// typed-argument index.
191fn value_row(r: &postgres::Row, cell_id: &str) -> Result<SliceValue> {
192    let bad =
193        |what: &str| Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")));
194    let (ty, value): (String, String) = (r.try_get(3).db()?, r.try_get(4).db()?);
195    let ty = Type::from_name(&ty).ok_or_else(|| bad("type"))?;
196    let args = cell_args(r.try_get::<_, Vec<String>>(8).db()?)?;
197    let cell = Cell { args, fn_hash: r.try_get(7).db()?, fn_name: r.try_get(6).db()?, ns: r.try_get(5).db()? };
198    Ok(SliceValue { version: version_row(r, cell_id)?, value: Scalar::from_lexical(ty, &value)?, cell })
199}
200
201/// A cell from a row of (ns, fn, fn_hash, "name:type:value" of each argument).
202fn cell_row(r: &postgres::Row) -> Result<Cell> {
203    Ok(Cell {
204        args: cell_args(r.try_get::<_, Vec<String>>(3).db()?)?,
205        fn_hash: r.try_get(2).db()?,
206        fn_name: r.try_get(1).db()?,
207        ns: r.try_get(0).db()?,
208    })
209}
210
211fn get_bytes(c: &mut Conn, q: Q, key: &str) -> Result<Option<Vec<u8>>> {
212    let st = c.stmt(q)?;
213    let row = c.client.query_opt(&st, &[&key]).db()?;
214    Ok(match row {
215        Some(r) => Some(r.try_get(0).db()?),
216        None => None,
217    })
218}
219
220fn get_strings(c: &mut Conn, q: Q, key: &str) -> Result<Vec<String>> {
221    let st = c.stmt(q)?;
222    let rows = c.client.query(&st, &[&key]).db()?;
223    rows.iter().map(|r| r.try_get(0).db()).collect()
224}
225
226impl Resolver for PgStore {
227    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
228        if !is_hash(fn_hash) {
229            return None;
230        }
231        self.resolve("descriptor", |c| get_bytes(c, Q::DescriptorGet, fn_hash)).map(Cow::Owned)
232    }
233
234    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
235        if !is_hash(hash) {
236            return None;
237        }
238        self.resolve("receipt", |c| get_bytes(c, Q::ReceiptGet, hash)).map(Cow::Owned)
239    }
240
241    /// The stored manifest of slice entry `entry` ([`Store::put_manifest`]), its canonical
242    /// form; `None` when there is none, or `entry` is not an entry (since 0.3.1).
243    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
244        if check_entry(entry, "$").is_err() {
245            return None;
246        }
247        self.resolve("manifest", |c| get_bytes(c, Q::ManifestGet, entry)).map(Cow::Owned)
248    }
249
250    /// `Some` only for a `stored` function (descriptor `code.lang` is `stored`, and the store
251    /// has the descriptor): the value of the receipt of the version that answers as of
252    /// `asof`, [`stored_asof`](Store::stored_asof)'s: the latest version (by tx) with `tx <=
253    /// asof` whose receipt's asof is also `<= asof` (the core's testkit
254    /// `AnswerRule::TxAndAsof`). `None` for every other function, and when no version
255    /// answers. (Until 0.2.0 it looked at `tx` only, as [`version_asof`](Store::version_asof)
256    /// still does; the same when every receipt's asof is its tx.)
257    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
258        if !is_instant(asof) {
259            return None;
260        }
261        self.resolve("evaluate", |c| {
262            let Some(desc) = get_bytes(c, Q::DescriptorGet, &cell.fn_hash)? else { return Ok(None) };
263            match FunctionDescriptor::from_json(&desc) {
264                Ok(d) if d.lang == "stored" => {}
265                Ok(_) => return Ok(None),
266                Err(e) => {
267                    tracing::error!(target: "datumesh_store", fn_hash = %cell.fn_hash, error = %e, "stored descriptor does not parse");
268                    return Ok(None);
269                }
270            }
271            let st = c.stmt(Q::ValueAsof)?;
272            let Some(row) = c.client.query_opt(&st, &[&cell.id(), &asof]).db()? else { return Ok(None) };
273            let bytes: Vec<u8> = row.try_get(0).db()?;
274            match Receipt::from_json(&bytes) {
275                Ok(r) => Ok(Some(r.value().clone())),
276                Err(e) => {
277                    tracing::error!(target: "datumesh_store", cell_id = %cell.id(), error = %e, "stored receipt does not parse");
278                    Ok(None)
279                }
280            }
281        })
282    }
283}
284
285/// The host of a fully qualified function name (`host/name`): what precedes the last `/`.
286fn name_host(fn_name: &str) -> &str {
287    fn_name.rsplit_once('/').map_or("", |(h, _)| h)
288}
289
290/// The namespace in `row`, whose columns from `at` are keydoc, validated_at, suspended_at,
291/// consecutive_failures, last_checked_at.
292fn namespace_row(host: &str, row: &postgres::Row, at: usize) -> Result<Namespace> {
293    let failures: i32 = row.try_get(at + 3).db()?;
294    Ok(Namespace {
295        host: host.to_string(),
296        keydoc: row.try_get(at).db()?,
297        validated_at: row.try_get(at + 1).db()?,
298        suspended_at: row.try_get(at + 2).db()?,
299        consecutive_failures: u32::try_from(failures).unwrap_or(0),
300        last_checked_at: row.try_get(at + 4).db()?,
301    })
302}
303
304impl PgStore {
305    /// A failed check (`threshold` is `Some`) or a successful one (`None`) at `checked_at`.
306    fn record_check(
307        &self,
308        op: &'static str,
309        host: &str,
310        checked_at: &str,
311        threshold: Option<u32>,
312    ) -> Result<Option<Namespace>> {
313        check_dns_name(host, "host")?;
314        check_instant(checked_at, "checked_at")?;
315        let out = self.run(op, |c| {
316            let lock = c.stmt(Q::Lock)?;
317            let get = c.stmt(Q::NamespaceGet)?;
318            let put = c.stmt(Q::NamespaceCheck)?;
319            let mut t = c.client.transaction().db()?;
320            t.execute(&lock, &[&"namespaces", &host]).db()?;
321            let Some(row) = t.query_opt(&get, &[&host]).db()? else { return Ok(None) };
322            let mut ns = namespace_row(host, &row, 0)?;
323            if let Some(at) = &ns.last_checked_at {
324                if checked_at < at.as_str() {
325                    return Err(Error::NotLater {
326                        what: "namespace",
327                        key: host.to_string(),
328                        given: checked_at.to_string(),
329                        latest: at.clone(),
330                    });
331                }
332            }
333            crate::apply_check(&mut ns, checked_at, threshold);
334            let failures = i32::try_from(ns.consecutive_failures).unwrap_or(i32::MAX);
335            t.execute(&put, &[&host, &failures, &checked_at, &ns.suspended_at]).db()?;
336            t.commit().db()?;
337            Ok(Some(ns))
338        })?;
339        tracing::debug!(target: "datumesh_store", host, checked_at, ok = threshold.is_none(), "namespace check");
340        Ok(out)
341    }
342}
343
344/// Items per statement of `latest_many` and `receipts_many` (longer inputs are split).
345const MANY: usize = 10_000;
346
347/// One item of a `put_cells` call, parsed before its transaction: the receipt's canonical
348/// bytes and the columns `put_receipt` stores, with its edges.
349struct Prepared {
350    canonical: Vec<u8>,
351    hash: String,
352    cell_id: String,
353    tx: String,
354    asof: String,
355    fn_hash: String,
356    publisher: String,
357    host: String,
358    entries: Vec<String>,
359    inputs: Vec<String>,
360}
361
362fn prepare(bytes: &[u8]) -> Result<Prepared> {
363    // The steps `put_receipt` takes before its query, in its order.
364    let r = Receipt::from_json(bytes)?;
365    let canonical = json::parse(bytes)?.to_jcs();
366    // Receipt hashes are edges; slice entries (spec-0.4.0) slice edges.
367    let (entries, inputs): (Vec<String>, Vec<String>) =
368        r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
369    Ok(Prepared {
370        canonical,
371        hash: r.hash().to_string(),
372        cell_id: r.cell().id(),
373        tx: r.tx().to_string(),
374        asof: r.asof().to_string(),
375        fn_hash: r.cell().fn_hash.clone(),
376        publisher: r.publisher().to_string(),
377        host: r.signer_host().to_string(),
378        entries,
379        inputs,
380    })
381}
382
383/// The receipt's verdict against the keys of its signer host, as `put_receipt` gives it:
384/// `None` when it verifies.
385fn verdict(bytes: &[u8], keys: &Keys) -> Option<datumesh_core::Error> {
386    let out = verify(bytes, keys, None, None);
387    if out.ok {
388        return None;
389    }
390    Some(
391        out.error()
392            .unwrap_or_else(|| datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")),
393    )
394}
395
396/// `f` over `items` on up to `available_parallelism()` threads; the results in item order.
397fn parallel<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
398    let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len());
399    if threads <= 1 {
400        return items.iter().map(f).collect();
401    }
402    let size = items.len().div_ceil(threads);
403    std::thread::scope(|s| {
404        let handles: Vec<_> = items
405            .chunks(size)
406            .map(|part| {
407                let f = &f;
408                s.spawn(move || part.iter().map(f).collect::<Vec<R>>())
409            })
410            .collect();
411        handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))).collect()
412    })
413}
414
415/// A signer host's namespace as `put_receipt` and `put_version` read it: its key document
416/// (the keys it verifies with) and whether it is suspended, and since when.
417struct HostState {
418    keys: Keys,
419    suspended_at: Option<String>,
420}
421
422/// `put_cells` on one connection, in one transaction: the items in order, with the checks
423/// and the errors of `put_receipt` and `put_version` (see `Store::put_cells`).
424fn put_cells_in(c: &mut Conn, items: &[CellWrite<'_>], prepared: Vec<Result<Prepared>>) -> Result<Vec<String>> {
425    let version_cells = || {
426        items
427            .iter()
428            .filter_map(|w| w.version)
429            .filter(|(cell, tx)| check_hex(cell, 64, "cell_id").is_ok() && check_instant(tx, "tx").is_ok())
430    };
431    let st_lock = c.stmt(Q::VersionLocksMany)?;
432    let st_get = c.stmt(Q::ReceiptsGetMany)?;
433    let st_ns = c.stmt(Q::NamespacesGetMany)?;
434    let st_latest = c.stmt(Q::VersionsLatestTxMany)?;
435    let st_put = c.stmt(Q::ReceiptsPutMany)?;
436    let st_edges = c.stmt(Q::EdgesPutMany)?;
437    let st_slice_edges = c.stmt(Q::SliceEdgesPutMany)?;
438    let st_versions = c.stmt(Q::VersionsPutMany)?;
439    let mut t = c.client.transaction().db()?;
440
441    // The version locks, in item order (as put_version takes them; one statement).
442    let mut locked: Vec<&str> = Vec::new();
443    for (cell, _) in version_cells() {
444        if !locked.contains(&cell) {
445            locked.push(cell);
446        }
447    }
448    if !locked.is_empty() {
449        t.execute(&st_lock, &[&locked]).db()?;
450    }
451
452    // What the store holds for the call: the receipts (by hash), the namespaces of the signer
453    // hosts and the latest tx of the version cells, all read after the locks.
454    let parsed: Vec<&Prepared> = prepared.iter().filter_map(|p| p.as_ref().ok()).collect();
455    let mut hashes: Vec<&str> = parsed.iter().map(|p| p.hash.as_str()).collect();
456    hashes.sort_unstable();
457    hashes.dedup();
458    let mut stored: HashMap<String, Vec<u8>> = HashMap::new();
459    if !hashes.is_empty() {
460        for row in t.query(&st_get, &[&hashes]).db()? {
461            stored.insert(row.try_get(0).db()?, row.try_get(1).db()?);
462        }
463    }
464    let mut hosts: Vec<&str> = parsed.iter().map(|p| p.host.as_str()).collect();
465    hosts.sort_unstable();
466    hosts.dedup();
467    let mut namespaces: HashMap<String, HostState> = HashMap::new();
468    if !hosts.is_empty() {
469        for row in t.query(&st_ns, &[&hosts]).db()? {
470            let host: String = row.try_get(0).db()?;
471            let doc: Vec<u8> = row.try_get(1).db()?;
472            let suspended_at: Option<String> = row.try_get(2).db()?;
473            let mut keys = Keys::new();
474            keys.insert_response(&host, 200, Some(&doc));
475            namespaces.insert(host, HostState { keys, suspended_at });
476        }
477    }
478    let mut cells: Vec<&str> = version_cells().map(|(cell, _)| cell).collect();
479    cells.sort_unstable();
480    cells.dedup();
481    let mut latest: HashMap<String, String> = HashMap::new();
482    if !cells.is_empty() {
483        for row in t.query(&st_latest, &[&cells]).db()? {
484            latest.insert(row.try_get(0).db()?, row.try_get(1).db()?);
485        }
486    }
487
488    // The signatures, on threads: every item not already stored with the same bytes (the
489    // others are not checked, as put_receipt's idempotence says). A namespace's keys are
490    // those of the stored key document; none stored is a host without keys.
491    let empty = Keys::new();
492    let keys_of = |host: &str| namespaces.get(host).map_or(&empty, |h| &h.keys);
493    let jobs: Vec<usize> = (0..items.len())
494        .filter(|&i| match &prepared[i] {
495            Ok(p) => stored.get(&p.hash) != Some(&p.canonical),
496            Err(_) => false,
497        })
498        .collect();
499    let mut verdicts: Vec<Option<Option<datumesh_core::Error>>> = vec![None; items.len()];
500    let checked = parallel(&jobs, |&i| {
501        let host = prepared[i].as_ref().map_or("", |p| p.host.as_str());
502        verdict(items[i].receipt, keys_of(host))
503    });
504    for (i, v) in jobs.into_iter().zip(checked) {
505        verdicts[i] = Some(v);
506    }
507
508    // In item order, as the loop of put_receipt and put_version would run them, against the
509    // state of the store plus the items before. The first failure is the call's error.
510    let mut out: Vec<String> = Vec::with_capacity(items.len());
511    let mut new: Vec<Prepared> = Vec::new();
512    let mut versions: Vec<(&str, &str, String)> = Vec::new();
513    for (i, pr) in prepared.into_iter().enumerate() {
514        let p = pr?;
515        let host_state = namespaces.get(&p.host);
516        let suspended = |host: &str| -> Result<()> {
517            match host_state.and_then(|h| h.suspended_at.as_ref()) {
518                // No new writes under a suspended namespace.
519                Some(since) => Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since.clone() }),
520                None => Ok(()),
521            }
522        };
523        // put_receipt: the stored copy with the same bytes is the receipt (no checks).
524        let is_stored = stored.get(&p.hash).is_some_and(|b| *b == p.canonical);
525        if !is_stored {
526            suspended(&p.host)?;
527            match verdicts[i].take() {
528                Some(Some(e)) => return Err(Error::Invalid(e)),
529                Some(None) => {}
530                None => unreachable!("an item not stored is checked"),
531            }
532            if stored.contains_key(&p.hash) {
533                return Err(Error::Conflict { hash: p.hash.clone() });
534            }
535            stored.insert(p.hash.clone(), p.canonical.clone());
536        }
537        // put_version, for the item's version.
538        if let Some((cell, tx)) = items[i].version {
539            check_hex(cell, 64, "cell_id")?;
540            check_instant(tx, "tx")?;
541            suspended(&p.host)?;
542            if p.cell_id != cell {
543                return Err(Error::Mismatch { what: "cell_id", expected: cell.to_string(), found: p.cell_id.clone() });
544            }
545            if p.tx != tx {
546                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: p.tx.clone() });
547            }
548            if let Some(l) = latest.get(cell) {
549                if tx <= l.as_str() {
550                    return Err(Error::NotLater {
551                        what: "version",
552                        key: cell.to_string(),
553                        given: tx.to_string(),
554                        latest: l.clone(),
555                    });
556                }
557            }
558            latest.insert(cell.to_string(), tx.to_string());
559            versions.push((cell, tx, p.hash.clone()));
560        }
561        out.push(p.hash.clone());
562        if !is_stored {
563            new.push(p);
564        }
565    }
566
567    // The writes. A receipt another transaction stored meanwhile must hold the same bytes.
568    if !new.is_empty() {
569        let hashes: Vec<&str> = new.iter().map(|p| p.hash.as_str()).collect();
570        let bytes: Vec<&[u8]> = new.iter().map(|p| p.canonical.as_slice()).collect();
571        let cells: Vec<&str> = new.iter().map(|p| p.cell_id.as_str()).collect();
572        let txs: Vec<&str> = new.iter().map(|p| p.tx.as_str()).collect();
573        let asofs: Vec<&str> = new.iter().map(|p| p.asof.as_str()).collect();
574        let fns: Vec<&str> = new.iter().map(|p| p.fn_hash.as_str()).collect();
575        let pubs: Vec<&str> = new.iter().map(|p| p.publisher.as_str()).collect();
576        let rows = t.query(&st_put, &[&hashes, &bytes, &cells, &txs, &asofs, &fns, &pubs]).db()?;
577        let mut got: HashSet<String> = HashSet::new();
578        for row in &rows {
579            got.insert(row.try_get(0).db()?);
580        }
581        let missing: Vec<&str> = hashes.iter().copied().filter(|h| !got.contains(*h)).collect();
582        if !missing.is_empty() {
583            let mut held: HashMap<String, Vec<u8>> = HashMap::new();
584            for row in t.query(&st_get, &[&missing]).db()? {
585                held.insert(row.try_get(0).db()?, row.try_get(1).db()?);
586            }
587            for p in new.iter().filter(|p| missing.contains(&p.hash.as_str())) {
588                if held.get(&p.hash) != Some(&p.canonical) {
589                    return Err(Error::Conflict { hash: p.hash.clone() });
590                }
591            }
592        }
593        let edges: Vec<(&str, &str)> =
594            new.iter().flat_map(|p| p.inputs.iter().map(move |i| (p.hash.as_str(), i.as_str()))).collect();
595        if !edges.is_empty() {
596            let (r, i): (Vec<&str>, Vec<&str>) = edges.into_iter().unzip();
597            t.execute(&st_edges, &[&r, &i]).db()?;
598        }
599        let slice_edges: Vec<(&str, &str)> =
600            new.iter().flat_map(|p| p.entries.iter().map(move |e| (p.hash.as_str(), e.as_str()))).collect();
601        if !slice_edges.is_empty() {
602            let (r, e): (Vec<&str>, Vec<&str>) = slice_edges.into_iter().unzip();
603            t.execute(&st_slice_edges, &[&r, &e]).db()?;
604        }
605    }
606    if !versions.is_empty() {
607        let cells: Vec<&str> = versions.iter().map(|v| v.0).collect();
608        let txs: Vec<&str> = versions.iter().map(|v| v.1).collect();
609        let hashes: Vec<&str> = versions.iter().map(|v| v.2.as_str()).collect();
610        t.execute(&st_versions, &[&cells, &txs, &hashes]).db()?;
611    }
612    t.commit().db()?;
613    Ok(out)
614}
615
616/// The version of `cell_id` in a row of `VersionLatestMany` (tx, receipt hash, asof), `None`
617/// when the cell has none.
618fn latest_row(r: &postgres::Row, cell_id: &str) -> Result<Option<Version>> {
619    let Some(tx) = r.try_get::<_, Option<String>>(0).db()? else { return Ok(None) };
620    Ok(Some(Version { cell_id: cell_id.to_string(), tx, receipt_hash: r.try_get(1).db()?, asof: r.try_get(2).db()? }))
621}
622
623impl Store for PgStore {
624    fn put_descriptor(&self, bytes: &[u8]) -> Result<String> {
625        // spec-0.4.0's descriptor: `signature.order` and argument `extent` allowed.
626        let d = FunctionDescriptor::from_json(bytes)?;
627        let hash = d.hash();
628        let canonical = d.canonical();
629        // The descriptor and its inputs' index (0.5.1), in one transaction.
630        self.run("put_descriptor", |c| {
631            let st = c.stmt(Q::DescriptorPut)?;
632            let inputs_put = c.stmt(Q::DescriptorInputsPut)?;
633            let mut t = c.client.transaction().db()?;
634            t.execute(&st, &[&hash, &canonical]).db()?;
635            if !d.inputs.is_empty() {
636                t.execute(&inputs_put, &[&hash, &d.inputs]).db()?;
637            }
638            t.commit().db()?;
639            Ok(())
640        })?;
641        tracing::debug!(target: "datumesh_store", fn_hash = %hash, "put_descriptor");
642        Ok(hash)
643    }
644
645    fn put_receipt(&self, bytes: &[u8]) -> Result<String> {
646        // Steps 1-4 first: a receipt that is not one is refused without a query.
647        let r = Receipt::from_json(bytes)?;
648        // Steps 1-4 passed, so the text parses; its JCS is the canonical form.
649        let canonical = json::parse(bytes)?.to_jcs();
650        let hash = r.hash().to_string();
651        let cell_id = r.cell().id();
652        let host = r.signer_host().to_string();
653        // Receipt hashes are edges; slice entries (spec-0.4.0) slice edges.
654        let (entries, inputs): (Vec<String>, Vec<String>) =
655            r.inputs().iter().cloned().partition(|e| e.starts_with("slice:"));
656        self.run("put_receipt", |c| {
657            let ns = c.stmt(Q::NamespaceGet)?;
658            let put = c.stmt(Q::ReceiptPut)?;
659            let get = c.stmt(Q::ReceiptGet)?;
660            let edges = c.stmt(Q::EdgesPut)?;
661            let slice_edges = c.stmt(Q::SliceEdgesPut)?;
662            let mut t = c.client.transaction().db()?;
663            // Idempotent: the very receipt already stored verified when it was stored, and
664            // the stored copy is unchanged, so it is not checked again (even if its key has
665            // since been revoked).
666            if let Some(row) = t.query_opt(&get, &[&hash]).db()? {
667                let stored: Vec<u8> = row.try_get(0).db()?;
668                if stored == canonical {
669                    return Ok(());
670                }
671            }
672            // Steps 5-6 against the stored key document of the signer host; none stored is
673            // a host without keys (E_KEY_UNAVAILABLE).
674            let mut keys = Keys::new();
675            if let Some(row) = t.query_opt(&ns, &[&host]).db()? {
676                // No new writes under a suspended namespace.
677                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
678                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
679                }
680                let doc: Vec<u8> = row.try_get(0).db()?;
681                keys.insert_response(&host, 200, Some(&doc));
682            }
683            let out = verify(bytes, &keys, None, None);
684            if !out.ok {
685                return Err(Error::Invalid(out.error().unwrap_or_else(|| {
686                    datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")
687                })));
688            }
689            let n = t
690                .execute(&put, &[&hash, &canonical, &cell_id, &r.tx(), &r.asof(), &r.cell().fn_hash, &r.publisher()])
691                .db()?;
692            if n == 0 {
693                let row = t.query_one(&get, &[&hash]).db()?;
694                let stored: Vec<u8> = row.try_get(0).db()?;
695                if stored != canonical {
696                    return Err(Error::Conflict { hash: hash.clone() });
697                }
698            }
699            if !inputs.is_empty() {
700                t.execute(&edges, &[&hash, &inputs]).db()?;
701            }
702            if !entries.is_empty() {
703                t.execute(&slice_edges, &[&hash, &entries]).db()?;
704            }
705            t.commit().db()?;
706            Ok(())
707        })?;
708        tracing::debug!(target: "datumesh_store", hash = %hash, cell_id = %cell_id, "put_receipt");
709        Ok(hash)
710    }
711
712    fn put_blob(&self, bytes: &[u8]) -> Result<String> {
713        let sha = sha256_hex(bytes);
714        let length = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
715        self.run("put_blob", |c| {
716            let st = c.stmt(Q::BlobPut)?;
717            c.client.execute(&st, &[&sha, &bytes, &length]).db()?;
718            Ok(())
719        })?;
720        tracing::debug!(target: "datumesh_store", sha256 = %sha, length, "put_blob");
721        Ok(sha)
722    }
723
724    fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>> {
725        check_hex(sha256, 64, "sha256")?;
726        Ok(self.run("blob", |c| get_bytes(c, Q::BlobGet, sha256))?.map(Cow::Owned))
727    }
728
729    fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
730        check_hex(cell_id, 64, "cell_id")?;
731        check_instant(tx, "tx")?;
732        check_hex(receipt_hash, 64, "receipt_hash")?;
733        self.run("put_version", |c| {
734            let lock = c.stmt(Q::Lock)?;
735            let meta = c.stmt(Q::ReceiptMeta)?;
736            let get = c.stmt(Q::ReceiptGet)?;
737            let ns = c.stmt(Q::NamespaceGet)?;
738            let latest = c.stmt(Q::VersionLatestTx)?;
739            let put = c.stmt(Q::VersionPut)?;
740            let mut t = c.client.transaction().db()?;
741            t.execute(&lock, &[&"versions", &cell_id]).db()?;
742            let Some(row) = t.query_opt(&meta, &[&receipt_hash]).db()? else {
743                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
744            };
745            // No new versions of a receipt signed by a suspended namespace.
746            let stored: Vec<u8> = t.query_one(&get, &[&receipt_hash]).db()?.try_get(0).db()?;
747            let signer = Receipt::from_json(&stored)?.signer_host().to_string();
748            if let Some(row) = t.query_opt(&ns, &[&signer]).db()? {
749                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
750                    return Err(Error::NamespaceSuspended { host: signer, suspended_at: since });
751                }
752            }
753            let (r_cell, r_tx): (String, String) = (row.try_get(0).db()?, row.try_get(1).db()?);
754            if r_cell != cell_id {
755                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
756            }
757            if r_tx != tx {
758                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
759            }
760            if let Some(row) = t.query_opt(&latest, &[&cell_id]).db()? {
761                let l: String = row.try_get(0).db()?;
762                if tx <= l.as_str() {
763                    return Err(Error::NotLater {
764                        what: "version",
765                        key: cell_id.to_string(),
766                        given: tx.to_string(),
767                        latest: l,
768                    });
769                }
770            }
771            t.execute(&put, &[&cell_id, &tx, &receipt_hash]).db()?;
772            t.commit().db()?;
773            Ok(())
774        })?;
775        tracing::debug!(target: "datumesh_store", cell_id, tx, receipt_hash, "put_version");
776        Ok(())
777    }
778
779    fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
780        self.asof_version("version_asof", Q::VersionAsof, cell_id, asof)
781    }
782
783    fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>> {
784        check_hex(cell_id, 64, "cell_id")?;
785        check_instant(from, "from")?;
786        check_instant(to, "to")?;
787        self.run("versions", |c| {
788            let st = c.stmt(Q::VersionRange)?;
789            let rows = c.client.query(&st, &[&cell_id, &from, &to]).db()?;
790            PgStore::version_rows(&rows, cell_id)
791        })
792    }
793
794    fn latest(&self, cell_id: &str) -> Result<Option<Version>> {
795        check_hex(cell_id, 64, "cell_id")?;
796        self.run("latest", |c| {
797            let st = c.stmt(Q::VersionLatest)?;
798            let rows = c.client.query(&st, &[&cell_id]).db()?;
799            Ok(PgStore::version_rows(&rows, cell_id)?.pop())
800        })
801    }
802
803    fn latest_many(&self, cell_ids: &[&str]) -> Result<Vec<Option<Version>>> {
804        for id in cell_ids {
805            check_hex(id, 64, "cell_id")?;
806        }
807        let mut out = Vec::with_capacity(cell_ids.len());
808        for part in cell_ids.chunks(MANY) {
809            let versions = self.run("latest_many", |c| {
810                let st = c.stmt(Q::VersionLatestMany)?;
811                let rows = c.client.query(&st, &[&part]).db()?;
812                rows.iter().zip(part).map(|(r, id)| latest_row(r, id)).collect::<Result<Vec<_>>>()
813            })?;
814            out.extend(versions);
815        }
816        Ok(out)
817    }
818
819    fn receipts_many(&self, hashes: &[&str]) -> Result<Vec<Option<Vec<u8>>>> {
820        let mut out = Vec::with_capacity(hashes.len());
821        for part in hashes.chunks(MANY) {
822            // A malformed hash has no receipt (as `receipt` answers): it is not sent.
823            let valid: Vec<&str> = part.iter().copied().filter(|h| is_hash(h)).collect();
824            let found: Vec<Option<Vec<u8>>> = if valid.is_empty() {
825                Vec::new()
826            } else {
827                self.run("receipts_many", |c| {
828                    let st = c.stmt(Q::ReceiptsMany)?;
829                    let rows = c.client.query(&st, &[&valid]).db()?;
830                    rows.iter().map(|r| r.try_get::<_, Option<Vec<u8>>>(0).db()).collect::<Result<Vec<_>>>()
831                })?
832            };
833            let mut found = found.into_iter();
834            for h in part {
835                out.push(if is_hash(h) { found.next().flatten() } else { None });
836            }
837        }
838        Ok(out)
839    }
840
841    fn put_cells(&self, items: &[CellWrite<'_>]) -> Result<Vec<String>> {
842        if items.is_empty() {
843            return Ok(Vec::new());
844        }
845        // Parsing (and so the first malformed receipt's error) is in item order below.
846        let prepared = parallel(items, |w| prepare(w.receipt));
847        let hashes = self.run("put_cells", |c| put_cells_in(c, items, prepared))?;
848        tracing::debug!(target: "datumesh_store", items = items.len(), "put_cells");
849        Ok(hashes)
850    }
851
852    fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>> {
853        check_hex(receipt_hash, 64, "receipt_hash")?;
854        self.run("dependents", |c| get_strings(c, Q::Dependents, receipt_hash))
855    }
856
857    fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>> {
858        check_hex(receipt_hash, 64, "receipt_hash")?;
859        self.run("inputs", |c| get_strings(c, Q::Inputs, receipt_hash))
860    }
861
862    fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()> {
863        // SPEC 9.3: a 200 with this body, for this host (a DNS name equal to the document's).
864        keys_from_response(host, 200, Some(keydoc_bytes))?;
865        check_instant(validated_at, "validated_at")?;
866        let canonical = json::parse(keydoc_bytes)?.to_jcs();
867        self.run("put_namespace", |c| {
868            let lock = c.stmt(Q::Lock)?;
869            let get = c.stmt(Q::NamespaceGet)?;
870            let put = c.stmt(Q::NamespacePut)?;
871            let mut t = c.client.transaction().db()?;
872            t.execute(&lock, &[&"namespaces", &host]).db()?;
873            if let Some(row) = t.query_opt(&get, &[&host]).db()? {
874                let at: String = row.try_get(1).db()?;
875                if validated_at < at.as_str() {
876                    return Err(Error::NotLater {
877                        what: "namespace",
878                        key: host.to_string(),
879                        given: validated_at.to_string(),
880                        latest: at,
881                    });
882                }
883            }
884            t.execute(&put, &[&host, &canonical, &validated_at]).db()?;
885            t.commit().db()?;
886            Ok(())
887        })?;
888        tracing::debug!(target: "datumesh_store", host, validated_at, "put_namespace");
889        Ok(())
890    }
891
892    fn namespace(&self, host: &str) -> Result<Option<Namespace>> {
893        check_dns_name(host, "host")?;
894        self.run("namespace", |c| {
895            let st = c.stmt(Q::NamespaceGet)?;
896            let Some(row) = c.client.query_opt(&st, &[&host]).db()? else { return Ok(None) };
897            Ok(Some(namespace_row(host, &row, 0)?))
898        })
899    }
900
901    fn namespaces(&self) -> Result<Vec<Namespace>> {
902        self.run("namespaces", |c| {
903            let st = c.stmt(Q::NamespaceList)?;
904            let mut out = Vec::new();
905            for row in c.client.query(&st, &[]).db()? {
906                let host: String = row.try_get(0).db()?;
907                out.push(namespace_row(&host, &row, 1)?);
908            }
909            Ok(out)
910        })
911    }
912
913    fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>> {
914        self.record_check("record_namespace_failure", host, checked_at, Some(threshold))
915    }
916
917    fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>> {
918        self.record_check("record_namespace_success", host, checked_at, None)
919    }
920
921    fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()> {
922        check_function_name(fn_name, "fn_name")?;
923        check_hex(fn_hash, 64, "fn_hash")?;
924        check_instant(tx, "tx")?;
925        self.run("bind_name", |c| {
926            let lock = c.stmt(Q::Lock)?;
927            let exists = c.stmt(Q::DescriptorExists)?;
928            let ns = c.stmt(Q::NamespaceGet)?;
929            let latest = c.stmt(Q::NameLatest)?;
930            let put = c.stmt(Q::NamePut)?;
931            let class_bound = c.stmt(Q::ClassNameBound)?;
932            let mut t = c.client.transaction().db()?;
933            t.execute(&lock, &[&"names", &fn_name]).db()?;
934            // No new bindings under a suspended namespace.
935            if let Some(row) = t.query_opt(&ns, &[&name_host(fn_name)]).db()? {
936                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
937                    return Err(Error::NamespaceSuspended {
938                        host: name_host(fn_name).to_string(),
939                        suspended_at: since,
940                    });
941                }
942            }
943            // One namespace of names: a class name is not a function name.
944            let class: bool = t.query_one(&class_bound, &[&fn_name]).db()?.try_get(0).db()?;
945            if class {
946                return Err(Error::NameTaken { name: fn_name.to_string(), bound_as: "class" });
947            }
948            let found: bool = t.query_one(&exists, &[&fn_hash]).db()?.try_get(0).db()?;
949            if !found {
950                return Err(Error::NotFound { what: "descriptor", key: fn_hash.to_string() });
951            }
952            if let Some(row) = t.query_opt(&latest, &[&fn_name]).db()? {
953                let l: String = row.try_get(0).db()?;
954                if tx <= l.as_str() {
955                    return Err(Error::NotLater {
956                        what: "name",
957                        key: fn_name.to_string(),
958                        given: tx.to_string(),
959                        latest: l,
960                    });
961                }
962            }
963            t.execute(&put, &[&fn_name, &tx, &fn_hash]).db()?;
964            t.commit().db()?;
965            Ok(())
966        })?;
967        tracing::debug!(target: "datumesh_store", fn_name, fn_hash, tx, "bind_name");
968        Ok(())
969    }
970
971    fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
972        check_hex(cell_id, 64, "cell_id")?;
973        check_instant(tx, "tx")?;
974        check_hex(receipt_hash, 64, "receipt_hash")?;
975        // No lock: the primary key serialises writers of one (cell_id, tx, asof). An insert
976        // that meets a concurrent one waits for it; if it committed, nothing is inserted and
977        // the row it wrote (visible to the next statement under READ COMMITTED) decides.
978        let asof = self.run("put_computed", |c| {
979            let meta = c.stmt(Q::ReceiptMeta)?;
980            let put = c.stmt(Q::ComputedPut)?;
981            let get = c.stmt(Q::ComputedGet)?;
982            let mut t = c.client.transaction().db()?;
983            let Some(row) = t.query_opt(&meta, &[&receipt_hash]).db()? else {
984                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
985            };
986            let (r_cell, r_tx, asof): (String, String, String) =
987                (row.try_get(0).db()?, row.try_get(1).db()?, row.try_get(2).db()?);
988            if r_cell != cell_id {
989                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
990            }
991            if r_tx != tx {
992                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
993            }
994            if t.execute(&put, &[&cell_id, &tx, &asof, &receipt_hash]).db()? == 0 {
995                let stored: String = t.query_one(&get, &[&cell_id, &tx, &asof]).db()?.try_get(0).db()?;
996                if stored != receipt_hash {
997                    return Err(Error::Conflict { hash: receipt_hash.to_string() });
998                }
999            }
1000            t.commit().db()?;
1001            Ok(asof)
1002        })?;
1003        tracing::debug!(target: "datumesh_store", cell_id, tx, asof, receipt_hash, "put_computed");
1004        Ok(())
1005    }
1006
1007    fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1008        self.asof_version("computed_asof", Q::ComputedAsof, cell_id, asof)
1009    }
1010
1011    fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1012        self.asof_version("stored_asof", Q::StoredAsof, cell_id, asof)
1013    }
1014
1015    fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>> {
1016        check_hex(cell_id, 64, "cell_id")?;
1017        self.run("cell_dependents", |c| get_strings(c, Q::CellDependents, cell_id))
1018    }
1019
1020    /// One query: the version and its receipt's bytes.
1021    fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1022        Ok(self
1023            .asof_with_receipt("computed_asof_with_receipt", Q::ComputedAsofReceipt, cell_id, asof)?
1024            .map(|(v, b)| (v, Cow::Owned(b))))
1025    }
1026
1027    /// One query: the version and its receipt's bytes.
1028    fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1029        Ok(self
1030            .asof_with_receipt("stored_asof_with_receipt", Q::StoredAsofReceipt, cell_id, asof)?
1031            .map(|(v, b)| (v, Cow::Owned(b))))
1032    }
1033
1034    fn put_manifest(&self, bytes: &[u8]) -> Result<String> {
1035        let m = Manifest::from_json(bytes)?;
1036        let entry = m.entry();
1037        let canonical = m.canonical();
1038        let members = m.members();
1039        let n = i32::try_from(members.len()).unwrap_or(i32::MAX);
1040        self.run("put_manifest", |c| {
1041            let put = c.stmt(Q::ManifestPut)?;
1042            let put_members = c.stmt(Q::ManifestMembersPut)?;
1043            let mut t = c.client.transaction().db()?;
1044            // The entry hashes the content: a stored entry has these very bytes. A concurrent
1045            // insert of it waits for the other; if that one committed, nothing is inserted
1046            // here, members included (it inserted them).
1047            let inserted = t
1048                .execute(&put, &[&entry, &m.slice().id(), &m.members_hash(), &m.slice().fn_hash(), &n, &canonical])
1049                .db()?;
1050            if inserted == 1 && !members.is_empty() {
1051                t.execute(&put_members, &[&entry, &members]).db()?;
1052            }
1053            t.commit().db()?;
1054            Ok(())
1055        })?;
1056        tracing::debug!(target: "datumesh_store", entry = %entry, members = n, "put_manifest");
1057        Ok(entry)
1058    }
1059
1060    fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>> {
1061        check_hex(receipt_hash, 64, "receipt_hash")?;
1062        self.run("member_manifests", |c| get_strings(c, Q::MemberManifests, receipt_hash))
1063    }
1064
1065    fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>> {
1066        check_hex(receipt_hash, 64, "receipt_hash")?;
1067        self.run("slice_entries", |c| get_strings(c, Q::SliceEntries, receipt_hash))
1068    }
1069
1070    fn slice_dependents(&self, entry: &str) -> Result<Vec<String>> {
1071        check_entry(entry, "entry")?;
1072        self.run("slice_dependents", |c| get_strings(c, Q::SliceDependents, entry))
1073    }
1074
1075    fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>> {
1076        check_instant(asof, "asof")?;
1077        let v = slice.to_value();
1078        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1079            return self.versions_between(&cell_id, &from, &to, asof);
1080        }
1081        let pattern = Pattern::of(&v)?;
1082        self.run("slice_members", |c| pattern.members(c, asof))
1083    }
1084
1085    fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>> {
1086        check_hex(cell_id, 64, "cell_id")?;
1087        check_instant(from, "from")?;
1088        check_instant(to, "to")?;
1089        check_instant(asof, "asof")?;
1090        self.run("versions_between", |c| {
1091            let st = c.stmt(Q::VersionsBetween)?;
1092            let rows = c.client.query(&st, &[&cell_id, &from, &to, &asof]).db()?;
1093            rows.iter().map(|r| member_row(r, cell_id)).collect()
1094        })
1095    }
1096
1097    fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>> {
1098        check_instant(asof, "asof")?;
1099        let v = slice.to_value();
1100        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1101            return self.run("slice_values", |c| {
1102                let st = c.stmt(Q::VersionsBetweenValues)?;
1103                let rows = c.client.query(&st, &[&cell_id, &from, &to, &asof]).db()?;
1104                rows.iter().map(|r| value_row(r, &cell_id)).collect()
1105            });
1106        }
1107        let pattern = Pattern::of(&v)?;
1108        self.run("slice_values", |c| pattern.values(c, asof))
1109    }
1110
1111    fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool> {
1112        check_instant(asof, "asof")?;
1113        let v = slice.to_value();
1114        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1115            return self.run("slice_changed_after", |c| {
1116                let st = c.stmt(Q::VersionsChangedAfter)?;
1117                c.client.query_one(&st, &[&cell_id, &from, &to, &asof]).db()?.try_get(0).db()
1118            });
1119        }
1120        let pattern = Pattern::of(&v)?;
1121        self.run("slice_changed_after", |c| pattern.changed_after(c, asof))
1122    }
1123
1124    fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>> {
1125        check_instant(asof, "asof")?;
1126        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1127        let pattern = Pattern::of(&slice.to_value())?;
1128        self.run("computed_cells", |c| pattern.computed_cells(c, asof, limit))
1129    }
1130
1131    fn has_bindings_under(&self, namespace: &str) -> Result<bool> {
1132        let prefix = format!("{namespace}/");
1133        self.run("has_bindings_under", |c| {
1134            let st = c.stmt(Q::HasBindingsUnder)?;
1135            c.client.query_one(&st, &[&prefix]).db()?.try_get(0).db()
1136        })
1137    }
1138
1139    fn put_class(&self, bytes: &[u8]) -> Result<String> {
1140        // The core checks the descriptor (strict JSON, then 16.1); the bytes must be its
1141        // canonical form, since the class hash is the hash of the bytes stored.
1142        let d = ClassDescriptor::from_json(bytes)?;
1143        let canonical = d.canonical();
1144        if canonical != bytes {
1145            return Err(not_canonical_class());
1146        }
1147        let hash = d.hash();
1148        let host = d.steward.namespace.clone();
1149        self.run("put_class", |c| {
1150            // No new writes under a suspended namespace: the steward's (16.2).
1151            let ns = c.stmt(Q::NamespaceGet)?;
1152            if let Some(row) = c.client.query_opt(&ns, &[&host]).db()? {
1153                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1154                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
1155                }
1156            }
1157            let put = c.stmt(Q::ClassPut)?;
1158            c.client.execute(&put, &[&hash, &canonical]).db()?;
1159            Ok(())
1160        })?;
1161        tracing::debug!(target: "datumesh_store", class_hash = %hash, "put_class");
1162        Ok(hash)
1163    }
1164
1165    fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>> {
1166        check_hex(class_hash, 64, "class_hash")?;
1167        self.run("class", |c| get_bytes(c, Q::ClassGet, class_hash))
1168    }
1169
1170    fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()> {
1171        check_function_name(class_name, "class_name")?;
1172        check_hex(class_hash, 64, "class_hash")?;
1173        check_instant(tx, "tx")?;
1174        self.run("bind_class", |c| {
1175            let lock = c.stmt(Q::Lock)?;
1176            let ns = c.stmt(Q::NamespaceGet)?;
1177            let get = c.stmt(Q::ClassGet)?;
1178            let exists = c.stmt(Q::DescriptorExists)?;
1179            let name_bound = c.stmt(Q::NameBound)?;
1180            let class_bound = c.stmt(Q::ClassNameBound)?;
1181            let class_latest = c.stmt(Q::ClassBindingLatest)?;
1182            let latest = c.stmt(Q::NameLatest)?;
1183            let class_put = c.stmt(Q::ClassBindingPut)?;
1184            let name_put = c.stmt(Q::NamePut)?;
1185            let mut t = c.client.transaction().db()?;
1186            // Every name this binding makes is locked before it is read: the class name, then
1187            // its method names (the flattened descriptor's, in JCS order).
1188            t.execute(&lock, &[&"names", &class_name]).db()?;
1189            // No new bindings under a suspended namespace: the host of the class name.
1190            let host = name_host(class_name);
1191            if let Some(row) = t.query_opt(&ns, &[&host]).db()? {
1192                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1193                    return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
1194                }
1195            }
1196            let Some(row) = t.query_opt(&get, &[&class_hash]).db()? else {
1197                return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
1198            };
1199            let flat = ClassDescriptor::from_json(&row.try_get::<_, Vec<u8>>(0).db()?)?;
1200            let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
1201            let method_names: Vec<String> = methods.iter().map(|(m, _)| format!("{class_name}/{m}")).collect();
1202            for name in &method_names {
1203                t.execute(&lock, &[&"names", &name.as_str()]).db()?;
1204            }
1205            // Every method's function descriptor is stored.
1206            for (_, h) in &methods {
1207                let found: bool = t.query_one(&exists, &[h]).db()?.try_get(0).db()?;
1208                if !found {
1209                    return Err(Error::NotFound { what: "descriptor", key: h.clone() });
1210                }
1211            }
1212            // One namespace of names: the class name is not a function name, and no method
1213            // name is a class name.
1214            let function: bool = t.query_one(&name_bound, &[&class_name]).db()?.try_get(0).db()?;
1215            if function {
1216                return Err(Error::NameTaken { name: class_name.to_string(), bound_as: "function" });
1217            }
1218            for name in &method_names {
1219                let class: bool = t.query_one(&class_bound, &[&name.as_str()]).db()?.try_get(0).db()?;
1220                if class {
1221                    return Err(Error::NameTaken { name: name.clone(), bound_as: "class" });
1222                }
1223            }
1224            // Later than the latest binding of the class name and of each method name.
1225            if let Some(row) = t.query_opt(&class_latest, &[&class_name]).db()? {
1226                let l: String = row.try_get(0).db()?;
1227                if tx <= l.as_str() {
1228                    return Err(Error::NotLater {
1229                        what: "name",
1230                        key: class_name.to_string(),
1231                        given: tx.to_string(),
1232                        latest: l,
1233                    });
1234                }
1235            }
1236            for name in &method_names {
1237                if let Some(row) = t.query_opt(&latest, &[&name.as_str()]).db()? {
1238                    let l: String = row.try_get(0).db()?;
1239                    if tx <= l.as_str() {
1240                        return Err(Error::NotLater {
1241                            what: "name",
1242                            key: name.clone(),
1243                            given: tx.to_string(),
1244                            latest: l,
1245                        });
1246                    }
1247                }
1248            }
1249            t.execute(&class_put, &[&class_name, &tx, &class_hash]).db()?;
1250            for ((_, h), name) in methods.iter().zip(&method_names) {
1251                t.execute(&name_put, &[&name.as_str(), &tx, &h.as_str()]).db()?;
1252            }
1253            t.commit().db()?;
1254            Ok(())
1255        })?;
1256        tracing::debug!(target: "datumesh_store", class_name, class_hash, tx, "bind_class");
1257        Ok(())
1258    }
1259
1260    fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>> {
1261        Ok(self.resolve_class_binding(class_name, asof)?.map(|b| b.class_hash))
1262    }
1263
1264    fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>> {
1265        check_function_name(class_name, "class_name")?;
1266        check_instant(asof, "asof")?;
1267        self.run("resolve_class_binding", |c| {
1268            let st = c.stmt(Q::ClassBindingAsof)?;
1269            let Some(row) = c.client.query_opt(&st, &[&class_name, &asof]).db()? else { return Ok(None) };
1270            Ok(Some(ClassBinding { class_hash: row.try_get(0).db()?, tx: row.try_get(1).db()? }))
1271        })
1272    }
1273
1274    fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>> {
1275        check_function_name(fn_name, "fn_name")?;
1276        check_instant(asof, "asof")?;
1277        self.run("resolve_binding", |c| {
1278            let st = c.stmt(Q::BindingAsof)?;
1279            let Some(row) = c.client.query_opt(&st, &[&fn_name, &asof]).db()? else { return Ok(None) };
1280            Ok(Some(Binding { fn_hash: row.try_get(0).db()?, tx: row.try_get(1).db()? }))
1281        })
1282    }
1283
1284    fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>> {
1285        check_function_name(fn_name, "fn_name")?;
1286        check_instant(asof, "asof")?;
1287        self.run("resolve_name", |c| {
1288            let st = c.stmt(Q::NameAsof)?;
1289            let row = c.client.query_opt(&st, &[&fn_name, &asof]).db()?;
1290            Ok(match row {
1291                Some(r) => Some(r.try_get(0).db()?),
1292                None => None,
1293            })
1294        })
1295    }
1296
1297    fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>> {
1298        for e in entries {
1299            check_catalog_entry(e)?;
1300        }
1301        if entries.is_empty() {
1302            return Ok(Vec::new());
1303        }
1304        self.run("upsert_catalog", |c| {
1305            let mut t = c.client.transaction().db()?;
1306            let mut ids = Vec::with_capacity(entries.len());
1307            for e in entries {
1308                let kind = e.kind.as_str();
1309                let args = args_json(&e.args);
1310                let examples = canonical_examples(&e.examples)?;
1311                let before = t
1312                    .query_opt("SELECT label, description FROM catalog_entries WHERE kind = $1 AND name = $2", &[&kind, &e.name])
1313                    .db()?
1314                    .map(|r| -> Result<(String, String)> { Ok((r.try_get(0).db()?, r.try_get(1).db()?)) })
1315                    .transpose()?;
1316                let updated = t
1317                    .query_opt(
1318                        "INSERT INTO catalog_entries (kind, name, hash, label, description, args, examples, source, signed_by, updated_at)
1319                         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, now())
1320                         ON CONFLICT (kind, name) DO UPDATE SET hash = EXCLUDED.hash, label = EXCLUDED.label,
1321                             description = EXCLUDED.description, args = EXCLUDED.args, examples = EXCLUDED.examples,
1322                             source = EXCLUDED.source, signed_by = EXCLUDED.signed_by, updated_at = now()
1323                         WHERE catalog_entries.source = 'operator' OR EXCLUDED.source = 'publisher'
1324                         RETURNING id",
1325                        &[&kind, &e.name, &e.hash, &e.label, &e.description, &args, &examples, &e.source.as_str(), &e.signed_by],
1326                    )
1327                    .db()?;
1328                let id: i64 = match updated {
1329                    Some(row) => {
1330                        let id: i64 = row.try_get(0).db()?;
1331                        // A new text drops the embedding (the old one is of other words).
1332                        if let Some((label, description)) = before {
1333                            if self.vectors && entry_text(&label, &description) != entry_text(&e.label, &e.description) {
1334                                t.execute("DELETE FROM embeddings WHERE ref_kind = 'entry' AND ref_id = $1", &[&id]).db()?;
1335                            }
1336                        }
1337                        id
1338                    }
1339                    // An operator's entry over a publisher's: kept as it is.
1340                    None => t
1341                        .query_one("SELECT id FROM catalog_entries WHERE kind = $1 AND name = $2", &[&kind, &e.name])
1342                        .db()?
1343                        .try_get(0)
1344                        .db()?,
1345                };
1346                ids.push(id);
1347            }
1348            t.commit().db()?;
1349            Ok(ids)
1350        })
1351    }
1352
1353    fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>> {
1354        check_key_values(owner, key, values)?;
1355        if values.is_empty() {
1356            return Ok(Vec::new());
1357        }
1358        self.run("upsert_key_values", |c| {
1359            let mut t = c.client.transaction().db()?;
1360            let mut ids = Vec::with_capacity(values.len());
1361            for v in values {
1362                let before = t
1363                    .query_opt("SELECT label, value FROM key_values WHERE owner = $1 AND key = $2 AND value = $3", &[&owner, &key, &v.value])
1364                    .db()?
1365                    .map(|r| -> Result<(String, String)> { Ok((r.try_get(0).db()?, r.try_get(1).db()?)) })
1366                    .transpose()?;
1367                let id: i64 = t
1368                    .query_one(
1369                        "INSERT INTO key_values (owner, key, value, label, aliases) VALUES ($1, $2, $3, $4, $5)
1370                         ON CONFLICT (owner, key, value) DO UPDATE SET label = EXCLUDED.label, aliases = EXCLUDED.aliases
1371                         RETURNING id",
1372                        &[&owner, &key, &v.value, &v.label, &v.aliases],
1373                    )
1374                    .db()?
1375                    .try_get(0)
1376                    .db()?;
1377                if let Some((label, value)) = before {
1378                    if self.vectors && value_text(&label, &value) != value_text(&v.label, &v.value) {
1379                        t.execute("DELETE FROM embeddings WHERE ref_kind = 'value' AND ref_id = $1", &[&id]).db()?;
1380                    }
1381                }
1382                ids.push(id);
1383            }
1384            t.commit().db()?;
1385            Ok(ids)
1386        })
1387    }
1388
1389    fn refresh_value_counts(&self) -> Result<u64> {
1390        self.run("refresh_value_counts", |c| {
1391            c.client
1392                .execute(
1393                    "WITH counts AS (
1394                         SELECT e.name AS owner, a.name AS key, a.value AS value, count(*) AS n
1395                           FROM catalog_entries e JOIN cell_args a ON a.fn_hash = e.hash
1396                          WHERE e.kind = 'function'
1397                          GROUP BY e.name, a.name, a.value)
1398                     UPDATE key_values kv SET n_cells = x.n
1399                       FROM (SELECT v.id, COALESCE(c.n, 0) AS n
1400                               FROM key_values v
1401                               LEFT JOIN counts c ON c.owner = v.owner AND c.key = v.key AND c.value = v.value) x
1402                      WHERE x.id = kv.id",
1403                    &[],
1404                )
1405                .db()
1406        })
1407    }
1408
1409    fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>> {
1410        let Some(words) = Words::new(query) else { return Ok(Vec::new()) };
1411        if limit == 0 {
1412            return Ok(Vec::new());
1413        }
1414        let entry_where = like_where(&words, &["name", "label", "description", "args"]);
1415        let value_where = like_where(&words, &["value", "label", "array_to_string(aliases, ' ')"]);
1416        self.run("text_find", |c| {
1417            let mut hits = Vec::new();
1418            let refs = as_refs(&entry_where.1);
1419            for r in c.client.query(&format!("SELECT id, kind, name, hash, label, description, args, examples, source, signed_by FROM catalog_entries WHERE TRUE{}", entry_where.0), &refs).db()? {
1420                let entry = entry_from_columns(
1421                    &r.try_get::<_, String>(1).db()?,
1422                    r.try_get(2).db()?,
1423                    r.try_get(3).db()?,
1424                    r.try_get(4).db()?,
1425                    r.try_get(5).db()?,
1426                    &r.try_get::<_, String>(6).db()?,
1427                    &r.try_get::<_, String>(7).db()?,
1428                    &r.try_get::<_, String>(8).db()?,
1429                    r.try_get(9).db()?,
1430                )?;
1431                let score = words.score(&entry_fields(&entry));
1432                if let Some(score) = score {
1433                    hits.push(Hit::Entry { id: r.try_get(0).db()?, entry, score });
1434                }
1435            }
1436            let refs = as_refs(&value_where.1);
1437            for r in c.client.query(&format!("SELECT id, owner, key, value, label, aliases FROM key_values WHERE TRUE{}", value_where.0), &refs).db()? {
1438                let aliases: Vec<String> = r.try_get(5).db()?;
1439                let (value, label): (String, String) = (r.try_get(3).db()?, r.try_get(4).db()?);
1440                let score = {
1441                    let mut fields: Vec<&str> = vec![&value, &label];
1442                    fields.extend(aliases.iter().map(String::as_str));
1443                    words.score(&fields)
1444                };
1445                if let Some(score) = score {
1446                    hits.push(Hit::Value { id: r.try_get(0).db()?, owner: r.try_get(1).db()?, key: r.try_get(2).db()?, value, label, aliases, score });
1447                }
1448            }
1449            Ok(rank(hits, limit))
1450        })
1451    }
1452
1453    fn vector_find(&self, model: &str, vec: &[f32], limit: usize) -> Result<Vec<Hit>> {
1454        self.vectors_or_unsupported()?;
1455        let lit = vector_literal(vec)?;
1456        check_model(model)?;
1457        if limit == 0 {
1458            return Ok(Vec::new());
1459        }
1460        self.run("vector_find", |c| {
1461            let near = c
1462                .client
1463                .query(
1464                    "SELECT ref_kind, ref_id, (vec <=> $2::text::vector)::float8 FROM embeddings
1465                      WHERE model = $1 ORDER BY vec <=> $2::text::vector LIMIT $3",
1466                    &[&model, &lit, &as_i64(limit)],
1467                )
1468                .db()?;
1469            let mut order = Vec::with_capacity(near.len());
1470            for r in &near {
1471                order.push((r.try_get::<_, String>(0).db()?, r.try_get::<_, i64>(1).db()?, r.try_get::<_, f64>(2).db()?));
1472            }
1473            let entry_ids: Vec<i64> = order.iter().filter(|o| o.0 == "entry").map(|o| o.1).collect();
1474            let value_ids: Vec<i64> = order.iter().filter(|o| o.0 == "value").map(|o| o.1).collect();
1475            let mut entries = HashMap::new();
1476            for r in c.client.query("SELECT id, kind, name, hash, label, description, args, examples, source, signed_by FROM catalog_entries WHERE id = ANY($1)", &[&entry_ids]).db()? {
1477                let entry = entry_from_columns(
1478                    &r.try_get::<_, String>(1).db()?,
1479                    r.try_get(2).db()?,
1480                    r.try_get(3).db()?,
1481                    r.try_get(4).db()?,
1482                    r.try_get(5).db()?,
1483                    &r.try_get::<_, String>(6).db()?,
1484                    &r.try_get::<_, String>(7).db()?,
1485                    &r.try_get::<_, String>(8).db()?,
1486                    r.try_get(9).db()?,
1487                )?;
1488                entries.insert(r.try_get::<_, i64>(0).db()?, entry);
1489            }
1490            let mut values = HashMap::new();
1491            for r in c.client.query("SELECT id, owner, key, value, label, aliases FROM key_values WHERE id = ANY($1)", &[&value_ids]).db()? {
1492                values.insert(
1493                    r.try_get::<_, i64>(0).db()?,
1494                    (r.try_get::<_, String>(1).db()?, r.try_get::<_, String>(2).db()?, r.try_get::<_, String>(3).db()?, r.try_get::<_, String>(4).db()?, r.try_get::<_, Vec<String>>(5).db()?),
1495                );
1496            }
1497            let mut hits = Vec::with_capacity(order.len());
1498            for (kind, id, dist) in order {
1499                let score = 1.0 - dist;
1500                if kind == "entry" {
1501                    if let Some(entry) = entries.remove(&id) {
1502                        hits.push(Hit::Entry { id, entry, score });
1503                    }
1504                } else if let Some((owner, key, value, label, aliases)) = values.remove(&id) {
1505                    hits.push(Hit::Value { id, owner, key, value, label, aliases, score });
1506                }
1507            }
1508            Ok(hits)
1509        })
1510    }
1511
1512    fn put_embeddings(&self, model: &str, items: &[Embedding]) -> Result<()> {
1513        self.vectors_or_unsupported()?;
1514        check_model(model)?;
1515        let lits: Vec<String> = items.iter().map(|i| vector_literal(&i.vec)).collect::<Result<_>>()?;
1516        if items.is_empty() {
1517            return Ok(());
1518        }
1519        self.run("put_embeddings", |c| {
1520            let mut t = c.client.transaction().db()?;
1521            for (item, lit) in items.iter().zip(&lits) {
1522                let (exists, what) = match item.ref_kind {
1523                    EmbedRef::Entry => ("SELECT 1 FROM catalog_entries WHERE id = $1", "catalog entry"),
1524                    EmbedRef::Value => ("SELECT 1 FROM key_values WHERE id = $1", "dictionary value"),
1525                };
1526                if t.query_opt(exists, &[&item.ref_id]).db()?.is_none() {
1527                    return Err(Error::NotFound { what, key: item.ref_id.to_string() });
1528                }
1529                t.execute(
1530                    "INSERT INTO embeddings (ref_kind, ref_id, model, vec) VALUES ($1, $2, $3, $4::text::vector)
1531                     ON CONFLICT (ref_kind, ref_id, model) DO UPDATE SET vec = EXCLUDED.vec",
1532                    &[&item.ref_kind.as_str(), &item.ref_id, &model, lit],
1533                )
1534                .db()?;
1535            }
1536            t.commit().db()?;
1537            Ok(())
1538        })
1539    }
1540
1541    fn pending_embeddings(&self, model: &str, limit: usize) -> Result<Vec<PendingEmbedding>> {
1542        if !self.vectors {
1543            return Ok(Vec::new());
1544        }
1545        check_model(model)?;
1546        if limit == 0 {
1547            return Ok(Vec::new());
1548        }
1549        self.run("pending_embeddings", |c| {
1550            let rows = c
1551                .client
1552                .query(
1553                    "SELECT k, id, t FROM (
1554                         SELECT 'entry' AS k, e.id AS id,
1555                                CASE WHEN e.label = '' THEN e.description ELSE e.label || '. ' || e.description END AS t
1556                           FROM catalog_entries e
1557                          WHERE NOT EXISTS (SELECT 1 FROM embeddings m WHERE m.ref_kind = 'entry' AND m.ref_id = e.id AND m.model = $1)
1558                         UNION ALL
1559                         SELECT 'value', v.id, CASE WHEN v.label = '' THEN v.value ELSE v.label END
1560                           FROM key_values v
1561                          WHERE NOT EXISTS (SELECT 1 FROM embeddings m WHERE m.ref_kind = 'value' AND m.ref_id = v.id AND m.model = $1)
1562                     ) x
1563                     ORDER BY CASE k WHEN 'entry' THEN 0 ELSE 1 END, id LIMIT $2",
1564                    &[&model, &as_i64(limit)],
1565                )
1566                .db()?;
1567            rows.iter()
1568                .map(|r| {
1569                    let ref_kind = match r.try_get::<_, String>(0).db()?.as_str() {
1570                        "entry" => EmbedRef::Entry,
1571                        _ => EmbedRef::Value,
1572                    };
1573                    Ok(PendingEmbedding { ref_kind, ref_id: r.try_get(1).db()?, text: r.try_get(2).db()? })
1574                })
1575                .collect()
1576        })
1577    }
1578
1579    fn vector_available(&self) -> bool {
1580        self.vectors
1581    }
1582
1583    fn log_miss(&self, query: &str) -> Result<()> {
1584        let Some(q) = miss_text(query) else { return Ok(()) };
1585        self.run("log_miss", |c| {
1586            let mut t = c.client.transaction().db()?;
1587            t.execute("INSERT INTO find_misses (query) VALUES ($1)", &[&q]).db()?;
1588            // Keep the newest FIND_MISSES_CAP rows: prune the oldest beyond that.
1589            t.execute(
1590                "DELETE FROM find_misses WHERE ctid IN (SELECT ctid FROM find_misses ORDER BY at
1591                     LIMIT GREATEST((SELECT count(*) FROM find_misses) - $1, 0))",
1592                &[&as_i64(FIND_MISSES_CAP)],
1593            )
1594            .db()?;
1595            t.commit().db()?;
1596            Ok(())
1597        })
1598    }
1599
1600    fn put_function_test(&self, test: &FunctionTest) -> Result<bool> {
1601        let (total, covered) = crate::functions::check_test(test)?;
1602        self.run("put_function_test", |c| {
1603            let st = c.stmt(Q::FunctionTestPut)?;
1604            let n = c
1605                .client
1606                .execute(
1607                    &st,
1608                    &[
1609                        &test.fn_hash,
1610                        &test.case,
1611                        &test.test_json,
1612                        &test.signed_by,
1613                        &test.last_run_at,
1614                        &test.last_result,
1615                        &test.last_detail,
1616                        &total,
1617                        &covered,
1618                    ],
1619                )
1620                .db()?;
1621            Ok(n == 1)
1622        })
1623    }
1624
1625    fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>> {
1626        check_hex(fn_hash, 64, "fn_hash")?;
1627        self.run("function_tests", |c| {
1628            let st = c.stmt(Q::FunctionTestsOf)?;
1629            let rows = c.client.query(&st, &[&fn_hash]).db()?;
1630            rows.iter().map(function_test_row).collect()
1631        })
1632    }
1633
1634    fn record_function_test(
1635        &self,
1636        fn_hash: &str,
1637        case: &str,
1638        run_at: &str,
1639        result: &str,
1640        detail: &str,
1641    ) -> Result<bool> {
1642        check_hex(fn_hash, 64, "fn_hash")?;
1643        crate::functions::check_case(case)?;
1644        check_instant(run_at, "run_at")?;
1645        crate::functions::check_result(result)?;
1646        self.run("record_function_test", |c| {
1647            let st = c.stmt(Q::FunctionTestRecord)?;
1648            let n = c.client.execute(&st, &[&run_at, &result, &detail, &fn_hash, &case]).db()?;
1649            Ok(n == 1)
1650        })
1651    }
1652
1653    fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()> {
1654        check_hex(fn_hash, 64, "fn_hash")?;
1655        let (total, covered) = crate::functions::branch_counts(total, covered)?;
1656        self.run("set_function_branches", |c| {
1657            let st = c.stmt(Q::FunctionBranches)?;
1658            c.client.execute(&st, &[&fn_hash, &total, &covered]).db()?;
1659            Ok(())
1660        })
1661    }
1662
1663    fn function_readers(&self, name: &str) -> Result<Vec<String>> {
1664        check_function_name(name, "name")?;
1665        self.run("function_readers", |c| get_strings(c, Q::FunctionReaders, name))
1666    }
1667
1668    fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>> {
1669        check_hex(fn_hash, 64, "fn_hash")?;
1670        self.run("bound_names", |c| get_strings(c, Q::BoundNames, fn_hash))
1671    }
1672
1673    fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
1674        check_hex(fn_hash, 64, "fn_hash")?;
1675        for (case, name) in names {
1676            crate::functions::check_case(case)?;
1677            check_function_name(name, "name")?;
1678        }
1679        if names.is_empty() {
1680            return Ok(0);
1681        }
1682        let cases: Vec<String> = names.iter().map(|(c, _)| c.clone()).collect();
1683        let fn_names: Vec<String> = names.iter().map(|(_, n)| n.clone()).collect();
1684        self.run("name_function_tests", |c| {
1685            let st = c.stmt(Q::FunctionTestName)?;
1686            c.client.execute(&st, &[&fn_hash, &cases, &fn_names]).db()
1687        })
1688    }
1689
1690    fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
1691        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1692        self.run("unnamed_function_tests", |c| {
1693            let st = c.stmt(Q::FunctionTestsUnnamed)?;
1694            let rows = c.client.query(&st, &[&limit]).db()?;
1695            rows.iter().map(function_test_row).collect()
1696        })
1697    }
1698
1699    fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
1700        check_hex(fn_hash, 64, "fn_hash")?;
1701        self.run("function_test_summary", |c| {
1702            let st = c.stmt(Q::FunctionTestSummary)?;
1703            let r = c.client.query_one(&st, &[&fn_hash, &fn_name]).db()?;
1704            // The counts are bigint, the branch counts integer (at least zero): exact casts.
1705            let count = |i: usize| -> Result<u64> { Ok(r.try_get::<_, i64>(i).db()? as u64) };
1706            let total: i32 = r.try_get(6).db()?;
1707            let covered: i32 = r.try_get(7).db()?;
1708            Ok(TestSummary {
1709                count: count(0)?,
1710                pass: count(1)?,
1711                fail: count(2)?,
1712                error: count(3)?,
1713                not_run: count(4)?,
1714                last_run_at: r.try_get(5).db()?,
1715                branches_total: total as u32,
1716                branches_covered: covered as u32,
1717            })
1718        })
1719    }
1720
1721    fn function_tests_page(
1722        &self,
1723        fn_hash: &str,
1724        fn_name: Option<&str>,
1725        after_case: Option<&str>,
1726        limit: usize,
1727    ) -> Result<Vec<FunctionTest>> {
1728        check_hex(fn_hash, 64, "fn_hash")?;
1729        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1730        self.run("function_tests_page", |c| {
1731            let rows = match fn_name {
1732                None => {
1733                    let st = c.stmt(Q::FunctionTestsPage)?;
1734                    c.client.query(&st, &[&fn_hash, &after_case, &limit]).db()?
1735                }
1736                Some(name) => {
1737                    let st = c.stmt(Q::FunctionTestsPageNamed)?;
1738                    c.client.query(&st, &[&fn_hash, &name, &after_case, &limit]).db()?
1739                }
1740            };
1741            rows.iter().map(function_test_row).collect()
1742        })
1743    }
1744
1745    fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
1746        check_hex(fn_hash, 64, "fn_hash")?;
1747        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1748        self.run("stored_receipts_of", |c| {
1749            let st = c.stmt(Q::StoredReceiptsOf)?;
1750            let rows = c.client.query(&st, &[&fn_hash, &ns, &fn_name, &limit]).db()?;
1751            rows.iter().map(|r| r.try_get::<_, Vec<u8>>(0).db()).collect()
1752        })
1753    }
1754
1755    fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
1756        check_instant(asof, "asof")?;
1757        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1758        let v = slice.to_value();
1759        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1760            return self.run("slice_values_limit", |c| {
1761                // The statement of slice_values, with its LIMIT: the same order (tx).
1762                let sql = format!("{} LIMIT $5", Q::VersionsBetweenValues.sql());
1763                let rows = c.client.query(sql.as_str(), &[&cell_id, &from, &to, &asof, &limit]).db()?;
1764                rows.iter().map(|r| value_row(r, &cell_id)).collect()
1765            });
1766        }
1767        let pattern = Pattern::of(&v)?;
1768        self.run("slice_values_limit", |c| pattern.values_limited(c, asof, limit))
1769    }
1770
1771    fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
1772        check_hex(cell_id, 64, "cell_id")?;
1773        check_instant(from, "from")?;
1774        check_instant(to, "to")?;
1775        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1776        self.run("versions_limit", |c| {
1777            let st = c.stmt(Q::VersionRangeLimit)?;
1778            let rows = c.client.query(&st, &[&cell_id, &from, &to, &limit]).db()?;
1779            PgStore::version_rows(&rows, cell_id)
1780        })
1781    }
1782
1783    fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
1784        check_hex(fn_hash, 64, "fn_hash")?;
1785        self.run("stored_cell_count", |c| {
1786            let st = c.stmt(Q::StoredCellCount)?;
1787            let n: i64 = c.client.query_one(&st, &[&fn_hash, &ns, &fn_name]).db()?.try_get(0).db()?;
1788            Ok(n as u64)
1789        })
1790    }
1791
1792    fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
1793        self.run("has_key_value", |c| {
1794            let st = c.stmt(Q::DictionaryHas)?;
1795            c.client.query_one(&st, &[&owner, &key, &value]).db()?.try_get(0).db()
1796        })
1797    }
1798
1799    fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
1800        self.run("key_value_count", |c| {
1801            let st = c.stmt(Q::DictionaryCount)?;
1802            let n: i64 = c.client.query_one(&st, &[&owner, &key]).db()?.try_get(0).db()?;
1803            Ok(n as u64)
1804        })
1805    }
1806
1807    fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
1808        if owner.is_empty() || owner.len() > 512 || key.is_empty() || key.len() > 128 {
1809            return Err(invalid("key", "an owner of 1 to 512 bytes and a key of 1 to 128 bytes"));
1810        }
1811        self.run("mark_key_open", |c| {
1812            let st = c.stmt(Q::KeyOpenPut)?;
1813            c.client.execute(&st, &[&owner, &key]).db()?;
1814            Ok(())
1815        })
1816    }
1817
1818    fn open_key_count(&self) -> Result<u64> {
1819        self.run("open_key_count", |c| {
1820            let st = c.stmt(Q::OpenKeyCount)?;
1821            let n: i64 = c.client.query_one(&st, &[]).db()?.try_get(0).db()?;
1822            Ok(n as u64)
1823        })
1824    }
1825
1826    fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
1827        self.run("key_is_open", |c| {
1828            let st = c.stmt(Q::KeyIsOpen)?;
1829            c.client.query_one(&st, &[&owner, &key]).db()?.try_get(0).db()
1830        })
1831    }
1832
1833    fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
1834        self.run("catalog_entry", |c| {
1835            let st = c.stmt(Q::CatalogEntryNamed)?;
1836            let Some(r) = c.client.query_opt(&st, &[&name]).db()? else { return Ok(None) };
1837            entry_from_columns(
1838                &r.try_get::<_, String>(0).db()?,
1839                r.try_get(1).db()?,
1840                r.try_get(2).db()?,
1841                r.try_get(3).db()?,
1842                r.try_get(4).db()?,
1843                &r.try_get::<_, String>(5).db()?,
1844                &r.try_get::<_, String>(6).db()?,
1845                &r.try_get::<_, String>(7).db()?,
1846                r.try_get(8).db()?,
1847            )
1848            .map(Some)
1849        })
1850    }
1851
1852    fn catalog_summary(&self) -> Result<Summary> {
1853        self.run("catalog_summary", |c| {
1854            let mut entries = Vec::new();
1855            for r in c.client.query(
1856                "SELECT e.kind, e.name, e.label,
1857                        CASE WHEN e.kind = 'function' THEN (SELECT count(*) FROM cells x WHERE x.fn_hash = e.hash) ELSE 0 END
1858                   FROM catalog_entries e ORDER BY e.kind COLLATE \"C\", e.name COLLATE \"C\"",
1859                &[],
1860            ).db()? {
1861                let kind = CatalogKind::parse(&r.try_get::<_, String>(0).db()?)
1862                    .ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
1863                entries.push(SummaryEntry { kind, name: r.try_get(1).db()?, label: r.try_get(2).db()?, n_cells: r.try_get(3).db()? });
1864            }
1865            let mut dictionaries = Vec::new();
1866            let groups = c.client.query(
1867                "SELECT owner, key, count(*) FROM key_values GROUP BY owner, key ORDER BY owner COLLATE \"C\", key COLLATE \"C\"",
1868                &[],
1869            ).db()?;
1870            for g in groups {
1871                let (owner, key): (String, String) = (g.try_get(0).db()?, g.try_get(1).db()?);
1872                let mut values = Vec::new();
1873                for r in c.client.query(
1874                    "SELECT value, label, n_cells FROM key_values WHERE owner = $1 AND key = $2
1875                      ORDER BY value COLLATE \"C\" LIMIT $3",
1876                    &[&owner, &key, &as_i64(SUMMARY_VALUES)],
1877                ).db()? {
1878                    values.push(DictionaryValue { value: r.try_get(0).db()?, label: r.try_get(1).db()?, n_cells: r.try_get(2).db()? });
1879                }
1880                dictionaries.push(Dictionary { owner, key, n_values: g.try_get(2).db()?, values });
1881            }
1882            Ok(Summary { entries, dictionaries })
1883        })
1884    }
1885}
1886
1887impl Pattern {
1888    /// The members as of `asof`, in key order.
1889    fn members(&self, c: &mut Conn, asof: &str) -> Result<Vec<SliceMember>> {
1890        let qs = [Q::SliceMembersAll, Q::SliceMembersText, Q::SliceMembersNum];
1891        self.rows(c, asof, qs, 4, member_row, |m| &m.version.cell_id)
1892    }
1893
1894    /// The members' values as of `asof`, in key order.
1895    fn values(&self, c: &mut Conn, asof: &str) -> Result<Vec<SliceValue>> {
1896        let qs = [Q::SliceValuesAll, Q::SliceValuesText, Q::SliceValuesNum];
1897        self.rows(c, asof, qs, 9, value_row, |m| &m.version.cell_id)
1898    }
1899
1900    /// The members' values as of `asof`, in key order, at most `limit`: the statement of
1901    /// `values` with the key order and the LIMIT in SQL. The key order of `cmp_keys` is, per
1902    /// key argument by name, the type's name, then the number (exact) or the text.
1903    fn values_limited(&self, c: &mut Conn, asof: &str, limit: i64) -> Result<Vec<SliceValue>> {
1904        let (drive, _) = self.drive(c, false)?;
1905        let [names, kinds, types, los, his] = self.columns();
1906        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
1907        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
1908        let (base, d_name, d_ty, d_lo, d_hi) = match drive {
1909            None => (Q::SliceValuesAll, "", "", "", ""),
1910            Some(a) => {
1911                let q = if a.ty == "number" { Q::SliceValuesNum } else { Q::SliceValuesText };
1912                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
1913            }
1914        };
1915        // $16.. name each key argument; its order is the type, then the number, then the text.
1916        let mut order = Vec::with_capacity(keys.len() * 3 + 1);
1917        for i in 0..keys.len() {
1918            let p = 16 + i;
1919            let of =
1920                |col: &str| format!("(SELECT a.{col} FROM cell_args a WHERE a.cell_id = c.cell_id AND a.name = ${p})");
1921            order.push(format!("{} COLLATE \"C\"", of("type")));
1922            order.push(of("num"));
1923            order.push(format!("{} COLLATE \"C\"", of("value")));
1924        }
1925        order.push("c.cell_id".to_string());
1926        let sql = format!("{} ORDER BY {} LIMIT ${}", base.sql(), order.join(", "), 16 + keys.len());
1927        // The parameters the base statement does not use (the drive's, when there is none) are
1928        // typed as its statement types them: the text of the statement alone would not say.
1929        let mut param_types = base.types().to_vec();
1930        param_types.extend(std::iter::repeat_n(postgres::types::Type::TEXT, keys.len()));
1931        param_types.push(postgres::types::Type::INT8);
1932        let st = c.client.prepare_typed(sql.as_str(), &param_types).db()?;
1933        let mut params: Vec<&(dyn postgres::types::ToSql + Sync)> = vec![
1934            &self.fn_hash,
1935            &self.ns,
1936            &self.fn_name,
1937            &nargs,
1938            &asof,
1939            &names,
1940            &kinds,
1941            &types,
1942            &los,
1943            &his,
1944            &keys,
1945            &d_name,
1946            &d_ty,
1947            &d_lo,
1948            &d_hi,
1949        ];
1950        for k in &keys {
1951            params.push(k);
1952        }
1953        params.push(&limit);
1954        let rows = c.client.query(&st, &params).db()?;
1955        rows.iter()
1956            .map(|r| {
1957                let cell_id: String = r.try_get(9).db()?;
1958                value_row(r, &cell_id)
1959            })
1960            .collect()
1961    }
1962
1963    /// The cells with a computed version answering as of `asof`, in cell id order, at most
1964    /// `limit` (`computed_cells`); the candidates narrowed as the member queries narrow them.
1965    fn computed_cells(&self, c: &mut Conn, asof: &str, limit: i64) -> Result<Vec<Cell>> {
1966        let (drive, _) = self.drive(c, false)?;
1967        let [names, kinds, types, los, his] = self.columns();
1968        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
1969        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
1970        let (q, d_name, d_ty, d_lo, d_hi) = match drive {
1971            None => (Q::ComputedCellsAll, "", "", "", ""),
1972            Some(a) => {
1973                let q = if a.ty == "number" { Q::ComputedCellsNum } else { Q::ComputedCellsText };
1974                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
1975            }
1976        };
1977        let st = c.stmt(q)?;
1978        let rows = c
1979            .client
1980            .query(
1981                &st,
1982                &[
1983                    &self.fn_hash,
1984                    &self.ns,
1985                    &self.fn_name,
1986                    &nargs,
1987                    &asof,
1988                    &names,
1989                    &kinds,
1990                    &types,
1991                    &los,
1992                    &his,
1993                    &keys,
1994                    &d_name,
1995                    &d_ty,
1996                    &d_lo,
1997                    &d_hi,
1998                    &limit,
1999                ],
2000            )
2001            .db()?;
2002        rows.iter().map(cell_row).collect()
2003    }
2004
2005    /// The constraint columns of the member and change queries ($6-$10).
2006    fn columns(&self) -> [Vec<String>; 5] {
2007        let col = |f: fn(&Constraint) -> &str| -> Vec<String> { self.args.iter().map(|a| f(a).to_string()).collect() };
2008        [
2009            col(|a| a.name.as_str()),
2010            col(|a| a.kind.as_str()),
2011            col(|a| a.ty.as_str()),
2012            col(|a| a.lo.as_str()),
2013            col(|a| a.hi.as_str()),
2014        ]
2015    }
2016
2017    /// Whether a matching cell has a stored version answering from after `asof`: from
2018    /// whichever side is smaller (both probed, up to 10,001), the function's receipts with an
2019    /// asof after `asof` (then each one's cell checked against the slice), or the slice's
2020    /// candidate cells (then each one's receipts by cell and asof).
2021    fn changed_after(&self, c: &mut Conn, asof: &str) -> Result<bool> {
2022        let (drive, candidates) = self.drive(c, true)?;
2023        let st = c.stmt(Q::ProbeRecent)?;
2024        let recent: i64 = c.client.query_one(&st, &[&self.fn_hash, &asof]).db()?.try_get(0).db()?;
2025        let qs = if recent <= candidates.unwrap_or(i64::MAX) {
2026            [Q::ChangedRecent; 3]
2027        } else {
2028            [Q::ChangedCandAll, Q::ChangedCandText, Q::ChangedCandNum]
2029        };
2030        let rows = self.query(c, asof, qs, drive)?;
2031        match rows.first() {
2032            Some(r) => r.try_get(0).db(),
2033            None => Ok(false),
2034        }
2035    }
2036
2037    /// The bound or ranged argument holding the fewest cells (probed, up to 10,001, when
2038    /// there are several, or when `count` asks), else none (every cell of the function); and
2039    /// the number of candidates when probed.
2040    fn drive(&self, c: &mut Conn, count: bool) -> Result<(Option<&Constraint>, Option<i64>)> {
2041        let mut probe = |a: Option<&Constraint>| -> Result<i64> {
2042            match a {
2043                None => {
2044                    let st = c.stmt(Q::ProbeCells)?;
2045                    c.client.query_one(&st, &[&self.fn_hash]).db()?.try_get(0).db()
2046                }
2047                Some(a) => {
2048                    let st = c.stmt(if a.ty == "number" { Q::SliceProbeNum } else { Q::SliceProbeText })?;
2049                    c.client.query_one(&st, &[&self.fn_hash, &a.name, &a.ty, &a.lo, &a.hi]).db()?.try_get(0).db()
2050                }
2051            }
2052        };
2053        let constrained: Vec<&Constraint> = self.args.iter().filter(|a| a.kind != Kind::Open).collect();
2054        Ok(match constrained.as_slice() {
2055            [] => (None, if count { Some(probe(None)?) } else { None }),
2056            [one] => (Some(*one), if count { Some(probe(Some(one))?) } else { None }),
2057            several => {
2058                let mut best: Option<(i64, &Constraint)> = None;
2059                for a in several {
2060                    let n = probe(Some(a))?;
2061                    if best.is_none_or(|(m, _)| n < m) {
2062                        best = Some((n, a));
2063                    }
2064                }
2065                (best.map(|(_, a)| a), best.map(|(n, _)| n))
2066            }
2067        })
2068    }
2069
2070    /// Runs one of a family of slice queries `qs` (all cells, a text range, a number range)
2071    /// with the slice's parameters and the candidates narrowed by `drive`.
2072    fn query(&self, c: &mut Conn, asof: &str, qs: [Q; 3], drive: Option<&Constraint>) -> Result<Vec<postgres::Row>> {
2073        let [names, kinds, types, los, his] = self.columns();
2074        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
2075        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
2076        let (q, d_name, d_ty, d_lo, d_hi) = match drive {
2077            None => (qs[0], "", "", "", ""),
2078            Some(a) => {
2079                let q = if a.ty == "number" { qs[2] } else { qs[1] };
2080                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
2081            }
2082        };
2083        let st = c.stmt(q)?;
2084        c.client
2085            .query(
2086                &st,
2087                &[
2088                    &self.fn_hash,
2089                    &self.ns,
2090                    &self.fn_name,
2091                    &nargs,
2092                    &asof,
2093                    &names,
2094                    &kinds,
2095                    &types,
2096                    &los,
2097                    &his,
2098                    &keys,
2099                    &d_name,
2100                    &d_ty,
2101                    &d_lo,
2102                    &d_hi,
2103                ],
2104            )
2105            .db()
2106    }
2107
2108    /// The rows of one of the member queries `qs` (all cells, a text range, a number range),
2109    /// each made into a `T` (the cell id in column `at`, the key after it), in key order.
2110    fn rows<T>(
2111        &self,
2112        c: &mut Conn,
2113        asof: &str,
2114        qs: [Q; 3],
2115        at: usize,
2116        make: impl Fn(&postgres::Row, &str) -> Result<T>,
2117        cell_of: impl Fn(&T) -> &String,
2118    ) -> Result<Vec<T>> {
2119        let (drive, _) = self.drive(c, false)?;
2120        let rows = self.query(c, asof, qs, drive)?;
2121        let mut out: Vec<(Vec<String>, T)> = Vec::with_capacity(rows.len());
2122        for r in &rows {
2123            let cell_id: String = r.try_get(at).db()?;
2124            let key: Vec<String> = r.try_get(at + 1).db()?;
2125            out.push((key, make(r, &cell_id)?));
2126        }
2127        out.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
2128        Ok(out.into_iter().map(|(_, m)| m).collect())
2129    }
2130}
2131
2132/// Whether a word can be matched by the SQL prefilter exactly: JSON text escapes `"` and `\`
2133/// and control characters, and a word with them is matched in Rust only.
2134fn pg_safe(word: &str) -> bool {
2135    !word.chars().any(|c| c == '"' || c == '\\' || c.is_control())
2136}
2137
2138/// The `AND (...)` prefilter of a text search over `fields` (SQL expressions of text): one
2139/// clause per word the SQL can match, each word a LIKE pattern over lower-cased fields, and
2140/// the parameters they take (numbered from $1).
2141fn like_where(words: &Words, fields: &[&str]) -> (String, Vec<String>) {
2142    let mut sql = String::new();
2143    let mut params = Vec::new();
2144    for i in 0..words.len() {
2145        if let Some(p) = words.pattern(i, pg_safe) {
2146            params.push(p);
2147            let n = params.len();
2148            let ors: Vec<String> = fields.iter().map(|f| format!("lower({f}) LIKE ${n} ESCAPE '!'")).collect();
2149            sql.push_str(&format!(" AND ({})", ors.join(" OR ")));
2150        }
2151    }
2152    (sql, params)
2153}
2154
2155/// Parameters for a query built at run time.
2156fn as_refs(params: &[String]) -> Vec<&(dyn postgres::types::ToSql + Sync)> {
2157    params.iter().map(|p| p as &(dyn postgres::types::ToSql + Sync)).collect()
2158}
2159
2160/// A function test row of `function_tests`, in the column order of `FunctionTestsOf`.
2161fn function_test_row(r: &postgres::Row) -> Result<FunctionTest> {
2162    // The branch counts are `integer` with a check of at least zero: an `as` is exact.
2163    let total: i32 = r.try_get(7).db()?;
2164    let covered: i32 = r.try_get(8).db()?;
2165    Ok(FunctionTest {
2166        fn_hash: r.try_get(0).db()?,
2167        case: r.try_get(1).db()?,
2168        test_json: r.try_get(2).db()?,
2169        signed_by: r.try_get(3).db()?,
2170        last_run_at: r.try_get(4).db()?,
2171        last_result: r.try_get(5).db()?,
2172        last_detail: r.try_get(6).db()?,
2173        branches_total: total as u32,
2174        branches_covered: covered as u32,
2175    })
2176}