polydat-core 0.13.1

Polydat runtime: value model, graph compiler, execution engines, kernels
Documentation
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The record-field nodes against vectordata's predicated fixture
//! (`vectordata::fixtures`): a dataset on disk whose metadata is one
//! record of named, typed fields per base vector, with a layout facet
//! that types every field and says which are never null.
//!
//! The fixture is regenerated from the dataset pipeline and is not
//! byte-stable, so nothing here names a field or a value. Each test
//! reads the layout and the records through vectordata, which is what
//! the nodes are built on, and holds the nodes to what it says: a
//! field reads as the wire type its layout type carries, at every
//! ordinal, on every engine, and every other reading of it is refused
//! when the program is built.

#![cfg(feature = "vectordata-fixtures")]

use std::path::PathBuf;
use std::sync::OnceLock;

use polydat_core::ast::Value;
use polydat_core::dsl::compile::compile_polydat_to_assembler;
use polydat_core::{Engine, JitMode, Provenance};
use vectordata::binding::{BindType, Layout, LayoutSource, Nullability};
use vectordata::formats::mnode::{MNode, MValue};
use vectordata::{TestDataGroup, TestDataView, TestDataViewExt};

/// The wire types a record field reads as, with the keyword each
/// node's name carries.
const WIRES: [&str; 5] = ["str", "bool", "i64", "f64", "bytes"];

/// The fixture, written once per process under the target's scratch
/// space. Writing it again overwrites the same files.
fn dataset() -> &'static str {
    static PATH: OnceLock<String> = OnceLock::new();
    PATH.get_or_init(|| {
        let dir = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
            .join(format!("record-fields-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap_or_else(|e| panic!("create {}: {e}", dir.display()));
        let dataset = polydat_core::library::vectors::fixtures::predicated(&dir)
            .unwrap_or_else(|e| panic!("write the fixture to {}: {e}", dir.display()));
        dataset.to_string_lossy().replace('\\', "/")
    })
}

/// The fixture's default profile, as vectordata opens it.
fn view() -> std::sync::Arc<dyn TestDataView> {
    TestDataGroup::load(dataset())
        .unwrap_or_else(|e| panic!("load the fixture: {e}"))
        .profile("default")
        .expect("the fixture has a default profile")
}

/// The wire type a field of layout type `bind` reads as, or `None`
/// for a type no scalar wire carries.
fn wire_of(bind: &BindType) -> Option<&'static str> {
    match bind {
        BindType::Text | BindType::Ascii => Some("str"),
        BindType::Bool => Some("bool"),
        BindType::Int16 | BindType::Int32 | BindType::Int64 => Some("i64"),
        BindType::Float16 | BindType::Float32 | BindType::Float64 => Some("f64"),
        BindType::Blob => Some("bytes"),
        _ => None,
    }
}

/// What a record holds in a field, as the wire value the field's node
/// yields, decoded by vectordata's own record decoder.
fn wire_value(value: &MValue) -> Value {
    match value {
        MValue::Text(s) | MValue::Ascii(s) => Value::Str(s.as_str().into()),
        MValue::Bool(b) => Value::Bool(*b),
        MValue::Int(i) => Value::I64(*i),
        MValue::Int32(i) => Value::I64(i64::from(*i)),
        MValue::Short(i) => Value::I64(i64::from(*i)),
        MValue::Float(f) => Value::F64(*f),
        MValue::Float32(f) => Value::F64(f64::from(*f)),
        MValue::Bytes(b) => Value::Bytes(b.as_slice().into()),
        other => panic!("no scalar wire carries {other:?}"),
    }
}

fn engines() -> Vec<Engine> {
    let mut all = vec![
        Engine::Interpreter(JitMode::Off),
        Engine::Interpreter(JitMode::Force),
    ];
    for m in [Provenance::Raw, Provenance::PushPull, Provenance::Auto] {
        all.push(Engine::Closures(m));
        all.push(Engine::Native(m));
    }
    if cfg!(feature = "jit") {
        all.push(Engine::PureNative(Provenance::PushPull));
    }
    all
}

/// The error building `src` gives, on the interpreter.
fn refusal(src: &str) -> String {
    match compile_polydat_to_assembler(src)
        .and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)))
    {
        Ok(_) => panic!("built, and should have been refused:\n{src}"),
        Err(e) => e.to_string(),
    }
}

/// The fixture is what these tests need it to be: a declared layout
/// that types every field, with scalar-wire fields declared never
/// null among them.
#[test]
fn the_fixture_declares_a_layout_with_scalar_fields() {
    let view = view();
    let layout = Layout::resolve(&*view).expect("the fixture has a layout");
    assert_eq!(layout.source(), LayoutSource::LayoutFacet);
    assert!(layout.unproven().is_empty(), "{:?}", layout.unproven());
    let readable = layout
        .types()
        .iter()
        .zip(layout.nullability())
        .filter(|(t, n)| wire_of(t).is_some() && **n == Nullability::NeverNull)
        .count();
    assert!(
        readable > 0,
        "no never-null scalar field: {:?} {:?}",
        layout.types(),
        layout.nullability()
    );
}

/// Every field a scalar wire carries reads, at every ordinal and on
/// every engine, as the value vectordata decodes from the record, and
/// the record index wraps modulo the record count.
#[test]
fn a_field_reads_as_what_the_record_holds_on_every_engine() {
    let view = view();
    let layout = Layout::resolve(&*view).expect("the fixture has a layout");
    let content = view
        .open_facet_records("metadata_content")
        .expect("the fixture has metadata records");
    let count = content.count().expect("a record count");
    let records: Vec<MNode> = (0..count)
        .map(|i| MNode::from_bytes(&content.record_bytes(i).expect("a record")).expect("decodes"))
        .collect();

    let mut src = String::from("input cycle: u64\n");
    let mut outputs: Vec<(String, String)> = Vec::new();
    for (i, (name, bind)) in layout.names().iter().zip(layout.types()).enumerate() {
        let Some(wire) = wire_of(bind) else { continue };
        if layout.nullability()[i] == Nullability::Nullable {
            continue;
        }
        src.push_str(&format!(
            "field_{i} := record_field_{wire}(\"{}\", \"{name}\")\n\
             out_{i} := record_{wire}_at(field_{i}, cycle)\n",
            dataset()
        ));
        outputs.push((format!("out_{i}"), name.clone()));
    }
    assert!(!outputs.is_empty(), "the fixture has a field to read");

    // Past the last record, to show the index wraps.
    let cycles: Vec<u64> = (0..count).chain([count, count + 1]).collect();
    for engine in engines() {
        let mut k = compile_polydat_to_assembler(&src)
            .and_then(|asm| asm.compile_with(engine))
            .unwrap_or_else(|e| panic!("{engine}: {e}\n{src}"));
        for &c in &cycles {
            k.set_inputs(&[c]);
            let record = &records[(c % count) as usize];
            for (out, name) in &outputs {
                let held = record
                    .fields
                    .get(name)
                    .unwrap_or_else(|| panic!("record {c} has no `{name}`"));
                assert_eq!(
                    k.pull(out).to_display_string(),
                    wire_value(held).to_display_string(),
                    "{engine}: `{name}` at cycle {c}"
                );
            }
        }
    }
}

/// A field resolves as exactly the wire type its layout type carries.
/// Every other reading is refused when the program is built, naming
/// the field's type, and so is a field of a type no scalar wire
/// carries, and a field the dataset declares may be null.
#[test]
fn a_field_of_another_type_is_refused_when_the_program_is_built() {
    let view = view();
    let layout = Layout::resolve(&*view).expect("the fixture has a layout");
    for (i, (name, bind)) in layout.names().iter().zip(layout.types()).enumerate() {
        let nullable = layout.nullability()[i] == Nullability::Nullable;
        for wire in WIRES {
            let src = format!(
                "input cycle: u64\n\
                 field := record_field_{wire}(\"{}\", \"{name}\")\n\
                 out := record_{wire}_at(field, cycle)\n",
                dataset()
            );
            let built = compile_polydat_to_assembler(&src)
                .and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)));
            if wire_of(bind) == Some(wire) && !nullable {
                built.unwrap_or_else(|e| panic!("`{name}` ({bind:?}) as {wire}: {e}"));
                continue;
            }
            let message = match built {
                Ok(_) => panic!("`{name}` ({bind:?}, nullable: {nullable}) built as {wire}"),
                Err(e) => e.to_string(),
            };
            let expected = if wire_of(bind) == Some(wire) {
                "is declared nullable".to_string()
            } else {
                format!("is {bind:?}, which does not read as {wire}")
            };
            assert!(
                message.contains(&format!("record_field_{wire}"))
                    && message.contains(&format!("`{name}`"))
                    && message.contains(&expected),
                "`{name}` as {wire}: {message}"
            );
        }
    }
}

/// A field the records do not have is refused when the program is
/// built, naming the fields they have.
#[test]
fn a_missing_field_is_refused_with_the_fields_the_records_have() {
    let view = view();
    let layout = Layout::resolve(&*view).expect("the fixture has a layout");
    let missing = "no_such_field_in_any_record";
    assert!(layout.position_of(missing).is_none());
    let message = refusal(&format!(
        "input cycle: u64\n\
         field := record_field_str(\"{}\", \"{missing}\")\n\
         out := record_str_at(field, cycle)\n",
        dataset()
    ));
    assert!(
        message.contains(&format!("have no field `{missing}`")),
        "{message}"
    );
    for name in layout.names() {
        assert!(message.contains(name.as_str()), "`{name}` in: {message}");
    }
}

/// A field resolved as one wire type is not read by another type's
/// accessor: the mismatch is named by both nodes' types.
#[test]
fn an_accessor_reads_only_a_field_resolved_for_its_type() {
    let view = view();
    let layout = Layout::resolve(&*view).expect("the fixture has a layout");
    let (name, wire) = layout
        .names()
        .iter()
        .zip(layout.types())
        .zip(layout.nullability())
        .find_map(|((name, bind), n)| {
            (*n != Nullability::Nullable)
                .then(|| wire_of(bind).map(|w| (name, w)))
                .flatten()
        })
        .expect("the fixture has a scalar field");
    let other = WIRES.iter().find(|w| **w != wire).expect("another type");
    let src = format!(
        "input cycle: u64\n\
         field := record_field_{wire}(\"{}\", \"{name}\")\n\
         out := record_{other}_at(field, cycle)\n",
        dataset()
    );
    let outcome = std::panic::catch_unwind(|| {
        let mut k = compile_polydat_to_assembler(&src)
            .and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)))?;
        k.set_inputs(&[0]);
        Ok::<_, polydat_core::KernelError>(k.pull("out").to_display_string())
    });
    let message = match outcome {
        Ok(Ok(answer)) => panic!("read `{name}` ({wire}) as {other}: {answer}"),
        Ok(Err(e)) => e.to_string(),
        Err(panic) => panic
            .downcast_ref::<String>()
            .cloned()
            .or_else(|| panic.downcast_ref::<&str>().map(|s| s.to_string()))
            .unwrap_or_default(),
    };
    assert!(
        message.contains(&format!(
            "was resolved as {wire}, and this node reads {other}"
        )),
        "{message}"
    );
}

/// A source string names the fixture by its path, with a profile after
/// the last colon, as vectordata's own specs read a path that exists.
#[test]
fn a_source_string_names_a_dataset_by_path() {
    for profile in polydat_core::library::vectors::fixtures::PREDICATED_PROFILES {
        let src = format!("n := vector_count(\"{}:{profile}\")\n", dataset());
        let mut k = compile_polydat_to_assembler(&src)
            .and_then(|asm| asm.compile_with(Engine::Interpreter(JitMode::Off)))
            .unwrap_or_else(|e| panic!("{profile}: {e}"));
        let expected = TestDataGroup::load(dataset())
            .expect("load the fixture")
            .profile(profile)
            .unwrap_or_else(|| panic!("the fixture has profile {profile}"))
            .base_vectors_as::<f32>()
            .unwrap_or_else(|e| panic!("{profile}: {e}"))
            .count();
        assert_eq!(
            k.pull("n").to_display_string(),
            expected.to_string(),
            "{profile}"
        );
    }
}