doubleentry 0.7.0

An immutable, tamper-evident double-entry bookkeeping engine. Balanced-by-construction entries, exact integer money, deterministic identity, and an append-only Merkle log with inclusion and consistency proofs. Zero I/O. No async. No chart of accounts.
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
//! Posting dimensions.
//!
//! Dimensions are the axes reporting slices by, carried on every posting and
//! orthogonal to the account path. The account path carries the general-ledger
//! structure; dimensions carry everything else you need to group by.
//!
//! Encoding an axis into the path instead — `Grid:Electricity:HV:Revenue` —
//! multiplies the account count by the product of the axes and freezes the
//! reporting dimensions at design time. Keeping them separate lets a trial
//! balance group by any axis without restructuring the tree.
//!
//! # The axes are yours
//!
//! A [`Dimensions`] value is a small, ordered map from axis name to value, both
//! [`Label`]s. The engine ships no axis names, because there is no set that is
//! right for everyone: an energy utility separates by regulated activity, a fund
//! administrator by mandate, a marketplace by counterparty. Naming four of them
//! in the library would be a chart of accounts by another route — and would then
//! have to be worked around by everyone whose fifth axis matters.
//!
//! What the engine does is bound them ([`MAX_DIMENSIONS`] axes, [`MAX_LABEL_LEN`]
//! characters each), order them deterministically, fold them into the entry hash
//! so they are covered by tamper evidence, let you insist that a posting carry
//! the ones your books cannot be kept without — through
//! [`LedgerPolicy::required_dimensions`](crate::entry::LedgerPolicy::required_dimensions)
//! — and **report on them**: a [`DimensionFilter`] narrows any balance read, and
//! [`Journal::dimension_values`](crate::Journal::dimension_values) says which
//! values an axis actually takes. It never interprets one.
//!
//! ```
//! use doubleentry::{Dimensions, Label};
//!
//! let dims = Dimensions::none()
//!     .with(Label::new("activity")?, Label::new("Network")?)?
//!     .with(Label::new("segment")?, Label::new("Electricity")?)?;
//!
//! assert_eq!(dims.get("activity").map(Label::as_str), Some("Network"));
//! assert_eq!(dims.len(), 2);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::collections::BTreeMap;

use crate::canonical::{Canonical, CanonicalWriter};
use crate::serde_support::validating_string_serde;

/// Maximum length of an axis name or a dimension value, in characters.
pub const MAX_LABEL_LEN: usize = 64;

/// Maximum number of axes one posting may carry.
///
/// A bound rather than a limit anyone should reach. Dimensions are hashed into
/// every entry and written on every posting row, so an unbounded map would make
/// the size of a ledger a function of what a caller happened to attach; eight
/// independent reporting axes is already past what a chart of accounts can be
/// meaningfully sliced by.
pub const MAX_DIMENSIONS: usize = 8;

/// Failure constructing a label or a dimension set.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DimensionError {
    /// The value was empty.
    #[error("label is empty")]
    Empty,
    /// The value exceeded [`MAX_LABEL_LEN`].
    #[error("label exceeds {MAX_LABEL_LEN} characters")]
    TooLong,
    /// The value contained a control character.
    #[error("label contains a control character")]
    ControlCharacter,
    /// More than [`MAX_DIMENSIONS`] axes were attached to one posting.
    #[error("a posting may carry at most {MAX_DIMENSIONS} dimensions")]
    TooManyDimensions,
}

/// A validated, bounded string: an axis name, a dimension value, an identifier.
///
/// The same type is used for every short opaque string in the engine — a
/// dimension axis, a dimension value, an entry kind, a period identifier, a
/// provenance actor — because they have the same rules and inventing a newtype
/// per position would give type safety over values that are, by design,
/// interchangeable opaque text.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Label(String);

validating_string_serde!(Label);

impl Label {
    /// Validates and wraps a value.
    ///
    /// # Errors
    ///
    /// Rejects the empty string, anything longer than [`MAX_LABEL_LEN`]
    /// characters, and any control character. Control characters are refused
    /// because a label ends up in log lines, CSV exports and error messages, and
    /// an embedded newline or terminal escape turns one field into two.
    pub fn new(s: impl Into<String>) -> Result<Self, DimensionError> {
        let s = s.into();
        if s.is_empty() {
            return Err(DimensionError::Empty);
        }
        if s.chars().count() > MAX_LABEL_LEN {
            return Err(DimensionError::TooLong);
        }
        if s.chars().any(char::is_control) {
            return Err(DimensionError::ControlCharacter);
        }
        Ok(Self(s))
    }

    /// The underlying value.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for Label {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::str::FromStr for Label {
    type Err = DimensionError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s)
    }
}

/// Lets a `Label`-keyed map be looked up by `&str` without allocating.
///
/// Sound because `Label`'s `Ord` and `Hash` are the inner `String`'s, which are
/// `str`'s — the borrowed and owned forms compare and hash identically, which is
/// what `Borrow` requires.
impl std::borrow::Borrow<str> for Label {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Canonical for Label {
    fn encode(&self, w: &mut CanonicalWriter) {
        w.str(&self.0);
    }
}

/// The axes attached to one posting.
///
/// Ordered by axis name, so the canonical encoding — and therefore the entry
/// hash — does not depend on the order the axes were set.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Dimensions {
    axes: BTreeMap<Label, Label>,
}

impl Dimensions {
    /// No dimensions.
    #[must_use]
    pub fn none() -> Self {
        Self::default()
    }

    /// Attaches one axis, replacing any value already set for it.
    ///
    /// # Errors
    ///
    /// Returns [`DimensionError::TooManyDimensions`] when this would push the
    /// set past [`MAX_DIMENSIONS`]. Overwriting an axis already present never
    /// does.
    pub fn with(mut self, axis: Label, value: Label) -> Result<Self, DimensionError> {
        self.set(axis, value)?;
        Ok(self)
    }

    /// Attaches one axis in place, returning the value it replaced.
    ///
    /// # Errors
    ///
    /// Returns [`DimensionError::TooManyDimensions`] when this would push the
    /// set past [`MAX_DIMENSIONS`].
    pub fn set(&mut self, axis: Label, value: Label) -> Result<Option<Label>, DimensionError> {
        if !self.axes.contains_key(&axis) && self.axes.len() >= MAX_DIMENSIONS {
            return Err(DimensionError::TooManyDimensions);
        }
        Ok(self.axes.insert(axis, value))
    }

    /// Builds a dimension set from axis/value pairs.
    ///
    /// Later pairs win over earlier ones for the same axis.
    ///
    /// # Errors
    ///
    /// Returns [`DimensionError::TooManyDimensions`] when the pairs name more
    /// than [`MAX_DIMENSIONS`] distinct axes.
    pub fn from_pairs(
        pairs: impl IntoIterator<Item = (Label, Label)>,
    ) -> Result<Self, DimensionError> {
        let mut out = Self::none();
        for (axis, value) in pairs {
            out.set(axis, value)?;
        }
        Ok(out)
    }

    /// The value on `axis`, if it is set.
    #[must_use]
    pub fn get(&self, axis: &str) -> Option<&Label> {
        self.axes.get(axis)
    }

    /// True when `axis` is set.
    #[must_use]
    pub fn contains(&self, axis: &str) -> bool {
        self.get(axis).is_some()
    }

    /// Every axis and value, in axis order.
    pub fn iter(&self) -> impl ExactSizeIterator<Item = (&Label, &Label)> {
        self.axes.iter()
    }

    /// Number of axes set.
    #[must_use]
    pub fn len(&self) -> usize {
        self.axes.len()
    }

    /// True when no axis is set.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.axes.is_empty()
    }
}

impl<'a> IntoIterator for &'a Dimensions {
    type Item = (&'a Label, &'a Label);
    type IntoIter = std::collections::btree_map::Iter<'a, Label, Label>;
    fn into_iter(self) -> Self::IntoIter {
        self.axes.iter()
    }
}

impl Canonical for Dimensions {
    fn encode(&self, w: &mut CanonicalWriter) {
        // Counted, and in axis order: the encoding must be a function of the set,
        // not of the order the caller happened to build it in.
        w.seq(self.axes.iter(), |w, (axis, value)| {
            axis.encode(w);
            value.encode(w);
        });
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Dimensions {
    /// Serialised as a plain object, `{"activity": "Network"}`.
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        serde::Serialize::serialize(&self.axes, s)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Dimensions {
    /// Re-runs the cardinality check: a value read off a wire must satisfy the
    /// same bound as one that was constructed, or the bound guarantees nothing.
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let axes = <BTreeMap<Label, Label> as serde::Deserialize>::deserialize(d)?;
        Self::from_pairs(axes).map_err(serde::de::Error::custom)
    }
}

/// Which postings a report includes, by their dimensions.
///
/// A conjunction: every clause must hold.
///
/// - [`matching`](Self::matching): the axis is present and equal to this value.
/// - [`missing`](Self::missing): the axis is not set at all.
///
/// The second is what makes a set of reports **exhaustive**. Slice by the values
/// an axis takes and the totals will not reach the trial balance, because
/// postings carrying no value land in none of the slices.
/// [`LedgerPolicy::required_dimensions`](crate::entry::LedgerPolicy::required_dimensions)
/// prevents that going forward; `missing` finds what slipped through before.
///
/// ```
/// use doubleentry::{DimensionFilter, Dimensions, Label};
///
/// let network = Dimensions::none()
///     .with(Label::new("activity")?, Label::new("Network")?)?
///     .with(Label::new("segment")?, Label::new("Electricity")?)?;
///
/// let filter = DimensionFilter::any()
///     .matching(Label::new("activity")?, Label::new("Network")?)
///     .missing(Label::new("fund")?);
///
/// assert!(filter.matches(&network));
/// assert!(DimensionFilter::any().matches(&Dimensions::none()));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DimensionFilter {
    /// `Some(value)` requires equality; `None` requires the axis to be absent.
    clauses: BTreeMap<Label, Option<Label>>,
}

impl DimensionFilter {
    /// A filter that includes every posting.
    #[must_use]
    pub fn any() -> Self {
        Self::default()
    }

    /// Requires `axis` to be present and equal to `value`.
    ///
    /// Naming the same axis twice replaces the earlier clause: a posting carries
    /// at most one value per axis, so a conjunction of two different values for
    /// one axis could only ever match nothing, and silently returning an empty
    /// report is worse than taking the last word.
    #[must_use]
    pub fn matching(mut self, axis: Label, value: Label) -> Self {
        self.clauses.insert(axis, Some(value));
        self
    }

    /// Requires `axis` to be absent.
    #[must_use]
    pub fn missing(mut self, axis: Label) -> Self {
        self.clauses.insert(axis, None);
        self
    }

    /// True when this filter constrains nothing.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.clauses.is_empty()
    }

    /// Number of clauses.
    #[must_use]
    pub fn len(&self) -> usize {
        self.clauses.len()
    }

    /// Every clause, in axis order: `Some(value)` for an equality, `None` for an
    /// absence.
    ///
    /// Ordered so a backend building a query from it produces the same SQL for
    /// the same filter, which is what lets a statement cache do its job.
    pub fn clauses(&self) -> impl ExactSizeIterator<Item = (&Label, Option<&Label>)> {
        self.clauses.iter().map(|(a, v)| (a, v.as_ref()))
    }

    /// True when `dimensions` satisfies every clause.
    #[must_use]
    pub fn matches(&self, dimensions: &Dimensions) -> bool {
        self.clauses.iter().all(|(axis, expected)| {
            match (dimensions.get(axis.as_str()), expected.as_ref()) {
                (Some(actual), Some(want)) => actual == want,
                (None, None) => true,
                _ => false,
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn label(s: &str) -> Label {
        Label::new(s).expect("valid label")
    }

    #[test]
    fn validates_labels() {
        assert!(Label::new("Network").is_ok());
        assert_eq!(Label::new(""), Err(DimensionError::Empty));
        assert_eq!(
            Label::new("x".repeat(MAX_LABEL_LEN + 1)),
            Err(DimensionError::TooLong)
        );
        assert_eq!(
            Label::new("bad\nvalue"),
            Err(DimensionError::ControlCharacter)
        );
        assert!(Label::new("x".repeat(MAX_LABEL_LEN)).is_ok());
    }

    #[test]
    fn empty_dimensions_report_empty() {
        assert!(Dimensions::none().is_empty());
        let d = Dimensions::none()
            .with(label("activity"), label("Network"))
            .expect("fits");
        assert!(!d.is_empty());
        assert_eq!(d.len(), 1);
        assert!(d.contains("activity"));
        assert!(!d.contains("segment"));
    }

    #[test]
    fn setting_an_axis_twice_replaces_it() {
        let d = Dimensions::none()
            .with(label("activity"), label("Network"))
            .expect("fits")
            .with(label("activity"), label("Supply"))
            .expect("fits");
        assert_eq!(d.len(), 1);
        assert_eq!(d.get("activity").map(Label::as_str), Some("Supply"));
    }

    #[test]
    fn the_axis_count_is_bounded() {
        let mut d = Dimensions::none();
        for i in 0..MAX_DIMENSIONS {
            d = d
                .with(label(&format!("axis{i}")), label("v"))
                .expect("fits");
        }
        assert_eq!(
            d.clone().with(label("one-too-many"), label("v")),
            Err(DimensionError::TooManyDimensions)
        );
        // Replacing an existing axis at the bound is still fine.
        assert!(d.with(label("axis0"), label("w")).is_ok());
    }

    #[test]
    fn encoding_is_order_independent_and_stable() {
        let a = Dimensions::none()
            .with(label("activity"), label("N"))
            .expect("fits")
            .with(label("segment"), label("E"))
            .expect("fits");
        let b = Dimensions::none()
            .with(label("segment"), label("E"))
            .expect("fits")
            .with(label("activity"), label("N"))
            .expect("fits");
        assert_eq!(a.to_canonical_bytes(), b.to_canonical_bytes());
    }

    #[test]
    fn encoding_distinguishes_the_axis_from_the_value() {
        // Same strings, swapped roles: the encoding must tell them apart.
        let forward = Dimensions::none()
            .with(label("a"), label("b"))
            .expect("fits");
        let backward = Dimensions::none()
            .with(label("b"), label("a"))
            .expect("fits");
        assert_ne!(forward.to_canonical_bytes(), backward.to_canonical_bytes());
    }

    #[test]
    fn encoding_distinguishes_a_split_axis_name() {
        // Length prefixes: ("ab","c") must not encode as ("a","bc").
        let one = Dimensions::none()
            .with(label("ab"), label("c"))
            .expect("fits");
        let other = Dimensions::none()
            .with(label("a"), label("bc"))
            .expect("fits");
        assert_ne!(one.to_canonical_bytes(), other.to_canonical_bytes());
    }

    #[test]
    fn an_absent_axis_is_not_an_empty_value() {
        let absent = Dimensions::none();
        let present = Dimensions::none()
            .with(label("activity"), label("-"))
            .expect("fits");
        assert_ne!(absent.to_canonical_bytes(), present.to_canonical_bytes());
    }

    #[cfg(feature = "serde")]
    #[test]
    fn serde_round_trips_and_re_validates() {
        let d = Dimensions::none()
            .with(label("activity"), label("Network"))
            .expect("fits");
        let json = serde_json::to_string(&d).expect("serialises");
        assert_eq!(json, r#"{"activity":"Network"}"#);
        assert_eq!(
            serde_json::from_str::<Dimensions>(&json).expect("deserialises"),
            d
        );

        // Bounds are enforced on the way in, not merely on the way out.
        let overflowing: String = format!(
            "{{{}}}",
            (0..=MAX_DIMENSIONS)
                .map(|i| format!("\"axis{i}\":\"v\""))
                .collect::<Vec<_>>()
                .join(",")
        );
        assert!(serde_json::from_str::<Dimensions>(&overflowing).is_err());
        assert!(serde_json::from_str::<Dimensions>(r#"{"":"v"}"#).is_err());
    }
}