influxdb3-plugin-schemas 0.4.0

Schema types for InfluxDB 3 plugins.
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! Pure plugin-directory validation contract.
//!
//! This module defines *what a valid plugin is* — the layout rules
//! (entry-point classification) and the trigger-binding rule — as pure
//! functions over in-memory inputs. It is the shared contract that every
//! consumer (the packaging CLI today, the InfluxDB runtime later) must agree
//! on.
//!
//! # Purity
//!
//! This module is deliberately **pure**: no filesystem access, no Python
//! parser, no `tree-sitter` dependency. The heavyweight mechanism — walking a
//! directory and extracting top-level Python definitions — lives in
//! `influxdb3-plugin-sdk`, which feeds its results into the pure checks here.
//! A consumer that cannot take a `tree-sitter` dependency (or that loads
//! plugins from a non-filesystem source) implements the extraction rules
//! documented on [`TopLevelFunctionDef`] against its own parser and then calls
//! [`check_trigger_bindings`].
//!
//! # Extraction drift
//!
//! Because the extractor is not single-sourced (the SDK uses tree-sitter; a
//! runtime might use the CPython AST), the rules an extractor must satisfy are
//! captured three ways: the prose on [`TopLevelFunctionDef`], the SDK's reference
//! implementation, and the executable [`TOP_LEVEL_DEF_CONFORMANCE_CASES`] that any
//! extractor's test suite can iterate to prove conformance.

use crate::{Manifest, ReportedError, TriggerType};

/// A validated plugin: the parsed manifest plus the classified entry point.
///
/// Returned by the SDK's `validate::plugin_dir` on success so callers don't
/// re-parse the TOML or re-derive the entry-point kind.
///
/// `#[non_exhaustive]`: fields may be added without a breaking change; use
/// [`ValidatedPluginDefinition::new`] to construct.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ValidatedPluginDefinition {
    /// The parsed manifest.
    pub manifest: Manifest,
    /// The classified entry point.
    pub entry_point: EntryPoint,
}

impl ValidatedPluginDefinition {
    /// Constructs a [`ValidatedPluginDefinition`].
    ///
    /// Required because `#[non_exhaustive]` blocks struct-literal construction
    /// from other crates (e.g. the SDK orchestrator).
    pub fn new(manifest: Manifest, entry_point: EntryPoint) -> Self {
        Self {
            manifest,
            entry_point,
        }
    }
}

/// The classified Python entry point of a plugin directory.
///
/// `#[non_exhaustive]`: variants may be added without a breaking change.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EntryPoint {
    /// Entry point is the sole top-level `.py` file (single-file plugin).
    Single { file_name: String },
    /// Entry point is `__init__.py` (multi-file plugin).
    Multi,
}

impl EntryPoint {
    /// The entry-point filename. Returns the constant `"__init__.py"` for
    /// [`EntryPoint::Multi`].
    pub fn file_name(&self) -> &str {
        match self {
            EntryPoint::Single { file_name } => file_name,
            EntryPoint::Multi => "__init__.py",
        }
    }
}

/// A top-level Python definition extracted from an entry-point source.
///
/// An extractor (e.g. `influxdb3-plugin-sdk`'s reference `extract_top_level_defs`)
/// **must** capture, in source order:
///
/// - a top-level `def foo(...)` — sync,
/// - a top-level `async def foo(...)` — async,
/// - a top-level decorated function (`@deco` then `def foo`) — a decorator is
///   not indirection.
///
/// It **must not** capture:
///
/// - class methods,
/// - nested definitions (a `def` inside another `def`),
/// - definitions guarded by `if`/`try`/etc. (not at module top level),
/// - re-exports / module-level assignments (`foo = bar`).
///
/// The extractor does **not** dedup: a redefined name appears once per
/// occurrence, in source order. Last-occurrence-wins resolution is the
/// responsibility of [`check_trigger_bindings`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TopLevelFunctionDef {
    /// The function name.
    pub name: String,
    /// Whether the definition is `async def`.
    pub is_async: bool,
}

/// An individual validation failure.
///
/// The diagnostic type of the plugin-validation contract. Collected by the
/// SDK into a `ValidationReport` and surfaced together so multiple issues
/// appear in one pass.
///
/// `#[non_exhaustive]`: new variants may be added without a breaking change.
/// (On an enum, `#[non_exhaustive]` blocks exhaustive matching from outside
/// the crate, not construction of existing variants — so the SDK can still
/// build any variant.)
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ValidationError {
    /// Wraps a structural [`ReportedError`] from the schemas crate's
    /// two-phase parse (`Manifest::parse_toml` / `Index::parse_json`),
    /// preserving the field path and inner `SchemaError` losslessly so the
    /// CLI can render structural and cross-file diagnostics in one array.
    #[error(transparent)]
    SchemaReported(ReportedError),

    #[error("required file {file:?} is missing from the plugin directory")]
    MissingRequiredFile { file: String },

    #[error("{entry_point} does not parse as valid Python: {message}")]
    PythonParse {
        entry_point: String,
        message: String,
    },

    #[error(
        "trigger {trigger:?} is declared in manifest.toml but has no matching \
         top-level `def {}(...)` in {entry_point}",
        .trigger.as_str()
    )]
    TriggerNotImplemented {
        trigger: TriggerType,
        entry_point: String,
    },

    #[error(
        "trigger {trigger:?} is implemented as `async def` in {entry_point}; \
         the runtime invokes trigger functions synchronously"
    )]
    AsyncTriggerFn {
        trigger: TriggerType,
        entry_point: String,
    },

    #[error("no Python entry point found in the plugin directory (no .py files at the top level)")]
    NoEntryPoint,

    #[error(
        "multiple .py files found at the top level without __init__.py: {files:?}; add __init__.py for a multi-file plugin, or keep only one .py file"
    )]
    AmbiguousEntryPoint { files: Vec<String> },

    /// Plugin `(name, version)` already exists in the target index. Surfaces
    /// from the SDK's `validate::plugin_dir_with_index` so index-aware
    /// validation can collect uniqueness conflicts alongside other validation
    /// errors.
    #[error("plugin ({name:?}, {version:?}) already exists in the target index")]
    NameVersionConflict { name: String, version: String },
}

impl ValidationError {
    /// Stable tag per variant; backs the CLI's JSON code mapping. The
    /// exhaustive match forces new variants to be registered (drift guard).
    pub fn variant_name(&self) -> &'static str {
        match self {
            Self::SchemaReported(_) => "SchemaReported",
            Self::MissingRequiredFile { .. } => "MissingRequiredFile",
            Self::PythonParse { .. } => "PythonParse",
            Self::TriggerNotImplemented { .. } => "TriggerNotImplemented",
            Self::AsyncTriggerFn { .. } => "AsyncTriggerFn",
            Self::NoEntryPoint => "NoEntryPoint",
            Self::AmbiguousEntryPoint { .. } => "AmbiguousEntryPoint",
            Self::NameVersionConflict { .. } => "NameVersionConflict",
        }
    }
}

/// Classifies the entry point of a plugin directory from its top-level
/// regular-file names.
///
/// `file_names` must already be filtered to top-level regular files
/// (symlinks and subdirectories excluded — that filesystem mechanism is owned
/// by the SDK lister). Classification is exact and case-sensitive.
///
/// Rules:
///
/// - `__init__.py` present → [`EntryPoint::Multi`] (priority, regardless of
///   any other `.py` files).
/// - no `__init__.py`, exactly one `.py` → [`EntryPoint::Single`].
/// - no `__init__.py`, zero `.py` → [`ValidationError::NoEntryPoint`].
/// - no `__init__.py`, two or more `.py` →
///   [`ValidationError::AmbiguousEntryPoint`], with the file list **sorted
///   here** (the lister yields OS-dependent `read_dir` order; determinism is a
///   contract property the CLI snapshots depend on).
pub fn classify_entry_point(file_names: &[String]) -> Result<EntryPoint, ValidationError> {
    if file_names.iter().any(|name| name == "__init__.py") {
        return Ok(EntryPoint::Multi);
    }

    let mut py_files: Vec<String> = file_names
        .iter()
        .filter(|name| name.ends_with(".py"))
        .cloned()
        .collect();

    match py_files.len() {
        0 => Err(ValidationError::NoEntryPoint),
        1 => Ok(EntryPoint::Single {
            file_name: py_files.pop().unwrap(),
        }),
        _ => {
            py_files.sort();
            Err(ValidationError::AmbiguousEntryPoint { files: py_files })
        }
    }
}

/// Checks that each declared trigger has a matching top-level synchronous
/// `def` in the extracted definitions.
///
/// Resolution is **last-occurrence-wins** over `defs`: when a name is defined
/// more than once, the last matching entry decides sync/async. This mirrors
/// the historical `HashMap` last-insert behavior, including the case where a
/// sync `def` is later redefined as `async def` (the later `async` kind wins).
///
/// For each declared trigger, in manifest order:
///
/// - no matching def → [`ValidationError::TriggerNotImplemented`],
/// - matched by an `async def` → [`ValidationError::AsyncTriggerFn`],
/// - matched by a sync `def` → ok.
///
/// Extra defs not declared as triggers are ignored.
pub fn check_trigger_bindings(
    declared: &[TriggerType],
    defs: &[TopLevelFunctionDef],
    entry_point: &str,
) -> Vec<ValidationError> {
    let mut errors = Vec::new();
    for trigger in declared {
        let expected = trigger.as_str();
        // Last-occurrence-wins: scan from the end for the first match.
        let resolved = defs.iter().rev().find(|d| d.name == expected);
        match resolved {
            None => errors.push(ValidationError::TriggerNotImplemented {
                trigger: *trigger,
                entry_point: entry_point.to_owned(),
            }),
            Some(def) if def.is_async => errors.push(ValidationError::AsyncTriggerFn {
                trigger: *trigger,
                entry_point: entry_point.to_owned(),
            }),
            Some(_) => {}
        }
    }
    errors
}

// ---------------------------------------------------------------------------
// Executable conformance corpus
// ---------------------------------------------------------------------------

/// One conformance case: a Python source and the extraction result any
/// conforming extractor must produce.
///
/// Pure data — `schemas` never parses Python. The corpus is `pub` so other
/// crates' test suites (the SDK's reference extractor today, a runtime's
/// extractor later) can iterate it and assert their extractor conforms.
#[derive(Debug, Clone, Copy)]
pub struct TopLevelDefConformanceCase {
    pub label: &'static str,
    pub source: &'static str,
    pub expected: TopLevelDefExpectation,
}

/// The expected outcome of extracting top-level defs from a source.
#[derive(Debug, Clone, Copy)]
pub enum TopLevelDefExpectation {
    /// Source parses; the extractor must return exactly these defs, in order.
    Defs(&'static [ExpectedTopLevelFunctionDef]),
    /// Source is unparseable; the extractor must return a parse error.
    ParseError,
}

/// An expected top-level def in a [`TopLevelDefConformanceCase`].
///
/// Distinct from [`TopLevelFunctionDef`] by design: `ExpectedTopLevelFunctionDef` uses `&'static str`
/// so the whole corpus can live in a `pub const`, whereas `TopLevelFunctionDef` uses
/// owned `String` because runtime extractors build it from arbitrary parsed
/// source. Same shape, different lifetimes — do not collapse.
#[derive(Debug, Clone, Copy)]
pub struct ExpectedTopLevelFunctionDef {
    pub name: &'static str,
    pub is_async: bool,
}

/// Canonical input → expected-output table for top-level-def extraction.
///
/// Covers the F6–F15 extraction rules in one table. Any extractor must
/// satisfy every case; the SDK's `tests/conformance.rs` iterates this against
/// its reference extractor and a runtime would mirror that loop.
pub const TOP_LEVEL_DEF_CONFORMANCE_CASES: &[TopLevelDefConformanceCase] = &[
    TopLevelDefConformanceCase {
        label: "plain_def",
        source: "def foo(): pass",
        expected: TopLevelDefExpectation::Defs(&[ExpectedTopLevelFunctionDef {
            name: "foo",
            is_async: false,
        }]),
    },
    TopLevelDefConformanceCase {
        label: "async_def",
        source: "async def foo(): pass",
        expected: TopLevelDefExpectation::Defs(&[ExpectedTopLevelFunctionDef {
            name: "foo",
            is_async: true,
        }]),
    },
    TopLevelDefConformanceCase {
        label: "decorated_def",
        source: "@staticmethod\ndef foo(): pass",
        expected: TopLevelDefExpectation::Defs(&[ExpectedTopLevelFunctionDef {
            name: "foo",
            is_async: false,
        }]),
    },
    TopLevelDefConformanceCase {
        label: "class_method",
        source: "class C:\n    def foo(self): pass",
        expected: TopLevelDefExpectation::Defs(&[]),
    },
    TopLevelDefConformanceCase {
        label: "nested_def",
        source: "def outer():\n    def inner(): pass",
        expected: TopLevelDefExpectation::Defs(&[ExpectedTopLevelFunctionDef {
            name: "outer",
            is_async: false,
        }]),
    },
    TopLevelDefConformanceCase {
        label: "guarded_if",
        source: "if True:\n    def foo(): pass",
        expected: TopLevelDefExpectation::Defs(&[]),
    },
    TopLevelDefConformanceCase {
        label: "reexport",
        source: "from bar import foo",
        expected: TopLevelDefExpectation::Defs(&[]),
    },
    TopLevelDefConformanceCase {
        label: "assignment",
        source: "foo = bar",
        expected: TopLevelDefExpectation::Defs(&[]),
    },
    TopLevelDefConformanceCase {
        label: "same_kind_redefinition",
        source: "def foo(): pass\ndef foo(): pass",
        expected: TopLevelDefExpectation::Defs(&[
            ExpectedTopLevelFunctionDef {
                name: "foo",
                is_async: false,
            },
            ExpectedTopLevelFunctionDef {
                name: "foo",
                is_async: false,
            },
        ]),
    },
    TopLevelDefConformanceCase {
        label: "sync_then_async",
        source: "def foo(): pass\nasync def foo(): pass",
        expected: TopLevelDefExpectation::Defs(&[
            ExpectedTopLevelFunctionDef {
                name: "foo",
                is_async: false,
            },
            ExpectedTopLevelFunctionDef {
                name: "foo",
                is_async: true,
            },
        ]),
    },
    TopLevelDefConformanceCase {
        label: "unparseable_source",
        source: "def foo(:",
        expected: TopLevelDefExpectation::ParseError,
    },
    TopLevelDefConformanceCase {
        label: "empty_source",
        source: "",
        expected: TopLevelDefExpectation::Defs(&[]),
    },
];

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{FieldPath, SchemaError};
    use pretty_assertions::assert_eq;

    // -- EntryPoint / ValidatedPluginDefinition data shapes ---------------------------

    #[test]
    fn entry_point_file_name() {
        assert_eq!(
            EntryPoint::Single {
                file_name: "my_plugin.py".into()
            }
            .file_name(),
            "my_plugin.py"
        );
        assert_eq!(EntryPoint::Multi.file_name(), "__init__.py");
    }

    #[test]
    fn validated_plugin_new_constructs() {
        let manifest = Manifest::parse_toml(
            "manifest_schema_version = \"1.0\"\n\
             [plugin]\n\
             name = \"p\"\n\
             version = \"0.1.0\"\n\
             description = \"x\"\n\
             triggers = [\"process_writes\"]\n\
             [dependencies]\n\
             database_version = \">=3.0.0\"\n",
        )
        .expect("fixture manifest parses");
        let vp = ValidatedPluginDefinition::new(manifest, EntryPoint::Multi);
        assert_eq!(vp.entry_point, EntryPoint::Multi);
        assert_eq!(vp.manifest.plugin.name.as_str(), "p");
    }

    // -- classify_entry_point  A1-A8 ----------------------------------------

    fn names(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn a1_init_py_present_is_multi() {
        assert_eq!(
            classify_entry_point(&names(&["__init__.py"])).unwrap(),
            EntryPoint::Multi
        );
    }

    #[test]
    fn a2_single_py_is_single() {
        assert_eq!(
            classify_entry_point(&names(&["plugin.py"])).unwrap(),
            EntryPoint::Single {
                file_name: "plugin.py".into()
            }
        );
    }

    #[test]
    fn a3_zero_py_is_no_entry_point() {
        let err = classify_entry_point(&names(&["README.md"])).unwrap_err();
        assert!(matches!(err, ValidationError::NoEntryPoint));
    }

    #[test]
    fn a4_multiple_py_is_ambiguous_sorted() {
        // Input deliberately unsorted; classify must sort.
        let err = classify_entry_point(&names(&["foo.py", "bar.py", "aaa.py"])).unwrap_err();
        match err {
            ValidationError::AmbiguousEntryPoint { files } => {
                assert_eq!(files, vec!["aaa.py", "bar.py", "foo.py"]);
            }
            other => panic!("expected AmbiguousEntryPoint, got {other:?}"),
        }
    }

    #[test]
    fn a5_non_py_files_ignored() {
        assert_eq!(
            classify_entry_point(&names(&["plugin.py", "requirements.txt", "README.md"])).unwrap(),
            EntryPoint::Single {
                file_name: "plugin.py".into()
            }
        );
    }

    #[test]
    fn a6_init_py_plus_helper_is_multi() {
        assert_eq!(
            classify_entry_point(&names(&["__init__.py", "helper.py"])).unwrap(),
            EntryPoint::Multi
        );
    }

    #[test]
    fn a7_bare_dot_py_counts() {
        assert_eq!(
            classify_entry_point(&names(&[".py"])).unwrap(),
            EntryPoint::Single {
                file_name: ".py".into()
            }
        );
    }

    #[test]
    fn a8_classification_is_case_sensitive() {
        // `Foo.PY` does not end with ".py"; `__INIT__.py` is not `__init__.py`.
        // `__INIT__.py` does end in ".py" though, so it's the sole single-file.
        assert_eq!(
            classify_entry_point(&names(&["__INIT__.py"])).unwrap(),
            EntryPoint::Single {
                file_name: "__INIT__.py".into()
            }
        );
        let err = classify_entry_point(&names(&["Foo.PY"])).unwrap_err();
        assert!(
            matches!(err, ValidationError::NoEntryPoint),
            "Foo.PY must not be recognized as a .py file"
        );
    }

    // -- check_trigger_bindings  F1-F5, F13 -----------------------------------------

    fn def(name: &str, is_async: bool) -> TopLevelFunctionDef {
        TopLevelFunctionDef {
            name: name.into(),
            is_async,
        }
    }

    #[test]
    fn f1_sync_def_matches_trigger() {
        let errs = check_trigger_bindings(
            &[TriggerType::ProcessWrites],
            &[def("process_writes", false)],
            "__init__.py",
        );
        assert!(errs.is_empty(), "expected no errors, got {errs:?}");
    }

    #[test]
    fn f2_no_matching_def_is_not_implemented() {
        let errs = check_trigger_bindings(
            &[TriggerType::ProcessWrites],
            &[def("something_else", false)],
            "__init__.py",
        );
        assert_eq!(errs.len(), 1);
        assert!(matches!(
            errs[0],
            ValidationError::TriggerNotImplemented {
                trigger: TriggerType::ProcessWrites,
                ..
            }
        ));
    }

    #[test]
    fn f3_async_def_is_async_trigger_fn() {
        let errs = check_trigger_bindings(
            &[TriggerType::ProcessWrites],
            &[def("process_writes", true)],
            "__init__.py",
        );
        assert_eq!(errs.len(), 1);
        assert!(matches!(errs[0], ValidationError::AsyncTriggerFn { .. }));
    }

    #[test]
    fn f4_multiple_bad_triggers_all_reported() {
        let errs = check_trigger_bindings(
            &[
                TriggerType::ProcessWrites,
                TriggerType::ProcessScheduledCall,
                TriggerType::ProcessRequest,
            ],
            &[def("unrelated", false)],
            "__init__.py",
        );
        assert_eq!(errs.len(), 3);
    }

    #[test]
    fn f5_extra_defs_ignored() {
        let errs = check_trigger_bindings(
            &[TriggerType::ProcessWrites],
            &[def("process_writes", false), def("helper", false)],
            "__init__.py",
        );
        assert!(errs.is_empty());
    }

    #[test]
    fn f13_redefinition_last_wins_sync_only() {
        // Two sync defs: last wins, still sync → ok.
        let errs = check_trigger_bindings(
            &[TriggerType::ProcessWrites],
            &[def("process_writes", false), def("process_writes", false)],
            "__init__.py",
        );
        assert!(errs.is_empty());
    }

    #[test]
    fn f13_redefinition_last_wins_sync_then_async() {
        // Sync then async: later async kind wins → AsyncTriggerFn.
        let errs = check_trigger_bindings(
            &[TriggerType::ProcessWrites],
            &[def("process_writes", false), def("process_writes", true)],
            "__init__.py",
        );
        assert_eq!(errs.len(), 1);
        assert!(matches!(errs[0], ValidationError::AsyncTriggerFn { .. }));
    }

    #[test]
    fn f13_redefinition_last_wins_async_then_sync() {
        // Async then sync: later sync kind wins → ok.
        let errs = check_trigger_bindings(
            &[TriggerType::ProcessWrites],
            &[def("process_writes", true), def("process_writes", false)],
            "__init__.py",
        );
        assert!(errs.is_empty());
    }

    // -- ValidationError display + variant tags (moved from sdk) -------------

    fn every_validation_variant() -> Vec<ValidationError> {
        vec![
            ValidationError::SchemaReported(ReportedError::new(
                FieldPath::root().field("plugin").field("description"),
                SchemaError::DescriptionEmpty,
            )),
            ValidationError::MissingRequiredFile {
                file: "__init__.py".into(),
            },
            ValidationError::PythonParse {
                entry_point: "__init__.py".into(),
                message: "unexpected token".into(),
            },
            ValidationError::TriggerNotImplemented {
                trigger: TriggerType::ProcessWrites,
                entry_point: "__init__.py".into(),
            },
            ValidationError::AsyncTriggerFn {
                trigger: TriggerType::ProcessScheduledCall,
                entry_point: "__init__.py".into(),
            },
            ValidationError::NoEntryPoint,
            ValidationError::AmbiguousEntryPoint {
                files: vec!["a.py".into(), "b.py".into()],
            },
            ValidationError::NameVersionConflict {
                name: "downsampler".into(),
                version: "1.2.0".into(),
            },
        ]
    }

    #[test]
    fn every_validation_variant_covered() {
        // Sanity: the fixture lists one of every variant_name.
        let tags: Vec<&'static str> = every_validation_variant()
            .iter()
            .map(ValidationError::variant_name)
            .collect();
        assert_eq!(tags.len(), 8);
    }

    #[test]
    fn validation_error_display_stable() {
        let rendered: Vec<String> = every_validation_variant()
            .iter()
            .map(|e| e.to_string())
            .collect();
        insta::assert_yaml_snapshot!("validation_error_display", rendered);
    }

    #[test]
    fn validation_error_variant_tags_stable() {
        let tags: Vec<&'static str> = every_validation_variant()
            .iter()
            .map(ValidationError::variant_name)
            .collect();
        insta::assert_yaml_snapshot!("validation_error_variant_tags", tags);
    }

    /// `ValidationError::SchemaReported` wraps `ReportedError` losslessly
    /// (path + inner variant), so downstream callers can pattern-match on
    /// the original `SchemaError` variant and field path.
    #[test]
    fn schemas_error_structured_payload_preserved_via_validation_schema_reported() {
        let reported = ReportedError::new(
            FieldPath::root().field("plugin").field("description"),
            SchemaError::DescriptionEmpty,
        );
        let wrapped = ValidationError::SchemaReported(reported);
        match &wrapped {
            ValidationError::SchemaReported(r) => {
                assert_eq!(r.path.as_str(), "plugin.description");
                assert!(matches!(r.error, SchemaError::DescriptionEmpty));
            }
            other => panic!("expected SchemaReported, got {other:?}"),
        }
    }

    // -- conformance corpus sanity ------------------------------------------

    #[test]
    fn corpus_labels_unique() {
        let mut labels: Vec<&str> = TOP_LEVEL_DEF_CONFORMANCE_CASES
            .iter()
            .map(|c| c.label)
            .collect();
        let count = labels.len();
        labels.sort_unstable();
        labels.dedup();
        assert_eq!(labels.len(), count, "corpus labels must be unique");
    }

    #[test]
    fn corpus_covers_required_rules() {
        let labels: Vec<&str> = TOP_LEVEL_DEF_CONFORMANCE_CASES
            .iter()
            .map(|c| c.label)
            .collect();
        for required in [
            "plain_def",
            "async_def",
            "decorated_def",
            "class_method",
            "nested_def",
            "guarded_if",
            "reexport",
            "assignment",
            "same_kind_redefinition",
            "sync_then_async",
            "unparseable_source",
            "empty_source",
        ] {
            assert!(
                labels.contains(&required),
                "corpus missing required case `{required}`"
            );
        }
    }
}