polydat-core 0.12.0

Polydat runtime: value model, graph compiler, execution engines, kernels
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The dataset port types (`forms`, `fragment`, `admitted_rows`) and
//! the text pathway beside them, against vectordata's predicated
//! fixture (`vectordata::fixtures`): record metadata with a declared
//! layout, a mixed predicate set of several forms with strata, the
//! rows each predicate admits, and all three ground truths.
//!
//! The fixture is regenerated from the dataset pipeline and is not
//! byte-stable, so nothing here names a field, a form or a row. Each
//! test reads the dataset through vectordata, which is what the nodes
//! are built on, and holds the nodes to what it says, on every engine:
//! a wire's port type states what it carries, a host reads vectordata's
//! own types by matching the value, and the structural pathway and the
//! text pathway are different types.

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

use std::path::PathBuf;
use std::sync::{Arc, OnceLock};

use polydat_core::ast::{PortType, Value};
use polydat_core::dataset_value::DatasetValue;
use polydat_core::dsl::compile::{compile_polydat_interpreter, compile_polydat_to_assembler};
use polydat_core::{Engine, JitMode, Kernel, Provenance};
use vectordata::binding::Layout;
use vectordata::formats::mnode::MNode;
use vectordata::formats::pnode::Comparand;
use vectordata::ground_truth::{AdmittedRows, GroundTruth, TruthKind};
use vectordata::predicate_forms::FormCensus;
use vectordata::records::{codec_by_name, codec_names};
use vectordata::{NoProgress, TestDataGroup, TestDataView};

/// 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!("dataset-values-{}", 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('\\', "/")
    })
}

/// A profile of the fixture, as vectordata opens it.
fn view(profile: &str) -> Arc<dyn TestDataView> {
    TestDataGroup::load(dataset())
        .unwrap_or_else(|e| panic!("load the fixture: {e}"))
        .profile(profile)
        .unwrap_or_else(|| panic!("the fixture has profile {profile}"))
}

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
}

fn kernel_on(engine: Engine, src: &str) -> Box<dyn Kernel> {
    compile_polydat_to_assembler(src)
        .and_then(|asm| asm.compile_with(engine))
        .unwrap_or_else(|e| panic!("{engine}: {e}\n{src}"))
}

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

/// What a predicate binds, as text: each condition's field, operator
/// and typed comparands, in the binder's order.
fn bound(binder: &vectordata::binding::PredicateBinder, record: &[u8]) -> Vec<String> {
    let mut out = Vec::new();
    binder
        .bind_each(record, |condition, comparands: &[Comparand]| {
            out.push(format!(
                "{} {:?} {:?} {comparands:?}",
                condition.field, condition.op, condition.bind_type
            ));
        })
        .unwrap_or_else(|e| panic!("bind: {e}"));
    out
}

/// A predicate facet's forms are a `forms` constant and each predicate
/// a `fragment`, on every engine. The fragment names the predicate's
/// form and ordinal as vectordata's census gives them, and binding the
/// record it names through that form's binder, compiled once per form
/// from the `forms` value alone, gives what vectordata binds.
#[test]
fn a_predicate_fragment_binds_through_its_forms_on_every_engine() {
    let view = view("default");
    let predicates = view
        .open_facet_records("metadata_predicates")
        .expect("the fixture has predicate records");
    let census = FormCensus::of_facet(&predicates, &mut NoProgress).expect("a census");
    let layout = Layout::resolve(&*view).expect("a layout");
    let queries = census.count();
    assert!(
        census.forms().len() > 1,
        "the mixed set has several forms: {}",
        census.forms().len()
    );

    let src = format!(
        "input cycle: u64\n\
         forms := predicate_forms(\"{}\")\n\
         filter := predicate_at(forms, cycle)\n",
        dataset()
    );
    let asm = compile_polydat_to_assembler(&src).unwrap_or_else(|e| panic!("{e}\n{src}"));
    assert_eq!(asm.output_type("forms"), Some(PortType::Forms));
    assert_eq!(asm.output_type("filter"), Some(PortType::Fragment));

    for engine in engines() {
        let mut k = kernel_on(engine, &src);
        k.set_inputs(&[0]);
        let Value::Dataset(DatasetValue::PredicateForms(forms)) = k.pull("forms") else {
            panic!("{engine}: forms is not the forms of a predicate facet");
        };
        assert_eq!(forms.census.count(), queries, "{engine}");
        assert_eq!(forms.census.forms().len(), census.forms().len(), "{engine}");
        assert_eq!(forms.layout, layout, "{engine}");
        // What a host does at construction: one binder per form, kept
        // by the form's index.
        let binders: Vec<_> = forms
            .census
            .forms()
            .iter()
            .map(|form| {
                form.binder(&forms.layout)
                    .unwrap_or_else(|e| panic!("{engine}: form {}: {e}", form.form()))
            })
            .collect();

        // Past the last predicate, to show the index wraps.
        for c in (0..queries).chain([queries, queries + 1]) {
            k.set_inputs(&[c]);
            let Value::Dataset(DatasetValue::Predicate(fragment)) = k.pull("filter") else {
                panic!("{engine}: filter at cycle {c} is not a predicate fragment");
            };
            let ordinal = c % queries;
            assert_eq!(fragment.ordinal, ordinal, "{engine}: cycle {c}");
            assert_eq!(
                Some(fragment.form as usize),
                census.form_at(ordinal),
                "{engine}: cycle {c}"
            );
            assert!(
                Arc::ptr_eq(&fragment.forms, &forms),
                "{engine}: a fragment belongs to the forms it was made from"
            );
            let record = fragment
                .forms
                .predicates
                .record_shared(fragment.ordinal)
                .expect("the predicate's record");
            let expected = census.forms()[fragment.form as usize]
                .binder(&layout)
                .expect("the form binds");
            assert_eq!(
                bound(&binders[fragment.form as usize], &record),
                bound(
                    &expected,
                    &predicates.record_bytes(ordinal).expect("a record")
                ),
                "{engine}: predicate {ordinal}"
            );
        }
    }
}

/// A metadata facet's layout is its one form, a `forms` constant, and
/// each record a `fragment`, on every engine. Binding the record a
/// fragment names through the forms' binder reads every field, in
/// layout order, as the record holds it.
#[test]
fn a_record_fragment_binds_every_field_on_every_engine() {
    let view = view("default");
    let layout = Layout::resolve(&*view).expect("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 src = format!(
        "input cycle: u64\n\
         forms := record_forms(\"{}\")\n\
         row := record_at(forms, cycle)\n",
        dataset()
    );
    let asm = compile_polydat_to_assembler(&src).unwrap_or_else(|e| panic!("{e}\n{src}"));
    assert_eq!(asm.output_type("forms"), Some(PortType::Forms));
    assert_eq!(asm.output_type("row"), Some(PortType::Fragment));

    for engine in engines() {
        let mut k = kernel_on(engine, &src);
        for c in (0..count).chain([count, count + 1]) {
            k.set_inputs(&[c]);
            let Value::Dataset(DatasetValue::Record(fragment)) = k.pull("row") else {
                panic!("{engine}: row at cycle {c} is not a record fragment");
            };
            let ordinal = c % count;
            assert_eq!(fragment.ordinal, ordinal, "{engine}: cycle {c}");
            assert_eq!(fragment.forms.layout, layout, "{engine}");
            assert_eq!(
                fragment.forms.binder.parameters(),
                layout.names(),
                "{engine}: the binder reads every field, in layout order"
            );
            let record = fragment
                .forms
                .records
                .record_shared(fragment.ordinal)
                .expect("the record");
            let held = MNode::from_bytes(&content.record_bytes(ordinal).expect("a record"))
                .expect("the record decodes");
            let mut seen = Vec::new();
            fragment
                .forms
                .binder
                .bind_each(&record, |slot, field| {
                    let name = field.name_str().expect("a field name").to_string();
                    assert_eq!(name, layout.names()[slot], "{engine}: record {ordinal}");
                    assert_eq!(
                        field.is_null(),
                        matches!(held.fields[&name], vectordata::formats::mnode::MValue::Null),
                        "{engine}: record {ordinal}, `{name}`"
                    );
                    seen.push(name);
                })
                .expect("the record binds");
            assert_eq!(seen, layout.names(), "{engine}: record {ordinal}");
        }
    }
}

/// A fragment node takes the forms of its own kind: the forms of a
/// record facet are not the forms of a predicate facet, and the
/// mismatch is refused in those words.
#[test]
fn a_fragment_node_takes_the_forms_of_its_own_kind() {
    let message = refusal(&format!(
        "forms := record_forms(\"{}\")\nfilter := predicate_at(forms, 0)\n",
        dataset()
    ));
    assert!(
        message.contains("expected the forms of a predicate facet")
            && message.contains("got the forms of a record facet"),
        "{message}"
    );
}

/// Before any cycle, a kernel of any engine says which forms a
/// fragment output can depend on, and every engine gives the answer
/// the interpreter's program gives. Forms made from a constant source
/// are there to be read, each once, whichever fragment is asked about;
/// forms that arrive as an input are named for the enclosing scope to
/// resolve; forms computed from a source that is itself an input
/// cannot be known and are named as computed.
#[test]
fn a_kernel_names_the_forms_a_fragment_can_depend_on() {
    let source = dataset();
    let constant = format!(
        "input cycle: u64\n\
         forms := predicate_forms(\"{source}\")\n\
         filter := predicate_at(forms, cycle)\n\
         inline := predicate_at(predicate_forms(\"{source}\"), cycle)\n\
         layout := record_forms(\"{source}\")\n\
         row := record_at(layout, cycle)\n\
         n := vector_count(\"{source}\")\n"
    );
    let supplied = "input cycle: u64\nextern outer: forms\nfilter := predicate_at(outer, cycle)\n";
    let computed = "input cycle: u64\n\
                    extern source: str\n\
                    forms := predicate_forms(source)\n\
                    filter := predicate_at(forms, cycle)\n";

    // The interpreter's program is the reference.
    let reference = compile_polydat_interpreter(&constant).expect("builds");
    let program = reference.program();

    for engine in engines() {
        // Constant forms: held by the kernel, read before any cycle.
        let k = kernel_on(engine, &constant);
        let filter = k.dataset_sources("filter").expect("an output");
        assert!(
            filter.inputs.is_empty() && filter.computed.is_empty(),
            "{engine}: {filter:?}"
        );
        let [DatasetValue::PredicateForms(forms)] = filter.constants.as_slice() else {
            panic!("{engine}: filter depends on one predicate facet's forms: {filter:?}");
        };
        assert!(forms.census.count() > 0, "{engine}");
        for output in ["forms", "filter", "inline", "layout", "row", "n"] {
            assert_eq!(
                k.dataset_sources(output),
                program.dataset_sources(output),
                "{engine}: {output}"
            );
        }
        // Forms written inline are the same forms as the named wire's:
        // a facet is surveyed once and shared.
        assert_eq!(
            k.dataset_sources("inline").expect("an output").constants,
            filter.constants,
            "{engine}"
        );
        let row = k.dataset_sources("row").expect("an output");
        assert!(
            matches!(row.constants.as_slice(), [DatasetValue::RecordForms(_)])
                && row.inputs.is_empty()
                && row.computed.is_empty(),
            "{engine}: {row:?}"
        );
        // An output that reads no forms, and a name that is no output.
        assert_eq!(k.dataset_sources("n"), Some(Default::default()), "{engine}");
        assert!(k.dataset_sources("no_such_output").is_none(), "{engine}");

        // The forms a fragment carries at run time are the ones the
        // kernel named before the first cycle.
        let mut k = k;
        k.set_inputs(&[0]);
        let Value::Dataset(DatasetValue::Predicate(fragment)) = k.pull("filter") else {
            panic!("{engine}: filter is not a predicate fragment");
        };
        assert!(
            Arc::ptr_eq(&fragment.forms, forms),
            "{engine}: the fragment's forms are the forms named at construction"
        );

        // Forms supplied by an enclosing scope: an input of type forms.
        let k = kernel_on(engine, supplied);
        let filter = k.dataset_sources("filter").expect("an output");
        assert!(
            filter.constants.is_empty() && filter.computed.is_empty(),
            "{engine}: {filter:?}"
        );
        assert_eq!(filter.inputs, ["outer"], "{engine}");

        // Forms of a source that is not known when the program is
        // built.
        let k = kernel_on(engine, computed);
        let filter = k.dataset_sources("filter").expect("an output");
        assert!(
            filter.constants.is_empty() && filter.inputs.is_empty(),
            "{engine}: {filter:?}"
        );
        assert_eq!(filter.computed, ["predicate_forms"], "{engine}");
    }
}

/// A scope that must know a fragment's forms when it is built takes
/// the forms across the scope boundary, not the fragment, and the
/// scope model already carries them: on every engine, a child bound
/// under a parent holds the parent's `forms` constant in its own input
/// before any cycle, as the same shared value, and makes fragments of
/// those forms itself. A child that declares the same forms again from
/// the same source has them as a constant of its own, and they are the
/// same value, since a facet is surveyed once. A child that takes the
/// fragment holds nothing at construction, because a fragment is made
/// per cycle.
#[test]
fn a_child_scope_holds_its_parents_forms_at_construction() {
    use polydat_core::kernel::bind_under;

    let source = dataset();
    let parent_src = format!(
        "input cycle: u64\n\
         const forms := predicate_forms(\"{source}\")\n\
         filter := predicate_at(forms, cycle)\n"
    );
    let takes_forms =
        "input cycle: u64\nextern forms: forms\nfilter := predicate_at(forms, cycle)\n";
    let declares_forms = format!(
        "input cycle: u64\n\
         const forms := predicate_forms(\"{source}\")\n\
         filter := predicate_at(forms, cycle)\n"
    );
    let takes_fragment = "input cycle: u64\nextern filter: fragment\nbound := filter\n";

    for engine in engines() {
        let parent = kernel_on(engine, &parent_src);
        let constants = parent
            .dataset_sources("filter")
            .expect("an output")
            .constants;
        let [DatasetValue::PredicateForms(forms)] = constants.as_slice() else {
            panic!("{engine}: the parent has one predicate facet's forms");
        };
        let bind = |src: &str| {
            bind_under(parent.as_ref(), kernel_on(engine, src).into_program(), &[])
                .unwrap_or_else(|e| panic!("{engine}: {e}\n{src}"))
        };

        // The constant crosses the boundary: named as an input, typed
        // as forms, and held before any cycle.
        let mut child = bind(takes_forms);
        let sources = child.dataset_sources("filter").expect("an output");
        assert!(
            sources.constants.is_empty() && sources.computed.is_empty(),
            "{engine}: {sources:?}"
        );
        assert_eq!(sources.inputs, ["forms"], "{engine}");
        assert_eq!(
            child.input_port_type("forms"),
            Some(PortType::Forms),
            "{engine}"
        );
        let Some(Value::Dataset(DatasetValue::PredicateForms(held))) = child.input_value("forms")
        else {
            panic!("{engine}: the child holds no forms at construction");
        };
        assert!(
            Arc::ptr_eq(&held, forms),
            "{engine}: the child holds its parent's forms"
        );
        // And the fragments it makes are of those forms.
        child.set_inputs(&[1]);
        let Value::Dataset(DatasetValue::Predicate(fragment)) = child.pull("filter") else {
            panic!("{engine}: the child's filter is not a predicate fragment");
        };
        assert!(Arc::ptr_eq(&fragment.forms, forms), "{engine}");

        // Declared again in the child: a constant of its own, and the
        // same forms.
        let child = bind(&declares_forms);
        let sources = child.dataset_sources("filter").expect("an output");
        let [DatasetValue::PredicateForms(own)] = sources.constants.as_slice() else {
            panic!("{engine}: the child has one predicate facet's forms: {sources:?}");
        };
        assert!(Arc::ptr_eq(own, forms), "{engine}: one survey, one value");
        assert!(sources.inputs.is_empty(), "{engine}: {sources:?}");

        // The fragment itself: named as an input, and nothing held.
        let child = bind(takes_fragment);
        let sources = child.dataset_sources("bound").expect("an output");
        assert!(sources.constants.is_empty(), "{engine}: {sources:?}");
        assert_eq!(sources.inputs, ["filter"], "{engine}");
        assert!(
            matches!(child.input_value("filter"), None | Some(Value::None)),
            "{engine}: a fragment input holds nothing before a cycle"
        );
    }
}

/// The text pathway is a different type from the structural one: a
/// record or a predicate rendered by a packaged vernacular is a `str`,
/// equal to what vectordata's renderer of that name gives, on every
/// engine. An unknown vernacular is refused when the program is built,
/// with the names that exist.
#[test]
fn a_record_renders_as_text_in_a_packaged_vernacular() {
    let view = view("default");
    let content = view
        .open_facet_records("metadata_content")
        .expect("metadata records");
    let predicates = view
        .open_facet_records("metadata_predicates")
        .expect("predicate records");
    let layout = Layout::resolve(&*view).expect("a layout");
    let names = codec_names();
    assert!(names.len() > 1, "{names:?}");

    for vernacular in names.iter().copied().filter(|n| *n != "anode") {
        let src = format!(
            "input cycle: u64\n\
             row := record_text_at(\"{0}\", \"{vernacular}\", cycle)\n\
             filter := predicate_text_at(\"{0}\", \"{vernacular}\", cycle)\n\
             columns := record_layout_text(\"{0}\", \"{vernacular}\")\n",
            dataset()
        );
        let asm = match compile_polydat_to_assembler(&src) {
            Ok(asm) => asm,
            // A vernacular that renders only one kind of record
            // refuses the other when the constant is built.
            Err(_) => continue,
        };
        for out in ["row", "filter", "columns"] {
            assert_eq!(
                asm.output_type(out),
                Some(PortType::Str),
                "{vernacular}: {out}"
            );
        }
        let codec = || codec_by_name(vernacular).expect("a packaged vernacular");
        let exemplar = vectordata::formats::anode::encode(&layout.exemplar());
        let Ok(columns) = vectordata::records::RecordCodec::decode(&codec(), &exemplar) else {
            continue;
        };
        for engine in [
            Engine::Interpreter(JitMode::Off),
            Engine::Closures(Provenance::Auto),
        ] {
            let mut k = kernel_on(engine, &src);
            for c in 0..4 {
                k.set_inputs(&[c]);
                let (Ok(row), Ok(filter)) = (
                    content.decode(codec()).get(c),
                    predicates.decode(codec()).get(c),
                ) else {
                    continue;
                };
                assert_eq!(
                    k.pull("row"),
                    Value::Str(row.into()),
                    "{engine}: {vernacular}"
                );
                assert_eq!(
                    k.pull("filter"),
                    Value::Str(filter.into()),
                    "{engine}: {vernacular}"
                );
                assert_eq!(
                    k.pull("columns"),
                    Value::Str(columns.as_str().into()),
                    "{engine}: {vernacular}"
                );
            }
        }
    }

    let message = refusal(&format!(
        "columns := record_layout_text(\"{}\", \"no-such-vernacular\")\n",
        dataset()
    ));
    assert!(
        message.contains("no packaged vernacular is named `no-such-vernacular`"),
        "{message}"
    );
    for name in &names {
        assert!(message.contains(name), "`{name}` in: {message}");
    }
}

/// The constant projections of a dataset's records are what its layout
/// and its predicates' census say: the field names in layout order,
/// the fields the predicates constrain, and the distinct families and
/// bands, with each predicate's own, on every engine.
#[test]
fn the_projections_and_strata_are_what_the_dataset_declares() {
    let view = view("default");
    let layout = Layout::resolve(&*view).expect("a layout");
    let predicates = view
        .open_facet_records("metadata_predicates")
        .expect("predicate records");
    let census = FormCensus::of_facet(&predicates, &mut NoProgress).expect("a census");
    let strata = census.strata().expect("the mixed set publishes strata");
    let queries = census.count();

    let src = format!(
        "input cycle: u64\n\
         fields := record_field_names(\"{0}\")\n\
         constrained := predicate_field_names(\"{0}\")\n\
         families := predicate_families(\"{0}\")\n\
         bands := predicate_bands(\"{0}\")\n\
         family := predicate_family_at(\"{0}\", cycle)\n\
         band := predicate_band_at(\"{0}\", cycle)\n",
        dataset()
    );
    let text = |s: String| Value::Str(s.into());
    for engine in engines() {
        let mut k = kernel_on(engine, &src);
        for c in 0..queries + 1 {
            k.set_inputs(&[c]);
            let q = c % queries;
            assert_eq!(k.pull("fields"), text(layout.names().join(",")), "{engine}");
            assert_eq!(
                k.pull("constrained"),
                text(census.fields().into_iter().collect::<Vec<_>>().join(",")),
                "{engine}"
            );
            assert_eq!(
                k.pull("families"),
                text(strata.families().join(",")),
                "{engine}"
            );
            assert_eq!(k.pull("bands"), text(strata.bands().join(",")), "{engine}");
            assert_eq!(
                k.pull("family"),
                text(strata.family_at(q).expect("a family").to_string()),
                "{engine}: query {q}"
            );
            assert_eq!(
                k.pull("band"),
                text(strata.band_at(q).unwrap_or_default().to_string()),
                "{engine}: query {q}"
            );
        }
    }
}

/// The form key of each query's predicate is the key vectordata gives
/// the form that predicate takes, as a `str` wire, on every engine,
/// with the query index wrapping; it is the key of the form the
/// fragment of the same query carries; and the constant
/// `predicate_form_keys` is the distinct keys, sorted.
#[test]
fn a_predicates_form_key_is_the_key_of_the_form_it_takes() {
    let predicates = view("default")
        .open_facet_records("metadata_predicates")
        .expect("predicate records");
    let census = FormCensus::of_facet(&predicates, &mut NoProgress).expect("a census");
    let queries = census.count();
    let key_of = |q: u64| {
        let form = census.form_at(q).expect("a form");
        (
            form,
            census.forms()[form]
                .key()
                .expect("the fixture's forms have keys")
                .to_string(),
        )
    };
    assert!(
        (0..queries)
            .map(|q| key_of(q).1)
            .collect::<std::collections::BTreeSet<_>>()
            .len()
            > 1,
        "the fixture's predicates take more than one form"
    );

    let all_keys = census
        .forms()
        .iter()
        .map(|form| form.key().expect("the fixture's forms have keys"))
        .collect::<std::collections::BTreeSet<_>>()
        .into_iter()
        .collect::<Vec<_>>()
        .join(",");

    let src = format!(
        "input cycle: u64\n\
         const forms := predicate_forms(\"{0}\")\n\
         const keys := predicate_form_keys(\"{0}\")\n\
         predicate := predicate_at(forms, cycle)\n\
         form := predicate_form_at(forms, cycle)\n",
        dataset()
    );
    let asm = compile_polydat_to_assembler(&src).unwrap_or_else(|e| panic!("{e}\n{src}"));
    assert_eq!(asm.output_type("form"), Some(PortType::Str));
    assert_eq!(asm.output_type("keys"), Some(PortType::Str));
    for engine in engines() {
        let mut k = kernel_on(engine, &src);
        for c in 0..queries + 1 {
            k.set_inputs(&[c]);
            assert_eq!(
                k.pull("keys"),
                Value::Str(all_keys.clone().into()),
                "{engine}"
            );
            let (form, key) = key_of(c % queries);
            assert_eq!(
                k.pull("form"),
                Value::Str(key.into()),
                "{engine}: query {c}"
            );
            match k.pull("predicate") {
                Value::Dataset(DatasetValue::Predicate(fragment)) => {
                    assert_eq!(fragment.form as usize, form, "{engine}: query {c}");
                }
                other => panic!("{engine}: expected a predicate fragment, got {other:?}"),
            }
        }
    }
}

/// On a dataset whose rows vectordata's pipeline computed: the
/// admitted rows, the live neighbors and the coverage the nodes give
/// are what vectordata's readers give, for every profile that has the
/// facet, on every engine. The fixture's prefiltered truth has full,
/// short and empty rows.
#[test]
fn ground_truth_and_admitted_rows_are_what_vectordata_reads() {
    for profile in polydat_core::library::vectors::fixtures::PREDICATED_PROFILES {
        let view = view(profile);
        let source = format!("{}:{profile}", dataset());
        for (kind, prefix) in [
            (TruthKind::Unfiltered, "neighbor"),
            (TruthKind::Prefiltered, "prefiltered_neighbor"),
            (TruthKind::Postfiltered, "postfiltered_neighbor"),
        ] {
            let Ok(truth) = GroundTruth::open(&*view, kind) else {
                continue;
            };
            let k_depth = truth.width();
            let coverage = truth.coverage(k_depth, &mut NoProgress).expect("coverage");
            let src = format!(
                "input cycle: u64\n\
                 live := {prefix}_live_indices_at(\"{source}\", cycle)\n\
                 depth := {prefix}_live_depth_at(\"{source}\", cycle)\n\
                 full := {prefix}_full_rows(\"{source}\", {k_depth})\n\
                 empty := {prefix}_empty_rows(\"{source}\", {k_depth})\n\
                 ceiling := {prefix}_recall_ceiling(\"{source}\", {k_depth})\n"
            );
            for engine in engines() {
                let mut k = kernel_on(engine, &src);
                for q in 0..truth.queries() {
                    k.set_inputs(&[q as u64]);
                    let live: Vec<i64> = truth
                        .neighbors(q)
                        .expect("a row")
                        .into_iter()
                        .map(|n| n as i64)
                        .collect();
                    assert_eq!(
                        k.pull("depth"),
                        Value::U64(live.len() as u64),
                        "{engine}: {profile} {prefix} {q}"
                    );
                    assert_eq!(
                        k.pull("live"),
                        Value::VecI64(polydat_core::ast::SliceArc::from_vec(live)),
                        "{engine}: {profile} {prefix} {q}"
                    );
                }
                assert_eq!(
                    k.pull("full"),
                    Value::U64(coverage.full),
                    "{engine}: {profile}"
                );
                assert_eq!(
                    k.pull("empty"),
                    Value::U64(coverage.empty),
                    "{engine}: {profile}"
                );
                assert_eq!(
                    k.pull("ceiling"),
                    Value::F64(coverage.ceiling()),
                    "{engine}: {profile}"
                );
            }
        }

        let Ok(admitted) = AdmittedRows::open(&*view) else {
            continue;
        };
        let src = format!(
            "input cycle: u64\n\
             rows := admitted_rows_at(\"{source}\", cycle)\n\
             n := admitted_rows_len(rows)\n\
             first := admitted_rows_contain(rows, cycle)\n\
             list := metadata_results_at(\"{source}\", cycle)\n\
             list_n := metadata_results_len_at(\"{source}\", cycle)\n\
             queries := metadata_results_count(\"{source}\")\n"
        );
        let asm = compile_polydat_to_assembler(&src).unwrap_or_else(|e| panic!("{e}\n{src}"));
        assert_eq!(asm.output_type("rows"), Some(PortType::AdmittedRows));
        for engine in engines() {
            let mut k = kernel_on(engine, &src);
            for q in 0..admitted.queries() {
                k.set_inputs(&[q as u64]);
                let expected = admitted.get(q).expect("a set");
                let Value::Dataset(DatasetValue::AdmittedRows(set)) = k.pull("rows") else {
                    panic!("{engine}: rows is not the admitted rows");
                };
                assert_eq!(*set, expected, "{engine}: {profile} {q}");
                assert_eq!(
                    k.pull("n"),
                    Value::U64(expected.len() as u64),
                    "{engine}: {profile} {q}"
                );
                assert_eq!(
                    k.pull("first"),
                    Value::Bool(expected.contains(q as u64)),
                    "{engine}: {profile} {q}"
                );
                // The list accessors read the same rows, whichever
                // encoding the dataset publishes them in.
                let list: Vec<i32> = expected.iter().map(|o| o as i32).collect();
                assert_eq!(
                    k.pull("list"),
                    Value::VecI32(polydat_core::ast::SliceArc::from_vec(list)),
                    "{engine}: {profile} {q}"
                );
                assert_eq!(
                    k.pull("list_n"),
                    Value::U64(expected.len() as u64),
                    "{engine}: {profile} {q}"
                );
                assert_eq!(
                    k.pull("queries"),
                    Value::U64(admitted.queries() as u64),
                    "{engine}: {profile}"
                );
            }
        }
    }
}