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_catalog_ext, check_key_values, check_model,
8    entry_ext, entry_from_columns, entry_text, invalid, miss_text, parse_facets, rank, value_text, vector_literal,
9    CatalogRow, Words, SUMMARY_VALUES,
10};
11use crate::error::{Db, Error, Result};
12use crate::listings::{
13    check_listed_host, check_listing, listing_facets_json, parse_subjects, same_listing, subjects_json,
14};
15use crate::pg_unstable::Connector;
16use crate::pool::{Conn, Pool, PoolOptions, Pooled};
17use crate::slices::{check_entry, cmp_keys, is_hash, is_instant, version_slice, Constraint, Kind, Pattern};
18use crate::sql::Q;
19use crate::{
20    later_than, not_canonical_class, parse_receipt, stored_value, unbound, Binding, CatalogEntry, CatalogEntryExt,
21    CatalogKind, CellWrite, ClassBinding, Dictionary, DictionaryValue, EmbedRef, Embedding, FacetedEntry, FunctionTest,
22    Hit, KeyValue, MemberSet, Namespace, Parsed, PendingEmbedding, SliceMember, SliceValue, Store, Summary,
23    SummaryEntry, TestSummary, Version, FIND_MISSES_CAP,
24};
25use crate::{ListedHost, Listing, ListingWrite};
26use datumesh_core::lexical::{check_dns_name, check_function_name, check_hex, check_instant};
27use datumesh_core::{
28    json, keys_from_response, sha256_hex, verify, Cell, ClassDescriptor, ErrorCode, FunctionDescriptor, Keys, Manifest,
29    Resolver, Scalar, Slice, Type,
30};
31
32/// The store on PostgreSQL, with a connection pool. `Send + Sync`: share one per process
33/// (behind an `Arc`); each call checks a connection out for its duration.
34///
35/// Every `put_*` is one transaction. [`Store`] methods return errors: a malformed argument
36/// is [`Error::Invalid`] (no query is made), a database failure [`Error::Database`]. The
37/// [`Resolver`] methods answer both with `None`; a database failure is logged with
38/// `tracing` (target `datumesh_store`, level `error`).
39pub struct PgStore {
40    pool: Pool,
41    /// Whether the `embeddings` table exists (the `vector` extension was available when the
42    /// schema was migrated), looked at when the store was opened.
43    vectors: bool,
44    /// The recording clock (G9): the version's recorded time is the greater of its tx and this.
45    clock: Option<crate::RecordingClock>,
46    /// Set once the versions table is found to have the recorded column (migration 17).
47    recorded_schema: std::sync::atomic::AtomicBool,
48    /// How long the barrier waits (PoolOptions::barrier_timeout).
49    barrier_timeout: std::time::Duration,
50}
51
52impl std::fmt::Debug for PgStore {
53    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54        f.debug_struct("PgStore").finish_non_exhaustive()
55    }
56}
57
58impl PgStore {
59    /// Connects to a `postgres://` URL or `key=value` connection string with the default
60    /// [`PoolOptions`]: [`connect_with(url, PoolOptions::new())`](Self::connect_with).
61    pub fn connect(url: &str) -> Result<PgStore> {
62        PgStore::connect_with(url, PoolOptions::new())
63    }
64
65    /// Connects to a `postgres://` URL or `key=value` connection string, with a pool and TLS
66    /// roots as `options` say. One connection is opened at once, so a wrong URL, an
67    /// unreachable server or a refused certificate fails here; nothing else is done on it
68    /// (no statement is prepared, the schema is not looked at), so an empty database is fine
69    /// (create the schema with [`migrate::apply`](crate::migrate::apply)).
70    ///
71    /// TLS (rustls) is used as the URL's `sslmode` says: `disable` never, `prefer` (the
72    /// default) when the server offers it, `require` always. Whenever it is used, the
73    /// server's certificate and host name are verified, against the Mozilla roots plus the
74    /// roots added with [`PoolOptions::tls_root_certificates_pem`]; there is no way to
75    /// accept any certificate. So a server with `ssl=on` and a self-signed certificate (or
76    /// one from a private CA) fails even under the default `prefer`: add its CA, or connect
77    /// with `sslmode=disable`.
78    pub fn connect_with(url: &str, options: PoolOptions) -> Result<PgStore> {
79        let config = url.parse::<postgres::Config>().db()?;
80        let connector = Connector::new(config, &options)?;
81        let clock = options.recording_clock.clone().map(|c| c.0);
82        let barrier_timeout = options.barrier_timeout;
83        let mut store = PgStore::from_pool(Pool::new(Box::new(move || connector.connect()), options))?;
84        store.clock = clock;
85        store.barrier_timeout = barrier_timeout;
86        Ok(store)
87    }
88
89    /// A store on `pool`, after opening one connection.
90    pub(crate) fn from_pool(pool: Pool) -> Result<PgStore> {
91        let mut store = PgStore {
92            pool,
93            vectors: false,
94            clock: None,
95            recorded_schema: std::sync::atomic::AtomicBool::new(false),
96            barrier_timeout: std::time::Duration::from_secs(5),
97        };
98        let vectors: bool = {
99            let mut c = store.pool.get()?;
100            c.client.query_one("SELECT to_regclass('embeddings') IS NOT NULL", &[]).db()?.try_get(0).db()?
101        };
102        store.vectors = vectors;
103        Ok(store)
104    }
105
106    /// `Ok` where vectors are stored and searched; otherwise [`Error::Unsupported`].
107    fn vectors_or_unsupported(&self) -> Result<()> {
108        if self.vectors {
109            Ok(())
110        } else {
111            Err(Error::Unsupported("vectors need PostgreSQL with the vector extension (migration 9)".into()))
112        }
113    }
114
115    /// A pooled connection, held until dropped (migrations hold one throughout).
116    pub(crate) fn conn(&self) -> Result<Pooled<'_>> {
117        self.pool.get()
118    }
119
120    /// Prepares every SQL statement the store uses against the live schema, on a fresh
121    /// connection's behalf (no cached statement is reused), and returns how many there are.
122    /// Fails with the first statement the schema cannot serve.
123    pub fn check_statements(&self) -> Result<usize> {
124        let mut c = self.pool.get()?;
125        for q in Q::ALL {
126            c.client.prepare_typed(q.sql(), q.types()).db()?;
127        }
128        Ok(Q::ALL.len())
129    }
130
131    /// A [`Resolver`] lookup: a failure (logged by `run`) becomes `None`.
132    fn resolve<T>(&self, op: &'static str, f: impl FnOnce(&mut Conn) -> Result<Option<T>>) -> Option<T> {
133        self.run(op, f).ok().flatten()
134    }
135
136    /// Runs `f` on a pooled connection; a database or pool failure is logged.
137    fn run<T>(&self, op: &'static str, f: impl FnOnce(&mut Conn) -> Result<T>) -> Result<T> {
138        let result = self.pool.get().and_then(|mut c| f(&mut c));
139        if let Err(e @ (Error::Database(_) | Error::PoolTimeout)) = &result {
140            tracing::error!(target: "datumesh_store", op, error = %e, "database failure");
141        }
142        result
143    }
144
145    /// Versions from rows of (tx, receipt_hash, asof, withdrawn).
146    fn version_rows(rows: &[postgres::Row], cell_id: &str) -> Result<Vec<Version>> {
147        rows.iter().map(|r| version_row(r, cell_id)).collect()
148    }
149
150    /// A version (and its receipt's bytes) from a query answering
151    /// (tx, receipt_hash, asof, withdrawn, recorded, bytes) for (cell_id, asof).
152    fn asof_with_receipt(
153        &self,
154        op: &'static str,
155        q: Q,
156        cell_id: &str,
157        asof: &str,
158    ) -> Result<Option<(Version, Vec<u8>)>> {
159        check_hex(cell_id, 64, "cell_id")?;
160        check_instant(asof, "asof")?;
161        self.run(op, |c| {
162            let st = c.stmt(q)?;
163            let Some(row) = c.client.query_opt(&st, &[&cell_id, &asof]).db()? else { return Ok(None) };
164            Ok(Some((version_row(&row, cell_id)?, row.try_get(5).db()?)))
165        })
166    }
167
168    /// A version from a query answering (tx, receipt_hash, asof) for (cell_id, asof).
169    fn asof_version(&self, op: &'static str, q: Q, cell_id: &str, asof: &str) -> Result<Option<Version>> {
170        check_hex(cell_id, 64, "cell_id")?;
171        check_instant(asof, "asof")?;
172        self.run(op, |c| {
173            let st = c.stmt(q)?;
174            let rows = c.client.query(&st, &[&cell_id, &asof]).db()?;
175            Ok(PgStore::version_rows(&rows, cell_id)?.pop())
176        })
177    }
178}
179
180/// A version from a row of (tx, receipt_hash, asof, withdrawn, recorded, ...).
181fn version_row(r: &postgres::Row, cell_id: &str) -> Result<Version> {
182    Ok(Version {
183        cell_id: cell_id.to_string(),
184        tx: r.try_get(0).db()?,
185        receipt_hash: r.try_get(1).db()?,
186        asof: r.try_get(2).db()?,
187        withdrawn: r.try_get(3).db()?,
188        recorded: r.try_get(4).db()?,
189        seq: r.try_get::<_, i64>("seq").db()?,
190    })
191}
192
193/// A version from a row of (tx, receipt_hash, asof, recorded, ...) whose withdrawn versions are
194/// left out of the query (a member or a value of a slice).
195fn valued_version_row(r: &postgres::Row, cell_id: &str) -> Result<Version> {
196    Ok(Version {
197        cell_id: cell_id.to_string(),
198        tx: r.try_get(0).db()?,
199        receipt_hash: r.try_get(1).db()?,
200        asof: r.try_get(2).db()?,
201        withdrawn: false,
202        recorded: r.try_get(3).db()?,
203        seq: r.try_get::<_, i64>("seq").db()?,
204    })
205}
206
207/// A member from a row of (tx, receipt_hash, asof, bytes, ...): a slice's member, never withdrawn.
208fn member_row(r: &postgres::Row, cell_id: &str) -> Result<SliceMember> {
209    Ok(SliceMember { version: valued_version_row(r, cell_id)?, receipt: r.try_get(4).db()? })
210}
211
212/// A version-slice member from a row of (tx, receipt_hash, asof, withdrawn, bytes).
213fn versions_between_row(r: &postgres::Row, cell_id: &str) -> Result<SliceMember> {
214    Ok(SliceMember { version: version_row(r, cell_id)?, receipt: r.try_get(5).db()? })
215}
216
217/// A cell's arguments from the "name:type:value" items of the typed-argument index
218/// (`cell_args` holds every argument's type and lexical form).
219fn cell_args(items: Vec<String>) -> Result<datumesh_core::Args> {
220    let bad =
221        |what: &str| Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")));
222    let mut args = datumesh_core::Args::new();
223    for a in items {
224        let mut parts = a.splitn(3, ':');
225        let (Some(name), Some(t), Some(v)) = (parts.next(), parts.next(), parts.next()) else {
226            return Err(bad("argument"));
227        };
228        let ty = Type::from_name(t).ok_or_else(|| bad("type"))?;
229        args.insert(name.to_string(), datumesh_core::Arg::Value(Scalar::from_lexical(ty, v)?));
230    }
231    Ok(args)
232}
233
234/// A member's value and cell from a row of (tx, receipt_hash, asof, recorded, value_type, value,
235/// ns, fn, fn_hash, "name:type:value" of each argument, sort key): the cell is rebuilt from the
236/// typed-argument index.
237fn value_row(r: &postgres::Row, cell_id: &str) -> Result<SliceValue> {
238    let bad =
239        |what: &str| Error::Invalid(datumesh_core::Error::new(ErrorCode::CanonType, "$", format!("a stored {what}")));
240    let (ty, value): (String, String) = (r.try_get(4).db()?, r.try_get(5).db()?);
241    let ty = Type::from_name(&ty).ok_or_else(|| bad("type"))?;
242    let args = cell_args(r.try_get::<_, Vec<String>>(9).db()?)?;
243    let cell = Cell { args, fn_hash: r.try_get(8).db()?, fn_name: r.try_get(7).db()?, ns: r.try_get(6).db()? };
244    let sort_key: Vec<u8> = r.try_get(10).db()?;
245    Ok(SliceValue {
246        version: valued_version_row(r, cell_id)?,
247        value: Scalar::from_lexical(ty, &value)?,
248        cell,
249        sort_key,
250    })
251}
252
253/// A cell from a row of (ns, fn, fn_hash, "name:type:value" of each argument).
254fn cell_row(r: &postgres::Row) -> Result<Cell> {
255    Ok(Cell {
256        args: cell_args(r.try_get::<_, Vec<String>>(3).db()?)?,
257        fn_hash: r.try_get(2).db()?,
258        fn_name: r.try_get(1).db()?,
259        ns: r.try_get(0).db()?,
260    })
261}
262
263fn get_bytes(c: &mut Conn, q: Q, key: &str) -> Result<Option<Vec<u8>>> {
264    let st = c.stmt(q)?;
265    let row = c.client.query_opt(&st, &[&key]).db()?;
266    Ok(match row {
267        Some(r) => Some(r.try_get(0).db()?),
268        None => None,
269    })
270}
271
272fn get_strings(c: &mut Conn, q: Q, key: &str) -> Result<Vec<String>> {
273    let st = c.stmt(q)?;
274    let rows = c.client.query(&st, &[&key]).db()?;
275    rows.iter().map(|r| r.try_get(0).db()).collect()
276}
277
278impl Resolver for PgStore {
279    fn descriptor(&self, fn_hash: &str) -> Option<Cow<'_, [u8]>> {
280        if !is_hash(fn_hash) {
281            return None;
282        }
283        self.resolve("descriptor", |c| get_bytes(c, Q::DescriptorGet, fn_hash)).map(Cow::Owned)
284    }
285
286    fn receipt(&self, hash: &str) -> Option<Cow<'_, [u8]>> {
287        if !is_hash(hash) {
288            return None;
289        }
290        self.resolve("receipt", |c| get_bytes(c, Q::ReceiptGet, hash)).map(Cow::Owned)
291    }
292
293    /// The stored manifest of slice entry `entry` ([`Store::put_manifest`]), its canonical
294    /// form; `None` when there is none, or `entry` is not an entry (since 0.3.1).
295    fn manifest(&self, entry: &str) -> Option<Cow<'_, [u8]>> {
296        if check_entry(entry, "$").is_err() {
297            return None;
298        }
299        self.resolve("manifest", |c| get_bytes(c, Q::ManifestGet, entry)).map(Cow::Owned)
300    }
301
302    /// `Some` only for a `stored` function (descriptor `code.lang` is `stored`, and the store
303    /// has the descriptor): the value of the receipt of the version that answers as of
304    /// `asof`, [`stored_asof`](Store::stored_asof)'s: the latest version (by tx) with `tx <=
305    /// asof` whose receipt's asof is also `<= asof` (the core's testkit
306    /// `AnswerRule::TxAndAsof`). `None` for every other function, and when no version
307    /// answers. (Until 0.2.0 it looked at `tx` only, as [`version_asof`](Store::version_asof)
308    /// still does; the same when every receipt's asof is its tx.)
309    fn evaluate(&self, cell: &Cell, asof: &str) -> Option<Scalar> {
310        if !is_instant(asof) {
311            return None;
312        }
313        self.resolve("evaluate", |c| {
314            let Some(desc) = get_bytes(c, Q::DescriptorGet, &cell.fn_hash)? else { return Ok(None) };
315            match FunctionDescriptor::from_json(&desc) {
316                Ok(d) if d.lang == "stored" => {}
317                Ok(_) => return Ok(None),
318                Err(e) => {
319                    tracing::error!(target: "datumesh_store", fn_hash = %cell.fn_hash, error = %e, "stored descriptor does not parse");
320                    return Ok(None);
321                }
322            }
323            let st = c.stmt(Q::ValueAsof)?;
324            let Some(row) = c.client.query_opt(&st, &[&cell.id(), &asof]).db()? else { return Ok(None) };
325            let bytes: Vec<u8> = row.try_get(0).db()?;
326            match stored_value(&bytes) {
327                Ok(value) => Ok(value),
328                Err(e) => {
329                    tracing::error!(target: "datumesh_store", cell_id = %cell.id(), error = %e, "stored receipt does not parse");
330                    Ok(None)
331                }
332            }
333        })
334    }
335}
336
337/// The host of a fully qualified function name (`host/name`): what precedes the last `/`.
338fn name_host(fn_name: &str) -> &str {
339    fn_name.rsplit_once('/').map_or("", |(h, _)| h)
340}
341
342/// The namespace in `row`, whose columns from `at` are keydoc, validated_at, suspended_at,
343/// consecutive_failures, last_checked_at.
344fn namespace_row(host: &str, row: &postgres::Row, at: usize) -> Result<Namespace> {
345    let failures: i32 = row.try_get(at + 3).db()?;
346    Ok(Namespace {
347        host: host.to_string(),
348        keydoc: row.try_get(at).db()?,
349        validated_at: row.try_get(at + 1).db()?,
350        suspended_at: row.try_get(at + 2).db()?,
351        consecutive_failures: u32::try_from(failures).unwrap_or(0),
352        last_checked_at: row.try_get(at + 4).db()?,
353    })
354}
355
356/// The version-sequence lock (a fixed key). Every writer of versions takes it at the start of its
357/// transaction and holds it to commit, before it reads the recording time and takes the seq. So the seq
358/// and the recorded time follow commit order: a writer that waited records the time it holds the lock at,
359/// and `barrier` waits for the writers in flight. The trigger of migration 17 takes the same key (its
360/// literal is 7412030007).
361const VERSION_SEQ_LOCK: i64 = 7412030007;
362
363impl PgStore {
364    /// Whether the versions table has the recorded column, cached once it is found (a store never goes
365    /// back to an older schema; review item 6).
366    fn schema_has_recorded(&self, c: &mut Conn) -> Result<bool> {
367        if self.recorded_schema.load(std::sync::atomic::Ordering::Acquire) {
368            return Ok(true);
369        }
370        let has = has_recorded(c)?;
371        if has {
372            self.recorded_schema.store(true, std::sync::atomic::Ordering::Release);
373        }
374        Ok(has)
375    }
376
377    /// A failed check (`threshold` is `Some`) or a successful one (`None`) at `checked_at`.
378    fn record_check(
379        &self,
380        op: &'static str,
381        host: &str,
382        checked_at: &str,
383        threshold: Option<u32>,
384    ) -> Result<Option<Namespace>> {
385        check_dns_name(host, "host")?;
386        check_instant(checked_at, "checked_at")?;
387        let out = self.run(op, |c| {
388            let lock = c.stmt(Q::Lock)?;
389            let get = c.stmt(Q::NamespaceGet)?;
390            let put = c.stmt(Q::NamespaceCheck)?;
391            let mut t = c.client.transaction().db()?;
392            t.execute(&lock, &[&"namespaces", &host]).db()?;
393            let Some(row) = t.query_opt(&get, &[&host]).db()? else { return Ok(None) };
394            let mut ns = namespace_row(host, &row, 0)?;
395            if let Some(at) = &ns.last_checked_at {
396                if checked_at < at.as_str() {
397                    return Err(Error::NotLater {
398                        what: "namespace",
399                        key: host.to_string(),
400                        given: checked_at.to_string(),
401                        latest: at.clone(),
402                    });
403                }
404            }
405            crate::apply_check(&mut ns, checked_at, threshold);
406            let failures = i32::try_from(ns.consecutive_failures).unwrap_or(i32::MAX);
407            t.execute(&put, &[&host, &failures, &checked_at, &ns.suspended_at]).db()?;
408            t.commit().db()?;
409            Ok(Some(ns))
410        })?;
411        tracing::debug!(target: "datumesh_store", host, checked_at, ok = threshold.is_none(), "namespace check");
412        Ok(out)
413    }
414}
415
416/// Items per statement of `latest_many` and `receipts_many` (longer inputs are split).
417const MANY: usize = 10_000;
418
419/// The receipt's verdict against the keys of its signer host, as `put_receipt` gives it:
420/// `None` when it verifies.
421fn verdict(bytes: &[u8], keys: &Keys) -> Option<datumesh_core::Error> {
422    let out = verify(bytes, keys, None, None);
423    if out.ok {
424        return None;
425    }
426    Some(
427        out.error()
428            .unwrap_or_else(|| datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")),
429    )
430}
431
432/// `f` over `items` on up to `available_parallelism()` threads; the results in item order.
433fn parallel<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync) -> Vec<R> {
434    let threads = std::thread::available_parallelism().map_or(1, |n| n.get()).min(items.len());
435    if threads <= 1 {
436        return items.iter().map(f).collect();
437    }
438    let size = items.len().div_ceil(threads);
439    std::thread::scope(|s| {
440        let handles: Vec<_> = items
441            .chunks(size)
442            .map(|part| {
443                let f = &f;
444                s.spawn(move || part.iter().map(f).collect::<Vec<R>>())
445            })
446            .collect();
447        handles.into_iter().flat_map(|h| h.join().unwrap_or_else(|e| std::panic::resume_unwind(e))).collect()
448    })
449}
450
451/// A signer host's namespace as `put_receipt` and `put_version` read it: its key document
452/// (the keys it verifies with) and whether it is suspended, and since when.
453struct HostState {
454    keys: Keys,
455    suspended_at: Option<String>,
456}
457
458/// `put_cells` on one connection, in one transaction: the items in order, with the checks
459/// and the errors of `put_receipt` and `put_version` (see `Store::put_cells`).
460/// Whether the versions table has the recorded column (migration 17). A store on an older schema
461/// writes versions by tx, as 0.6.4 did, and migration 17 backfills their recorded time (decision B).
462fn has_recorded(c: &mut Conn) -> Result<bool> {
463    let st = c.stmt(Q::HasRecorded)?;
464    c.client.query_one(&st, &[]).db()?.try_get(0).db()
465}
466
467fn put_cells_in(
468    c: &mut Conn,
469    items: &[CellWrite<'_>],
470    prepared: Vec<Result<Parsed>>,
471    clock: Option<&crate::RecordingClock>,
472    has: bool,
473) -> Result<Vec<String>> {
474    let version_cells = || {
475        items
476            .iter()
477            .filter_map(|w| w.version)
478            .filter(|(cell, tx)| check_hex(cell, 64, "cell_id").is_ok() && check_instant(tx, "tx").is_ok())
479    };
480    let st_lock = c.stmt(Q::VersionLocksMany)?;
481    let st_vlock = c.stmt(Q::VersionSeqLock)?;
482    let st_many = c.stmt(Q::VersionsAtMany)?;
483    let st_signed_many = c.stmt(Q::VersionsLatestSignedMany)?;
484    let st_get = c.stmt(Q::ReceiptsGetMany)?;
485    let st_ns = c.stmt(Q::NamespacesGetMany)?;
486    let st_latest = c.stmt(if has { Q::VersionsLatestTxMany } else { Q::VersionsLatestTxManyLegacy })?;
487    let st_put = c.stmt(Q::ReceiptsPutMany)?;
488    let st_edges = c.stmt(Q::EdgesPutMany)?;
489    let st_slice_edges = c.stmt(Q::SliceEdgesPutMany)?;
490    let st_versions = c.stmt(if has { Q::VersionsPutMany } else { Q::VersionsPutManyLegacy })?;
491    let mut t = c.client.transaction().db()?;
492
493    // The version locks, in item order (as put_version takes them; one statement).
494    let mut locked: Vec<&str> = Vec::new();
495    for (cell, _) in version_cells() {
496        if !locked.contains(&cell) {
497            locked.push(cell);
498        }
499    }
500    if !locked.is_empty() {
501        t.execute(&st_lock, &[&locked]).db()?;
502        // The version lock, after the cell locks (the order put_version takes them in), before the reads;
503        // taken only when the batch has versions (decided 27 Nov, B4).
504        t.execute(&st_vlock, &[&VERSION_SEQ_LOCK]).db()?;
505    }
506
507    // What the store holds for the call: the receipts (by hash), the namespaces of the signer
508    // hosts and the latest tx of the version cells, all read after the locks.
509    let parsed: Vec<&Parsed> = prepared.iter().filter_map(|p| p.as_ref().ok()).collect();
510    let mut hashes: Vec<&str> = parsed.iter().map(|p| p.hash.as_str()).collect();
511    hashes.sort_unstable();
512    hashes.dedup();
513    let mut stored: HashMap<String, Vec<u8>> = HashMap::new();
514    if !hashes.is_empty() {
515        for row in t.query(&st_get, &[&hashes]).db()? {
516            stored.insert(row.try_get(0).db()?, row.try_get(1).db()?);
517        }
518    }
519    let mut hosts: Vec<&str> = parsed.iter().map(|p| p.host.as_str()).collect();
520    hosts.sort_unstable();
521    hosts.dedup();
522    let mut namespaces: HashMap<String, HostState> = HashMap::new();
523    if !hosts.is_empty() {
524        for row in t.query(&st_ns, &[&hosts]).db()? {
525            let host: String = row.try_get(0).db()?;
526            let doc: Vec<u8> = row.try_get(1).db()?;
527            let suspended_at: Option<String> = row.try_get(2).db()?;
528            let mut keys = Keys::new();
529            keys.insert_response(&host, 200, Some(&doc));
530            namespaces.insert(host, HostState { keys, suspended_at });
531        }
532    }
533    let mut cells: Vec<&str> = version_cells().map(|(cell, _)| cell).collect();
534    cells.sort_unstable();
535    cells.dedup();
536    let mut latest: HashMap<String, String> = HashMap::new();
537    if !cells.is_empty() {
538        for row in t.query(&st_latest, &[&cells]).db()? {
539            latest.insert(row.try_get(0).db()?, row.try_get(1).db()?);
540        }
541    }
542    // The batch's existing versions, in one statement (decided 27 Nov, B4): a (cell_id, tx) the store holds
543    // with the same receipt is a no-op, with another a refusal. `pending` is the same for the batch's own
544    // versions decided so far.
545    let mut existing: HashMap<(String, String), String> = HashMap::new();
546    let mut pending: HashMap<(String, String), String> = HashMap::new();
547    // The cells' latest signed tx, kept up to date as the batch's versions are decided (decided by the user,
548    // 27 Nov): a version not later than its cell's latest signed tx is refused.
549    let mut signed_latest: HashMap<String, String> = HashMap::new();
550    if !locked.is_empty() {
551        let pairs: Vec<(&str, &str)> = version_cells().collect();
552        let cs: Vec<&str> = pairs.iter().map(|p| p.0).collect();
553        let txs: Vec<&str> = pairs.iter().map(|p| p.1).collect();
554        for row in t.query(&st_many, &[&cs, &txs]).db()? {
555            existing.insert((row.try_get(0).db()?, row.try_get(1).db()?), row.try_get(2).db()?);
556        }
557        for row in t.query(&st_signed_many, &[&cells]).db()? {
558            signed_latest.insert(row.try_get(0).db()?, row.try_get(1).db()?);
559        }
560    }
561
562    // The signatures, on threads: every item not already stored with the same bytes (the
563    // others are not checked, as put_receipt's idempotence says). A namespace's keys are
564    // those of the stored key document; none stored is a host without keys.
565    let empty = Keys::new();
566    let keys_of = |host: &str| namespaces.get(host).map_or(&empty, |h| &h.keys);
567    let jobs: Vec<usize> = (0..items.len())
568        .filter(|&i| match &prepared[i] {
569            Ok(p) => stored.get(&p.hash) != Some(&p.canonical),
570            Err(_) => false,
571        })
572        .collect();
573    let mut verdicts: Vec<Option<Option<datumesh_core::Error>>> = vec![None; items.len()];
574    let checked = parallel(&jobs, |&i| {
575        let host = prepared[i].as_ref().map_or("", |p| p.host.as_str());
576        verdict(items[i].receipt, keys_of(host))
577    });
578    for (i, v) in jobs.into_iter().zip(checked) {
579        verdicts[i] = Some(v);
580    }
581
582    // In item order, as the loop of put_receipt and put_version would run them, against the
583    // state of the store plus the items before. The first failure is the call's error.
584    let mut out: Vec<String> = Vec::with_capacity(items.len());
585    let mut new: Vec<Parsed> = Vec::new();
586    let mut versions: Vec<(&str, &str, String, String)> = Vec::new();
587    for (i, pr) in prepared.into_iter().enumerate() {
588        let p = pr?;
589        let host_state = namespaces.get(&p.host);
590        let suspended = |host: &str| -> Result<()> {
591            match host_state.and_then(|h| h.suspended_at.as_ref()) {
592                // No new writes under a suspended namespace.
593                Some(since) => Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since.clone() }),
594                None => Ok(()),
595            }
596        };
597        // put_receipt: the stored copy with the same bytes is the receipt (no checks).
598        let is_stored = stored.get(&p.hash).is_some_and(|b| *b == p.canonical);
599        if !is_stored {
600            suspended(&p.host)?;
601            match verdicts[i].take() {
602                Some(Some(e)) => return Err(Error::Invalid(e)),
603                Some(None) => {}
604                None => unreachable!("an item not stored is checked"),
605            }
606            if stored.contains_key(&p.hash) {
607                return Err(Error::Conflict { hash: p.hash.clone() });
608            }
609            stored.insert(p.hash.clone(), p.canonical.clone());
610        }
611        // put_version, for the item's version.
612        if let Some((cell, tx)) = items[i].version {
613            check_hex(cell, 64, "cell_id")?;
614            check_instant(tx, "tx")?;
615            suspended(&p.host)?;
616            if p.cell_id != cell {
617                return Err(Error::Mismatch { what: "cell_id", expected: cell.to_string(), found: p.cell_id.clone() });
618            }
619            if p.tx != tx {
620                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: p.tx.clone() });
621            }
622            // The cell already has a version at this tx: the same receipt writes nothing; another is refused
623            // (review item 3).
624            let key = (cell.to_string(), tx.to_string());
625            let held: Option<String> = existing.get(&key).or_else(|| pending.get(&key)).cloned();
626            match held {
627                Some(h) if h == p.hash => {}
628                Some(_) => {
629                    return Err(Error::NotLater {
630                        what: "version",
631                        key: cell.to_string(),
632                        given: tx.to_string(),
633                        latest: tx.to_string(),
634                    })
635                }
636                None => {
637                    // The cell's latest signed tx: a version not later is refused (decided by the user, 27 Nov).
638                    if let Some(l) = signed_latest.get(cell) {
639                        if tx <= l.as_str() {
640                            return Err(Error::NotLater {
641                                what: "version",
642                                key: cell.to_string(),
643                                given: tx.to_string(),
644                                latest: l.clone(),
645                            });
646                        }
647                    }
648                    signed_latest.insert(cell.to_string(), tx.to_string());
649                    // Recorded under the lock (review item 2), and after the cell's latest (decided 27 Nov, B5).
650                    let base = if has { crate::recorded_at(clock, tx) } else { tx.to_string() };
651                    let recorded = match latest.get(cell) {
652                        Some(l) if has => crate::later_of(&base, &crate::instant_after(l)),
653                        _ => base,
654                    };
655                    if let Some(l) = latest.get(cell) {
656                        if recorded.as_str() <= l.as_str() {
657                            return Err(Error::NotLater {
658                                what: "version",
659                                key: cell.to_string(),
660                                given: recorded.clone(),
661                                latest: l.clone(),
662                            });
663                        }
664                    }
665                    latest.insert(cell.to_string(), recorded.clone());
666                    versions.push((cell, tx, p.hash.clone(), recorded));
667                    pending.insert(key, p.hash.clone());
668                }
669            }
670        }
671        out.push(p.hash.clone());
672        if !is_stored {
673            new.push(p);
674        }
675    }
676
677    // The writes. A receipt another transaction stored meanwhile must hold the same bytes.
678    if !new.is_empty() {
679        let hashes: Vec<&str> = new.iter().map(|p| p.hash.as_str()).collect();
680        let bytes: Vec<&[u8]> = new.iter().map(|p| p.canonical.as_slice()).collect();
681        let cells: Vec<&str> = new.iter().map(|p| p.cell_id.as_str()).collect();
682        let txs: Vec<&str> = new.iter().map(|p| p.tx.as_str()).collect();
683        let asofs: Vec<&str> = new.iter().map(|p| p.asof.as_str()).collect();
684        let fns: Vec<&str> = new.iter().map(|p| p.fn_hash.as_str()).collect();
685        let pubs: Vec<&str> = new.iter().map(|p| p.publisher.as_str()).collect();
686        let rows = t.query(&st_put, &[&hashes, &bytes, &cells, &txs, &asofs, &fns, &pubs]).db()?;
687        let mut got: HashSet<String> = HashSet::new();
688        for row in &rows {
689            got.insert(row.try_get(0).db()?);
690        }
691        let missing: Vec<&str> = hashes.iter().copied().filter(|h| !got.contains(*h)).collect();
692        if !missing.is_empty() {
693            let mut held: HashMap<String, Vec<u8>> = HashMap::new();
694            for row in t.query(&st_get, &[&missing]).db()? {
695                held.insert(row.try_get(0).db()?, row.try_get(1).db()?);
696            }
697            for p in new.iter().filter(|p| missing.contains(&p.hash.as_str())) {
698                if held.get(&p.hash) != Some(&p.canonical) {
699                    return Err(Error::Conflict { hash: p.hash.clone() });
700                }
701            }
702        }
703        let edges: Vec<(&str, &str)> =
704            new.iter().flat_map(|p| p.inputs.iter().map(move |i| (p.hash.as_str(), i.as_str()))).collect();
705        if !edges.is_empty() {
706            let (r, i): (Vec<&str>, Vec<&str>) = edges.into_iter().unzip();
707            t.execute(&st_edges, &[&r, &i]).db()?;
708        }
709        let slice_edges: Vec<(&str, &str)> =
710            new.iter().flat_map(|p| p.entries.iter().map(move |e| (p.hash.as_str(), e.as_str()))).collect();
711        if !slice_edges.is_empty() {
712            let (r, e): (Vec<&str>, Vec<&str>) = slice_edges.into_iter().unzip();
713            t.execute(&st_slice_edges, &[&r, &e]).db()?;
714        }
715    }
716    if !versions.is_empty() {
717        let cells: Vec<&str> = versions.iter().map(|v| v.0).collect();
718        let txs: Vec<&str> = versions.iter().map(|v| v.1).collect();
719        let hashes: Vec<&str> = versions.iter().map(|v| v.2.as_str()).collect();
720        if has {
721            let recorded: Vec<&str> = versions.iter().map(|v| v.3.as_str()).collect();
722            t.execute(&st_versions, &[&cells, &txs, &hashes, &recorded]).db()?;
723        } else {
724            t.execute(&st_versions, &[&cells, &txs, &hashes]).db()?;
725        }
726    }
727    t.commit().db()?;
728    Ok(out)
729}
730
731/// The version of `cell_id` in a row of `VersionLatestMany` (tx, receipt hash, asof, withdrawn,
732/// recorded), `None` when the cell has none.
733fn latest_row(r: &postgres::Row, cell_id: &str) -> Result<Option<Version>> {
734    let Some(tx) = r.try_get::<_, Option<String>>(0).db()? else { return Ok(None) };
735    Ok(Some(Version {
736        cell_id: cell_id.to_string(),
737        tx,
738        receipt_hash: r.try_get(1).db()?,
739        asof: r.try_get(2).db()?,
740        withdrawn: r.try_get(3).db()?,
741        recorded: r.try_get(4).db()?,
742        seq: r.try_get::<_, i64>("seq").db()?,
743    }))
744}
745
746/// The method names a class binds (K5, as `bind_class` does): `<class name>/<m>` for each
747/// method the class adds or overrides (its function hash differs from its parent's), with the
748/// function hash.
749fn own_method_bindings(
750    t: &mut postgres::Transaction<'_>,
751    get: &postgres::Statement,
752    class_name: &str,
753    class_hash: &str,
754) -> Result<Vec<(String, String)>> {
755    let Some(row) = t.query_opt(get, &[&class_hash]).db()? else {
756        return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
757    };
758    let flat = ClassDescriptor::from_json(&row.try_get::<_, Vec<u8>>(0).db()?)?;
759    let parent = match &flat.parent {
760        Some(p) => match t.query_opt(get, &[p]).db()? {
761            Some(row) => Some(ClassDescriptor::from_json(&row.try_get::<_, Vec<u8>>(0).db()?)?.methods),
762            None => None,
763        },
764        None => None,
765    };
766    let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
767    Ok(methods
768        .iter()
769        .filter(|(m, h)| parent.as_ref().and_then(|pm| pm.get(m)) != Some(h))
770        .map(|(m, h)| (format!("{class_name}/{m}"), h.clone()))
771        .collect())
772}
773
774impl Store for PgStore {
775    fn put_member_set_checked(&self, set: &MemberSet) -> Result<bool> {
776        let licences = crate::licences_text(&set.licences);
777        let members = i32::try_from(set.members).map_err(|_| {
778            Error::Invalid(datumesh_core::Error::new(
779                datumesh_core::ErrorCode::Schema,
780                "$",
781                "members is over the limit",
782            ))
783        })?;
784        self.run("put_member_set", |c| {
785            let st = c.stmt(Q::MemberSetPut)?;
786            let n = c
787                .client
788                .execute(
789                    &st,
790                    &[
791                        &set.entry,
792                        &set.slice_id,
793                        &set.members_hash,
794                        &set.fn_hash,
795                        &set.slice,
796                        &members,
797                        &set.tx,
798                        &set.asof,
799                        &licences,
800                        &set.seen_seq,
801                    ],
802                )
803                .db()?;
804            Ok(n == 1)
805        })
806    }
807
808    fn member_set_checked(&self, entry: &str) -> Result<Option<MemberSet>> {
809        self.run("member_set", |c| {
810            let st = c.stmt(Q::MemberSetGet)?;
811            let Some(row) = c.client.query_opt(&st, &[&entry]).db()? else { return Ok(None) };
812            let members: i32 = row.try_get(4).db()?;
813            Ok(Some(MemberSet {
814                entry: entry.to_string(),
815                slice_id: row.try_get(0).db()?,
816                members_hash: row.try_get(1).db()?,
817                fn_hash: row.try_get(2).db()?,
818                slice: row.try_get(3).db()?,
819                members: u64::try_from(members).unwrap_or(0),
820                tx: row.try_get(5).db()?,
821                asof: row.try_get(6).db()?,
822                licences: crate::licences_of(&row.try_get::<_, String>(7).db()?)?,
823                seen_seq: row.try_get(8).db()?,
824            }))
825        })
826    }
827
828    fn put_slice_definition_checked(&self, slice: &Slice) -> Result<bool> {
829        let (id, fn_hash, bytes) = (slice.id(), slice.fn_hash(), slice.canonical());
830        self.run("put_slice_definition", |c| {
831            let st = c.stmt(Q::SliceDefinitionPut)?;
832            Ok(c.client.execute(&st, &[&id, &fn_hash, &bytes]).db()? == 1)
833        })
834    }
835
836    fn recording_clock_of(&self) -> Option<crate::RecordingClock> {
837        self.clock.clone()
838    }
839
840    fn slice_member_hashes(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<String>> {
841        check_instant(asof, "asof")?;
842        let v = slice.to_value();
843        if version_slice(slice, &v)?.is_some() {
844            return Ok(crate::hashes_limited(self.slice_members(slice, asof)?, limit));
845        }
846        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
847        let pattern = Pattern::of(&v)?;
848        self.run("slice_member_hashes", |c| pattern.member_hashes(c, asof, limit))
849    }
850
851    fn barrier_checked(&self) -> Result<()> {
852        // One autocommit statement (decided 27 Nov, B2/B3): the lock timeout for the statement, the shared
853        // lock (it waits for the writers in flight) released when the statement ends.
854        let timeout = format!("{}ms", self.barrier_timeout.as_millis().max(1));
855        self.run("barrier", |c| {
856            let s = c.stmt(Q::BarrierShared)?;
857            c.client.query_one(&s, &[&VERSION_SEQ_LOCK, &timeout]).db()?;
858            Ok(())
859        })
860        .map_err(|e| crate::error::timed_out(e, "barrier"))
861    }
862
863    fn later_bound_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<String>> {
864        self.run("later_bound", |c| {
865            let st = c.stmt(Q::LaterBound)?;
866            let row = c.client.query_one(&st, &[&cell_id, &recorded]).db()?;
867            row.try_get(0).db()
868        })
869    }
870
871    fn slice_member_hashes_within_checked(
872        &self,
873        slice: &Slice,
874        asof: &str,
875        limit: usize,
876        timeout: std::time::Duration,
877    ) -> Result<Vec<String>> {
878        check_instant(asof, "asof")?;
879        let v = slice.to_value();
880        if version_slice(slice, &v)?.is_some() {
881            return Ok(crate::hashes_limited(self.slice_members(slice, asof)?, limit));
882        }
883        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
884        let pattern = Pattern::of(&v)?;
885        let ms = timeout.as_millis().max(1);
886        self.run("slice_member_hashes_within", |c| {
887            // One transaction, its statement timeout set for it alone (SET LOCAL), then the listing.
888            c.client.batch_execute("BEGIN").db()?;
889            let r = c
890                .client
891                .batch_execute(&format!("SET LOCAL statement_timeout = {ms}"))
892                .db()
893                .and_then(|()| pattern.member_hashes(c, asof, limit));
894            match r {
895                Ok(hashes) => {
896                    c.client.batch_execute("COMMIT").db()?;
897                    Ok(hashes)
898                }
899                Err(e) => {
900                    let _ = c.client.batch_execute("ROLLBACK");
901                    Err(e)
902                }
903            }
904        })
905        .map_err(|e| crate::error::timed_out(e, "slice_member_hashes_within"))
906    }
907
908    fn next_version_after_checked(&self, cell_id: &str, recorded: &str) -> Result<Option<Version>> {
909        self.run("next_version_after", |c| {
910            let st = c.stmt(Q::VersionNextAfter)?;
911            match c.client.query_opt(&st, &[&cell_id, &recorded]).db()? {
912                Some(r) => Ok(Some(version_row(&r, cell_id)?)),
913                None => Ok(None),
914            }
915        })
916    }
917
918    fn fn_seq_checked(&self, fn_hash: &str) -> Result<i64> {
919        self.run("fn_seq", |c| {
920            let st = c.stmt(Q::FnSeq)?;
921            c.client.query_one(&st, &[&fn_hash]).db()?.try_get(0).db()
922        })
923    }
924
925    fn slice_seq_checked(&self, slice: &Slice) -> Result<i64> {
926        let v = slice.to_value();
927        if let Some((cell_id, _, _)) = version_slice(slice, &v)? {
928            check_hex(&cell_id, 64, "cell_id")?;
929            return self.run("slice_seq", |c| {
930                let st = c.stmt(Q::VersionSeqMax)?;
931                c.client.query_one(&st, &[&cell_id]).db()?.try_get(0).db()
932            });
933        }
934        let pattern = Pattern::of(&v)?;
935        self.run("slice_seq", |c| pattern.seq(c))
936    }
937
938    fn slice_definition_checked(&self, slice_id: &str) -> Result<Option<Slice>> {
939        let bytes: Option<Vec<u8>> = self.run("slice_definition", |c| {
940            let st = c.stmt(Q::SliceDefinitionGet)?;
941            match c.client.query_opt(&st, &[&slice_id]).db()? {
942                Some(row) => Ok(Some(row.try_get(0).db()?)),
943                None => Ok(None),
944            }
945        })?;
946        bytes.map(|b| Slice::from_json(&b).map_err(Error::Invalid)).transpose()
947    }
948
949    fn put_descriptor(&self, bytes: &[u8]) -> Result<String> {
950        // spec-0.4.0's descriptor: `signature.order` and argument `extent` allowed.
951        let d = FunctionDescriptor::from_json(bytes)?;
952        let hash = d.hash();
953        let canonical = d.canonical();
954        // The descriptor and its inputs' index (0.5.1), in one transaction.
955        self.run("put_descriptor", |c| {
956            let st = c.stmt(Q::DescriptorPut)?;
957            let inputs_put = c.stmt(Q::DescriptorInputsPut)?;
958            let mut t = c.client.transaction().db()?;
959            t.execute(&st, &[&hash, &canonical]).db()?;
960            if !d.inputs.is_empty() {
961                t.execute(&inputs_put, &[&hash, &d.inputs]).db()?;
962            }
963            t.commit().db()?;
964            Ok(())
965        })?;
966        tracing::debug!(target: "datumesh_store", fn_hash = %hash, "put_descriptor");
967        Ok(hash)
968    }
969
970    fn put_receipt(&self, bytes: &[u8]) -> Result<String> {
971        // Steps 1-4 first (a valued receipt or a withdrawal): one that is neither is refused
972        // without a query.
973        let p = parse_receipt(bytes)?;
974        let canonical = p.canonical.clone();
975        let hash = p.hash.clone();
976        let cell_id = p.cell_id.clone();
977        let host = p.host.clone();
978        let (entries, inputs) = (p.entries.clone(), p.inputs.clone());
979        self.run("put_receipt", |c| {
980            let ns = c.stmt(Q::NamespaceGet)?;
981            let put = c.stmt(Q::ReceiptPut)?;
982            let get = c.stmt(Q::ReceiptGet)?;
983            let edges = c.stmt(Q::EdgesPut)?;
984            let slice_edges = c.stmt(Q::SliceEdgesPut)?;
985            let mut t = c.client.transaction().db()?;
986            // Idempotent: the very receipt already stored verified when it was stored, and
987            // the stored copy is unchanged, so it is not checked again (even if its key has
988            // since been revoked).
989            if let Some(row) = t.query_opt(&get, &[&hash]).db()? {
990                let stored: Vec<u8> = row.try_get(0).db()?;
991                if stored == canonical {
992                    return Ok(());
993                }
994            }
995            // Steps 5-6 against the stored key document of the signer host; none stored is
996            // a host without keys (E_KEY_UNAVAILABLE).
997            let mut keys = Keys::new();
998            if let Some(row) = t.query_opt(&ns, &[&host]).db()? {
999                // No new writes under a suspended namespace.
1000                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1001                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
1002                }
1003                let doc: Vec<u8> = row.try_get(0).db()?;
1004                keys.insert_response(&host, 200, Some(&doc));
1005            }
1006            let out = verify(bytes, &keys, None, None);
1007            if !out.ok {
1008                return Err(Error::Invalid(out.error().unwrap_or_else(|| {
1009                    datumesh_core::Error::new(ErrorCode::Signature, "$", "the receipt did not verify")
1010                })));
1011            }
1012            let n = t.execute(&put, &[&hash, &canonical, &cell_id, &p.tx, &p.asof, &p.fn_hash, &p.publisher]).db()?;
1013            if n == 0 {
1014                let row = t.query_one(&get, &[&hash]).db()?;
1015                let stored: Vec<u8> = row.try_get(0).db()?;
1016                if stored != canonical {
1017                    return Err(Error::Conflict { hash: hash.clone() });
1018                }
1019            }
1020            if !inputs.is_empty() {
1021                t.execute(&edges, &[&hash, &inputs]).db()?;
1022            }
1023            if !entries.is_empty() {
1024                t.execute(&slice_edges, &[&hash, &entries]).db()?;
1025            }
1026            t.commit().db()?;
1027            Ok(())
1028        })?;
1029        tracing::debug!(target: "datumesh_store", hash = %hash, cell_id = %cell_id, "put_receipt");
1030        Ok(hash)
1031    }
1032
1033    fn put_blob(&self, bytes: &[u8]) -> Result<String> {
1034        let sha = sha256_hex(bytes);
1035        let length = i64::try_from(bytes.len()).unwrap_or(i64::MAX);
1036        self.run("put_blob", |c| {
1037            let st = c.stmt(Q::BlobPut)?;
1038            c.client.execute(&st, &[&sha, &bytes, &length]).db()?;
1039            Ok(())
1040        })?;
1041        tracing::debug!(target: "datumesh_store", sha256 = %sha, length, "put_blob");
1042        Ok(sha)
1043    }
1044
1045    fn blob(&self, sha256: &str) -> Result<Option<Cow<'_, [u8]>>> {
1046        check_hex(sha256, 64, "sha256")?;
1047        Ok(self.run("blob", |c| get_bytes(c, Q::BlobGet, sha256))?.map(Cow::Owned))
1048    }
1049
1050    fn put_version(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
1051        check_hex(cell_id, 64, "cell_id")?;
1052        check_instant(tx, "tx")?;
1053        check_hex(receipt_hash, 64, "receipt_hash")?;
1054        self.run("put_version", |c| {
1055            let has = self.schema_has_recorded(c)?;
1056            let lock = c.stmt(Q::Lock)?;
1057            let vlock = c.stmt(Q::VersionSeqLock)?;
1058            let at = c.stmt(Q::VersionAt)?;
1059            let signed = c.stmt(Q::VersionLatestSigned)?;
1060            let meta = c.stmt(Q::ReceiptMeta)?;
1061            let get = c.stmt(Q::ReceiptGet)?;
1062            let ns = c.stmt(Q::NamespaceGet)?;
1063            let latest = c.stmt(if has { Q::VersionLatestTx } else { Q::VersionLatestTxLegacy })?;
1064            let put = c.stmt(if has { Q::VersionPut } else { Q::VersionPutLegacy })?;
1065            let mut t = c.client.transaction().db()?;
1066            t.execute(&lock, &[&"versions", &cell_id]).db()?;
1067            // The version lock, then the recording time, both under it (review item 2).
1068            t.execute(&vlock, &[&VERSION_SEQ_LOCK]).db()?;
1069            // Recorded under the lock, and after the cell's latest (decided 27 Nov, B5).
1070            let latest_now: Option<String> =
1071                t.query_opt(&latest, &[&cell_id]).db()?.map(|r| r.try_get(0)).transpose().db()?;
1072            let recorded = if has {
1073                let base = crate::recorded_at(self.clock.as_ref(), tx);
1074                match &latest_now {
1075                    Some(l) => crate::later_of(&base, &crate::instant_after(l)),
1076                    None => base,
1077                }
1078            } else {
1079                tx.to_string()
1080            };
1081            let Some(row) = t.query_opt(&meta, &[&receipt_hash]).db()? else {
1082                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
1083            };
1084            // No new versions of a receipt signed by a suspended namespace.
1085            let stored: Vec<u8> = t.query_one(&get, &[&receipt_hash]).db()?.try_get(0).db()?;
1086            let signer = parse_receipt(&stored)?.host;
1087            if let Some(row) = t.query_opt(&ns, &[&signer]).db()? {
1088                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1089                    return Err(Error::NamespaceSuspended { host: signer, suspended_at: since });
1090                }
1091            }
1092            let (r_cell, r_tx): (String, String) = (row.try_get(0).db()?, row.try_get(1).db()?);
1093            if r_cell != cell_id {
1094                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
1095            }
1096            if r_tx != tx {
1097                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
1098            }
1099            // The cell already has a version at this tx: the same receipt is a no-op; another is refused
1100            // (review item 3).
1101            if let Some(row) = t.query_opt(&at, &[&cell_id, &tx]).db()? {
1102                let held: String = row.try_get(0).db()?;
1103                if held == receipt_hash {
1104                    t.commit().db()?;
1105                    return Ok(());
1106                }
1107                return Err(Error::NotLater {
1108                    what: "version",
1109                    key: cell_id.to_string(),
1110                    given: tx.to_string(),
1111                    latest: tx.to_string(),
1112                });
1113            }
1114            // The cell's latest signed tx: a version not later is refused (decided by the user, 27 Nov).
1115            let signed_now: Option<String> =
1116                t.query_opt(&signed, &[&cell_id]).db()?.map(|r| r.try_get(0)).transpose().db()?;
1117            if let Some(l) = &signed_now {
1118                if tx <= l.as_str() {
1119                    return Err(Error::NotLater {
1120                        what: "version",
1121                        key: cell_id.to_string(),
1122                        given: tx.to_string(),
1123                        latest: l.clone(),
1124                    });
1125                }
1126            }
1127            if let Some(l) = &latest_now {
1128                if recorded.as_str() <= l.as_str() {
1129                    return Err(Error::NotLater {
1130                        what: "version",
1131                        key: cell_id.to_string(),
1132                        given: recorded.clone(),
1133                        latest: l.clone(),
1134                    });
1135                }
1136            }
1137            if has {
1138                t.execute(&put, &[&cell_id, &tx, &receipt_hash, &recorded]).db()?;
1139            } else {
1140                t.execute(&put, &[&cell_id, &tx, &receipt_hash]).db()?;
1141            }
1142            t.commit().db()?;
1143            Ok(())
1144        })?;
1145        tracing::debug!(target: "datumesh_store", cell_id, tx, receipt_hash, "put_version");
1146        Ok(())
1147    }
1148
1149    fn version_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1150        self.asof_version("version_asof", Q::VersionAsof, cell_id, asof)
1151    }
1152
1153    fn versions(&self, cell_id: &str, from: &str, to: &str) -> Result<Vec<Version>> {
1154        check_hex(cell_id, 64, "cell_id")?;
1155        check_instant(from, "from")?;
1156        check_instant(to, "to")?;
1157        self.run("versions", |c| {
1158            let st = c.stmt(Q::VersionRange)?;
1159            let rows = c.client.query(&st, &[&cell_id, &from, &to]).db()?;
1160            PgStore::version_rows(&rows, cell_id)
1161        })
1162    }
1163
1164    fn latest(&self, cell_id: &str) -> Result<Option<Version>> {
1165        check_hex(cell_id, 64, "cell_id")?;
1166        self.run("latest", |c| {
1167            let st = c.stmt(Q::VersionLatest)?;
1168            let rows = c.client.query(&st, &[&cell_id]).db()?;
1169            Ok(PgStore::version_rows(&rows, cell_id)?.pop())
1170        })
1171    }
1172
1173    fn latest_many(&self, cell_ids: &[&str]) -> Result<Vec<Option<Version>>> {
1174        for id in cell_ids {
1175            check_hex(id, 64, "cell_id")?;
1176        }
1177        let mut out = Vec::with_capacity(cell_ids.len());
1178        for part in cell_ids.chunks(MANY) {
1179            let versions = self.run("latest_many", |c| {
1180                let st = c.stmt(Q::VersionLatestMany)?;
1181                let rows = c.client.query(&st, &[&part]).db()?;
1182                rows.iter().zip(part).map(|(r, id)| latest_row(r, id)).collect::<Result<Vec<_>>>()
1183            })?;
1184            out.extend(versions);
1185        }
1186        Ok(out)
1187    }
1188
1189    fn receipts_many(&self, hashes: &[&str]) -> Result<Vec<Option<Vec<u8>>>> {
1190        let mut out = Vec::with_capacity(hashes.len());
1191        for part in hashes.chunks(MANY) {
1192            // A malformed hash has no receipt (as `receipt` answers): it is not sent.
1193            let valid: Vec<&str> = part.iter().copied().filter(|h| is_hash(h)).collect();
1194            let found: Vec<Option<Vec<u8>>> = if valid.is_empty() {
1195                Vec::new()
1196            } else {
1197                self.run("receipts_many", |c| {
1198                    let st = c.stmt(Q::ReceiptsMany)?;
1199                    let rows = c.client.query(&st, &[&valid]).db()?;
1200                    rows.iter().map(|r| r.try_get::<_, Option<Vec<u8>>>(0).db()).collect::<Result<Vec<_>>>()
1201                })?
1202            };
1203            let mut found = found.into_iter();
1204            for h in part {
1205                out.push(if is_hash(h) { found.next().flatten() } else { None });
1206            }
1207        }
1208        Ok(out)
1209    }
1210
1211    fn put_cells(&self, items: &[CellWrite<'_>]) -> Result<Vec<String>> {
1212        if items.is_empty() {
1213            return Ok(Vec::new());
1214        }
1215        // Parsing (and so the first malformed receipt's error) is in item order below.
1216        let prepared = parallel(items, |w| parse_receipt(w.receipt));
1217        let clock = self.clock.as_ref();
1218        let hashes = self.run("put_cells", |c| {
1219            let has = self.schema_has_recorded(c)?;
1220            put_cells_in(c, items, prepared, clock, has)
1221        })?;
1222        tracing::debug!(target: "datumesh_store", items = items.len(), "put_cells");
1223        Ok(hashes)
1224    }
1225
1226    fn dependents(&self, receipt_hash: &str) -> Result<Vec<String>> {
1227        check_hex(receipt_hash, 64, "receipt_hash")?;
1228        self.run("dependents", |c| get_strings(c, Q::Dependents, receipt_hash))
1229    }
1230
1231    fn inputs(&self, receipt_hash: &str) -> Result<Vec<String>> {
1232        check_hex(receipt_hash, 64, "receipt_hash")?;
1233        self.run("inputs", |c| get_strings(c, Q::Inputs, receipt_hash))
1234    }
1235
1236    fn put_namespace(&self, host: &str, keydoc_bytes: &[u8], validated_at: &str) -> Result<()> {
1237        // SPEC 9.3: a 200 with this body, for this host (a DNS name equal to the document's).
1238        keys_from_response(host, 200, Some(keydoc_bytes))?;
1239        check_instant(validated_at, "validated_at")?;
1240        let canonical = json::parse(keydoc_bytes)?.to_jcs();
1241        self.run("put_namespace", |c| {
1242            let lock = c.stmt(Q::Lock)?;
1243            let get = c.stmt(Q::NamespaceGet)?;
1244            let put = c.stmt(Q::NamespacePut)?;
1245            let mut t = c.client.transaction().db()?;
1246            t.execute(&lock, &[&"namespaces", &host]).db()?;
1247            if let Some(row) = t.query_opt(&get, &[&host]).db()? {
1248                let at: String = row.try_get(1).db()?;
1249                if validated_at < at.as_str() {
1250                    return Err(Error::NotLater {
1251                        what: "namespace",
1252                        key: host.to_string(),
1253                        given: validated_at.to_string(),
1254                        latest: at,
1255                    });
1256                }
1257            }
1258            t.execute(&put, &[&host, &canonical, &validated_at]).db()?;
1259            t.commit().db()?;
1260            Ok(())
1261        })?;
1262        tracing::debug!(target: "datumesh_store", host, validated_at, "put_namespace");
1263        Ok(())
1264    }
1265
1266    fn namespace(&self, host: &str) -> Result<Option<Namespace>> {
1267        check_dns_name(host, "host")?;
1268        self.run("namespace", |c| {
1269            let st = c.stmt(Q::NamespaceGet)?;
1270            let Some(row) = c.client.query_opt(&st, &[&host]).db()? else { return Ok(None) };
1271            Ok(Some(namespace_row(host, &row, 0)?))
1272        })
1273    }
1274
1275    fn namespaces(&self) -> Result<Vec<Namespace>> {
1276        self.run("namespaces", |c| {
1277            let st = c.stmt(Q::NamespaceList)?;
1278            let mut out = Vec::new();
1279            for row in c.client.query(&st, &[]).db()? {
1280                let host: String = row.try_get(0).db()?;
1281                out.push(namespace_row(&host, &row, 1)?);
1282            }
1283            Ok(out)
1284        })
1285    }
1286
1287    fn record_namespace_failure(&self, host: &str, checked_at: &str, threshold: u32) -> Result<Option<Namespace>> {
1288        self.record_check("record_namespace_failure", host, checked_at, Some(threshold))
1289    }
1290
1291    fn record_namespace_success(&self, host: &str, checked_at: &str) -> Result<Option<Namespace>> {
1292        self.record_check("record_namespace_success", host, checked_at, None)
1293    }
1294
1295    fn bind_name(&self, fn_name: &str, fn_hash: &str, tx: &str) -> Result<()> {
1296        check_function_name(fn_name, "fn_name")?;
1297        check_hex(fn_hash, 64, "fn_hash")?;
1298        check_instant(tx, "tx")?;
1299        self.run("bind_name", |c| {
1300            let lock = c.stmt(Q::Lock)?;
1301            let exists = c.stmt(Q::DescriptorExists)?;
1302            let ns = c.stmt(Q::NamespaceGet)?;
1303            let latest = c.stmt(Q::NameLatest)?;
1304            let put = c.stmt(Q::NamePut)?;
1305            let class_bound = c.stmt(Q::ClassNameBound)?;
1306            let mut t = c.client.transaction().db()?;
1307            t.execute(&lock, &[&"names", &fn_name]).db()?;
1308            // No new bindings under a suspended namespace.
1309            if let Some(row) = t.query_opt(&ns, &[&name_host(fn_name)]).db()? {
1310                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1311                    return Err(Error::NamespaceSuspended {
1312                        host: name_host(fn_name).to_string(),
1313                        suspended_at: since,
1314                    });
1315                }
1316            }
1317            // One namespace of names: a class name is not a function name.
1318            let class: bool = t.query_one(&class_bound, &[&fn_name]).db()?.try_get(0).db()?;
1319            if class {
1320                return Err(Error::NameTaken { name: fn_name.to_string(), bound_as: "class" });
1321            }
1322            let found: bool = t.query_one(&exists, &[&fn_hash]).db()?.try_get(0).db()?;
1323            if !found {
1324                return Err(Error::NotFound { what: "descriptor", key: fn_hash.to_string() });
1325            }
1326            if let Some(row) = t.query_opt(&latest, &[&fn_name]).db()? {
1327                let l: String = row.try_get(0).db()?;
1328                if tx <= l.as_str() {
1329                    return Err(Error::NotLater {
1330                        what: "name",
1331                        key: fn_name.to_string(),
1332                        given: tx.to_string(),
1333                        latest: l,
1334                    });
1335                }
1336            }
1337            t.execute(&put, &[&fn_name, &tx, &fn_hash]).db()?;
1338            t.commit().db()?;
1339            Ok(())
1340        })?;
1341        tracing::debug!(target: "datumesh_store", fn_name, fn_hash, tx, "bind_name");
1342        Ok(())
1343    }
1344
1345    fn put_computed(&self, cell_id: &str, tx: &str, receipt_hash: &str) -> Result<()> {
1346        check_hex(cell_id, 64, "cell_id")?;
1347        check_instant(tx, "tx")?;
1348        check_hex(receipt_hash, 64, "receipt_hash")?;
1349        // No lock: the primary key serialises writers of one (cell_id, tx, asof). An insert
1350        // that meets a concurrent one waits for it; if it committed, nothing is inserted and
1351        // the row it wrote (visible to the next statement under READ COMMITTED) decides.
1352        let asof = self.run("put_computed", |c| {
1353            let meta = c.stmt(Q::ReceiptMeta)?;
1354            let put = c.stmt(Q::ComputedPut)?;
1355            let get = c.stmt(Q::ComputedGet)?;
1356            let mut t = c.client.transaction().db()?;
1357            let Some(row) = t.query_opt(&meta, &[&receipt_hash]).db()? else {
1358                return Err(Error::NotFound { what: "receipt", key: receipt_hash.to_string() });
1359            };
1360            let (r_cell, r_tx, asof): (String, String, String) =
1361                (row.try_get(0).db()?, row.try_get(1).db()?, row.try_get(2).db()?);
1362            // A computed version states a value: a withdrawal is refused (0.6.0).
1363            if row.try_get::<_, bool>(3).db()? {
1364                return Err(Error::Invalid(datumesh_core::Error::new(
1365                    ErrorCode::Schema,
1366                    "$",
1367                    "a withdrawal is not the receipt of a computed version",
1368                )));
1369            }
1370            if r_cell != cell_id {
1371                return Err(Error::Mismatch { what: "cell_id", expected: cell_id.to_string(), found: r_cell });
1372            }
1373            if r_tx != tx {
1374                return Err(Error::Mismatch { what: "tx", expected: tx.to_string(), found: r_tx });
1375            }
1376            if t.execute(&put, &[&cell_id, &tx, &asof, &receipt_hash]).db()? == 0 {
1377                let stored: String = t.query_one(&get, &[&cell_id, &tx, &asof]).db()?.try_get(0).db()?;
1378                if stored != receipt_hash {
1379                    return Err(Error::Conflict { hash: receipt_hash.to_string() });
1380                }
1381            }
1382            t.commit().db()?;
1383            Ok(asof)
1384        })?;
1385        tracing::debug!(target: "datumesh_store", cell_id, tx, asof, receipt_hash, "put_computed");
1386        Ok(())
1387    }
1388
1389    fn computed_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1390        self.asof_version("computed_asof", Q::ComputedAsof, cell_id, asof)
1391    }
1392
1393    fn stored_asof(&self, cell_id: &str, asof: &str) -> Result<Option<Version>> {
1394        self.asof_version("stored_asof", Q::StoredAsof, cell_id, asof)
1395    }
1396
1397    fn cell_dependents(&self, cell_id: &str) -> Result<Vec<String>> {
1398        check_hex(cell_id, 64, "cell_id")?;
1399        self.run("cell_dependents", |c| get_strings(c, Q::CellDependents, cell_id))
1400    }
1401
1402    /// One query: the version and its receipt's bytes.
1403    fn computed_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1404        Ok(self
1405            .asof_with_receipt("computed_asof_with_receipt", Q::ComputedAsofReceipt, cell_id, asof)?
1406            .map(|(v, b)| (v, Cow::Owned(b))))
1407    }
1408
1409    /// One query: the version and its receipt's bytes.
1410    fn stored_asof_with_receipt(&self, cell_id: &str, asof: &str) -> Result<Option<(Version, Cow<'_, [u8]>)>> {
1411        Ok(self
1412            .asof_with_receipt("stored_asof_with_receipt", Q::StoredAsofReceipt, cell_id, asof)?
1413            .map(|(v, b)| (v, Cow::Owned(b))))
1414    }
1415
1416    fn put_manifest(&self, bytes: &[u8]) -> Result<String> {
1417        let m = Manifest::from_json(bytes)?;
1418        let entry = m.entry();
1419        let canonical = m.canonical();
1420        let members = m.members();
1421        let n = i32::try_from(members.len()).unwrap_or(i32::MAX);
1422        self.run("put_manifest", |c| {
1423            let put = c.stmt(Q::ManifestPut)?;
1424            let put_members = c.stmt(Q::ManifestMembersPut)?;
1425            let mut t = c.client.transaction().db()?;
1426            // The entry hashes the content: a stored entry has these very bytes. A concurrent
1427            // insert of it waits for the other; if that one committed, nothing is inserted
1428            // here, members included (it inserted them).
1429            let inserted = t
1430                .execute(&put, &[&entry, &m.slice().id(), &m.members_hash(), &m.slice().fn_hash(), &n, &canonical])
1431                .db()?;
1432            if inserted == 1 && !members.is_empty() {
1433                t.execute(&put_members, &[&entry, &members]).db()?;
1434            }
1435            t.commit().db()?;
1436            Ok(())
1437        })?;
1438        tracing::debug!(target: "datumesh_store", entry = %entry, members = n, "put_manifest");
1439        Ok(entry)
1440    }
1441
1442    fn member_manifests(&self, receipt_hash: &str) -> Result<Vec<String>> {
1443        check_hex(receipt_hash, 64, "receipt_hash")?;
1444        self.run("member_manifests", |c| get_strings(c, Q::MemberManifests, receipt_hash))
1445    }
1446
1447    fn slice_entries(&self, receipt_hash: &str) -> Result<Vec<String>> {
1448        check_hex(receipt_hash, 64, "receipt_hash")?;
1449        self.run("slice_entries", |c| get_strings(c, Q::SliceEntries, receipt_hash))
1450    }
1451
1452    fn slice_dependents(&self, entry: &str) -> Result<Vec<String>> {
1453        check_entry(entry, "entry")?;
1454        self.run("slice_dependents", |c| get_strings(c, Q::SliceDependents, entry))
1455    }
1456
1457    fn slice_members(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceMember>> {
1458        check_instant(asof, "asof")?;
1459        let v = slice.to_value();
1460        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1461            return self.versions_between(&cell_id, &from, &to, asof);
1462        }
1463        let pattern = Pattern::of(&v)?;
1464        self.run("slice_members", |c| pattern.members(c, asof))
1465    }
1466
1467    fn versions_between(&self, cell_id: &str, from: &str, to: &str, asof: &str) -> Result<Vec<SliceMember>> {
1468        check_hex(cell_id, 64, "cell_id")?;
1469        check_instant(from, "from")?;
1470        check_instant(to, "to")?;
1471        check_instant(asof, "asof")?;
1472        self.run("versions_between", |c| {
1473            let st = c.stmt(Q::VersionsBetween)?;
1474            let rows = c.client.query(&st, &[&cell_id, &from, &to, &asof]).db()?;
1475            rows.iter().map(|r| versions_between_row(r, cell_id)).collect()
1476        })
1477    }
1478
1479    fn slice_values(&self, slice: &Slice, asof: &str) -> Result<Vec<SliceValue>> {
1480        check_instant(asof, "asof")?;
1481        let v = slice.to_value();
1482        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1483            return self.run("slice_values", |c| {
1484                let st = c.stmt(Q::VersionsBetweenValues)?;
1485                let rows = c.client.query(&st, &[&cell_id, &from, &to, &asof]).db()?;
1486                rows.iter().map(|r| value_row(r, &cell_id)).collect()
1487            });
1488        }
1489        let pattern = Pattern::of(&v)?;
1490        self.run("slice_values", |c| pattern.values(c, asof))
1491    }
1492
1493    fn slice_withdrawn_latest(&self, slice: &Slice, asof: &str) -> Result<Option<(String, String)>> {
1494        check_instant(asof, "asof")?;
1495        let v = slice.to_value();
1496        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1497            // A version slice: its cell's version answering as of asof, when a withdrawal in range.
1498            return Ok(self
1499                .stored_asof(&cell_id, asof)?
1500                .filter(|s| s.withdrawn && from.as_str() <= s.tx.as_str() && s.tx.as_str() <= to.as_str())
1501                .map(|s| (s.tx, s.asof)));
1502        }
1503        let pattern = Pattern::of(&v)?;
1504        self.run("slice_withdrawn_latest", |c| pattern.withdrawn_latest(c, asof))
1505    }
1506
1507    fn slice_changed_after(&self, slice: &Slice, asof: &str) -> Result<bool> {
1508        check_instant(asof, "asof")?;
1509        let v = slice.to_value();
1510        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
1511            return self.run("slice_changed_after", |c| {
1512                let st = c.stmt(Q::VersionsChangedAfter)?;
1513                c.client.query_one(&st, &[&cell_id, &from, &to, &asof]).db()?.try_get(0).db()
1514            });
1515        }
1516        let pattern = Pattern::of(&v)?;
1517        self.run("slice_changed_after", |c| pattern.changed_after(c, asof))
1518    }
1519
1520    fn computed_cells(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<Cell>> {
1521        check_instant(asof, "asof")?;
1522        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1523        let pattern = Pattern::of(&slice.to_value())?;
1524        self.run("computed_cells", |c| pattern.computed_cells(c, asof, limit))
1525    }
1526
1527    fn has_bindings_under(&self, namespace: &str) -> Result<bool> {
1528        let prefix = format!("{namespace}/");
1529        self.run("has_bindings_under", |c| {
1530            let st = c.stmt(Q::HasBindingsUnder)?;
1531            c.client.query_one(&st, &[&prefix]).db()?.try_get(0).db()
1532        })
1533    }
1534
1535    fn put_class(&self, bytes: &[u8]) -> Result<String> {
1536        // The core checks the descriptor (strict JSON, then 16.1); the bytes must be its
1537        // canonical form, since the class hash is the hash of the bytes stored.
1538        let d = ClassDescriptor::from_json(bytes)?;
1539        let canonical = d.canonical();
1540        if canonical != bytes {
1541            return Err(not_canonical_class());
1542        }
1543        let hash = d.hash();
1544        let host = d.steward.namespace.clone();
1545        self.run("put_class", |c| {
1546            // No new writes under a suspended namespace: the steward's (16.2).
1547            let ns = c.stmt(Q::NamespaceGet)?;
1548            if let Some(row) = c.client.query_opt(&ns, &[&host]).db()? {
1549                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1550                    return Err(Error::NamespaceSuspended { host: host.clone(), suspended_at: since });
1551                }
1552            }
1553            let put = c.stmt(Q::ClassPut)?;
1554            c.client.execute(&put, &[&hash, &canonical]).db()?;
1555            Ok(())
1556        })?;
1557        tracing::debug!(target: "datumesh_store", class_hash = %hash, "put_class");
1558        Ok(hash)
1559    }
1560
1561    fn class(&self, class_hash: &str) -> Result<Option<Vec<u8>>> {
1562        check_hex(class_hash, 64, "class_hash")?;
1563        self.run("class", |c| get_bytes(c, Q::ClassGet, class_hash))
1564    }
1565
1566    fn bind_class(&self, class_name: &str, class_hash: &str, tx: &str) -> Result<()> {
1567        check_function_name(class_name, "class_name")?;
1568        check_hex(class_hash, 64, "class_hash")?;
1569        check_instant(tx, "tx")?;
1570        self.run("bind_class", |c| {
1571            let lock = c.stmt(Q::Lock)?;
1572            let ns = c.stmt(Q::NamespaceGet)?;
1573            let get = c.stmt(Q::ClassGet)?;
1574            let exists = c.stmt(Q::DescriptorExists)?;
1575            let name_bound = c.stmt(Q::NameBound)?;
1576            let class_bound = c.stmt(Q::ClassNameBound)?;
1577            let class_latest = c.stmt(Q::ClassBindingLatest)?;
1578            let latest = c.stmt(Q::NameLatest)?;
1579            let class_put = c.stmt(Q::ClassBindingPut)?;
1580            let name_put = c.stmt(Q::NamePut)?;
1581            let mut t = c.client.transaction().db()?;
1582            // Every name this binding makes is locked before it is read: the class name, then
1583            // its own method names (the flattened descriptor's, in JCS order).
1584            t.execute(&lock, &[&"names", &class_name]).db()?;
1585            // No new bindings under a suspended namespace: the host of the class name.
1586            let host = name_host(class_name);
1587            if let Some(row) = t.query_opt(&ns, &[&host]).db()? {
1588                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1589                    return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
1590                }
1591            }
1592            let Some(row) = t.query_opt(&get, &[&class_hash]).db()? else {
1593                return Err(Error::NotFound { what: "class", key: class_hash.to_string() });
1594            };
1595            let flat = ClassDescriptor::from_json(&row.try_get::<_, Vec<u8>>(0).db()?)?;
1596            let methods: Vec<(String, String)> = flat.methods.into_iter().collect();
1597            // K5: only the methods this class adds or overrides are bound under its name: those
1598            // whose function hash the parent's flattened descriptor does not give.
1599            let parent = match &flat.parent {
1600                Some(p) => match t.query_opt(&get, &[p]).db()? {
1601                    Some(row) => Some(ClassDescriptor::from_json(&row.try_get::<_, Vec<u8>>(0).db()?)?.methods),
1602                    None => None,
1603                },
1604                None => None,
1605            };
1606            let own: Vec<(String, String)> =
1607                methods.iter().filter(|(m, h)| parent.as_ref().and_then(|pm| pm.get(m)) != Some(h)).cloned().collect();
1608            let own_names: Vec<String> = own.iter().map(|(m, _)| format!("{class_name}/{m}")).collect();
1609            for name in &own_names {
1610                t.execute(&lock, &[&"names", &name.as_str()]).db()?;
1611            }
1612            // Every method's function descriptor is stored.
1613            for (_, h) in &methods {
1614                let found: bool = t.query_one(&exists, &[h]).db()?.try_get(0).db()?;
1615                if !found {
1616                    return Err(Error::NotFound { what: "descriptor", key: h.clone() });
1617                }
1618            }
1619            // One namespace of names: the class name is not a function name, and no method
1620            // name is a class name.
1621            let function: bool = t.query_one(&name_bound, &[&class_name]).db()?.try_get(0).db()?;
1622            if function {
1623                return Err(Error::NameTaken { name: class_name.to_string(), bound_as: "function" });
1624            }
1625            for name in &own_names {
1626                let class: bool = t.query_one(&class_bound, &[&name.as_str()]).db()?.try_get(0).db()?;
1627                if class {
1628                    return Err(Error::NameTaken { name: name.clone(), bound_as: "class" });
1629                }
1630            }
1631            // Later than the latest binding of the class name and of each method name.
1632            if let Some(row) = t.query_opt(&class_latest, &[&class_name]).db()? {
1633                let l: String = row.try_get(0).db()?;
1634                if tx <= l.as_str() {
1635                    return Err(Error::NotLater {
1636                        what: "name",
1637                        key: class_name.to_string(),
1638                        given: tx.to_string(),
1639                        latest: l,
1640                    });
1641                }
1642            }
1643            for name in &own_names {
1644                if let Some(row) = t.query_opt(&latest, &[&name.as_str()]).db()? {
1645                    let l: String = row.try_get(0).db()?;
1646                    if tx <= l.as_str() {
1647                        return Err(Error::NotLater {
1648                            what: "name",
1649                            key: name.clone(),
1650                            given: tx.to_string(),
1651                            latest: l,
1652                        });
1653                    }
1654                }
1655            }
1656            t.execute(&class_put, &[&class_name, &tx, &class_hash]).db()?;
1657            for ((_, h), name) in own.iter().zip(&own_names) {
1658                t.execute(&name_put, &[&name.as_str(), &tx, &h.as_str()]).db()?;
1659            }
1660            t.commit().db()?;
1661            Ok(())
1662        })?;
1663        tracing::debug!(target: "datumesh_store", class_name, class_hash, tx, "bind_class");
1664        Ok(())
1665    }
1666
1667    fn close_binding(&self, name: &str, at: &str) -> Result<()> {
1668        check_function_name(name, "name")?;
1669        check_instant(at, "at")?;
1670        self.run("close_binding", |c| {
1671            let lock = c.stmt(Q::Lock)?;
1672            let ns = c.stmt(Q::NamespaceGet)?;
1673            let class_bound = c.stmt(Q::ClassNameBound)?;
1674            let name_latest = c.stmt(Q::NameLatestRow)?;
1675            let class_latest = c.stmt(Q::ClassBindingLatestRow)?;
1676            let name_close = c.stmt(Q::NameClose)?;
1677            let class_close = c.stmt(Q::ClassBindingClose)?;
1678            let get = c.stmt(Q::ClassGet)?;
1679            let mut t = c.client.transaction().db()?;
1680            t.execute(&lock, &[&"names", &name]).db()?;
1681            // No new writes under a suspended namespace: the host of the name.
1682            let host = name_host(name);
1683            if let Some(row) = t.query_opt(&ns, &[&host]).db()? {
1684                if let Some(since) = row.try_get::<_, Option<String>>(2).db()? {
1685                    return Err(Error::NamespaceSuspended { host: host.to_string(), suspended_at: since });
1686                }
1687            }
1688            let class: bool = t.query_one(&class_bound, &[&name]).db()?.try_get(0).db()?;
1689            if class {
1690                // The class name, then the method names its binding bound and that are still bound.
1691                let row = t.query_opt(&class_latest, &[&name]).db()?.ok_or_else(|| unbound(name))?;
1692                let (tx, class_hash): (String, Option<String>) = (row.try_get(0).db()?, row.try_get(1).db()?);
1693                let class_hash = class_hash.ok_or_else(|| unbound(name))?;
1694                later_than("name", name, at, &tx)?;
1695                let methods = own_method_bindings(&mut t, &get, name, &class_hash)?;
1696                let mut closing: Vec<String> = Vec::new();
1697                for (m, _) in &methods {
1698                    t.execute(&lock, &[&"names", &m.as_str()]).db()?;
1699                    if let Some(row) = t.query_opt(&name_latest, &[&m.as_str()]).db()? {
1700                        let (mtx, mhash): (String, Option<String>) = (row.try_get(0).db()?, row.try_get(1).db()?);
1701                        if mhash.is_some() {
1702                            later_than("name", m, at, &mtx)?;
1703                            closing.push(m.clone());
1704                        }
1705                    }
1706                }
1707                t.execute(&class_close, &[&name, &at]).db()?;
1708                for m in &closing {
1709                    t.execute(&name_close, &[&m.as_str(), &at]).db()?;
1710                }
1711            } else {
1712                let row = t.query_opt(&name_latest, &[&name]).db()?.ok_or_else(|| unbound(name))?;
1713                let (tx, fn_hash): (String, Option<String>) = (row.try_get(0).db()?, row.try_get(1).db()?);
1714                fn_hash.ok_or_else(|| unbound(name))?;
1715                later_than("name", name, at, &tx)?;
1716                t.execute(&name_close, &[&name, &at]).db()?;
1717            }
1718            t.commit().db()?;
1719            Ok(())
1720        })?;
1721        tracing::debug!(target: "datumesh_store", name, at, "close_binding");
1722        Ok(())
1723    }
1724
1725    fn resolve_class(&self, class_name: &str, asof: &str) -> Result<Option<String>> {
1726        Ok(self.resolve_class_binding(class_name, asof)?.map(|b| b.class_hash))
1727    }
1728
1729    fn resolve_class_binding(&self, class_name: &str, asof: &str) -> Result<Option<ClassBinding>> {
1730        check_function_name(class_name, "class_name")?;
1731        check_instant(asof, "asof")?;
1732        self.run("resolve_class_binding", |c| {
1733            let st = c.stmt(Q::ClassBindingAsof)?;
1734            let Some(row) = c.client.query_opt(&st, &[&class_name, &asof]).db()? else { return Ok(None) };
1735            // A closed binding (0.6.0) has no class hash: the name is unbound from its tx on.
1736            let Some(class_hash) = row.try_get::<_, Option<String>>(0).db()? else { return Ok(None) };
1737            Ok(Some(ClassBinding { class_hash, tx: row.try_get(1).db()? }))
1738        })
1739    }
1740
1741    fn class_names_bound_to(&self, class_hash: &str, at: &str) -> Result<Vec<String>> {
1742        check_hex(class_hash, 64, "class_hash")?;
1743        check_instant(at, "at")?;
1744        self.run("class_names_bound_to", |c| {
1745            let st = c.stmt(Q::ClassNamesBound)?;
1746            let rows = c.client.query(&st, &[&class_hash, &at]).db()?;
1747            rows.iter().map(|r| r.try_get(0).db()).collect()
1748        })
1749    }
1750
1751    fn resolve_binding(&self, fn_name: &str, asof: &str) -> Result<Option<Binding>> {
1752        check_function_name(fn_name, "fn_name")?;
1753        check_instant(asof, "asof")?;
1754        self.run("resolve_binding", |c| {
1755            let st = c.stmt(Q::BindingAsof)?;
1756            let Some(row) = c.client.query_opt(&st, &[&fn_name, &asof]).db()? else { return Ok(None) };
1757            // A closed binding (0.6.0) has no function hash: the name is unbound from its tx on.
1758            let Some(fn_hash) = row.try_get::<_, Option<String>>(0).db()? else { return Ok(None) };
1759            Ok(Some(Binding { fn_hash, tx: row.try_get(1).db()? }))
1760        })
1761    }
1762
1763    fn resolve_name(&self, fn_name: &str, asof: &str) -> Result<Option<String>> {
1764        check_function_name(fn_name, "fn_name")?;
1765        check_instant(asof, "asof")?;
1766        self.run("resolve_name", |c| {
1767            let st = c.stmt(Q::NameAsof)?;
1768            let row = c.client.query_opt(&st, &[&fn_name, &asof]).db()?;
1769            // NULL for a closed binding (0.6.0): the name means nothing from then on.
1770            Ok(match row {
1771                Some(r) => r.try_get::<_, Option<String>>(0).db()?,
1772                None => None,
1773            })
1774        })
1775    }
1776
1777    fn upsert_catalog(&self, entries: &[CatalogEntry]) -> Result<Vec<i64>> {
1778        for e in entries {
1779            check_catalog_entry(e)?;
1780        }
1781        let rows: Vec<CatalogRow> = entries.iter().map(CatalogRow::plain).collect();
1782        self.write_catalog(&rows, false)
1783    }
1784
1785    fn upsert_catalog_ext(&self, entries: &[CatalogEntryExt]) -> Result<Vec<i64>> {
1786        for e in entries {
1787            check_catalog_ext(e)?;
1788        }
1789        let rows: Vec<CatalogRow> = entries.iter().map(CatalogRow::ext).collect();
1790        self.write_catalog(&rows, true)
1791    }
1792
1793    fn upsert_key_values(&self, owner: &str, key: &str, values: &[KeyValue]) -> Result<Vec<i64>> {
1794        check_key_values(owner, key, values)?;
1795        if values.is_empty() {
1796            return Ok(Vec::new());
1797        }
1798        self.run("upsert_key_values", |c| {
1799            let mut t = c.client.transaction().db()?;
1800            let mut ids = Vec::with_capacity(values.len());
1801            for v in values {
1802                let before = t
1803                    .query_opt("SELECT label, value FROM key_values WHERE owner = $1 AND key = $2 AND value = $3", &[&owner, &key, &v.value])
1804                    .db()?
1805                    .map(|r| -> Result<(String, String)> { Ok((r.try_get(0).db()?, r.try_get(1).db()?)) })
1806                    .transpose()?;
1807                let id: i64 = t
1808                    .query_one(
1809                        "INSERT INTO key_values (owner, key, value, label, aliases) VALUES ($1, $2, $3, $4, $5)
1810                         ON CONFLICT (owner, key, value) DO UPDATE SET label = EXCLUDED.label, aliases = EXCLUDED.aliases
1811                         RETURNING id",
1812                        &[&owner, &key, &v.value, &v.label, &v.aliases],
1813                    )
1814                    .db()?
1815                    .try_get(0)
1816                    .db()?;
1817                if let Some((label, value)) = before {
1818                    if self.vectors && value_text(&label, &value) != value_text(&v.label, &v.value) {
1819                        t.execute("DELETE FROM embeddings WHERE ref_kind = 'value' AND ref_id = $1", &[&id]).db()?;
1820                    }
1821                }
1822                ids.push(id);
1823            }
1824            t.commit().db()?;
1825            Ok(ids)
1826        })
1827    }
1828
1829    fn refresh_value_counts(&self) -> Result<u64> {
1830        self.run("refresh_value_counts", |c| {
1831            c.client
1832                .execute(
1833                    "WITH counts AS (
1834                         SELECT e.name AS owner, a.name AS key, a.value AS value, count(*) AS n
1835                           FROM catalog_entries e JOIN cell_args a ON a.fn_hash = e.hash
1836                          WHERE e.kind = 'function'
1837                          GROUP BY e.name, a.name, a.value)
1838                     UPDATE key_values kv SET n_cells = x.n
1839                       FROM (SELECT v.id, COALESCE(c.n, 0) AS n
1840                               FROM key_values v
1841                               LEFT JOIN counts c ON c.owner = v.owner AND c.key = v.key AND c.value = v.value) x
1842                      WHERE x.id = kv.id",
1843                    &[],
1844                )
1845                .db()
1846        })
1847    }
1848
1849    fn text_find(&self, query: &str, limit: usize) -> Result<Vec<Hit>> {
1850        let Some(words) = Words::new(query) else { return Ok(Vec::new()) };
1851        if limit == 0 {
1852            return Ok(Vec::new());
1853        }
1854        // The words (lower-cased) are $1; the prefilter's patterns follow; the LIMIT is last.
1855        // The scores are computed in SQL (migration 12), so each table is ordered and cut in SQL.
1856        let word_list: Vec<String> = words.words().to_vec();
1857        let entry_where = like_where(&words, &["name", "label", "description", "args"], 2);
1858        let value_where = like_where(&words, &["value", "label", "array_to_string(aliases, ' ')"], 2);
1859        let cap = limit;
1860        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
1861        self.run("text_find", |c| {
1862            let mut hits = Vec::new();
1863            let mut params: Vec<Box<dyn postgres::types::ToSql + Sync>> = vec![Box::new(word_list.clone())];
1864            params.extend(entry_where.1.iter().map(|p| Box::new(p.clone()) as Box<dyn postgres::types::ToSql + Sync>));
1865            params.push(Box::new(limit));
1866            let sql = format!(
1867                "SELECT * FROM (SELECT id, kind, name, hash, label, description, args, examples, source, signed_by,
1868                        datumesh_entry_total($1::text[], name, label, description, args) AS total
1869                   FROM catalog_entries WHERE TRUE{}) e
1870                  WHERE total IS NOT NULL ORDER BY total DESC, name COLLATE \"C\" LIMIT ${}",
1871                entry_where.0,
1872                params.len()
1873            );
1874            let refs: Vec<&(dyn postgres::types::ToSql + Sync)> = params.iter().map(|p| p.as_ref() as _).collect();
1875            for r in c.client.query(&sql, &refs).db()? {
1876                let entry = entry_from_columns(
1877                    &r.try_get::<_, String>(1).db()?,
1878                    r.try_get(2).db()?,
1879                    r.try_get(3).db()?,
1880                    r.try_get(4).db()?,
1881                    r.try_get(5).db()?,
1882                    &r.try_get::<_, String>(6).db()?,
1883                    &r.try_get::<_, String>(7).db()?,
1884                    &r.try_get::<_, String>(8).db()?,
1885                    r.try_get(9).db()?,
1886                )?;
1887                let total: i32 = r.try_get(10).db()?;
1888                hits.push(Hit::Entry { id: r.try_get(0).db()?, entry, score: words.score_of(total as u32) });
1889            }
1890            let mut params: Vec<Box<dyn postgres::types::ToSql + Sync>> = vec![Box::new(word_list.clone())];
1891            params.extend(value_where.1.iter().map(|p| Box::new(p.clone()) as Box<dyn postgres::types::ToSql + Sync>));
1892            params.push(Box::new(limit));
1893            let sql = format!(
1894                "SELECT * FROM (SELECT id, owner, key, value, label, aliases,
1895                        datumesh_value_total($1::text[], value, label, aliases) AS total
1896                   FROM key_values WHERE TRUE{}) v
1897                  WHERE total IS NOT NULL
1898                  ORDER BY total DESC, (owner || chr(1) || key || chr(1) || value) COLLATE \"C\" LIMIT ${}",
1899                value_where.0,
1900                params.len()
1901            );
1902            let refs: Vec<&(dyn postgres::types::ToSql + Sync)> = params.iter().map(|p| p.as_ref() as _).collect();
1903            for r in c.client.query(&sql, &refs).db()? {
1904                let aliases: Vec<String> = r.try_get(5).db()?;
1905                let (value, label): (String, String) = (r.try_get(3).db()?, r.try_get(4).db()?);
1906                let total: i32 = r.try_get(6).db()?;
1907                hits.push(Hit::Value {
1908                    id: r.try_get(0).db()?,
1909                    owner: r.try_get(1).db()?,
1910                    key: r.try_get(2).db()?,
1911                    value,
1912                    label,
1913                    aliases,
1914                    score: words.score_of(total as u32),
1915                });
1916            }
1917            Ok(rank(hits, cap))
1918        })
1919    }
1920
1921    fn vector_find(&self, model: &str, vec: &[f32], limit: usize) -> Result<Vec<Hit>> {
1922        self.vectors_or_unsupported()?;
1923        let lit = vector_literal(vec)?;
1924        check_model(model)?;
1925        if limit == 0 {
1926            return Ok(Vec::new());
1927        }
1928        self.run("vector_find", |c| {
1929            let near = c
1930                .client
1931                .query(
1932                    "SELECT ref_kind, ref_id, (vec <=> $2::text::vector)::float8 FROM embeddings
1933                      WHERE model = $1 ORDER BY vec <=> $2::text::vector LIMIT $3",
1934                    &[&model, &lit, &as_i64(limit)],
1935                )
1936                .db()?;
1937            let mut order = Vec::with_capacity(near.len());
1938            for r in &near {
1939                order.push((r.try_get::<_, String>(0).db()?, r.try_get::<_, i64>(1).db()?, r.try_get::<_, f64>(2).db()?));
1940            }
1941            let entry_ids: Vec<i64> = order.iter().filter(|o| o.0 == "entry").map(|o| o.1).collect();
1942            let value_ids: Vec<i64> = order.iter().filter(|o| o.0 == "value").map(|o| o.1).collect();
1943            let mut entries = HashMap::new();
1944            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()? {
1945                let entry = entry_from_columns(
1946                    &r.try_get::<_, String>(1).db()?,
1947                    r.try_get(2).db()?,
1948                    r.try_get(3).db()?,
1949                    r.try_get(4).db()?,
1950                    r.try_get(5).db()?,
1951                    &r.try_get::<_, String>(6).db()?,
1952                    &r.try_get::<_, String>(7).db()?,
1953                    &r.try_get::<_, String>(8).db()?,
1954                    r.try_get(9).db()?,
1955                )?;
1956                entries.insert(r.try_get::<_, i64>(0).db()?, entry);
1957            }
1958            let mut values = HashMap::new();
1959            for r in c.client.query("SELECT id, owner, key, value, label, aliases FROM key_values WHERE id = ANY($1)", &[&value_ids]).db()? {
1960                values.insert(
1961                    r.try_get::<_, i64>(0).db()?,
1962                    (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()?),
1963                );
1964            }
1965            let mut hits = Vec::with_capacity(order.len());
1966            for (kind, id, dist) in order {
1967                let score = 1.0 - dist;
1968                if kind == "entry" {
1969                    if let Some(entry) = entries.remove(&id) {
1970                        hits.push(Hit::Entry { id, entry, score });
1971                    }
1972                } else if let Some((owner, key, value, label, aliases)) = values.remove(&id) {
1973                    hits.push(Hit::Value { id, owner, key, value, label, aliases, score });
1974                }
1975            }
1976            Ok(hits)
1977        })
1978    }
1979
1980    fn put_embeddings(&self, model: &str, items: &[Embedding]) -> Result<()> {
1981        self.vectors_or_unsupported()?;
1982        check_model(model)?;
1983        let lits: Vec<String> = items.iter().map(|i| vector_literal(&i.vec)).collect::<Result<_>>()?;
1984        if items.is_empty() {
1985            return Ok(());
1986        }
1987        self.run("put_embeddings", |c| {
1988            let mut t = c.client.transaction().db()?;
1989            for (item, lit) in items.iter().zip(&lits) {
1990                let (exists, what) = match item.ref_kind {
1991                    EmbedRef::Entry => ("SELECT 1 FROM catalog_entries WHERE id = $1", "catalog entry"),
1992                    EmbedRef::Value => ("SELECT 1 FROM key_values WHERE id = $1", "dictionary value"),
1993                };
1994                if t.query_opt(exists, &[&item.ref_id]).db()?.is_none() {
1995                    return Err(Error::NotFound { what, key: item.ref_id.to_string() });
1996                }
1997                t.execute(
1998                    "INSERT INTO embeddings (ref_kind, ref_id, model, vec) VALUES ($1, $2, $3, $4::text::vector)
1999                     ON CONFLICT (ref_kind, ref_id, model) DO UPDATE SET vec = EXCLUDED.vec",
2000                    &[&item.ref_kind.as_str(), &item.ref_id, &model, lit],
2001                )
2002                .db()?;
2003            }
2004            t.commit().db()?;
2005            Ok(())
2006        })
2007    }
2008
2009    fn pending_embeddings(&self, model: &str, limit: usize) -> Result<Vec<PendingEmbedding>> {
2010        if !self.vectors {
2011            return Ok(Vec::new());
2012        }
2013        check_model(model)?;
2014        if limit == 0 {
2015            return Ok(Vec::new());
2016        }
2017        self.run("pending_embeddings", |c| {
2018            let rows = c
2019                .client
2020                .query(
2021                    "SELECT k, id, t FROM (
2022                         SELECT 'entry' AS k, e.id AS id,
2023                                CASE WHEN e.label = '' THEN e.description ELSE e.label || '. ' || e.description END AS t
2024                           FROM catalog_entries e
2025                          WHERE NOT EXISTS (SELECT 1 FROM embeddings m WHERE m.ref_kind = 'entry' AND m.ref_id = e.id AND m.model = $1)
2026                         UNION ALL
2027                         SELECT 'value', v.id, CASE WHEN v.label = '' THEN v.value ELSE v.label END
2028                           FROM key_values v
2029                          WHERE NOT EXISTS (SELECT 1 FROM embeddings m WHERE m.ref_kind = 'value' AND m.ref_id = v.id AND m.model = $1)
2030                     ) x
2031                     ORDER BY CASE k WHEN 'entry' THEN 0 ELSE 1 END, id LIMIT $2",
2032                    &[&model, &as_i64(limit)],
2033                )
2034                .db()?;
2035            rows.iter()
2036                .map(|r| {
2037                    let ref_kind = match r.try_get::<_, String>(0).db()?.as_str() {
2038                        "entry" => EmbedRef::Entry,
2039                        _ => EmbedRef::Value,
2040                    };
2041                    Ok(PendingEmbedding { ref_kind, ref_id: r.try_get(1).db()?, text: r.try_get(2).db()? })
2042                })
2043                .collect()
2044        })
2045    }
2046
2047    fn vector_available(&self) -> bool {
2048        self.vectors
2049    }
2050
2051    fn log_miss(&self, query: &str) -> Result<()> {
2052        let Some(q) = miss_text(query) else { return Ok(()) };
2053        self.run("log_miss", |c| {
2054            let mut t = c.client.transaction().db()?;
2055            t.execute("INSERT INTO find_misses (query) VALUES ($1)", &[&q]).db()?;
2056            // Keep the newest FIND_MISSES_CAP rows: prune the oldest beyond that.
2057            t.execute(
2058                "DELETE FROM find_misses WHERE ctid IN (SELECT ctid FROM find_misses ORDER BY at
2059                     LIMIT GREATEST((SELECT count(*) FROM find_misses) - $1, 0))",
2060                &[&as_i64(FIND_MISSES_CAP)],
2061            )
2062            .db()?;
2063            t.commit().db()?;
2064            Ok(())
2065        })
2066    }
2067
2068    fn put_function_test(&self, test: &FunctionTest) -> Result<bool> {
2069        let (total, covered) = crate::functions::check_test(test)?;
2070        self.run("put_function_test", |c| {
2071            let st = c.stmt(Q::FunctionTestPut)?;
2072            let ensure = c.stmt(Q::CounterEnsure)?;
2073            let add = c.stmt(Q::CounterAdd)?;
2074            let mut t = c.client.transaction().db()?;
2075            let n = t
2076                .execute(
2077                    &st,
2078                    &[
2079                        &test.fn_hash,
2080                        &test.case,
2081                        &test.test_json,
2082                        &test.signed_by,
2083                        &test.last_run_at,
2084                        &test.last_result,
2085                        &test.last_detail,
2086                        &total,
2087                        &covered,
2088                    ],
2089                )
2090                .db()?;
2091            if n == 1 {
2092                let results = crate::functions::result_counts(test.last_result.as_deref());
2093                let last = test.last_run_at.as_deref();
2094                bump_counter(&mut t, &ensure, &add, &test.fn_hash, "", 1, results, last, (total, covered))?;
2095            }
2096            t.commit().db()?;
2097            Ok(n == 1)
2098        })
2099    }
2100
2101    fn function_test(&self, fn_hash: &str, case: &str) -> Result<Option<FunctionTest>> {
2102        check_hex(fn_hash, 64, "fn_hash")?;
2103        crate::functions::check_case(case)?;
2104        self.run("function_test", |c| {
2105            let st = c.stmt(Q::FunctionTestOne)?;
2106            c.client.query_opt(&st, &[&fn_hash, &case]).db()?.as_ref().map(function_test_row).transpose()
2107        })
2108    }
2109
2110    fn function_tests_failing(&self, fn_hash: &str, fn_name: Option<&str>, limit: usize) -> Result<Vec<FunctionTest>> {
2111        check_hex(fn_hash, 64, "fn_hash")?;
2112        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2113        self.run("function_tests_failing", |c| {
2114            let st = c.stmt(Q::FunctionTestsFailing)?;
2115            let rows = c.client.query(&st, &[&fn_hash, &fn_name, &limit]).db()?;
2116            rows.iter().map(function_test_row).collect()
2117        })
2118    }
2119
2120    fn false_test_cells(&self, fn_hash: &str, limit: usize) -> Result<Vec<(String, Vec<u8>)>> {
2121        check_hex(fn_hash, 64, "fn_hash")?;
2122        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2123        self.run("false_test_cells", |c| {
2124            let st = c.stmt(Q::FalseTestCells)?;
2125            let rows = c.client.query(&st, &[&fn_hash, &limit]).db()?;
2126            rows.iter().map(|r| -> Result<(String, Vec<u8>)> { Ok((r.try_get(0).db()?, r.try_get(1).db()?)) }).collect()
2127        })
2128    }
2129
2130    fn dependants_of(&self, name: &str, at: &str, limit: usize) -> Result<Vec<(String, String)>> {
2131        check_function_name(name, "name")?;
2132        check_instant(at, "at")?;
2133        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2134        self.run("dependants_of", |c| {
2135            let st = c.stmt(Q::DependantsOf)?;
2136            let rows = c.client.query(&st, &[&name, &at, &limit]).db()?;
2137            rows.iter().map(|r| -> Result<(String, String)> { Ok((r.try_get(0).db()?, r.try_get(1).db()?)) }).collect()
2138        })
2139    }
2140
2141    fn slice_values_page(
2142        &self,
2143        slice: &Slice,
2144        asof: &str,
2145        after_cell_id: Option<&str>,
2146        limit: usize,
2147    ) -> Result<Vec<SliceValue>> {
2148        check_instant(asof, "asof")?;
2149        if limit == 0 {
2150            return Ok(Vec::new());
2151        }
2152        let v = slice.to_value();
2153        if version_slice(slice, &v)?.is_some() {
2154            // A version slice is one cell's versions: paged here, from its values.
2155            let mut values = self.slice_values(slice, asof)?;
2156            values.retain(|x| after_cell_id.is_none_or(|a| x.version.cell_id.as_str() > a));
2157            values.sort_by(|a, b| a.version.cell_id.cmp(&b.version.cell_id));
2158            values.truncate(limit);
2159            return Ok(values);
2160        }
2161        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2162        let pattern = Pattern::of(&v)?;
2163        self.run("slice_values_page", |c| pattern.values_page(c, asof, after_cell_id, limit))
2164    }
2165
2166    fn catalog_entries_all(&self, limit: usize) -> Result<Vec<(CatalogKind, String, String, String)>> {
2167        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2168        self.run("catalog_entries_all", |c| {
2169            let st = c.stmt(Q::CatalogEntriesAll)?;
2170            let rows = c.client.query(&st, &[&limit]).db()?;
2171            rows.iter()
2172                .map(|r| -> Result<(CatalogKind, String, String, String)> {
2173                    let kind = CatalogKind::parse(&r.try_get::<_, String>(0).db()?)
2174                        .ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
2175                    Ok((kind, r.try_get(1).db()?, r.try_get(2).db()?, r.try_get(3).db()?))
2176                })
2177                .collect()
2178        })
2179    }
2180
2181    fn dictionary_values_ordered(&self, owner: &str, key: &str, limit: usize) -> Result<Vec<String>> {
2182        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2183        self.run("dictionary_values_ordered", |c| {
2184            let st = c.stmt(Q::DictionaryValuesOrdered)?;
2185            let rows = c.client.query(&st, &[&owner, &key, &limit]).db()?;
2186            rows.iter().map(|r| r.try_get::<_, String>(0).db()).collect()
2187        })
2188    }
2189
2190    fn function_tests(&self, fn_hash: &str) -> Result<Vec<FunctionTest>> {
2191        check_hex(fn_hash, 64, "fn_hash")?;
2192        self.run("function_tests", |c| {
2193            let st = c.stmt(Q::FunctionTestsOf)?;
2194            let rows = c.client.query(&st, &[&fn_hash]).db()?;
2195            rows.iter().map(function_test_row).collect()
2196        })
2197    }
2198
2199    fn record_function_test(
2200        &self,
2201        fn_hash: &str,
2202        case: &str,
2203        run_at: &str,
2204        result: &str,
2205        detail: &str,
2206    ) -> Result<bool> {
2207        check_hex(fn_hash, 64, "fn_hash")?;
2208        crate::functions::check_case(case)?;
2209        check_instant(run_at, "run_at")?;
2210        crate::functions::check_result(result)?;
2211        self.run("record_function_test", |c| {
2212            let st = c.stmt(Q::FunctionTestRecord)?;
2213            let old_st = c.stmt(Q::FunctionTestOld)?;
2214            let ensure = c.stmt(Q::CounterEnsure)?;
2215            let add = c.stmt(Q::CounterAdd)?;
2216            let recompute = c.stmt(Q::CounterRunRecompute)?;
2217            let mut t = c.client.transaction().db()?;
2218            let Some(old) = t.query_opt(&old_st, &[&fn_hash, &case]).db()? else { return Ok(false) };
2219            let old_name: Option<String> = old.try_get(0).db()?;
2220            let old_result: Option<String> = old.try_get(1).db()?;
2221            t.execute(&st, &[&run_at, &result, &detail, &fn_hash, &case]).db()?;
2222            // The test moves within its row: the row's counts change by the difference.
2223            let (before, after) =
2224                (crate::functions::result_counts(old_result.as_deref()), crate::functions::result_counts(Some(result)));
2225            let row = old_name.unwrap_or_default();
2226            let d: Vec<i64> = after.iter().zip(before.iter()).map(|(a, b)| a - b).collect();
2227            let results = [d[0], d[1], d[2], d[3]];
2228            bump_counter(&mut t, &ensure, &add, fn_hash, &row, 0, results, None, (0, 0))?;
2229            t.execute(&recompute, &[&fn_hash, &row]).db()?;
2230            t.commit().db()?;
2231            Ok(true)
2232        })
2233    }
2234
2235    fn set_function_branches(&self, fn_hash: &str, total: u32, covered: u32) -> Result<()> {
2236        check_hex(fn_hash, 64, "fn_hash")?;
2237        let (total, covered) = crate::functions::branch_counts(total, covered)?;
2238        self.run("set_function_branches", |c| {
2239            let st = c.stmt(Q::FunctionBranches)?;
2240            c.client.execute(&st, &[&fn_hash, &total, &covered]).db()?;
2241            Ok(())
2242        })
2243    }
2244
2245    fn function_readers(&self, name: &str) -> Result<Vec<String>> {
2246        check_function_name(name, "name")?;
2247        self.run("function_readers", |c| get_strings(c, Q::FunctionReaders, name))
2248    }
2249
2250    fn bound_names(&self, fn_hash: &str) -> Result<Vec<String>> {
2251        check_hex(fn_hash, 64, "fn_hash")?;
2252        self.run("bound_names", |c| get_strings(c, Q::BoundNames, fn_hash))
2253    }
2254
2255    fn name_function_tests(&self, fn_hash: &str, names: &[(String, String)]) -> Result<u64> {
2256        check_hex(fn_hash, 64, "fn_hash")?;
2257        for (case, name) in names {
2258            crate::functions::check_case(case)?;
2259            check_function_name(name, "name")?;
2260        }
2261        if names.is_empty() {
2262            return Ok(0);
2263        }
2264        let cases: Vec<String> = names.iter().map(|(c, _)| c.clone()).collect();
2265        let fn_names: Vec<String> = names.iter().map(|(_, n)| n.clone()).collect();
2266        self.run("name_function_tests", |c| {
2267            let st = c.stmt(Q::FunctionTestName)?;
2268            let ensure = c.stmt(Q::CounterEnsure)?;
2269            let add = c.stmt(Q::CounterAdd)?;
2270            let recompute = c.stmt(Q::CounterRunRecompute)?;
2271            let mut t = c.client.transaction().db()?;
2272            let named = t.query(&st, &[&fn_hash, &cases, &fn_names]).db()?;
2273            // The rows moved from unnamed to their names, with their results: [tests, pass,
2274            // fail, error, not_run] per name.
2275            let mut moved: std::collections::BTreeMap<String, [i64; 5]> = std::collections::BTreeMap::new();
2276            for r in &named {
2277                let name: String = r.try_get(0).db()?;
2278                let result: Option<String> = r.try_get(1).db()?;
2279                let d = crate::functions::result_counts(result.as_deref());
2280                let e = moved.entry(name).or_insert([0; 5]);
2281                e[0] += 1;
2282                for (i, x) in d.iter().enumerate() {
2283                    e[i + 1] += x;
2284                }
2285            }
2286            let unnamed = "";
2287            for (name, d) in &moved {
2288                let results = [d[1], d[2], d[3], d[4]];
2289                let minus = results.map(|x| -x);
2290                bump_counter(&mut t, &ensure, &add, fn_hash, name, d[0], results, None, (0, 0))?;
2291                bump_counter(&mut t, &ensure, &add, fn_hash, unnamed, -d[0], minus, None, (0, 0))?;
2292                t.execute(&recompute, &[&fn_hash, name]).db()?;
2293            }
2294            if !moved.is_empty() {
2295                t.execute(&recompute, &[&fn_hash, &unnamed]).db()?;
2296            }
2297            t.commit().db()?;
2298            Ok(named.len() as u64)
2299        })
2300    }
2301
2302    fn unnamed_function_tests(&self, limit: usize) -> Result<Vec<FunctionTest>> {
2303        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2304        self.run("unnamed_function_tests", |c| {
2305            let st = c.stmt(Q::FunctionTestsUnnamed)?;
2306            let rows = c.client.query(&st, &[&limit]).db()?;
2307            rows.iter().map(function_test_row).collect()
2308        })
2309    }
2310
2311    fn function_test_summary(&self, fn_hash: &str, fn_name: Option<&str>) -> Result<TestSummary> {
2312        check_hex(fn_hash, 64, "fn_hash")?;
2313        self.run("function_test_summary", |c| {
2314            let st = c.stmt(Q::FunctionTestSummary)?;
2315            let r = c.client.query_one(&st, &[&fn_hash, &fn_name]).db()?;
2316            // The counts are bigint, the branch counts integer (at least zero): exact casts.
2317            let count = |i: usize| -> Result<u64> { Ok(r.try_get::<_, i64>(i).db()? as u64) };
2318            let total: i32 = r.try_get(6).db()?;
2319            let covered: i32 = r.try_get(7).db()?;
2320            Ok(TestSummary {
2321                count: count(0)?,
2322                pass: count(1)?,
2323                fail: count(2)?,
2324                error: count(3)?,
2325                not_run: count(4)?,
2326                last_run_at: r.try_get(5).db()?,
2327                branches_total: total as u32,
2328                branches_covered: covered as u32,
2329            })
2330        })
2331    }
2332
2333    fn function_tests_page(
2334        &self,
2335        fn_hash: &str,
2336        fn_name: Option<&str>,
2337        after_case: Option<&str>,
2338        limit: usize,
2339    ) -> Result<Vec<FunctionTest>> {
2340        check_hex(fn_hash, 64, "fn_hash")?;
2341        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2342        self.run("function_tests_page", |c| {
2343            let rows = match fn_name {
2344                None => {
2345                    let st = c.stmt(Q::FunctionTestsPage)?;
2346                    c.client.query(&st, &[&fn_hash, &after_case, &limit]).db()?
2347                }
2348                Some(name) => {
2349                    let st = c.stmt(Q::FunctionTestsPageNamed)?;
2350                    c.client.query(&st, &[&fn_hash, &name, &after_case, &limit]).db()?
2351                }
2352            };
2353            rows.iter().map(function_test_row).collect()
2354        })
2355    }
2356
2357    fn stored_receipts_of(&self, ns: &str, fn_name: &str, fn_hash: &str, limit: usize) -> Result<Vec<Vec<u8>>> {
2358        check_hex(fn_hash, 64, "fn_hash")?;
2359        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2360        self.run("stored_receipts_of", |c| {
2361            let st = c.stmt(Q::StoredReceiptsOf)?;
2362            let rows = c.client.query(&st, &[&fn_hash, &ns, &fn_name, &limit]).db()?;
2363            rows.iter().map(|r| r.try_get::<_, Vec<u8>>(0).db()).collect()
2364        })
2365    }
2366
2367    fn slice_page(&self, slice: &Slice, asof: &str, after: Option<&[u8]>, limit: usize) -> Result<Vec<SliceValue>> {
2368        check_instant(asof, "asof")?;
2369        if limit == 0 {
2370            return Ok(Vec::new());
2371        }
2372        let v = slice.to_value();
2373        if version_slice(slice, &v)?.is_some() {
2374            return Err(Error::Unsupported("a version slice has no key order to page by".into()));
2375        }
2376        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2377        let pattern = Pattern::of(&v)?;
2378        self.run("slice_page", |c| pattern.values_by_key(c, asof, after, limit))
2379    }
2380
2381    fn slice_values_limit(&self, slice: &Slice, asof: &str, limit: usize) -> Result<Vec<SliceValue>> {
2382        check_instant(asof, "asof")?;
2383        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2384        let v = slice.to_value();
2385        if let Some((cell_id, from, to)) = version_slice(slice, &v)? {
2386            return self.run("slice_values_limit", |c| {
2387                // The statement of slice_values, with its LIMIT: the same order (tx).
2388                let sql = format!("{} LIMIT $5", Q::VersionsBetweenValues.sql());
2389                let rows = c.client.query(sql.as_str(), &[&cell_id, &from, &to, &asof, &limit]).db()?;
2390                rows.iter().map(|r| value_row(r, &cell_id)).collect()
2391            });
2392        }
2393        let pattern = Pattern::of(&v)?;
2394        self.run("slice_values_limit", |c| pattern.values_limited(c, asof, limit))
2395    }
2396
2397    fn versions_limit(&self, cell_id: &str, from: &str, to: &str, limit: usize) -> Result<Vec<Version>> {
2398        check_hex(cell_id, 64, "cell_id")?;
2399        check_instant(from, "from")?;
2400        check_instant(to, "to")?;
2401        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2402        self.run("versions_limit", |c| {
2403            let st = c.stmt(Q::VersionRangeLimit)?;
2404            let rows = c.client.query(&st, &[&cell_id, &from, &to, &limit]).db()?;
2405            PgStore::version_rows(&rows, cell_id)
2406        })
2407    }
2408
2409    fn stored_cell_count(&self, ns: &str, fn_name: &str, fn_hash: &str) -> Result<u64> {
2410        check_hex(fn_hash, 64, "fn_hash")?;
2411        self.run("stored_cell_count", |c| {
2412            let st = c.stmt(Q::StoredCellCount)?;
2413            let n: i64 = c.client.query_one(&st, &[&fn_hash, &ns, &fn_name]).db()?.try_get(0).db()?;
2414            Ok(n as u64)
2415        })
2416    }
2417
2418    fn has_key_value(&self, owner: &str, key: &str, value: &str) -> Result<bool> {
2419        self.run("has_key_value", |c| {
2420            let st = c.stmt(Q::DictionaryHas)?;
2421            c.client.query_one(&st, &[&owner, &key, &value]).db()?.try_get(0).db()
2422        })
2423    }
2424
2425    fn key_value_count(&self, owner: &str, key: &str) -> Result<u64> {
2426        self.run("key_value_count", |c| {
2427            let st = c.stmt(Q::DictionaryCount)?;
2428            let n: i64 = c.client.query_one(&st, &[&owner, &key]).db()?.try_get(0).db()?;
2429            Ok(n as u64)
2430        })
2431    }
2432
2433    fn mark_key_open(&self, owner: &str, key: &str) -> Result<()> {
2434        if owner.is_empty() || owner.len() > 512 || key.is_empty() || key.len() > 128 {
2435            return Err(invalid("key", "an owner of 1 to 512 bytes and a key of 1 to 128 bytes"));
2436        }
2437        self.run("mark_key_open", |c| {
2438            let st = c.stmt(Q::KeyOpenPut)?;
2439            c.client.execute(&st, &[&owner, &key]).db()?;
2440            Ok(())
2441        })
2442    }
2443
2444    fn open_key_count(&self) -> Result<u64> {
2445        self.run("open_key_count", |c| {
2446            let st = c.stmt(Q::OpenKeyCount)?;
2447            let n: i64 = c.client.query_one(&st, &[]).db()?.try_get(0).db()?;
2448            Ok(n as u64)
2449        })
2450    }
2451
2452    fn key_is_open(&self, owner: &str, key: &str) -> Result<bool> {
2453        self.run("key_is_open", |c| {
2454            let st = c.stmt(Q::KeyIsOpen)?;
2455            c.client.query_one(&st, &[&owner, &key]).db()?.try_get(0).db()
2456        })
2457    }
2458
2459    fn catalog_entry(&self, name: &str) -> Result<Option<CatalogEntry>> {
2460        self.run("catalog_entry", |c| {
2461            let st = c.stmt(Q::CatalogEntryNamed)?;
2462            let Some(r) = c.client.query_opt(&st, &[&name]).db()? else { return Ok(None) };
2463            entry_from_columns(
2464                &r.try_get::<_, String>(0).db()?,
2465                r.try_get(1).db()?,
2466                r.try_get(2).db()?,
2467                r.try_get(3).db()?,
2468                r.try_get(4).db()?,
2469                &r.try_get::<_, String>(5).db()?,
2470                &r.try_get::<_, String>(6).db()?,
2471                &r.try_get::<_, String>(7).db()?,
2472                r.try_get(8).db()?,
2473            )
2474            .map(Some)
2475        })
2476    }
2477
2478    fn catalog_entry_ext(&self, kind: CatalogKind, name: &str) -> Result<Option<CatalogEntryExt>> {
2479        self.run("catalog_entry_ext", |c| {
2480            let Some(r) = c.client.query_opt(CATALOG_EXT_SELECT_BY_KIND_NAME, &[&kind.as_str(), &name]).db()? else {
2481                return Ok(None);
2482            };
2483            ext_from_row(&r).map(Some)
2484        })
2485    }
2486
2487    fn catalog_entries_with_facets(&self) -> Result<Vec<FacetedEntry>> {
2488        self.run("catalog_entries_with_facets", |c| {
2489            let mut out = Vec::new();
2490            for r in c
2491                .client
2492                .query(
2493                    "SELECT e.kind, e.name, e.hash, e.facets,
2494                        CASE WHEN e.kind = 'class'
2495                             THEN (SELECT min(b.tx) FROM class_bindings b WHERE b.class_name = e.name)
2496                             ELSE (SELECT min(b.tx) FROM name_bindings b WHERE b.fn_name = e.name) END,
2497                        e.source_name
2498                   FROM catalog_entries e
2499                  WHERE e.facets::jsonb <> '{}'::jsonb
2500                  ORDER BY e.kind COLLATE \"C\", e.name COLLATE \"C\"",
2501                    &[],
2502                )
2503                .db()?
2504            {
2505                let kind = CatalogKind::parse(&r.try_get::<_, String>(0).db()?)
2506                    .ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
2507                out.push(FacetedEntry {
2508                    kind,
2509                    name: r.try_get(1).db()?,
2510                    hash: r.try_get(2).db()?,
2511                    facets: parse_facets(&r.try_get::<_, String>(3).db()?)?,
2512                    first_bound: r.try_get(4).db()?,
2513                    source_name: r.try_get(5).db()?,
2514                });
2515            }
2516            Ok(out)
2517        })
2518    }
2519
2520    fn extensions_of(&self, class: &str) -> Result<Vec<CatalogEntryExt>> {
2521        check_function_name(class, "class")?;
2522        self.run("extensions_of", |c| {
2523            let mut out = Vec::new();
2524            for r in c
2525                .client
2526                .query(
2527                    "SELECT kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name
2528                   FROM catalog_entries WHERE extends = $1 ORDER BY name COLLATE \"C\"",
2529                    &[&class],
2530                )
2531                .db()?
2532            {
2533                out.push(ext_from_row(&r)?);
2534            }
2535            Ok(out)
2536        })
2537    }
2538
2539    fn extensions_of_limit(&self, class: &str, limit: usize) -> Result<Vec<CatalogEntryExt>> {
2540        check_function_name(class, "class")?;
2541        let limit = i64::try_from(limit).unwrap_or(i64::MAX);
2542        self.run("extensions_of", |c| {
2543            let mut out = Vec::new();
2544            for r in c
2545                .client
2546                .query(
2547                    "SELECT kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name
2548                   FROM catalog_entries WHERE extends = $1 ORDER BY name COLLATE \"C\" LIMIT $2",
2549                    &[&class, &limit],
2550                )
2551                .db()?
2552            {
2553                out.push(ext_from_row(&r)?);
2554            }
2555            Ok(out)
2556        })
2557    }
2558
2559    fn catalog_summary(&self) -> Result<Summary> {
2560        self.run("catalog_summary", |c| {
2561            let mut entries = Vec::new();
2562            for r in c.client.query(
2563                "SELECT e.kind, e.name, e.label,
2564                        CASE WHEN e.kind = 'function' THEN (SELECT COALESCE(sum(x.n), 0)::bigint FROM cell_counts x WHERE x.fn_hash = e.hash) ELSE 0 END
2565                   FROM catalog_entries e ORDER BY e.kind COLLATE \"C\", e.name COLLATE \"C\"",
2566                &[],
2567            ).db()? {
2568                let kind = CatalogKind::parse(&r.try_get::<_, String>(0).db()?)
2569                    .ok_or_else(|| invalid("catalog", "a stored entry has a bad kind"))?;
2570                entries.push(SummaryEntry { kind, name: r.try_get(1).db()?, label: r.try_get(2).db()?, n_cells: r.try_get(3).db()? });
2571            }
2572            let mut dictionaries = Vec::new();
2573            let groups = c.client.query(
2574                "SELECT owner, key, count(*) FROM key_values GROUP BY owner, key ORDER BY owner COLLATE \"C\", key COLLATE \"C\"",
2575                &[],
2576            ).db()?;
2577            for g in groups {
2578                let (owner, key): (String, String) = (g.try_get(0).db()?, g.try_get(1).db()?);
2579                let mut values = Vec::new();
2580                for r in c.client.query(
2581                    "SELECT value, label, n_cells FROM key_values WHERE owner = $1 AND key = $2
2582                      ORDER BY value COLLATE \"C\" LIMIT $3",
2583                    &[&owner, &key, &as_i64(SUMMARY_VALUES)],
2584                ).db()? {
2585                    values.push(DictionaryValue { value: r.try_get(0).db()?, label: r.try_get(1).db()?, n_cells: r.try_get(2).db()? });
2586                }
2587                dictionaries.push(Dictionary { owner, key, n_values: g.try_get(2).db()?, values });
2588            }
2589            Ok(Summary { entries, dictionaries })
2590        })
2591    }
2592
2593    // ---- Listings (0.7.0; CONTRACT-http-listing L3) ----------------------------------------------
2594
2595    fn put_listing(&self, l: &Listing) -> Result<ListingWrite> {
2596        check_listing(l)?;
2597        let d = FunctionDescriptor::from_json(&l.descriptor)?;
2598        let canonical = d.canonical();
2599        let subjects = subjects_json(&l.subjects);
2600        let facets = listing_facets_json(&l.subjects);
2601        self.run("put_listing", |c| {
2602            let descriptor_put = c.stmt(Q::DescriptorPut)?;
2603            let inputs_put = c.stmt(Q::DescriptorInputsPut)?;
2604            let mut t = c.client.transaction().db()?;
2605            let stored = t
2606                .query_opt(&format!("SELECT {LISTING_COLUMNS} FROM listings WHERE name = $1 FOR UPDATE"), &[&l.name])
2607                .db()?
2608                .map(|r| listing_from_pg(&r))
2609                .transpose()?;
2610            if stored.as_ref().is_some_and(|s| same_listing(s, l)) {
2611                return Ok(ListingWrite::Unchanged);
2612            }
2613            // The descriptor (once) and its inputs, as put_descriptor writes them.
2614            t.execute(&descriptor_put, &[&l.fn_hash, &canonical]).db()?;
2615            if !d.inputs.is_empty() {
2616                t.execute(&inputs_put, &[&l.fn_hash, &d.inputs]).db()?;
2617            }
2618            // The row: listed_at is kept by a change.
2619            t.execute(
2620                "INSERT INTO listings (name, host, fn_hash, subjects, descriptor, key_id, label, description, fetched_at, listed_at)
2621                 VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
2622                 ON CONFLICT (name) DO UPDATE SET host = EXCLUDED.host, fn_hash = EXCLUDED.fn_hash,
2623                     subjects = EXCLUDED.subjects, descriptor = EXCLUDED.descriptor, key_id = EXCLUDED.key_id,
2624                     label = EXCLUDED.label, description = EXCLUDED.description, fetched_at = EXCLUDED.fetched_at",
2625                &[
2626                    &l.name,
2627                    &l.host,
2628                    &l.fn_hash,
2629                    &subjects,
2630                    &l.descriptor,
2631                    &l.key_id,
2632                    &l.label,
2633                    &l.description,
2634                    &l.fetched_at,
2635                    &l.listed_at,
2636                ],
2637            )
2638            .db()?;
2639            // The catalogue entry (source listed); an embedding is dropped when its text changes.
2640            let before = t
2641                .query_opt(
2642                    "SELECT id, label, description FROM catalog_entries WHERE kind = 'function' AND name = $1",
2643                    &[&l.name],
2644                )
2645                .db()?
2646                .map(|r| -> Result<(i64, String, String)> {
2647                    Ok((r.try_get(0).db()?, r.try_get(1).db()?, r.try_get(2).db()?))
2648                })
2649                .transpose()?;
2650            let written =
2651                t.execute(CATALOG_LISTED_UPSERT, &[&l.name, &l.fn_hash, &l.label, &l.description, &l.host, &facets]).db()?;
2652            if written == 0 {
2653                // Another source's entry has this name (decided 27 Nov, C3): nothing is written; the
2654                // transaction is dropped and rolled back.
2655                return Err(crate::catalogue::invalid("name", "a catalogue entry of another source has this name"));
2656            }
2657            if let (true, Some((id, label, description))) = (self.vectors, &before) {
2658                if crate::catalogue::entry_text(label, description) != crate::catalogue::entry_text(&l.label, &l.description)
2659                {
2660                    t.execute("DELETE FROM embeddings WHERE ref_kind = 'entry' AND ref_id = $1", &[id]).db()?;
2661                }
2662            }
2663            t.commit().db()?;
2664            Ok(if stored.is_some() { ListingWrite::Changed } else { ListingWrite::Inserted })
2665        })
2666    }
2667
2668    fn listing(&self, name: &str) -> Result<Option<Listing>> {
2669        self.run("listing", |c| {
2670            let sql = format!("SELECT {LISTING_COLUMNS} FROM listings WHERE name = $1");
2671            c.client.query_opt(&sql, &[&name]).db()?.map(|r| listing_from_pg(&r)).transpose()
2672        })
2673    }
2674
2675    fn listings_of(&self, host: &str) -> Result<Vec<Listing>> {
2676        self.run("listings_of", |c| {
2677            let sql = format!("SELECT {LISTING_COLUMNS} FROM listings WHERE host = $1 ORDER BY name");
2678            c.client.query(&sql, &[&host]).db()?.iter().map(listing_from_pg).collect()
2679        })
2680    }
2681
2682    fn listing_count(&self) -> Result<u64> {
2683        self.run("listing_count", |c| {
2684            let n: i64 = c.client.query_one("SELECT count(*) FROM listings", &[]).db()?.try_get(0).db()?;
2685            Ok(u64::try_from(n).unwrap_or(0))
2686        })
2687    }
2688
2689    fn delete_listing(&self, name: &str) -> Result<bool> {
2690        self.run("delete_listing", |c| {
2691            let mut t = c.client.transaction().db()?;
2692            if self.vectors {
2693                t.execute(
2694                    "DELETE FROM embeddings WHERE ref_kind = 'entry' AND ref_id IN (SELECT id FROM catalog_entries
2695                     WHERE kind = 'function' AND source = 'listed' AND name = $1)",
2696                    &[&name],
2697                )
2698                .db()?;
2699            }
2700            t.execute(
2701                "DELETE FROM catalog_entries WHERE kind = 'function' AND source = 'listed' AND name = $1",
2702                &[&name],
2703            )
2704            .db()?;
2705            let removed = t.execute("DELETE FROM listings WHERE name = $1", &[&name]).db()?;
2706            t.commit().db()?;
2707            Ok(removed > 0)
2708        })
2709    }
2710
2711    fn set_listing_unreached(&self, name: &str, since: Option<&str>) -> Result<bool> {
2712        if since.is_some_and(|s| !is_instant(s)) {
2713            return Err(crate::catalogue::invalid("since", "an instant (YYYY-MM-DDThh:mm:ss.ffffffZ)"));
2714        }
2715        self.run("set_listing_unreached", |c| {
2716            let mut t = c.client.transaction().db()?;
2717            let stored: Option<Option<String>> = t
2718                .query_opt("SELECT unreached_since FROM listings WHERE name = $1 FOR UPDATE", &[&name])
2719                .db()?
2720                .map(|r| r.try_get(0).db())
2721                .transpose()?;
2722            let Some(stored) = stored else {
2723                return Err(Error::NotFound { what: "listing", key: name.to_string() });
2724            };
2725            if stored.as_deref() == since {
2726                return Ok(false);
2727            }
2728            t.execute("UPDATE listings SET unreached_since = $2 WHERE name = $1", &[&name, &since]).db()?;
2729            t.commit().db()?;
2730            Ok(true)
2731        })
2732    }
2733
2734    fn listing_unreached(&self, name: &str) -> Result<Option<String>> {
2735        self.run("listing_unreached", |c| {
2736            let row = c.client.query_opt("SELECT unreached_since FROM listings WHERE name = $1", &[&name]).db()?;
2737            Ok(match row {
2738                Some(r) => r.try_get::<_, Option<String>>(0).db()?,
2739                None => None,
2740            })
2741        })
2742    }
2743
2744    fn put_listed_host(&self, h: &ListedHost) -> Result<bool> {
2745        check_listed_host(h)?;
2746        self.run("put_listed_host", |c| {
2747            let mut t = c.client.transaction().db()?;
2748            let stored = t
2749                .query_opt(
2750                    "SELECT host, last_seen, unreachable_since FROM listed_hosts WHERE host = $1 FOR UPDATE",
2751                    &[&h.host],
2752                )
2753                .db()?
2754                .map(|r| listed_host_pg(&r))
2755                .transpose()?;
2756            if stored.as_ref() == Some(h) {
2757                return Ok(false);
2758            }
2759            t.execute(
2760                "INSERT INTO listed_hosts (host, last_seen, unreachable_since) VALUES ($1, $2, $3)
2761                 ON CONFLICT (host) DO UPDATE SET last_seen = EXCLUDED.last_seen,
2762                     unreachable_since = EXCLUDED.unreachable_since",
2763                &[&h.host, &h.last_seen, &h.unreachable_since],
2764            )
2765            .db()?;
2766            t.commit().db()?;
2767            Ok(true)
2768        })
2769    }
2770
2771    fn listed_host(&self, host: &str) -> Result<Option<ListedHost>> {
2772        self.run("listed_host", |c| {
2773            c.client
2774                .query_opt("SELECT host, last_seen, unreachable_since FROM listed_hosts WHERE host = $1", &[&host])
2775                .db()?
2776                .map(|r| listed_host_pg(&r))
2777                .transpose()
2778        })
2779    }
2780
2781    fn listed_hosts(&self) -> Result<Vec<ListedHost>> {
2782        self.run("listed_hosts", |c| {
2783            c.client
2784                .query("SELECT host, last_seen, unreachable_since FROM listed_hosts ORDER BY host", &[])
2785                .db()?
2786                .iter()
2787                .map(listed_host_pg)
2788                .collect()
2789        })
2790    }
2791
2792    fn delete_listed_host(&self, host: &str) -> Result<bool> {
2793        self.run("delete_listed_host", |c| {
2794            let mut t = c.client.transaction().db()?;
2795            let listed = "SELECT name FROM listings WHERE host = $1";
2796            if self.vectors {
2797                t.execute(
2798                    &format!(
2799                        "DELETE FROM embeddings WHERE ref_kind = 'entry' AND ref_id IN (SELECT id FROM catalog_entries
2800                         WHERE kind = 'function' AND source = 'listed' AND name IN ({listed}))"
2801                    ),
2802                    &[&host],
2803                )
2804                .db()?;
2805            }
2806            t.execute(
2807                &format!(
2808                    "DELETE FROM catalog_entries WHERE kind = 'function' AND source = 'listed' AND name IN ({listed})"
2809                ),
2810                &[&host],
2811            )
2812            .db()?;
2813            t.execute("DELETE FROM listings WHERE host = $1", &[&host]).db()?;
2814            let gone = t.execute("DELETE FROM listed_hosts WHERE host = $1", &[&host]).db()?;
2815            t.commit().db()?;
2816            Ok(gone > 0)
2817        })
2818    }
2819}
2820
2821impl PgStore {
2822    /// Writes catalogue rows, all or nothing, keyed by (kind, name) (the call's bounds are
2823    /// checked by the caller). An operator's row never replaces a publisher's. An existing row
2824    /// keeps its facets and `extends` unless `replace_ext` (the facets call), in which case
2825    /// they are replaced. A new text drops the embedding.
2826    fn write_catalog(&self, rows: &[CatalogRow<'_>], replace_ext: bool) -> Result<Vec<i64>> {
2827        if rows.is_empty() {
2828            return Ok(Vec::new());
2829        }
2830        let replace = if replace_ext {
2831            ", facets = EXCLUDED.facets, extends = EXCLUDED.extends, source_name = EXCLUDED.source_name"
2832        } else {
2833            ""
2834        };
2835        let upsert = format!(
2836            "INSERT INTO catalog_entries (kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name, updated_at)
2837             VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, now())
2838             ON CONFLICT (kind, name) DO UPDATE SET hash = EXCLUDED.hash, label = EXCLUDED.label,
2839                 description = EXCLUDED.description, args = EXCLUDED.args, examples = EXCLUDED.examples,
2840                 source = EXCLUDED.source, signed_by = EXCLUDED.signed_by, updated_at = now(){replace}
2841             WHERE catalog_entries.source = 'operator' OR EXCLUDED.source = 'publisher'
2842             RETURNING id"
2843        );
2844        self.run("upsert_catalog", |c| {
2845            let mut t = c.client.transaction().db()?;
2846            let mut ids = Vec::with_capacity(rows.len());
2847            for row in rows {
2848                let e = row.entry;
2849                let kind = e.kind.as_str();
2850                let args = args_json(&e.args);
2851                let examples = canonical_examples(&e.examples)?;
2852                let before = t
2853                    .query_opt(
2854                        "SELECT label, description FROM catalog_entries WHERE kind = $1 AND name = $2",
2855                        &[&kind, &e.name],
2856                    )
2857                    .db()?
2858                    .map(|r| -> Result<(String, String)> { Ok((r.try_get(0).db()?, r.try_get(1).db()?)) })
2859                    .transpose()?;
2860                let updated = t
2861                    .query_opt(
2862                        &upsert,
2863                        &[
2864                            &kind,
2865                            &e.name,
2866                            &e.hash,
2867                            &e.label,
2868                            &e.description,
2869                            &args,
2870                            &examples,
2871                            &e.source.as_str(),
2872                            &e.signed_by,
2873                            &row.facets,
2874                            &row.extends,
2875                            &row.source_name,
2876                        ],
2877                    )
2878                    .db()?;
2879                let id: i64 = match updated {
2880                    Some(r) => {
2881                        let id: i64 = r.try_get(0).db()?;
2882                        // A new text drops the embedding (the old one is of other words).
2883                        if let Some((label, description)) = before {
2884                            if self.vectors && entry_text(&label, &description) != entry_text(&e.label, &e.description)
2885                            {
2886                                t.execute("DELETE FROM embeddings WHERE ref_kind = 'entry' AND ref_id = $1", &[&id])
2887                                    .db()?;
2888                            }
2889                        }
2890                        id
2891                    }
2892                    // An operator's entry over a publisher's: kept as it is.
2893                    None => t
2894                        .query_one("SELECT id FROM catalog_entries WHERE kind = $1 AND name = $2", &[&kind, &e.name])
2895                        .db()?
2896                        .try_get(0)
2897                        .db()?,
2898                };
2899                ids.push(id);
2900            }
2901            t.commit().db()?;
2902            Ok(ids)
2903        })
2904    }
2905}
2906
2907impl Pattern {
2908    /// The highest insertion seq among the versions of the slice's cells (0 when none), one
2909    /// statement: the candidates' (cell_id, seq) probes (G3).
2910    fn seq(&self, c: &mut Conn) -> Result<i64> {
2911        let (drive, _) = self.drive(c, false)?;
2912        let rows = self.query(c, "", [Q::SliceSeqAll, Q::SliceSeqText, Q::SliceSeqNum], drive)?;
2913        match rows.first() {
2914            Some(r) => r.try_get(0).db(),
2915            None => Ok(0),
2916        }
2917    }
2918
2919    /// The members as of `asof`, in key order.
2920    fn members(&self, c: &mut Conn, asof: &str) -> Result<Vec<SliceMember>> {
2921        let qs = [Q::SliceMembersAll, Q::SliceMembersText, Q::SliceMembersNum];
2922        self.rows(c, asof, qs, 5, member_row, |m| &m.version.cell_id)
2923    }
2924
2925    /// The members' values as of `asof`, in key order.
2926    fn values(&self, c: &mut Conn, asof: &str) -> Result<Vec<SliceValue>> {
2927        let qs = [Q::SliceValuesAll, Q::SliceValuesText, Q::SliceValuesNum];
2928        self.rows(c, asof, qs, 11, value_row, |m| &m.version.cell_id)
2929    }
2930
2931    /// The members' values as of `asof`, in key order, at most `limit`: the statement of
2932    /// `values` with the key order and the LIMIT in SQL. The key order of `cmp_keys` is, per
2933    /// key argument by name, the type's name, then the number (exact) or the text.
2934    fn values_limited(&self, c: &mut Conn, asof: &str, limit: i64) -> Result<Vec<SliceValue>> {
2935        let (drive, _) = self.drive(c, false)?;
2936        let [names, kinds, types, los, his] = self.columns();
2937        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
2938        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
2939        let (base, d_name, d_ty, d_lo, d_hi) = match drive {
2940            None => (Q::SliceValuesAll, "", "", "", ""),
2941            Some(a) => {
2942                let q = if a.ty == "number" { Q::SliceValuesNum } else { Q::SliceValuesText };
2943                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
2944            }
2945        };
2946        // $16.. name each key argument; its order is the type, then the number, then the text.
2947        let mut order = Vec::with_capacity(keys.len() * 3 + 1);
2948        for i in 0..keys.len() {
2949            let p = 16 + i;
2950            let of =
2951                |col: &str| format!("(SELECT a.{col} FROM cell_args a WHERE a.cell_id = c.cell_id AND a.name = ${p})");
2952            order.push(format!("{} COLLATE \"C\"", of("type")));
2953            order.push(of("num"));
2954            order.push(format!("{} COLLATE \"C\"", of("value")));
2955        }
2956        order.push("c.cell_id".to_string());
2957        let sql = format!("{} ORDER BY {} LIMIT ${}", base.sql(), order.join(", "), 16 + keys.len());
2958        // The parameters the base statement does not use (the drive's, when there is none) are
2959        // typed as its statement types them: the text of the statement alone would not say.
2960        let mut param_types = base.types().to_vec();
2961        param_types.extend(std::iter::repeat_n(postgres::types::Type::TEXT, keys.len()));
2962        param_types.push(postgres::types::Type::INT8);
2963        let st = c.client.prepare_typed(sql.as_str(), &param_types).db()?;
2964        let mut params: Vec<&(dyn postgres::types::ToSql + Sync)> = vec![
2965            &self.fn_hash,
2966            &self.ns,
2967            &self.fn_name,
2968            &nargs,
2969            &asof,
2970            &names,
2971            &kinds,
2972            &types,
2973            &los,
2974            &his,
2975            &keys,
2976            &d_name,
2977            &d_ty,
2978            &d_lo,
2979            &d_hi,
2980        ];
2981        for k in &keys {
2982            params.push(k);
2983        }
2984        params.push(&limit);
2985        let rows = c.client.query(&st, &params).db()?;
2986        rows.iter()
2987            .map(|r| {
2988                let cell_id: String = r.try_get(11).db()?;
2989                value_row(r, &cell_id)
2990            })
2991            .collect()
2992    }
2993
2994    /// A page of the members' values as of `asof` in sort-key order, after `after` (exclusive),
2995    /// at most `limit` (CONTRACT-0.5.1 S2). The statement reads the sort-key range of the
2996    /// slice's leading arguments (`slices::key_bounds`) when there is one: O(limit) rows. Else
2997    /// its candidates are driven by the most selective bound argument, as `values` drives them,
2998    /// and ordered by key (O(members)); else the index is walked from its start. Membership is
2999    /// checked in SQL before the LIMIT, so withdrawn and absent members do not count.
3000    fn values_by_key(&self, c: &mut Conn, asof: &str, after: Option<&[u8]>, limit: i64) -> Result<Vec<SliceValue>> {
3001        let bounds = crate::slices::key_bounds(&self.args);
3002        let drive = if bounds.is_some() { None } else { self.drive(c, false)?.0 };
3003        // A key range, or the whole index from its start: read in key order (O(limit) rows).
3004        let walk = bounds.is_some() || drive.is_none();
3005        let [names, kinds, types, los, his] = self.columns();
3006        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
3007        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
3008        let (base, d_name, d_ty, d_lo, d_hi) = match drive {
3009            None => (Q::SliceValuesAll, "", "", "", ""),
3010            Some(a) => {
3011                let q = if a.ty == "number" { Q::SliceValuesNum } else { Q::SliceValuesText };
3012                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
3013            }
3014        };
3015        // The parameters after the base statement's $1-$15, in order: the key range, the cursor,
3016        // then the LIMIT.
3017        let mut extra: Vec<Vec<u8>> = Vec::new();
3018        let mut sql = base.sql().to_string();
3019        if let Some((lo, hi)) = &bounds {
3020            extra.push(lo.clone());
3021            sql += &format!(" AND c.sort_key >= ${}", 15 + extra.len());
3022            if let Some(hi) = hi {
3023                extra.push(hi.clone());
3024                sql += &format!(" AND c.sort_key < ${}", 15 + extra.len());
3025            }
3026        }
3027        if let Some(a) = after {
3028            extra.push(a.to_vec());
3029            sql += &format!(" AND c.sort_key > ${}", 15 + extra.len());
3030        }
3031        sql += &format!(" ORDER BY c.sort_key LIMIT ${}", 16 + extra.len());
3032        let mut param_types = base.types().to_vec();
3033        param_types.extend(std::iter::repeat_n(postgres::types::Type::BYTEA, extra.len()));
3034        param_types.push(postgres::types::Type::INT8);
3035        let mut params: Vec<&(dyn postgres::types::ToSql + Sync)> = vec![
3036            &self.fn_hash,
3037            &self.ns,
3038            &self.fn_name,
3039            &nargs,
3040            &asof,
3041            &names,
3042            &kinds,
3043            &types,
3044            &los,
3045            &his,
3046            &keys,
3047            &d_name,
3048            &d_ty,
3049            &d_lo,
3050            &d_hi,
3051        ];
3052        for bytes in &extra {
3053            params.push(bytes);
3054        }
3055        params.push(&limit);
3056        // A key range or an index walk is read in key order: PostgreSQL cannot estimate a bytea
3057        // range or the membership checks, takes them for a few rows, and would bitmap and sort
3058        // every member, so such a page is read with bitmap scans off (for this read only, in its
3059        // transaction). Seen on a fresh catalogue of 6,144 subjects: the first page sorted them all.
3060        let rows = if walk {
3061            let mut t = c.client.transaction().db()?;
3062            t.batch_execute("SET LOCAL enable_bitmapscan = off").db()?;
3063            let st = t.prepare_typed(sql.as_str(), &param_types).db()?;
3064            let rows = t.query(&st, &params).db()?;
3065            t.commit().db()?;
3066            rows
3067        } else {
3068            let st = c.client.prepare_typed(sql.as_str(), &param_types).db()?;
3069            c.client.query(&st, &params).db()?
3070        };
3071        rows.iter()
3072            .map(|r| {
3073                let cell_id: String = r.try_get(11).db()?;
3074                value_row(r, &cell_id)
3075            })
3076            .collect()
3077    }
3078
3079    /// The members' values as of `asof` in cell id order, after `after` (exclusive), at most
3080    /// `limit`: the statement of `values` with the cell id order and the LIMIT in SQL (0.5.3).
3081    fn values_page(&self, c: &mut Conn, asof: &str, after: Option<&str>, limit: i64) -> Result<Vec<SliceValue>> {
3082        let (drive, _) = self.drive(c, false)?;
3083        let [names, kinds, types, los, his] = self.columns();
3084        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
3085        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
3086        let (base, d_name, d_ty, d_lo, d_hi) = match drive {
3087            None => (Q::SliceValuesAll, "", "", "", ""),
3088            Some(a) => {
3089                let q = if a.ty == "number" { Q::SliceValuesNum } else { Q::SliceValuesText };
3090                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
3091            }
3092        };
3093        let sql = format!("{} AND ($16::text IS NULL OR c.cell_id > $16) ORDER BY c.cell_id LIMIT $17", base.sql());
3094        let mut param_types = base.types().to_vec();
3095        param_types.push(postgres::types::Type::TEXT);
3096        param_types.push(postgres::types::Type::INT8);
3097        let st = c.client.prepare_typed(sql.as_str(), &param_types).db()?;
3098        let params: Vec<&(dyn postgres::types::ToSql + Sync)> = vec![
3099            &self.fn_hash,
3100            &self.ns,
3101            &self.fn_name,
3102            &nargs,
3103            &asof,
3104            &names,
3105            &kinds,
3106            &types,
3107            &los,
3108            &his,
3109            &keys,
3110            &d_name,
3111            &d_ty,
3112            &d_lo,
3113            &d_hi,
3114            &after,
3115            &limit,
3116        ];
3117        let rows = c.client.query(&st, &params).db()?;
3118        rows.iter()
3119            .map(|r| {
3120                let cell_id: String = r.try_get(11).db()?;
3121                value_row(r, &cell_id)
3122            })
3123            .collect()
3124    }
3125
3126    /// The cells with a computed version answering as of `asof`, in cell id order, at most
3127    /// `limit` (`computed_cells`); the candidates narrowed as the member queries narrow them.
3128    fn computed_cells(&self, c: &mut Conn, asof: &str, limit: i64) -> Result<Vec<Cell>> {
3129        let (drive, _) = self.drive(c, false)?;
3130        let [names, kinds, types, los, his] = self.columns();
3131        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
3132        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
3133        let (q, d_name, d_ty, d_lo, d_hi) = match drive {
3134            None => (Q::ComputedCellsAll, "", "", "", ""),
3135            Some(a) => {
3136                let q = if a.ty == "number" { Q::ComputedCellsNum } else { Q::ComputedCellsText };
3137                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
3138            }
3139        };
3140        let st = c.stmt(q)?;
3141        let rows = c
3142            .client
3143            .query(
3144                &st,
3145                &[
3146                    &self.fn_hash,
3147                    &self.ns,
3148                    &self.fn_name,
3149                    &nargs,
3150                    &asof,
3151                    &names,
3152                    &kinds,
3153                    &types,
3154                    &los,
3155                    &his,
3156                    &keys,
3157                    &d_name,
3158                    &d_ty,
3159                    &d_lo,
3160                    &d_hi,
3161                    &limit,
3162                ],
3163            )
3164            .db()?;
3165        rows.iter().map(cell_row).collect()
3166    }
3167
3168    /// The members' receipt hashes as of `asof`, at most `limit`, in no particular order (one statement; see
3169    /// MemberHashesAll). The statement's parameters are those of computed_cells.
3170    fn member_hashes(&self, c: &mut Conn, asof: &str, limit: i64) -> Result<Vec<String>> {
3171        let (drive, _) = self.drive(c, false)?;
3172        let [names, kinds, types, los, his] = self.columns();
3173        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
3174        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
3175        let (q, d_name, d_ty, d_lo, d_hi) = match drive {
3176            None => (Q::MemberHashesAll, "", "", "", ""),
3177            Some(a) => {
3178                let q = if a.ty == "number" { Q::MemberHashesNum } else { Q::MemberHashesText };
3179                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
3180            }
3181        };
3182        let st = c.stmt(q)?;
3183        let rows = c
3184            .client
3185            .query(
3186                &st,
3187                &[
3188                    &self.fn_hash,
3189                    &self.ns,
3190                    &self.fn_name,
3191                    &nargs,
3192                    &asof,
3193                    &names,
3194                    &kinds,
3195                    &types,
3196                    &los,
3197                    &his,
3198                    &keys,
3199                    &d_name,
3200                    &d_ty,
3201                    &d_lo,
3202                    &d_hi,
3203                    &limit,
3204                ],
3205            )
3206            .db()?;
3207        rows.iter().map(|r| r.try_get::<_, String>(0).db()).collect()
3208    }
3209
3210    /// The constraint columns of the member and change queries ($6-$10).
3211    fn columns(&self) -> [Vec<String>; 5] {
3212        let col = |f: fn(&Constraint) -> &str| -> Vec<String> { self.args.iter().map(|a| f(a).to_string()).collect() };
3213        [
3214            col(|a| a.name.as_str()),
3215            col(|a| a.kind.as_str()),
3216            col(|a| a.ty.as_str()),
3217            col(|a| a.lo.as_str()),
3218            col(|a| a.hi.as_str()),
3219        ]
3220    }
3221
3222    /// Whether a matching cell has a stored version answering from after `asof`: from
3223    /// whichever side is smaller (both probed, up to 10,001), the function's receipts with an
3224    /// asof after `asof` (then each one's cell checked against the slice), or the slice's
3225    /// candidate cells (then each one's receipts by cell and asof).
3226    fn changed_after(&self, c: &mut Conn, asof: &str) -> Result<bool> {
3227        let (drive, candidates) = self.drive(c, true)?;
3228        let st = c.stmt(Q::ProbeRecent)?;
3229        let recent: i64 = c.client.query_one(&st, &[&self.fn_hash, &asof]).db()?.try_get(0).db()?;
3230        let qs = if recent <= candidates.unwrap_or(i64::MAX) {
3231            [Q::ChangedRecent; 3]
3232        } else {
3233            [Q::ChangedCandAll, Q::ChangedCandText, Q::ChangedCandNum]
3234        };
3235        let rows = self.query(c, asof, qs, drive)?;
3236        match rows.first() {
3237            Some(r) => r.try_get(0).db(),
3238            None => Ok(false),
3239        }
3240    }
3241
3242    /// The latest withdrawal among the members as of `asof`: the (tx, asof) of the greatest,
3243    /// one indexed query (0.6.0; SPEC 8.2).
3244    fn withdrawn_latest(&self, c: &mut Conn, asof: &str) -> Result<Option<(String, String)>> {
3245        let (drive, _) = self.drive(c, false)?;
3246        let qs = [Q::SliceWithdrawnAll, Q::SliceWithdrawnText, Q::SliceWithdrawnNum];
3247        let rows = self.query(c, asof, qs, drive)?;
3248        match rows.first() {
3249            Some(r) => Ok(Some((r.try_get(0).db()?, r.try_get(1).db()?))),
3250            None => Ok(None),
3251        }
3252    }
3253
3254    /// The bound or ranged argument holding the fewest cells (probed, up to 10,001, when
3255    /// there are several, or when `count` asks), else none (every cell of the function); and
3256    /// the number of candidates when probed.
3257    fn drive(&self, c: &mut Conn, count: bool) -> Result<(Option<&Constraint>, Option<i64>)> {
3258        let mut probe = |a: Option<&Constraint>| -> Result<i64> {
3259            match a {
3260                None => {
3261                    let st = c.stmt(Q::ProbeCells)?;
3262                    c.client.query_one(&st, &[&self.fn_hash]).db()?.try_get(0).db()
3263                }
3264                Some(a) => {
3265                    let st = c.stmt(if a.ty == "number" { Q::SliceProbeNum } else { Q::SliceProbeText })?;
3266                    c.client.query_one(&st, &[&self.fn_hash, &a.name, &a.ty, &a.lo, &a.hi]).db()?.try_get(0).db()
3267                }
3268            }
3269        };
3270        let constrained: Vec<&Constraint> = self.args.iter().filter(|a| a.kind != Kind::Open).collect();
3271        Ok(match constrained.as_slice() {
3272            [] => (None, if count { Some(probe(None)?) } else { None }),
3273            [one] => (Some(*one), if count { Some(probe(Some(one))?) } else { None }),
3274            several => {
3275                let mut best: Option<(i64, &Constraint)> = None;
3276                for a in several {
3277                    let n = probe(Some(a))?;
3278                    if best.is_none_or(|(m, _)| n < m) {
3279                        best = Some((n, a));
3280                    }
3281                }
3282                (best.map(|(_, a)| a), best.map(|(n, _)| n))
3283            }
3284        })
3285    }
3286
3287    /// Runs one of a family of slice queries `qs` (all cells, a text range, a number range)
3288    /// with the slice's parameters and the candidates narrowed by `drive`.
3289    fn query(&self, c: &mut Conn, asof: &str, qs: [Q; 3], drive: Option<&Constraint>) -> Result<Vec<postgres::Row>> {
3290        let [names, kinds, types, los, his] = self.columns();
3291        let keys: Vec<String> = self.args.iter().filter(|a| a.kind != Kind::Value).map(|a| a.name.clone()).collect();
3292        let nargs = i32::try_from(self.args.len()).unwrap_or(i32::MAX);
3293        let (q, d_name, d_ty, d_lo, d_hi) = match drive {
3294            None => (qs[0], "", "", "", ""),
3295            Some(a) => {
3296                let q = if a.ty == "number" { qs[2] } else { qs[1] };
3297                (q, a.name.as_str(), a.ty.as_str(), a.lo.as_str(), a.hi.as_str())
3298            }
3299        };
3300        let st = c.stmt(q)?;
3301        c.client
3302            .query(
3303                &st,
3304                &[
3305                    &self.fn_hash,
3306                    &self.ns,
3307                    &self.fn_name,
3308                    &nargs,
3309                    &asof,
3310                    &names,
3311                    &kinds,
3312                    &types,
3313                    &los,
3314                    &his,
3315                    &keys,
3316                    &d_name,
3317                    &d_ty,
3318                    &d_lo,
3319                    &d_hi,
3320                ],
3321            )
3322            .db()
3323    }
3324
3325    /// The rows of one of the member queries `qs` (all cells, a text range, a number range),
3326    /// each made into a `T` (the cell id in column `at`, the key after it), in key order.
3327    fn rows<T>(
3328        &self,
3329        c: &mut Conn,
3330        asof: &str,
3331        qs: [Q; 3],
3332        at: usize,
3333        make: impl Fn(&postgres::Row, &str) -> Result<T>,
3334        cell_of: impl Fn(&T) -> &String,
3335    ) -> Result<Vec<T>> {
3336        let (drive, _) = self.drive(c, false)?;
3337        let rows = self.query(c, asof, qs, drive)?;
3338        let mut out: Vec<(Vec<String>, T)> = Vec::with_capacity(rows.len());
3339        for r in &rows {
3340            let cell_id: String = r.try_get(at).db()?;
3341            let key: Vec<String> = r.try_get(at + 1).db()?;
3342            out.push((key, make(r, &cell_id)?));
3343        }
3344        out.sort_by(|(a, ma), (b, mb)| cmp_keys(a, b).then_with(|| cell_of(ma).cmp(cell_of(mb))));
3345        Ok(out.into_iter().map(|(_, m)| m).collect())
3346    }
3347}
3348
3349/// Whether a word can be matched by the SQL prefilter exactly: JSON text escapes `"` and `\`
3350/// and control characters, and a word with them is matched in Rust only.
3351fn pg_safe(word: &str) -> bool {
3352    !word.chars().any(|c| c == '"' || c == '\\' || c.is_control())
3353}
3354
3355/// The `AND (...)` prefilter of a text search over `fields` (SQL expressions of text): one
3356/// clause per word the SQL can match, each word a LIKE pattern over lower-cased fields, and
3357/// the parameters they take (numbered from `first`).
3358fn like_where(words: &Words, fields: &[&str], first: usize) -> (String, Vec<String>) {
3359    let mut sql = String::new();
3360    let mut params = Vec::new();
3361    for i in 0..words.len() {
3362        if let Some(p) = words.pattern(i, pg_safe) {
3363            params.push(p);
3364            let n = first + params.len() - 1;
3365            let ors: Vec<String> = fields.iter().map(|f| format!("lower({f}) LIKE ${n} ESCAPE '!'")).collect();
3366            sql.push_str(&format!(" AND ({})", ors.join(" OR ")));
3367        }
3368    }
3369    (sql, params)
3370}
3371
3372/// A function test row of `function_tests`, in the column order of `FunctionTestsOf`.
3373/// Adds to a function's counter row (0.5.3): `n` tests and the deltas of their results, and the
3374/// latest run of them. The row is made first, with the hash's branch counts (or `init`).
3375#[allow(clippy::too_many_arguments)]
3376fn bump_counter(
3377    t: &mut postgres::Transaction<'_>,
3378    ensure: &postgres::Statement,
3379    add: &postgres::Statement,
3380    fn_hash: &str,
3381    fn_name: &str,
3382    n: i64,
3383    results: [i64; 4],
3384    last_run_at: Option<&str>,
3385    init: (i32, i32),
3386) -> Result<()> {
3387    let (total, covered) = init;
3388    t.execute(ensure, &[&fn_hash, &fn_name, &total, &covered]).db()?;
3389    let [pass, fail, error, not_run] = results;
3390    let last_run_at = last_run_at.map(str::to_string);
3391    t.execute(add, &[&fn_hash, &fn_name, &n, &pass, &fail, &error, &not_run, &last_run_at]).db()?;
3392    Ok(())
3393}
3394
3395fn function_test_row(r: &postgres::Row) -> Result<FunctionTest> {
3396    // The branch counts are `integer` with a check of at least zero: an `as` is exact.
3397    let total: i32 = r.try_get(7).db()?;
3398    let covered: i32 = r.try_get(8).db()?;
3399    Ok(FunctionTest {
3400        fn_hash: r.try_get(0).db()?,
3401        case: r.try_get(1).db()?,
3402        test_json: r.try_get(2).db()?,
3403        signed_by: r.try_get(3).db()?,
3404        last_run_at: r.try_get(4).db()?,
3405        last_result: r.try_get(5).db()?,
3406        last_detail: r.try_get(6).db()?,
3407        branches_total: total as u32,
3408        branches_covered: covered as u32,
3409    })
3410}
3411
3412/// The columns of a catalogue entry with its facets and `extends`, by kind and name.
3413const CATALOG_EXT_SELECT_BY_KIND_NAME: &str =
3414    "SELECT kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name
3415       FROM catalog_entries WHERE kind = $1 AND name = $2";
3416
3417/// A catalogue entry with its facets and `extends` from a row of [`CATALOG_EXT_SELECT_BY_KIND_NAME`]
3418/// (or of any query with those eleven columns in that order).
3419fn ext_from_row(r: &postgres::Row) -> Result<CatalogEntryExt> {
3420    let entry = entry_from_columns(
3421        &r.try_get::<_, String>(0).db()?,
3422        r.try_get(1).db()?,
3423        r.try_get(2).db()?,
3424        r.try_get(3).db()?,
3425        r.try_get(4).db()?,
3426        &r.try_get::<_, String>(5).db()?,
3427        &r.try_get::<_, String>(6).db()?,
3428        &r.try_get::<_, String>(7).db()?,
3429        r.try_get(8).db()?,
3430    )?;
3431    entry_ext(entry, &r.try_get::<_, String>(9).db()?, r.try_get(10).db()?, r.try_get(11).db()?)
3432}
3433
3434// ---- Listings (0.7.0) --------------------------------------------------------------------------
3435
3436/// The columns of a listing, in the order [`listing_from_pg`] reads them.
3437const LISTING_COLUMNS: &str =
3438    "name, host, fn_hash, subjects, descriptor, key_id, label, description, fetched_at, listed_at";
3439
3440/// The catalogue entry of a listed name: kind function, source listed, signed by the host; its
3441/// arguments and examples are empty and it extends nothing.
3442const CATALOG_LISTED_UPSERT: &str = "INSERT INTO catalog_entries
3443    (kind, name, hash, label, description, args, examples, source, signed_by, facets, extends, source_name, updated_at)
3444    VALUES ('function', $1, $2, $3, $4, '{}', '[]', 'listed', $5, $6, NULL, NULL, now())
3445    ON CONFLICT (kind, name) DO UPDATE SET hash = EXCLUDED.hash, label = EXCLUDED.label,
3446        description = EXCLUDED.description, args = EXCLUDED.args, examples = EXCLUDED.examples,
3447        source = EXCLUDED.source, signed_by = EXCLUDED.signed_by, facets = EXCLUDED.facets,
3448        extends = NULL, source_name = NULL, updated_at = now()
3449    WHERE catalog_entries.source = 'listed'";
3450
3451fn listing_from_pg(r: &postgres::Row) -> Result<Listing> {
3452    Ok(Listing {
3453        name: r.try_get(0).db()?,
3454        host: r.try_get(1).db()?,
3455        fn_hash: r.try_get(2).db()?,
3456        subjects: parse_subjects(&r.try_get::<_, String>(3).db()?)?,
3457        descriptor: r.try_get(4).db()?,
3458        key_id: r.try_get(5).db()?,
3459        label: r.try_get(6).db()?,
3460        description: r.try_get(7).db()?,
3461        fetched_at: r.try_get(8).db()?,
3462        listed_at: r.try_get(9).db()?,
3463    })
3464}
3465
3466fn listed_host_pg(r: &postgres::Row) -> Result<ListedHost> {
3467    Ok(ListedHost { host: r.try_get(0).db()?, last_seen: r.try_get(1).db()?, unreachable_since: r.try_get(2).db()? })
3468}