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
41use vectordata::catalog::{Catalog, CatalogSources};
42use vectordata::fetch::{FetchRequest, LogMeter};
43use vectordata::{TestDataGroup, TestDataView, TestDataViewExt, VectorReader, VvecReader};
44
45/// Global cache for loaded dataset groups keyed by source string.
46/// Ensures each dataset is loaded exactly once regardless of how many
47/// node functions reference it. The race-free init pattern lives in
48/// [`crate::library::support::cache::OnceCache`].
49static DATASET_CACHE: LazyLock<OnceCache<String, Arc<TestDataGroup>>> =
50 LazyLock::new(OnceCache::new);
51
52/// Type-erased facet cache: (source, profile, facet) → Arc<dyn Any + Send + Sync>.
53/// Ensures each reader (of any element type) is opened exactly once
54/// and shared across all node instances that reference the same data.
55/// The concrete type inside is `Arc<UniformDataset<T>>` or `Arc<Ivvec32Dataset>`
56/// or `Arc<GenericFacetDataset>`. The race-free init pattern lives
57/// in [`OnceCache`].
58type FacetCache = OnceCache<(String, String, String), Arc<dyn std::any::Any + Send + Sync>>;
59static FACET_CACHE: LazyLock<FacetCache> = LazyLock::new(OnceCache::new);
60
61/// Whole-dataset prebuffer cache keyed by source string. Wraps
62/// [`do_dataset_prebuffer_inner`] so N fibers all calling
63/// `dataset_prebuffer("ds:profile")` at init time serialize on
64/// one OnceLock and share the resulting handle. Without this,
65/// each fiber's own kernel-init pass invokes the real prebuffer
66/// body and they all race into the manifest walk + per-facet
67/// download — exactly the thundering herd we hit. The inner
68/// caches (DATASET_CACHE, FACET_CACHE) only protect the
69/// group-resolve and per-facet-reader steps, not the outer
70/// "walk every facet and pull all chunks" work.
71static PREBUFFER_CACHE: LazyLock<OnceCache<String, Arc<DatasetHandle>>> =
72 LazyLock::new(OnceCache::new);
73
74// =================================================================
75// Dataset resolution — catalog-aware, cache-aware
76// =================================================================
77
78/// Parse a source specifier into (dataset_name, profile_name).
79///
80/// Supports `"dataset:profile"` syntax. If no colon is present,
81/// the profile defaults to `"default"`.
82fn parse_source_specifier(source: &str) -> (&str, &str) {
83 // Don't split on colon in URLs
84 if source.starts_with("http://") || source.starts_with("https://") {
85 return (source, "default");
86 }
87 if let Some(pos) = source.find(':') {
88 (&source[..pos], &source[pos + 1..])
89 } else {
90 (source, "default")
91 }
92}
93
94/// Run a synchronous body that may internally drive
95/// `reqwest::blocking` (and thus spin up a private tokio
96/// runtime per HTTP request). If we're sitting on an outer
97/// async runtime — we are, in every per-cycle and per-phase
98/// path — the inner runtime panics on drop with "Cannot drop a
99/// runtime in a context where blocking is not allowed".
100/// `block_in_place` parks the outer multi-thread worker for
101/// the duration of the call so the inner runtime sees a
102/// non-async drop context. Falls back to a direct call when no
103/// runtime is current (e.g. unit tests). Single helper used by
104/// all three vectordata-facing entry points
105/// ([`load_dataset_group`], [`load_uniform_facet`],
106/// [`GenericFacetDataset::load`]).
107fn run_blocking_io<R>(body: impl FnOnce() -> R) -> R {
108 // tokio rides the `vectordata` feature: without the crate there is
109 // no HTTP client to park a worker for.
110 #[cfg(feature = "vectordata")]
111 if tokio::runtime::Handle::try_current().is_ok() {
112 return tokio::task::block_in_place(body);
113 }
114 body()
115}
116
117/// Load a dataset group by name.
118///
119/// Uses the vectordata catalog API: `catalog.open(name)` handles
120/// catalog discovery, cache resolution, and download transparently.
121pub(crate) fn load_dataset_group(source: &str) -> Result<Arc<TestDataGroup>, String> {
122 let (dataset_name, _profile) = parse_source_specifier(source);
123 // Both keys (dataset name and full source spec) point at the
124 // same `Arc<TestDataGroup>`; the `OnceCache` slot for one is
125 // primed by the other on first hit.
126 DATASET_CACHE.get_or_init(dataset_name.to_string(), || {
127 run_blocking_io(|| {
128 let catalog = Catalog::of(&CatalogSources::new().configure_default());
129 catalog
130 .open(dataset_name)
131 .map(Arc::new)
132 .map_err(|e| format!("failed to load dataset '{dataset_name}': {e}"))
133 })
134 })
135}
136
137// =================================================================
138// Dataset handles — loaded once at node construction, shared via Arc
139// =================================================================
140
141/// Generic handle to a loaded uniform vector facet. Thread-safe, random-access.
142/// Supports any element type provided by the vectordata API (f32, f64,
143/// i32, i16, u8, i8, u16, u32, u64, i64, f16).
144pub(crate) struct UniformDataset<T: Send + Sync + 'static> {
145 reader: Arc<dyn VectorReader<T>>,
146 count: usize,
147 dim: usize,
148}
149
150/// Cache-aware loader for uniform vector facets.
151/// Returns a shared `Arc<UniformDataset<T>>`, creating and caching it
152/// on first access. Subsequent loads for the same (source, profile, facet)
153/// return the cached instance.
154fn load_uniform_facet<T: Send + Sync + 'static>(
155 source: &str,
156 profile: &str,
157 facet: &str,
158 open_fn: impl FnOnce(
159 &dyn TestDataView,
160 ) -> std::result::Result<Arc<dyn VectorReader<T>>, vectordata::Error>,
161) -> Result<Arc<UniformDataset<T>>, String> {
162 let key = (source.to_string(), profile.to_string(), facet.to_string());
163 let any = FACET_CACHE.get_or_init(key, || {
164 let group = load_dataset_group(source)?;
165 let view = group
166 .profile(profile)
167 .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
168 // Audit: log the open *before* `open_fn` runs so the
169 // line appears even if the open errors. Inside
170 // `get_or_init`'s closure, this fires exactly once per
171 // (source, profile, facet) — the prior shape logged
172 // once per concurrent miss (storms of N for N fibers).
173 crate::library::support::audit::record_opened(
174 parse_source_specifier(source).0,
175 profile,
176 facet,
177 "uniform",
178 );
179 let reader = run_blocking_io(|| open_fn(view.as_ref()))
180 .map_err(|e| format!("failed to access {facet} from '{source}': {e}"))?;
181 let count = reader.count();
182 let dim = reader.dim();
183 let arc: Arc<UniformDataset<T>> = Arc::new(UniformDataset { reader, count, dim });
184 Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
185 })?;
186 any.downcast::<UniformDataset<T>>().map_err(|_| {
187 format!(
188 "facet cache type mismatch for '{source}:{profile}/{facet}' — \
189 this should be impossible; please file a bug."
190 )
191 })
192}
193
194// Type aliases for backward compatibility
195type F32Dataset = UniformDataset<f32>;
196type I32Dataset = UniformDataset<i32>;
197
198impl F32Dataset {
199 fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
200 let facet_name = facet.to_string();
201 load_uniform_facet(source, profile, facet, move |view| {
202 match facet_name.as_str() {
203 "base" => view.base_vectors_as(),
204 "query" => view.query_vectors_as(),
205 "neighbor_distances" => view.neighbor_distances_as(),
206 "filtered_neighbor_distances" => view.prefiltered_neighbor_distances_as(),
207 other => Err(vectordata::Error::MissingFacet(format!(
208 "unknown f32 facet: '{other}'"
209 ))),
210 }
211 })
212 }
213}
214
215impl I32Dataset {
216 fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
217 let facet_name = facet.to_string();
218 load_uniform_facet(source, profile, facet, move |view| {
219 match facet_name.as_str() {
220 "neighbor_indices" => view.neighbor_indices_as(),
221 "filtered_neighbor_indices" => view.prefiltered_neighbor_indices_as(),
222 other => Err(vectordata::Error::MissingFacet(format!(
223 "unknown i32 facet: '{other}'"
224 ))),
225 }
226 })
227 }
228}
229
230// =================================================================
231// Dataset handle — typed enum wrapping all per-facet dataset shapes
232// =================================================================
233//
234// Per type_system.md §1.8: `dataset_open(source, facet)` is
235// the resolver node; per-cycle accessors take a handle wire and
236// downcast to the concrete variant they expect. A single Value
237// variant `Value::Handle(Arc<dyn Any>)` carries any of the
238// concrete shapes — the enum below is what's actually inside the
239// Arc, and accessors `match` on the variant.
240//
241// One handle may be opened against multiple facets at the
242// `dataset_open` boundary (the user calls `dataset_open(spec,
243// "base")` vs. `dataset_open(spec, "query")` and gets two
244// distinct handles); the downstream accessor matches on whatever
245// variant came back.
246
247/// Typed wrapper around a resolved dataset facet or group. Held
248/// inside `Value::Handle` as `Arc<DatasetHandle>` and downcast by
249/// accessor nodes via [`Value::as_handle::<DatasetHandle>()`].
250/// Cloning a `Value::Handle` is one `Arc::clone` — one atomic
251/// increment, no allocation — which is the design contract this
252/// enum exists to satisfy.
253#[derive(Clone)]
254pub(crate) enum DatasetHandle {
255 /// Uniform `f32` vector facet (base, query, neighbor_distances,
256 /// filtered_neighbor_distances).
257 F32(Arc<F32Dataset>),
258 /// Uniform `i32` vector facet (neighbor_indices, filtered_neighbor_indices).
259 I32(Arc<I32Dataset>),
260 /// Variable-length `i32` facet (metadata_results).
261 Ivvec32(Arc<Ivvec32Dataset>),
262 /// Type-erased generic-typed scalar facet (metadata_content,
263 /// metadata_predicates, ...).
264 Generic(Arc<GenericFacetDataset>),
265 /// Dataset-group handle — used by group-level metadata
266 /// accessors (`dataset_profile_count`, `dataset_facets`,
267 /// `dataset_distance_function`, ...) that operate on the
268 /// `TestDataGroup` before any profile/facet is chosen.
269 Group(Arc<TestDataGroup>),
270 /// Prebuffered-and-resident dataset, returned by
271 /// `dataset_prebuffer(source)`. Carries both the group and
272 /// the source spec: a facet accessor opens its facet from
273 /// `<source>:<profile>` (`query_vector_at(prebuffered, q)`
274 /// reads the `query` facet), and a group accessor reads the
275 /// group. [`DatasetHandle::resolve_facet`] and
276 /// [`DatasetHandle::resolve_group`] are those two readings.
277 ///
278 /// The `group` field also keeps the prebuffered `TestDataGroup`
279 /// alive for the duration of the handle — vectordata's
280 /// internal storage cache is keyed off the group instance,
281 /// so dropping the group prematurely would force per-facet
282 /// readers to re-open against transport.
283 Prebuffered {
284 group: Arc<TestDataGroup>,
285 source: String,
286 },
287}
288
289impl DatasetHandle {
290 fn open(source: &str, facet: &str) -> Result<Self, String> {
291 let (_, profile) = parse_source_specifier(source);
292 match facet {
293 "base" | "query" | "neighbor_distances" | "filtered_neighbor_distances" => {
294 F32Dataset::load(source, profile, facet).map(DatasetHandle::F32)
295 }
296 "neighbor_indices" | "filtered_neighbor_indices" => {
297 I32Dataset::load(source, profile, facet).map(DatasetHandle::I32)
298 }
299 "metadata_results" => Ivvec32Dataset::load(source, profile).map(DatasetHandle::Ivvec32),
300 // Anything else routes through GenericFacetDataset (typed
301 // scalar reader), which covers metadata_content,
302 // metadata_predicates, and any future scalar facet.
303 _ => GenericFacetDataset::load(source, profile, facet).map(DatasetHandle::Generic),
304 }
305 }
306
307 fn open_group(source: &str) -> Result<Self, String> {
308 load_dataset_group(source).map(DatasetHandle::Group)
309 }
310}
311
312/// `dataset_open(source: str, facet: str) -> Handle`
313///
314/// The single resolver node. Provenance follows its two wire
315/// inputs; when both are scope-extern constants (the iter-var
316/// case), this evaluates exactly once at iteration entry and
317/// stays cached for every cycle in that iteration. When source
318/// or facet is cycle-time, it re-evaluates accordingly.
319///
320/// All per-cycle accessors take the resulting handle on a wire
321/// — the catalog/HTTP/mmap path is never on the cycle hot path.
322///
323/// A resolve failure panics with the underlying error rather than
324/// yielding `Value::None`, so a catalog miss cannot degrade into a
325/// garbage value downstream: the engine's `enrich_eval_panic` adds
326/// node provenance, `eval_const_expr` traps the panic into
327/// `Result::Err`, and `evaluate_spec` propagates it as a
328/// clause-level diagnostic.
329#[crate::polydat_node(category = RealData)]
330fn dataset_open(source: &str, facet: &str) -> Arc<DatasetHandle> {
331 match DatasetHandle::open(source, facet) {
332 Ok(h) => Arc::new(h),
333 Err(e) => {
334 let msg = format!("dataset_open: failed to resolve '{source}' facet='{facet}': {e}");
335 crate::library::support::audit::error(&msg);
336 panic!("{msg}");
337 }
338 }
339}
340
341/// `dataset_group_open(source: str) -> Handle`
342///
343/// Group-level resolver. Returns a handle wrapping `Arc<TestDataGroup>`
344/// — used by group-level metadata accessors (`dataset_profile_count`,
345/// `dataset_facets`, ...) that operate on the dataset as a whole
346/// before any profile/facet is selected.
347///
348/// A resolve failure panics, as in `dataset_open` and for the
349/// same reason.
350#[crate::polydat_node(category = RealData)]
351fn dataset_group_open(source: &str) -> Arc<DatasetHandle> {
352 match DatasetHandle::open_group(source) {
353 Ok(h) => Arc::new(h),
354 Err(e) => {
355 let msg = format!("dataset_group_open: failed to resolve '{source}': {e}");
356 crate::library::support::audit::error(&msg);
357 panic!("{msg}");
358 }
359 }
360}
361
362// =================================================================
363// Base vector nodes
364// =================================================================
365
366// All indexed-accessor nodes share the same shape: a handle wire
367// and an `index` wire (u64). A source string in the handle
368// position is promoted to `dataset_open(source, "<facet>")` for
369// the facet the accessor names, and the facet reader is opened
370// once per (source, profile, facet) through `FACET_CACHE`, so
371// the per-cycle work is the facet read alone.
372
373// =================================================================
374// Per-cycle indexed accessors
375// =================================================================
376
377/// Resolve a Prebuffered handle to a specific-facet handle by
378/// opening the named facet via the existing FACET_CACHE path
379/// (which is `OnceCache`-backed — concurrent callers serialize
380/// per (source, profile, facet)). For non-Prebuffered handles
381/// this is a borrow-through; the macro callers use the result as
382/// `&DatasetHandle` regardless of which arm fires.
383///
384/// Lives on `DatasetHandle` so the resolution logic — and the
385/// "what does Prebuffered mean to a per-facet accessor" question
386/// — sits next to the variant declaration.
387impl DatasetHandle {
388 fn resolve_facet<'a>(&'a self, facet: &str) -> std::borrow::Cow<'a, DatasetHandle> {
389 match self {
390 DatasetHandle::Prebuffered { source, .. } => match DatasetHandle::open(source, facet) {
391 Ok(opened) => std::borrow::Cow::Owned(opened),
392 Err(e) => panic!(
393 "DatasetHandle::resolve_facet: failed to open \
394 '{facet}' from prebuffered '{source}': {e}"
395 ),
396 },
397 _ => std::borrow::Cow::Borrowed(self),
398 }
399 }
400
401 /// The dataset group a group accessor reads: the group of a
402 /// `dataset_group_open` handle, or the group a prebuffered handle
403 /// carries. A facet handle has no group, and asking one for it
404 /// panics with the handle's kind.
405 fn resolve_group(&self) -> &TestDataGroup {
406 match self {
407 DatasetHandle::Group(g) | DatasetHandle::Prebuffered { group: g, .. } => g.as_ref(),
408 other => panic!(
409 "expected a group or prebuffered handle, got {}",
410 dataset_handle_kind(other)
411 ),
412 }
413 }
414}
415
416/// The facet each accessor opens, as a type.
417///
418/// A node states its facet twice — in the auto-resolver that splices
419/// `dataset_open(_, "<facet>")` when the source is a string, and in
420/// the `resolve_facet` call that follows a prebuffered handle — and
421/// both readings come from here, so the two cannot drift apart.
422macro_rules! facet_kind {
423 ($name:ident, $facet:literal) => {
424 /// The `
425 #[doc = $facet]
426 /// ` facet of a dataset.
427 pub struct $name;
428 impl $name {
429 /// The facet's name, as `dataset_open` takes it.
430 pub const FACET: &'static str = $facet;
431 }
432 impl crate::derive_support::ResolverKind for $name {
433 const RESOLVER: crate::dsl::registry::DefaultResolver =
434 crate::dsl::registry::DefaultResolver::Facet($facet);
435 }
436 };
437}
438
439facet_kind!(BaseFacet, "base");
440facet_kind!(QueryFacet, "query");
441facet_kind!(NeighborIndicesFacet, "neighbor_indices");
442facet_kind!(NeighborDistancesFacet, "neighbor_distances");
443facet_kind!(FilteredNeighborIndicesFacet, "filtered_neighbor_indices");
444facet_kind!(
445 FilteredNeighborDistancesFacet,
446 "filtered_neighbor_distances"
447);
448facet_kind!(MetadataResultsFacet, "metadata_results");
449facet_kind!(MetadataContentFacet, "metadata_content");
450facet_kind!(MetadataPredicatesFacet, "metadata_predicates");
451
452/// A handle wire that carries its facet in its type.
453type Facet<R> = crate::derive_support::Resolved<R, DatasetHandle>;
454
455/// A handle wire on the dataset group rather than one of its facets.
456type Group = crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>;
457
458/// The record count of a facet handle, opening `facet` first when the
459/// handle is prebuffered. `who` names the caller in the diagnostics,
460/// which is what the reader needs to see when a workload asks a
461/// facet for a count it cannot give.
462fn facet_record_count(h: &DatasetHandle, who: &str, facet: &str) -> u64 {
463 match h.resolve_facet(facet).as_ref() {
464 DatasetHandle::F32(d) => d.count as u64,
465 DatasetHandle::I32(d) => d.count as u64,
466 DatasetHandle::Ivvec32(d) => d.count as u64,
467 DatasetHandle::Generic(d) => d.count as u64,
468 other => panic!(
469 "{who}: expected a facet handle, got {}",
470 dataset_handle_kind(other)
471 ),
472 }
473}
474
475/// The `f32` record at `index`, as the typed vector it is.
476fn f32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<f32> {
477 match h {
478 DatasetHandle::F32(d) => slice_arc_from_uniform(d, index),
479 other => panic!(
480 "expected F32 dataset handle, got {}",
481 dataset_handle_kind(other)
482 ),
483 }
484}
485
486/// The `i32` record at `index`, as the typed vector it is.
487fn i32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<i32> {
488 match h {
489 DatasetHandle::I32(d) => slice_arc_from_uniform(d, index),
490 other => panic!(
491 "expected I32 dataset handle, got {}",
492 dataset_handle_kind(other)
493 ),
494 }
495}
496
497fn ivvec32_vec_typed(h: &DatasetHandle, index: usize) -> crate::ast::SliceArc<i32> {
498 match h {
499 // Variable-length records — vectordata's trait doesn't expose
500 // a zero-copy slice path for these (per-record dim is read
501 // from the file), so we always allocate. One Vec<i32> per
502 // cycle; same bound as the upstream trait API.
503 DatasetHandle::Ivvec32(d) => {
504 if d.count == 0 {
505 return crate::ast::SliceArc::from_vec(Vec::<i32>::new());
506 }
507 let v = d.reader.get(index % d.count).unwrap_or_default();
508 crate::ast::SliceArc::from_vec(v)
509 }
510 other => panic!(
511 "expected Ivvec32 dataset handle, got {}",
512 dataset_handle_kind(other)
513 ),
514 }
515}
516
517/// Build a [`SliceArc<T>`] from any uniform-stride dataset at
518/// `index`. One generic helper serves every element type — element type is
519/// erased by the upstream `VectorReader<T>` trait, and `SliceArc`
520/// is element-type-generic, so one body suffices for `f32`,
521/// `i32`, and any other element type the trait supports.
522///
523/// Tries the zero-copy `VectorReader::get_slice` path first —
524/// that returns a borrow into the mmap'd file pages, kept alive
525/// by the `Arc<UniformDataset<T>>` that we move into the
526/// `SliceArc` as owner. No allocation, no element decoding, no
527/// copy.
528///
529/// Falls back to `VectorReader::get(idx) -> Vec<T>` for readers
530/// that don't support zero-copy (HTTP-backed, or merkle-cached
531/// storage that hasn't been promoted to mmap yet); that path
532/// allocates one `Vec<T>` per cycle.
533fn slice_arc_from_uniform<T>(d: &Arc<UniformDataset<T>>, index: usize) -> crate::ast::SliceArc<T>
534where
535 T: Send + Sync + Copy + 'static,
536{
537 if d.count == 0 {
538 return crate::ast::SliceArc::from_vec(Vec::<T>::new());
539 }
540 let idx = index % d.count;
541 if let Some(slice) = d.reader.get_slice(idx) {
542 // SAFETY: the slice points into the mmap pages owned by
543 // `d`'s reader; cloning `d` into the `SliceArc`'s owner
544 // keeps the mmap alive for as long as the slice is held.
545 let ptr_len = (slice.as_ptr(), slice.len());
546 let owner = d.clone();
547 let owner_dyn: Arc<dyn std::any::Any + Send + Sync> = owner;
548 return unsafe {
549 crate::ast::SliceArc::from_borrowed(
550 owner_dyn,
551 std::slice::from_raw_parts(ptr_len.0, ptr_len.1),
552 )
553 };
554 }
555 crate::ast::SliceArc::from_vec(d.reader.get(idx).unwrap_or_default())
556}
557
558fn dataset_handle_kind(h: &DatasetHandle) -> &'static str {
559 match h {
560 DatasetHandle::F32(_) => "F32",
561 DatasetHandle::I32(_) => "I32",
562 DatasetHandle::Ivvec32(_) => "Ivvec32",
563 DatasetHandle::Generic(_) => "Generic",
564 DatasetHandle::Group(_) => "Group",
565 DatasetHandle::Prebuffered { .. } => "Prebuffered",
566 }
567}
568
569/// Access an `f32` vector by index, returning a typed `VecF32`.
570/// Reads the base facet of a source string or prebuffered handle,
571/// and whatever facet an opened F32 handle names.
572///
573/// Signature: `vector_at(handle, index: u64) -> VecF32`
574#[crate::polydat_node(category = RealData)]
575fn vector_at(handle: Facet<BaseFacet>, index: u64) -> crate::ast::SliceArc<f32> {
576 f32_vec_typed(
577 handle.resolve_facet(BaseFacet::FACET).as_ref(),
578 index as usize,
579 )
580}
581
582/// Access a query vector by index. Reads the query facet of a
583/// source string or prebuffered handle, as `vector_at` reads the
584/// base facet.
585///
586/// Signature: `query_vector_at(handle, index: u64) -> VecF32`
587#[crate::polydat_node(category = RealData)]
588fn query_vector_at(handle: Facet<QueryFacet>, index: u64) -> crate::ast::SliceArc<f32> {
589 f32_vec_typed(
590 handle.resolve_facet(QueryFacet::FACET).as_ref(),
591 index as usize,
592 )
593}
594
595/// Access ground-truth neighbor indices for a query. Expects an
596/// I32 handle.
597///
598/// Signature: `neighbor_indices_at(handle, index: u64) -> VecI32`
599#[crate::polydat_node(category = RealData)]
600fn neighbor_indices_at(
601 handle: Facet<NeighborIndicesFacet>,
602 index: u64,
603) -> crate::ast::SliceArc<i32> {
604 i32_vec_typed(
605 handle.resolve_facet(NeighborIndicesFacet::FACET).as_ref(),
606 index as usize,
607 )
608}
609
610/// Access ground-truth neighbor distances for a query. Expects an
611/// F32 handle.
612///
613/// Signature: `neighbor_distances_at(handle, index: u64) -> VecF32`
614#[crate::polydat_node(category = RealData)]
615fn neighbor_distances_at(
616 handle: Facet<NeighborDistancesFacet>,
617 index: u64,
618) -> crate::ast::SliceArc<f32> {
619 f32_vec_typed(
620 handle.resolve_facet(NeighborDistancesFacet::FACET).as_ref(),
621 index as usize,
622 )
623}
624
625/// Access filtered ground-truth neighbor indices. Expects an I32 handle.
626#[crate::polydat_node(category = RealData)]
627fn filtered_neighbor_indices_at(
628 handle: Facet<FilteredNeighborIndicesFacet>,
629 index: u64,
630) -> crate::ast::SliceArc<i32> {
631 i32_vec_typed(
632 handle
633 .resolve_facet(FilteredNeighborIndicesFacet::FACET)
634 .as_ref(),
635 index as usize,
636 )
637}
638
639/// Access filtered ground-truth neighbor distances. Expects an F32 handle.
640#[crate::polydat_node(category = RealData)]
641fn filtered_neighbor_distances_at(
642 handle: Facet<FilteredNeighborDistancesFacet>,
643 index: u64,
644) -> crate::ast::SliceArc<f32> {
645 f32_vec_typed(
646 handle
647 .resolve_facet(FilteredNeighborDistancesFacet::FACET)
648 .as_ref(),
649 index as usize,
650 )
651}
652
653// =================================================================
654// Metadata nodes (constant per dataset)
655// =================================================================
656
657// =================================================================
658// Per-handle metadata nodes
659// =================================================================
660//
661// Take `(handle: Handle)` and read shape/metadata directly from the
662// resolved dataset. Provenance bounded by the handle, which itself
663// is bounded by the resolver's externs — so these collapse to a
664// single per-iteration eval chain via the standard provenance
665// caching. No per-cycle work.
666
667/// Return the dimensionality (`f32` count per record) of a
668/// vector facet handle.
669///
670/// Signature: `vector_dim(handle) -> (u64)`
671#[crate::polydat_node(category = RealData)]
672fn vector_dim(handle: Facet<BaseFacet>) -> u64 {
673 match handle.resolve_facet(BaseFacet::FACET).as_ref() {
674 DatasetHandle::F32(d) => d.dim as u64,
675 DatasetHandle::I32(d) => d.dim as u64,
676 _ => 0,
677 }
678}
679
680/// Return the count of records in the facet a handle was opened
681/// against. This is the canonical "how many vectors / queries /
682/// neighbor-rows" accessor — `vector_count(base_handle)` for
683/// base vectors, `vector_count(query_handle)` for query
684/// vectors, etc. A source string or prebuffered handle counts
685/// the base facet.
686///
687/// Signature: `vector_count(handle) -> (u64)`
688#[crate::polydat_node(category = RealData)]
689fn vector_count(handle: Facet<BaseFacet>) -> u64 {
690 facet_record_count(&handle, "vector_count", BaseFacet::FACET)
691}
692
693/// Return the count of query vectors. Counts the query facet of a
694/// source string or prebuffered handle, as `vector_count` counts
695/// the base facet.
696///
697/// Signature: `query_count(handle) -> (u64)`
698#[crate::polydat_node(category = RealData)]
699fn query_count(handle: Facet<QueryFacet>) -> u64 {
700 // `query_count(prebuffered)` is a legitimate idiom in the
701 // pvs_query workload (`cursor q = range(0, query_count(...))`),
702 // so the prebuffered case resolves the query facet and reads
703 // its count, through the same OnceCache-backed open the
704 // per-cycle accessors use.
705 facet_record_count(&handle, "query_count", QueryFacet::FACET)
706}
707
708/// Return the per-record neighbor count (k) for an I32
709/// neighbor-indices handle.
710///
711/// Signature: `neighbor_count(handle) -> (u64)`
712#[crate::polydat_node(category = RealData)]
713fn neighbor_count(handle: Facet<NeighborIndicesFacet>) -> u64 {
714 match handle.resolve_facet(NeighborIndicesFacet::FACET).as_ref() {
715 DatasetHandle::I32(d) => d.dim as u64,
716 _ => 0,
717 }
718}
719
720/// Return the dataset's distance function (e.g., "COSINE",
721/// "EUCLIDEAN"). Operates on the dataset group; takes a group or
722/// prebuffered handle.
723///
724/// Signature: `dataset_distance_function(group) -> (String)`
725#[crate::polydat_node(category = RealData)]
726fn dataset_distance_function(group: Group) -> String {
727 let group = group.resolve_group();
728 let raw = group
729 .attribute("distance_function")
730 .and_then(|v| v.as_str())
731 .unwrap_or("unknown");
732 match raw.to_uppercase().as_str() {
733 "L2" | "EUCLIDEAN" => "EUCLIDEAN",
734 "L1" | "MANHATTAN" => "MANHATTAN",
735 "COSINE" => "COSINE",
736 "DOT_PRODUCT" | "DOTPRODUCT" | "DOT" | "INNER_PRODUCT" | "IP" => "DOT_PRODUCT",
737 _ => raw,
738 }
739 .to_string()
740}
741
742// =================================================================
743// Metadata facet nodes
744// =================================================================
745
746/// Handle to a loaded variable-length i32 facet (metadata_results).
747pub(crate) struct Ivvec32Dataset {
748 reader: Arc<dyn VvecReader<i32>>,
749 count: usize,
750}
751
752impl Ivvec32Dataset {
753 fn load(source: &str, profile: &str) -> Result<Arc<Self>, String> {
754 let key = (
755 source.to_string(),
756 profile.to_string(),
757 "metadata_results".to_string(),
758 );
759 let any = FACET_CACHE.get_or_init(key, || {
760 let group = load_dataset_group(source)?;
761 let view = group
762 .profile(profile)
763 .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
764 crate::library::support::audit::record_opened(
765 parse_source_specifier(source).0,
766 profile,
767 "metadata_results",
768 "ivvec32",
769 );
770 // A remote variable-length facet published without its
771 // `IDXFOR__` offset index can only be opened from every
772 // byte; the fetching open downloads it whole, with progress,
773 // where a plain open refuses.
774 let reader = run_blocking_io(|| {
775 view.metadata_results_fetching_as(&mut fetch_meter(&format!("open {source}")))
776 })
777 .map_err(|e| format!("failed to access metadata_results from '{source}': {e}"))?;
778 let count = reader.count();
779 let arc: Arc<Self> = Arc::new(Self { reader, count });
780 Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
781 })?;
782 any.downcast::<Self>().map_err(|_| {
783 format!("facet cache type mismatch for '{source}:{profile}/metadata_results'")
784 })
785 }
786}
787
788/// Access metadata indices (variable-length matching base ordinals
789/// per query) at an index. Expects an Ivvec32 handle.
790///
791/// Signature: `metadata_results_at(handle, index: u64) -> VecI32`
792#[crate::polydat_node(category = RealData)]
793fn metadata_results_at(
794 handle: Facet<MetadataResultsFacet>,
795 index: u64,
796) -> crate::ast::SliceArc<i32> {
797 ivvec32_vec_typed(
798 handle.resolve_facet(MetadataResultsFacet::FACET).as_ref(),
799 index as usize,
800 )
801}
802
803/// Return the length of one metadata_results record without
804/// loading the data (reads only the 4-byte header). Expects an
805/// Ivvec32 handle.
806///
807/// Signature: `metadata_results_len_at(handle, index: u64) -> (u64)`
808#[crate::polydat_node(category = RealData)]
809fn metadata_results_len_at(handle: Facet<MetadataResultsFacet>, index: u64) -> u64 {
810 match handle.resolve_facet(MetadataResultsFacet::FACET).as_ref() {
811 DatasetHandle::Ivvec32(d) if d.count > 0 => {
812 d.reader.dim_at(index as usize % d.count).unwrap_or(0) as u64
813 }
814 _ => 0,
815 }
816}
817
818/// Return the metadata indices count (number of predicate result
819/// sets). Expects an Ivvec32 handle.
820#[crate::polydat_node(category = RealData)]
821fn metadata_results_count(handle: Facet<MetadataResultsFacet>) -> u64 {
822 match handle.resolve_facet(MetadataResultsFacet::FACET).as_ref() {
823 DatasetHandle::Ivvec32(d) => d.count as u64,
824 _ => 0,
825 }
826}
827
828/// Report which facets are available for the default profile of
829/// a dataset group as a comma-separated list. Expects a group or
830/// prebuffered handle.
831///
832/// Signature: `dataset_facets(group) -> (String)`
833#[crate::polydat_node(category = RealData)]
834fn dataset_facets(group: Group) -> String {
835 let group = group.resolve_group();
836 // Use the default profile — group-level callers want a
837 // dataset-wide manifest; specific profile facets come via
838 // `profile_facets(group, idx)`.
839 let names = group.profile_names();
840 if let Some(first) = names.first()
841 && let Some(view) = group.profile(first)
842 {
843 let manifest = view.facet_manifest();
844 let mut names: Vec<&String> = manifest.keys().collect();
845 names.sort();
846 return names
847 .iter()
848 .map(|s| s.as_str())
849 .collect::<Vec<_>>()
850 .join(", ");
851 }
852 String::new()
853}
854
855// =================================================================
856// Profile enumeration — discover and iterate over dataset profiles
857// =================================================================
858//
859// Group-level: take a Group handle, read the dataset's sorted profile
860// list. Sort order is canonical (by base_count via `profile_sort_by_size`)
861// and computed once per group via the underlying TestDataGroup.
862
863/// Total number of profiles in a dataset group.
864///
865/// Signature: `dataset_profile_count(group) -> (u64)`
866#[crate::polydat_node(category = RealData)]
867fn dataset_profile_count(group: Group) -> u64 {
868 group.resolve_group().profile_names().len() as u64
869}
870
871/// Comma-separated list of all profile names in canonical sort
872/// order (by base_count).
873///
874/// Signature: `dataset_profile_names(group) -> (String)`
875#[crate::polydat_node(category = RealData)]
876fn dataset_profile_names(group: Group) -> String {
877 group.resolve_group().profile_names().join(", ")
878}
879
880/// Return profile names matching a prefix, comma-separated.
881///
882/// Signature: `matching_profiles(group, prefix: str) -> (String)`
883///
884/// If prefix is empty, returns all profiles. Used by `for_each:`
885/// phase templates to discover profiles dynamically.
886///
887/// `group` declares its source-string auto-resolver via the
888/// `Resolved<GroupResolver, _>` marker wrapper — the macro reads
889/// `<Resolved<GroupResolver, DatasetHandle> as Wire>::RESOLVER` at
890/// codegen and emits the matching `FuncSig.default_resolver`
891/// (`DefaultResolver::Group`). The spliced `dataset_group_open` yields
892/// the canonical `Value::Handle(Arc<DatasetHandle>)`, so the wire is
893/// resolved as `DatasetHandle` and the group is taken via
894/// `DatasetHandle::resolve_group` (downcasting straight to
895/// `TestDataGroup` would fail — the handle is always the unified
896/// `DatasetHandle` enum).
897#[crate::polydat_node(category = RealData)]
898fn matching_profiles(
899 group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
900 prefix: &str,
901) -> String {
902 let group: &TestDataGroup = group.resolve_group();
903 let all = group.profile_names();
904 let mut matched: Vec<&str> = if prefix.is_empty() {
905 all.iter().map(|s| s.as_str()).collect()
906 } else {
907 all.iter()
908 .filter(|s| s.starts_with(prefix))
909 .map(|s| s.as_str())
910 .collect()
911 };
912 // Natural-order sort: alphabetic with numeric runs
913 // compared as numbers so `label_03` sorts before
914 // `label_10`. The upstream `group.profile_names()`
915 // orders by `base_count` (vectordata's choice — useful
916 // for index-based lookups), but `for_each` iteration
917 // wants stable, human-natural order so users see
918 // label_01, label_02, label_03 instead of whatever the
919 // size-sort happens to produce.
920 matched.sort_by(|a, b| natural_cmp(a, b));
921 matched.join(",")
922}
923
924/// Natural ordering: split each string into alternating text
925/// and numeric runs and compare run-by-run, comparing numeric
926/// runs as integers. Beats lexicographic on `label_03` vs
927/// `label_10` (lex: "10" < "3"; natural: 3 < 10).
928fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
929 let mut ai = a.chars().peekable();
930 let mut bi = b.chars().peekable();
931 loop {
932 match (ai.peek().copied(), bi.peek().copied()) {
933 (None, None) => return std::cmp::Ordering::Equal,
934 (None, _) => return std::cmp::Ordering::Less,
935 (_, None) => return std::cmp::Ordering::Greater,
936 (Some(ac), Some(bc)) => {
937 if ac.is_ascii_digit() && bc.is_ascii_digit() {
938 let mut na: u64 = 0;
939 while let Some(c) = ai.peek().copied()
940 && c.is_ascii_digit()
941 {
942 na = na
943 .saturating_mul(10)
944 .saturating_add((c as u8 - b'0') as u64);
945 ai.next();
946 }
947 let mut nb: u64 = 0;
948 while let Some(c) = bi.peek().copied()
949 && c.is_ascii_digit()
950 {
951 nb = nb
952 .saturating_mul(10)
953 .saturating_add((c as u8 - b'0') as u64);
954 bi.next();
955 }
956 match na.cmp(&nb) {
957 std::cmp::Ordering::Equal => continue,
958 non_eq => return non_eq,
959 }
960 } else {
961 match ac.cmp(&bc) {
962 std::cmp::Ordering::Equal => {
963 ai.next();
964 bi.next();
965 }
966 non_eq => return non_eq,
967 }
968 }
969 }
970 }
971 }
972}
973
974/// Look up a profile name by index from the canonical sorted list.
975///
976/// Signature: `dataset_profile_name_at(group, index: u64) -> (String)`
977///
978/// Index wraps modulo the number of profiles.
979#[crate::polydat_node(category = RealData)]
980fn dataset_profile_name_at(
981 group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
982 index: u64,
983) -> String {
984 let group: &TestDataGroup = group.resolve_group();
985 let names = group.profile_names();
986 if names.is_empty() {
987 String::new()
988 } else {
989 names[(index as usize) % names.len()].clone()
990 }
991}
992
993/// Return the base vector count for the profile at a given index.
994///
995/// Signature: `profile_base_count(group, index: u64) -> (u64)`
996#[crate::polydat_node(category = RealData)]
997fn profile_base_count(
998 group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
999 index: u64,
1000) -> u64 {
1001 let group: &TestDataGroup = group.resolve_group();
1002 let names = group.profile_names();
1003 if names.is_empty() {
1004 0
1005 } else {
1006 let name = &names[(index as usize) % names.len()];
1007 group
1008 .profile(name)
1009 .and_then(|view| view.base_count())
1010 .unwrap_or(0)
1011 }
1012}
1013
1014/// Return the comma-separated facet list for the profile at a given index.
1015///
1016/// Signature: `profile_facets(group, index: u64) -> (String)`
1017#[crate::polydat_node(category = RealData)]
1018fn profile_facets(
1019 group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1020 index: u64,
1021) -> String {
1022 let group: &TestDataGroup = group.resolve_group();
1023 let names = group.profile_names();
1024 if names.is_empty() {
1025 String::new()
1026 } else {
1027 let name = &names[(index as usize) % names.len()];
1028 match group.profile(name) {
1029 Some(view) => {
1030 let manifest = view.facet_manifest();
1031 let mut fnames: Vec<&String> = manifest.keys().collect();
1032 fnames.sort();
1033 fnames
1034 .iter()
1035 .map(|s| s.as_str())
1036 .collect::<Vec<_>>()
1037 .join(", ")
1038 }
1039 None => String::new(),
1040 }
1041 }
1042}
1043
1044/// Partition a dataset's vector space by its **profiles matching a
1045/// pattern**, treated as cumulative size tiers (a partition source,
1046/// cursor_partitions.md §7.1). One partition per masked profile, in canonical
1047/// (base-count-ascending) order: partition `k` spans
1048/// `[prev_masked_base_count, this_masked_base_count)` — exactly the
1049/// vectors added at that tier — so a sweep's "load only the increment
1050/// since the previously loaded set" is just the partition's
1051/// `[start_of(p), end_of(p))`, and a partition inherently knows its
1052/// start (no cross-iteration carry needed). `idx_of(p)` is the 0-based
1053/// masked position (pairs with `matching_profile_name_at` to address
1054/// the tier's own ground-truth facets); `count_of(p)` is the number of
1055/// masked tiers; `base_extent` is the largest masked tier's size.
1056///
1057/// `pattern` follows the literal / glob / regex promotion of
1058/// [`crate::library::support::pattern::compile_pattern`]; `*` (or any pattern that
1059/// matches all names) selects every profile.
1060///
1061/// Signature: `profile_partitions(group, pattern: str) -> (PartitionList)`
1062#[crate::polydat_node(category = RealData)]
1063fn profile_partitions(
1064 group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1065 pattern: &str,
1066) -> crate::derive_support::Ext<crate::iteration::cursor_partition::PartitionList> {
1067 let group: &TestDataGroup = group.resolve_group();
1068 let parts = build_profile_partitions(group, pattern);
1069 crate::derive_support::Ext(crate::iteration::cursor_partition::PartitionList::new(
1070 parts,
1071 ))
1072}
1073
1074/// Build the cumulative size-tier partitions for the profiles of `group`
1075/// matching `pattern` (literal/glob/regex promotion). Shared by the
1076/// [`profile_partitions`] node and the comprehension-source desugaring
1077/// in `iteration::comprehension::eval` so a `for: "p in
1078/// profile_partitions(...)"` sweep produces identical partitions either
1079/// way. Partition `k` spans `[prev masked base_count, this base_count)`.
1080/// The masked profile size-tiers for `group` matching `pattern`, in
1081/// canonical (base-count-ascending) order: `(name, cumulative_base_count)`
1082/// for each matching profile WITH a non-zero base count. Profiles with no
1083/// base facet, or a zero count, are skipped — they would otherwise emit a
1084/// degenerate empty `[prev, prev)` partition (and a query against an empty
1085/// tier). Shared by [`build_profile_partitions`] and
1086/// [`matching_profile_name_at`] so a partition's `idx_of(p)` and the tier
1087/// name resolve against the SAME masked sequence.
1088fn masked_profile_tiers(group: &TestDataGroup, pattern: &str) -> Vec<(String, u64)> {
1089 let (re, _) = crate::library::support::pattern::compile_pattern(pattern)
1090 .unwrap_or_else(|e| panic!("profile pattern: {e}"));
1091 group
1092 .profile_names()
1093 .iter()
1094 .filter(|n| re.is_match(n))
1095 .filter_map(|n| {
1096 group
1097 .profile(n)
1098 .and_then(|v| v.base_count())
1099 .filter(|&c| c > 0)
1100 .map(|c| (n.clone(), c))
1101 })
1102 .collect()
1103}
1104
1105pub(crate) fn build_profile_partitions(
1106 group: &TestDataGroup,
1107 pattern: &str,
1108) -> Vec<crate::iteration::cursor_partition::Partition> {
1109 // Masked size-tiers (matching profiles with a non-zero base count),
1110 // canonical (ascending) order — skipping zero-count profiles avoids a
1111 // degenerate empty first partition.
1112 let masked: Vec<u64> = masked_profile_tiers(group, pattern)
1113 .into_iter()
1114 .map(|(_, c)| c)
1115 .collect();
1116 let base_extent = masked.last().copied().unwrap_or(0);
1117 let count = masked.len() as u64;
1118 let pct = |o: u64| {
1119 if base_extent == 0 {
1120 0.0
1121 } else {
1122 (o as f64 / base_extent as f64) * 100.0
1123 }
1124 };
1125 let mut parts: Vec<crate::iteration::cursor_partition::Partition> =
1126 Vec::with_capacity(masked.len());
1127 let mut prev: u64 = 0;
1128 for (k, &this) in masked.iter().enumerate() {
1129 parts.push(crate::iteration::cursor_partition::Partition {
1130 idx: k as u64,
1131 count,
1132 start_ord: prev,
1133 end_ord: this,
1134 start_pct: pct(prev),
1135 end_pct: pct(this),
1136 base_extent,
1137 });
1138 prev = this;
1139 }
1140 parts
1141}
1142
1143/// Name of the `index`-th profile **matching `pattern`**, in canonical
1144/// (base-count-ascending) order. Pairs with `profile_partitions`'s
1145/// masked-position `idx_of` so a sweep can prebuffer the active tier's
1146/// own ground-truth facets (`dataset_prebuffer(str_concat("ds:", name))`).
1147/// `pattern` follows the literal / glob / regex promotion; the index
1148/// wraps modulo the number of matching profiles; empty string if none
1149/// match.
1150///
1151/// Signature: `matching_profile_name_at(group, pattern: str, index: u64) -> (String)`
1152#[crate::polydat_node(category = RealData)]
1153fn matching_profile_name_at(
1154 group: crate::derive_support::Resolved<crate::derive_support::GroupResolver, DatasetHandle>,
1155 pattern: &str,
1156 index: u64,
1157) -> String {
1158 let group: &TestDataGroup = group.resolve_group();
1159 // Same masked sequence `profile_partitions` uses (matching profiles
1160 // with a non-zero base count, canonical order), so `idx_of(p)` from a
1161 // partition resolves to the right tier name.
1162 let tiers = masked_profile_tiers(group, pattern);
1163 if tiers.is_empty() {
1164 String::new()
1165 } else {
1166 tiers[(index as usize) % tiers.len()].0.clone()
1167 }
1168}
1169
1170// =================================================================
1171// Prebuffering — eagerly download dataset facets before workload run
1172// =================================================================
1173
1174/// Eagerly download all facets for a dataset profile into the
1175/// local cache, returning a dataset handle that every facet
1176/// accessor and every group accessor takes as its first
1177/// argument. After this returns, every subsequent facet read
1178/// served by [`vectordata::TestDataView`] hits the merkle-
1179/// verified mmap fast path with no further network traffic.
1180///
1181/// Signature: `dataset_prebuffer(source) -> Handle`
1182///
1183/// **Why a handle, not a count.** Returning a value the
1184/// downstream accessors *consume* makes prebuffer part of
1185/// the dataflow graph: DCE keeps the chain alive because
1186/// `vector_at(prebuffered, q)` needs `prebuffered` to be
1187/// resolvable, which forces evaluation. A binding such as
1188/// `init prebuffered = dataset_prebuffer(...)` whose result
1189/// nothing reads is pruned, so a workload threads the handle
1190/// through its accessors.
1191///
1192/// `source` is the canonical `dataset:profile` string. The
1193/// returned handle names the dataset rather than one facet: a
1194/// facet accessor opens its own facet of `source` from it
1195/// (`DatasetHandle::resolve_facet`), and a group accessor
1196/// (`dataset_facets`, `dataset_distance_function`, ...) reads
1197/// the dataset's group (`DatasetHandle::resolve_group`).
1198///
1199/// A dataset that does not resolve yields no handle, and the
1200/// resolve error goes to the audit log. A profile the dataset
1201/// lacks, or a facet whose download fails, is logged there too
1202/// and still yields the handle: prebuffering is a best-effort
1203/// warm-up, and an accessor that then reads a missing facet
1204/// fails with that facet's own error.
1205#[crate::polydat_node(category = RealData)]
1206fn dataset_prebuffer(source: &str) -> Option<Arc<dyn std::any::Any + Send + Sync>> {
1207 // The const binding contract (evaluation_model.md §"Const
1208 // Binding Contract") means this runs exactly once per scope
1209 // activation: the activation kernel pulls the binding and the host propagates the result to every
1210 // fiber. PREBUFFER_CACHE is belt-and-suspenders: it serializes
1211 // anyone who reaches here by another path, so a per-source
1212 // thundering herd is structurally impossible whatever the caller
1213 // does.
1214 match PREBUFFER_CACHE.get_or_init(source.to_string(), || {
1215 // Only the first concurrent caller for this source runs the
1216 // inner body — the audit "entered" event reflects that one
1217 // download, not per-caller noise.
1218 crate::library::support::audit::record_prebuffer_entered(source);
1219 do_dataset_prebuffer_inner(source)
1220 }) {
1221 Ok(handle) => Some(handle as Arc<dyn std::any::Any + Send + Sync>),
1222 Err(_) => None,
1223 }
1224}
1225
1226/// Inner body of [`dataset_prebuffer`]. Runs **at most once
1227/// per (source, process)** under the [`PREBUFFER_CACHE`] OnceLock.
1228fn do_dataset_prebuffer_inner(source: &str) -> Result<Arc<DatasetHandle>, String> {
1229 // Every exit after the group resolves returns a prebuffered
1230 // handle, so the downstream `*_at(prebuffered, q)` accessors can
1231 // resolve. A failed download still hands back the handle — the
1232 // accessors then read through the transport, and the operator
1233 // sees the prebuffer error in the audit log.
1234 let group = match load_dataset_group(source) {
1235 Ok(g) => g,
1236 Err(e) => {
1237 let msg = format!("dataset_prebuffer: cannot resolve '{source}': {e}");
1238 crate::library::support::audit::error(&msg);
1239 // No group → no handle to hand back. Sticky error in
1240 // the cache; downstream accessors will produce a
1241 // diagnostic when they fail to downcast.
1242 return Err(msg);
1243 }
1244 };
1245 let group_for_handle = group.clone();
1246 let (_, profile) = parse_source_specifier(source);
1247 let view = match group.profile(profile) {
1248 Some(v) => v,
1249 None => {
1250 crate::library::support::audit::error(&format!(
1251 "dataset_prebuffer: profile '{profile}' not found in '{source}'"
1252 ));
1253 return Ok(Arc::new(DatasetHandle::Prebuffered {
1254 group: group_for_handle,
1255 source: source.to_string(),
1256 }));
1257 }
1258 };
1259 // One fetch over every facet that holds data: vectordata plans
1260 // each facet, refuses a run the cache directory cannot hold
1261 // before any byte moves, and skips chunks already resident.
1262 // [`fetch_meter`] reports the run through the audit channel,
1263 // throttled so a multi-gigabyte facet doesn't spew thousands of
1264 // lines into session.log.
1265 //
1266 // Audit instrumentation: log every facet the fetch *covers* with
1267 // its key (`source:profile/facet`). Compared against the
1268 // `vectordata: opened …` lines emitted by [`load_uniform_facet`] /
1269 // [`GenericFacetDataset::load`], this surfaces any facet the
1270 // workload reads at cycle time that prebuffer did NOT pull — the
1271 // typical cause of a "still hitting HTTP after prebuffer" symptom.
1272 //
1273 // `fetch` drives `reqwest::blocking`, which spins up a private
1274 // tokio runtime per request; `run_blocking_io` parks the outer
1275 // worker so dropping that inner runtime doesn't panic. Same
1276 // pattern as `load_dataset_group` and `load_uniform_facet`.
1277 let mut meter = fetch_meter(&format!("prebuffer {source}"));
1278 let facet_count = match run_blocking_io(|| view.fetch(&FetchRequest::all(), &mut meter)) {
1279 Ok(report) => {
1280 for fetched in &report.facets {
1281 crate::library::support::audit::record_prebuffered(
1282 parse_source_specifier(source).0,
1283 profile,
1284 &fetched.id.facet,
1285 );
1286 }
1287 report.facets.len() as u64
1288 }
1289 Err(e) => {
1290 crate::library::support::audit::warn(&format!(
1291 "dataset_prebuffer: download error for '{source}': {e}"
1292 ));
1293 0
1294 }
1295 };
1296 crate::library::support::audit::log_prebuffer_summary(
1297 parse_source_specifier(source).0,
1298 profile,
1299 facet_count,
1300 );
1301 Ok(Arc::new(DatasetHandle::Prebuffered {
1302 group: group_for_handle,
1303 source: source.to_string(),
1304 }))
1305}
1306
1307/// The progress meter for a fetch, titled `title`: whole lines on the
1308/// audit channel — a line as each facet starts and finishes, and a
1309/// progress line per 10% of the run but at most one per 10s — and
1310/// nothing for data already in the cache.
1311fn fetch_meter(title: &str) -> LogMeter {
1312 LogMeter::to_lines(title, |level, line| {
1313 crate::library::support::audit::log(level.into(), line)
1314 })
1315 .min_interval(std::time::Duration::from_secs(10))
1316 .quiet_when_resident(true)
1317}
1318
1319// =================================================================
1320// Generic facet access — type-aware scalar/vector readers
1321// =================================================================
1322
1323/// A type-erased facet reader that reads values as i64.
1324/// Uses [`TestDataViewExt::facet_as`] at `i64`, which widens every
1325/// integer element type (u8, i32, …) and serves local and remote
1326/// facets through the same cache.
1327pub(crate) struct GenericFacetDataset {
1328 reader: Arc<dyn VectorReader<i64>>,
1329 count: usize,
1330}
1331
1332impl GenericFacetDataset {
1333 fn load(source: &str, profile: &str, facet: &str) -> Result<Arc<Self>, String> {
1334 let key = (source.to_string(), profile.to_string(), facet.to_string());
1335 let any = FACET_CACHE.get_or_init(key, || {
1336 let group = load_dataset_group(source)?;
1337 let view = group
1338 .profile(profile)
1339 .ok_or_else(|| format!("profile '{profile}' not found in '{source}'"))?;
1340 crate::library::support::audit::record_opened(
1341 parse_source_specifier(source).0,
1342 profile,
1343 facet,
1344 "generic-typed",
1345 );
1346 let reader = run_blocking_io(|| view.facet_as::<i64>(facet))
1347 .map_err(|e| format!("failed to open {facet} from '{source}:{profile}': {e}"))?;
1348 let count = reader.count();
1349 let arc: Arc<Self> = Arc::new(Self { reader, count });
1350 Ok(arc as Arc<dyn std::any::Any + Send + Sync>)
1351 })?;
1352 any.downcast::<Self>()
1353 .map_err(|_| format!("facet cache type mismatch for '{source}:{profile}/{facet}'"))
1354 }
1355
1356 fn get_scalar(&self, index: usize) -> i64 {
1357 if self.count == 0 {
1358 return 0;
1359 }
1360 let index = index % self.count;
1361 match self.reader.get_slice(index) {
1362 Some(record) => record.first().copied().unwrap_or(0),
1363 None => self
1364 .reader
1365 .get(index)
1366 .ok()
1367 .and_then(|record| record.first().copied())
1368 .unwrap_or(0),
1369 }
1370 }
1371
1372 fn format_scalar(&self, index: usize) -> String {
1373 self.get_scalar(index).to_string()
1374 }
1375}
1376
1377// Generic-facet readers (typed scalar). Take a Generic handle and
1378// read the i64-cast value at the requested index.
1379/// The scalar of a Generic facet at `idx`, rendered.
1380fn generic_str_typed(h: &DatasetHandle, idx: usize) -> String {
1381 match h {
1382 DatasetHandle::Generic(d) => d.format_scalar(idx),
1383 _ => String::new(),
1384 }
1385}
1386
1387/// Access a metadata value per base ordinal. Expects a Generic
1388/// handle opened against the `metadata_content` facet.
1389///
1390/// Signature: `metadata_value_at(handle, index: u64) -> (String)`
1391#[crate::polydat_node(category = RealData)]
1392fn metadata_value_at(handle: Facet<MetadataContentFacet>, index: u64) -> String {
1393 generic_str_typed(
1394 handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
1395 index as usize,
1396 )
1397}
1398
1399/// Access a predicate value per query ordinal. Expects a Generic
1400/// handle opened against the `metadata_predicates` facet.
1401///
1402/// Signature: `predicate_value_at(handle, index: u64) -> (String)`
1403#[crate::polydat_node(category = RealData)]
1404fn predicate_value_at(handle: Facet<MetadataPredicatesFacet>, index: u64) -> String {
1405 generic_str_typed(
1406 handle
1407 .resolve_facet(MetadataPredicatesFacet::FACET)
1408 .as_ref(),
1409 index as usize,
1410 )
1411}
1412
1413/// Count of metadata content records. Expects a Generic handle.
1414///
1415/// Signature: `metadata_content_count(handle) -> (u64)`
1416#[crate::polydat_node(category = RealData)]
1417fn metadata_content_count(handle: Facet<MetadataContentFacet>) -> u64 {
1418 match handle.resolve_facet(MetadataContentFacet::FACET).as_ref() {
1419 DatasetHandle::Generic(d) => d.count as u64,
1420 _ => 0,
1421 }
1422}
1423
1424// ── Counting a facet's matching records ─────────────────────────────
1425
1426/// How many scalars of a Generic facet equal `value`.
1427///
1428/// A linear read of the facet, which is what the question is: the
1429/// reader holds the values and nothing indexes them by content. Both
1430/// callers below pass a handle and a value that are fixed for a scope,
1431/// so the count is computed once at scope init and reused, the way the
1432/// facet itself is loaded once.
1433/// How many scalars of a Generic facet equal `value`.
1434fn generic_count_typed(h: &DatasetHandle, value: i64) -> u64 {
1435 match h {
1436 DatasetHandle::Generic(d) => {
1437 (0..d.count).filter(|i| d.get_scalar(*i) == value).count() as u64
1438 }
1439 _ => 0,
1440 }
1441}
1442
1443/// How many records carry the metadata value `value`.
1444///
1445/// The per-label cardinality the recall audit compares against a
1446/// profile's declared count: not a counter advancing as records are
1447/// visited, but a property of the facet and the value, so it
1448/// replays and agrees on every engine and every fiber
1449/// (docs/design/runtime_model.md §9.1).
1450///
1451/// `metadata_value_at(handle, i)` formats the same scalar as text,
1452/// so a host comparing labels as strings and one counting them
1453/// here are reading one facet.
1454#[crate::polydat_node(category = RealData)]
1455fn metadata_count_of(handle: Facet<MetadataContentFacet>, value: i64) -> u64 {
1456 generic_count_typed(
1457 handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
1458 value,
1459 )
1460}
1461
1462/// How many queries carry the predicate value `value`.
1463///
1464/// The denominator of a per-predicate recall figure, and the bound
1465/// on a rank within one predicate's queries.
1466///
1467/// Signature: `predicate_count_of(handle, value: i64) -> (u64)`
1468#[crate::polydat_node(category = RealData)]
1469fn predicate_count_of(handle: Facet<MetadataPredicatesFacet>, value: i64) -> u64 {
1470 generic_count_typed(
1471 handle
1472 .resolve_facet(MetadataPredicatesFacet::FACET)
1473 .as_ref(),
1474 value,
1475 )
1476}
1477
1478// ── Listing a facet's matching records ──────────────────────────────
1479
1480/// The indices of a Generic facet whose scalar equals `value`,
1481/// ascending.
1482///
1483/// The same linear read as [`generic_count_typed`], keeping the
1484/// indices it counts, so a list's length is the matching count, and
1485/// the list is computed once at scope init and reused the same way.
1486/// An index past `i32::MAX` is a facet larger than a `vec_i32`
1487/// addresses and fails by name rather than wrapping.
1488fn generic_ordinals_typed(node: &str, h: &DatasetHandle, value: i64) -> Vec<i32> {
1489 match h {
1490 DatasetHandle::Generic(d) => (0..d.count)
1491 .filter(|i| d.get_scalar(*i) == value)
1492 .map(|i| {
1493 i32::try_from(i)
1494 .unwrap_or_else(|_| panic!("{node}: ordinal {i} is outside the i32 range"))
1495 })
1496 .collect(),
1497 _ => Vec::new(),
1498 }
1499}
1500
1501/// The base ordinals whose metadata value is `value`, ascending.
1502///
1503/// The list whose length `metadata_count_of(handle, value)` is. The
1504/// record at local row `l` among those carrying `value` has global
1505/// ordinal `vec_at_i32(metadata_ordinals_of(handle, value), l)`
1506/// (docs/design/runtime_model.md §9.1).
1507#[crate::polydat_node(category = RealData)]
1508fn metadata_ordinals_of(handle: Facet<MetadataContentFacet>, value: i64) -> Vec<i32> {
1509 generic_ordinals_typed(
1510 "metadata_ordinals_of",
1511 handle.resolve_facet(MetadataContentFacet::FACET).as_ref(),
1512 value,
1513 )
1514}
1515
1516/// The query ordinals whose predicate value is `value`, ascending.
1517///
1518/// The list whose length `predicate_count_of(handle, value)` is.
1519#[crate::polydat_node(category = RealData)]
1520fn predicate_ordinals_of(handle: Facet<MetadataPredicatesFacet>, value: i64) -> Vec<i32> {
1521 generic_ordinals_typed(
1522 "predicate_ordinals_of",
1523 handle
1524 .resolve_facet(MetadataPredicatesFacet::FACET)
1525 .as_ref(),
1526 value,
1527 )
1528}
1529
1530// =========================================================================
1531// Cursor-sugar handlers
1532// =========================================================================
1533//
1534// Three sugar forms recognized by this module — none of them
1535// known to the core compiler, which dispatches generically
1536// through `dsl::cursor_sugar`. Each desugars to a synthetic
1537// `range(0, vector_count|query_count(...))` constructor plus
1538// auxiliary bindings:
1539//
1540// - `__<cursor>_prebuffer := dataset_prebuffer("ds:profile")`
1541// loaded once at init time so cycle-time accessor calls hit
1542// prefetched memory.
1543// - `<cursor>__vector := vector_at("ds:profile", <cursor>__ordinal)`
1544// (or `query_vector_at` for the query
1545// facet) — published as the cursor's `vector` projection so
1546// workloads can reference `<cursor>.vector`.
1547//
1548// Forms:
1549// - `vectordata_source(dataset, profile, facet)` — explicit facet
1550// - `vectordata_base(dataset, profile)` — facet = "base"
1551// - `vectordata_query(dataset, profile)` — facet = "query"
1552//
1553// Facet-specific projections like `metadata` / `ground_truth` /
1554// `predicate` stay explicit (the user writes
1555// `meta := metadata_value_at(<cursor>.ordinal, "ds:profile")` by
1556// hand) because their existence is dataset-conditional — not
1557// every dataset declares a metadata column or a predicate facet.
1558
1559#[cfg(feature = "vectordata")]
1560fn vectordata_sugar(
1561 source_name: &str,
1562 constructor: &crate::dsl::ast::Expr,
1563) -> Result<Option<crate::dsl::cursor_sugar::CursorSugar>, String> {
1564 use crate::dsl::ast::{Arg, CallExpr, Expr};
1565 use crate::dsl::compile::positional_str_lit;
1566 use crate::dsl::cursor_sugar::{AuxBinding, CursorSugar};
1567
1568 let Expr::Call(call) = constructor else {
1569 return Ok(None);
1570 };
1571
1572 let (dataset, profile, facet) = match call.func.as_str() {
1573 "vectordata_source" => {
1574 let d = positional_str_lit(call.args.first()).ok_or_else(|| format!(
1575 "cursor '{source_name}': vectordata_source(dataset, profile, facet) — first arg must be a string literal"
1576 ))?;
1577 let p = positional_str_lit(call.args.get(1)).ok_or_else(|| format!(
1578 "cursor '{source_name}': vectordata_source(dataset, profile, facet) — second arg must be a string literal"
1579 ))?;
1580 let f = positional_str_lit(call.args.get(2)).ok_or_else(|| format!(
1581 "cursor '{source_name}': vectordata_source(dataset, profile, facet) — third arg must be a string literal (\"base\" or \"query\")"
1582 ))?;
1583 (d, p, f)
1584 }
1585 "vectordata_base" | "vectordata_query" => {
1586 let f = call.func.strip_prefix("vectordata_").unwrap().to_string();
1587 let d = positional_str_lit(call.args.first()).ok_or_else(|| format!(
1588 "cursor '{source_name}': {}(dataset, profile) — first arg must be a string literal",
1589 call.func,
1590 ))?;
1591 let p = positional_str_lit(call.args.get(1)).ok_or_else(|| format!(
1592 "cursor '{source_name}': {}(dataset, profile) — second arg must be a string literal",
1593 call.func,
1594 ))?;
1595 (d, p, f)
1596 }
1597 _ => return Ok(None),
1598 };
1599
1600 if facet != "base" && facet != "query" {
1601 return Err(format!(
1602 "cursor '{source_name}': vectordata facet must be \"base\" or \"query\", got \"{facet}\""
1603 ));
1604 }
1605 let (count_func, vector_func) = match facet.as_str() {
1606 "base" => ("vector_count", "vector_at"),
1607 "query" => ("query_count", "query_vector_at"),
1608 _ => unreachable!(),
1609 };
1610
1611 let combined = format!("{dataset}:{profile}");
1612 let span = call.span;
1613 let lit = |s: String| Expr::StringLit(s, span);
1614 let positional = |e: Expr| Arg::Positional(e);
1615
1616 let effective_constructor = Expr::Call(CallExpr {
1617 func: "range".into(),
1618 args: vec![
1619 positional(Expr::IntLit(0, span)),
1620 positional(Expr::Call(CallExpr {
1621 func: count_func.into(),
1622 args: vec![positional(lit(combined.clone()))],
1623 span,
1624 })),
1625 ],
1626 span,
1627 });
1628
1629 let prebuffer_binding = AuxBinding {
1630 name: format!("__{source_name}_prebuffer"),
1631 value: Expr::Call(CallExpr {
1632 func: "dataset_prebuffer".into(),
1633 args: vec![positional(lit(combined.clone()))],
1634 span,
1635 }),
1636 projection: None,
1637 };
1638
1639 // Cursor sugar emits the call in (handle, index) order. The
1640 // combined source string auto-promotes to the right facet handle
1641 // through the wire's default resolver (library_catalog.md
1642 // "Shapes", `Resolved<R, T>`).
1643 let vector_binding = AuxBinding {
1644 name: format!("{source_name}__vector"),
1645 value: Expr::Call(CallExpr {
1646 func: vector_func.into(),
1647 args: vec![
1648 positional(lit(combined)),
1649 positional(Expr::Ident(format!("{source_name}__ordinal"), span)),
1650 ],
1651 span,
1652 }),
1653 projection: Some(("vector".into(), crate::ast::PortType::VecF32)),
1654 };
1655
1656 Ok(Some(CursorSugar {
1657 effective_constructor,
1658 aux_bindings: vec![prebuffer_binding, vector_binding],
1659 }))
1660}
1661
1662#[cfg(feature = "vectordata")]
1663inventory::submit! {
1664 crate::dsl::cursor_sugar::CursorSugarRegistration {
1665 handler: vectordata_sugar,
1666 name: "vectordata",
1667 }
1668}
1669
1670#[cfg(test)]
1671mod count_of_tests {
1672 use super::*;
1673 use crate::ast::{PolydatNode, PortType, Slot};
1674 use crate::dsl::registry::DefaultResolver;
1675
1676 /// The ports the compiler types a call against: a handle and a
1677 /// signed value in, a count out. The value is `i64` because that is
1678 /// what the facet stores; a caller with a literal reaches it
1679 /// through `to_i64`, since an integer literal is a `u64` and the
1680 /// adapter catalog will not heal that pair.
1681 #[test]
1682 fn the_count_of_nodes_take_a_handle_and_a_signed_value() {
1683 for node in [
1684 Box::new(MetadataCountOf::new()) as Box<dyn PolydatNode>,
1685 Box::new(PredicateCountOf::new()) as Box<dyn PolydatNode>,
1686 ] {
1687 let meta = node.meta();
1688 assert_eq!(meta.outs.len(), 1);
1689 assert_eq!(meta.outs[0].typ, PortType::U64, "{}", meta.name);
1690 assert_eq!(meta.ins.len(), 2, "{}", meta.name);
1691 let Slot::Wire(handle) = &meta.ins[0] else {
1692 panic!("{}: the first input is a wire", meta.name)
1693 };
1694 let Slot::Wire(value) = &meta.ins[1] else {
1695 panic!("{}: the second input is a wire", meta.name)
1696 };
1697 assert_eq!(handle.typ, PortType::Handle, "{}", meta.name);
1698 assert_eq!(value.typ, PortType::I64, "{}", meta.name);
1699 }
1700 }
1701
1702 /// The ordinals nodes take the same handle and value as the counts
1703 /// and give a `vec_i32` of ordinals.
1704 #[test]
1705 fn the_ordinals_of_nodes_take_what_the_counts_take() {
1706 for node in [
1707 Box::new(MetadataOrdinalsOf::new()) as Box<dyn PolydatNode>,
1708 Box::new(PredicateOrdinalsOf::new()) as Box<dyn PolydatNode>,
1709 ] {
1710 let meta = node.meta();
1711 assert_eq!(meta.outs.len(), 1);
1712 assert_eq!(meta.outs[0].typ, PortType::VecI32, "{}", meta.name);
1713 let types: Vec<PortType> = meta
1714 .ins
1715 .iter()
1716 .map(|s| match s {
1717 Slot::Wire(w) => w.typ,
1718 _ => panic!("{}: every input is a wire", meta.name),
1719 })
1720 .collect();
1721 assert_eq!(types, [PortType::Handle, PortType::I64], "{}", meta.name);
1722 }
1723 }
1724
1725 /// A handle of the wrong shape answers zero rather than failing.
1726 /// The facets these read are scalar ones; a caller that opened a
1727 /// vector facet by mistake gets a count of nothing, which is the
1728 /// same answer the facet's own readers give for a shape they do not
1729 /// hold.
1730 #[test]
1731 fn a_handle_of_another_shape_counts_nothing() {
1732 let group_shaped = DatasetHandle::Prebuffered {
1733 group: match load_dataset_group("nonexistent:profile") {
1734 Ok(g) => g,
1735 // No dataset available in this environment: the
1736 // fallback is still exercised through the match arm
1737 // below, which is what this test is about.
1738 Err(_) => return,
1739 },
1740 source: "nonexistent:profile".into(),
1741 };
1742 assert_eq!(generic_count_typed(&group_shaped, 1), 0);
1743 assert!(generic_ordinals_typed("test", &group_shaped, 1).is_empty());
1744 }
1745
1746 /// Both names resolve through the registry and carry a default
1747 /// resolver, so `metadata_count_of("ds:profile", v)` promotes the
1748 /// source string to the right facet the way its neighbours do.
1749 #[test]
1750 fn both_names_are_registered_with_a_facet_resolver() {
1751 for (name, facet) in [
1752 ("metadata_count_of", "metadata_content"),
1753 ("predicate_count_of", "metadata_predicates"),
1754 ("metadata_ordinals_of", "metadata_content"),
1755 ("predicate_ordinals_of", "metadata_predicates"),
1756 ] {
1757 let sig = crate::dsl::registry::lookup(name)
1758 .unwrap_or_else(|| panic!("{name} is registered"));
1759 assert_eq!(sig.outputs, 1, "{name}");
1760 assert_eq!(sig.params.len(), 2, "{name}");
1761 // The facet comes from the handle argument's type, so
1762 // this is the resolver the macro read off `Facet<_>`.
1763 match sig.default_resolver {
1764 Some(DefaultResolver::Facet(f)) => assert_eq!(f, facet, "{name}"),
1765 other => panic!("{name}: expected a facet resolver, got {other:?}"),
1766 }
1767 }
1768 }
1769}