Skip to main content

dataprof_core/
execution.rs

1/// Reason why profiling was truncated before exhausting the source.
2#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
3pub enum TruncationReason {
4    /// Stopped after processing a maximum number of rows.
5    MaxRows(u64),
6    /// Stopped after consuming a maximum number of bytes.
7    MaxBytes(u64),
8    /// Stopped due to memory pressure.
9    MemoryPressure,
10    /// Stopped due to a user-defined stop condition.
11    StopCondition(String),
12    /// The input stream was closed by the producer.
13    StreamClosed,
14    /// Stopped due to a timeout.
15    Timeout,
16}
17
18/// Metadata about the profiling execution.
19#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
20pub struct ExecutionMetadata {
21    /// Engine or parser that actually produced the report.
22    #[serde(default, skip_serializing_if = "Option::is_none")]
23    pub engine: Option<String>,
24    /// Number of rows actually processed or analyzed.
25    pub rows_processed: usize,
26    /// Number of bytes consumed from the source, if known.
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub bytes_consumed: Option<u64>,
29    /// Number of columns detected in the data.
30    pub columns_detected: usize,
31    /// Total execution time in milliseconds.
32    pub scan_time_ms: u128,
33    /// Throughput in rows per second, auto-calculated when possible.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub throughput_rows_sec: Option<f64>,
36    /// Peak process memory usage (resident set size) in megabytes observed
37    /// during profiling, sampled at chunk/batch boundaries. Absent when the
38    /// platform provided no reading or the input path does not track memory.
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub memory_peak_mb: Option<f64>,
41    /// Number of errors encountered during profiling.
42    pub error_count: usize,
43    /// Number of data rows whose field count differed from the header's.
44    ///
45    /// These rows were recovered — extra trailing fields dropped, missing
46    /// trailing fields padded to null — so profiling continued, but each one
47    /// is a structural violation in the source. A nonzero value means the file
48    /// did not parse cleanly even though a report was produced. Additive field:
49    /// legacy documents without it deserialize as `0`.
50    #[serde(default)]
51    pub ragged_row_count: usize,
52    /// Whether the entire source was consumed.
53    pub source_exhausted: bool,
54    /// If the source was not exhausted, why processing stopped.
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub truncation_reason: Option<TruncationReason>,
57    /// Whether sampling was applied.
58    pub sampling_applied: bool,
59    /// Ratio of rows analyzed to total rows when sampling is meaningful.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub sampling_ratio: Option<f64>,
62}
63
64impl ExecutionMetadata {
65    /// Create new execution metadata with throughput calculated automatically.
66    pub fn new(rows_processed: usize, columns_detected: usize, scan_time_ms: u128) -> Self {
67        let throughput_rows_sec = if scan_time_ms > 0 {
68            Some(rows_processed as f64 / (scan_time_ms as f64 / 1000.0))
69        } else {
70            None
71        };
72
73        Self {
74            engine: None,
75            rows_processed,
76            bytes_consumed: None,
77            columns_detected,
78            scan_time_ms,
79            throughput_rows_sec,
80            memory_peak_mb: None,
81            error_count: 0,
82            ragged_row_count: 0,
83            source_exhausted: true,
84            truncation_reason: None,
85            sampling_applied: false,
86            sampling_ratio: None,
87        }
88    }
89
90    /// Record the engine or parser that actually produced the report.
91    pub fn with_engine(mut self, engine: impl Into<String>) -> Self {
92        self.engine = Some(engine.into());
93        self
94    }
95
96    /// Set sampling information.
97    pub fn with_sampling(mut self, ratio: f64) -> Self {
98        self.sampling_applied = true;
99        self.sampling_ratio = Some(ratio);
100        self
101    }
102
103    /// Explicitly set whether the source was fully consumed.
104    pub fn with_source_exhausted(mut self, exhausted: bool) -> Self {
105        self.source_exhausted = exhausted;
106        self
107    }
108
109    /// Mark the execution as truncated.
110    pub fn with_truncation(mut self, reason: TruncationReason) -> Self {
111        self.source_exhausted = false;
112        self.truncation_reason = Some(reason);
113        self
114    }
115
116    /// Set the number of bytes consumed from the source.
117    pub fn with_bytes_consumed(mut self, bytes: u64) -> Self {
118        self.bytes_consumed = Some(bytes);
119        self
120    }
121
122    /// Set the error count.
123    pub fn with_error_count(mut self, count: usize) -> Self {
124        self.error_count = count;
125        self
126    }
127
128    /// Set the count of ragged rows (field count != header field count).
129    pub fn with_ragged_row_count(mut self, count: usize) -> Self {
130        self.ragged_row_count = count;
131        self
132    }
133
134    /// Set peak memory usage.
135    pub fn with_memory_peak_mb(mut self, mb: f64) -> Self {
136        self.memory_peak_mb = Some(mb);
137        self
138    }
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn test_execution_metadata_throughput_calculation() {
147        let meta = ExecutionMetadata::new(1000, 5, 500);
148        assert!(meta.throughput_rows_sec.is_some());
149        assert!((meta.throughput_rows_sec.unwrap() - 2000.0).abs() < 1.0);
150        assert!(meta.source_exhausted);
151        assert!(!meta.sampling_applied);
152        assert!(meta.sampling_ratio.is_none());
153    }
154
155    #[test]
156    fn test_execution_metadata_zero_time_no_throughput() {
157        let meta = ExecutionMetadata::new(100, 3, 0);
158        assert!(meta.throughput_rows_sec.is_none());
159    }
160
161    #[test]
162    fn test_execution_metadata_with_engine() {
163        let meta = ExecutionMetadata::new(100, 3, 25).with_engine("incremental");
164        assert_eq!(meta.engine.as_deref(), Some("incremental"));
165    }
166
167    #[test]
168    fn test_execution_metadata_with_sampling() {
169        let meta = ExecutionMetadata::new(500, 3, 100).with_sampling(0.5);
170        assert!(meta.sampling_applied);
171        assert_eq!(meta.sampling_ratio, Some(0.5));
172    }
173
174    #[test]
175    fn test_execution_metadata_ragged_row_count() {
176        let meta = ExecutionMetadata::new(100, 3, 25);
177        assert_eq!(meta.ragged_row_count, 0);
178        let meta = meta.with_ragged_row_count(2);
179        assert_eq!(meta.ragged_row_count, 2);
180    }
181
182    #[test]
183    fn test_execution_metadata_ragged_defaults_when_absent() {
184        // A document written before the field existed must deserialize as 0,
185        // not fail or fabricate a value.
186        let json = r#"{
187            "rows_processed": 10,
188            "columns_detected": 2,
189            "scan_time_ms": 5,
190            "error_count": 0,
191            "source_exhausted": true,
192            "sampling_applied": false
193        }"#;
194        let meta: ExecutionMetadata = serde_json::from_str(json).unwrap();
195        assert_eq!(meta.ragged_row_count, 0);
196    }
197
198    #[test]
199    fn test_execution_metadata_with_truncation() {
200        let meta =
201            ExecutionMetadata::new(1000, 5, 200).with_truncation(TruncationReason::MaxRows(1000));
202        assert!(!meta.source_exhausted);
203        assert!(meta.truncation_reason.is_some());
204    }
205
206    #[test]
207    fn test_truncation_reason_serde_roundtrip() {
208        let reasons = vec![
209            TruncationReason::MaxRows(5000),
210            TruncationReason::MaxBytes(1_000_000),
211            TruncationReason::MemoryPressure,
212            TruncationReason::StopCondition("accuracy > 0.95".to_string()),
213            TruncationReason::StreamClosed,
214            TruncationReason::Timeout,
215        ];
216
217        for reason in reasons {
218            let json = serde_json::to_string(&reason).unwrap();
219            let deserialized: TruncationReason = serde_json::from_str(&json).unwrap();
220            let json2 = serde_json::to_string(&deserialized).unwrap();
221            assert_eq!(json, json2);
222        }
223    }
224}