alef 0.71.0

Opinionated polyglot binding generator for Rust libraries
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
use super::{PYREFLY_UNAVAILABLE, PythonValidator};
use crate::snippets::session::ValidationSession;
use crate::snippets::types::{Language, Snippet, SnippetMetadata, SnippetStatus, SourceOrigin, ValidationLevel};
use crate::snippets::validators::SnippetValidator;
use std::path::PathBuf;

const TOOLCHAIN_TEST_TIMEOUT_SECS: u64 = 120;

fn python_snippet(code: &str) -> Snippet {
    Snippet {
        id: None,
        path: PathBuf::from("guide.md"),
        language: Language::Python,
        title: None,
        code: code.into(),
        start_line: 1,
        block_index: 0,
        annotation: None,
        metadata: SnippetMetadata::default(),
        source_origin: SourceOrigin {
            path: PathBuf::from("guide.md"),
            line: 1,
            block_index: 0,
        },
    }
}

#[test]
fn batch_declines_run_so_each_snippet_executes_on_its_own() {
    let only = python_snippet("value = 1\n");

    let declined = PythonValidator.validate_batch_in_session(&[&only], ValidationLevel::Run, 10, None);

    assert!(declined.is_none());
}

#[test]
fn batch_returns_one_result_per_snippet_in_input_order() {
    if !PythonValidator.is_available() {
        return;
    }
    let first = python_snippet("first = 1\n");
    let second = python_snippet("second = 2\n");
    let third = python_snippet("third = 3\n");

    let results = PythonValidator::validate_batch_with_context(
        &[&first, &second, &third],
        ValidationLevel::Syntax,
        TOOLCHAIN_TEST_TIMEOUT_SECS,
        None,
    )
    .expect("batch validation runs");

    assert_eq!(
        results,
        vec![
            (SnippetStatus::Pass, None),
            (SnippetStatus::Pass, None),
            (SnippetStatus::Pass, None)
        ]
    );
}

#[test]
fn batch_syntax_fails_only_the_broken_snippet_and_passes_its_neighbours() {
    if !PythonValidator.is_available() {
        return;
    }
    let first = python_snippet("value = 1\n");
    let broken = python_snippet("def broken(:\n    pass\n");
    let third = python_snippet("value = 3\n");

    let results = PythonValidator::validate_batch_with_context(
        &[&first, &broken, &third],
        ValidationLevel::Syntax,
        TOOLCHAIN_TEST_TIMEOUT_SECS,
        None,
    )
    .expect("batch validation runs");

    assert_eq!(results.len(), 3);
    assert_eq!(results[0], (SnippetStatus::Pass, None));
    assert_eq!(results[2], (SnippetStatus::Pass, None));
    assert_eq!(results[1].0, SnippetStatus::Fail);
    assert!(
        results[1]
            .1
            .as_deref()
            .is_some_and(|message| message.contains("SyntaxError")),
        "the failing snippet must carry its own diagnostic: {:?}",
        results[1].1
    );
}

#[test]
fn batch_compile_fails_only_the_broken_snippet() {
    if !PythonValidator.is_available() {
        return;
    }
    let first = python_snippet("value = 1\n");
    let broken = python_snippet("return 1\n");
    let third = python_snippet("value = 3\n");

    let results = PythonValidator::validate_batch_with_context(
        &[&first, &broken, &third],
        ValidationLevel::Compile,
        TOOLCHAIN_TEST_TIMEOUT_SECS,
        None,
    )
    .expect("batch validation runs");

    assert_eq!(results[0], (SnippetStatus::Pass, None));
    assert_eq!(results[1].0, SnippetStatus::Fail);
    assert_eq!(results[2], (SnippetStatus::Pass, None));
}

#[test]
fn batch_type_check_fails_only_the_snippet_pyrefly_names() {
    if which::which("pyrefly").is_err() {
        return;
    }
    let first = python_snippet("value: int = 1\nprint(value)\n");
    let broken = python_snippet("undefined_batch_name()\n");
    let third = python_snippet("other: int = 3\nprint(other)\n");

    let results = PythonValidator::validate_batch_with_context(
        &[&first, &broken, &third],
        ValidationLevel::TypeCheck,
        TOOLCHAIN_TEST_TIMEOUT_SECS,
        None,
    )
    .expect("batch validation runs");

    assert_eq!(results.len(), 3);
    assert_eq!(results[0], (SnippetStatus::Pass, None), "{:?}", results[0]);
    assert_eq!(results[1].0, SnippetStatus::Fail);
    assert!(
        results[1]
            .1
            .as_deref()
            .is_some_and(|message| message.contains("undefined_batch_name")),
        "{:?}",
        results[1].1
    );
    assert_eq!(results[2], (SnippetStatus::Pass, None), "{:?}", results[2]);
}

/// Regression for task #463: a published snippet with `level: typecheck` front matter and a
/// hard `IndentationError` (an empty `for` loop body) still passed, because `TypeCheck`
/// validated only through `pyrefly`, whose own parser does not have to reject exactly what
/// CPython's does. Simulates a `pyrefly` batch that reported nothing wrong at all (the shape a
/// lenient/recovering parser produces) alongside a real `py_compile` failure, and asserts the
/// compile precheck wins. ~keep
#[test]
fn compile_precheck_overrides_a_typecheck_pass_pyrefly_never_flagged() {
    let typecheck_results = vec![(SnippetStatus::Pass, None)];
    let compile_results = vec![(
        SnippetStatus::Fail,
        Some("IndentationError: expected an indented block after 'for' statement".to_string()),
    )];

    let merged = PythonValidator::apply_compile_precheck(typecheck_results, compile_results);

    assert_eq!(merged.len(), 1);
    assert_eq!(merged[0].0, SnippetStatus::Fail);
    assert!(
        merged[0]
            .1
            .as_deref()
            .is_some_and(|message| message.contains("IndentationError")),
        "{:?}",
        merged[0]
    );
}

/// Negative control: a genuine `pyrefly` finding on code that compiles cleanly must not be
/// discarded just because the compile precheck exists. ~keep
#[test]
fn compile_precheck_leaves_a_real_typecheck_failure_untouched_when_compile_passes() {
    let typecheck_results = vec![(SnippetStatus::Fail, Some("undefined_batch_name".to_string()))];
    let compile_results = vec![(SnippetStatus::Pass, None)];

    let merged = PythonValidator::apply_compile_precheck(typecheck_results, compile_results);

    assert_eq!(
        merged,
        vec![(SnippetStatus::Fail, Some("undefined_batch_name".to_string()))]
    );
}

/// Negative control: a clean compile precheck alongside a clean `pyrefly` pass must stay a
/// pass -- the override must never fire on a snippet the compile check did not itself fail.
#[test]
fn compile_precheck_leaves_a_clean_pass_untouched() {
    let typecheck_results = vec![(SnippetStatus::Pass, None)];
    let compile_results = vec![(SnippetStatus::Pass, None)];

    let merged = PythonValidator::apply_compile_precheck(typecheck_results, compile_results);

    assert_eq!(merged, vec![(SnippetStatus::Pass, None)]);
}

/// End-to-end confidence when the real toolchain is present: a snippet that does not parse at
/// all must fail `TypeCheck`, even though this validator's own early-return only guards
/// `pyrefly`'s absence, not a construct `pyrefly` might tolerate. ~keep
#[test]
fn batch_type_check_fails_a_snippet_that_does_not_compile() {
    if which::which("pyrefly").is_err() {
        return;
    }
    let broken = python_snippet("for value in range(3):\n");

    let results = PythonValidator::validate_batch_with_context(
        &[&broken],
        ValidationLevel::TypeCheck,
        TOOLCHAIN_TEST_TIMEOUT_SECS,
        None,
    )
    .expect("batch validation runs");

    assert_eq!(results.len(), 1);
    assert_ne!(results[0].0, SnippetStatus::Pass, "{:?}", results[0]);
}

#[test]
fn batch_type_check_reports_every_snippet_unavailable_when_pyrefly_is_missing() {
    if which::which("pyrefly").is_ok() {
        return;
    }
    let first = python_snippet("value = 1\n");
    let second = python_snippet("value = 2\n");

    let results =
        PythonValidator::validate_batch_with_context(&[&first, &second], ValidationLevel::TypeCheck, 10, None)
            .expect("batch validation runs");

    assert_eq!(
        results,
        vec![
            (SnippetStatus::Unavailable, Some(PYREFLY_UNAVAILABLE.to_string())),
            (SnippetStatus::Unavailable, Some(PYREFLY_UNAVAILABLE.to_string())),
        ]
    );
}

/// A checker that dies before reporting on a snippet must fail that snippet carrying the real
/// output, never leave it passing by default. ~keep
#[test]
fn unreported_snippets_fail_with_the_real_output_when_the_checker_breaks() {
    let file_names = vec!["snippet_batch_0.py".to_string(), "snippet_batch_1.py".to_string()];
    let output = concat!(
        r#"{"path": "/tmp/x/snippet_batch_0.py", "ok": true, "error": ""}"#,
        "\nTraceback (most recent call last)\n"
    );

    let results = PythonValidator::checker_results(&file_names, output);

    assert_eq!(results[0], (SnippetStatus::Pass, None));
    assert_eq!(
        results[1],
        (
            SnippetStatus::Fail,
            Some("Traceback (most recent call last)".to_string())
        )
    );
}

#[test]
fn pyrefly_blocks_attach_to_the_file_named_on_their_location_line() {
    let file_names = vec!["snippet_batch_0.py".to_string(), "snippet_batch_1.py".to_string()];
    let output = concat!(
        "ERROR Could not find name `missing` [unknown-name]\n",
        " --> /tmp/x/snippet_batch_1.py:1:1\n",
        "  |\n",
        "1 | missing()\n",
        " INFO 1 error\n"
    );

    let results = PythonValidator::typecheck_results(&file_names, false, output);

    assert_eq!(results[0], (SnippetStatus::Pass, None));
    assert_eq!(results[1].0, SnippetStatus::Fail);
    assert!(
        results[1]
            .1
            .as_deref()
            .is_some_and(|message| message.contains("snippet_batch_1.py:1:1")),
        "{:?}",
        results[1].1
    );
}

#[test]
fn a_type_checker_failure_naming_no_file_fails_every_snippet_with_the_real_output() {
    let file_names = vec!["snippet_batch_0.py".to_string(), "snippet_batch_1.py".to_string()];
    let output = "No `pyrefly.toml` found and the preset could not be resolved\n";

    let results = PythonValidator::typecheck_results(&file_names, false, output);

    assert_eq!(results.len(), 2);
    for result in &results {
        assert_eq!(result.0, SnippetStatus::Fail);
        assert_eq!(
            result.1.as_deref(),
            Some("No `pyrefly.toml` found and the preset could not be resolved")
        );
    }
}

#[test]
fn pyrefly_command_matches_scaffolded_python_tooling() {
    let command = PythonValidator::command(
        ValidationLevel::TypeCheck,
        std::path::Path::new("."),
        "python3",
        "snippet.py",
    )
    .expect("type-check command");
    assert_eq!(command.get_program(), "pyrefly");
    assert_eq!(command.get_args().collect::<Vec<_>>(), ["check", "snippet.py"]);
}

#[test]
fn unavailable_diagnostic_names_only_the_supported_checker() {
    assert_eq!(PYREFLY_UNAVAILABLE, "pyrefly is not available for Python type-checking");
    assert!(!PYREFLY_UNAVAILABLE.contains("mypy"));
}

#[test]
fn preserves_multiline_async_signature_lines() {
    let code = r"class UserServiceHandler:
    async def CreateUsers(
        self, request_iterator
    ) -> CreateUsersResponse:
        created_users = []
        return created_users
";

    let patched = PythonValidator::patch_code(code);
    assert!(patched.contains(") -> CreateUsersResponse:"));
    assert!(patched.contains("created_users = []"));
}

#[test]
fn syntax_validation_rejects_malformed_imports_and_indentation() {
    let path = PathBuf::from("broken.py");
    let snippet = Snippet {
        id: None,
        path: path.clone(),
        language: Language::Python,
        title: None,
        code: "from sample import call    from sample.types import Request\n  result = call()".into(),
        start_line: 1,
        block_index: 0,
        annotation: None,
        metadata: SnippetMetadata::default(),
        source_origin: SourceOrigin {
            path,
            line: 1,
            block_index: 0,
        },
    };

    let (status, _) = PythonValidator
        .validate(&snippet, ValidationLevel::Syntax, 10)
        .expect("syntax validator runs");
    assert_eq!(status, SnippetStatus::Fail);
}

#[test]
fn run_session_resolves_local_binding_from_working_directory() {
    if !PythonValidator.is_available() {
        return;
    }
    let directory = tempfile::tempdir().expect("temp directory");
    std::fs::write(directory.path().join("local_binding.py"), "VALUE = 42\n").expect("local binding");
    let path = PathBuf::from("local.py");
    let snippet = Snippet {
        id: None,
        path: path.clone(),
        language: Language::Python,
        title: None,
        code: "import local_binding\nassert local_binding.VALUE == 42\n".into(),
        start_line: 1,
        block_index: 0,
        annotation: None,
        metadata: SnippetMetadata::default(),
        source_origin: SourceOrigin {
            path,
            line: 1,
            block_index: 0,
        },
    };
    let session = ValidationSession {
        language: Language::Python,
        working_directory: directory.path().to_path_buf(),
        manifest: None,
        fingerprint: "test-binding".into(),
        env: std::collections::BTreeMap::new(),
        include_paths: Vec::new(),
        rust_features: Vec::new(),
        rust_dependencies: std::collections::BTreeMap::new(),
    };

    let (status, message) = PythonValidator
        .validate_in_session(&snippet, ValidationLevel::Run, 10, Some(&session))
        .expect("session validation runs");

    assert_eq!(status, SnippetStatus::Pass, "{message:?}");
}

/// Regression: `validate_with_context` used to create its session-scoped scratch directory
/// directly inside `session.working_directory` via a bare `tempdir_in`, leaving a
/// `.alef-snippet-*/` directory loose in a tracked package source directory after every run.
/// It must nest under the session's own `.alef/snippets/tmp` cache root instead — and stay
/// gone whether the snippet passes or fails. ~keep
#[test]
fn session_scratch_resolves_under_the_cache_root_and_is_removed_on_pass_and_fail() {
    if !PythonValidator.is_available() {
        return;
    }
    let directory = tempfile::tempdir().expect("temp directory");
    let session = ValidationSession {
        language: Language::Python,
        working_directory: directory.path().to_path_buf(),
        manifest: None,
        fingerprint: "scratch-shape-fixture".into(),
        env: std::collections::BTreeMap::new(),
        include_paths: Vec::new(),
        rust_features: Vec::new(),
        rust_dependencies: std::collections::BTreeMap::new(),
    };
    let passing = Snippet {
        id: None,
        path: "passing.py".into(),
        language: Language::Python,
        title: None,
        code: "value = 1\n".into(),
        start_line: 1,
        block_index: 0,
        annotation: None,
        metadata: SnippetMetadata::default(),
        source_origin: SourceOrigin {
            path: "passing.py".into(),
            line: 1,
            block_index: 0,
        },
    };
    let mut failing = passing.clone();
    failing.code = "def broken(:\n".into();

    let (pass_status, pass_message) = PythonValidator
        .validate_in_session(&passing, ValidationLevel::Syntax, 10, Some(&session))
        .expect("passing snippet validates");
    assert_eq!(pass_status, SnippetStatus::Pass, "{pass_message:?}");
    let (fail_status, _) = PythonValidator
        .validate_in_session(&failing, ValidationLevel::Syntax, 10, Some(&session))
        .expect("failing snippet validates");
    assert_eq!(fail_status, SnippetStatus::Fail);

    let top_level_entries: Vec<_> = std::fs::read_dir(directory.path())
        .expect("read working directory")
        .filter_map(|entry| entry.ok())
        .map(|entry| entry.file_name())
        .filter(|name| name != ".alef")
        .collect();
    assert!(
        top_level_entries.is_empty(),
        "no scratch entry may be left directly in working_directory: {top_level_entries:?}"
    );
    let scratch_root = directory.path().join(".alef/snippets/tmp");
    let remaining = std::fs::read_dir(&scratch_root)
        .map(|entries| entries.filter_map(|entry| entry.ok()).count())
        .unwrap_or(0);
    assert_eq!(
        remaining, 0,
        "scratch left behind under the cache root after a passing and a failing snippet validation"
    );
}