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
//! Corpus runner: transpiles entries and measures quality.
//!
//! Implements the v2 scoring system from the corpus specification:
//! - A. Transpilation Success (30 points)
//! - B. Output Correctness: L1 containment (10) + L2 exact match (8) + L3 behavioral (7)
//! - C. Test Coverage (15 points) -- real LLVM coverage ratio per format (V2-8)
//! - D. Lint Compliance (10 points)
//! - E. Determinism (10 points)
//! - F. Metamorphic Consistency (5 points) -- MR-1 through MR-7
//! - G. Cross-shell agreement (5 points)
//!
//! Gateway logic: if A < 60%, B-G are scored as 0 (Popperian falsification barrier).
//! Secondary gate: if B_L1 < 60%, B_L2 and B_L3 are scored as 0.
//!
//! Split into:
//! - `runner_types.rs`: Data types (CorpusResult, FormatScore, CorpusScore, etc.)
//! - `runner_helpers.rs`: Free functions for coverage detection, error classification
//! - `runner_checks.rs`: Validation methods (MR relations, schema, lint, behavioral)
//! - `runner.rs` (this file): CorpusRunner struct and core run/compute/convergence methods
use crate::corpus::registry::{CorpusEntry, CorpusFormat, CorpusRegistry, Grade};
use crate::models::Config;
use std::collections::HashMap;
// Re-export types so `crate::corpus::runner::TypeName` paths keep working.
pub(crate) use super::runner_helpers::{
check_exact_match, classify_error, detect_coverage_ratio, detect_test_exists,
};
pub use super::runner_types::{
ConvergenceEntry, CorpusResult, CorpusScore, FormatScore, Regression, RegressionReport,
};
/// Corpus runner: loads entries, transpiles, scores, tracks convergence.
pub struct CorpusRunner {
pub(crate) config: Config,
}
impl CorpusRunner {
/// Create a new corpus runner with the given config.
pub fn new(config: Config) -> Self {
Self { config }
}
/// Run the full corpus and return aggregate score.
///
/// KAIZEN-080: Parallelized with std::thread::scope -- each thread processes
/// a chunk of entries independently. CorpusRunner is Send+Sync (Config is scalar,
/// OnceLock caches are thread-safe, run_entry takes &self).
pub fn run(&self, registry: &CorpusRegistry) -> CorpusScore {
let entry_refs: Vec<&CorpusEntry> = registry.entries.iter().collect();
let results = self.run_entries_parallel(&entry_refs);
// KAIZEN-071: pass owned Vec to avoid cloning 17,942 CorpusResult structs
self.compute_score(results, registry)
}
/// Run corpus for a single format.
///
/// KAIZEN-080: Parallelized -- collects format entries then dispatches to thread pool.
pub fn run_format(&self, registry: &CorpusRegistry, format: CorpusFormat) -> CorpusScore {
let entries: Vec<&CorpusEntry> = registry.by_format(format);
let results = self.run_entries_parallel(&entries);
self.compute_score(results, registry)
}
/// Run entries in parallel using std::thread::scope.
///
/// Contract:
/// - Pre: entries is a slice of corpus entry references
/// - Post: returns Vec<CorpusResult> with len == entries.len(), in same order
/// - Invariant: no shared mutable state -- each run_entry call is independent
fn run_entries_parallel(&self, entries: &[&CorpusEntry]) -> Vec<CorpusResult> {
if entries.is_empty() {
return Vec::new();
}
let n_threads = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
// For small entry counts or single-thread systems, skip thread overhead
if entries.len() < n_threads * 2 || n_threads <= 1 {
return entries.iter().map(|e| self.run_entry(e)).collect();
}
let chunk_size = entries.len().div_ceil(n_threads);
let chunks: Vec<&[&CorpusEntry]> = entries.chunks(chunk_size).collect();
std::thread::scope(|s| {
let handles: Vec<_> = chunks
.into_iter()
.map(|chunk| {
s.spawn(move || chunk.iter().map(|e| self.run_entry(e)).collect::<Vec<_>>())
})
.collect();
let mut results = Vec::with_capacity(entries.len());
for handle in handles {
results.extend(handle.join().expect("corpus runner thread panicked"));
}
results
})
}
/// Run a single corpus entry and return its detailed result.
pub fn run_single(&self, entry: &CorpusEntry) -> CorpusResult {
self.run_entry(entry)
}
/// Run a single entry with decision tracing enabled.
/// For Bash entries, uses `transpile_with_trace()` to collect emitter decisions.
/// Makefile/Dockerfile entries fall back to the normal path (no trace).
pub fn run_entry_with_trace(&self, entry: &CorpusEntry) -> CorpusResult {
if entry.format != CorpusFormat::Bash {
return self.run_entry(entry);
}
let transpile_result = crate::transpile_with_trace(&entry.input, &self.config);
match transpile_result {
Ok((output, trace)) => {
let schema_valid = self.check_schema(&output, entry.format);
let output_contains = output.contains(&entry.expected_output);
let output_exact = check_exact_match(&output, &entry.expected_output);
let output_behavioral = self.check_behavioral(&output, entry.format);
let coverage_ratio = detect_coverage_ratio(entry.format, &entry.id);
let has_test = coverage_ratio > 0.0 || detect_test_exists(&entry.id);
let lint_clean = self.check_lint(&output, entry.format);
// KAIZEN-070: reuse output from run_entry_with_trace
let deterministic = self.check_determinism_with_output(entry, &output);
// KAIZEN-072: pass output_contains to MR checks to avoid re-transpiling original
let metamorphic_consistent = deterministic
&& self.check_mr2_stability(entry, output_contains)
&& self.check_mr3_whitespace(entry, output_contains)
&& self.check_mr4_leading_blanks(entry, output_contains)
&& self.check_mr5_subsumption(entry)
&& self.check_mr6_composition(entry)
&& self.check_mr7_negation(entry);
// KAIZEN-073/074: pass output + behavioral result
let cross_shell_agree =
self.check_cross_shell_with_output(entry, &output, output_behavioral);
CorpusResult {
id: entry.id.clone(),
transpiled: true,
output_contains,
output_exact,
output_behavioral,
schema_valid,
has_test,
coverage_ratio,
lint_clean,
deterministic,
metamorphic_consistent,
cross_shell_agree,
expected_output: Some(entry.expected_output.clone()),
actual_output: Some(output),
error: None,
error_category: None,
error_confidence: None,
decision_trace: Some(trace),
}
}
Err(e) => {
let error_msg = format!("{e}");
let (error_category, error_confidence) = classify_error(&error_msg);
let cov = detect_coverage_ratio(entry.format, &entry.id);
CorpusResult {
id: entry.id.clone(),
transpiled: false,
output_contains: false,
output_exact: false,
output_behavioral: false,
schema_valid: false,
has_test: cov > 0.0 || detect_test_exists(&entry.id),
coverage_ratio: cov,
lint_clean: false,
deterministic: false,
metamorphic_consistent: false,
cross_shell_agree: false,
expected_output: Some(entry.expected_output.clone()),
actual_output: None,
error: Some(error_msg),
error_category,
error_confidence,
decision_trace: None,
}
}
}
}
/// Run a single corpus entry with v2 multi-level correctness checking.
fn run_entry(&self, entry: &CorpusEntry) -> CorpusResult {
let transpile_result = match entry.format {
CorpusFormat::Bash => crate::transpile(&entry.input, &self.config),
CorpusFormat::Makefile => crate::transpile_makefile(&entry.input, &self.config),
CorpusFormat::Dockerfile => crate::transpile_dockerfile(&entry.input, &self.config),
};
match transpile_result {
Ok(output) => {
// Schema hard gate: validate output conforms to format grammar
let schema_valid = self.check_schema(&output, entry.format);
// B_L1: Containment check (original metric)
let output_contains = output.contains(&entry.expected_output);
// B_L2: Exact match -- check if expected appears as exact trimmed lines
let output_exact = check_exact_match(&output, &entry.expected_output);
// B_L3: Behavioral equivalence -- execute transpiled shell and verify exit 0
let output_behavioral = self.check_behavioral(&output, entry.format);
// C: Coverage ratio (V2-8) -- real LLVM coverage or test name fallback
let coverage_ratio = detect_coverage_ratio(entry.format, &entry.id);
let has_test = coverage_ratio > 0.0 || detect_test_exists(&entry.id);
// D: Check lint compliance
let lint_clean = self.check_lint(&output, entry.format);
// E: Check determinism (transpile again and compare)
// KAIZEN-070: pass first output to avoid redundant re-transpilation
let deterministic = self.check_determinism_with_output(entry, &output);
// F: Metamorphic consistency -- all MR properties must hold
// MR-1: determinism (already checked as E)
// MR-2: stability under no-op comment addition
// MR-3: trailing whitespace invariance
// MR-4: leading blank line invariance
// MR-5: subsumption (simplification preserves transpilability)
// MR-6: composition (independent stmts transpile separately)
// MR-7: negation (negated condition still transpiles)
// KAIZEN-072: pass output_contains to MR checks to avoid re-transpiling original
let metamorphic_consistent = deterministic
&& self.check_mr2_stability(entry, output_contains)
&& self.check_mr3_whitespace(entry, output_contains)
&& self.check_mr4_leading_blanks(entry, output_contains)
&& self.check_mr5_subsumption(entry)
&& self.check_mr6_composition(entry)
&& self.check_mr7_negation(entry);
// G: Cross-shell agreement -- for bash entries, verify output
// equivalence across Posix and Bash dialect configs
// KAIZEN-073: pass output to avoid re-transpiling with matching dialect
// KAIZEN-074: pass behavioral result to skip redundant sh execution
let cross_shell_agree =
self.check_cross_shell_with_output(entry, &output, output_behavioral);
CorpusResult {
id: entry.id.clone(),
transpiled: true,
output_contains,
output_exact,
output_behavioral,
schema_valid,
has_test,
coverage_ratio,
lint_clean,
deterministic,
metamorphic_consistent,
cross_shell_agree,
expected_output: Some(entry.expected_output.clone()),
actual_output: Some(output),
error: None,
error_category: None,
error_confidence: None,
decision_trace: None,
}
}
Err(e) => {
let error_msg = format!("{e}");
let (error_category, error_confidence) = classify_error(&error_msg);
let cov = detect_coverage_ratio(entry.format, &entry.id);
CorpusResult {
id: entry.id.clone(),
transpiled: false,
output_contains: false,
output_exact: false,
output_behavioral: false,
schema_valid: false,
has_test: cov > 0.0 || detect_test_exists(&entry.id),
coverage_ratio: cov,
lint_clean: false,
deterministic: false,
metamorphic_consistent: false,
cross_shell_agree: false,
expected_output: Some(entry.expected_output.clone()),
actual_output: None,
error: Some(error_msg),
error_category,
error_confidence,
decision_trace: None,
}
}
}
}
fn compute_score(&self, results: Vec<CorpusResult>, registry: &CorpusRegistry) -> CorpusScore {
let total = results.len();
let passed = results.iter().filter(|r| r.transpiled).count();
let failed = total - passed;
let rate = if total > 0 {
passed as f64 / total as f64
} else {
0.0
};
// Gateway check (Popperian falsification barrier, spec SS11.4)
let score = if rate < 0.60 {
// Below gateway: only count transpilation component (A=30 max)
rate * 30.0
} else {
// Above gateway: compute weighted average
if total > 0 {
let total_score: f64 = results.iter().map(|r| r.score()).sum();
total_score / total as f64
} else {
0.0
}
};
let grade = Grade::from_score(score);
// Per-format breakdowns (spec SS11.3)
let format_scores = self.compute_format_scores(&results, registry);
// KAIZEN-071: move owned Vec directly instead of cloning
CorpusScore {
total,
passed,
failed,
rate,
score,
grade,
format_scores,
results,
}
}
}
include!("runner_compute_format_.rs");