Skip to main content

polydat_core/library/
vectors.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Vector dataset access nodes via the `vectordata` crate.
5//!
6//! Each node takes a dataset source string (URL, local path, or
7//! catalog name) as a const parameter and loads the dataset handle at
8//! construction time.
9//!
10//! Source specifier formats:
11//! - `"dataset"` — catalog lookup, uses default profile
12//! - `"dataset:profile"` — catalog lookup with explicit profile
13//! - `"https://..."` — direct URL
14//! - `"/path/to/dir"` — local filesystem path
15//!
16//! ## Prebuffering
17//!
18//! Use `dataset_prebuffer("source")` to eagerly download all facets
19//! for a dataset before workload execution. After prebuffering, data
20//! access uses local mmap readers (zero HTTP overhead).
21//!
22//! ## Cache-aware loading
23//!
24//! For catalog-resolved datasets, the loader checks the local cache
25//! at `~/.cache/vectordata/<dataset>/` before issuing HTTP requests.
26//! Prebuffering populates this cache; subsequent loads are local.
27//!
28//! Feature-gated behind `vectordata`.
29//!
30//! ## Upstream API reference
31//!
32//! See the vectordata consumer guide for the full dataset access,
33//! catalog, caching, and fetch model — the crate's `AGENTS.md`,
34//! rendered as `vectordata::_agents`:
35//! <https://docs.rs/vectordata/latest/vectordata/_agents/index.html>
36
37use std::sync::{Arc, LazyLock};
38
39use crate::library::support::cache::OnceCache;
40
41/// The small predicated dataset vectordata embeds for tests: 190 base
42/// vectors and 10 queries with record metadata, a layout that types
43/// every field, a mixed predicate set, the rows each predicate admits
44/// and all three ground truths. [`predicated`](fixtures::predicated)
45/// writes it to a directory, which a source string then names by path.
46/// It is regenerated from the dataset pipeline, so a test asserts
47/// properties of it and not particular rows.
48#[cfg(feature = "vectordata-fixtures")]
49pub mod fixtures {
50    pub use vectordata::fixtures::{PREDICATED_DEPTH, PREDICATED_PROFILES, predicated};
51}
52
53use vectordata::binding::{BindType, Binder, Layout, Nullability};
54use vectordata::catalog::{Catalog, CatalogSources};
55use vectordata::dataset::facet::FacetShape;
56use vectordata::fetch::{FetchRequest, LogMeter};
57use vectordata::ground_truth::{AdmittedRows, GroundTruth, OrdinalSet, TruthKind};
58use vectordata::predicate_forms::FormCensus;
59
60// By path, not by name: the node macro names each node's type after
61// its function, and `predicate_forms` and `record_forms` are nodes.
62use crate::dataset_value as dv;
63use vectordata::{TestDataGroup, TestDataView, TestDataViewExt, VectorReader, VvecReader};
64
65/// Global cache for loaded dataset groups keyed by source string.
66/// Ensures each dataset is loaded exactly once regardless of how many
67/// node functions reference it. The race-free init pattern lives in
68/// [`crate::library::support::cache::OnceCache`].
69static DATASET_CACHE: LazyLock<OnceCache<String, Arc<TestDataGroup>>> =
70    LazyLock::new(OnceCache::new);
71
72/// Type-erased facet cache: (source, profile, facet) → Arc<dyn Any + Send + Sync>.
73/// Ensures each reader (of any element type) is opened exactly once
74/// and shared across all node instances that reference the same data.
75/// The concrete type inside is `Arc<UniformDataset<T>>` or `Arc<Ivvec32Dataset>`
76/// or `Arc<GenericFacetDataset>`. The race-free init pattern lives
77/// in [`OnceCache`].
78type FacetCache = OnceCache<(String, String, String), Arc<dyn std::any::Any + Send + Sync>>;
79static FACET_CACHE: LazyLock<FacetCache> = LazyLock::new(OnceCache::new);
80
81/// Whole-dataset prebuffer cache keyed by source string. Wraps
82/// [`do_dataset_prebuffer_inner`] so N fibers all calling
83/// `dataset_prebuffer("ds:profile")` at init time serialize on
84/// one OnceLock and share the resulting handle. Without this,
85/// each fiber's own kernel-init pass invokes the real prebuffer
86/// body and they all race into the manifest walk + per-facet
87/// download — exactly the thundering herd we hit. The inner
88/// caches (DATASET_CACHE, FACET_CACHE) only protect the
89/// group-resolve and per-facet-reader steps, not the outer
90/// "walk every facet and pull all chunks" work.
91static PREBUFFER_CACHE: LazyLock<OnceCache<String, Arc<DatasetHandle>>> =
92    LazyLock::new(OnceCache::new);
93
94// =================================================================
95// Dataset resolution — catalog-aware, cache-aware
96// =================================================================
97
98/// Parse a source specifier into (dataset, profile_name).
99///
100/// Supports `"dataset:profile"` syntax. If no colon is present,
101/// the profile defaults to `"default"`. The dataset is a catalog name
102/// or a path to a dataset on disk (its directory or its
103/// `dataset.yaml`): a path that exists is a path, whatever punctuation
104/// it holds, which is the rule vectordata's own specs follow. So a
105/// source that exists is the dataset with the default profile, and
106/// otherwise a source whose text before its last colon exists is that
107/// dataset with the profile after it.
108fn parse_source_specifier(source: &str) -> (&str, &str) {
109    // Don't split on colon in URLs
110    if source.starts_with("http://") || source.starts_with("https://") {
111        return (source, "default");
112    }
113    if is_dataset_path(source) {
114        return (source, "default");
115    }
116    if let Some(pos) = source.rfind(':')
117        && is_dataset_path(&source[..pos])
118    {
119        return (&source[..pos], &source[pos + 1..]);
120    }
121    if let Some(pos) = source.find(':') {
122        (&source[..pos], &source[pos + 1..])
123    } else {
124        (source, "default")
125    }
126}
127
128/// Whether `dataset` names a dataset on disk rather than in a catalog:
129/// a path that exists.
130fn is_dataset_path(dataset: &str) -> bool {
131    !dataset.is_empty() && std::path::Path::new(dataset).exists()
132}
133
134/// Run a synchronous body that may internally drive
135/// `reqwest::blocking` (and thus spin up a private tokio
136/// runtime per HTTP request). If we're sitting on an outer
137/// async runtime — we are, in every per-cycle and per-phase
138/// path — the inner runtime panics on drop with "Cannot drop a
139/// runtime in a context where blocking is not allowed".
140/// `block_in_place` parks the outer multi-thread worker for
141/// the duration of the call so the inner runtime sees a
142/// non-async drop context. Falls back to a direct call when no
143/// runtime is current (e.g. unit tests). Single helper used by
144/// all three vectordata-facing entry points
145/// ([`load_dataset_group`], [`load_uniform_facet`],
146/// [`GenericFacetDataset::load`]).
147fn run_blocking_io<R>(body: impl FnOnce() -> R) -> R {
148    // tokio rides the `vectordata` feature: without the crate there is
149    // no HTTP client to park a worker for.
150    #[cfg(feature = "vectordata")]
151    if tokio::runtime::Handle::try_current().is_ok() {
152        return tokio::task::block_in_place(body);
153    }
154    body()
155}
156
157/// Load a dataset group by catalog name or by path.
158///
159/// A name goes through the vectordata catalog API: `catalog.open(name)`
160/// handles catalog discovery, cache resolution, and download
161/// transparently. A path that exists is opened where it is.
162pub(crate) fn load_dataset_group(source: &str) -> Result<Arc<TestDataGroup>, String> {
163    let (dataset_name, _profile) = parse_source_specifier(source);
164    // Both keys (dataset name and full source spec) point at the
165    // same `Arc<TestDataGroup>`; the `OnceCache` slot for one is
166    // primed by the other on first hit.
167    DATASET_CACHE.get_or_init(dataset_name.to_string(), || {
168        run_blocking_io(|| {
169            let opened = if is_dataset_path(dataset_name) {
170                TestDataGroup::load(dataset_name)
171            } else {
172                Catalog::of(&CatalogSources::new().configure_default()).open(dataset_name)
173            };
174            opened
175                .map(Arc::new)
176                .map_err(|e| format!("failed to load dataset '{dataset_name}': {e}"))
177        })
178    })
179}
180
181// =================================================================
182// Dataset handles — loaded once at node construction, shared via Arc
183// =================================================================
184
185/// Generic handle to a loaded uniform vector facet. Thread-safe, random-access.
186/// Supports any element type provided by the vectordata API (f32, f64,
187/// i32, i16, u8, i8, u16, u32, u64, i64, f16).
188pub(crate) struct UniformDataset<T: Send + Sync + 'static> {
189    reader: Arc<dyn VectorReader<T>>,
190    count: usize,
191    dim: usize,
192    /// The facet read as ground truth, when it is a neighbor-indices
193    /// facet: vectordata's reader of a row's live neighbors and of the
194    /// facet's coverage, or the reason it refuses the profile. `None`
195    /// for every other facet.
196    truth: Option<Result<GroundTruth, String>>,
197}
198
199/// Cache-aware loader for uniform vector facets.
200/// Returns a shared `Arc<UniformDataset<T>>`, creating and caching it
201/// on first access. Subsequent loads for the same (source, profile, facet)
202/// return the cached instance.
203fn load_uniform_facet<T: Send + Sync + 'static>(
204    source: &str,
205    profile: &str,
206    facet: &str,
207    open_fn: impl FnOnce(
208        &dyn TestDataView,
209    ) -> std::result::Result<Arc<dyn VectorReader<T>>, vectordata::Error>,
210    truth: Option<TruthKind>,
211) -> Result<Arc<UniformDataset<T>>, String> {
212    let key = (source.to_string(), profile.to_string(), facet.to_string());
213    let any = FACET_CACHE.get_or_init(key, || {
214        let group = load_dataset_group(source)?;
215        let view = group
216            .profile(profile)
217            .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
218        // Audit: log the open *before* `open_fn` runs so the
219        // line appears even if the open errors. Inside
220        // `get_or_init`'s closure, this fires exactly once per
221        // (source, profile, facet) — the prior shape logged
222        // once per concurrent miss (storms of N for N fibers).
223        crate::library::support::audit::record_opened(
224            parse_source_specifier(source).0,
225            profile,
226            facet,
227            "uniform",
228        );
229        let reader = run_blocking_io(|| open_fn(view.as_ref()))
230            .map_err(|e| format!("failed to access {facet} from '{source}': {e}"))?;
231        let count = reader.count();
232        let dim = reader.dim();
233        // A profile vectordata refuses as ground truth still reads as
234        // fixed-width rows, so the refusal is kept for the nodes that
235        // ask for live neighbors or coverage, and reported by them.
236        let truth = truth.map(|kind| {
237            run_blocking_io(|| GroundTruth::open(view.as_ref(), kind)).map_err(|e| e.to_string())
238        });
239        let arc: Arc<UniformDataset<T>> = Arc::new(UniformDataset {
240            reader,
241            count,
242            dim,
243            truth,
244        });
245        Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
246    })?;
247    any.downcast::<UniformDataset<T>>().map_err(|_| {
248        format!(
249            "facet cache type mismatch for '{source}:{profile}/{facet}' — \
250             this should be impossible; please file a bug."
251        )
252    })
253}
254
255// Type aliases for backward compatibility
256type F32Dataset = UniformDataset<f32>;
257type I32Dataset = UniformDataset<i32>;
258
259impl F32Dataset {
260    fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
261        let facet_name = facet.to_string();
262        load_uniform_facet(
263            source,
264            profile,
265            facet,
266            move |view| match facet_name.as_str() {
267                "base" => view.base_vectors_as(),
268                "query" => view.query_vectors_as(),
269                "neighbor_distances" => view.neighbor_distances_as(),
270                "filtered_neighbor_distances" | "prefiltered_neighbor_distances" => {
271                    view.prefiltered_neighbor_distances_as()
272                }
273                "postfiltered_neighbor_distances" => view.postfiltered_neighbor_distances_as(),
274                other => Err(vectordata::Error::MissingFacet(format!(
275                    "unknown f32 facet: '{other}'"
276                ))),
277            },
278            None,
279        )
280    }
281}
282
283impl I32Dataset {
284    fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
285        let facet_name = facet.to_string();
286        let truth = match facet {
287            "neighbor_indices" => Some(TruthKind::Unfiltered),
288            "filtered_neighbor_indices" | "prefiltered_neighbor_indices" => {
289                Some(TruthKind::Prefiltered)
290            }
291            "postfiltered_neighbor_indices" => Some(TruthKind::Postfiltered),
292            _ => None,
293        };
294        let open = move |view: &dyn TestDataView| match facet_name.as_str() {
295            "neighbor_indices" => view.neighbor_indices_as(),
296            "filtered_neighbor_indices" | "prefiltered_neighbor_indices" => {
297                view.prefiltered_neighbor_indices_as()
298            }
299            "postfiltered_neighbor_indices" => view.postfiltered_neighbor_indices_as(),
300            other => Err(vectordata::Error::MissingFacet(format!(
301                "unknown i32 facet: '{other}'"
302            ))),
303        };
304        load_uniform_facet(source, profile, facet, open, truth)
305    }
306}
307
308// =================================================================
309// Dataset handle — typed enum wrapping all per-facet dataset shapes
310// =================================================================
311//
312// Per type_system.md §1.8: `dataset_open(source, facet)` is
313// the resolver node; per-cycle accessors take a handle wire and
314// downcast to the concrete variant they expect. A single Value
315// variant `Value::Handle(Arc<dyn Any>)` carries any of the
316// concrete shapes — the enum below is what's actually inside the
317// Arc, and accessors `match` on the variant.
318//
319// One handle may be opened against multiple facets at the
320// `dataset_open` boundary (the user calls `dataset_open(spec,
321// "base")` vs. `dataset_open(spec, "query")` and gets two
322// distinct handles); the downstream accessor matches on whatever
323// variant came back.
324
325/// Typed wrapper around a resolved dataset facet or group. Held
326/// inside `Value::Handle` as `Arc<DatasetHandle>` and downcast by
327/// accessor nodes via [`Value::as_handle::<DatasetHandle>()`].
328/// Cloning a `Value::Handle` is one `Arc::clone` — one atomic
329/// increment, no allocation — which is the design contract this
330/// enum exists to satisfy.
331#[derive(Clone)]
332pub(crate) enum DatasetHandle {
333    /// Uniform `f32` vector facet (base, query, neighbor_distances,
334    /// and the filtered, prefiltered and postfiltered neighbor
335    /// distances).
336    F32(Arc<F32Dataset>),
337    /// Uniform `i32` vector facet (neighbor_indices, and the filtered,
338    /// prefiltered and postfiltered neighbor indices).
339    I32(Arc<I32Dataset>),
340    /// Variable-length `i32` facet (metadata_results).
341    Ivvec32(Arc<Ivvec32Dataset>),
342    /// Type-erased generic-typed scalar facet (metadata_content,
343    /// metadata_predicates, ...).
344    Generic(Arc<GenericFacetDataset>),
345    /// The `metadata_content` facet of a dataset that publishes it as
346    /// records: one record of named, typed fields per base vector, with
347    /// the layout that types them.
348    Records(Arc<RecordDataset>),
349    /// The `metadata_predicates` facet of a dataset that publishes it
350    /// as records: one predicate per query, with the forms they take.
351    Predicates(Arc<dv::PredicateForms>),
352    /// Dataset-group handle — used by group-level metadata
353    /// accessors (`dataset_profile_count`, `dataset_facets`,
354    /// `dataset_distance_function`, ...) that operate on the
355    /// `TestDataGroup` before any profile/facet is chosen.
356    Group(Arc<TestDataGroup>),
357    /// Prebuffered-and-resident dataset, returned by
358    /// `dataset_prebuffer(source)`. Carries both the group and
359    /// the source spec: a facet accessor opens its facet from
360    /// `<source>:<profile>` (`query_vector_at(prebuffered, q)`
361    /// reads the `query` facet), and a group accessor reads the
362    /// group. [`DatasetHandle::resolve_facet`] and
363    /// [`DatasetHandle::resolve_group`] are those two readings.
364    ///
365    /// The `group` field also keeps the prebuffered `TestDataGroup`
366    /// alive for the duration of the handle — vectordata's
367    /// internal storage cache is keyed off the group instance,
368    /// so dropping the group prematurely would force per-facet
369    /// readers to re-open against transport.
370    Prebuffered {
371        group: Arc<TestDataGroup>,
372        source: String,
373    },
374}
375
376impl DatasetHandle {
377    fn open(source: &str, facet: &str) -> Result<Self, String> {
378        let (_, profile) = parse_source_specifier(source);
379        match facet {
380            "base"
381            | "query"
382            | "neighbor_distances"
383            | "filtered_neighbor_distances"
384            | "prefiltered_neighbor_distances"
385            | "postfiltered_neighbor_distances" => {
386                F32Dataset::load(source, profile, facet).map(DatasetHandle::F32)
387            }
388            "neighbor_indices"
389            | "filtered_neighbor_indices"
390            | "prefiltered_neighbor_indices"
391            | "postfiltered_neighbor_indices" => {
392                I32Dataset::load(source, profile, facet).map(DatasetHandle::I32)
393            }
394            "metadata_results" => Ivvec32Dataset::load(source, profile).map(DatasetHandle::Ivvec32),
395            // A dataset publishes its metadata either as one scalar per
396            // base vector or as a record of fields per base vector;
397            // the profile says which, and each has its own reader.
398            MetadataContentFacet::FACET
399                if facet_shape(source, profile, facet) == Some(FacetShape::Records) =>
400            {
401                RecordDataset::load(source, profile).map(DatasetHandle::Records)
402            }
403            MetadataPredicatesFacet::FACET
404                if facet_shape(source, profile, facet) == Some(FacetShape::Records) =>
405            {
406                load_predicate_forms(source, profile).map(DatasetHandle::Predicates)
407            }
408            // Anything else routes through GenericFacetDataset (typed
409            // scalar reader), which covers a scalar metadata_content,
410            // metadata_predicates, and any future scalar facet.
411            _ => GenericFacetDataset::load(source, profile, facet).map(DatasetHandle::Generic),
412        }
413    }
414
415    fn open_group(source: &str) -> Result<Self, String> {
416        load_dataset_group(source).map(DatasetHandle::Group)
417    }
418}
419
420/// `dataset_open(source: str, facet: str) -> Handle`
421///
422/// The single resolver node. Provenance follows its two wire
423/// inputs; when both are scope-extern constants (the iter-var
424/// case), this evaluates exactly once at iteration entry and
425/// stays cached for every cycle in that iteration. When source
426/// or facet is cycle-time, it re-evaluates accordingly.
427///
428/// All per-cycle accessors take the resulting handle on a wire
429/// — the catalog/HTTP/mmap path is never on the cycle hot path.
430///
431/// A resolve failure panics with the underlying error rather than
432/// yielding `Value::None`, so a catalog miss cannot degrade into a
433/// garbage value downstream: the engine's `enrich_eval_panic` adds
434/// node provenance, `eval_const_expr` traps the panic into
435/// `Result::Err`, and `evaluate_spec` propagates it as a
436/// clause-level diagnostic.
437#[crate::polydat_node(category = RealData)]
438fn dataset_open(source: &str, facet: &str) -> Arc<DatasetHandle> {
439    match DatasetHandle::open(source, facet) {
440        Ok(h) => Arc::new(h),
441        Err(e) => {
442            let msg = format!("dataset_open: failed to resolve '{source}' facet='{facet}': {e}");
443            crate::library::support::audit::error(&msg);
444            panic!("{msg}");
445        }
446    }
447}
448
449/// `dataset_group_open(source: str) -> Handle`
450///
451/// Group-level resolver. Returns a handle wrapping `Arc<TestDataGroup>`
452/// — used by group-level metadata accessors (`dataset_profile_count`,
453/// `dataset_facets`, ...) that operate on the dataset as a whole
454/// before any profile/facet is selected.
455///
456/// A resolve failure panics, as in `dataset_open` and for the
457/// same reason.
458#[crate::polydat_node(category = RealData)]
459fn dataset_group_open(source: &str) -> Arc<DatasetHandle> {
460    match DatasetHandle::open_group(source) {
461        Ok(h) => Arc::new(h),
462        Err(e) => {
463            let msg = format!("dataset_group_open: failed to resolve '{source}': {e}");
464            crate::library::support::audit::error(&msg);
465            panic!("{msg}");
466        }
467    }
468}
469
470// =================================================================
471// Base vector nodes
472// =================================================================
473
474// All indexed-accessor nodes share the same shape: a handle wire
475// and an `index` wire (u64). A source string in the handle
476// position is promoted to `dataset_open(source, "<facet>")` for
477// the facet the accessor names, and the facet reader is opened
478// once per (source, profile, facet) through `FACET_CACHE`, so
479// the per-cycle work is the facet read alone.
480
481// =================================================================
482// Per-cycle indexed accessors
483// =================================================================
484
485/// Resolve a Prebuffered handle to a specific-facet handle by
486/// opening the named facet via the existing FACET_CACHE path
487/// (which is `OnceCache`-backed — concurrent callers serialize
488/// per (source, profile, facet)). For non-Prebuffered handles
489/// this is a borrow-through; the macro callers use the result as
490/// `&DatasetHandle` regardless of which arm fires.
491///
492/// Lives on `DatasetHandle` so the resolution logic — and the
493/// "what does Prebuffered mean to a per-facet accessor" question
494/// — sits next to the variant declaration.
495impl DatasetHandle {
496    fn resolve_facet<'a>(&'a self, facet: &str) -> std::borrow::Cow<'a, DatasetHandle> {
497        match self {
498            DatasetHandle::Prebuffered { source, .. } => match DatasetHandle::open(source, facet) {
499                Ok(opened) => std::borrow::Cow::Owned(opened),
500                Err(e) => panic!(
501                    "DatasetHandle::resolve_facet: failed to open \
502                         '{facet}' from prebuffered '{source}': {e}"
503                ),
504            },
505            _ => std::borrow::Cow::Borrowed(self),
506        }
507    }
508
509    /// The dataset group a group accessor reads: the group of a
510    /// `dataset_group_open` handle, or the group a prebuffered handle
511    /// carries. A facet handle has no group, and asking one for it
512    /// panics with the handle's kind.
513    fn resolve_group(&self) -> &TestDataGroup {
514        match self {
515            DatasetHandle::Group(g) | DatasetHandle::Prebuffered { group: g, .. } => g.as_ref(),
516            other => panic!(
517                "expected a group or prebuffered handle, got {}",
518                dataset_handle_kind(other)
519            ),
520        }
521    }
522}
523
524/// The facet each accessor opens, as a type.
525///
526/// A node states its facet twice — in the auto-resolver that splices
527/// `dataset_open(_, "<facet>")` when the source is a string, and in
528/// the `resolve_facet` call that follows a prebuffered handle — and
529/// both readings come from here, so the two cannot drift apart.
530macro_rules! facet_kind {
531    ($name:ident, $facet:literal) => {
532        /// The `
533        #[doc = $facet]
534        /// ` facet of a dataset.
535        pub struct $name;
536        impl $name {
537            /// The facet's name, as `dataset_open` takes it.
538            pub const FACET: &'static str = $facet;
539        }
540        impl crate::derive_support::ResolverKind for $name {
541            const RESOLVER: crate::dsl::registry::DefaultResolver =
542                crate::dsl::registry::DefaultResolver::Facet($facet);
543        }
544    };
545}
546
547facet_kind!(BaseFacet, "base");
548facet_kind!(QueryFacet, "query");
549facet_kind!(NeighborIndicesFacet, "neighbor_indices");
550facet_kind!(NeighborDistancesFacet, "neighbor_distances");
551facet_kind!(FilteredNeighborIndicesFacet, "filtered_neighbor_indices");
552facet_kind!(
553    FilteredNeighborDistancesFacet,
554    "filtered_neighbor_distances"
555);
556facet_kind!(
557    PrefilteredNeighborIndicesFacet,
558    "prefiltered_neighbor_indices"
559);
560facet_kind!(
561    PrefilteredNeighborDistancesFacet,
562    "prefiltered_neighbor_distances"
563);
564facet_kind!(
565    PostfilteredNeighborIndicesFacet,
566    "postfiltered_neighbor_indices"
567);
568facet_kind!(
569    PostfilteredNeighborDistancesFacet,
570    "postfiltered_neighbor_distances"
571);
572facet_kind!(MetadataResultsFacet, "metadata_results");
573facet_kind!(MetadataContentFacet, "metadata_content");
574facet_kind!(MetadataPredicatesFacet, "metadata_predicates");
575
576/// A handle wire that carries its facet in its type.
577type Facet<R> = crate::derive_support::Resolved<R, DatasetHandle>;
578
579/// A handle wire on the dataset group rather than one of its facets.
580type Group = crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>;
581
582/// The record count of a facet handle, opening `facet` first when the
583/// handle is prebuffered. `who` names the caller in the diagnostics,
584/// which is what the reader needs to see when a workload asks a
585/// facet for a count it cannot give.
586fn facet_record_count(h: &DatasetHandle, who: &str, facet: &str) -> u64 {
587    match h.resolve_facet(facet).as_ref() {
588        DatasetHandle::F32(d) => d.count as u64,
589        DatasetHandle::I32(d) => d.count as u64,
590        DatasetHandle::Ivvec32(d) => d.count as u64,
591        DatasetHandle::Generic(d) => d.count as u64,
592        DatasetHandle::Records(d) => d.count,
593        DatasetHandle::Predicates(d) => d.census.count(),
594        other => panic!(
595            "{who}: expected a facet handle, got {}",
596            dataset_handle_kind(other)
597        ),
598    }
599}
600
601/// The `f32` record at `index`, as the typed vector it is.
602fn f32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<f32> {
603    match h {
604        DatasetHandle::F32(d) => slice_arc_from_uniform(d, index),
605        other => panic!(
606            "expected F32 dataset handle, got {}",
607            dataset_handle_kind(other)
608        ),
609    }
610}
611
612/// The `i32` record at `index`, as the typed vector it is.
613fn i32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<i32> {
614    match h {
615        DatasetHandle::I32(d) => slice_arc_from_uniform(d, index),
616        other => panic!(
617            "expected I32 dataset handle, got {}",
618            dataset_handle_kind(other)
619        ),
620    }
621}
622
623fn ivvec32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<i32> {
624    match h {
625        // Variable-length records — vectordata's trait doesn't expose
626        // a zero-copy slice path for these (per-record dim is read
627        // from the file), so we always allocate. One Vec<i32> per
628        // cycle; same bound as the upstream trait API.
629        DatasetHandle::Ivvec32(d) => {
630            if d.count == 0 {
631                return crate::ast::SliceArc::from_vec(Vec::<i32>::new());
632            }
633            let query = index % d.count;
634            let v = match &d.reader {
635                Some(reader) => reader.get(query).unwrap_or_default(),
636                // The slab encoding has no list reader: the list is
637                // the admitted rows, read out in order.
638                None => d
639                    .admitted_rows("metadata_results_at")
640                    .get(query)
641                    .unwrap_or_else(|e| panic!("metadata_results_at: {e}"))
642                    .iter()
643                    .map(|ordinal| {
644                        i32::try_from(ordinal).unwrap_or_else(|_| {
645                            panic!(
646                                "metadata_results_at: base position {ordinal} is outside the \
647                                 i32 range; read the rows with `admitted_rows_at`"
648                            )
649                        })
650                    })
651                    .collect(),
652            };
653            crate::ast::SliceArc::from_vec(v)
654        }
655        other => panic!(
656            "expected Ivvec32 dataset handle, got {}",
657            dataset_handle_kind(other)
658        ),
659    }
660}
661
662/// Build a [`SliceArc<T>`] from any uniform-stride dataset at
663/// `index`. One generic helper serves every element type — element type is
664/// erased by the upstream `VectorReader<T>` trait, and `SliceArc`
665/// is element-type-generic, so one body suffices for `f32`,
666/// `i32`, and any other element type the trait supports.
667///
668/// Tries the zero-copy `VectorReader::get_slice` path first —
669/// that returns a borrow into the mmap'd file pages, kept alive
670/// by the `Arc<UniformDataset<T>>` that we move into the
671/// `SliceArc` as owner. No allocation, no element decoding, no
672/// copy.
673///
674/// Falls back to `VectorReader::get(idx) -> Vec<T>` for readers
675/// that don't support zero-copy (HTTP-backed, or merkle-cached
676/// storage that hasn't been promoted to mmap yet); that path
677/// allocates one `Vec<T>` per cycle.
678fn slice_arc_from_uniform<T>(d: &Arc<UniformDataset<T>>, index: usize) -> crate::ast::SliceArc<T>
679where
680    T: Send + Sync + Copy + 'static,
681{
682    if d.count == 0 {
683        return crate::ast::SliceArc::from_vec(Vec::<T>::new());
684    }
685    let idx = index % d.count;
686    if let Some(slice) = d.reader.get_slice(idx) {
687        // SAFETY: the slice points into the mmap pages owned by
688        // `d`'s reader; cloning `d` into the `SliceArc`'s owner
689        // keeps the mmap alive for as long as the slice is held.
690        let ptr_len = (slice.as_ptr(), slice.len());
691        let owner = d.clone();
692        let owner_dyn: Arc<dyn std::any::Any + Send + Sync> = owner;
693        return unsafe {
694            crate::ast::SliceArc::from_borrowed(
695                owner_dyn,
696                std::slice::from_raw_parts(ptr_len.0, ptr_len.1),
697            )
698        };
699    }
700    crate::ast::SliceArc::from_vec(d.reader.get(idx).unwrap_or_default())
701}
702
703fn dataset_handle_kind(h: &DatasetHandle) -> &'static str {
704    match h {
705        DatasetHandle::F32(_) => "F32",
706        DatasetHandle::I32(_) => "I32",
707        DatasetHandle::Ivvec32(_) => "Ivvec32",
708        DatasetHandle::Generic(_) => "Generic",
709        DatasetHandle::Records(_) => "Records",
710        DatasetHandle::Predicates(_) => "Predicates",
711        DatasetHandle::Group(_) => "Group",
712        DatasetHandle::Prebuffered { .. } => "Prebuffered",
713    }
714}
715
716/// Access an `f32` vector by index, returning a typed `VecF32`.
717/// Reads the base facet of a source string or prebuffered handle,
718/// and whatever facet an opened F32 handle names.
719///
720/// Signature: `vector_at(handle, index: u64) -> VecF32`
721#[crate::polydat_node(category = RealData)]
722fn vector_at(handle: Facet<BaseFacet>, index: u64) -> crate::ast::SliceArc<f32> {
723    f32_vec_typed(
724        handle.resolve_facet(BaseFacet::FACET).as_ref(),
725        index as usize,
726    )
727}
728
729/// Access a query vector by index. Reads the query facet of a
730/// source string or prebuffered handle, as `vector_at` reads the
731/// base facet.
732///
733/// Signature: `query_vector_at(handle, index: u64) -> VecF32`
734#[crate::polydat_node(category = RealData)]
735fn query_vector_at(handle: Facet<QueryFacet>, index: u64) -> crate::ast::SliceArc<f32> {
736    f32_vec_typed(
737        handle.resolve_facet(QueryFacet::FACET).as_ref(),
738        index as usize,
739    )
740}
741
742/// Access ground-truth neighbor indices for a query. Expects an
743/// I32 handle.
744///
745/// Signature: `neighbor_indices_at(handle, index: u64) -> VecI32`
746#[crate::polydat_node(category = RealData)]
747fn neighbor_indices_at(
748    handle: Facet<NeighborIndicesFacet>,
749    index: u64,
750) -> crate::ast::SliceArc<i32> {
751    i32_vec_typed(
752        handle.resolve_facet(NeighborIndicesFacet::FACET).as_ref(),
753        index as usize,
754    )
755}
756
757/// Access ground-truth neighbor distances for a query. Expects an
758/// F32 handle.
759///
760/// Signature: `neighbor_distances_at(handle, index: u64) -> VecF32`
761#[crate::polydat_node(category = RealData)]
762fn neighbor_distances_at(
763    handle: Facet<NeighborDistancesFacet>,
764    index: u64,
765) -> crate::ast::SliceArc<f32> {
766    f32_vec_typed(
767        handle.resolve_facet(NeighborDistancesFacet::FACET).as_ref(),
768        index as usize,
769    )
770}
771
772/// Access filtered ground-truth neighbor indices. Expects an I32
773/// handle. `filtered_neighbor_indices` is the legacy name of the
774/// prefiltered facet, so this reads what
775/// `prefiltered_neighbor_indices_at` reads.
776///
777/// Signature: `filtered_neighbor_indices_at(handle, index: u64) -> VecI32`
778#[crate::polydat_node(category = RealData)]
779fn filtered_neighbor_indices_at(
780    handle: Facet<FilteredNeighborIndicesFacet>,
781    index: u64,
782) -> crate::ast::SliceArc<i32> {
783    i32_vec_typed(
784        handle
785            .resolve_facet(FilteredNeighborIndicesFacet::FACET)
786            .as_ref(),
787        index as usize,
788    )
789}
790
791/// Access filtered ground-truth neighbor distances. Expects an F32
792/// handle. `filtered_neighbor_distances` is the legacy name of the
793/// prefiltered facet, so this reads what
794/// `prefiltered_neighbor_distances_at` reads.
795///
796/// Signature: `filtered_neighbor_distances_at(handle, index: u64) -> VecF32`
797#[crate::polydat_node(category = RealData)]
798fn filtered_neighbor_distances_at(
799    handle: Facet<FilteredNeighborDistancesFacet>,
800    index: u64,
801) -> crate::ast::SliceArc<f32> {
802    f32_vec_typed(
803        handle
804            .resolve_facet(FilteredNeighborDistancesFacet::FACET)
805            .as_ref(),
806        index as usize,
807    )
808}
809
810/// Access the prefiltered ground-truth neighbor indices of a query:
811/// its nearest neighbors among the base vectors its predicate admits,
812/// nearest first. A row with fewer admitted vectors than the facet's
813/// depth is padded with `-1`. Expects an I32 handle.
814///
815/// Signature: `prefiltered_neighbor_indices_at(handle, index: u64) -> VecI32`
816#[crate::polydat_node(category = RealData)]
817fn prefiltered_neighbor_indices_at(
818    handle: Facet<PrefilteredNeighborIndicesFacet>,
819    index: u64,
820) -> crate::ast::SliceArc<i32> {
821    i32_vec_typed(
822        handle
823            .resolve_facet(PrefilteredNeighborIndicesFacet::FACET)
824            .as_ref(),
825        index as usize,
826    )
827}
828
829/// Access the distances of a query's prefiltered ground-truth
830/// neighbors, in the order of `prefiltered_neighbor_indices_at`.
831/// Expects an F32 handle.
832///
833/// Signature: `prefiltered_neighbor_distances_at(handle, index: u64) -> VecF32`
834#[crate::polydat_node(category = RealData)]
835fn prefiltered_neighbor_distances_at(
836    handle: Facet<PrefilteredNeighborDistancesFacet>,
837    index: u64,
838) -> crate::ast::SliceArc<f32> {
839    f32_vec_typed(
840        handle
841            .resolve_facet(PrefilteredNeighborDistancesFacet::FACET)
842            .as_ref(),
843        index as usize,
844    )
845}
846
847/// Access the postfiltered ground-truth neighbor indices of a query:
848/// its unfiltered nearest neighbors with those its predicate does not
849/// admit removed, in rank order. A row with fewer survivors than the
850/// facet's depth is padded with `-1`. Expects an I32 handle.
851///
852/// Signature: `postfiltered_neighbor_indices_at(handle, index: u64) -> VecI32`
853#[crate::polydat_node(category = RealData)]
854fn postfiltered_neighbor_indices_at(
855    handle: Facet<PostfilteredNeighborIndicesFacet>,
856    index: u64,
857) -> crate::ast::SliceArc<i32> {
858    i32_vec_typed(
859        handle
860            .resolve_facet(PostfilteredNeighborIndicesFacet::FACET)
861            .as_ref(),
862        index as usize,
863    )
864}
865
866/// Access the distances of a query's postfiltered ground-truth
867/// neighbors, in the order of `postfiltered_neighbor_indices_at`.
868/// Expects an F32 handle.
869///
870/// Signature: `postfiltered_neighbor_distances_at(handle, index: u64) -> VecF32`
871#[crate::polydat_node(category = RealData)]
872fn postfiltered_neighbor_distances_at(
873    handle: Facet<PostfilteredNeighborDistancesFacet>,
874    index: u64,
875) -> crate::ast::SliceArc<f32> {
876    f32_vec_typed(
877        handle
878            .resolve_facet(PostfilteredNeighborDistancesFacet::FACET)
879            .as_ref(),
880        index as usize,
881    )
882}
883
884// =================================================================
885// Ground truth as vectordata reads it: live neighbors and coverage
886// =================================================================
887//
888// What a ground-truth row means is vectordata's definition
889// (`vectordata::ground_truth`): a row's live neighbors are its entries
890// before the first negative one, and the rest is padding. These nodes
891// hand on what vectordata's reader answers and decide nothing
892// themselves. That a dataset's rows meet the definition is verified
893// where the dataset is published, so nothing is checked per read.
894//
895// The coverage answers are properties of the facet and the depth, so
896// each is computed once per scope, replays, and agrees on every engine
897// and every fiber, as `metadata_count_of` does.
898
899/// vectordata's ground-truth reader for the neighbor-indices handle
900/// `h`. `who` names the calling node in the diagnostics. A profile
901/// vectordata refuses as ground truth, such as one whose base window
902/// does not start at zero under a filtered facet, is refused here with
903/// vectordata's reason.
904fn ground_truth<'a>(h: &'a DatasetHandle, who: &str) -> &'a GroundTruth {
905    let DatasetHandle::I32(d) = h else {
906        panic!(
907            "{who}: expected a neighbor-indices handle, got {}",
908            dataset_handle_kind(h)
909        );
910    };
911    match &d.truth {
912        Some(Ok(truth)) => truth,
913        Some(Err(e)) => panic!("{who}: {e}"),
914        None => panic!("{who}: the handle is not of a ground-truth facet"),
915    }
916}
917
918/// The live neighbors of query `index` in `truth`, nearest first. The
919/// query index wraps modulo the facet's rows, as the fixed-width
920/// accessors' does.
921fn live_neighbors(truth: &GroundTruth, index: u64, who: &str) -> crate::ast::SliceArc<i64> {
922    let queries = truth.queries();
923    if queries == 0 {
924        return crate::ast::SliceArc::from_vec(Vec::new());
925    }
926    let neighbors = truth
927        .neighbors(index as usize % queries)
928        .unwrap_or_else(|e| panic!("{who}: {e}"));
929    crate::ast::SliceArc::from_vec(neighbors.into_iter().map(|n| n as i64).collect())
930}
931
932/// The number of live neighbors of query `index` in `truth`.
933fn live_depth(truth: &GroundTruth, index: u64, who: &str) -> u64 {
934    let queries = truth.queries();
935    if queries == 0 {
936        return 0;
937    }
938    truth
939        .depth(index as usize % queries)
940        .unwrap_or_else(|e| panic!("{who}: {e}")) as u64
941}
942
943/// vectordata's coverage of `truth` at depth `k`. A depth vectordata
944/// cannot answer for, zero or deeper than the facet, is its error.
945fn coverage(truth: &GroundTruth, k: u64, who: &str) -> vectordata::ground_truth::Coverage {
946    let depth = usize::try_from(k).unwrap_or(usize::MAX);
947    run_blocking_io(|| truth.coverage(depth, &mut vectordata::NoProgress))
948        .unwrap_or_else(|e| panic!("{who}: {e}"))
949}
950
951/// Generate the live-neighbor and coverage nodes of one ground-truth
952/// facet. Each is a registered node of its own, so its documentation
953/// and its facet are stated where it is declared.
954macro_rules! ground_truth_nodes {
955    (
956        facet: $facet:ident,
957        truth: $truth:literal,
958        live_indices: $live_indices:ident,
959        live_depth: $live_depth:ident,
960        full_rows: $full_rows:ident,
961        empty_rows: $empty_rows:ident,
962        recall_ceiling: $recall_ceiling:ident $(,)?
963    ) => {
964        /// The live neighbors of a query in the
965        #[doc = $truth]
966        /// ground truth: the base positions its row names, nearest
967        /// first, without the padding a row carries when it has fewer
968        /// neighbors than the facet is deep. As long as the row's live
969        /// depth, so shorter than the facet's width for a padded row
970        /// and empty for a query with no neighbor.
971        #[crate::polydat_node(category = RealData)]
972        fn $live_indices(handle: Facet<$facet>, index: u64) -> crate::ast::SliceArc<i64> {
973            let h = handle.resolve_facet($facet::FACET);
974            let who = stringify!($live_indices);
975            live_neighbors(ground_truth(h.as_ref(), who), index, who)
976        }
977
978        /// How many live neighbors a query has in the
979        #[doc = $truth]
980        /// ground truth: the length of its row before the padding.
981        #[crate::polydat_node(category = RealData)]
982        fn $live_depth(handle: Facet<$facet>, index: u64) -> u64 {
983            let h = handle.resolve_facet($facet::FACET);
984            let who = stringify!($live_depth);
985            live_depth(ground_truth(h.as_ref(), who), index, who)
986        }
987
988        /// How many queries have at least `k` live neighbors in the
989        #[doc = $truth]
990        /// ground truth, as vectordata counts its coverage. A depth of
991        /// zero, or deeper than the facet, is refused.
992        #[crate::polydat_node(category = RealData)]
993        fn $full_rows(handle: Facet<$facet>, k: u64) -> u64 {
994            let h = handle.resolve_facet($facet::FACET);
995            let who = stringify!($full_rows);
996            coverage(ground_truth(h.as_ref(), who), k, who).full
997        }
998
999        /// How many queries have no live neighbor in the
1000        #[doc = $truth]
1001        /// ground truth, as vectordata counts its coverage. A depth of
1002        /// zero, or deeper than the facet, is refused.
1003        #[crate::polydat_node(category = RealData)]
1004        fn $empty_rows(handle: Facet<$facet>, k: u64) -> u64 {
1005            let h = handle.resolve_facet($facet::FACET);
1006            let who = stringify!($empty_rows);
1007            coverage(ground_truth(h.as_ref(), who), k, who).empty
1008        }
1009
1010        /// The recall at `k` a perfect search would score against the
1011        #[doc = $truth]
1012        /// ground truth when every query is scored out of `k`:
1013        /// vectordata's coverage ceiling. 1.0 when every query has `k`
1014        /// neighbors, and less by the share of slots no neighbor
1015        /// exists for. A depth of zero, or deeper than the facet, is
1016        /// refused.
1017        #[crate::polydat_node(category = RealData)]
1018        fn $recall_ceiling(handle: Facet<$facet>, k: u64) -> f64 {
1019            let h = handle.resolve_facet($facet::FACET);
1020            let who = stringify!($recall_ceiling);
1021            coverage(ground_truth(h.as_ref(), who), k, who).ceiling()
1022        }
1023    };
1024}
1025
1026ground_truth_nodes! {
1027    facet: NeighborIndicesFacet,
1028    truth: "unfiltered (`neighbor_indices`)",
1029    live_indices: neighbor_live_indices_at,
1030    live_depth: neighbor_live_depth_at,
1031    full_rows: neighbor_full_rows,
1032    empty_rows: neighbor_empty_rows,
1033    recall_ceiling: neighbor_recall_ceiling,
1034}
1035
1036ground_truth_nodes! {
1037    facet: PrefilteredNeighborIndicesFacet,
1038    truth: "prefiltered (`prefiltered_neighbor_indices`)",
1039    live_indices: prefiltered_neighbor_live_indices_at,
1040    live_depth: prefiltered_neighbor_live_depth_at,
1041    full_rows: prefiltered_neighbor_full_rows,
1042    empty_rows: prefiltered_neighbor_empty_rows,
1043    recall_ceiling: prefiltered_neighbor_recall_ceiling,
1044}
1045
1046ground_truth_nodes! {
1047    facet: PostfilteredNeighborIndicesFacet,
1048    truth: "postfiltered (`postfiltered_neighbor_indices`)",
1049    live_indices: postfiltered_neighbor_live_indices_at,
1050    live_depth: postfiltered_neighbor_live_depth_at,
1051    full_rows: postfiltered_neighbor_full_rows,
1052    empty_rows: postfiltered_neighbor_empty_rows,
1053    recall_ceiling: postfiltered_neighbor_recall_ceiling,
1054}
1055
1056// =================================================================
1057// Metadata nodes (constant per dataset)
1058// =================================================================
1059
1060// =================================================================
1061// Per-handle metadata nodes
1062// =================================================================
1063//
1064// Take `(handle: Handle)` and read shape/metadata directly from the
1065// resolved dataset. Provenance bounded by the handle, which itself
1066// is bounded by the resolver's externs — so these collapse to a
1067// single per-iteration eval chain via the standard provenance
1068// caching. No per-cycle work.
1069
1070/// Return the dimensionality (`f32` count per record) of a
1071/// vector facet handle.
1072///
1073/// Signature: `vector_dim(handle) -> (u64)`
1074#[crate::polydat_node(category = RealData)]
1075fn vector_dim(handle: Facet<BaseFacet>) -> u64 {
1076    match handle.resolve_facet(BaseFacet::FACET).as_ref() {
1077        DatasetHandle::F32(d) => d.dim as u64,
1078        DatasetHandle::I32(d) => d.dim as u64,
1079        _ => 0,
1080    }
1081}
1082
1083/// Return the count of records in the facet a handle was opened
1084/// against. This is the canonical "how many vectors / queries /
1085/// neighbor-rows" accessor — `vector_count(base_handle)` for
1086/// base vectors, `vector_count(query_handle)` for query
1087/// vectors, etc. A source string or prebuffered handle counts
1088/// the base facet.
1089///
1090/// Signature: `vector_count(handle) -> (u64)`
1091#[crate::polydat_node(category = RealData)]
1092fn vector_count(handle: Facet<BaseFacet>) -> u64 {
1093    facet_record_count(&handle, "vector_count", BaseFacet::FACET)
1094}
1095
1096/// Return the count of query vectors. Counts the query facet of a
1097/// source string or prebuffered handle, as `vector_count` counts
1098/// the base facet.
1099///
1100/// Signature: `query_count(handle) -> (u64)`
1101#[crate::polydat_node(category = RealData)]
1102fn query_count(handle: Facet<QueryFacet>) -> u64 {
1103    // `query_count(prebuffered)` is a legitimate idiom in the
1104    // pvs_query workload (`cursor q = range(0, query_count(...))`),
1105    // so the prebuffered case resolves the query facet and reads
1106    // its count, through the same OnceCache-backed open the
1107    // per-cycle accessors use.
1108    facet_record_count(&handle, "query_count", QueryFacet::FACET)
1109}
1110
1111/// Return the per-record neighbor count (k) for an I32
1112/// neighbor-indices handle.
1113///
1114/// Signature: `neighbor_count(handle) -> (u64)`
1115#[crate::polydat_node(category = RealData)]
1116fn neighbor_count(handle: Facet<NeighborIndicesFacet>) -> u64 {
1117    match handle.resolve_facet(NeighborIndicesFacet::FACET).as_ref() {
1118        DatasetHandle::I32(d) => d.dim as u64,
1119        _ => 0,
1120    }
1121}
1122
1123/// Return the dataset's distance function (e.g., "COSINE",
1124/// "EUCLIDEAN"). Operates on the dataset group; takes a group or
1125/// prebuffered handle.
1126///
1127/// Signature: `dataset_distance_function(group) -> (str)`
1128#[crate::polydat_node(category = RealData)]
1129fn dataset_distance_function(group: Group) -> String {
1130    let group = group.resolve_group();
1131    let raw = group
1132        .attribute("distance_function")
1133        .and_then(|v| v.as_str())
1134        .unwrap_or("unknown");
1135    match raw.to_uppercase().as_str() {
1136        "L2" | "EUCLIDEAN" => "EUCLIDEAN",
1137        "L1" | "MANHATTAN" => "MANHATTAN",
1138        "COSINE" => "COSINE",
1139        "DOT_PRODUCT" | "DOTPRODUCT" | "DOT" | "INNER_PRODUCT" | "IP" => "DOT_PRODUCT",
1140        _ => raw,
1141    }
1142    .to_string()
1143}
1144
1145// =================================================================
1146// Metadata facet nodes
1147// =================================================================
1148
1149/// Handle to the `metadata_results` facet: the base positions each
1150/// query's predicate admits. A dataset publishes it as variable-length
1151/// `i32` lists or as a slab of records, and both are read here.
1152pub(crate) struct Ivvec32Dataset {
1153    /// The list reader, for the variable-length encoding; `None` for a
1154    /// slab of records, which is read through `admitted`.
1155    reader: Option<Arc<dyn VvecReader<i32>>>,
1156    count: usize,
1157    /// The facet read as the rows each query's predicate admits:
1158    /// vectordata's reader of a row as a set that is not read until it
1159    /// is asked, or the reason it refuses the profile.
1160    admitted: Result<AdmittedRows, String>,
1161}
1162
1163impl Ivvec32Dataset {
1164    /// vectordata's reader of the admitted rows, for the node `who`,
1165    /// or its reason for refusing the profile.
1166    fn admitted_rows(&self, who: &str) -> &AdmittedRows {
1167        self.admitted
1168            .as_ref()
1169            .unwrap_or_else(|e| panic!("{who}: {e}"))
1170    }
1171
1172    fn load(source: &str, profile: &str) -> Result<Arc<Self>, String> {
1173        let key = (
1174            source.to_string(),
1175            profile.to_string(),
1176            "metadata_results".to_string(),
1177        );
1178        let any = FACET_CACHE.get_or_init(key, || {
1179            let group = load_dataset_group(source)?;
1180            let view = group
1181                .profile(profile)
1182                .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
1183            crate::library::support::audit::record_opened(
1184                parse_source_specifier(source).0,
1185                profile,
1186                "metadata_results",
1187                "ivvec32",
1188            );
1189            // A remote variable-length facet published without its
1190            // `IDXFOR__` offset index can only be opened from every
1191            // byte; the fetching open downloads it whole, with progress,
1192            // where a plain open refuses.
1193            let failed =
1194                |e: String| format!("failed to access metadata_results from '{source}': {e}");
1195            let records = view.facet_shape("metadata_results").ok() == Some(FacetShape::Records);
1196            let reader = if records {
1197                None
1198            } else {
1199                Some(
1200                    run_blocking_io(|| {
1201                        view.metadata_results_fetching_as(&mut fetch_meter(&format!(
1202                            "open {source}"
1203                        )))
1204                    })
1205                    .map_err(|e| failed(e.to_string()))?,
1206                )
1207            };
1208            // A profile vectordata refuses for the set still reads as
1209            // lists, so the refusal is kept for the node that asks for
1210            // the set, and reported by it. A slab has no other reader,
1211            // so there the refusal is the facet's.
1212            let admitted =
1213                run_blocking_io(|| AdmittedRows::open(view.as_ref())).map_err(|e| e.to_string());
1214            let count = match (&reader, &admitted) {
1215                (Some(reader), _) => reader.count(),
1216                (None, Ok(admitted)) => admitted.queries(),
1217                (None, Err(e)) => return Err(failed(e.clone())),
1218            };
1219            let arc: Arc<Self> = Arc::new(Self {
1220                reader,
1221                count,
1222                admitted,
1223            });
1224            Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
1225        })?;
1226        any.downcast::<Self>().map_err(|_| {
1227            format!("facet cache type mismatch for '{source}:{profile}/metadata_results'")
1228        })
1229    }
1230}
1231
1232/// Access metadata indices (variable-length matching base ordinals
1233/// per query) at an index. Expects an Ivvec32 handle.
1234///
1235/// Signature: `metadata_results_at(handle, index: u64) -> VecI32`
1236#[crate::polydat_node(category = RealData)]
1237fn metadata_results_at(
1238    handle: Facet<MetadataResultsFacet>,
1239    index: u64,
1240) -> crate::ast::SliceArc<i32> {
1241    ivvec32_vec_typed(
1242        handle.resolve_facet(MetadataResultsFacet::FACET).as_ref(),
1243        index as usize,
1244    )
1245}
1246
1247/// Return the length of one metadata_results record without
1248/// loading the data (reads only the 4-byte header). Expects an
1249/// Ivvec32 handle.
1250///
1251/// Signature: `metadata_results_len_at(handle, index: u64) -> (u64)`
1252#[crate::polydat_node(category = RealData)]
1253fn metadata_results_len_at(handle: Facet<MetadataResultsFacet>, index: u64) -> u64 {
1254    match handle.resolve_facet(MetadataResultsFacet::FACET).as_ref() {
1255        DatasetHandle::Ivvec32(d) if d.count > 0 => {
1256            let query = index as usize % d.count;
1257            match &d.reader {
1258                Some(reader) => reader.dim_at(query).unwrap_or(0) as u64,
1259                None => d
1260                    .admitted_rows("metadata_results_len_at")
1261                    .count_at(query)
1262                    .unwrap_or_else(|e| panic!("metadata_results_len_at: {e}"))
1263                    as u64,
1264            }
1265        }
1266        _ => 0,
1267    }
1268}
1269
1270/// The base positions the predicate of query `index` admits, as a set:
1271/// vectordata's admitted-row set over the query's `metadata_results`
1272/// record, on an `admitted_rows` wire. Where `metadata_results_at`
1273/// puts the whole list on a wire, this is a handle to the record that
1274/// reads nothing until it is asked, by `admitted_rows_contain`, by
1275/// `admitted_rows_len`, or by a host that keeps the value and asks it
1276/// directly (`Value::Dataset(DatasetValue::AdmittedRows(set))`, where
1277/// `set` is vectordata's `OrdinalSet`). Holding one keeps the record's
1278/// storage open. The query index wraps modulo the facet's rows. A
1279/// profile whose base window does not start at zero is refused with
1280/// vectordata's reason.
1281///
1282/// That a record's positions are ascending and within the base is the
1283/// dataset's guarantee, verified where it is published; nothing is
1284/// checked here.
1285///
1286/// Signature: `admitted_rows_at(handle, index: u64) -> (admitted_rows)`
1287#[crate::polydat_node(category = RealData)]
1288fn admitted_rows_at(handle: Facet<MetadataResultsFacet>, index: u64) -> dv::Shared<OrdinalSet> {
1289    let who = "admitted_rows_at";
1290    let h = handle.resolve_facet(MetadataResultsFacet::FACET);
1291    let DatasetHandle::Ivvec32(d) = h.as_ref() else {
1292        panic!(
1293            "{who}: expected a metadata_results handle, got {}",
1294            dataset_handle_kind(h.as_ref())
1295        );
1296    };
1297    let admitted = d.admitted_rows(who);
1298    let queries = admitted.queries();
1299    assert!(queries > 0, "{who}: the facet has no rows");
1300    let set = admitted
1301        .get(index as usize % queries)
1302        .unwrap_or_else(|e| panic!("{who}: {e}"));
1303    dv::Shared(Arc::new(set))
1304}
1305
1306/// Whether the admitted rows `rows`, from `admitted_rows_at`, hold the
1307/// base position `ordinal`: whether the query's predicate admits that
1308/// base vector.
1309///
1310/// Signature: `admitted_rows_contain(rows: admitted_rows, ordinal: u64) -> (bool)`
1311#[crate::polydat_node(category = RealData)]
1312fn admitted_rows_contain(rows: dv::Shared<OrdinalSet>, ordinal: u64) -> bool {
1313    rows.contains(ordinal)
1314}
1315
1316/// How many base positions the admitted rows `rows`, from
1317/// `admitted_rows_at`, hold.
1318///
1319/// Signature: `admitted_rows_len(rows: admitted_rows) -> (u64)`
1320#[crate::polydat_node(category = RealData)]
1321fn admitted_rows_len(rows: dv::Shared<OrdinalSet>) -> u64 {
1322    rows.len() as u64
1323}
1324
1325/// Return the metadata indices count (number of predicate result
1326/// sets). Expects an Ivvec32 handle.
1327#[crate::polydat_node(category = RealData)]
1328fn metadata_results_count(handle: Facet<MetadataResultsFacet>) -> u64 {
1329    match handle.resolve_facet(MetadataResultsFacet::FACET).as_ref() {
1330        DatasetHandle::Ivvec32(d) => d.count as u64,
1331        _ => 0,
1332    }
1333}
1334
1335/// Report which facets are available for the default profile of
1336/// a dataset group as a comma-separated list. Expects a group or
1337/// prebuffered handle.
1338///
1339/// Signature: `dataset_facets(group) -> (str)`
1340#[crate::polydat_node(category = RealData)]
1341fn dataset_facets(group: Group) -> String {
1342    let group = group.resolve_group();
1343    // Use the default profile — group-level callers want a
1344    // dataset-wide manifest; specific profile facets come via
1345    // `profile_facets(group, idx)`.
1346    let names = group.profile_names();
1347    if let Some(first) = names.first()
1348        && let Some(view) = group.profile(first)
1349    {
1350        let manifest = view.facet_manifest();
1351        let mut names: Vec<&String> = manifest.keys().collect();
1352        names.sort();
1353        return names
1354            .iter()
1355            .map(|s| s.as_str())
1356            .collect::<Vec<_>>()
1357            .join(", ");
1358    }
1359    String::new()
1360}
1361
1362// =================================================================
1363// Profile enumeration — discover and iterate over dataset profiles
1364// =================================================================
1365//
1366// Group-level: take a Group handle, read the dataset's sorted profile
1367// list. Sort order is canonical (by base_count via `profile_sort_by_size`)
1368// and computed once per group via the underlying TestDataGroup.
1369
1370/// Total number of profiles in a dataset group.
1371///
1372/// Signature: `dataset_profile_count(group) -> (u64)`
1373#[crate::polydat_node(category = RealData)]
1374fn dataset_profile_count(group: Group) -> u64 {
1375    group.resolve_group().profile_names().len() as u64
1376}
1377
1378/// Comma-separated list of all profile names in canonical sort
1379/// order (by base_count).
1380///
1381/// Signature: `dataset_profile_names(group) -> (str)`
1382#[crate::polydat_node(category = RealData)]
1383fn dataset_profile_names(group: Group) -> String {
1384    group.resolve_group().profile_names().join(", ")
1385}
1386
1387/// Return profile names matching a prefix, comma-separated.
1388///
1389/// Signature: `matching_profiles(group, prefix: str) -> (str)`
1390///
1391/// If prefix is empty, returns all profiles. Used by `for_each:`
1392/// phase templates to discover profiles dynamically.
1393///
1394/// `group` declares its source-string auto-resolver via the
1395/// `Resolved<GroupResolver, _>` marker wrapper — the macro reads
1396/// `<Resolved<GroupResolver, DatasetHandle> as Wire>::RESOLVER` at
1397/// codegen and emits the matching `FuncSig.default_resolver`
1398/// (`DefaultResolver::Group`). The spliced `dataset_group_open` yields
1399/// the canonical `Value::Handle(Arc<DatasetHandle>)`, so the wire is
1400/// resolved as `DatasetHandle` and the group is taken via
1401/// `DatasetHandle::resolve_group` (downcasting straight to
1402/// `TestDataGroup` would fail — the handle is always the unified
1403/// `DatasetHandle` enum).
1404#[crate::polydat_node(category = RealData)]
1405fn matching_profiles(
1406    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1407    prefix: &str,
1408) -> String {
1409    let group: &TestDataGroup = group.resolve_group();
1410    let all = group.profile_names();
1411    let mut matched: Vec<&str> = if prefix.is_empty() {
1412        all.iter().map(|s| s.as_str()).collect()
1413    } else {
1414        all.iter()
1415            .filter(|s| s.starts_with(prefix))
1416            .map(|s| s.as_str())
1417            .collect()
1418    };
1419    // Natural-order sort: alphabetic with numeric runs
1420    // compared as numbers so `label_03` sorts before
1421    // `label_10`. The upstream `group.profile_names()`
1422    // orders by `base_count` (vectordata's choice — useful
1423    // for index-based lookups), but `for_each` iteration
1424    // wants stable, human-natural order so users see
1425    // label_01, label_02, label_03 instead of whatever the
1426    // size-sort happens to produce.
1427    matched.sort_by(|a, b| natural_cmp(a, b));
1428    matched.join(",")
1429}
1430
1431/// Natural ordering: split each string into alternating text
1432/// and numeric runs and compare run-by-run, comparing numeric
1433/// runs as integers. Beats lexicographic on `label_03` vs
1434/// `label_10` (lex: "10" < "3"; natural: 3 < 10).
1435fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
1436    let mut ai = a.chars().peekable();
1437    let mut bi = b.chars().peekable();
1438    loop {
1439        match (ai.peek().copied(), bi.peek().copied()) {
1440            (None, None) => return std::cmp::Ordering::Equal,
1441            (None, _) => return std::cmp::Ordering::Less,
1442            (_, None) => return std::cmp::Ordering::Greater,
1443            (Some(ac), Some(bc)) => {
1444                if ac.is_ascii_digit() && bc.is_ascii_digit() {
1445                    let mut na: u64 = 0;
1446                    while let Some(c) = ai.peek().copied()
1447                        && c.is_ascii_digit()
1448                    {
1449                        na = na
1450                            .saturating_mul(10)
1451                            .saturating_add((c as u8 - b'0') as u64);
1452                        ai.next();
1453                    }
1454                    let mut nb: u64 = 0;
1455                    while let Some(c) = bi.peek().copied()
1456                        && c.is_ascii_digit()
1457                    {
1458                        nb = nb
1459                            .saturating_mul(10)
1460                            .saturating_add((c as u8 - b'0') as u64);
1461                        bi.next();
1462                    }
1463                    match na.cmp(&nb) {
1464                        std::cmp::Ordering::Equal => continue,
1465                        non_eq => return non_eq,
1466                    }
1467                } else {
1468                    match ac.cmp(&bc) {
1469                        std::cmp::Ordering::Equal => {
1470                            ai.next();
1471                            bi.next();
1472                        }
1473                        non_eq => return non_eq,
1474                    }
1475                }
1476            }
1477        }
1478    }
1479}
1480
1481/// Look up a profile name by index from the canonical sorted list.
1482///
1483/// Signature: `dataset_profile_name_at(group, index: u64) -> (str)`
1484///
1485/// Index wraps modulo the number of profiles.
1486#[crate::polydat_node(category = RealData)]
1487fn dataset_profile_name_at(
1488    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1489    index: u64,
1490) -> String {
1491    let group: &TestDataGroup = group.resolve_group();
1492    let names = group.profile_names();
1493    if names.is_empty() {
1494        String::new()
1495    } else {
1496        names[(index as usize) % names.len()].clone()
1497    }
1498}
1499
1500/// Return the base vector count for the profile at a given index.
1501///
1502/// Signature: `profile_base_count(group, index: u64) -> (u64)`
1503#[crate::polydat_node(category = RealData)]
1504fn profile_base_count(
1505    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1506    index: u64,
1507) -> u64 {
1508    let group: &TestDataGroup = group.resolve_group();
1509    let names = group.profile_names();
1510    if names.is_empty() {
1511        0
1512    } else {
1513        let name = &names[(index as usize) % names.len()];
1514        group
1515            .profile(name)
1516            .and_then(|view| view.base_count())
1517            .unwrap_or(0)
1518    }
1519}
1520
1521/// Return the comma-separated facet list for the profile at a given index.
1522///
1523/// Signature: `profile_facets(group, index: u64) -> (str)`
1524#[crate::polydat_node(category = RealData)]
1525fn profile_facets(
1526    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1527    index: u64,
1528) -> String {
1529    let group: &TestDataGroup = group.resolve_group();
1530    let names = group.profile_names();
1531    if names.is_empty() {
1532        String::new()
1533    } else {
1534        let name = &names[(index as usize) % names.len()];
1535        match group.profile(name) {
1536            Some(view) => {
1537                let manifest = view.facet_manifest();
1538                let mut fnames: Vec<&String> = manifest.keys().collect();
1539                fnames.sort();
1540                fnames
1541                    .iter()
1542                    .map(|s| s.as_str())
1543                    .collect::<Vec<_>>()
1544                    .join(", ")
1545            }
1546            None => String::new(),
1547        }
1548    }
1549}
1550
1551/// Partition a dataset's vector space by its **profiles matching a
1552/// pattern**, treated as cumulative size tiers (a partition source,
1553/// cursor_partitions.md §7.1). One partition per masked profile, in canonical
1554/// (base-count-ascending) order: partition `k` spans
1555/// `[prev_masked_base_count, this_masked_base_count)` — exactly the
1556/// vectors added at that tier — so a sweep's "load only the increment
1557/// since the previously loaded set" is just the partition's
1558/// `[start_of(p), end_of(p))`, and a partition inherently knows its
1559/// start (no cross-iteration carry needed). `idx_of(p)` is the 0-based
1560/// masked position (pairs with `matching_profile_name_at` to address
1561/// the tier's own ground-truth facets); `count_of(p)` is the number of
1562/// masked tiers; `base_extent` is the largest masked tier's size.
1563///
1564/// `pattern` follows the literal / glob / regex promotion of
1565/// [`crate::library::support::pattern::compile_pattern`]; `*` (or any pattern that
1566/// matches all names) selects every profile.
1567///
1568/// Signature: `profile_partitions(group, pattern: str) -> (PartitionList)`
1569#[crate::polydat_node(category = RealData)]
1570fn profile_partitions(
1571    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1572    pattern: &str,
1573) -> crate::derive_support::Ext<crate::iteration::cursor_partition::PartitionList> {
1574    let group: &TestDataGroup = group.resolve_group();
1575    let parts = build_profile_partitions(group, pattern);
1576    crate::derive_support::Ext(crate::iteration::cursor_partition::PartitionList::new(
1577        parts,
1578    ))
1579}
1580
1581/// Build the cumulative size-tier partitions for the profiles of `group`
1582/// matching `pattern` (literal/glob/regex promotion). Shared by the
1583/// [`profile_partitions`] node and the comprehension-source desugaring
1584/// in `iteration::comprehension::eval` so a `for: "p in
1585/// profile_partitions(...)"` sweep produces identical partitions either
1586/// way. Partition `k` spans `[prev masked base_count, this base_count)`.
1587/// The masked profile size-tiers for `group` matching `pattern`, in
1588/// canonical (base-count-ascending) order: `(name, cumulative_base_count)`
1589/// for each matching profile WITH a non-zero base count. Profiles with no
1590/// base facet, or a zero count, are skipped — they would otherwise emit a
1591/// degenerate empty `[prev, prev)` partition (and a query against an empty
1592/// tier). Shared by [`build_profile_partitions`] and
1593/// [`matching_profile_name_at`] so a partition's `idx_of(p)` and the tier
1594/// name resolve against the SAME masked sequence.
1595fn masked_profile_tiers(group: &TestDataGroup, pattern: &str) -> Vec<(String, u64)> {
1596    let (re, _) = crate::library::support::pattern::compile_pattern(pattern)
1597        .unwrap_or_else(|e| panic!("profile pattern: {e}"));
1598    group
1599        .profile_names()
1600        .iter()
1601        .filter(|n| re.is_match(n))
1602        .filter_map(|n| {
1603            group
1604                .profile(n)
1605                .and_then(|v| v.base_count())
1606                .filter(|&c| c > 0)
1607                .map(|c| (n.clone(), c))
1608        })
1609        .collect()
1610}
1611
1612pub(crate) fn build_profile_partitions(
1613    group: &TestDataGroup,
1614    pattern: &str,
1615) -> Vec<crate::iteration::cursor_partition::Partition> {
1616    // Masked size-tiers (matching profiles with a non-zero base count),
1617    // canonical (ascending) order — skipping zero-count profiles avoids a
1618    // degenerate empty first partition.
1619    let masked: Vec<u64> = masked_profile_tiers(group, pattern)
1620        .into_iter()
1621        .map(|(_, c)| c)
1622        .collect();
1623    let base_extent = masked.last().copied().unwrap_or(0);
1624    let count = masked.len() as u64;
1625    let pct = |o: u64| {
1626        if base_extent == 0 {
1627            0.0
1628        } else {
1629            (o as f64 / base_extent as f64) * 100.0
1630        }
1631    };
1632    let mut parts: Vec<crate::iteration::cursor_partition::Partition> =
1633        Vec::with_capacity(masked.len());
1634    let mut prev: u64 = 0;
1635    for (k, &this) in masked.iter().enumerate() {
1636        parts.push(crate::iteration::cursor_partition::Partition {
1637            idx: k as u64,
1638            count,
1639            start_ord: prev,
1640            end_ord: this,
1641            start_pct: pct(prev),
1642            end_pct: pct(this),
1643            base_extent,
1644        });
1645        prev = this;
1646    }
1647    parts
1648}
1649
1650/// Name of the `index`-th profile **matching `pattern`**, in canonical
1651/// (base-count-ascending) order. Pairs with `profile_partitions`'s
1652/// masked-position `idx_of` so a sweep can prebuffer the active tier's
1653/// own ground-truth facets (`dataset_prebuffer(str_concat("ds:", name))`).
1654/// `pattern` follows the literal / glob / regex promotion; the index
1655/// wraps modulo the number of matching profiles; empty string if none
1656/// match.
1657///
1658/// Signature: `matching_profile_name_at(group, pattern: str, index: u64) -> (str)`
1659#[crate::polydat_node(category = RealData)]
1660fn matching_profile_name_at(
1661    group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1662    pattern: &str,
1663    index: u64,
1664) -> String {
1665    let group: &TestDataGroup = group.resolve_group();
1666    // Same masked sequence `profile_partitions` uses (matching profiles
1667    // with a non-zero base count, canonical order), so `idx_of(p)` from a
1668    // partition resolves to the right tier name.
1669    let tiers = masked_profile_tiers(group, pattern);
1670    if tiers.is_empty() {
1671        String::new()
1672    } else {
1673        tiers[(index as usize) % tiers.len()].0.clone()
1674    }
1675}
1676
1677// =================================================================
1678// Prebuffering — eagerly download dataset facets before workload run
1679// =================================================================
1680
1681/// Eagerly download all facets for a dataset profile into the
1682/// local cache, returning a dataset handle that every facet
1683/// accessor and every group accessor takes as its first
1684/// argument. After this returns, every subsequent facet read
1685/// served by [`vectordata::TestDataView`] hits the merkle-
1686/// verified mmap fast path with no further network traffic.
1687///
1688/// Signature: `dataset_prebuffer(source) -> Handle`
1689///
1690/// **Why a handle, not a count.** Returning a value the
1691/// downstream accessors *consume* makes prebuffer part of
1692/// the dataflow graph: DCE keeps the chain alive because
1693/// `vector_at(prebuffered, q)` needs `prebuffered` to be
1694/// resolvable, which forces evaluation. A binding such as
1695/// `init prebuffered = dataset_prebuffer(...)` whose result
1696/// nothing reads is pruned, so a workload threads the handle
1697/// through its accessors.
1698///
1699/// `source` is the canonical `dataset:profile` string. The
1700/// returned handle names the dataset rather than one facet: a
1701/// facet accessor opens its own facet of `source` from it
1702/// (`DatasetHandle::resolve_facet`), and a group accessor
1703/// (`dataset_facets`, `dataset_distance_function`, ...) reads
1704/// the dataset's group (`DatasetHandle::resolve_group`).
1705///
1706/// A dataset that does not resolve yields no handle, and the
1707/// resolve error goes to the audit log. A profile the dataset
1708/// lacks, or a facet whose download fails, is logged there too
1709/// and still yields the handle: prebuffering is a best-effort
1710/// warm-up, and an accessor that then reads a missing facet
1711/// fails with that facet's own error.
1712#[crate::polydat_node(category = RealData)]
1713fn dataset_prebuffer(source: &str) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
1714    // The const binding contract (evaluation_model.md §"Const
1715    // Binding Contract") means this runs exactly once per scope
1716    // activation: the activation kernel pulls the binding and the host propagates the result to every
1717    // fiber. PREBUFFER_CACHE is belt-and-suspenders: it serializes
1718    // anyone who reaches here by another path, so a per-source
1719    // thundering herd is structurally impossible whatever the caller
1720    // does.
1721    match PREBUFFER_CACHE.get_or_init(source.to_string(), || {
1722        // Only the first concurrent caller for this source runs the
1723        // inner body — the audit "entered" event reflects that one
1724        // download, not per-caller noise.
1725        crate::library::support::audit::record_prebuffer_entered(source);
1726        do_dataset_prebuffer_inner(source)
1727    }) {
1728        Ok(handle) => Some(handle as Arc<dyn std::any::Any + Send + Sync>),
1729        Err(_) => None,
1730    }
1731}
1732
1733/// Inner body of [`dataset_prebuffer`]. Runs **at most once
1734/// per (source, process)** under the [`PREBUFFER_CACHE`] OnceLock.
1735fn do_dataset_prebuffer_inner(source: &str) -> Result<Arc<DatasetHandle>, String> {
1736    // Every exit after the group resolves returns a prebuffered
1737    // handle, so the downstream `*_at(prebuffered, q)` accessors can
1738    // resolve. A failed download still hands back the handle — the
1739    // accessors then read through the transport, and the operator
1740    // sees the prebuffer error in the audit log.
1741    let group = match load_dataset_group(source) {
1742        Ok(g) => g,
1743        Err(e) => {
1744            let msg = format!("dataset_prebuffer: cannot resolve '{source}': {e}");
1745            crate::library::support::audit::error(&msg);
1746            // No group → no handle to hand back. Sticky error in
1747            // the cache; downstream accessors will produce a
1748            // diagnostic when they fail to downcast.
1749            return Err(msg);
1750        }
1751    };
1752    let group_for_handle = group.clone();
1753    let (_, profile) = parse_source_specifier(source);
1754    let view = match group.profile(profile) {
1755        Some(v) => v,
1756        None => {
1757            crate::library::support::audit::error(&format!(
1758                "dataset_prebuffer: profile '{profile}' not found in '{source}'"
1759            ));
1760            return Ok(Arc::new(DatasetHandle::Prebuffered {
1761                group: group_for_handle,
1762                source: source.to_string(),
1763            }));
1764        }
1765    };
1766    // One fetch over every facet that holds data: vectordata plans
1767    // each facet, refuses a run the cache directory cannot hold
1768    // before any byte moves, and skips chunks already resident.
1769    // [`fetch_meter`] reports the run through the audit channel,
1770    // throttled so a multi-gigabyte facet doesn't spew thousands of
1771    // lines into session.log.
1772    //
1773    // Audit instrumentation: log every facet the fetch *covers* with
1774    // its key (`source:profile/facet`). Compared against the
1775    // `vectordata: opened …` lines emitted by [`load_uniform_facet`] /
1776    // [`GenericFacetDataset::load`], this surfaces any facet the
1777    // workload reads at cycle time that prebuffer did NOT pull — the
1778    // typical cause of a "still hitting HTTP after prebuffer" symptom.
1779    //
1780    // `fetch` drives `reqwest::blocking`, which spins up a private
1781    // tokio runtime per request; `run_blocking_io` parks the outer
1782    // worker so dropping that inner runtime doesn't panic. Same
1783    // pattern as `load_dataset_group` and `load_uniform_facet`.
1784    let mut meter = fetch_meter(&format!("prebuffer {source}"));
1785    let facet_count = match run_blocking_io(|| view.fetch(&FetchRequest::all(), &mut meter)) {
1786        Ok(report) => {
1787            for fetched in &report.facets {
1788                crate::library::support::audit::record_prebuffered(
1789                    parse_source_specifier(source).0,
1790                    profile,
1791                    &fetched.id.facet,
1792                );
1793            }
1794            report.facets.len() as u64
1795        }
1796        Err(e) => {
1797            crate::library::support::audit::warn(&format!(
1798                "dataset_prebuffer: download error for '{source}': {e}"
1799            ));
1800            0
1801        }
1802    };
1803    crate::library::support::audit::log_prebuffer_summary(
1804        parse_source_specifier(source).0,
1805        profile,
1806        facet_count,
1807    );
1808    Ok(Arc::new(DatasetHandle::Prebuffered {
1809        group: group_for_handle,
1810        source: source.to_string(),
1811    }))
1812}
1813
1814/// The progress meter for a fetch, titled `title`: whole lines on the
1815/// audit channel — a line as each facet starts and finishes, and a
1816/// progress line per 10% of the run but at most one per 10s — and
1817/// nothing for data already in the cache.
1818fn fetch_meter(title: &str) -> LogMeter {
1819    LogMeter::to_lines(title, |level, line| {
1820        crate::library::support::audit::log(level.into(), line)
1821    })
1822    .min_interval(std::time::Duration::from_secs(10))
1823    .quiet_when_resident(true)
1824}
1825
1826// =================================================================
1827// Generic facet access — type-aware scalar/vector readers
1828// =================================================================
1829
1830/// A type-erased facet reader that reads values as i64.
1831/// Uses [`TestDataViewExt::facet_as`] at `i64`, which widens every
1832/// integer element type (u8, i32, …) and serves local and remote
1833/// facets through the same cache.
1834pub(crate) struct GenericFacetDataset {
1835    reader: Arc<dyn VectorReader<i64>>,
1836    count: usize,
1837}
1838
1839impl GenericFacetDataset {
1840    fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
1841        let key = (source.to_string(), profile.to_string(), facet.to_string());
1842        let any = FACET_CACHE.get_or_init(key, || {
1843            let group = load_dataset_group(source)?;
1844            let view = group
1845                .profile(profile)
1846                .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
1847            crate::library::support::audit::record_opened(
1848                parse_source_specifier(source).0,
1849                profile,
1850                facet,
1851                "generic-typed",
1852            );
1853            let reader = run_blocking_io(|| view.facet_as::<i64>(facet))
1854                .map_err(|e| format!("failed to open {facet} from '{source}:{profile}': {e}"))?;
1855            let count = reader.count();
1856            let arc: Arc<Self> = Arc::new(Self { reader, count });
1857            Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
1858        })?;
1859        any.downcast::<Self>()
1860            .map_err(|_| format!("facet cache type mismatch for '{source}:{profile}/{facet}'"))
1861    }
1862
1863    fn get_scalar(&self, index: usize) -> i64 {
1864        if self.count == 0 {
1865            return 0;
1866        }
1867        let index = index % self.count;
1868        match self.reader.get_slice(index) {
1869            Some(record) => record.first().copied().unwrap_or(0),
1870            None => self
1871                .reader
1872                .get(index)
1873                .ok()
1874                .and_then(|record| record.first().copied())
1875                .unwrap_or(0),
1876        }
1877    }
1878
1879    fn format_scalar(&self, index: usize) -> String {
1880        self.get_scalar(index).to_string()
1881    }
1882}
1883
1884// Generic-facet readers (typed scalar). Take a Generic handle and
1885// read the i64-cast value at the requested index.
1886/// The scalar of a Generic facet at `idx`, rendered.
1887fn generic_str_typed(h: &DatasetHandle, idx: usize) -> String {
1888    match h {
1889        DatasetHandle::Generic(d) => d.format_scalar(idx),
1890        DatasetHandle::Records(_) => panic!("{}", RECORDS_NOT_SCALARS),
1891        DatasetHandle::Predicates(_) => panic!("{}", PREDICATES_NOT_SCALARS),
1892        _ => String::new(),
1893    }
1894}
1895
1896// =================================================================
1897// Record metadata: one named, typed field of a record per base vector
1898// =================================================================
1899//
1900// A dataset may publish `metadata_content` as records. A field of a
1901// record is read in two steps, so that everything about the field is
1902// settled once, before the first cycle:
1903//
1904//   age_field := record_field_i64(source, "age")   // a constant
1905//   age := record_i64_at(age_field, row)           // per cycle
1906//
1907// The first resolves the name to a position in the layout and refuses
1908// a field the layout lacks, one of another type, and one the dataset
1909// declares may be null. It has only constant inputs, so it runs when
1910// the program is built and its refusal is a build error. The second
1911// reads that position of the record at an ordinal and checks nothing:
1912// that every record carries the layout's fields at the layout's types
1913// is the dataset's guarantee, verified where it is published.
1914
1915/// What a scalar node says of a predicate facet that holds records.
1916const PREDICATES_NOT_SCALARS: &str = "the metadata_predicates facet of this profile holds one \
1917     predicate record per query, not one scalar; read it as structure with `predicate_forms` and \
1918     `predicate_at`, or as text with `predicate_text_at`";
1919
1920/// What a scalar node says of a facet that holds records.
1921const RECORDS_NOT_SCALARS: &str = "the metadata_content facet of this profile holds records, not \
1922     one scalar per base vector; read a field of a record with a `record_field_*` node and its \
1923     `record_*_at` accessor";
1924
1925/// Whether `facet` of `source`'s profile holds records or fixed-width
1926/// elements, as the profile declares it; `None` when the dataset, the
1927/// profile or the facet cannot be found, which the reader that is then
1928/// tried reports in its own words.
1929fn facet_shape(source: &str, profile: &str, facet: &str) -> Option<FacetShape> {
1930    let group = load_dataset_group(source).ok()?;
1931    let view = group.profile(profile)?;
1932    view.facet_shape(facet).ok()
1933}
1934
1935/// The `metadata_content` facet of a profile that publishes it as
1936/// records: the facet's forms (its layout, the binder over every field
1937/// and the records), and how many records there are.
1938pub(crate) struct RecordDataset {
1939    forms: Arc<dv::RecordForms>,
1940    count: u64,
1941}
1942
1943/// What opening a record facet of `source`'s profile needs: the
1944/// profile's view, and the name the diagnostics give the dataset.
1945fn record_view(source: &str, profile: &str) -> Result<(Arc<dyn TestDataView>, String), String> {
1946    let group = load_dataset_group(source)?;
1947    let view = group
1948        .profile(profile)
1949        .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
1950    Ok((
1951        view,
1952        format!("{}:{profile}", parse_source_specifier(source).0),
1953    ))
1954}
1955
1956/// The layout of a profile's metadata records, with a warning when the
1957/// dataset declares none and it is learned from the first record.
1958fn resolve_layout(view: &dyn TestDataView, origin: &str) -> Result<Layout, String> {
1959    let layout = Layout::resolve(view).map_err(|e| e.to_string())?;
1960    if !layout.source().is_declared() {
1961        crate::library::support::audit::warn(&format!(
1962            "metadata_content of '{origin}' declares no layout; its fields are typed from {}, \
1963             which cannot type a field that is null there or a container that is empty there",
1964            layout.source()
1965        ));
1966    }
1967    Ok(layout)
1968}
1969
1970impl RecordDataset {
1971    fn load(source: &str, profile: &str) -> Result<Arc<Self>, String> {
1972        let facet_name = MetadataContentFacet::FACET;
1973        let key = (
1974            source.to_string(),
1975            profile.to_string(),
1976            format!("records:{facet_name}"),
1977        );
1978        let any = FACET_CACHE.get_or_init(key, || {
1979            let (view, origin) = record_view(source, profile)?;
1980            crate::library::support::audit::record_opened(
1981                parse_source_specifier(source).0,
1982                profile,
1983                facet_name,
1984                "records",
1985            );
1986            let (records, layout, count) = run_blocking_io(|| {
1987                let records = view
1988                    .open_facet_records(facet_name)
1989                    .map_err(|e| e.to_string())?;
1990                let layout = resolve_layout(view.as_ref(), &origin)?;
1991                let count = records.count().map_err(|e| e.to_string())?;
1992                Ok::<_, String>((records, layout, count))
1993            })
1994            .map_err(|e| format!("failed to open {facet_name} from '{origin}': {e}"))?;
1995            let arc: Arc<Self> = Arc::new(Self {
1996                forms: Arc::new(dv::RecordForms::new(layout, records, origin)),
1997                count,
1998            });
1999            Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
2000        })?;
2001        any.downcast::<Self>().map_err(|_| {
2002            format!("facet cache type mismatch for '{source}:{profile}/records:{facet_name}'")
2003        })
2004    }
2005}
2006
2007/// The forms of a profile's `metadata_predicates` records: every
2008/// predicate read once, each distinct form recorded with its template
2009/// and count, beside the layout its conditions bind against. Surveyed
2010/// once per source and profile and shared by every fiber.
2011fn load_predicate_forms(source: &str, profile: &str) -> Result<Arc<dv::PredicateForms>, String> {
2012    let facet_name = MetadataPredicatesFacet::FACET;
2013    let key = (
2014        source.to_string(),
2015        profile.to_string(),
2016        format!("records:{facet_name}"),
2017    );
2018    let any = FACET_CACHE.get_or_init(key, || {
2019        let (view, origin) = record_view(source, profile)?;
2020        crate::library::support::audit::record_opened(
2021            parse_source_specifier(source).0,
2022            profile,
2023            facet_name,
2024            "records",
2025        );
2026        let (predicates, layout, census) = run_blocking_io(|| {
2027            let predicates = view
2028                .open_facet_records(facet_name)
2029                .map_err(|e| e.to_string())?;
2030            let layout = resolve_layout(view.as_ref(), &origin)?;
2031            let census = FormCensus::of_facet(&predicates, &mut vectordata::NoProgress)
2032                .map_err(|e| e.to_string())?;
2033            Ok::<_, String>((predicates, layout, census))
2034        })
2035        .map_err(|e| format!("failed to open {facet_name} from '{origin}': {e}"))?;
2036        let arc = Arc::new(dv::PredicateForms::new(census, layout, predicates, origin));
2037        Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
2038    })?;
2039    any.downcast::<dv::PredicateForms>().map_err(|_| {
2040        format!("facet cache type mismatch for '{source}:{profile}/records:{facet_name}'")
2041    })
2042}
2043
2044/// The wire type a record field is read as.
2045#[derive(Clone, Copy, PartialEq, Eq)]
2046enum FieldWire {
2047    Str,
2048    Bool,
2049    I64,
2050    F64,
2051    Bytes,
2052}
2053
2054impl FieldWire {
2055    /// The port type keyword, for diagnostics.
2056    fn keyword(self) -> &'static str {
2057        match self {
2058            FieldWire::Str => "str",
2059            FieldWire::Bool => "bool",
2060            FieldWire::I64 => "i64",
2061            FieldWire::F64 => "f64",
2062            FieldWire::Bytes => "bytes",
2063        }
2064    }
2065
2066    /// Whether a field the layout types as `bind` reads as this wire
2067    /// type: the type itself or a lossless widening of it. A type with
2068    /// a meaning of its own, such as a timestamp or an identifier, is
2069    /// not the integer, text or bytes it is stored as.
2070    fn carries(self, bind: &BindType) -> bool {
2071        match self {
2072            FieldWire::Str => matches!(bind, BindType::Text | BindType::Ascii),
2073            FieldWire::Bool => matches!(bind, BindType::Bool),
2074            FieldWire::I64 => {
2075                matches!(bind, BindType::Int16 | BindType::Int32 | BindType::Int64)
2076            }
2077            FieldWire::F64 => {
2078                matches!(
2079                    bind,
2080                    BindType::Float16 | BindType::Float32 | BindType::Float64
2081                )
2082            }
2083            FieldWire::Bytes => matches!(bind, BindType::Blob),
2084        }
2085    }
2086}
2087
2088/// One field of a record facet, resolved: where it sits in a record
2089/// and the wire type it reads as. What a `record_field_*` node yields
2090/// and a `record_*_at` node reads through.
2091pub(crate) struct RecordField {
2092    records: Arc<RecordDataset>,
2093    /// Picks the field out of a record by its position.
2094    binder: Binder,
2095    name: String,
2096    wire: FieldWire,
2097}
2098
2099/// Resolve `field` of the record facet `h` as `wire`, for the node
2100/// `who`. Refuses a facet that does not hold records, a field the
2101/// layout lacks, one whose type is not `wire`'s, one whose type the
2102/// layout does not establish, and one the dataset declares may be
2103/// null.
2104fn resolve_record_field(
2105    h: &DatasetHandle,
2106    field: &str,
2107    wire: FieldWire,
2108    who: &str,
2109) -> Arc<dyn std::any::Any + Send + Sync> {
2110    let records = match h {
2111        DatasetHandle::Records(d) => d.clone(),
2112        DatasetHandle::Generic(_) => panic!(
2113            "{who}: the metadata_content facet of this profile holds one scalar per base vector, \
2114             not records with named fields; read it with `metadata_value_at`"
2115        ),
2116        other => panic!(
2117            "{who}: expected a metadata_content handle, got {}",
2118            dataset_handle_kind(other)
2119        ),
2120    };
2121    let layout = &records.forms.layout;
2122    let origin = &records.forms.origin;
2123    let Some(position) = layout.position_of(field) else {
2124        panic!(
2125            "{who}: the records of '{origin}' have no field `{field}`; they have {}",
2126            layout.names().join(", ")
2127        );
2128    };
2129    let bind = &layout.types()[position];
2130    if layout.unproven().contains(&field) {
2131        panic!(
2132            "{who}: the layout of '{origin}', learned from {}, does not establish the type of \
2133             `{field}`",
2134            layout.source()
2135        );
2136    }
2137    if !wire.carries(bind) {
2138        panic!(
2139            "{who}: field `{field}` of '{origin}' is {bind:?}, which does not read as {}",
2140            wire.keyword()
2141        );
2142    }
2143    if layout.nullability()[position] == Nullability::Nullable {
2144        panic!(
2145            "{who}: field `{field}` of '{origin}' is declared nullable, and a {} wire has no \
2146             null; a nullable field is not read as a scalar",
2147            wire.keyword()
2148        );
2149    }
2150    let binder = Binder::select(layout, &[field]).unwrap_or_else(|e| panic!("{who}: {e}"));
2151    Arc::new(RecordField {
2152        records,
2153        binder,
2154        name: field.to_string(),
2155        wire,
2156    })
2157}
2158
2159/// Read the resolved field `handle` of the record at `index`, for the
2160/// node `who`, which reads fields resolved as `wire`. The record index
2161/// wraps modulo the record count, as the other accessors' does.
2162/// Nothing about the record is checked: `get` reads the field as its
2163/// declared type.
2164fn read_record_field<R>(
2165    handle: &Arc<dyn std::any::Any + Send + Sync>,
2166    index: u64,
2167    wire: FieldWire,
2168    who: &str,
2169    get: impl Fn(&vectordata::formats::mnode::scan::Field<'_>) -> Option<R>,
2170) -> R {
2171    let Some(field) = handle.downcast_ref::<RecordField>() else {
2172        panic!("{who}: expected a field resolved by a `record_field_*` node");
2173    };
2174    assert!(
2175        field.wire == wire,
2176        "{who}: field `{}` was resolved as {}, and this node reads {}",
2177        field.name,
2178        field.wire.keyword(),
2179        wire.keyword()
2180    );
2181    let records = &field.records;
2182    let origin = &records.forms.origin;
2183    assert!(records.count > 0, "{who}: '{origin}' has no records");
2184    let ordinal = index % records.count;
2185    let record = records
2186        .forms
2187        .records
2188        .record_bytes(ordinal)
2189        .unwrap_or_else(|e| panic!("{who}: record {ordinal} of '{origin}': {e}"));
2190    let mut value = None;
2191    field
2192        .binder
2193        .bind_each(&record, |_, f| value = get(&f))
2194        .unwrap_or_else(|e| panic!("{who}: record {ordinal} of '{origin}': {e}"));
2195    value.unwrap_or_else(|| {
2196        panic!(
2197            "{who}: record {ordinal} of '{origin}' does not hold `{}` as the {} its layout \
2198             declares",
2199            field.name,
2200            wire.keyword()
2201        )
2202    })
2203}
2204
2205/// Resolve a text field of a dataset's metadata records, for
2206/// `record_str_at` to read. The name is resolved to its position in
2207/// the layout here, once. Refused when the records have no such field,
2208/// when the field is not text, and when the dataset declares it may be
2209/// null. Expects the metadata_content facet of a profile that
2210/// publishes records.
2211///
2212/// Signature: `record_field_str(handle, field: str) -> (handle)`
2213#[crate::polydat_node(category = RealData)]
2214fn record_field_str(
2215    handle: Facet<MetadataContentFacet>,
2216    field: &str,
2217) -> Arc<dyn std::any::Any + Send + Sync> {
2218    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2219    resolve_record_field(h.as_ref(), field, FieldWire::Str, "record_field_str")
2220}
2221
2222/// Resolve a boolean field of a dataset's metadata records, for
2223/// `record_bool_at` to read. Refused when the records have no such
2224/// field, when the field is not a boolean, and when the dataset
2225/// declares it may be null.
2226///
2227/// Signature: `record_field_bool(handle, field: str) -> (handle)`
2228#[crate::polydat_node(category = RealData)]
2229fn record_field_bool(
2230    handle: Facet<MetadataContentFacet>,
2231    field: &str,
2232) -> Arc<dyn std::any::Any + Send + Sync> {
2233    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2234    resolve_record_field(h.as_ref(), field, FieldWire::Bool, "record_field_bool")
2235}
2236
2237/// Resolve an integer field of a dataset's metadata records, for
2238/// `record_i64_at` to read. A 16-bit or 32-bit field reads as `i64`
2239/// without loss. Refused when the records have no such field, when the
2240/// field is not an integer, and when the dataset declares it may be
2241/// null.
2242///
2243/// Signature: `record_field_i64(handle, field: str) -> (handle)`
2244#[crate::polydat_node(category = RealData)]
2245fn record_field_i64(
2246    handle: Facet<MetadataContentFacet>,
2247    field: &str,
2248) -> Arc<dyn std::any::Any + Send + Sync> {
2249    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2250    resolve_record_field(h.as_ref(), field, FieldWire::I64, "record_field_i64")
2251}
2252
2253/// Resolve a floating-point field of a dataset's metadata records, for
2254/// `record_f64_at` to read. A 16-bit or 32-bit field reads as `f64`
2255/// without loss. Refused when the records have no such field, when the
2256/// field is not a float, and when the dataset declares it may be null.
2257///
2258/// Signature: `record_field_f64(handle, field: str) -> (handle)`
2259#[crate::polydat_node(category = RealData)]
2260fn record_field_f64(
2261    handle: Facet<MetadataContentFacet>,
2262    field: &str,
2263) -> Arc<dyn std::any::Any + Send + Sync> {
2264    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2265    resolve_record_field(h.as_ref(), field, FieldWire::F64, "record_field_f64")
2266}
2267
2268/// Resolve a bytes field of a dataset's metadata records, for
2269/// `record_bytes_at` to read. Refused when the records have no such
2270/// field, when the field is not a blob, and when the dataset declares
2271/// it may be null.
2272///
2273/// Signature: `record_field_bytes(handle, field: str) -> (handle)`
2274#[crate::polydat_node(category = RealData)]
2275fn record_field_bytes(
2276    handle: Facet<MetadataContentFacet>,
2277    field: &str,
2278) -> Arc<dyn std::any::Any + Send + Sync> {
2279    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2280    resolve_record_field(h.as_ref(), field, FieldWire::Bytes, "record_field_bytes")
2281}
2282
2283/// The text field `field`, resolved by `record_field_str`, of the
2284/// metadata record at `index`. Nothing is checked per record.
2285///
2286/// Signature: `record_str_at(field: handle, index: u64) -> (str)`
2287#[crate::polydat_node(category = RealData)]
2288fn record_str_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> String {
2289    read_record_field(&field, index, FieldWire::Str, "record_str_at", |f| {
2290        f.as_str().map(str::to_string)
2291    })
2292}
2293
2294/// The boolean field `field`, resolved by `record_field_bool`, of the
2295/// metadata record at `index`. Nothing is checked per record.
2296///
2297/// Signature: `record_bool_at(field: handle, index: u64) -> (bool)`
2298#[crate::polydat_node(category = RealData)]
2299fn record_bool_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> bool {
2300    read_record_field(&field, index, FieldWire::Bool, "record_bool_at", |f| {
2301        f.as_bool()
2302    })
2303}
2304
2305/// The integer field `field`, resolved by `record_field_i64`, of the
2306/// metadata record at `index`. Nothing is checked per record.
2307///
2308/// Signature: `record_i64_at(field: handle, index: u64) -> (i64)`
2309#[crate::polydat_node(category = RealData)]
2310fn record_i64_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> i64 {
2311    read_record_field(&field, index, FieldWire::I64, "record_i64_at", |f| {
2312        f.as_i64()
2313    })
2314}
2315
2316/// The floating-point field `field`, resolved by `record_field_f64`,
2317/// of the metadata record at `index`. Nothing is checked per record.
2318///
2319/// Signature: `record_f64_at(field: handle, index: u64) -> (f64)`
2320#[crate::polydat_node(category = RealData)]
2321fn record_f64_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> f64 {
2322    read_record_field(&field, index, FieldWire::F64, "record_f64_at", |f| {
2323        f.as_f64()
2324    })
2325}
2326
2327/// The bytes field `field`, resolved by `record_field_bytes`, of the
2328/// metadata record at `index`. Nothing is checked per record.
2329///
2330/// Signature: `record_bytes_at(field: handle, index: u64) -> (bytes)`
2331#[crate::polydat_node(category = RealData)]
2332fn record_bytes_at(field: Arc<dyn std::any::Any + Send + Sync>, index: u64) -> Vec<u8> {
2333    read_record_field(&field, index, FieldWire::Bytes, "record_bytes_at", |f| {
2334        f.as_bytes().map(<[u8]>::to_vec)
2335    })
2336}
2337
2338// =================================================================
2339// Dataset records as structure: forms and fragments
2340// =================================================================
2341//
2342// A dataset's predicates and metadata records reach a host by one of
2343// two pathways, which are distinct in the type system. As structure,
2344// here: a `forms` constant and a `fragment` per cycle, carrying
2345// vectordata's own types, for a host that prepares a statement per
2346// form and binds records to it without parsing text. As text, in the
2347// next section: a `str` rendered by a packaged vernacular the program
2348// names.
2349//
2350//   forms := predicate_forms(source)        // a constant, type forms
2351//   filter := predicate_at(forms, query)    // per cycle, type fragment
2352//
2353// The first has only constant inputs, so the facet is surveyed when
2354// the program is built and never again. The second names a predicate
2355// by its form's index and its ordinal: it reads no record and
2356// allocates nothing. A host learns which forms a fragment wire can
2357// carry, before any cycle, from the program
2358// (`PolydatProgram::dataset_sources`).
2359
2360/// The predicate records of the handle `h`, for the node `who`.
2361/// Refuses a predicate facet that holds one scalar per query.
2362fn predicate_records<'a>(h: &'a DatasetHandle, who: &str) -> &'a Arc<dv::PredicateForms> {
2363    match h {
2364        DatasetHandle::Predicates(forms) => forms,
2365        DatasetHandle::Generic(_) => panic!(
2366            "{who}: the metadata_predicates facet of this profile holds one scalar per query, \
2367             not predicate records; read it with `predicate_value_at`"
2368        ),
2369        other => panic!(
2370            "{who}: expected a metadata_predicates handle, got {}",
2371            dataset_handle_kind(other)
2372        ),
2373    }
2374}
2375
2376/// The metadata records of the handle `h`, for the node `who`. Refuses
2377/// a metadata facet that holds one scalar per base vector.
2378fn metadata_records<'a>(h: &'a DatasetHandle, who: &str) -> &'a Arc<RecordDataset> {
2379    match h {
2380        DatasetHandle::Records(records) => records,
2381        DatasetHandle::Generic(_) => panic!(
2382            "{who}: the metadata_content facet of this profile holds one scalar per base vector, \
2383             not records with named fields; read it with `metadata_value_at`"
2384        ),
2385        other => panic!(
2386            "{who}: expected a metadata_content handle, got {}",
2387            dataset_handle_kind(other)
2388        ),
2389    }
2390}
2391
2392/// The forms of a dataset's predicates: every distinct form its
2393/// `metadata_predicates` records take, with the form's template and
2394/// count, the form of the predicate at each ordinal, the strata the
2395/// facet publishes, and the layout of the metadata records the
2396/// conditions bind against. A constant: the facet is read once, when
2397/// the program is built.
2398///
2399/// A form the layout cannot bind is not refused here. It is in the
2400/// forms with its count, and a host that compiles each form's binder
2401/// (`form.binder(&forms.layout)`) gets its reason, so it can report
2402/// every such form together with those its own dialect cannot express.
2403///
2404/// Signature: `predicate_forms(handle) -> (forms)`
2405#[crate::polydat_node(category = RealData)]
2406fn predicate_forms(handle: Facet<MetadataPredicatesFacet>) -> dv::Shared<dv::PredicateForms> {
2407    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
2408    dv::Shared(predicate_records(h.as_ref(), "predicate_forms").clone())
2409}
2410
2411/// The predicate of query `index`, as structure: which of `forms` it
2412/// takes, and its ordinal. A host selects the statement it prepared
2413/// for that form and binds the predicate's record through the form's
2414/// binder. Nothing is read and nothing is allocated here. The query
2415/// index wraps modulo the facet's predicates.
2416///
2417/// Signature: `predicate_at(forms: forms, index: u64) -> (fragment)`
2418#[crate::polydat_node(category = RealData)]
2419fn predicate_at(forms: dv::Shared<dv::PredicateForms>, index: u64) -> dv::PredicateFragment {
2420    let count = forms.census.count();
2421    assert!(
2422        count > 0,
2423        "predicate_at: '{}' has no predicates",
2424        forms.origin
2425    );
2426    let ordinal = index % count;
2427    let form = forms
2428        .census
2429        .form_at(ordinal)
2430        .expect("an ordinal below the census's count has a form");
2431    dv::PredicateFragment::new(forms.0, form as u32, ordinal)
2432}
2433
2434/// The form of a dataset's metadata records: the layout that names and
2435/// types a record's fields, with the binder that reads every field in
2436/// layout order. A record facet has this one form. A constant.
2437///
2438/// Signature: `record_forms(handle) -> (forms)`
2439#[crate::polydat_node(category = RealData)]
2440fn record_forms(handle: Facet<MetadataContentFacet>) -> dv::Shared<dv::RecordForms> {
2441    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2442    dv::Shared(metadata_records(h.as_ref(), "record_forms").forms.clone())
2443}
2444
2445/// The metadata record of base vector `index`, as structure: its
2446/// ordinal among the records `forms` describes. A host binds the
2447/// record's fields through `forms.binder` to the statement it prepared
2448/// from the layout. Nothing is read and nothing is allocated here. The
2449/// index wraps modulo the record count.
2450///
2451/// Signature: `record_at(forms: forms, index: u64) -> (fragment)`
2452#[crate::polydat_node(category = RealData)]
2453fn record_at(forms: dv::Shared<dv::RecordForms>, index: u64) -> dv::RecordFragment {
2454    let count = forms
2455        .records
2456        .count()
2457        .unwrap_or_else(|e| panic!("record_at: '{}': {e}", forms.origin));
2458    assert!(count > 0, "record_at: '{}' has no records", forms.origin);
2459    dv::RecordFragment::new(forms.0, index % count)
2460}
2461
2462/// The names of the fields of a dataset's metadata records, in layout
2463/// order, comma-joined: what a column list or an iteration over the
2464/// fields takes. A constant.
2465///
2466/// Signature: `record_field_names(handle) -> (str)`
2467#[crate::polydat_node(category = RealData)]
2468fn record_field_names(handle: Facet<MetadataContentFacet>) -> String {
2469    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2470    metadata_records(h.as_ref(), "record_field_names")
2471        .forms
2472        .layout
2473        .names()
2474        .join(",")
2475}
2476
2477/// The metadata fields a dataset's predicates constrain, sorted and
2478/// comma-joined: the fields a target indexes to serve them. A
2479/// constant.
2480///
2481/// Signature: `predicate_field_names(handle) -> (str)`
2482#[crate::polydat_node(category = RealData)]
2483fn predicate_field_names(handle: Facet<MetadataPredicatesFacet>) -> String {
2484    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
2485    let forms = predicate_records(h.as_ref(), "predicate_field_names");
2486    forms
2487        .census
2488        .fields()
2489        .into_iter()
2490        .collect::<Vec<_>>()
2491        .join(",")
2492}
2493
2494/// The strata of a predicate facet, for the node `who`; refused when
2495/// the facet publishes none.
2496fn predicate_strata<'a>(
2497    forms: &'a dv::PredicateForms,
2498    who: &str,
2499) -> &'a vectordata::predicate_forms::PredicateStrata {
2500    forms.census.strata().unwrap_or_else(|| {
2501        panic!(
2502            "{who}: the predicates of '{}' publish no family or selectivity",
2503            forms.origin
2504        )
2505    })
2506}
2507
2508/// The distinct families of a dataset's predicates, sorted and
2509/// comma-joined, or empty when the facet publishes none. A constant.
2510///
2511/// Signature: `predicate_families(handle) -> (str)`
2512#[crate::polydat_node(category = RealData)]
2513fn predicate_families(handle: Facet<MetadataPredicatesFacet>) -> String {
2514    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
2515    let forms = predicate_records(h.as_ref(), "predicate_families");
2516    forms
2517        .census
2518        .strata()
2519        .map_or_else(String::new, |strata| strata.families().join(","))
2520}
2521
2522/// The distinct selectivity bands of a dataset's predicates, widest
2523/// first and comma-joined, or empty when the facet publishes none. A
2524/// constant.
2525///
2526/// Signature: `predicate_bands(handle) -> (str)`
2527#[crate::polydat_node(category = RealData)]
2528fn predicate_bands(handle: Facet<MetadataPredicatesFacet>) -> String {
2529    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
2530    let forms = predicate_records(h.as_ref(), "predicate_bands");
2531    forms
2532        .census
2533        .strata()
2534        .map_or_else(String::new, |strata| strata.bands().join(","))
2535}
2536
2537/// The family of the predicate of query `index`, one of
2538/// `predicate_families`. Refused when the facet publishes no strata.
2539/// The query index wraps modulo the facet's predicates.
2540///
2541/// Signature: `predicate_family_at(handle, index: u64) -> (str)`
2542#[crate::polydat_node(category = RealData)]
2543fn predicate_family_at(handle: Facet<MetadataPredicatesFacet>, index: u64) -> String {
2544    let who = "predicate_family_at";
2545    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
2546    let forms = predicate_records(h.as_ref(), who);
2547    let ordinal = index % forms.census.count().max(1);
2548    predicate_strata(forms, who)
2549        .family_at(ordinal)
2550        .unwrap_or_else(|| panic!("{who}: '{}' has no predicate {ordinal}", forms.origin))
2551        .to_string()
2552}
2553
2554/// The selectivity band of the predicate of query `index`, one of
2555/// `predicate_bands`, or empty for a predicate whose recorded
2556/// selectivity no band is read from. Refused when the facet publishes
2557/// no strata. The query index wraps modulo the facet's predicates.
2558///
2559/// Signature: `predicate_band_at(handle, index: u64) -> (str)`
2560#[crate::polydat_node(category = RealData)]
2561fn predicate_band_at(handle: Facet<MetadataPredicatesFacet>, index: u64) -> String {
2562    let who = "predicate_band_at";
2563    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
2564    let forms = predicate_records(h.as_ref(), who);
2565    let ordinal = index % forms.census.count().max(1);
2566    predicate_strata(forms, who)
2567        .band_at(ordinal)
2568        .unwrap_or_default()
2569        .to_string()
2570}
2571
2572// =================================================================
2573// Dataset records as text, in a packaged vernacular
2574// =================================================================
2575//
2576// The other pathway: a record or a predicate rendered as text by one
2577// of the vernaculars vectordata packages, named by the program. The
2578// result is a `str` like any other. It is the form for a statement
2579// that is not prepared and for display, and it carries no structure.
2580
2581/// The packaged renderer `vernacular`, for the node `who`; an unknown
2582/// name is refused with the names that exist.
2583fn vernacular_codec(
2584    vernacular: &str,
2585    who: &str,
2586) -> Box<dyn vectordata::records::RecordCodec<Out = String>> {
2587    vectordata::records::codec_by_name(vernacular).unwrap_or_else(|| {
2588        panic!(
2589            "{who}: no packaged vernacular is named `{vernacular}`; the names are {}",
2590            vectordata::records::codec_names().join(", ")
2591        )
2592    })
2593}
2594
2595/// The metadata record of base vector `index`, rendered as text by the
2596/// packaged vernacular `vernacular`. An unknown vernacular is refused
2597/// with the names that exist. The index wraps modulo the record count.
2598///
2599/// Signature: `record_text_at(handle, vernacular: str, index: u64) -> (str)`
2600#[crate::polydat_node(category = RealData)]
2601fn record_text_at(handle: Facet<MetadataContentFacet>, vernacular: &str, index: u64) -> String {
2602    let who = "record_text_at";
2603    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2604    let records = metadata_records(h.as_ref(), who);
2605    let origin = &records.forms.origin;
2606    assert!(records.count > 0, "{who}: '{origin}' has no records");
2607    let ordinal = index % records.count;
2608    records
2609        .forms
2610        .records
2611        .decode(vernacular_codec(vernacular, who))
2612        .get(ordinal)
2613        .unwrap_or_else(|e| panic!("{who}: record {ordinal} of '{origin}': {e}"))
2614}
2615
2616/// The predicate of query `index`, rendered as text by the packaged
2617/// vernacular `vernacular`, comparands inline. An unknown vernacular is
2618/// refused with the names that exist. The query index wraps modulo the
2619/// facet's predicates.
2620///
2621/// Signature: `predicate_text_at(handle, vernacular: str, index: u64) -> (str)`
2622#[crate::polydat_node(category = RealData)]
2623fn predicate_text_at(
2624    handle: Facet<MetadataPredicatesFacet>,
2625    vernacular: &str,
2626    index: u64,
2627) -> String {
2628    let who = "predicate_text_at";
2629    let h = handle.resolve_facet(MetadataPredicatesFacet::FACET);
2630    let forms = predicate_records(h.as_ref(), who);
2631    let origin = &forms.origin;
2632    let count = forms.census.count();
2633    assert!(count > 0, "{who}: '{origin}' has no predicates");
2634    let ordinal = index % count;
2635    forms
2636        .predicates
2637        .decode(vernacular_codec(vernacular, who))
2638        .get(ordinal)
2639        .unwrap_or_else(|e| panic!("{who}: predicate {ordinal} of '{origin}': {e}"))
2640}
2641
2642/// The layout of a dataset's metadata records, rendered as text by the
2643/// packaged vernacular `vernacular`: the text one record stands for,
2644/// such as a schema's column definitions, before any record is read. A
2645/// constant. An unknown vernacular is refused with the names that
2646/// exist.
2647///
2648/// Signature: `record_layout_text(handle, vernacular: str) -> (str)`
2649#[crate::polydat_node(category = RealData)]
2650fn record_layout_text(handle: Facet<MetadataContentFacet>, vernacular: &str) -> String {
2651    use vectordata::records::RecordCodec;
2652    let who = "record_layout_text";
2653    let h = handle.resolve_facet(MetadataContentFacet::FACET);
2654    let records = metadata_records(h.as_ref(), who);
2655    let exemplar = vectordata::formats::anode::encode(&records.forms.layout.exemplar());
2656    vernacular_codec(vernacular, who)
2657        .decode(&exemplar)
2658        .unwrap_or_else(|e| panic!("{who}: the layout of '{}': {e}", records.forms.origin))
2659}
2660
2661/// Access a metadata value per base ordinal. Expects a Generic
2662/// handle opened against the `metadata_content` facet.
2663///
2664/// Signature: `metadata_value_at(handle, index: u64) -> (str)`
2665#[crate::polydat_node(category = RealData)]
2666fn metadata_value_at(handle: Facet<MetadataContentFacet>, index: u64) -> String {
2667    generic_str_typed(
2668        handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
2669        index as usize,
2670    )
2671}
2672
2673/// Access a predicate value per query ordinal. Expects a Generic
2674/// handle opened against the `metadata_predicates` facet.
2675///
2676/// Signature: `predicate_value_at(handle, index: u64) -> (str)`
2677#[crate::polydat_node(category = RealData)]
2678fn predicate_value_at(handle: Facet<MetadataPredicatesFacet>, index: u64) -> String {
2679    generic_str_typed(
2680        handle
2681            .resolve_facet(MetadataPredicatesFacet::FACET)
2682            .as_ref(),
2683        index as usize,
2684    )
2685}
2686
2687/// Count of metadata content records. Expects a Generic handle.
2688///
2689/// Signature: `metadata_content_count(handle) -> (u64)`
2690#[crate::polydat_node(category = RealData)]
2691fn metadata_content_count(handle: Facet<MetadataContentFacet>) -> u64 {
2692    match handle.resolve_facet(MetadataContentFacet::FACET).as_ref() {
2693        DatasetHandle::Generic(d) => d.count as u64,
2694        DatasetHandle::Records(d) => d.count,
2695        _ => 0,
2696    }
2697}
2698
2699// ── Counting a facet's matching records ─────────────────────────────
2700
2701/// How many scalars of a Generic facet equal `value`.
2702///
2703/// A linear read of the facet, which is what the question is: the
2704/// reader holds the values and nothing indexes them by content. Both
2705/// callers below pass a handle and a value that are fixed for a scope,
2706/// so the count is computed once at scope init and reused, the way the
2707/// facet itself is loaded once.
2708/// How many scalars of a Generic facet equal `value`.
2709fn generic_count_typed(h: &DatasetHandle, value: i64) -> u64 {
2710    match h {
2711        DatasetHandle::Generic(d) => {
2712            (0..d.count).filter(|i| d.get_scalar(*i) == value).count() as u64
2713        }
2714        DatasetHandle::Records(_) => panic!("{}", RECORDS_NOT_SCALARS),
2715        DatasetHandle::Predicates(_) => panic!("{}", PREDICATES_NOT_SCALARS),
2716        _ => 0,
2717    }
2718}
2719
2720/// How many records carry the metadata value `value`.
2721///
2722/// The per-label cardinality the recall audit compares against a
2723/// profile's declared count: not a counter advancing as records are
2724/// visited, but a property of the facet and the value, so it
2725/// replays and agrees on every engine and every fiber
2726/// (docs/design/runtime_model.md §9.1).
2727///
2728/// `metadata_value_at(handle, i)` formats the same scalar as text,
2729/// so a host comparing labels as strings and one counting them
2730/// here are reading one facet.
2731#[crate::polydat_node(category = RealData)]
2732fn metadata_count_of(handle: Facet<MetadataContentFacet>, value: i64) -> u64 {
2733    generic_count_typed(
2734        handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
2735        value,
2736    )
2737}
2738
2739/// How many queries carry the predicate value `value`.
2740///
2741/// The denominator of a per-predicate recall figure, and the bound
2742/// on a rank within one predicate's queries.
2743///
2744/// Signature: `predicate_count_of(handle, value: i64) -> (u64)`
2745#[crate::polydat_node(category = RealData)]
2746fn predicate_count_of(handle: Facet<MetadataPredicatesFacet>, value: i64) -> u64 {
2747    generic_count_typed(
2748        handle
2749            .resolve_facet(MetadataPredicatesFacet::FACET)
2750            .as_ref(),
2751        value,
2752    )
2753}
2754
2755// ── Listing a facet's matching records ──────────────────────────────
2756
2757/// The indices of a Generic facet whose scalar equals `value`,
2758/// ascending.
2759///
2760/// The same linear read as [`generic_count_typed`], keeping the
2761/// indices it counts, so a list's length is the matching count, and
2762/// the list is computed once at scope init and reused the same way.
2763/// An index past `i32::MAX` is a facet larger than a `vec_i32`
2764/// addresses and fails by name rather than wrapping.
2765fn generic_ordinals_typed(node: &str, h: &DatasetHandle, value: i64) -> Vec<i32> {
2766    match h {
2767        DatasetHandle::Generic(d) => (0..d.count)
2768            .filter(|i| d.get_scalar(*i) == value)
2769            .map(|i| {
2770                i32::try_from(i)
2771                    .unwrap_or_else(|_| panic!("{node}: ordinal {i} is outside the i32 range"))
2772            })
2773            .collect(),
2774        DatasetHandle::Records(_) => panic!("{node}: {RECORDS_NOT_SCALARS}"),
2775        DatasetHandle::Predicates(_) => panic!("{node}: {PREDICATES_NOT_SCALARS}"),
2776        _ => Vec::new(),
2777    }
2778}
2779
2780/// The base ordinals whose metadata value is `value`, ascending.
2781///
2782/// The list whose length `metadata_count_of(handle, value)` is. The
2783/// record at local row `l` among those carrying `value` has global
2784/// ordinal `vec_at_i32(metadata_ordinals_of(handle, value), l)`
2785/// (docs/design/runtime_model.md §9.1).
2786#[crate::polydat_node(category = RealData)]
2787fn metadata_ordinals_of(handle: Facet<MetadataContentFacet>, value: i64) -> Vec<i32> {
2788    generic_ordinals_typed(
2789        "metadata_ordinals_of",
2790        handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
2791        value,
2792    )
2793}
2794
2795/// The query ordinals whose predicate value is `value`, ascending.
2796///
2797/// The list whose length `predicate_count_of(handle, value)` is.
2798#[crate::polydat_node(category = RealData)]
2799fn predicate_ordinals_of(handle: Facet<MetadataPredicatesFacet>, value: i64) -> Vec<i32> {
2800    generic_ordinals_typed(
2801        "predicate_ordinals_of",
2802        handle
2803            .resolve_facet(MetadataPredicatesFacet::FACET)
2804            .as_ref(),
2805        value,
2806    )
2807}
2808
2809// =========================================================================
2810// Cursor-sugar handlers
2811// =========================================================================
2812//
2813// Three sugar forms recognized by this module — none of them
2814// known to the core compiler, which dispatches generically
2815// through `dsl::cursor_sugar`. Each desugars to a synthetic
2816// `range(0, vector_count|query_count(...))` constructor plus
2817// auxiliary bindings:
2818//
2819//   - `__<cursor>_prebuffer := dataset_prebuffer("ds:profile")`
2820//     loaded once at init time so cycle-time accessor calls hit
2821//     prefetched memory.
2822//   - `<cursor>__vector := vector_at("ds:profile", <cursor>__ordinal)`
2823//     (or `query_vector_at` for the query
2824//     facet) — published as the cursor's `vector` projection so
2825//     workloads can reference `<cursor>.vector`.
2826//
2827// Forms:
2828//   - `vectordata_source(dataset, profile, facet)` — explicit facet
2829//   - `vectordata_base(dataset, profile)`           — facet = "base"
2830//   - `vectordata_query(dataset, profile)`          — facet = "query"
2831//
2832// Facet-specific projections like `metadata` / `ground_truth` /
2833// `predicate` stay explicit (the user writes
2834// `meta := metadata_value_at(<cursor>.ordinal, "ds:profile")` by
2835// hand) because their existence is dataset-conditional — not
2836// every dataset declares a metadata column or a predicate facet.
2837
2838#[cfg(feature = "vectordata")]
2839fn vectordata_sugar(
2840    source_name: &str,
2841    constructor: &crate::dsl::ast::Expr,
2842) -> Result<Option<crate::dsl::cursor_sugar::CursorSugar>, String> {
2843    use crate::dsl::ast::{Arg, CallExpr, Expr};
2844    use crate::dsl::compile::positional_str_lit;
2845    use crate::dsl::cursor_sugar::{AuxBinding, CursorSugar};
2846
2847    let Expr::Call(call) = constructor else {
2848        return Ok(None);
2849    };
2850
2851    let (dataset, profile, facet) = match call.func.as_str() {
2852        "vectordata_source" => {
2853            let d = positional_str_lit(call.args.first()).ok_or_else(|| format!(
2854                "cursor '{source_name}': vectordata_source(dataset, profile, facet) — first arg must be a string literal"
2855            ))?;
2856            let p = positional_str_lit(call.args.get(1)).ok_or_else(|| format!(
2857                "cursor '{source_name}': vectordata_source(dataset, profile, facet) — second arg must be a string literal"
2858            ))?;
2859            let f = positional_str_lit(call.args.get(2)).ok_or_else(|| format!(
2860                "cursor '{source_name}': vectordata_source(dataset, profile, facet) — third arg must be a string literal (\"base\" or \"query\")"
2861            ))?;
2862            (d, p, f)
2863        }
2864        "vectordata_base" | "vectordata_query" => {
2865            let f = call.func.strip_prefix("vectordata_").unwrap().to_string();
2866            let d = positional_str_lit(call.args.first()).ok_or_else(|| format!(
2867                "cursor '{source_name}': {}(dataset, profile) — first arg must be a string literal",
2868                call.func,
2869            ))?;
2870            let p = positional_str_lit(call.args.get(1)).ok_or_else(|| format!(
2871                "cursor '{source_name}': {}(dataset, profile) — second arg must be a string literal",
2872                call.func,
2873            ))?;
2874            (d, p, f)
2875        }
2876        _ => return Ok(None),
2877    };
2878
2879    if facet != "base" && facet != "query" {
2880        return Err(format!(
2881            "cursor '{source_name}': vectordata facet must be \"base\" or \"query\", got \"{facet}\""
2882        ));
2883    }
2884    let (count_func, vector_func) = match facet.as_str() {
2885        "base" => ("vector_count", "vector_at"),
2886        "query" => ("query_count", "query_vector_at"),
2887        _ => unreachable!(),
2888    };
2889
2890    let combined = format!("{dataset}:{profile}");
2891    let span = call.span;
2892    let lit = |s: String| Expr::StringLit(s, span);
2893    let positional = |e: Expr| Arg::Positional(e);
2894
2895    let effective_constructor = Expr::Call(CallExpr {
2896        func: "range".into(),
2897        args: vec![
2898            positional(Expr::IntLit(0, span)),
2899            positional(Expr::Call(CallExpr {
2900                func: count_func.into(),
2901                args: vec![positional(lit(combined.clone()))],
2902                span,
2903            })),
2904        ],
2905        span,
2906    });
2907
2908    let prebuffer_binding = AuxBinding {
2909        name: format!("__{source_name}_prebuffer"),
2910        value: Expr::Call(CallExpr {
2911            func: "dataset_prebuffer".into(),
2912            args: vec![positional(lit(combined.clone()))],
2913            span,
2914        }),
2915        projection: None,
2916    };
2917
2918    // Cursor sugar emits the call in (handle, index) order. The
2919    // combined source string auto-promotes to the right facet handle
2920    // through the wire's default resolver (library_catalog.md
2921    // "Shapes", `Resolved<R, T>`).
2922    let vector_binding = AuxBinding {
2923        name: format!("{source_name}__vector"),
2924        value: Expr::Call(CallExpr {
2925            func: vector_func.into(),
2926            args: vec![
2927                positional(lit(combined)),
2928                positional(Expr::Ident(format!("{source_name}__ordinal"), span)),
2929            ],
2930            span,
2931        }),
2932        projection: Some(("vector".into(), crate::ast::PortType::VecF32)),
2933    };
2934
2935    Ok(Some(CursorSugar {
2936        effective_constructor,
2937        aux_bindings: vec![prebuffer_binding, vector_binding],
2938    }))
2939}
2940
2941#[cfg(feature = "vectordata")]
2942inventory::submit! {
2943    crate::dsl::cursor_sugar::CursorSugarRegistration {
2944        handler: vectordata_sugar,
2945        name: "vectordata",
2946    }
2947}
2948
2949#[cfg(test)]
2950mod count_of_tests {
2951    use super::*;
2952    use crate::ast::{PolydatNode, PortType, Slot};
2953    use crate::dsl::registry::DefaultResolver;
2954
2955    /// The ports the compiler types a call against: a handle and a
2956    /// signed value in, a count out. The value is `i64` because that is
2957    /// what the facet stores; a caller with a literal reaches it
2958    /// through `to_i64`, since an integer literal is a `u64` and the
2959    /// adapter catalog will not heal that pair.
2960    #[test]
2961    fn the_count_of_nodes_take_a_handle_and_a_signed_value() {
2962        for node in [
2963            Box::new(MetadataCountOf::new()) as Box<dyn PolydatNode>,
2964            Box::new(PredicateCountOf::new()) as Box<dyn PolydatNode>,
2965        ] {
2966            let meta = node.meta();
2967            assert_eq!(meta.outs.len(), 1);
2968            assert_eq!(meta.outs[0].typ, PortType::U64, "{}", meta.name);
2969            assert_eq!(meta.ins.len(), 2, "{}", meta.name);
2970            let Slot::Wire(handle) = &meta.ins[0] else {
2971                panic!("{}: the first input is a wire", meta.name)
2972            };
2973            let Slot::Wire(value) = &meta.ins[1] else {
2974                panic!("{}: the second input is a wire", meta.name)
2975            };
2976            assert_eq!(handle.typ, PortType::Handle, "{}", meta.name);
2977            assert_eq!(value.typ, PortType::I64, "{}", meta.name);
2978        }
2979    }
2980
2981    /// The ordinals nodes take the same handle and value as the counts
2982    /// and give a `vec_i32` of ordinals.
2983    #[test]
2984    fn the_ordinals_of_nodes_take_what_the_counts_take() {
2985        for node in [
2986            Box::new(MetadataOrdinalsOf::new()) as Box<dyn PolydatNode>,
2987            Box::new(PredicateOrdinalsOf::new()) as Box<dyn PolydatNode>,
2988        ] {
2989            let meta = node.meta();
2990            assert_eq!(meta.outs.len(), 1);
2991            assert_eq!(meta.outs[0].typ, PortType::VecI32, "{}", meta.name);
2992            let types: Vec<PortType> = meta
2993                .ins
2994                .iter()
2995                .map(|s| match s {
2996                    Slot::Wire(w) => w.typ,
2997                    _ => panic!("{}: every input is a wire", meta.name),
2998                })
2999                .collect();
3000            assert_eq!(types, [PortType::Handle, PortType::I64], "{}", meta.name);
3001        }
3002    }
3003
3004    /// A handle of the wrong shape answers zero rather than failing.
3005    /// The facets these read are scalar ones; a caller that opened a
3006    /// vector facet by mistake gets a count of nothing, which is the
3007    /// same answer the facet's own readers give for a shape they do not
3008    /// hold.
3009    #[test]
3010    fn a_handle_of_another_shape_counts_nothing() {
3011        let group_shaped = DatasetHandle::Prebuffered {
3012            group: match load_dataset_group("nonexistent:profile") {
3013                Ok(g) => g,
3014                // No dataset available in this environment: the
3015                // fallback is still exercised through the match arm
3016                // below, which is what this test is about.
3017                Err(_) => return,
3018            },
3019            source: "nonexistent:profile".into(),
3020        };
3021        assert_eq!(generic_count_typed(&group_shaped, 1), 0);
3022        assert!(generic_ordinals_typed("test", &group_shaped, 1).is_empty());
3023    }
3024
3025    /// Both names resolve through the registry and carry a default
3026    /// resolver, so `metadata_count_of("ds:profile", v)` promotes the
3027    /// source string to the right facet the way its neighbours do.
3028    #[test]
3029    fn both_names_are_registered_with_a_facet_resolver() {
3030        for (name, facet) in [
3031            ("metadata_count_of", "metadata_content"),
3032            ("predicate_count_of", "metadata_predicates"),
3033            ("metadata_ordinals_of", "metadata_content"),
3034            ("predicate_ordinals_of", "metadata_predicates"),
3035        ] {
3036            let sig = crate::dsl::registry::lookup(name)
3037                .unwrap_or_else(|| panic!("{name} is registered"));
3038            assert_eq!(sig.outputs, 1, "{name}");
3039            assert_eq!(sig.params.len(), 2, "{name}");
3040            // The facet comes from the handle argument's type, so
3041            // this is the resolver the macro read off `Facet<_>`.
3042            match sig.default_resolver {
3043                Some(DefaultResolver::Facet(f)) => assert_eq!(f, facet, "{name}"),
3044                other => panic!("{name}: expected a facet resolver, got {other:?}"),
3045            }
3046        }
3047    }
3048}