brygge-ir 0.10.0

brygge's intermediate representation: the faithfulness-with-provenance model, its canonical content-addressed artifact, and the honesty machinery. The light core that links no source-decoder dependency.
Documentation
//! Deterministic IR construction (RFC 003 D-5, RFC 011 §2.5).
//!
//! [`IrBuilder`] is the sanctioned way to build an [`Ir`]: it canonicalizes each atom's operations and
//! copies, computes the content-addressed [`AtomId`], validates that refs target known atoms and that a
//! copy's `from_atom` was already added, and on [`IrBuilder::finish`] emits atoms in a deterministic
//! **topological order with a total tiebreak by source atom id**, refs/drops/flags in their own
//! canonical orders, and prunes any blob no op ended up referencing — so re-decoding the same source
//! yields byte-identical output (`VF-1`).

use std::collections::{BTreeMap, BTreeSet};

use crate::content::{BlobId, ContentStore, Storage};
use crate::model::{
    AtomId, ChangeAtom, Content, CopyRecord, Flag, ImportProvenance, Ir, LossBoundary,
    MetadataClaims, PathOp, RefRecord, SourceIdentity, TransformRecord,
};
use crate::status::EpistemicStatus;
use crate::{Error, Result};

/// An atom to add, without its (computed) id.
#[derive(Debug, Clone)]
pub struct AtomDraft {
    /// Parent atom ids, order significant.
    pub parents: Vec<AtomId>,
    /// Path operations (any order; the builder canonicalizes).
    pub ops: Vec<PathOp>,
    /// Copy records (any order; the builder canonicalizes).
    pub copies: Vec<CopyRecord>,
    /// Message/authorship claims.
    pub metadata: MetadataClaims,
    /// The source's opaque identity for this atom.
    pub source: SourceIdentity,
    /// Atom-level epistemic status.
    pub status: EpistemicStatus,
}

/// The default ceiling for [`IrBuilder`]'s running count of every atom's `ops`, across the whole
/// artifact (0.8.1, the amplification-bounds patch): the total `PathOp`s a decoder or an `Edit`-based
/// transform can add before `add_atom` refuses, so an amplifying input cannot grow the IR itself without
/// bound even once a decoder's own ceilings (tree entries, copy expansion, snapshot retention) are held.
pub(crate) const DEFAULT_MAX_IR_OPS: usize = 200_000_000;

/// Builds an [`Ir`] deterministically.
#[derive(Debug)]
pub struct IrBuilder {
    content: ContentStore,
    atoms: Vec<ChangeAtom>,
    known: BTreeSet<AtomId>,
    refs: Vec<RefRecord>,
    provenance: ImportProvenance,
    loss: LossBoundary,
    flags: Vec<Flag>,
    transforms: Vec<TransformRecord>,
    max_ops: usize,
    total_ops: usize,
}

impl IrBuilder {
    /// Start a build with the given import provenance.
    #[must_use]
    pub fn new(provenance: ImportProvenance) -> Self {
        Self {
            content: ContentStore::new(),
            atoms: Vec::new(),
            known: BTreeSet::new(),
            refs: Vec::new(),
            provenance,
            loss: LossBoundary::default(),
            flags: Vec::new(),
            transforms: Vec::new(),
            max_ops: DEFAULT_MAX_IR_OPS,
            total_ops: 0,
        }
    }

    /// Start a build with the given import provenance and [`Storage`] (RFC 015 D-3). `Storage::Memory`
    /// behaves exactly like [`IrBuilder::new`]; `Storage::Spill` opens a private spill file in the given
    /// directory (RFC 015 D-3a). The storage is never recorded in `provenance`: it cannot change the
    /// output (review 076).
    ///
    /// # Errors
    /// [`Error::Io`] if `storage` is `Storage::Spill` and the spill file could not be created.
    pub fn with_storage(provenance: ImportProvenance, storage: &Storage) -> Result<Self> {
        Ok(Self {
            content: ContentStore::for_storage(storage)?,
            atoms: Vec::new(),
            known: BTreeSet::new(),
            refs: Vec::new(),
            provenance,
            loss: LossBoundary::default(),
            flags: Vec::new(),
            transforms: Vec::new(),
            max_ops: DEFAULT_MAX_IR_OPS,
            total_ops: 0,
        })
    }

    /// Override [`DEFAULT_MAX_IR_OPS`] for a test, so the ceiling can be crossed without building an
    /// artifact anywhere near 200,000,000 operations (0.8.1).
    #[cfg(test)]
    pub(crate) fn with_max_ops_for_test(mut self, max_ops: usize) -> Self {
        self.max_ops = max_ops;
        self
    }

    /// Insert file bytes into the content store, returning the content address.
    ///
    /// # Errors
    /// [`Error::Io`] if the store is file-backed (RFC 015 D-3) and the blob could not be written.
    pub fn add_blob(&mut self, bytes: Vec<u8>) -> Result<BlobId> {
        self.content.insert(bytes)
    }

    /// The bytes of a blob already given to [`add_blob`](Self::add_blob), if any: a read accessor over the
    /// content store the builder holds, for a decoder whose next change is a delta against content it has
    /// already added (Subversion's svndiff). It lets the decoder keep no second copy of file contents.
    ///
    /// # Errors
    /// [`Error::Io`] if the store is file-backed (RFC 015 D-3) and `id` is present but could not be
    /// read back.
    pub fn blob(&self, id: &BlobId) -> Result<Option<Vec<u8>>> {
        self.content.get(id)
    }

    /// Add an atom, canonicalizing its operations and copies and computing its id.
    ///
    /// # Errors
    /// [`Error::Invariant`] if two ops in `draft.ops` share a path, two copies share the same `(to,
    /// from, from_atom)`, or a copy's `from_atom` is not an atom already added.
    pub fn add_atom(&mut self, draft: AtomDraft) -> Result<AtomId> {
        let mut ops = draft.ops;
        // 0.8.1: counted and checked before this atom's ops are stored, so an amplifying input cannot
        // grow the IR without bound even once a decoder's own ceilings are held (every decoder and every
        // `Edit`-based transform builds through here).
        let next_total = self.total_ops.saturating_add(ops.len());
        if next_total > self.max_ops {
            return Err(Error::ResourceLimit {
                what: "the path-operation total in this artifact".to_string(),
                ceiling: format!("{} operations", self.max_ops),
            });
        }
        self.total_ops = next_total;
        ops.sort_by(|a, b| a.path().cmp(b.path()));
        for (a, b) in ops.iter().zip(ops.iter().skip(1)) {
            if a.path() == b.path() {
                return Err(Error::Invariant(format!(
                    "two ops on one path in one atom: {:?}",
                    a.path()
                )));
            }
        }
        // RFC 021 D-1: a submodule's pinned commit id must be 20 bytes (SHA-1) or 32 (SHA-256) — the
        // only two lengths a Git repository's own object format ever produces. This check applies to
        // `Content::Submodule` only; a blob's address is already fixed-length by its type.
        for op in &ops {
            if let Some(Content::Submodule { commit }) = op.content() {
                if commit.len() != 20 && commit.len() != 32 {
                    return Err(Error::Invariant(format!(
                        "a submodule's commit id is {} bytes at {:?}, must be 20 or 32",
                        commit.len(),
                        op.path()
                    )));
                }
            }
        }
        let mut copies = draft.copies;
        copies.sort_by(|a, b| (&a.to, &a.from, a.from_atom).cmp(&(&b.to, &b.from, b.from_atom)));
        for (a, b) in copies.iter().zip(copies.iter().skip(1)) {
            if (&a.to, &a.from, a.from_atom) == (&b.to, &b.from, b.from_atom) {
                return Err(Error::Invariant(format!(
                    "two copy records with the same (to, from, from_atom): ({:?}, {:?}, {})",
                    a.to, a.from, a.from_atom
                )));
            }
        }
        for copy in &copies {
            if !self.known.contains(&copy.from_atom) {
                return Err(Error::Invariant(format!(
                    "copy of {:?} names from_atom {} which was not already added",
                    copy.from, copy.from_atom
                )));
            }
        }

        let mut atom = ChangeAtom {
            id: AtomId([0u8; 32]),
            parents: draft.parents,
            ops,
            copies,
            metadata: draft.metadata,
            source: draft.source,
            status: draft.status,
        };
        atom.id = atom.compute_id();
        let id = atom.id;
        self.known.insert(id);
        self.atoms.push(atom);
        Ok(id)
    }

    /// Add a ref. The target must be an atom already added.
    ///
    /// # Errors
    /// [`Error::Invariant`] if `record.target` is not a known atom.
    pub fn add_ref(&mut self, record: RefRecord) -> Result<()> {
        if !self.known.contains(&record.target) {
            return Err(Error::Invariant(format!(
                "ref {:?} targets unknown atom {}",
                record.name, record.target
            )));
        }
        self.refs.push(record);
        Ok(())
    }

    /// Set the loss boundary for this import.
    pub fn set_loss(&mut self, loss: LossBoundary) {
        self.loss = loss;
    }

    /// Add a flagged condition (RFC 011 D-8) — drives CLI exit 30.
    pub fn add_flag(&mut self, flag: Flag) {
        self.flags.push(flag);
    }

    /// Add one transform record (RFC 018 D-5), oldest first. Returns the step index this record now
    /// has — `self.transforms.len()` just before the push — the index later
    /// [`crate::status::EpistemicStatus::Transformed`] values and [`crate::model::DropRecord::step`]
    /// reference.
    pub fn add_transform(&mut self, record: TransformRecord) -> usize {
        let step = self.transforms.len();
        self.transforms.push(record);
        step
    }

    /// Finish the build: order the atoms canonically, sort refs/drops/flags, prune unreferenced blobs,
    /// and assemble the [`Ir`].
    ///
    /// # Errors
    /// [`Error::Invariant`] if the atom graph contains a cycle (source histories are acyclic; a cycle
    /// signals a decoder bug), or if two refs share `(name, kind variant)`, two drops share
    /// `(class, what)`, or two flags share `(kind, what)` (the reader would refuse such an artifact).
    pub fn finish(self) -> Result<Ir> {
        let ordered = topo_order(&self.atoms)?;

        // The canonical orders are on the variant numbers of the format (`ir-artifact-format.md` §6), the
        // same numbers the reader checks. A key that repeats cannot be written: the reader would refuse it.
        let mut refs = self.refs;
        refs.sort_by(|a, b| (&a.name, a.kind.variant()).cmp(&(&b.name, b.kind.variant())));
        if let Some((a, _)) = refs
            .iter()
            .zip(refs.iter().skip(1))
            .find(|(a, b)| (&a.name, a.kind.variant()) == (&b.name, b.kind.variant()))
        {
            return Err(Error::Invariant(format!(
                "two refs named {:?} of one kind",
                a.name
            )));
        }

        if self.transforms.len() > 64 {
            return Err(Error::Invariant(
                "more than 64 transform records".to_string(),
            ));
        }

        let mut loss = self.loss;
        loss.dropped.sort_by(|a, b| {
            (a.class.variant(), a.step, &a.what).cmp(&(b.class.variant(), b.step, &b.what))
        });
        if let Some((a, _)) = loss
            .dropped
            .iter()
            .zip(loss.dropped.iter().skip(1))
            .find(|(a, b)| {
                (a.class.variant(), a.step, &a.what) == (b.class.variant(), b.step, &b.what)
            })
        {
            return Err(Error::Invariant(format!(
                "two drops of one class/step with the same `what`: {:?}",
                a.what
            )));
        }

        let mut flags = self.flags;
        flags.sort_by(|a, b| (a.kind.variant(), &a.what).cmp(&(b.kind.variant(), &b.what)));
        if let Some((a, _)) = flags
            .iter()
            .zip(flags.iter().skip(1))
            .find(|(a, b)| (a.kind.variant(), &a.what) == (b.kind.variant(), &b.what))
        {
            return Err(Error::Invariant(format!(
                "two flags of one kind with the same `what`: {:?}",
                a.what
            )));
        }

        let referenced: BTreeSet<BlobId> = ordered
            .iter()
            .flat_map(|a| a.ops.iter())
            .filter_map(|op| match op.content() {
                Some(Content::Blob { blob, .. }) => Some(*blob),
                Some(Content::Submodule { .. }) | None => None,
            })
            .collect();
        let mut content = self.content;
        content.retain(|id| referenced.contains(id));

        Ok(Ir {
            atoms: ordered,
            refs,
            provenance: self.provenance,
            loss,
            flags,
            content,
            transforms: self.transforms,
        })
    }
}

/// Deterministic topological order: Kahn's algorithm, with the ready set ordered by
/// (source atom id, `AtomId`) so ties break the same way every run (RFC 003 D-5, RFC 011 §2.5). Returns
/// only the id sequence — shared between [`topo_order`] (construction) and
/// [`crate::artifact::from_bytes`] (decode-time verification that stored atoms are already in this
/// order). `None` means the atom graph contains a cycle.
pub(crate) fn canonical_order_ids(atoms: &[ChangeAtom]) -> Option<Vec<AtomId>> {
    let by_id: BTreeMap<AtomId, &ChangeAtom> = atoms.iter().map(|a| (a.id, a)).collect();
    // in-degree counts only parents that are part of this set (external parents are treated as roots).
    let mut indegree: BTreeMap<AtomId, usize> = atoms.iter().map(|a| (a.id, 0usize)).collect();
    let mut children: BTreeMap<AtomId, Vec<AtomId>> = BTreeMap::new();
    for a in atoms {
        for p in &a.parents {
            if by_id.contains_key(p) {
                children.entry(*p).or_default().push(a.id);
                if let Some(d) = indegree.get_mut(&a.id) {
                    *d += 1;
                }
            }
        }
    }
    // ready set keyed by (source atom id bytes, atom id) for a stable total order.
    let mut ready: BTreeSet<(Vec<u8>, AtomId)> = BTreeSet::new();
    for a in atoms {
        if indegree.get(&a.id).copied().unwrap_or(0) == 0 {
            ready.insert((a.source.atom_id.clone(), a.id));
        }
    }
    let mut out: Vec<AtomId> = Vec::with_capacity(atoms.len());
    while let Some(key) = ready.iter().next().cloned() {
        ready.remove(&key);
        let id = key.1;
        out.push(id);
        if let Some(kids) = children.get(&id) {
            for kid in kids {
                if let Some(d) = indegree.get_mut(kid) {
                    *d = d.saturating_sub(1);
                    if *d == 0 {
                        if let Some(k) = by_id.get(kid) {
                            ready.insert((k.source.atom_id.clone(), *kid));
                        }
                    }
                }
            }
        }
    }
    if out.len() != atoms.len() {
        return None;
    }
    Some(out)
}

/// Order `atoms` canonically (construction time — see [`canonical_order_ids`]).
fn topo_order(atoms: &[ChangeAtom]) -> Result<Vec<ChangeAtom>> {
    let order = canonical_order_ids(atoms).ok_or_else(|| {
        Error::Invariant("atom graph contains a cycle (source history must be acyclic)".to_string())
    })?;
    let mut by_id: BTreeMap<AtomId, ChangeAtom> =
        atoms.iter().cloned().map(|a| (a.id, a)).collect();
    Ok(order
        .into_iter()
        .filter_map(|id| by_id.remove(&id))
        .collect())
}

#[cfg(test)]
mod tests;