spanfold 0.1.0

Temporal state-window recording, comparison, and audit primitives for Rust.
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
use std::collections::BTreeMap;

use thiserror::Error;

use crate::{ComparisonDiagnostic, ComparisonResult, TemporalPoint};

/// Assertion failure returned by Spanfold testing helpers.
#[derive(Clone, Debug, Error, Eq, PartialEq)]
#[error("{message}")]
pub struct SpanfoldAssertionError {
    message: String,
}

impl SpanfoldAssertionError {
    /// Creates an assertion error with a concise message.
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
        }
    }

    /// Returns the failure message.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

/// Framework-neutral assertions for Spanfold comparison artifacts.
pub struct SpanfoldAssert;

impl SpanfoldAssert {
    /// Asserts that a comparison result is valid.
    pub fn is_valid(result: &ComparisonResult) -> Result<(), SpanfoldAssertionError> {
        if result.is_valid {
            return Ok(());
        }
        Err(SpanfoldAssertionError::new(
            "Expected a valid Spanfold result.",
        ))
    }

    /// Asserts that a comparison result contains no diagnostics.
    pub fn has_no_diagnostics(result: &ComparisonResult) -> Result<(), SpanfoldAssertionError> {
        if result.diagnostics.is_empty() {
            return Ok(());
        }
        Err(SpanfoldAssertionError::new(format!(
            "Expected no Spanfold diagnostics, found {}.",
            result.diagnostics.len()
        )))
    }

    /// Asserts that a comparison result contains a diagnostic code.
    pub fn has_diagnostic<'a>(
        result: &'a ComparisonResult,
        code: &str,
    ) -> Result<&'a ComparisonDiagnostic, SpanfoldAssertionError> {
        result
            .diagnostics
            .iter()
            .find(|diagnostic| diagnostic.code == code)
            .ok_or_else(|| {
                SpanfoldAssertionError::new(format!("Expected Spanfold diagnostic {code}."))
            })
    }

    /// Asserts that a named row collection contains an expected count.
    pub fn has_row_count(
        result: &ComparisonResult,
        row_type: &str,
        expected_count: usize,
    ) -> Result<(), SpanfoldAssertionError> {
        let actual = row_count(result, row_type)?;
        if actual == expected_count {
            return Ok(());
        }
        Err(SpanfoldAssertionError::new(format!(
            "Expected {expected_count} {row_type} rows, found {actual}."
        )))
    }

    /// Asserts that no row is provisional.
    pub fn has_no_provisional_rows(
        result: &ComparisonResult,
    ) -> Result<(), SpanfoldAssertionError> {
        if !result.has_provisional_rows() {
            return Ok(());
        }
        Err(SpanfoldAssertionError::new(format!(
            "Expected no provisional Spanfold rows, found {}.",
            result.provisional_row_finalities().len()
        )))
    }

    /// Asserts that at least one row is provisional.
    pub fn has_provisional_rows(result: &ComparisonResult) -> Result<(), SpanfoldAssertionError> {
        if result.has_provisional_rows() {
            return Ok(());
        }
        Err(SpanfoldAssertionError::new(
            "Expected at least one provisional Spanfold row.",
        ))
    }
}

/// Snapshot normalization helpers for Spanfold artifacts.
pub struct SpanfoldSnapshot;

impl SpanfoldSnapshot {
    /// Normalizes line endings, trailing whitespace, and volatile record IDs.
    #[must_use]
    pub fn normalize(value: &str, normalize_record_ids: bool) -> String {
        let mut normalized = value.replace("\r\n", "\n").replace('\r', "\n");
        normalized = normalized
            .lines()
            .map(str::trim_end)
            .collect::<Vec<_>>()
            .join("\n")
            .trim_end()
            .to_owned();
        if normalize_record_ids {
            normalized = normalize_hex_record_ids(&normalized);
        }
        normalized.push('\n');
        normalized
    }

    /// Asserts that two snapshot strings are equal after normalization.
    pub fn assert_equal(expected: &str, actual: &str) -> Result<(), SpanfoldAssertionError> {
        let normalized_expected = Self::normalize(expected, true);
        let normalized_actual = Self::normalize(actual, true);
        if normalized_expected == normalized_actual {
            return Ok(());
        }
        let expected_lines = normalized_expected.lines().collect::<Vec<_>>();
        let actual_lines = normalized_actual.lines().collect::<Vec<_>>();
        let first_difference = expected_lines
            .iter()
            .zip(&actual_lines)
            .position(|(expected, actual)| expected != actual)
            .unwrap_or(expected_lines.len().min(actual_lines.len()));
        Err(SpanfoldAssertionError::new(format!(
            "Spanfold snapshot mismatch at line {}.\n- {}\n+ {}",
            first_difference + 1,
            expected_lines
                .get(first_difference)
                .copied()
                .unwrap_or("<missing>"),
            actual_lines
                .get(first_difference)
                .copied()
                .unwrap_or("<missing>")
        )))
    }
}

/// Deterministic processing-position clock for comparison tests.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct VirtualComparisonClock {
    position: i64,
}

impl VirtualComparisonClock {
    /// Creates a clock at an initial processing position.
    pub fn new(initial_position: i64) -> Result<Self, SpanfoldAssertionError> {
        if initial_position < 0 {
            return Err(SpanfoldAssertionError::new(
                "Initial position cannot be negative.",
            ));
        }
        Ok(Self {
            position: initial_position,
        })
    }

    /// Creates a clock at position zero.
    #[must_use]
    pub const fn zero() -> Self {
        Self { position: 0 }
    }

    /// Returns the current position.
    #[must_use]
    pub const fn position(self) -> i64 {
        self.position
    }

    /// Returns the current processing-position horizon.
    #[must_use]
    pub fn horizon(self) -> TemporalPoint {
        TemporalPoint::position(self.position)
    }

    /// Advances by a non-negative position delta.
    pub fn advance_by(&mut self, positions: i64) -> Result<TemporalPoint, SpanfoldAssertionError> {
        if positions < 0 {
            return Err(SpanfoldAssertionError::new(
                "Position delta cannot be negative.",
            ));
        }
        self.position += positions;
        Ok(self.horizon())
    }

    /// Advances to an absolute processing position.
    pub fn advance_to(&mut self, position: i64) -> Result<TemporalPoint, SpanfoldAssertionError> {
        if position < self.position {
            return Err(SpanfoldAssertionError::new(
                "Virtual comparison clocks cannot move backwards.",
            ));
        }
        self.position = position;
        Ok(self.horizon())
    }
}

fn row_count(result: &ComparisonResult, row_type: &str) -> Result<usize, SpanfoldAssertionError> {
    let normalized = row_type.replace(['-', '_'], "").to_lowercase();
    match normalized.as_str() {
        "overlap" => Ok(result.overlap_rows.len()),
        "residual" => Ok(result.residual_rows.len()),
        "missing" => Ok(result.missing_rows.len()),
        "coverage" => Ok(result.coverage_rows.len()),
        "gap" => Ok(result.gap_rows.len()),
        "symmetricdifference" => Ok(result.symmetric_difference_rows.len()),
        "containment" => Ok(result.containment_rows.len()),
        "leadlag" => Ok(result.lead_lag_rows.len()),
        "asof" => Ok(result.as_of_rows.len()),
        _ => Err(SpanfoldAssertionError::new(format!(
            "Unknown Spanfold row type: {row_type}"
        ))),
    }
}

fn normalize_hex_record_ids(value: &str) -> String {
    let mut ids: BTreeMap<String, String> = BTreeMap::new();
    let mut next_id = 1;
    let mut output = String::with_capacity(value.len());
    let mut token = String::new();
    let mut normalize_token = false;

    for character in value.chars() {
        if normalize_token && character.is_ascii_hexdigit() {
            token.push(character);
            continue;
        }
        if normalize_token {
            flush_token(&mut output, &mut token, &mut ids, &mut next_id, true);
        }
        output.push(character);
        normalize_token = id_value_context(&output);
    }
    flush_token(
        &mut output,
        &mut token,
        &mut ids,
        &mut next_id,
        normalize_token,
    );
    output
}

fn flush_token(
    output: &mut String,
    token: &mut String,
    ids: &mut BTreeMap<String, String>,
    next_id: &mut usize,
    normalize: bool,
) {
    if normalize && token.len() >= 16 && token.len() <= 64 {
        let replacement = ids.entry(token.clone()).or_insert_with(|| {
            let replacement = format!("<record-id:{next_id}>");
            *next_id += 1;
            replacement
        });
        output.push_str(replacement);
    } else {
        output.push_str(token);
    }
    token.clear();
}

fn id_value_context(output: &str) -> bool {
    let suffix = output
        .rsplit_once('\n')
        .map_or(output, |(_, line)| line)
        .trim_end();
    suffix.ends_with("id=")
        || suffix.ends_with("recordId=")
        || suffix.ends_with("\"id\":\"")
        || suffix.ends_with("\"recordId\":\"")
        || suffix.ends_with("\"windowId\":\"")
        || suffix.ends_with("\"recordIds\":[\"")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        AgainstSelection, Comparator, ComparisonDuplicateWindowPolicy, ComparisonPlan,
        OpenWindowPolicy, WindowHistoryFixture,
    };

    #[test]
    fn fixture_aliases_can_create_comparison_history() {
        let history = crate::WindowHistoryFixture::new()
            .closed_window("DeviceOffline", "device-1", 1, 5, |window| {
                window.source("provider-a")
            })
            .expect("closed window")
            .closed_window("DeviceOffline", "device-1", 3, 7, |window| {
                window.source("provider-b")
            })
            .expect("closed window")
            .build();
        let plan = ComparisonPlan {
            name: "fixture helper".to_owned(),
            target_source: "provider-a".to_owned(),
            against: AgainstSelection::Sources(vec!["provider-b".to_owned()]),
            target_selector: None,
            against_selectors: Vec::new(),
            scope_window: Some("DeviceOffline".to_owned()),
            scope_key: None,
            scope_partition: None,
            scope_segments: Vec::new(),
            scope_tags: Vec::new(),
            comparators: vec![Comparator::Overlap, Comparator::Residual],
            require_closed_windows: true,
            use_half_open_ranges: true,
            time_axis: crate::TemporalAxis::ProcessingPosition,
            null_timestamp_policy: crate::ComparisonNullTimestampPolicy::Reject,
            known_at: None,
            open_window_policy: OpenWindowPolicy::RequireClosed,
            open_window_horizon: None,
            coalesce_adjacent_windows: false,
            duplicate_window_policy: ComparisonDuplicateWindowPolicy::Preserve,
            output: crate::ComparisonOutputOptions::default_options(),
            strict: false,
        };

        let result = crate::compare(&history, &plan);

        SpanfoldAssert::is_valid(&result).expect("valid result");
        SpanfoldAssert::has_row_count(&result, "overlap", 1).expect("overlap rows");
        SpanfoldAssert::has_row_count(&result, "residual", 1).expect("residual rows");
    }

    #[test]
    fn snapshot_helper_normalizes_record_ids_and_line_endings() {
        let expected = "recordId=0123456789abcdef\r\nrecordId=0123456789abcdef  \n";
        let actual = "recordId=fedcba9876543210\nrecordId=fedcba9876543210\n";

        SpanfoldSnapshot::assert_equal(expected, actual).expect("normalized snapshots");
    }

    #[test]
    fn virtual_clock_produces_deterministic_horizons() {
        let mut clock = VirtualComparisonClock::zero();

        assert_eq!(clock.horizon(), TemporalPoint::position(0));
        assert_eq!(
            clock.advance_by(5).expect("advance by"),
            TemporalPoint::position(5)
        );
        assert_eq!(
            clock.advance_to(9).expect("advance to"),
            TemporalPoint::position(9)
        );
        assert!(clock.advance_to(8).is_err());
    }

    #[test]
    fn assertion_reports_unknown_row_type() {
        let history = WindowHistoryFixture::new().build();
        let plan = ComparisonPlan {
            name: "empty".to_owned(),
            target_source: "provider-a".to_owned(),
            against: AgainstSelection::Sources(vec!["provider-b".to_owned()]),
            target_selector: None,
            against_selectors: Vec::new(),
            scope_window: None,
            scope_key: None,
            scope_partition: None,
            scope_segments: Vec::new(),
            scope_tags: Vec::new(),
            comparators: vec![Comparator::Overlap],
            require_closed_windows: true,
            use_half_open_ranges: true,
            time_axis: crate::TemporalAxis::ProcessingPosition,
            null_timestamp_policy: crate::ComparisonNullTimestampPolicy::Reject,
            known_at: None,
            open_window_policy: OpenWindowPolicy::RequireClosed,
            open_window_horizon: None,
            coalesce_adjacent_windows: false,
            duplicate_window_policy: ComparisonDuplicateWindowPolicy::Preserve,
            output: crate::ComparisonOutputOptions::default_options(),
            strict: false,
        };
        let result = crate::compare(&history, &plan);

        let error = SpanfoldAssert::has_row_count(&result, "not-a-row", 0)
            .expect_err("unknown rows should fail");

        assert!(error.message().contains("Unknown Spanfold row type"));
    }
}