KiThe 0.3.24

A numerical suite for chemical kinetics and thermodynamics, combustion, TGA, heat and mass transfer,chemical equilibrium, chemical engeneering
//! Row-scoped provenance for measured, simulated, and reconstructed values.
//!
//! This is separate from `ColumnProvenance`: the latter describes how a column
//! was transformed, while this module records which source contributed values
//! to selected rows and columns.

use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct DataLineage {
    /// Namespace shared by the dataset's internal row IDs.
    pub row_namespace: String,
    /// Next row ID to allocate. Undo must never move this counter backwards.
    pub next_row_id: u64,
    pub contributions: Vec<DataContribution>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct DataContribution {
    pub source: DataSource,
    pub columns: Vec<String>,
    pub row_ranges: Vec<RowIdRange>,
    /// Operation-level inputs; these are source ranges, not per-cell dependencies.
    #[serde(default)]
    pub input_refs: Vec<DataRowReference>,
    pub operation_id: Option<usize>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct DataRowReference {
    pub namespace: String,
    pub row_ranges: Vec<RowIdRange>,
    pub columns: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum DataSource {
    Measured {
        artifact_id: Option<String>,
    },
    Synthetic {
        description: String,
    },
    Simulated {
        model: String,
        parameters: Vec<(String, f64)>,
    },
    Reconstructed {
        method: String,
        parameters: Vec<(String, f64)>,
    },
    Imported {
        description: Option<String>,
    },
}

/// A compact inclusive range of stable row ordinals within one source namespace.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RowIdRange {
    pub namespace: String,
    pub first: u64,
    pub last: u64,
}

impl DataLineage {
    pub fn validate(&self) -> Result<(), String> {
        if !self.contributions.is_empty() && self.row_namespace.trim().is_empty() {
            return Err("Lineage contributions require a row identity namespace".into());
        }
        for contribution in &self.contributions {
            contribution.validate()?;
            if contribution
                .row_ranges
                .iter()
                .any(|range| range.namespace != self.row_namespace)
            {
                return Err("Lineage output rows must use the dataset namespace".into());
            }
        }
        Ok(())
    }

    /// Validate that output ranges refer to exactly the live IDs in this dataset.
    pub(crate) fn validate_current_rows(&self, ids: &[u64]) -> Result<(), String> {
        let live_count = ids.len();
        let mut ids = ids.to_vec();
        ids.sort_unstable();
        ids.dedup();
        if ids.len() != live_count {
            return Err("Live row IDs are not unique within their namespace".into());
        }
        if self.row_namespace.trim().is_empty() && !ids.is_empty() {
            return Err("Live row IDs have no namespace".into());
        }
        if ids.last().is_some_and(|max_id| self.next_row_id <= *max_id) {
            return Err("Next row ID must be greater than every live row ID".into());
        }
        for contribution in &self.contributions {
            for range in &contribution.row_ranges {
                if range.namespace != self.row_namespace {
                    return Err(format!(
                        "Lineage output range uses foreign namespace '{}'",
                        range.namespace
                    ));
                }
                let begin = ids.partition_point(|id| *id < range.first);
                let end = ids.partition_point(|id| *id <= range.last);
                let expected = range
                    .last
                    .checked_sub(range.first)
                    .and_then(|span| span.checked_add(1))
                    .ok_or_else(|| "Lineage row range overflows UInt64".to_string())?;
                if (end - begin) as u64 != expected {
                    return Err(format!(
                        "Lineage output range {}..={} does not match live row IDs",
                        range.first, range.last
                    ));
                }
            }
        }
        Ok(())
    }

    pub(crate) fn validate_history_links(&self, history_len: usize) -> Result<(), String> {
        if self.contributions.iter().any(|contribution| {
            contribution
                .operation_id
                .is_some_and(|operation_id| operation_id >= history_len)
        }) {
            return Err("Lineage references an operation missing from dataset history".into());
        }
        Ok(())
    }

    pub(crate) fn retain_columns(&mut self, columns: &[&str]) {
        for contribution in &mut self.contributions {
            contribution
                .columns
                .retain(|column| columns.contains(&column.as_str()));
        }
        self.contributions
            .retain(|contribution| !contribution.columns.is_empty());
    }

    pub(crate) fn rename_column(&mut self, old: &str, new: &str) {
        for contribution in &mut self.contributions {
            for column in &mut contribution.columns {
                if column == old {
                    *column = new.to_string();
                }
            }
        }
    }

    /// Keep only row IDs still present after a row-removing operation.
    pub(crate) fn retain_current_rows(&mut self, current_ids: &[u64]) {
        let mut current_ids = current_ids.to_vec();
        current_ids.sort_unstable();
        current_ids.dedup();

        for contribution in &mut self.contributions {
            let mut retained = Vec::new();
            for range in &contribution.row_ranges {
                if range.namespace != self.row_namespace {
                    retained.push(range.clone());
                    continue;
                }
                let begin = current_ids.partition_point(|id| *id < range.first);
                let end = current_ids.partition_point(|id| *id <= range.last);
                let mut values = current_ids[begin..end].iter().copied();
                let Some(mut first) = values.next() else {
                    continue;
                };
                let mut last = first;
                for id in values {
                    if id == last.saturating_add(1) {
                        last = id;
                    } else {
                        retained.push(RowIdRange {
                            namespace: range.namespace.clone(),
                            first,
                            last,
                        });
                        first = id;
                        last = id;
                    }
                }
                retained.push(RowIdRange {
                    namespace: range.namespace.clone(),
                    first,
                    last,
                });
            }
            contribution.row_ranges = retained;
        }
        self.contributions
            .retain(|contribution| !contribution.row_ranges.is_empty());
    }

    /// Move row references from an appended dataset into the target namespace.
    pub(crate) fn remap_appended_rows(
        &mut self,
        source_namespace: &str,
        target_namespace: &str,
        offset: u64,
    ) -> Result<(), String> {
        for contribution in &mut self.contributions {
            for range in &mut contribution.row_ranges {
                if range.namespace == source_namespace {
                    range.namespace = target_namespace.to_string();
                    range.first = range
                        .first
                        .checked_add(offset)
                        .ok_or_else(|| "Appended row identity exceeds UInt64 range".to_string())?;
                    range.last = range
                        .last
                        .checked_add(offset)
                        .ok_or_else(|| "Appended row identity exceeds UInt64 range".to_string())?;
                }
            }
        }
        self.row_namespace = target_namespace.to_string();
        Ok(())
    }

    /// Move this dataset's own row references to a fresh identity namespace.
    pub(crate) fn fork_namespace(&mut self, namespace: String) {
        let old_namespace = std::mem::replace(&mut self.row_namespace, namespace.clone());
        for contribution in &mut self.contributions {
            for range in &mut contribution.row_ranges {
                if range.namespace == old_namespace {
                    range.namespace = namespace.clone();
                }
            }
        }
    }
}

impl RowIdRange {
    pub fn new(namespace: impl Into<String>, first: u64, last: u64) -> Option<Self> {
        (first <= last).then(|| Self {
            namespace: namespace.into(),
            first,
            last,
        })
    }
}

impl DataContribution {
    pub fn validate(&self) -> Result<(), String> {
        if self.columns.is_empty() {
            return Err("A data contribution must name at least one column".into());
        }
        if self.row_ranges.is_empty() {
            return Err("A data contribution must identify at least one row range".into());
        }
        if self
            .row_ranges
            .iter()
            .any(|range| range.namespace.is_empty() || range.first > range.last)
        {
            return Err("A data contribution contains an invalid row range".into());
        }
        validate_disjoint_ranges(&self.row_ranges)?;
        if self.columns.iter().any(|column| column.trim().is_empty()) {
            return Err("A data contribution contains an empty column name".into());
        }
        if self.input_refs.iter().any(|input| {
            input.namespace.trim().is_empty()
                || input.columns.is_empty()
                || input.columns.iter().any(|column| column.trim().is_empty())
                || input.row_ranges.is_empty()
                || input.row_ranges.iter().any(|range| {
                    range.namespace.trim().is_empty()
                        || range.namespace != input.namespace
                        || range.first > range.last
                })
        }) {
            return Err("A data contribution contains an invalid input row reference".into());
        }
        for input in &self.input_refs {
            validate_disjoint_ranges(&input.row_ranges)?;
        }
        let parameters = match &self.source {
            DataSource::Simulated { parameters, .. }
            | DataSource::Reconstructed { parameters, .. } => parameters,
            DataSource::Measured { .. }
            | DataSource::Synthetic { .. }
            | DataSource::Imported { .. } => return Ok(()),
        };
        if parameters
            .iter()
            .any(|(name, value)| name.trim().is_empty() || !value.is_finite())
        {
            return Err("Lineage parameters must have names and finite values".into());
        }
        Ok(())
    }
}

fn validate_disjoint_ranges(ranges: &[RowIdRange]) -> Result<(), String> {
    let mut sorted = ranges.iter().collect::<Vec<_>>();
    sorted.sort_unstable_by(|left, right| {
        left.namespace
            .cmp(&right.namespace)
            .then_with(|| left.first.cmp(&right.first))
    });
    for pair in sorted.windows(2) {
        if pair[0].namespace == pair[1].namespace && pair[1].first <= pair[0].last {
            return Err("Lineage row ranges overlap".into());
        }
    }
    Ok(())
}