aprender-verify-ml 0.30.0

Synthetic Data Factory for Domain-Specific Code Intelligence
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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Data pipeline for storing verified test cases
//!
//! This module handles the storage and retrieval of verified
//! (source, target, correctness) tuples in Parquet format.
//!
//! # Features
//!
//! - Large-scale parallel generation with progress tracking
//! - Automatic Parquet sharding for large datasets
//! - Support for all sampling strategies

#[cfg(feature = "parquet")]
pub mod parquet;

pub mod corpus;
pub mod pipeline;

pub use corpus::{CorpusFormat, CorpusManager, CorpusMetadata, TrainingCorpus};
pub use pipeline::{DataPipeline, PipelineConfig, PipelineStats, PipelineStrategy};

use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::generator::GeneratedCode;
use crate::mutator::MutationOperator;
use crate::oracle::VerificationResult;
use crate::Language;

/// Verified transpilation tuple for ML training
///
/// Represents a successful transpilation with both source and target code.
/// Used for LLM fine-tuning with entrenar.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifiedTuple {
    /// Source language
    pub source_language: Language,
    /// Target language
    pub target_language: Language,
    /// Original source code
    pub source_code: String,
    /// Transpiled target code
    pub target_code: String,
    /// Whether the transpilation was verified correct (I/O equivalent)
    pub is_correct: bool,
    /// Execution time in milliseconds
    pub execution_time_ms: u64,
}

impl VerifiedTuple {
    /// Create from a test case (only if transpilation succeeded)
    #[must_use]
    pub fn from_test_case(test_case: &TestCase) -> Option<Self> {
        let target_code = test_case.target_code.as_ref()?;
        Some(Self {
            source_language: test_case.source_language,
            target_language: test_case.target_language,
            source_code: test_case.source_code.clone(),
            target_code: target_code.clone(),
            is_correct: matches!(test_case.result, TestResult::Pass),
            execution_time_ms: 0, // Not tracked in TestCase
        })
    }
}

/// Test case with full metadata
///
/// From spec Section 8.1: Generated test case schema.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestCase {
    /// Unique identifier
    pub id: Uuid,

    /// Source language
    pub source_language: Language,

    /// Source code
    pub source_code: String,

    /// Target language
    pub target_language: Language,

    /// Transpiled code (if successful)
    pub target_code: Option<String>,

    /// Verification result
    pub result: TestResult,

    /// Features for ML
    pub features: CodeFeatures,

    /// Generation metadata
    pub metadata: GenerationMetadata,
}

/// Test result enum
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TestResult {
    /// I/O equivalent
    Pass,
    /// Transpilation failed
    TranspileError(String),
    /// Output mismatch
    OutputMismatch {
        /// Expected output
        expected: String,
        /// Actual output
        actual: String,
    },
    /// Timeout
    Timeout {
        /// Timeout limit in milliseconds
        limit_ms: u64,
    },
    /// Runtime error
    RuntimeError {
        /// Phase where error occurred
        phase: String,
        /// Error message
        error: String,
    },
}

/// Features extracted from source code for ML
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CodeFeatures {
    /// AST depth
    pub ast_depth: u32,
    /// Number of operators
    pub num_operators: u32,
    /// Number of control flow statements
    pub num_control_flow: u32,
    /// Cyclomatic complexity
    pub cyclomatic_complexity: f32,
    /// Number of type coercions
    pub num_type_coercions: u32,
    /// Uses edge values (0, -1, MAX_INT, etc.)
    pub uses_edge_values: bool,
}

/// Metadata about how the test case was generated
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GenerationMetadata {
    /// Generation strategy used
    pub strategy: String,
    /// Mutation operators applied
    pub mutation_operators: Vec<String>,
    /// Timestamp
    pub timestamp: String,
    /// Transpiler version
    pub transpiler_version: String,
}

impl TestCase {
    /// Create a new test case from generation and verification results
    #[must_use]
    pub fn new(
        generated: &GeneratedCode,
        verification: &VerificationResult,
        transpiler_version: &str,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            source_language: generated.language,
            source_code: generated.code.clone(),
            target_language: verification.target_language,
            target_code: Some(verification.target_code.clone()),
            result: TestResult::from_verification(verification),
            features: CodeFeatures {
                ast_depth: generated.ast_depth as u32,
                ..Default::default()
            },
            metadata: GenerationMetadata {
                strategy: "unknown".to_string(),
                mutation_operators: vec![],
                timestamp: chrono_lite_timestamp(),
                transpiler_version: transpiler_version.to_string(),
            },
        }
    }
}

impl TestResult {
    /// Convert from verification result
    fn from_verification(verification: &VerificationResult) -> Self {
        match &verification.verdict {
            crate::oracle::Verdict::Pass => Self::Pass,
            crate::oracle::Verdict::OutputMismatch { expected, actual } => Self::OutputMismatch {
                expected: expected.clone(),
                actual: actual.clone(),
            },
            crate::oracle::Verdict::Timeout { limit_ms, .. } => Self::Timeout {
                limit_ms: *limit_ms,
            },
            crate::oracle::Verdict::RuntimeError { phase, error } => Self::RuntimeError {
                phase: phase.to_string(),
                error: error.clone(),
            },
        }
    }
}

/// Simple timestamp without chrono dependency
fn chrono_lite_timestamp() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    format!("{}", duration.as_secs())
}

/// Builder for test cases with mutations
#[derive(Debug, Default)]
pub struct TestCaseBuilder {
    source_code: Option<String>,
    source_language: Option<Language>,
    mutation_operators: Vec<MutationOperator>,
    strategy: Option<String>,
}

impl TestCaseBuilder {
    /// Create a new builder
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the source code
    #[must_use]
    pub fn source_code(mut self, code: impl Into<String>) -> Self {
        self.source_code = Some(code.into());
        self
    }

    /// Set the source language
    #[must_use]
    pub fn source_language(mut self, language: Language) -> Self {
        self.source_language = Some(language);
        self
    }

    /// Add a mutation operator
    #[must_use]
    pub fn mutation_operator(mut self, operator: MutationOperator) -> Self {
        self.mutation_operators.push(operator);
        self
    }

    /// Set the generation strategy
    #[must_use]
    pub fn strategy(mut self, strategy: impl Into<String>) -> Self {
        self.strategy = Some(strategy.into());
        self
    }
}

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

    #[test]
    fn test_test_result_pass() {
        let result = TestResult::Pass;
        assert_eq!(result, TestResult::Pass);
    }

    #[test]
    fn test_test_result_transpile_error() {
        let result = TestResult::TranspileError("syntax error".to_string());
        assert!(matches!(result, TestResult::TranspileError(_)));
    }

    #[test]
    fn test_test_result_output_mismatch() {
        let result = TestResult::OutputMismatch {
            expected: "hello".to_string(),
            actual: "world".to_string(),
        };
        assert!(matches!(result, TestResult::OutputMismatch { .. }));
    }

    #[test]
    fn test_test_result_timeout() {
        let result = TestResult::Timeout { limit_ms: 5000 };
        if let TestResult::Timeout { limit_ms } = result {
            assert_eq!(limit_ms, 5000);
        } else {
            panic!("Expected Timeout");
        }
    }

    #[test]
    fn test_test_result_runtime_error() {
        let result = TestResult::RuntimeError {
            phase: "source".to_string(),
            error: "division by zero".to_string(),
        };
        assert!(matches!(result, TestResult::RuntimeError { .. }));
    }

    #[test]
    fn test_code_features_default() {
        let features = CodeFeatures::default();
        assert_eq!(features.ast_depth, 0);
        assert_eq!(features.num_operators, 0);
        assert_eq!(features.num_control_flow, 0);
        assert!((features.cyclomatic_complexity - 0.0).abs() < f32::EPSILON);
        assert_eq!(features.num_type_coercions, 0);
        assert!(!features.uses_edge_values);
    }

    #[test]
    fn test_code_features_custom() {
        let features = CodeFeatures {
            ast_depth: 5,
            num_operators: 10,
            num_control_flow: 3,
            cyclomatic_complexity: 4.5,
            num_type_coercions: 2,
            uses_edge_values: true,
        };
        assert_eq!(features.ast_depth, 5);
        assert!(features.uses_edge_values);
    }

    #[test]
    fn test_test_case_builder() {
        let builder = TestCaseBuilder::new()
            .source_code("x = 1")
            .source_language(Language::Python)
            .mutation_operator(MutationOperator::Aor)
            .strategy("exhaustive");

        assert_eq!(builder.source_code, Some("x = 1".to_string()));
        assert_eq!(builder.source_language, Some(Language::Python));
        assert_eq!(builder.mutation_operators.len(), 1);
        assert_eq!(builder.strategy, Some("exhaustive".to_string()));
    }

    #[test]
    fn test_test_case_builder_multiple_operators() {
        let builder = TestCaseBuilder::new()
            .mutation_operator(MutationOperator::Aor)
            .mutation_operator(MutationOperator::Ror)
            .mutation_operator(MutationOperator::Lor);

        assert_eq!(builder.mutation_operators.len(), 3);
    }

    #[test]
    fn test_chrono_lite_timestamp() {
        let ts = chrono_lite_timestamp();
        // Should be a numeric string
        assert!(!ts.is_empty());
        assert!(ts.parse::<u64>().is_ok());
    }

    #[test]
    fn test_generation_metadata_debug() {
        let metadata = GenerationMetadata {
            strategy: "exhaustive".to_string(),
            mutation_operators: vec!["AOR".to_string()],
            timestamp: "123456".to_string(),
            transpiler_version: "0.1.0".to_string(),
        };
        let debug = format!("{:?}", metadata);
        assert!(debug.contains("exhaustive"));
    }

    #[test]
    fn test_test_result_from_verdict_pass() {
        let verification = crate::oracle::VerificationResult {
            source_code: "print(1)".to_string(),
            source_language: Language::Python,
            target_code: "fn main() {}".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::Pass,
            source_result: None,
            target_result: None,
        };
        let result = TestResult::from_verification(&verification);
        assert_eq!(result, TestResult::Pass);
    }

    #[test]
    fn test_test_result_from_verdict_mismatch() {
        use crate::oracle::Phase;
        let verification = crate::oracle::VerificationResult {
            source_code: "print(1)".to_string(),
            source_language: Language::Python,
            target_code: "fn main() {}".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::OutputMismatch {
                expected: "1".to_string(),
                actual: "2".to_string(),
            },
            source_result: None,
            target_result: None,
        };
        let result = TestResult::from_verification(&verification);
        assert!(matches!(result, TestResult::OutputMismatch { .. }));
    }

    #[test]
    fn test_test_result_from_verdict_timeout() {
        use crate::oracle::Phase;
        let verification = crate::oracle::VerificationResult {
            source_code: "while True: pass".to_string(),
            source_language: Language::Python,
            target_code: "loop {}".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::Timeout {
                phase: Phase::Source,
                limit_ms: 5000,
            },
            source_result: None,
            target_result: None,
        };
        let result = TestResult::from_verification(&verification);
        assert!(matches!(result, TestResult::Timeout { .. }));
    }

    #[test]
    fn test_test_result_from_verdict_runtime_error() {
        use crate::oracle::Phase;
        let verification = crate::oracle::VerificationResult {
            source_code: "1/0".to_string(),
            source_language: Language::Python,
            target_code: "panic!()".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::RuntimeError {
                phase: Phase::Source,
                error: "division by zero".to_string(),
            },
            source_result: None,
            target_result: None,
        };
        let result = TestResult::from_verification(&verification);
        assert!(matches!(result, TestResult::RuntimeError { .. }));
    }

    #[test]
    fn test_test_case_new() {
        let generated = crate::generator::GeneratedCode {
            code: "print(1)".to_string(),
            language: Language::Python,
            ast_depth: 1,
            features: vec!["print".to_string()],
        };

        let verification = crate::oracle::VerificationResult {
            source_code: "print(1)".to_string(),
            source_language: Language::Python,
            target_code: "fn main() { println!(\"1\"); }".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::Pass,
            source_result: None,
            target_result: None,
        };

        let test_case = TestCase::new(&generated, &verification, "0.1.0");

        assert_eq!(test_case.source_language, Language::Python);
        assert_eq!(test_case.target_language, Language::Rust);
        assert!(test_case.target_code.is_some());
        assert_eq!(test_case.result, TestResult::Pass);
        assert_eq!(test_case.metadata.transpiler_version, "0.1.0");
    }

    #[test]
    fn test_test_case_debug() {
        let generated = crate::generator::GeneratedCode {
            code: "x = 1".to_string(),
            language: Language::Python,
            ast_depth: 1,
            features: vec![],
        };

        let verification = crate::oracle::VerificationResult {
            source_code: "x = 1".to_string(),
            source_language: Language::Python,
            target_code: "let x = 1;".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::Pass,
            source_result: None,
            target_result: None,
        };

        let test_case = TestCase::new(&generated, &verification, "0.1.0");
        let debug = format!("{:?}", test_case);
        assert!(debug.contains("TestCase"));
    }

    #[test]
    fn test_test_case_clone() {
        let generated = crate::generator::GeneratedCode {
            code: "x = 1".to_string(),
            language: Language::Python,
            ast_depth: 1,
            features: vec![],
        };

        let verification = crate::oracle::VerificationResult {
            source_code: "x = 1".to_string(),
            source_language: Language::Python,
            target_code: "let x = 1;".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::Pass,
            source_result: None,
            target_result: None,
        };

        let test_case = TestCase::new(&generated, &verification, "0.1.0");
        let cloned = test_case.clone();
        assert_eq!(cloned.source_code, test_case.source_code);
    }
}