aprender-profile 0.30.0

Pure Rust system call tracer with source-aware correlation for Rust binaries
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
//! Output formatters for validation results
//!
//! Per specification Section 3.3: Output Formats

use super::comparison::{ComparisonResult, MismatchType};
use super::config::ValidationOutputFormat;
use serde::Serialize;

/// Format validation result according to specified format
pub fn format_result(result: &ComparisonResult, format: ValidationOutputFormat) -> String {
    match format {
        ValidationOutputFormat::Text => format_text_report(result),
        ValidationOutputFormat::Json => format_json_report(result),
        ValidationOutputFormat::JUnit => format_junit_report(result),
    }
}

/// JSON output structure per specification Section 3.3
#[derive(Debug, Serialize)]
pub struct JsonValidationResult {
    /// Overall validation status
    pub status: String,
    /// Total syscalls compared
    pub total_compared: usize,
    /// Number of matches
    pub matches: usize,
    /// Number of mismatches
    pub mismatches: usize,
    /// Number of timing regressions
    pub timing_regressions: usize,
    /// Detailed syscall mismatches
    pub syscall_details: Vec<JsonSyscallMismatch>,
    /// Detailed timing regressions
    pub timing_details: Vec<JsonTimingRegression>,
}

#[derive(Debug, Serialize)]
pub struct JsonSyscallMismatch {
    pub index: usize,
    pub expected: String,
    pub found: String,
    pub mismatch_type: String,
}

#[derive(Debug, Serialize)]
pub struct JsonTimingRegression {
    pub syscall: String,
    pub baseline_ms: f64,
    pub actual_ms: f64,
    pub delta_percent: f64,
}

/// Format as human-readable text
pub fn format_text_report(result: &ComparisonResult) -> String {
    let mut output = String::new();

    // Header
    output.push_str("=== Validation Report ===\n\n");

    // Status
    let status = if result.passed { "PASSED" } else { "FAILED" };
    output.push_str(&format!("Status: {status}\n\n"));

    // Summary
    output.push_str("Summary:\n");
    output.push_str(&format!("  Total syscalls compared: {}\n", result.summary.total_compared));
    output.push_str(&format!("  Matches: {}\n", result.summary.matches));
    output.push_str(&format!("  Mismatches: {}\n", result.summary.mismatches));
    output.push_str(&format!("  Timing regressions: {}\n", result.summary.timing_regressions));
    output.push('\n');

    // Syscall mismatches
    if !result.syscall_mismatches.is_empty() {
        output.push_str("Syscall Mismatches:\n");
        for mismatch in &result.syscall_mismatches {
            let mismatch_type = match mismatch.mismatch_type {
                MismatchType::Different => "DIFFERENT",
                MismatchType::Extra => "EXTRA",
                MismatchType::Missing => "MISSING",
            };
            output.push_str(&format!(
                "  [{}] Index {}: expected '{}', found '{}'\n",
                mismatch_type, mismatch.index, mismatch.expected, mismatch.found
            ));
        }
        output.push('\n');
    }

    // Timing regressions
    if !result.timing_regressions.is_empty() {
        output.push_str("Timing Regressions:\n");
        for regression in &result.timing_regressions {
            output.push_str(&format!(
                "  {}: {:.2}ms -> {:.2}ms ({:+.1}%)\n",
                regression.syscall,
                regression.baseline_ms,
                regression.actual_ms,
                regression.delta_percent
            ));
        }
        output.push('\n');
    }

    output
}

/// Format as JSON
pub fn format_json_report(result: &ComparisonResult) -> String {
    let json_result = JsonValidationResult {
        status: if result.passed { "passed".to_string() } else { "failed".to_string() },
        total_compared: result.summary.total_compared,
        matches: result.summary.matches,
        mismatches: result.summary.mismatches,
        timing_regressions: result.summary.timing_regressions,
        syscall_details: result
            .syscall_mismatches
            .iter()
            .map(|m| JsonSyscallMismatch {
                index: m.index,
                expected: m.expected.clone(),
                found: m.found.clone(),
                mismatch_type: match m.mismatch_type {
                    MismatchType::Different => "different".to_string(),
                    MismatchType::Extra => "extra".to_string(),
                    MismatchType::Missing => "missing".to_string(),
                },
            })
            .collect(),
        timing_details: result
            .timing_regressions
            .iter()
            .map(|t| JsonTimingRegression {
                syscall: t.syscall.clone(),
                baseline_ms: t.baseline_ms,
                actual_ms: t.actual_ms,
                delta_percent: t.delta_percent,
            })
            .collect(),
    };

    serde_json::to_string_pretty(&json_result).unwrap_or_else(|_| "{}".to_string())
}

/// Format as `JUnit` XML for CI systems
pub fn format_junit_report(result: &ComparisonResult) -> String {
    let mut output = String::new();

    output.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

    let test_count = 1 + result.syscall_mismatches.len() + result.timing_regressions.len();
    let failure_count = result.syscall_mismatches.len() + result.timing_regressions.len();

    output.push_str(&format!(
        "<testsuite name=\"renacer-validate\" tests=\"{test_count}\" failures=\"{failure_count}\" errors=\"0\">\n"
    ));

    // Overall test case
    output.push_str("  <testcase name=\"validation-overall\" classname=\"renacer.validate\"");
    if result.passed {
        output.push_str("/>\n");
    } else {
        output.push_str(">\n");
        output.push_str(&format!(
            "    <failure message=\"Validation failed: {} mismatches, {} timing regressions\"/>\n",
            result.syscall_mismatches.len(),
            result.timing_regressions.len()
        ));
        output.push_str("  </testcase>\n");
    }

    // Individual syscall mismatch test cases
    for mismatch in &result.syscall_mismatches {
        output.push_str(&format!(
            "  <testcase name=\"syscall-{index}\" classname=\"renacer.validate.syscalls\">\n",
            index = mismatch.index
        ));
        output.push_str(&format!(
            "    <failure message=\"Expected '{}', found '{}' ({})\"/>\n",
            xml_escape(&mismatch.expected),
            xml_escape(&mismatch.found),
            match mismatch.mismatch_type {
                MismatchType::Different => "different",
                MismatchType::Extra => "extra",
                MismatchType::Missing => "missing",
            }
        ));
        output.push_str("  </testcase>\n");
    }

    // Individual timing regression test cases
    for regression in &result.timing_regressions {
        output.push_str(&format!(
            "  <testcase name=\"timing-{}\" classname=\"renacer.validate.timing\">\n",
            xml_escape(&regression.syscall)
        ));
        output.push_str(&format!(
            "    <failure message=\"Timing regression: {:.2}ms -> {:.2}ms ({:+.1}%)\"/>\n",
            regression.baseline_ms, regression.actual_ms, regression.delta_percent
        ));
        output.push_str("  </testcase>\n");
    }

    output.push_str("</testsuite>\n");

    output
}

/// Escape XML special characters
fn xml_escape(s: &str) -> String {
    s.replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&apos;")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::validate::comparison::{ComparisonSummary, SyscallMismatch, TimingRegression};

    #[test]
    fn test_text_format_passed() {
        let result = ComparisonResult::passed();
        let text = format_text_report(&result);
        assert!(text.contains("Status: PASSED"));
    }

    #[test]
    fn test_text_format_failed_with_mismatches() {
        let result = ComparisonResult {
            passed: false,
            syscall_mismatches: vec![
                SyscallMismatch {
                    index: 0,
                    expected: "read".to_string(),
                    found: "write".to_string(),
                    mismatch_type: MismatchType::Different,
                },
                SyscallMismatch {
                    index: 1,
                    expected: "(none)".to_string(),
                    found: "close".to_string(),
                    mismatch_type: MismatchType::Extra,
                },
                SyscallMismatch {
                    index: 2,
                    expected: "open".to_string(),
                    found: "(none)".to_string(),
                    mismatch_type: MismatchType::Missing,
                },
            ],
            timing_regressions: vec![TimingRegression {
                syscall: "read".to_string(),
                baseline_ms: 0.1,
                actual_ms: 0.15,
                delta_percent: 50.0,
            }],
            summary: ComparisonSummary {
                total_compared: 3,
                matches: 0,
                mismatches: 3,
                timing_regressions: 1,
            },
        };
        let text = format_text_report(&result);
        assert!(text.contains("Status: FAILED"));
        assert!(text.contains("[DIFFERENT]"));
        assert!(text.contains("[EXTRA]"));
        assert!(text.contains("[MISSING]"));
        assert!(text.contains("Timing Regressions:"));
        assert!(text.contains("read: 0.10ms -> 0.15ms (+50.0%)"));
    }

    #[test]
    fn test_json_format_structure() {
        let result = ComparisonResult::passed();
        let json = format_json_report(&result);
        assert!(json.contains("\"status\": \"passed\""));
    }

    #[test]
    fn test_json_format_with_details() {
        let result = ComparisonResult {
            passed: false,
            syscall_mismatches: vec![SyscallMismatch {
                index: 5,
                expected: "openat".to_string(),
                found: "close".to_string(),
                mismatch_type: MismatchType::Different,
            }],
            timing_regressions: vec![TimingRegression {
                syscall: "write".to_string(),
                baseline_ms: 0.5,
                actual_ms: 1.0,
                delta_percent: 100.0,
            }],
            summary: ComparisonSummary {
                total_compared: 10,
                matches: 9,
                mismatches: 1,
                timing_regressions: 1,
            },
        };
        let json = format_json_report(&result);
        assert!(json.contains("\"status\": \"failed\""));
        assert!(json.contains("\"mismatch_type\": \"different\""));
        assert!(json.contains("\"syscall\": \"write\""));
        assert!(json.contains("\"delta_percent\": 100.0"));
    }

    #[test]
    fn test_json_format_extra_and_missing_types() {
        let result = ComparisonResult {
            passed: false,
            syscall_mismatches: vec![
                SyscallMismatch {
                    index: 0,
                    expected: "(none)".to_string(),
                    found: "mmap".to_string(),
                    mismatch_type: MismatchType::Extra,
                },
                SyscallMismatch {
                    index: 1,
                    expected: "munmap".to_string(),
                    found: "(none)".to_string(),
                    mismatch_type: MismatchType::Missing,
                },
            ],
            timing_regressions: vec![],
            summary: ComparisonSummary::default(),
        };
        let json = format_json_report(&result);
        assert!(json.contains("\"mismatch_type\": \"extra\""));
        assert!(json.contains("\"mismatch_type\": \"missing\""));
    }

    #[test]
    fn test_junit_format_valid_xml() {
        let result = ComparisonResult::passed();
        let xml = format_junit_report(&result);
        assert!(xml.starts_with("<?xml version=\"1.0\""));
        assert!(xml.contains("<testsuite"));
        assert!(xml.contains("</testsuite>"));
    }

    #[test]
    fn test_junit_format_with_failures() {
        let result = ComparisonResult {
            passed: false,
            syscall_mismatches: vec![
                SyscallMismatch {
                    index: 0,
                    expected: "read".to_string(),
                    found: "write".to_string(),
                    mismatch_type: MismatchType::Different,
                },
                SyscallMismatch {
                    index: 1,
                    expected: "(none)".to_string(),
                    found: "close".to_string(),
                    mismatch_type: MismatchType::Extra,
                },
                SyscallMismatch {
                    index: 2,
                    expected: "open".to_string(),
                    found: "(none)".to_string(),
                    mismatch_type: MismatchType::Missing,
                },
            ],
            timing_regressions: vec![TimingRegression {
                syscall: "read".to_string(),
                baseline_ms: 0.1,
                actual_ms: 0.2,
                delta_percent: 100.0,
            }],
            summary: ComparisonSummary {
                total_compared: 3,
                matches: 0,
                mismatches: 3,
                timing_regressions: 1,
            },
        };
        let xml = format_junit_report(&result);
        assert!(xml.contains("failures=\"4\"")); // 3 syscall + 1 timing
        assert!(xml.contains("<failure message=\"Validation failed"));
        assert!(xml.contains("syscall-0"));
        assert!(xml.contains("timing-read"));
        assert!(xml.contains("(different)"));
        assert!(xml.contains("(extra)"));
        assert!(xml.contains("(missing)"));
    }

    #[test]
    fn test_xml_escape() {
        // Test XML special character escaping
        assert_eq!(xml_escape("a & b"), "a &amp; b");
        assert_eq!(xml_escape("<tag>"), "&lt;tag&gt;");
        assert_eq!(xml_escape("\"quoted\""), "&quot;quoted&quot;");
        assert_eq!(xml_escape("it's"), "it&apos;s");
    }

    #[test]
    fn test_format_result_dispatch() {
        let result = ComparisonResult::passed();

        let text = format_result(&result, ValidationOutputFormat::Text);
        assert!(text.contains("Status: PASSED"));

        let json = format_result(&result, ValidationOutputFormat::Json);
        assert!(json.contains("\"status\": \"passed\""));

        let junit = format_result(&result, ValidationOutputFormat::JUnit);
        assert!(junit.contains("<testsuite"));
    }
}