Skip to main content

lichtung_plot/data/
protocol.rs

1//! Owning role, domain and original-member queries.
2
3use std::sync::Arc;
4
5use super::{
6    binding::VectorSource, ArrayValueType, AxisValues, BindingGeneration, BindingSelector,
7    DataPayload, DataRole, DataSourceInfo, DataSourceRef, DataValueType, EstimateStatusBinding,
8    InstanceId, KeyValues, RawKey, RawKeyValues, SourceRows,
9};
10use crate::{
11    elements::ElementRef,
12    errors::{Diagnostic, DiagnosticKind, DiagnosticReference, ErrorContext, OperationPhase},
13    plots::PlotKind,
14    BooleanValues, CategoryValues, Error, NumericValues, Result,
15};
16
17/// Select a fixed role, an explicitly named input, or an actual bound reference.
18#[derive(Debug, Clone)]
19pub enum DataSelector {
20    /// A fixed native role.
21    Role(DataRole),
22    /// An explicitly declared open input name.
23    Named(String),
24    /// The actual declaration and binding identity.
25    Reference(DataRoleRef),
26}
27
28impl From<DataRole> for DataSelector {
29    fn from(role: DataRole) -> Self {
30        Self::Role(role)
31    }
32}
33impl From<DataRoleRef> for DataSelector {
34    fn from(reference: DataRoleRef) -> Self {
35        Self::Reference(reference)
36    }
37}
38impl From<&DataRoleRef> for DataSelector {
39    fn from(reference: &DataRoleRef) -> Self {
40        Self::Reference(reference.clone())
41    }
42}
43impl From<&str> for DataSelector {
44    fn from(name: &str) -> Self {
45        Self::Named(name.to_owned())
46    }
47}
48impl From<String> for DataSelector {
49    fn from(name: String) -> Self {
50        Self::Named(name)
51    }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
55pub(crate) enum DomainSlot {
56    Observations,
57    HistogramBins,
58    HistogramKde,
59    HistogramRug,
60    RaincloudSummary,
61    RaincloudDensity,
62    RaincloudPoints,
63    Alpha(DataRole),
64}
65
66#[derive(Debug, Clone, PartialEq, Eq, Hash)]
67enum DomainIdentity {
68    Bound {
69        owner: ElementRef,
70        slot: DomainSlot,
71        revision: InstanceId,
72    },
73    Scientific {
74        owner: ElementRef,
75        group: Option<super::GroupKey>,
76        identity: InstanceId,
77    },
78    Source {
79        capture: DataSourceRef,
80        coordinate: SourceCoordinate,
81        row_identity: Option<InstanceId>,
82    },
83}
84
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
86enum SourceCoordinate {
87    Rows,
88    Fields,
89    Array,
90}
91
92/// The actual identity of a member domain; independent of its length and role.
93#[derive(Debug, Clone, PartialEq, Eq, Hash)]
94pub struct DataDomainRef(DomainIdentity);
95
96impl DataDomainRef {
97    pub(crate) fn bound(owner: &ElementRef, slot: DomainSlot, revision: &InstanceId) -> Self {
98        Self(DomainIdentity::Bound {
99            owner: owner.clone(),
100            slot,
101            revision: revision.clone(),
102        })
103    }
104
105    pub(crate) fn scientific(owner: &ElementRef, group: Option<&super::GroupKey>) -> Self {
106        Self(DomainIdentity::Scientific {
107            owner: owner.clone(),
108            group: group.cloned(),
109            identity: InstanceId::new(),
110        })
111    }
112
113    /// Actual group associated with this independent result domain.
114    pub fn group_key(&self) -> Option<&super::GroupKey> {
115        match &self.0 {
116            DomainIdentity::Scientific { group, .. } => group.as_ref(),
117            _ => None,
118        }
119    }
120
121    fn same_position(&self, other: &Self) -> bool {
122        match (&self.0, &other.0) {
123            (
124                DomainIdentity::Bound { owner, slot, .. },
125                DomainIdentity::Bound {
126                    owner: other_owner,
127                    slot: other_slot,
128                    ..
129                },
130            ) => owner == other_owner && slot == other_slot,
131            _ => self == other,
132        }
133    }
134
135    /// The actual declaring layer, absent for an independent original source.
136    pub fn owner(&self) -> Option<&ElementRef> {
137        match &self.0 {
138            DomainIdentity::Bound { owner, .. } | DomainIdentity::Scientific { owner, .. } => {
139                Some(owner)
140            }
141            DomainIdentity::Source { .. } => None,
142        }
143    }
144}
145
146/// A reference to the actual bound instance of an input role.
147#[derive(Debug, Clone, PartialEq, Eq, Hash)]
148pub struct DataRoleRef {
149    role: DataRole,
150    owner: ElementRef,
151    binding: InstanceId,
152    domain: Option<DataDomainRef>,
153}
154
155impl DataRoleRef {
156    /// The fixed role of this declaration.
157    pub fn role(&self) -> Option<DataRole> {
158        Some(self.role)
159    }
160
161    /// Its actual owning layer.
162    pub fn owner(&self) -> Option<&ElementRef> {
163        Some(&self.owner)
164    }
165
166    /// Its unique domain, if there is one.
167    pub fn domain(&self) -> Option<&DataDomainRef> {
168        self.domain.as_ref()
169    }
170}
171
172/// The actual native axis-value type.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174#[non_exhaustive]
175pub enum AxisValueType {
176    /// Numeric input.
177    Numeric,
178    /// String categories.
179    Category,
180    /// Complete raw category keys.
181    Keys,
182    /// Exact dates.
183    Date,
184    /// Exact instants.
185    Instant,
186    /// Exact elapsed durations.
187    Duration,
188}
189
190fn payload_axis_type(value: &DataPayload) -> Option<AxisValueType> {
191    match value {
192        DataPayload::Axis(AxisValues::Numeric(_)) => Some(AxisValueType::Numeric),
193        DataPayload::Axis(AxisValues::Category(_)) => Some(AxisValueType::Category),
194        DataPayload::Axis(AxisValues::Keys(_)) => Some(AxisValueType::Keys),
195        _ => None,
196    }
197}
198
199/// A step through a real native composite field.
200#[derive(Debug, Clone, PartialEq, Eq, Hash)]
201pub enum ComponentPathPart {
202    /// A native field.
203    Field(String),
204    /// A collection position.
205    Index(usize),
206    /// A complete native key.
207    Key(RawKey),
208}
209
210impl From<&str> for ComponentPathPart {
211    fn from(field: &str) -> Self {
212        Self::Field(field.to_owned())
213    }
214}
215
216#[derive(Debug, Clone)]
217struct SourceRelation {
218    source: VectorSource,
219    field: Option<RawKey>,
220    length: usize,
221}
222
223/// Description of an actual native component and its captured relation.
224#[derive(Debug, Clone)]
225pub struct DataComponentInfo {
226    path: Arc<[ComponentPathPart]>,
227    name: Option<String>,
228    value_type: DataValueType,
229    axis_type: Option<AxisValueType>,
230    shape: Arc<[usize]>,
231    nullable: bool,
232    has_nulls: bool,
233    relation: Option<SourceRelation>,
234}
235
236impl DataComponentInfo {
237    #[expect(
238        clippy::too_many_arguments,
239        reason = "construct one complete actual column description and relation"
240    )]
241    fn vector(
242        path: Vec<ComponentPathPart>,
243        name: Option<&str>,
244        value_type: DataValueType,
245        source: &VectorSource,
246        field: Option<&RawKey>,
247        length: usize,
248        nullable: bool,
249        has_nulls: bool,
250    ) -> Self {
251        Self {
252            path: path.into(),
253            name: name.map(str::to_owned),
254            value_type,
255            axis_type: None,
256            shape: Arc::from([length]),
257            nullable,
258            has_nulls,
259            relation: Some(SourceRelation {
260                source: source.clone(),
261                field: field.cloned(),
262                length,
263            }),
264        }
265    }
266
267    pub(crate) fn numeric(path: Vec<ComponentPathPart>, values: &NumericValues) -> Self {
268        Self::vector(
269            path,
270            Some(values.name()),
271            DataValueType::Numeric,
272            values.vector_source(),
273            values.field_key(),
274            values.len(),
275            true,
276            values.has_nulls(),
277        )
278    }
279
280    pub(crate) fn category(path: Vec<ComponentPathPart>, values: &CategoryValues) -> Self {
281        let field = values.field_key();
282        match values.key_values() {
283            KeyValues::Strings(values) => Self::vector(
284                path,
285                Some(values.original_name()),
286                DataValueType::Category,
287                values.vector_source(),
288                field,
289                values.len(),
290                true,
291                values.has_nulls(),
292            ),
293            KeyValues::Raw(values) => Self::raw_keys(path, &values, field),
294        }
295    }
296
297    pub(crate) fn raw_keys(
298        path: Vec<ComponentPathPart>,
299        values: &RawKeyValues,
300        field: Option<&RawKey>,
301    ) -> Self {
302        Self::vector(
303            path,
304            Some(values.name()),
305            DataValueType::RawKeys,
306            values.vector_source(),
307            field,
308            values.len(),
309            true,
310            values.has_nulls(),
311        )
312    }
313
314    pub(crate) fn boolean(path: Vec<ComponentPathPart>, values: &BooleanValues) -> Self {
315        Self::vector(
316            path,
317            Some(values.name()),
318            DataValueType::Boolean,
319            values.vector_source(),
320            values.field_key(),
321            values.len(),
322            true,
323            values.has_nulls(),
324        )
325    }
326
327    pub(crate) fn statuses(binding: &EstimateStatusBinding) -> Self {
328        if let Some(values) = binding.get_boolean() {
329            return Self::boolean(vec!["get_boolean".into()], values);
330        }
331        if let Some((values, _)) = binding.get_categorical() {
332            return Self::category(
333                vec!["get_categorical".into(), ComponentPathPart::Index(0)],
334                values,
335            );
336        }
337        Self::vector(
338            vec![],
339            None,
340            DataValueType::EstimateStatuses,
341            binding.vector_source(),
342            None,
343            binding.statuses().len(),
344            false,
345            false,
346        )
347    }
348
349    pub(crate) fn scientific(name: &str, value: &DataPayload) -> Result<Self> {
350        Self::scientific_at(
351            vec![ComponentPathPart::Field(super::source::copy_source_string(
352                name,
353            )?)],
354            value,
355        )
356    }
357
358    pub(crate) fn scientific_at(path: Vec<ComponentPathPart>, value: &DataPayload) -> Result<Self> {
359        let mut component = Self::captured_at(path, value)?;
360        // Newly computed results are not independently supplied native columns.
361        component.relation = None;
362        Ok(component)
363    }
364
365    /// Describe an actual original input column retained in a scientific result.
366    pub(crate) fn captured(name: &str, value: &DataPayload) -> Result<Self> {
367        Self::captured_at(
368            vec![ComponentPathPart::Field(super::source::copy_source_string(
369                name,
370            )?)],
371            value,
372        )
373    }
374
375    pub(crate) fn captured_at(path: Vec<ComponentPathPart>, value: &DataPayload) -> Result<Self> {
376        let mut component = match value {
377            DataPayload::Numeric(values) => Self::numeric(path, values),
378            DataPayload::Category(values) => Self::category(path, values),
379            DataPayload::RawKeys(values) => Self::raw_keys(path, values, None),
380            DataPayload::Boolean(values) => Self::boolean(path, values),
381            DataPayload::Integer(values) => Self::vector(
382                path,
383                Some(values.name()),
384                DataValueType::Integer,
385                values.vector_source(),
386                None,
387                values.len(),
388                true,
389                values.iter().any(|value| value.is_none()),
390            ),
391            DataPayload::Axis(values) => match values {
392                AxisValues::Numeric(values) => Self::numeric(path, values),
393                AxisValues::Category(values) => Self::category(path, values),
394                AxisValues::Keys(values) => Self::raw_keys(path, values, None),
395            },
396            DataPayload::EstimateStatuses(statuses) => Self {
397                path: path.into(),
398                name: None,
399                value_type: DataValueType::EstimateStatuses,
400                axis_type: None,
401                shape: Arc::from([statuses.len()]),
402                nullable: false,
403                has_nulls: false,
404                relation: None,
405            },
406            _ => return Err(Error::Render("unsupported scientific field payload".into())),
407        };
408        component.value_type = value.value_type();
409        component.axis_type = payload_axis_type(value);
410        Ok(component)
411    }
412
413    /// Proven direct supply is identified by its actual original source
414    /// selection appearing in the result relation, never by vector length.
415    pub(crate) fn scientific_with_members(
416        name: &str,
417        value: &DataPayload,
418        members: &[Option<SourceMembers>],
419    ) -> Result<Self> {
420        let mut component = Self::captured(name, value)?;
421        if let Some(source) = component
422            .relation
423            .as_ref()
424            .map(|relation| relation.source.info())
425        {
426            let mut supplied = false;
427            for entries in members.iter().flatten() {
428                crate::operation::work(entries.entries().len())?;
429                if entries
430                    .entries()
431                    .iter()
432                    .any(|entry| entry.source() == source)
433                {
434                    supplied = true;
435                    break;
436                }
437            }
438            if !supplied {
439                component.relation = None;
440            }
441        }
442        Ok(component)
443    }
444
445    /// The actual native getter path.
446    pub fn path(&self) -> &[ComponentPathPart] {
447        &self.path
448    }
449    /// Original native column name, if present.
450    pub fn name(&self) -> Option<&str> {
451        self.name.as_deref()
452    }
453    /// The actual native value type.
454    pub fn value_type(&self) -> Option<DataValueType> {
455        Some(self.value_type)
456    }
457    /// Array type, when the component itself is an array.
458    pub fn array_type(&self) -> Option<ArrayValueType> {
459        None
460    }
461    /// Axis type, when the component itself is an axis.
462    pub fn axis_type(&self) -> Option<AxisValueType> {
463        self.axis_type
464    }
465    /// Actual value shape.
466    pub fn shape(&self) -> Option<&[usize]> {
467        Some(&self.shape)
468    }
469    /// Whether this value representation supports missing slots.
470    pub fn nullable(&self) -> bool {
471        self.nullable
472    }
473    /// Whether actual slots are missing.
474    pub fn has_nulls(&self) -> bool {
475        self.has_nulls
476    }
477    /// Actual captured source selections of this component.
478    pub fn sources(&self) -> &[DataSourceInfo] {
479        self.relation
480            .as_ref()
481            .map_or(&[], |relation| std::slice::from_ref(relation.source.info()))
482    }
483}
484
485/// An actual original alignment domain and the role's components in it.
486#[derive(Debug, Clone)]
487pub struct DataDomainInfo {
488    reference: DataDomainRef,
489    shape: Arc<[usize]>,
490    keys: Option<RawKeyValues>,
491    source_rows: Option<SourceRows>,
492    components: Arc<[DataComponentInfo]>,
493}
494
495impl DataDomainInfo {
496    pub(crate) fn bound(
497        reference: DataDomainRef,
498        length: usize,
499        rows: Option<&SourceRows>,
500        components: Vec<DataComponentInfo>,
501    ) -> Self {
502        Self {
503            reference,
504            shape: Arc::from([length]),
505            keys: None,
506            source_rows: rows.filter(|rows| rows.len() == length).cloned(),
507            components: components.into(),
508        }
509    }
510
511    pub(crate) fn with_source_rows(mut self, rows: Option<&SourceRows>) -> Self {
512        self.source_rows = rows
513            .filter(|rows| self.shape.as_ref() == [rows.len()])
514            .cloned();
515        self
516    }
517
518    pub(crate) fn with_keys(mut self, keys: &RawKeyValues) -> Self {
519        self.keys = Some(keys.clone());
520        self
521    }
522
523    pub(crate) fn with_component(mut self, component: DataComponentInfo) -> Result<Self> {
524        if component.shape() != Some(self.shape()) {
525            return Err(Error::Render(
526                "result component does not align with its domain".into(),
527            ));
528        }
529        let mut components =
530            super::source::collect_source(self.components.iter().cloned().map(Ok))?;
531        super::source::reserve_source(&mut components, 1)?;
532        components.push(component);
533        self.components = components.into();
534        Ok(self)
535    }
536
537    /// The actual alignment identity.
538    pub fn reference(&self) -> &DataDomainRef {
539        &self.reference
540    }
541    /// Shape of actual members, independent of value components.
542    pub fn shape(&self) -> &[usize] {
543        &self.shape
544    }
545    /// Explicit unique original member keys, when supplied.
546    pub fn keys(&self) -> Option<&RawKeyValues> {
547        self.keys.as_ref()
548    }
549    /// Explicit original per-axis keys, when supplied.
550    pub fn axis_keys(&self) -> Option<&[RawKeyValues]> {
551        // Current keyed domains are one-dimensional. Their actual ordered
552        // member keys also describe that axis. Unkeyed array domains have
553        // only their original positional index space.
554        self.keys.as_ref().map(std::slice::from_ref)
555    }
556    /// Explicit unique original source IDs in this domain.
557    pub fn source_rows(&self) -> Option<&SourceRows> {
558        self.source_rows.as_ref()
559    }
560    /// Actual components of this role in this domain.
561    pub fn components(&self) -> &[DataComponentInfo] {
562        &self.components
563    }
564
565    #[expect(
566        clippy::too_many_lines,
567        reason = "the original member address resolves once with its exact typed failure"
568    )]
569    pub(crate) fn resolve(&self, address: &MemberAddress) -> Result<usize> {
570        let mut context = ErrorContext::new()
571            .with_operation(OperationPhase::Check)
572            .with_member(address.clone());
573        if let Some(owner) = self.reference.owner() {
574            context = context.with_element(owner.clone());
575        }
576        let invalid_index = |index: Vec<super::ExactInteger>| {
577            Error::Data(
578                Diagnostic::new(
579                    DiagnosticKind::IndexOutOfBounds {
580                        index,
581                        shape: Some(self.shape.to_vec()),
582                    },
583                    format!(
584                        "invalid member address {address:?} for domain {:?}",
585                        self.shape
586                    ),
587                )
588                .with_context(context.clone()),
589            )
590        };
591        let unknown_key = |key: RawKey| {
592            Error::Data(
593                Diagnostic::new(
594                    DiagnosticKind::UnknownKey { key: Some(key) },
595                    format!(
596                        "unknown member address {address:?} for domain {:?}",
597                        self.shape
598                    ),
599                )
600                .with_context(context.clone()),
601            )
602        };
603        let absent_keys = |constraint: &str| {
604            Error::Data(
605                Diagnostic::new(
606                    DiagnosticKind::InvalidValue {
607                        value: None,
608                        constraint: constraint.to_owned(),
609                    },
610                    constraint,
611                )
612                .with_context(context.clone()),
613            )
614        };
615        match address {
616            MemberAddress::Slot(slot) => {
617                if self.shape.len() == 1 && *slot < self.shape[0] {
618                    Ok(*slot)
619                } else {
620                    Err(invalid_index(vec![(*slot).into()]))
621                }
622            }
623            MemberAddress::Index(indices) => {
624                if indices.len() != self.shape.len()
625                    || indices
626                        .iter()
627                        .zip(self.shape.iter())
628                        .any(|(index, extent)| index >= extent)
629                {
630                    return Err(invalid_index(
631                        indices.iter().copied().map(Into::into).collect(),
632                    ));
633                }
634                indices
635                    .iter()
636                    .zip(self.shape.iter())
637                    .try_fold(0usize, |slot, (index, extent)| {
638                        slot.checked_mul(*extent)?.checked_add(*index)
639                    })
640                    .ok_or_else(|| invalid_index(indices.iter().copied().map(Into::into).collect()))
641            }
642            MemberAddress::RowId(id) => {
643                let rows = self
644                    .source_rows
645                    .as_ref()
646                    .ok_or_else(|| absent_keys("member domain has no explicit row IDs"))?;
647                rows.iter()
648                    .position(|row| row == *id)
649                    .ok_or_else(|| unknown_key(RawKey::Integer((*id).into())))
650            }
651            MemberAddress::Key(key) => {
652                let keys = self
653                    .keys
654                    .as_ref()
655                    .ok_or_else(|| absent_keys("member domain has no explicit member keys"))?;
656                let slots: Vec<_> = keys
657                    .iter()
658                    .enumerate()
659                    .filter_map(|(slot, value)| (value == Some(key)).then_some(slot))
660                    .collect();
661                match slots.as_slice() {
662                    [] => Err(unknown_key(key.clone())),
663                    [slot] => Ok(*slot),
664                    _ => Err(Error::Data(
665                        Diagnostic::new(
666                            DiagnosticKind::Ambiguous {
667                                candidates: slots
668                                    .into_iter()
669                                    .map(|slot| DiagnosticReference::Member {
670                                        domain: Some(self.reference.clone()),
671                                        address: MemberAddress::Slot(slot),
672                                    })
673                                    .collect(),
674                            },
675                            "ambiguous original member key",
676                        )
677                        .with_context(context),
678                    )),
679                }
680            }
681        }
682    }
683
684    fn members(&self, slot: usize) -> Option<SourceMembers> {
685        let entries: Vec<_> = self
686            .components
687            .iter()
688            .filter_map(|component| component.origin(self, slot))
689            .collect();
690        (!entries.is_empty()).then(|| SourceMembers {
691            entries: entries.into(),
692        })
693    }
694}
695
696/// Metadata of one actually bound role.
697#[derive(Debug, Clone)]
698pub struct DataRoleInfo {
699    reference: DataRoleRef,
700    plot_kind: Option<PlotKind>,
701    value_type: DataValueType,
702    array_type: Option<ArrayValueType>,
703    axis_type: Option<AxisValueType>,
704    shape: Option<Arc<[usize]>>,
705    name: Option<String>,
706    domains: Arc<[DataDomainInfo]>,
707    source: Option<DataSourceRef>,
708    selector: Option<BindingSelector>,
709}
710
711impl DataRoleInfo {
712    /// Actual role and binding identity.
713    pub fn reference(&self) -> &DataRoleRef {
714        &self.reference
715    }
716    /// The fixed role, when this is a fixed input.
717    pub fn role(&self) -> Option<DataRole> {
718        self.reference.role()
719    }
720    /// The actual declaring plot family, when one exists.
721    pub fn plot_kind(&self) -> Option<PlotKind> {
722        self.plot_kind
723    }
724    /// Actual native payload type.
725    pub fn value_type(&self) -> DataValueType {
726        self.value_type
727    }
728    /// Actual native array type, if an array.
729    pub fn array_type(&self) -> Option<ArrayValueType> {
730        self.array_type
731    }
732    /// Actual native axis type, if an axis.
733    pub fn axis_type(&self) -> Option<AxisValueType> {
734        self.axis_type
735    }
736    /// Actual payload shape, if it has one shape.
737    pub fn shape(&self) -> Option<&[usize]> {
738        self.shape.as_deref()
739    }
740    /// The actual unique alignment domain.
741    pub fn domain(&self) -> Option<&DataDomainRef> {
742        self.reference.domain()
743    }
744    /// All actual component domains.
745    pub fn domains(&self) -> &[DataDomainInfo] {
746        &self.domains
747    }
748    /// Original native value name.
749    pub fn name(&self) -> Option<&str> {
750        self.name.as_deref()
751    }
752    /// Unique actual capture, when it exists.
753    pub fn source(&self) -> Option<&DataSourceRef> {
754        self.source.as_ref()
755    }
756    /// Unique authored selection, when it exists.
757    pub fn selector(&self) -> Option<&BindingSelector> {
758        self.selector.as_ref()
759    }
760}
761
762/// An immutable, independently owning original value with its actual binding.
763#[derive(Debug, Clone)]
764pub struct DataValue {
765    info: DataRoleInfo,
766    value: Arc<DataPayload>,
767}
768
769impl DataValue {
770    #[expect(
771        clippy::too_many_arguments,
772        reason = "construct a single owning value with its actual declaration and domain metadata"
773    )]
774    pub(crate) fn bound(
775        role: DataRole,
776        owner: &ElementRef,
777        revision: &InstanceId,
778        plot_kind: Option<PlotKind>,
779        value: DataPayload,
780        shape: Option<Vec<usize>>,
781        name: Option<&str>,
782        domains: Vec<DataDomainInfo>,
783    ) -> Self {
784        let domain = (domains.len() == 1).then(|| domains[0].reference.clone());
785        let mut sources = domains
786            .iter()
787            .flat_map(|domain| domain.components.iter())
788            .flat_map(DataComponentInfo::sources);
789        let first = sources.next();
790        let mut source = first.map(|source| source.reference().clone());
791        let mut selector = first.and_then(|source| source.selector().cloned());
792        for item in sources {
793            if source.as_ref() != Some(item.reference()) {
794                source = None;
795                selector = None;
796            }
797            if selector.as_ref() != item.selector() {
798                selector = None;
799            }
800        }
801        let axis_type = payload_axis_type(&value);
802        let array_type = match &value {
803            DataPayload::Array(array) => Some(array.array_type()),
804            _ => None,
805        };
806        Self {
807            info: DataRoleInfo {
808                reference: DataRoleRef {
809                    role,
810                    owner: owner.clone(),
811                    binding: revision.clone(),
812                    domain,
813                },
814                plot_kind,
815                value_type: value.value_type(),
816                array_type,
817                axis_type,
818                shape: shape.map(Arc::from),
819                name: name.map(str::to_owned),
820                domains: domains.into(),
821                source,
822                selector,
823            },
824            value: Arc::new(value),
825        }
826    }
827
828    /// Actual description of this original value.
829    pub fn info(&self) -> &DataRoleInfo {
830        &self.info
831    }
832    /// The actual immutable native payload.
833    pub fn value(&self) -> &DataPayload {
834        &self.value
835    }
836
837    /// Read an actual unique numeric vector.
838    pub fn numeric(&self) -> Result<NumericValues> {
839        match self.value() {
840            DataPayload::Numeric(values) | DataPayload::Axis(AxisValues::Numeric(values)) => {
841                Ok(values.clone())
842            }
843            DataPayload::AlphaEncoding(encoding)
844                if encoding.get_keyed().is_none() && encoding.get_bins().is_none() =>
845            {
846                encoding
847                    .values()
848                    .and_then(crate::scales::AlphaValues::get_numeric_source)
849                    .cloned()
850                    .ok_or_else(|| self.incompatible(DataValueType::Numeric))
851            }
852            _ => Err(self.incompatible(DataValueType::Numeric)),
853        }
854    }
855
856    /// Read an actual unique string category vector.
857    pub fn category(&self) -> Result<CategoryValues> {
858        match self.value() {
859            DataPayload::Category(values) | DataPayload::Axis(AxisValues::Category(values)) => {
860                Ok(values.clone())
861            }
862            DataPayload::AlphaEncoding(encoding)
863                if encoding.get_keyed().is_none() && encoding.get_bins().is_none() =>
864            {
865                encoding
866                    .values()
867                    .and_then(crate::scales::AlphaValues::get_category_source)
868                    .and_then(KeyValues::get_strings)
869                    .cloned()
870                    .ok_or_else(|| self.incompatible(DataValueType::Category))
871            }
872            _ => Err(self.incompatible(DataValueType::Category)),
873        }
874    }
875
876    /// Read the actual Boolean vector.
877    pub fn boolean(&self) -> Result<BooleanValues> {
878        match self.value() {
879            DataPayload::Boolean(values) => Ok(values.clone()),
880            _ => Err(self.incompatible(DataValueType::Boolean)),
881        }
882    }
883
884    /// Read a unique actual native axis.
885    pub fn axis(&self) -> Result<AxisValues> {
886        match self.value() {
887            DataPayload::Axis(values) => Ok(values.clone()),
888            DataPayload::Numeric(values) => Ok(AxisValues::Numeric(values.clone())),
889            DataPayload::Category(values) => Ok(AxisValues::Category(values.clone())),
890            DataPayload::RawKeys(values) => Ok(AxisValues::Keys(values.clone())),
891            _ => Err(self.incompatible(DataValueType::Axis)),
892        }
893    }
894
895    fn context(&self) -> ErrorContext {
896        ErrorContext::new()
897            .with_operation(OperationPhase::Check)
898            .with_element(self.info.reference.owner().expect("bound role").clone())
899            .with_role(self.info.reference.role().expect("fixed role"))
900    }
901
902    fn incompatible(&self, expected: DataValueType) -> Error {
903        Error::Data(
904            Diagnostic::new(
905                DiagnosticKind::WrongType {
906                    expected,
907                    actual: self.info.value_type,
908                },
909                format!(
910                    "role {:?} at {:?} contains {:?}, not a unique {} value",
911                    self.info.role(),
912                    self.info.reference.owner(),
913                    self.info.value_type,
914                    expected.as_str()
915                ),
916            )
917            .with_context(self.context()),
918        )
919    }
920
921    /// Explicit unique row IDs of the value's unique alignment domain.
922    pub fn source_rows(&self) -> Option<&SourceRows> {
923        self.info.domain()?;
924        self.info.domains[0].source_rows()
925    }
926
927    /// Read actual original members in this role's unique domain.
928    pub fn members(&self, address: impl Into<MemberAddress>) -> Result<Option<SourceMembers>> {
929        let domain = self.info.domain().ok_or_else(|| {
930            Error::Data(
931                Diagnostic::new(
932                    DiagnosticKind::Ambiguous {
933                        candidates: self
934                            .info
935                            .domains
936                            .iter()
937                            .map(|domain| DiagnosticReference::Domain(domain.reference.clone()))
938                            .collect(),
939                    },
940                    "role has no unique member domain; select an actual domain",
941                )
942                .with_context(self.context()),
943            )
944        })?;
945        self.members_in(domain, address)
946    }
947
948    /// Read actual original members in a specified domain of this value.
949    pub fn members_in(
950        &self,
951        domain: &DataDomainRef,
952        address: impl Into<MemberAddress>,
953    ) -> Result<Option<SourceMembers>> {
954        let domain = self
955            .info
956            .domains
957            .iter()
958            .find(|info| info.reference() == domain)
959            .ok_or_else(|| {
960                let current = self
961                    .info
962                    .domains
963                    .iter()
964                    .find(|info| info.reference.same_position(domain))
965                    .map(|info| Box::new(DiagnosticReference::Domain(info.reference.clone())));
966                Error::Data(
967                    Diagnostic::new(
968                        DiagnosticKind::StaleReference {
969                            reference: Box::new(DiagnosticReference::Domain(domain.clone())),
970                            current,
971                        },
972                        "member domain is foreign or no longer bound",
973                    )
974                    .with_context(self.context()),
975                )
976            })?;
977        let slot = domain.resolve(&address.into())?;
978        Ok(domain.members(slot))
979    }
980}
981
982/// Address of an original logical member in a known domain.
983#[derive(Debug, Clone, PartialEq, Eq, Hash)]
984pub enum MemberAddress {
985    /// One actual one-dimensional slot.
986    Slot(usize),
987    /// Full-rank logical array index.
988    Index(Vec<usize>),
989    /// An explicitly bound unique record ID.
990    RowId(usize),
991    /// A complete original member key.
992    Key(RawKey),
993}
994
995impl From<usize> for MemberAddress {
996    fn from(slot: usize) -> Self {
997        Self::Slot(slot)
998    }
999}
1000
1001/// One actual original source member.
1002#[derive(Debug, Clone)]
1003pub struct SourceMember {
1004    address: MemberAddress,
1005    key: Option<RawKey>,
1006    row_id: Option<usize>,
1007}
1008
1009impl SourceMember {
1010    /// Actual original position or key.
1011    pub fn address(&self) -> &MemberAddress {
1012        &self.address
1013    }
1014    /// Its actual original key, when present.
1015    pub fn key(&self) -> Option<&RawKey> {
1016        self.key.as_ref()
1017    }
1018    /// Explicit original record ID, when supplied.
1019    pub fn row_id(&self) -> Option<usize> {
1020        self.row_id
1021    }
1022}
1023
1024/// One actual source/domain relation in an owning member set.
1025#[derive(Debug, Clone)]
1026pub struct SourceMembersEntry {
1027    source: DataSourceInfo,
1028    domain: DataDomainInfo,
1029    field_key: Option<RawKey>,
1030    members: Option<Arc<[SourceMember]>>,
1031    member_limit: Option<usize>,
1032}
1033
1034impl SourceMembersEntry {
1035    /// Actual original capture.
1036    pub fn source(&self) -> &DataSourceInfo {
1037        &self.source
1038    }
1039    /// Original source alignment domain.
1040    pub fn domain(&self) -> &DataDomainInfo {
1041        &self.domain
1042    }
1043    /// Actual selected field key when this member comes from a field.
1044    pub fn field_key(&self) -> Option<&RawKey> {
1045        self.field_key.as_ref()
1046    }
1047    /// Original related members, distinct from unavailable relation.
1048    pub fn members(&self) -> Option<&[SourceMember]> {
1049        self.members
1050            .as_deref()
1051            .map(|members| &members[..self.member_limit.unwrap_or(members.len())])
1052    }
1053}
1054
1055/// An owned relation to original members across actual sources and domains.
1056#[derive(Debug, Clone)]
1057pub struct SourceMembers {
1058    entries: Arc<[SourceMembersEntry]>,
1059}
1060
1061#[derive(Default)]
1062struct MemberAccumulator {
1063    entries: Vec<(SourceMembersEntry, Vec<SourceMember>)>,
1064}
1065
1066impl MemberAccumulator {
1067    fn append(&mut self, domain: &DataDomainInfo, slot: usize) -> Result<()> {
1068        self.append_components(domain, slot, domain.components().iter())
1069    }
1070
1071    fn append_components<'a>(
1072        &mut self,
1073        domain: &DataDomainInfo,
1074        slot: usize,
1075        components: impl Iterator<Item = &'a DataComponentInfo>,
1076    ) -> Result<()> {
1077        domain.resolve(&MemberAddress::Slot(slot))?;
1078        for component in components {
1079            crate::operation::work(1)?;
1080            let Some(entry) = component.origin(domain, slot) else {
1081                continue;
1082            };
1083            let index = self.entries.iter().position(|(current, _)| {
1084                current.source == entry.source
1085                    && current.domain.reference == entry.domain.reference
1086                    && current.field_key == entry.field_key
1087            });
1088            let index = if let Some(index) = index {
1089                index
1090            } else {
1091                super::source::reserve_source(&mut self.entries, 1)?;
1092                let index = self.entries.len();
1093                self.entries.push((entry.clone(), Vec::new()));
1094                index
1095            };
1096            if let Some(members) = entry.members() {
1097                let retained = &mut self.entries[index].1;
1098                if retained.capacity() - retained.len() < members.len() {
1099                    super::source::reserve_source(retained, retained.len().max(members.len()))?;
1100                }
1101                retained.extend_from_slice(members);
1102            }
1103        }
1104        Ok(())
1105    }
1106
1107    fn finish(self) -> Result<SourceMembers> {
1108        let entries =
1109            super::source::collect_source(self.entries.into_iter().map(|(mut entry, members)| {
1110                entry.members = Some(members.into());
1111                Ok(entry)
1112            }))?;
1113        Ok(SourceMembers {
1114            entries: entries.into(),
1115        })
1116    }
1117}
1118
1119impl SourceMembers {
1120    pub(crate) fn from_slots(
1121        values: &[&DataValue],
1122        slots: impl IntoIterator<Item = usize>,
1123    ) -> Result<Self> {
1124        let domains = super::source::collect_source(values.iter().map(|value| {
1125            let [domain] = value.info.domains.as_ref() else {
1126                return Err(Error::Render(
1127                    "scientific input has no unique member domain".into(),
1128                ));
1129            };
1130            Ok(domain)
1131        }))?;
1132        Self::from_domains(&domains, slots)
1133    }
1134
1135    pub(crate) fn from_domains(
1136        domains: &[&DataDomainInfo],
1137        slots: impl IntoIterator<Item = usize>,
1138    ) -> Result<Self> {
1139        let mut accumulator = MemberAccumulator::default();
1140        for (index, slot) in slots.into_iter().enumerate() {
1141            if index.is_multiple_of(1024) {
1142                crate::operation::checkpoint()?;
1143            }
1144            for domain in domains {
1145                accumulator.append(domain, slot)?;
1146            }
1147        }
1148        accumulator.finish()
1149    }
1150
1151    pub(crate) fn from_component_slots(
1152        domain: &DataDomainInfo,
1153        component: &DataComponentInfo,
1154        slots: impl IntoIterator<Item = usize>,
1155    ) -> Result<Self> {
1156        let mut accumulator = MemberAccumulator::default();
1157        for (index, slot) in slots.into_iter().enumerate() {
1158            if index.is_multiple_of(1024) {
1159                crate::operation::checkpoint()?;
1160            }
1161            accumulator.append_components(domain, slot, std::iter::once(component))?;
1162        }
1163        accumulator.finish()
1164    }
1165
1166    pub(crate) fn prefixes(value: &DataValue, slots: &[usize]) -> Result<Vec<Self>> {
1167        let [domain] = value.info.domains.as_ref() else {
1168            return Err(Error::Render(
1169                "cumulative input has no unique member domain".into(),
1170            ));
1171        };
1172        let mut accumulator = MemberAccumulator::default();
1173        let mut counts = Vec::new();
1174        super::source::reserve_source(
1175            &mut counts,
1176            slots
1177                .len()
1178                .checked_add(1)
1179                .ok_or_else(|| Error::Render("cumulative member length overflow".into()))?,
1180        )?;
1181        counts.push(Vec::new());
1182        for (index, &slot) in slots.iter().enumerate() {
1183            if index.is_multiple_of(1024) {
1184                crate::operation::checkpoint()?;
1185            }
1186            accumulator.append(domain, slot)?;
1187            counts.push(super::source::collect_source(
1188                accumulator
1189                    .entries
1190                    .iter()
1191                    .map(|(_, members)| Ok(members.len())),
1192            )?);
1193        }
1194        let all = accumulator.finish()?;
1195        super::source::collect_source(counts.into_iter().map(|counts| {
1196            let entries = super::source::collect_source(
1197                all.entries
1198                    .iter()
1199                    .zip(counts)
1200                    .filter(|(_, count)| *count != 0)
1201                    .map(|(entry, count)| {
1202                        let mut entry = entry.clone();
1203                        entry.member_limit = Some(count);
1204                        Ok(entry)
1205                    }),
1206            )?;
1207            Ok(Self {
1208                entries: entries.into(),
1209            })
1210        }))
1211    }
1212
1213    /// Ordered actual source and domain relations.
1214    pub fn entries(&self) -> &[SourceMembersEntry] {
1215        &self.entries
1216    }
1217}
1218
1219impl SourceRelation {
1220    fn original_address(&self, member: usize) -> Option<OriginalAddress> {
1221        let relation = self;
1222        if member >= relation.length {
1223            return None;
1224        }
1225        let slot = relation.source.slot(member);
1226        let info = relation.source.info();
1227        let member_shape = info.member_shape();
1228        let mut field_key = relation.field.clone();
1229        let mut field_position = None;
1230        let mut key = None;
1231        let field_axis = info.generation() == Some(BindingGeneration::ColumnNames)
1232            || info.grid_axis() == Some(1);
1233        let (coordinate, shape, address) = if field_axis {
1234            let position = info
1235                .selected_indices()
1236                .and_then(|indices| indices.get(slot))
1237                .copied()
1238                .unwrap_or(slot);
1239            key = info
1240                .selected_keys()
1241                .and_then(|keys| keys.get(slot))
1242                .cloned();
1243            (
1244                SourceCoordinate::Fields,
1245                vec![*info.source_shape().get(1)?],
1246                MemberAddress::Slot(position),
1247            )
1248        } else if let [_, width] = member_shape {
1249            if *width == 0 {
1250                return None;
1251            }
1252            let row = slot / width;
1253            let selected_column = slot % width;
1254            let key = info
1255                .selected_keys()
1256                .and_then(|keys| keys.get(selected_column))
1257                .cloned();
1258            if let Some(key) = key {
1259                field_key = Some(key);
1260                field_position = Some(selected_column);
1261                (
1262                    SourceCoordinate::Rows,
1263                    vec![info.source_shape()[0]],
1264                    MemberAddress::Slot(row),
1265                )
1266            } else {
1267                let column = info
1268                    .selected_indices()
1269                    .and_then(|indices| indices.get(selected_column))
1270                    .copied()
1271                    .unwrap_or(selected_column);
1272                (
1273                    SourceCoordinate::Array,
1274                    info.source_shape().to_vec(),
1275                    MemberAddress::Index(vec![row, column]),
1276                )
1277            }
1278        } else {
1279            if info.generation() == Some(BindingGeneration::RowPosition)
1280                || info.grid_axis() == Some(0)
1281            {
1282                field_key = None;
1283            } else if field_key.is_none()
1284                && info.selected_keys().is_some_and(|keys| keys.len() == 1)
1285            {
1286                field_key = info.selected_keys().and_then(|keys| keys.first()).cloned();
1287            }
1288            if field_key.is_some() {
1289                field_position = Some(0);
1290            }
1291            (
1292                SourceCoordinate::Rows,
1293                vec![*info.source_shape().first()?],
1294                MemberAddress::Slot(slot),
1295            )
1296        };
1297        Some(OriginalAddress {
1298            coordinate,
1299            shape,
1300            address,
1301            key,
1302            field_key,
1303            field_position,
1304        })
1305    }
1306}
1307
1308struct OriginalAddress {
1309    coordinate: SourceCoordinate,
1310    shape: Vec<usize>,
1311    address: MemberAddress,
1312    key: Option<RawKey>,
1313    field_key: Option<RawKey>,
1314    field_position: Option<usize>,
1315}
1316
1317impl DataComponentInfo {
1318    fn origin(&self, bound: &DataDomainInfo, member: usize) -> Option<SourceMembersEntry> {
1319        let relation = self.relation.as_ref()?;
1320        let OriginalAddress {
1321            coordinate,
1322            shape,
1323            address,
1324            key,
1325            field_key,
1326            field_position,
1327        } = relation.original_address(member)?;
1328        let info = relation.source.info();
1329        let mut row_id = None;
1330        let mut rows = None;
1331        let mut row_identity = None;
1332        if coordinate == SourceCoordinate::Rows
1333            && relation.source.has_distinct_rows()
1334            && info.generation().is_none()
1335            && info.member_shape().len() == 1
1336        {
1337            row_id = bound.source_rows().and_then(|rows| rows.get(member));
1338            if relation.source.is_identity()
1339                && relation.length == info.member_shape()[0]
1340                && bound.shape() == info.member_shape()
1341            {
1342                rows = bound.source_rows().cloned();
1343            }
1344            if row_id.is_some() {
1345                if let DomainIdentity::Bound { revision, .. } = &bound.reference.0 {
1346                    row_identity = Some(revision.clone());
1347                }
1348            }
1349        }
1350        let reference = DataDomainRef(DomainIdentity::Source {
1351            capture: info.reference().clone(),
1352            coordinate,
1353            row_identity,
1354        });
1355        let mut component = self.clone();
1356        component.shape = match coordinate {
1357            SourceCoordinate::Rows => Arc::from(shape.as_slice()),
1358            SourceCoordinate::Fields | SourceCoordinate::Array => Arc::from(info.member_shape()),
1359        };
1360        component.has_nulls = relation.source.original_has_nulls(field_position);
1361        if let Some(field) = &field_key {
1362            component.path = Arc::from([ComponentPathPart::Key(field.clone())]);
1363            if let Some((_, name)) = field_position.and_then(|position| info.field(position)) {
1364                component.name = Some(name);
1365            }
1366        }
1367        // The capture describes the selected field, not unselected foreign fields.
1368        Some(SourceMembersEntry {
1369            source: info.clone(),
1370            field_key,
1371            domain: DataDomainInfo {
1372                reference,
1373                shape: shape.into(),
1374                source_rows: rows,
1375                keys: if coordinate == SourceCoordinate::Fields {
1376                    relation.source.field_axis_keys().cloned()
1377                } else {
1378                    None
1379                },
1380                components: Arc::from([component]),
1381            },
1382            member_limit: None,
1383            members: Some(Arc::from([SourceMember {
1384                address,
1385                key,
1386                row_id,
1387            }])),
1388        })
1389    }
1390}
1391
1392pub(crate) fn select_value(values: &[DataValue], selector: DataSelector) -> Result<DataValue> {
1393    match selector {
1394        DataSelector::Role(role) => {
1395            let mut context = ErrorContext::new()
1396                .with_operation(OperationPhase::Check)
1397                .with_role(role);
1398            if let Some(owner) = values
1399                .first()
1400                .and_then(|value| value.info.reference.owner())
1401            {
1402                context = context.with_element(owner.clone());
1403            }
1404            let matches: Vec<_> = values
1405                .iter()
1406                .filter(|value| value.info.role() == Some(role))
1407                .collect();
1408            match matches.as_slice() {
1409                [] => Err(Error::Data(
1410                    Diagnostic::new(
1411                        DiagnosticKind::UnknownKey { key: None },
1412                        format!("role {role:?} is not bound"),
1413                    )
1414                    .with_context(context),
1415                )),
1416                [found] => Ok((*found).clone()),
1417                _ => Err(Error::Data(
1418                    Diagnostic::new(
1419                        DiagnosticKind::Ambiguous {
1420                            candidates: matches
1421                                .into_iter()
1422                                .map(|value| {
1423                                    DiagnosticReference::Role(value.info.reference.clone())
1424                                })
1425                                .collect(),
1426                        },
1427                        format!("role {role:?} is ambiguous; use its actual reference"),
1428                    )
1429                    .with_context(context),
1430                )),
1431            }
1432        }
1433        DataSelector::Reference(reference) => {
1434            if let Some(value) = values
1435                .iter()
1436                .find(|value| value.info.reference == reference)
1437            {
1438                return Ok(value.clone());
1439            }
1440            let current = values
1441                .iter()
1442                .find(|value| {
1443                    value.info.reference.owner == reference.owner
1444                        && value.info.reference.role == reference.role
1445                })
1446                .map(|value| Box::new(DiagnosticReference::Role(value.info.reference.clone())));
1447            let context = ErrorContext::new()
1448                .with_operation(OperationPhase::Check)
1449                .with_element(reference.owner.clone())
1450                .with_role(reference.role);
1451            Err(Error::Data(
1452                Diagnostic::new(
1453                    DiagnosticKind::StaleReference {
1454                        reference: Box::new(DiagnosticReference::Role(reference)),
1455                        current,
1456                    },
1457                    "data role reference is foreign or no longer bound",
1458                )
1459                .with_context(context),
1460            ))
1461        }
1462        DataSelector::Named(name) => {
1463            let message = format!("no explicitly declared named input {name:?}");
1464            Err(Error::Data(
1465                Diagnostic::new(
1466                    DiagnosticKind::UnknownKey {
1467                        key: Some(name.into()),
1468                    },
1469                    message,
1470                )
1471                .with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
1472            ))
1473        }
1474    }
1475}