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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! The values of the dataset port types (`forms`, `fragment`,
//! `admitted_rows`): what a vector dataset publishes about its
//! predicates and records, on a wire as the types `vectordata` defines.
//!
//! A host reads one by matching [`DatasetValue`], with no downcast and
//! no inspection of a payload: the port type in a program's manifest
//! says which kind a wire carries, and the variant holds vectordata's
//! own type. Polydat adds only the two pairings vectordata has no type
//! for: a facet's forms with the layout and the records they describe
//! (`PredicateForms`, `RecordForms`), and one record's place among
//! them for a cycle (`PredicateFragment`, `RecordFragment`).
//!
//! The variants exist when the `vectordata` feature is on. Without it
//! the port types are still names of the language, and no value of
//! them can be made, so [`DatasetValue`] has no variant and
//! `Value::Dataset` is never constructed.
//!
//! Nothing here checks a record. That a dataset's records meet what it
//! declares is established where the dataset is published; these
//! values hand on what vectordata reads.

#[cfg(feature = "vectordata")]
use std::sync::Arc;

use crate::ast::PortType;

#[cfg(feature = "vectordata")]
pub use self::types::{PredicateForms, PredicateFragment, RecordForms, RecordFragment};
#[cfg(feature = "vectordata")]
pub use self::wires::Shared;

/// A value of one of the dataset port types.
#[derive(Debug, Clone)]
pub enum DatasetValue {
    /// The base positions a query's predicate admits: vectordata's
    /// set over the query's `metadata_results` record, which is not
    /// read until it is asked. Port type `admitted_rows`.
    #[cfg(feature = "vectordata")]
    AdmittedRows(Arc<vectordata::ground_truth::OrdinalSet>),
    /// The forms of a predicate facet. Port type `forms`.
    #[cfg(feature = "vectordata")]
    PredicateForms(Arc<PredicateForms>),
    /// The one form of a record facet: its layout. Port type `forms`.
    #[cfg(feature = "vectordata")]
    RecordForms(Arc<RecordForms>),
    /// One predicate, as its form and its record. Port type `fragment`.
    #[cfg(feature = "vectordata")]
    Predicate(PredicateFragment),
    /// One metadata record. Port type `fragment`.
    #[cfg(feature = "vectordata")]
    Record(RecordFragment),
}

impl DatasetValue {
    /// The port type of the wire this value rides.
    pub fn port_type(&self) -> PortType {
        match self {
            #[cfg(feature = "vectordata")]
            DatasetValue::AdmittedRows(_) => PortType::AdmittedRows,
            #[cfg(feature = "vectordata")]
            DatasetValue::PredicateForms(_) | DatasetValue::RecordForms(_) => PortType::Forms,
            #[cfg(feature = "vectordata")]
            DatasetValue::Predicate(_) | DatasetValue::Record(_) => PortType::Fragment,
            #[cfg(not(feature = "vectordata"))]
            _ => match *self {},
        }
    }

    /// A short rendering for diagnostics and dry runs: what the value
    /// is and where it comes from, never the records themselves. A set
    /// of admitted rows shows its first positions and its size.
    pub fn display(&self) -> String {
        match self {
            #[cfg(feature = "vectordata")]
            DatasetValue::AdmittedRows(set) => format!("{set:?}"),
            #[cfg(feature = "vectordata")]
            DatasetValue::PredicateForms(forms) => format!(
                "forms of {}: {} over {} predicates",
                forms.origin,
                forms.census.forms().len(),
                forms.census.count()
            ),
            #[cfg(feature = "vectordata")]
            DatasetValue::RecordForms(forms) => format!(
                "forms of {}: 1 over {} fields",
                forms.origin,
                forms.layout.names().len()
            ),
            #[cfg(feature = "vectordata")]
            DatasetValue::Predicate(fragment) => format!(
                "predicate {} of {}, form {}",
                fragment.ordinal, fragment.forms.origin, fragment.form
            ),
            #[cfg(feature = "vectordata")]
            DatasetValue::Record(fragment) => {
                format!("record {} of {}", fragment.ordinal, fragment.forms.origin)
            }
            #[cfg(not(feature = "vectordata"))]
            _ => match *self {},
        }
    }
}

/// Two dataset values are equal when they are the same thing: the same
/// admitted positions, the same forms, or the same record of the same
/// forms. Forms compare by identity, since they are built once and
/// shared.
impl PartialEq for DatasetValue {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            #[cfg(feature = "vectordata")]
            (DatasetValue::AdmittedRows(a), DatasetValue::AdmittedRows(b)) => {
                Arc::ptr_eq(a, b) || a == b
            }
            #[cfg(feature = "vectordata")]
            (DatasetValue::PredicateForms(a), DatasetValue::PredicateForms(b)) => Arc::ptr_eq(a, b),
            #[cfg(feature = "vectordata")]
            (DatasetValue::RecordForms(a), DatasetValue::RecordForms(b)) => Arc::ptr_eq(a, b),
            #[cfg(feature = "vectordata")]
            (DatasetValue::Predicate(a), DatasetValue::Predicate(b)) => {
                Arc::ptr_eq(&a.forms, &b.forms) && a.form == b.form && a.ordinal == b.ordinal
            }
            #[cfg(feature = "vectordata")]
            (DatasetValue::Record(a), DatasetValue::Record(b)) => {
                Arc::ptr_eq(&a.forms, &b.forms) && a.ordinal == b.ordinal
            }
            #[cfg(feature = "vectordata")]
            _ => false,
            #[cfg(not(feature = "vectordata"))]
            _ => match *self {},
        }
    }
}

#[cfg(feature = "vectordata")]
mod types {
    use std::sync::Arc;

    use vectordata::binding::{Binder, Layout};
    use vectordata::predicate_forms::FormCensus;
    use vectordata::records::RecordFacet;

    /// The forms of a predicate facet, with what a host needs to bind
    /// a predicate of any of them: a `forms` value.
    ///
    /// Built once, when a program is built, by reading every predicate
    /// of the facet. A host prepares one statement per form of
    /// [`census`](Self::census) from the form's template, compiles the
    /// form's binder against [`layout`](Self::layout)
    /// (`form.binder(&forms.layout)`), and keeps both by the form's
    /// index. A form whose binder cannot be compiled is that call's
    /// error, with `form.count()` predicates behind it; nothing here
    /// refuses it. The strata the facet publishes are
    /// `census.strata()`.
    #[non_exhaustive]
    pub struct PredicateForms {
        /// Every distinct form of the facet's predicates, with its
        /// template and count, and the form of the predicate at each
        /// ordinal.
        pub census: FormCensus,
        /// The layout of the metadata records the predicates select
        /// among, which types each condition's field.
        pub layout: Layout,
        /// The predicates themselves: the record of the predicate at
        /// an ordinal is what a form's binder binds.
        pub predicates: RecordFacet,
        /// The dataset and profile, for diagnostics.
        pub origin: String,
        /// The first form with no key, as its rendered form and the
        /// reason vectordata gives, or `None` when every form has one.
        unkeyed: Option<(String, String)>,
    }

    impl PredicateForms {
        pub(crate) fn new(
            census: FormCensus,
            layout: Layout,
            predicates: RecordFacet,
            origin: String,
        ) -> Self {
            let unkeyed = first_unkeyed(&census);
            Self {
                census,
                layout,
                predicates,
                origin,
                unkeyed,
            }
        }

        /// The key of the form the predicate at `ordinal` takes: the
        /// identifier the dataset publishes for the form, stable across
        /// releases and usable as a metric label, such as
        /// `citation_percentile.range_topic_l3.eq`.
        ///
        /// `Err` with the reason when any form of the facet has no key
        /// (it holds a disjunction, or addresses a field by index),
        /// whichever form `ordinal` takes, so a facet either labels
        /// every predicate or none. `Err` also for an ordinal the facet
        /// does not hold.
        pub fn form_key_at(&self, ordinal: u64) -> Result<&str, String> {
            form_key_at(&self.census, self.unkeyed.as_ref(), &self.origin, ordinal)
        }

        /// The distinct keys of the facet's forms, sorted: every value
        /// [`Self::form_key_at`] can give. `Err` with the reason when
        /// any form has no key, as `form_key_at` is.
        pub fn form_keys(&self) -> Result<Vec<&str>, String> {
            form_keys(&self.census, self.unkeyed.as_ref(), &self.origin)
        }
    }

    /// The first form of `census` with no key, as its rendered form and
    /// the reason vectordata gives.
    fn first_unkeyed(census: &FormCensus) -> Option<(String, String)> {
        census.forms().iter().find_map(|form| {
            form.unkeyed()
                .map(|reason| (form.form().to_string(), reason.to_string()))
        })
    }

    /// The refusal for a facet that holds the unkeyed form `unkeyed`.
    fn keyed(unkeyed: Option<&(String, String)>, origin: &str) -> Result<(), String> {
        match unkeyed {
            Some((form, reason)) => Err(format!(
                "the predicates of '{origin}' hold a form with no key, `{form}`: {reason}"
            )),
            None => Ok(()),
        }
    }

    /// [`PredicateForms::form_keys`], over its parts.
    fn form_keys<'a>(
        census: &'a FormCensus,
        unkeyed: Option<&(String, String)>,
        origin: &str,
    ) -> Result<Vec<&'a str>, String> {
        keyed(unkeyed, origin)?;
        let keys: std::collections::BTreeSet<&str> = census
            .forms()
            .iter()
            .filter_map(|form| form.key())
            .collect();
        Ok(keys.into_iter().collect())
    }

    /// [`PredicateForms::form_key_at`], over its parts.
    fn form_key_at<'a>(
        census: &'a FormCensus,
        unkeyed: Option<&(String, String)>,
        origin: &str,
        ordinal: u64,
    ) -> Result<&'a str, String> {
        keyed(unkeyed, origin)?;
        census
            .form_at(ordinal)
            .and_then(|form| census.forms()[form].key())
            .ok_or_else(|| format!("'{origin}' has no predicate {ordinal}"))
    }

    #[cfg(test)]
    mod form_key_tests {
        use super::{first_unkeyed, form_key_at, form_keys};
        use vectordata::formats::pnode::{
            Comparand, ConjugateNode, ConjugateType, FieldRef, OpType, PNode, PredicateNode,
        };
        use vectordata::predicate_forms::FormCensus;

        fn leaf(field: &str, op: OpType) -> PNode {
            PNode::Predicate(PredicateNode {
                field: FieldRef::Named(field.into()),
                op,
                comparands: vec![Comparand::Int(1)],
            })
        }

        fn junction(conjugate_type: ConjugateType, children: Vec<PNode>) -> PNode {
            PNode::Conjugate(ConjugateNode {
                conjugate_type,
                children,
            })
        }

        /// Every predicate of a facet whose forms all have keys is
        /// labelled with its own form's key, and an ordinal past the
        /// facet's predicates has none.
        #[test]
        fn a_keyed_facet_gives_each_predicate_its_forms_key() {
            let mut census = FormCensus::new();
            let both = junction(
                ConjugateType::And,
                vec![leaf("topic", OpType::Eq), leaf("rank", OpType::Ge)],
            );
            census.record(&leaf("topic", OpType::Eq), None, None);
            census.record(&both, None, None);
            census.record(&leaf("topic", OpType::Eq), None, None);
            let unkeyed = first_unkeyed(&census);
            assert_eq!(unkeyed, None);
            let key = |ordinal| form_key_at(&census, unkeyed.as_ref(), "ds:p", ordinal);
            assert_eq!(key(0), Ok("topic.eq"));
            assert_eq!(key(1), Ok("rank.range_topic.eq"));
            assert_eq!(key(2), Ok("topic.eq"));
            assert_eq!(key(3), Err("'ds:p' has no predicate 3".to_string()));
            assert_eq!(
                form_keys(&census, unkeyed.as_ref(), "ds:p"),
                Ok(vec!["rank.range_topic.eq", "topic.eq"])
            );
        }

        /// One form with no key refuses the key of every predicate of
        /// the facet, keyed ones included, naming the form and why.
        #[test]
        fn a_facet_holding_an_unkeyed_form_gives_no_keys() {
            let mut census = FormCensus::new();
            let either = junction(
                ConjugateType::Or,
                vec![leaf("a", OpType::Eq), leaf("b", OpType::Eq)],
            );
            census.record(&leaf("topic", OpType::Eq), None, None);
            census.record(&either, None, None);
            let unkeyed = first_unkeyed(&census);
            let refusals = (0..2)
                .map(|ordinal| {
                    form_key_at(&census, unkeyed.as_ref(), "ds:p", ordinal)
                        .expect_err("a facet with an unkeyed form has no keys")
                })
                .chain([form_keys(&census, unkeyed.as_ref(), "ds:p")
                    .expect_err("a facet with an unkeyed form lists no keys")]);
            for err in refusals {
                assert!(
                    err.starts_with(
                        "the predicates of 'ds:p' hold a form with no key, `(a = ? OR b = ?)`: "
                    ) && err.contains("disjunction"),
                    "{err}"
                );
            }
        }
    }

    impl std::fmt::Debug for PredicateForms {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("PredicateForms")
                .field("origin", &self.origin)
                .field("forms", &self.census.forms().len())
                .field("predicates", &self.census.count())
                .finish()
        }
    }

    /// The one form of a metadata record facet: its layout, with the
    /// binder that reads every field of a record in layout order. A
    /// `forms` value.
    #[non_exhaustive]
    pub struct RecordForms {
        /// The names and types of a record's fields, in wire order.
        pub layout: Layout,
        /// Reads every field of a record, in layout order.
        pub binder: Binder,
        /// The records.
        pub records: RecordFacet,
        /// The dataset and profile, for diagnostics.
        pub origin: String,
    }

    impl RecordForms {
        pub(crate) fn new(layout: Layout, records: RecordFacet, origin: String) -> Self {
            Self {
                binder: Binder::all(&layout),
                layout,
                records,
                origin,
            }
        }
    }

    impl std::fmt::Debug for RecordForms {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("RecordForms")
                .field("origin", &self.origin)
                .field("fields", &self.layout.names())
                .finish()
        }
    }

    /// One predicate for a cycle, as structure: a `fragment` value.
    ///
    /// It names the predicate and does not hold its bytes, so making
    /// one allocates nothing and reads no record. A host selects what
    /// it prepared for [`form`](Self::form), reads the record
    /// (`forms.predicates.record_shared(ordinal)` or `record_bytes`),
    /// and binds it through that form's binder.
    #[derive(Debug, Clone)]
    #[non_exhaustive]
    pub struct PredicateFragment {
        /// The forms this predicate is one of.
        pub forms: Arc<PredicateForms>,
        /// The index of this predicate's form in `forms.census.forms()`.
        pub form: u32,
        /// The predicate's ordinal in the facet: a query ordinal.
        pub ordinal: u64,
    }

    impl PredicateFragment {
        pub(crate) fn new(forms: Arc<PredicateForms>, form: u32, ordinal: u64) -> Self {
            Self {
                forms,
                form,
                ordinal,
            }
        }
    }

    /// One metadata record for a cycle, as structure: a `fragment`
    /// value. Like [`PredicateFragment`], it names the record and does
    /// not hold its bytes; a host reads the record
    /// (`forms.records.record_shared(ordinal)` or `record_bytes`) and
    /// binds it through `forms.binder`.
    #[derive(Debug, Clone)]
    #[non_exhaustive]
    pub struct RecordFragment {
        /// The record facet's one form.
        pub forms: Arc<RecordForms>,
        /// The record's ordinal in the facet: a base ordinal.
        pub ordinal: u64,
    }

    impl RecordFragment {
        pub(crate) fn new(forms: Arc<RecordForms>, ordinal: u64) -> Self {
            Self { forms, ordinal }
        }
    }
}

/// The `vectordata` types a host works with when it binds a fragment
/// or reads forms, re-exported at vectordata's own paths so a host
/// that reaches datasets only through polydat can name them. These are
/// vectordata's types, not copies: a breaking release of vectordata
/// that changes one is a breaking change here.
///
/// The node enums (`formats::mnode::MValue`, `formats::pnode::OpType`,
/// `formats::pnode::Comparand`) are
/// exhaustive on purpose, so a host's `match` over one stops compiling
/// when vectordata adds a kind, rather than binding the new kind as
/// something else.
#[cfg(feature = "vectordata")]
pub mod vectordata {
    /// The record codec stage: a record as a typed node.
    pub mod formats {
        /// Any record, decoded.
        pub mod anode {
            pub use ::vectordata::formats::anode::{ANode, decode, encode};
        }
        /// A metadata record, and one field of it read in place.
        pub mod mnode {
            pub use ::vectordata::formats::mnode::{MNode, MValue, TypeTag};
            /// A field of a record, read without decoding the record.
            pub mod scan {
                pub use ::vectordata::formats::mnode::scan::Field;
            }
        }
        /// A predicate record, and a predicate with its comparands
        /// left open.
        pub mod pnode {
            pub use ::vectordata::formats::pnode::{
                Comparand, ConjugateNode, ConjugateType, FieldRef, OpType, PNode, PredicateNode,
            };
            /// A predicate's structure with its comparands as slots:
            /// what a host renders once per form.
            pub mod template {
                pub use ::vectordata::formats::pnode::template::{
                    PredicateTemplate, parse_template,
                };
            }
        }
    }
    /// Layouts and the binders that read a record's values.
    pub mod binding {
        pub use ::vectordata::binding::{
            BindError, BindType, Binder, Condition, Layout, LayoutSource, Nullability,
            PredicateBinder,
        };
    }
    /// The forms of a predicate facet.
    pub mod predicate_forms {
        pub use ::vectordata::predicate_forms::{
            Access, FormCensus, PredicateForm, PredicateStrata,
        };
    }
    /// Record facets, their bytes, and the packaged text renderings.
    pub mod records {
        pub use ::vectordata::records::{
            RecordCodec, RecordError, RecordFacet, SharedBytes, codec_by_name, codec_names,
        };
    }
    /// The rows a predicate admits.
    pub mod ground_truth {
        pub use ::vectordata::ground_truth::OrdinalSet;
    }
}

#[cfg(feature = "vectordata")]
mod wires {
    use std::sync::Arc;

    use vectordata::ground_truth::OrdinalSet;

    use super::{DatasetValue, PredicateForms, PredicateFragment, RecordForms, RecordFragment};
    use crate::ast::{PortType, Value};
    use crate::derive_support::{Wire, extract_mismatch};

    /// A shared dataset value as a node's argument or result: the
    /// rows a predicate admits (`Shared<OrdinalSet>`, an
    /// `admitted_rows` wire) or the forms of a facet
    /// (`Shared<PredicateForms>`, `Shared<RecordForms>`, a `forms`
    /// wire). It derefs to the value. A node function names this
    /// rather than the `Arc` inside it, because a bare `Arc<T>`
    /// argument is an untyped `handle` wire to the node macro.
    #[derive(Debug)]
    pub struct Shared<T>(pub Arc<T>);

    impl<T> Clone for Shared<T> {
        fn clone(&self) -> Self {
            Shared(self.0.clone())
        }
    }

    impl<T> std::ops::Deref for Shared<T> {
        type Target = T;
        fn deref(&self) -> &T {
            &self.0
        }
    }

    /// A value of the right port type and the wrong kind: the forms of
    /// a record facet where a predicate facet's were wanted. The port
    /// type cannot tell the two apart, so this is a program's error and
    /// is said in its terms.
    fn wrong_kind(wanted: &str, got: &DatasetValue) -> ! {
        let got = match got {
            DatasetValue::AdmittedRows(_) => "the rows a predicate admits",
            DatasetValue::PredicateForms(_) => "the forms of a predicate facet",
            DatasetValue::RecordForms(_) => "the forms of a record facet",
            DatasetValue::Predicate(_) => "a predicate fragment",
            DatasetValue::Record(_) => "a record fragment",
        };
        panic!("expected {wanted}, got {got}")
    }

    /// The rows a predicate admits: an `admitted_rows` wire.
    impl Wire for Shared<OrdinalSet> {
        const PORT: PortType = PortType::AdmittedRows;
        fn extract(v: &Value) -> Self {
            match v {
                Value::Dataset(DatasetValue::AdmittedRows(set)) => Shared(set.clone()),
                other => extract_mismatch("Shared<OrdinalSet>", Self::PORT, other),
            }
        }
        fn inject(self) -> Value {
            Value::Dataset(DatasetValue::AdmittedRows(self.0))
        }
    }

    /// The forms of a predicate facet: a `forms` wire.
    impl Wire for Shared<PredicateForms> {
        const PORT: PortType = PortType::Forms;
        fn extract(v: &Value) -> Self {
            match v {
                Value::Dataset(DatasetValue::PredicateForms(forms)) => Shared(forms.clone()),
                Value::Dataset(d @ DatasetValue::RecordForms(_)) => {
                    wrong_kind("the forms of a predicate facet", d)
                }
                other => extract_mismatch("Shared<PredicateForms>", Self::PORT, other),
            }
        }
        fn inject(self) -> Value {
            Value::Dataset(DatasetValue::PredicateForms(self.0))
        }
    }

    /// The forms of a record facet: a `forms` wire.
    impl Wire for Shared<RecordForms> {
        const PORT: PortType = PortType::Forms;
        fn extract(v: &Value) -> Self {
            match v {
                Value::Dataset(DatasetValue::RecordForms(forms)) => Shared(forms.clone()),
                Value::Dataset(d @ DatasetValue::PredicateForms(_)) => {
                    wrong_kind("the forms of a record facet", d)
                }
                other => extract_mismatch("Shared<RecordForms>", Self::PORT, other),
            }
        }
        fn inject(self) -> Value {
            Value::Dataset(DatasetValue::RecordForms(self.0))
        }
    }

    /// One predicate as structure: a `fragment` wire.
    impl Wire for PredicateFragment {
        const PORT: PortType = PortType::Fragment;
        fn extract(v: &Value) -> Self {
            match v {
                Value::Dataset(DatasetValue::Predicate(fragment)) => fragment.clone(),
                Value::Dataset(d @ DatasetValue::Record(_)) => {
                    wrong_kind("a predicate fragment", d)
                }
                other => extract_mismatch("PredicateFragment", Self::PORT, other),
            }
        }
        fn inject(self) -> Value {
            Value::Dataset(DatasetValue::Predicate(self))
        }
    }

    /// One metadata record as structure: a `fragment` wire.
    impl Wire for RecordFragment {
        const PORT: PortType = PortType::Fragment;
        fn extract(v: &Value) -> Self {
            match v {
                Value::Dataset(DatasetValue::Record(fragment)) => fragment.clone(),
                Value::Dataset(d @ DatasetValue::Predicate(_)) => {
                    wrong_kind("a record fragment", d)
                }
                other => extract_mismatch("RecordFragment", Self::PORT, other),
            }
        }
        fn inject(self) -> Value {
            Value::Dataset(DatasetValue::Record(self))
        }
    }
}