etl-unit 0.1.0

Semantic data model for ETL units — qualities and measurements over subjects and time. Built on Polars.
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! Validation and instrumentation for signal policy operations.
//!
//! NOTE: Not yet activated. This module defines a validation framework
//! for asserting DataFrame shape and signal policy expectations before
//! and after processing. The signal policy currently works without
//! these checks. Revisit when adding automated signal policy testing
//! or when debugging policy behavior in production.
//!
//! Provides pre/post validation, shape assertions, and detailed tracing
//! to catch issues early and aid debugging.

use polars::{datatypes::TimeUnit as PolarsTimeUnit, prelude::*};
use serde::{Deserialize, Serialize};
use tracing::{debug, warn};

use crate::{EtlError, EtlResult};

// =============================================================================
// DataFrame Shape Snapshot
// =============================================================================

/// Captures the shape and schema of a DataFrame for validation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataFrameShape {
    pub rows: usize,
    pub cols: usize,
    pub column_names: Vec<String>,
    #[serde(skip)]
    pub column_dtypes: Vec<DataType>,
}

impl DataFrameShape {
    pub fn from_df(df: &DataFrame) -> Self {
        Self {
            rows: df.height(),
            cols: df.width(),
            column_names: df
                .get_column_names()
                .iter()
                .map(|s| s.to_string())
                .collect(),
            column_dtypes: df.dtypes().to_vec(),
        }
    }

    /// Check if another shape has the same columns (names and types)
    pub fn columns_match(&self, other: &DataFrameShape) -> bool {
        self.column_names == other.column_names && self.column_dtypes == other.column_dtypes
    }

    /// Get dtype for a column by name
    pub fn get_dtype(&self, col_name: &str) -> Option<&DataType> {
        self.column_names
            .iter()
            .position(|n| n == col_name)
            .map(|i| &self.column_dtypes[i])
    }

    /// Assert a column exists with expected dtype
    pub fn assert_column_dtype(&self, col_name: &str, expected: &DataType) -> EtlResult<()> {
        match self.get_dtype(col_name) {
            Some(actual) if actual == expected => Ok(()),
            Some(actual) => Err(EtlError::Config(format!(
                "Column '{}' has wrong type: expected {:?}, got {:?}",
                col_name, expected, actual
            ))),
            None => Err(EtlError::MissingColumn(col_name.to_string())),
        }
    }

    /// Assert column is a Datetime type (any unit), return the unit
    pub fn assert_datetime_column(&self, col_name: &str) -> EtlResult<PolarsTimeUnit> {
        match self.get_dtype(col_name) {
            Some(DataType::Datetime(tu, _)) => Ok(*tu),
            Some(actual) => Err(EtlError::Config(format!(
                "Column '{}' must be Datetime type, got {:?}",
                col_name, actual
            ))),
            None => Err(EtlError::MissingColumn(col_name.to_string())),
        }
    }

    /// Get dtype as string for serialization
    pub fn dtype_strings(&self) -> Vec<String> {
        self.column_dtypes
            .iter()
            .map(|dt| format!("{:?}", dt))
            .collect()
    }
}

impl std::fmt::Display for DataFrameShape {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "({} rows × {} cols)", self.rows, self.cols)
    }
}

// =============================================================================
// Signal Policy Expectations
// =============================================================================

/// Expected characteristics of signal policy output
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyExpectation {
    /// Name of the policy for logging
    pub policy_name: String,
    /// Input time span in the source time unit
    pub input_time_span: i64,
    /// Time unit being used (as string for serialization)
    pub time_unit_str: String,
    /// Number of partitions (subjects × components)
    pub partition_count: usize,

    #[serde(skip, default = "default_time_unit")]
    pub time_unit: PolarsTimeUnit,
}

impl PolicyExpectation {
    pub fn new(policy_name: impl Into<String>) -> Self {
        Self {
            policy_name: policy_name.into(),
            input_time_span: 0,
            time_unit: PolarsTimeUnit::Milliseconds,
            time_unit_str: "Milliseconds".into(),
            partition_count: 1,
        }
    }

    pub fn with_time_span(mut self, span: i64) -> Self {
        self.input_time_span = span;
        self
    }

    pub fn with_time_unit(mut self, tu: PolarsTimeUnit) -> Self {
        self.time_unit = tu;
        self.time_unit_str = format!("{:?}", tu);
        self
    }

    pub fn with_partition_count(mut self, count: usize) -> Self {
        self.partition_count = count;
        self
    }
}

impl std::fmt::Display for PolicyExpectation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: span={}, partitions={}",
            self.policy_name, self.input_time_span, self.partition_count,
        )
    }
}

// =============================================================================
// Validation Results
// =============================================================================

/// Result of a single validation check
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValidationResult {
    Ok,
    Warning(String),
    Error(String),
}

impl ValidationResult {
    pub fn is_ok(&self) -> bool {
        matches!(self, ValidationResult::Ok)
    }

    pub fn is_warning(&self) -> bool {
        matches!(self, ValidationResult::Warning(_))
    }

    pub fn is_error(&self) -> bool {
        matches!(self, ValidationResult::Error(_))
    }

    /// Get the message if this is a warning or error
    pub fn message(&self) -> Option<&str> {
        match self {
            ValidationResult::Ok => None,
            ValidationResult::Warning(msg) => Some(msg),
            ValidationResult::Error(msg) => Some(msg),
        }
    }

    /// Convert to a string suitable for metadata
    pub fn to_issue_string(&self) -> Option<String> {
        match self {
            ValidationResult::Ok => None,
            ValidationResult::Warning(msg) => Some(format!("[WARN] {}", msg)),
            ValidationResult::Error(msg) => Some(format!("[ERROR] {}", msg)),
        }
    }

    /// Log the result at appropriate level
    pub fn log(&self, context: &str) {
        match self {
            ValidationResult::Ok => {
                debug!(context = context, "Validation passed");
            }
            ValidationResult::Warning(msg) => {
                warn!(context = context, warning = %msg, "Validation warning");
            }
            ValidationResult::Error(msg) => {
                tracing::error!(context = context, error = %msg, "Validation failed");
            }
        }
    }
}

// =============================================================================
// Validation Events (for MetaCollector)
// =============================================================================

/// A validation event that can be collected during processing
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationEvent {
    /// Context where validation occurred (e.g., "instant_policy", "time_bucket")
    pub context: String,
    /// The validation result
    pub result: ValidationResult,
    /// Optional details about the validation
    pub details: Option<ValidationDetails>,
}

impl ValidationEvent {
    pub fn ok(context: impl Into<String>) -> Self {
        Self {
            context: context.into(),
            result: ValidationResult::Ok,
            details: None,
        }
    }

    pub fn warning(context: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            context: context.into(),
            result: ValidationResult::Warning(message.into()),
            details: None,
        }
    }

    pub fn error(context: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            context: context.into(),
            result: ValidationResult::Error(message.into()),
            details: None,
        }
    }

    pub fn with_details(mut self, details: ValidationDetails) -> Self {
        self.details = Some(details);
        self
    }

    /// Convert to a human-readable issue string
    pub fn to_issue_string(&self) -> Option<String> {
        self.result
            .to_issue_string()
            .map(|msg| format!("{}: {}", self.context, msg))
    }
}

/// Additional details about a validation event
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationDetails {
    /// Input row count
    #[serde(skip_serializing_if = "Option::is_none")]
    pub input_rows: Option<usize>,
    /// Output row count
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_rows: Option<usize>,
    /// Expected row count
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected_rows: Option<usize>,
    /// Columns involved
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub columns: Vec<String>,
    /// Time unit used
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_unit: Option<String>,
}

impl ValidationDetails {
    pub fn new() -> Self {
        Self {
            input_rows: None,
            output_rows: None,
            expected_rows: None,
            columns: Vec::new(),
            time_unit: None,
        }
    }

    pub fn with_input_rows(mut self, rows: usize) -> Self {
        self.input_rows = Some(rows);
        self
    }

    pub fn with_output_rows(mut self, rows: usize) -> Self {
        self.output_rows = Some(rows);
        self
    }

    pub fn with_expected_rows(mut self, rows: usize) -> Self {
        self.expected_rows = Some(rows);
        self
    }

    pub fn with_columns(mut self, columns: Vec<String>) -> Self {
        self.columns = columns;
        self
    }

    pub fn with_time_unit(mut self, tu: PolarsTimeUnit) -> Self {
        self.time_unit = Some(format!("{:?}", tu));
        self
    }
}

impl Default for ValidationDetails {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Policy Validator
// =============================================================================

/// Validates signal policy operations pre and post execution
#[derive(Debug)]
pub struct PolicyValidator {
    pub policy_name: String,
    pub input_shape: DataFrameShape,
    pub time_col: String,
    pub time_unit: PolarsTimeUnit,
    pub expectation: Option<PolicyExpectation>,
    /// Collected validation events during processing
    events: Vec<ValidationEvent>,
}

impl PolicyValidator {
    /// Create validator from input DataFrame
    pub fn new(
        policy_name: impl Into<String>,
        df: &DataFrame,
        time_col: impl Into<String>,
    ) -> EtlResult<Self> {
        let policy_name = policy_name.into();
        let time_col = time_col.into();
        let input_shape = DataFrameShape::from_df(df);

        // Validate and extract time unit
        let time_unit = input_shape.assert_datetime_column(&time_col)?;

        debug!(
             policy = %policy_name,
             input_shape = %input_shape,
             time_col = %time_col,
             time_unit = ?time_unit,
             columns = ?input_shape.column_names,
             "PolicyValidator created"
        );

        Ok(Self {
            policy_name,
            input_shape,
            time_col,
            time_unit,
            expectation: None,
            events: Vec::new(),
        })
    }

    /// Set expected output characteristics
    pub fn with_expectation(mut self, expectation: PolicyExpectation) -> Self {
        debug!(
             policy = %self.policy_name,
             expectation = %expectation,
             "Set policy expectation"
        );
        self.expectation = Some(expectation);
        self
    }

    /// Record a validation event
    pub fn record_event(&mut self, event: ValidationEvent) {
        event.result.log(&event.context);
        self.events.push(event);
    }

    /// Get all collected events
    pub fn events(&self) -> &[ValidationEvent] {
        &self.events
    }

    /// Get all events as issue strings (filtering out Ok results)
    pub fn issue_strings(&self) -> Vec<String> {
        self.events
            .iter()
            .filter_map(|e| e.to_issue_string())
            .collect()
    }

    /// Validate that two DataFrames can be joined on specified columns
    pub fn validate_join_compatibility(
        &mut self,
        left: &DataFrame,
        right: &DataFrame,
        join_cols: &[&str],
    ) -> EtlResult<()> {
        let left_shape = DataFrameShape::from_df(left);
        let right_shape = DataFrameShape::from_df(right);

        for col_name in join_cols {
            let left_dtype = left_shape.get_dtype(col_name).ok_or_else(|| {
                EtlError::MissingColumn(format!(
                    "Left DataFrame missing join column '{}'. Available: {:?}",
                    col_name, left_shape.column_names
                ))
            })?;

            let right_dtype = right_shape.get_dtype(col_name).ok_or_else(|| {
                EtlError::MissingColumn(format!(
                    "Right DataFrame missing join column '{}'. Available: {:?}",
                    col_name, right_shape.column_names
                ))
            })?;

            if left_dtype != right_dtype {
                let event = ValidationEvent::error(
                    "join_compatibility",
                    format!(
                        "Join column '{}' type mismatch: left={:?}, right={:?}",
                        col_name, left_dtype, right_dtype
                    ),
                );
                self.record_event(event);

                return Err(EtlError::Config(format!(
                    "Join column '{}' type mismatch: left={:?}, right={:?}",
                    col_name, left_dtype, right_dtype
                )));
            }

            debug!(
                 column = %col_name,
                 dtype = ?left_dtype,
                 "Join column types match"
            );
        }

        self.record_event(
            ValidationEvent::ok("join_compatibility").with_details(
                ValidationDetails::new()
                    .with_columns(join_cols.iter().map(|s| s.to_string()).collect()),
            ),
        );

        debug!(
             left_shape = %left_shape,
             right_shape = %right_shape,
             join_cols = ?join_cols,
             "Join compatibility validated"
        );

        Ok(())
    }

    /// Validate output DataFrame against expectations
    pub fn validate_output(&mut self, output_df: &DataFrame) -> Vec<ValidationResult> {
        let output_shape = DataFrameShape::from_df(output_df);
        let mut results = Vec::new();

        // Check column preservation
        if !self.input_shape.columns_match(&output_shape) {
            let missing: Vec<_> = self
                .input_shape
                .column_names
                .iter()
                .filter(|c| !output_shape.column_names.contains(c))
                .cloned()
                .collect();
            let extra: Vec<_> = output_shape
                .column_names
                .iter()
                .filter(|c| !self.input_shape.column_names.contains(c))
                .cloned()
                .collect();

            if !missing.is_empty() || !extra.is_empty() {
                let msg = format!(
                    "Column mismatch. Missing: {:?}, Extra: {:?}",
                    missing, extra
                );
                results.push(ValidationResult::Error(msg.clone()));
                self.record_event(ValidationEvent::error("column_preservation", msg));
            }

            // Check for dtype changes
            // ... to avoid mutating while reading...
            // 1. Create a temporary buffer to hold the events
            let mut events_to_record = Vec::new();

            // 2. READ PHASE: Iterate immutably
            for (i, col_name) in self.input_shape.column_names.iter().enumerate() {
                if let Some(output_dtype) = output_shape.get_dtype(col_name) {
                    let input_dtype = &self.input_shape.column_dtypes[i];

                    if input_dtype != output_dtype {
                        let msg = format!(
                            "Column '{}' dtype changed: {:?} -> {:?}",
                            col_name, input_dtype, output_dtype
                        );

                        // Push to local results (assuming 'results' is a local Vec, not on self)
                        results.push(ValidationResult::Warning(msg.clone()));

                        // STAGE the event locally instead of calling self.record_event() immediately
                        events_to_record.push(ValidationEvent::warning("dtype_change", msg));
                    }
                }
            }

            // 3. WRITE PHASE: Apply the changes
            // The immutable borrow of 'self' inside the loop has explicitly ended here.
            // Now we are free to borrow 'self' mutably.
            for event in events_to_record {
                self.record_event(event);
            }
        }

        // Log summary
        debug!(
             input_shape = %self.input_shape,
             output_shape = %output_shape,
             validation_issues = results.len(),
             "Output validation complete"
        );

        for result in &results {
            result.log(&self.policy_name);
        }

        if results.is_empty() {
            self.record_event(
                ValidationEvent::ok("output_validation").with_details(
                    ValidationDetails::new()
                        .with_input_rows(self.input_shape.rows)
                        .with_output_rows(output_shape.rows)
                        .with_time_unit(self.time_unit),
                ),
            );
            results.push(ValidationResult::Ok);
        }

        results
    }

    /// Create a validation summary for tracing
    pub fn summary(&self, output_df: &DataFrame) -> ValidationSummary {
        let output_shape = DataFrameShape::from_df(output_df);
        ValidationSummary {
            policy_name: self.policy_name.clone(),
            input_rows: self.input_shape.rows,
            output_rows: output_shape.rows,
            input_cols: self.input_shape.cols,
            output_cols: output_shape.cols,
            time_unit: self.time_unit,
            expected_rows: None,
            issues: self.issue_strings(),
        }
    }
}

/// Summary for structured logging
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationSummary {
    pub policy_name: String,
    pub input_rows: usize,
    pub output_rows: usize,
    pub input_cols: usize,
    pub output_cols: usize,
    #[serde(skip, default = "default_time_unit")]
    pub time_unit: PolarsTimeUnit,
    pub expected_rows: Option<usize>,
    /// Issues encountered during validation
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub issues: Vec<String>,
}

impl ValidationSummary {
    /// Get the time unit as a string
    pub fn time_unit_str(&self) -> String {
        format!("{:?}", self.time_unit)
    }

    /// Check if there were any issues
    pub fn has_issues(&self) -> bool {
        !self.issues.is_empty()
    }
}

impl Default for ValidationSummary {
    fn default() -> Self {
        Self {
            policy_name: String::new(),
            input_rows: 0,
            output_rows: 0,
            input_cols: 0,
            output_cols: 0,
            time_unit: PolarsTimeUnit::Milliseconds,
            expected_rows: None,
            issues: Vec::new(),
        }
    }
}

fn default_time_unit() -> PolarsTimeUnit {
    PolarsTimeUnit::Milliseconds
}

impl std::fmt::Display for ValidationSummary {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{}: {} rows -> {} rows ({} cols), time_unit={:?}",
            self.policy_name, self.input_rows, self.output_rows, self.output_cols, self.time_unit
        )?;
        if let Some(expected) = self.expected_rows {
            write!(f, ", expected={}", expected)?;
        }
        if !self.issues.is_empty() {
            write!(f, ", issues={}", self.issues.len())?;
        }
        Ok(())
    }
}

// =============================================================================
// Utility Functions
// =============================================================================

/// Extract time bounds from a DataFrame column with validation
pub fn extract_time_bounds_validated(
    df: &DataFrame,
    time_col: &str,
    time_unit: PolarsTimeUnit,
) -> EtlResult<(i64, i64)> {
    let shape = DataFrameShape::from_df(df);
    let actual_unit = shape.assert_datetime_column(time_col)?;

    if actual_unit != time_unit {
        return Err(EtlError::Config(format!(
            "Time column '{}' unit mismatch: expected {:?}, got {:?}",
            time_col, time_unit, actual_unit
        )));
    }

    let bounds = df
        .clone()
        .lazy()
        .select([
            col(time_col).dt().timestamp(time_unit).min().alias("min_t"),
            col(time_col).dt().timestamp(time_unit).max().alias("max_t"),
        ])
        .collect()?;

    let min_time = bounds
        .column("min_t")?
        .i64()?
        .get(0)
        .ok_or_else(|| EtlError::SignalPolicy("No valid timestamps for min".into()))?;

    let max_time = bounds
        .column("max_t")?
        .i64()?
        .get(0)
        .ok_or_else(|| EtlError::SignalPolicy("No valid timestamps for max".into()))?;

    debug!(
         min_time = min_time,
         max_time = max_time,
         span = max_time - min_time,
         time_unit = ?time_unit,
         "Extracted time bounds"
    );

    Ok((min_time, max_time))
}

/// Convert a collection of ValidationResults to issue strings
pub fn results_to_issues(results: &[ValidationResult]) -> Vec<String> {
    results.iter().filter_map(|r| r.to_issue_string()).collect()
}

// =============================================================================
// Tests
// =============================================================================

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

    #[test]
    fn test_dataframe_shape() {
        let df = df! {
             "a" => [1, 2, 3],
             "b" => ["x", "y", "z"]
        }
        .unwrap();

        let shape = DataFrameShape::from_df(&df);
        assert_eq!(shape.rows, 3);
        assert_eq!(shape.cols, 2);
        assert_eq!(shape.column_names, vec!["a", "b"]);
    }

    #[test]
    fn test_policy_expectation() {
        let exp = PolicyExpectation::new("test")
            .with_time_span(100_000)
            .with_partition_count(2);

        assert_eq!(exp.input_time_span, 100_000);
        assert_eq!(exp.partition_count, 2);
    }

    #[test]
    fn test_validation_result_to_issue_string() {
        assert!(ValidationResult::Ok.to_issue_string().is_none());

        let warning = ValidationResult::Warning("test warning".into());
        assert_eq!(
            warning.to_issue_string(),
            Some("[WARN] test warning".into())
        );

        let error = ValidationResult::Error("test error".into());
        assert_eq!(error.to_issue_string(), Some("[ERROR] test error".into()));
    }

    #[test]
    fn test_validation_event() {
        let event = ValidationEvent::warning("test_context", "something happened").with_details(
            ValidationDetails::new()
                .with_input_rows(100)
                .with_output_rows(50),
        );

        assert_eq!(
            event.to_issue_string(),
            Some("test_context: [WARN] something happened".into())
        );
        assert_eq!(event.details.as_ref().unwrap().input_rows, Some(100));
    }

    #[test]
    fn test_assert_datetime_column() {
        let df = df! {
             "time" => [1i64, 2, 3]
        }
        .unwrap()
        .lazy()
        .with_column(col("time").cast(DataType::Datetime(PolarsTimeUnit::Milliseconds, None)))
        .collect()
        .unwrap();

        let shape = DataFrameShape::from_df(&df);
        let tu = shape.assert_datetime_column("time").unwrap();
        assert_eq!(tu, PolarsTimeUnit::Milliseconds);
    }

    #[test]
    fn test_assert_datetime_column_wrong_type() {
        let df = df! {
             "time" => [1i64, 2, 3]
        }
        .unwrap();

        let shape = DataFrameShape::from_df(&df);
        let result = shape.assert_datetime_column("time");
        assert!(result.is_err());
    }

    #[test]
    fn test_validation_summary_display() {
        let summary = ValidationSummary {
            policy_name: "instant".into(),
            input_rows: 100,
            output_rows: 50,
            input_cols: 5,
            output_cols: 5,
            time_unit: PolarsTimeUnit::Milliseconds,
            expected_rows: Some(50),
            issues: vec!["[WARN] test issue".into()],
        };

        let display = format!("{}", summary);
        assert!(display.contains("instant"));
        assert!(display.contains("100 rows -> 50 rows"));
        assert!(display.contains("issues=1"));
    }

    #[test]
    fn test_results_to_issues() {
        let results = vec![
            ValidationResult::Ok,
            ValidationResult::Warning("warn 1".into()),
            ValidationResult::Ok,
            ValidationResult::Error("error 1".into()),
        ];

        let issues = results_to_issues(&results);
        assert_eq!(issues.len(), 2);
        assert!(issues[0].contains("WARN"));
        assert!(issues[1].contains("ERROR"));
    }
}