weirflow 0.1.0

GPU-first dataflow analysis primitives for Vyre and Santh compiler pipelines.
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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! Weir dataflow analysis crate.
//!
//! This crate owns dataflow analyses and reusable fixed-point execution
//! scaffolding. CPU functions in module internals are parity oracles only; the
//! production surface builds Vyre programs for GPU dispatch.
//!
//! # Example: dominators on a diamond CFG
//!
//! ```
//! use std::collections::{HashMap, HashSet};
//! use weir::ssa::{try_compute_dominators, Block, Cfg};
//!
//! // CFG:  0 → {1, 2} → 3
//! let mut blocks = HashMap::new();
//! for (id, preds, succs) in [
//!     (0u32, vec![],     vec![1, 2]),
//!     (1,    vec![0],    vec![3]),
//!     (2,    vec![0],    vec![3]),
//!     (3,    vec![1, 2], vec![]),
//! ] {
//!     blocks.insert(id, Block { id, preds, succs, defs: HashSet::new(), uses: HashSet::new() });
//! }
//!
//! let idoms = try_compute_dominators(&Cfg { entry: 0, blocks }).unwrap();
//! assert_eq!(idoms[&1], 0);
//! assert_eq!(idoms[&2], 0);
//! assert_eq!(idoms[&3], 0); // merge point is dominated by the diamond head
//! ```

/// Unifying trait and generic drivers for Weir's bitset fixed-point families.
///
/// This module is primarily used via the [`define_analysis_family!`] macro.
/// See [`reaching`](crate::reaching), [`live`](crate::live),
/// [`points_to`](crate::points_to), and [`slice`](crate::slice) for
/// concrete families.
pub mod analysis_family;

/// Call-graph construction with indirect resolution (DF-5).
///
/// Build a callgraph propagation Program:
///
/// ```no_run
/// use weir::callgraph::callgraph_build;
///
/// let program = callgraph_build("direct", "indirect", "pts", "cg_out");
/// ```
pub mod callgraph;

#[cfg(any(test, feature = "cpu-parity"))]
/// Bitset closure oracle for CPU parity verification.
///
/// ```ignore
/// use weir::bitset_closure_oracle;
/// ```
pub mod bitset_closure_oracle;

/// Control-dependence query (does `b` execute on every path through `a`?).
///
/// Build a control-dependence Program:
///
/// ```no_run
/// use weir::control_dependence::control_dependence;
///
/// let program = control_dependence(4, "successor_pdom", "pdom_n", "out");
/// ```
pub mod control_dependence;

/// Cross-language FFI reachability analysis.
///
/// Build a cross-language reach Program:
///
/// ```no_run
/// use weir::cross_language::cross_language;
///
/// let program = cross_language(
///     4, "source", "sink", "post_cross",
///     "current", "next", "changed", "seed", "out",
/// ).unwrap();
/// ```
pub mod cross_language;

/// Def-use chain queries over SSA form (DF-11).
///
/// Look up uses of an SSA definition:
///
/// ```
/// use std::collections::HashMap;
/// use weir::def_use::try_def_use_chain;
/// use weir::ssa::SsaForm;
///
/// let form = SsaForm {
///     phi_nodes: HashMap::new(),
///     renamed_usages: HashMap::new(),
///     def_use_chains: {
///         let mut m = HashMap::new();
///         m.insert(7, vec![3, 5, 9]);
///         m
///     },
/// };
///
/// assert_eq!(try_def_use_chain(&form, 7).unwrap(), vec![3, 5, 9]);
/// ```
pub mod def_use;

mod dense_domain;
pub mod dispatch_decode;
mod dispatch_input_cache;
pub mod resident_cache_identity;

/// Dominator-tree construction and query (DF-1).
///
/// Build a dominator predicate Program:
///
/// ```no_run
/// use weir::dominators::dominates;
///
/// let program = dominates(4, "dom_set", "target", "out");
/// ```
pub mod dominators;

mod error_format;

/// Escape analysis: does a pointer leave its defining frame? (DF-8).
///
/// Build an escape-propagation Program:
///
/// ```no_run
/// use weir::escape::escape_analyze_with_count;
///
/// let program = escape_analyze_with_count("pts", "cg", "out", 64);
/// ```
pub mod escape;

/// Escape-set query over points-to sets.
///
/// Build an escape-query Program:
///
/// ```no_run
/// use weir::escapes::escapes;
///
/// let program = escapes(4, "pts", "escape_set", "out");
/// ```
pub mod escapes;

/// Batch fixed-point execution over multiple seed sets.
///
/// ```ignore
/// use weir::fixed_point_batch::FixedPointBatch;
/// ```
pub mod fixed_point_batch;

mod fixed_point_closure;

/// Scale-aware execution planning for fixed-point analyses.
///
/// Build an execution plan from graph shape:
///
/// ```
/// use weir::fixed_point_execution_plan::{plan_from_parts, FixedPointExecutionPlan};
/// use weir::fixed_point_scratch::FrontierDensityTelemetry;
///
/// let telemetry = FrontierDensityTelemetry::default();
/// let plan = plan_from_parts(128, 16, 0, 2048, telemetry).unwrap();
/// assert!(!plan.should_use_resident_graph());
/// ```
pub mod fixed_point_execution_plan;

/// LRU cache for reusable fixed-point execution plans.
///
/// ```ignore
/// use weir::fixed_point_execution_plan_cache::FixedPointExecutionPlanCache;
/// ```
pub mod fixed_point_execution_plan_cache;

/// Packed forward CSR graph buffers for fixed-point GPU wrappers.
///
/// Build a prepared graph for generic forward analysis:
///
/// ```
/// use weir::fixed_point_graph::FixedPointForwardGraph;
///
/// let graph = FixedPointForwardGraph::new(
///     "example", 2, &[0, 1, 1], &[1], &[0xFFFF_FFFF],
/// ).unwrap();
/// assert_eq!(graph.node_count(), 2);
/// assert_eq!(graph.edge_count(), 1);
/// ```
pub mod fixed_point_graph;

/// Resident-GPU fixed-point closure drivers.
///
/// ```ignore
/// use weir::fixed_point_resident::FixedPointResidentGraph;
/// ```
pub mod fixed_point_resident;

/// Batch resident fixed-point execution.
///
/// ```ignore
/// use weir::fixed_point_resident_batch::FixedPointResidentBatch;
/// ```
pub mod fixed_point_resident_batch;

/// Cache for resident fixed-point graph and plan reuse.
///
/// ```ignore
/// use weir::fixed_point_resident_cache::FixedPointResidentGraphCache;
/// ```
pub mod fixed_point_resident_cache;

/// Reusable resident frontier scratch buffers.
///
/// ```ignore
/// use weir::fixed_point_resident_frontier::FixedPointResidentFrontierScratch;
/// ```
pub mod fixed_point_resident_frontier;

/// Resident execution plan construction.
///
/// ```ignore
/// use weir::fixed_point_resident_plan::FixedPointResidentPlan;
/// ```
pub mod fixed_point_resident_plan;

mod fixed_point_resident_sequence;

/// Reusable host-side scratch for fixed-point graph preparation.
///
/// ```
/// use weir::fixed_point_scratch::FixedPointScratch;
///
/// let scratch = FixedPointScratch::default();
/// ```
pub mod fixed_point_scratch;

/// Shared graph-layout contracts for CSR normalization.
///
/// Normalize a raw CSR into a canonical layout:
///
/// ```
/// use weir::graph_layout::{CsrGraph, NormalizedCsrGraph, CsrGraphNormalizationScratch};
///
/// let graph = CsrGraph::new(2, &[0, 1, 1], &[1], &[0xFFFF_FFFF]);
/// let normalized = graph.normalize("example").unwrap();
/// assert_eq!(normalized.node_count(), 2);
/// assert_eq!(normalized.edge_count(), 1);
/// ```
pub mod graph_layout;

/// IFDS/IDE interprocedural dataflow framework (DF-4).
///
/// Build one reachability step over the exploded supergraph:
///
/// ```no_run
/// use weir::ifds::ifds_reach_step;
/// use vyre_primitives::graph::program_graph::ProgramGraphShape;
///
/// let shape = ProgramGraphShape::new(4, 4);
/// let step = ifds_reach_step(shape, "fin", "fout");
/// ```
pub mod ifds;

mod ifds_borrowed_solve;
#[cfg(any(test, feature = "cpu-parity"))]
mod ifds_cpu_oracle;
#[cfg(test)]
mod ifds_cpu_oracle_tests;
mod ifds_csr_prepare;
mod ifds_csr_split;
mod ifds_frontier_decode;

/// GPU-native IFDS/IDE driver (G3).
///
/// Build a BFS step over the exploded supergraph:
///
/// ```no_run
/// use weir::ifds_gpu::{ifds_gpu_step, IfdsShape};
///
/// let shape = IfdsShape {
///     num_procs: 1, blocks_per_proc: 4, facts_per_proc: 4, edge_count: 4,
/// };
/// let step = ifds_gpu_step(shape, "fin", "fout").unwrap();
/// ```
pub mod ifds_gpu;

mod ifds_gpu_bytes;
mod ifds_resident_alloc;

/// Batch resident IFDS execution.
///
/// ```ignore
/// use weir::ifds_resident_batch::ResidentIfdsBatch;
/// ```
pub mod ifds_resident_batch;

/// Cache for resident IFDS graph reuse.
///
/// ```ignore
/// use weir::ifds_resident_cache::ResidentIfdsCache;
/// ```
pub mod ifds_resident_cache;

/// Direct-resident IFDS batch facade.
///
/// ```ignore
/// use weir::ifds_resident_direct_batch::DirectResidentIfdsBatch;
/// ```
pub mod ifds_resident_direct_batch;

/// Direct resident IFDS CSR preparation.
///
/// ```ignore
/// use weir::ifds_resident_direct_prepare::prepare_ifds_csr_resident_direct_via;
/// ```
pub mod ifds_resident_direct_prepare;

/// Reusable host scratch for direct-resident IFDS CSR preparation.
///
/// ```ignore
/// use weir::ifds_resident_direct_prepare_scratch::DirectResidentIfdsPrepareScratch;
/// ```
pub mod ifds_resident_direct_prepare_scratch;

mod ifds_resident_solve;
mod ifds_resident_types;
mod ifds_seed_frontiers;
mod ifds_seed_pack;
mod ifds_shape;

/// Adapter from the common Vyre resident backend contract to Weir IFDS.
///
/// ```ignore
/// use weir::ifds_vyre_resident::VyreResidentIfds;
/// ```
pub mod ifds_vyre_resident;

/// Live-variable analysis (DF-2 backward variant).
///
/// Prepare a graph for backward live-variable closure:
///
/// ```
/// use weir::live::prepare_live_graph;
///
/// let graph = prepare_live_graph(
///     2,
///     &[0, 1, 1],
///     &[1],
///     &[0xFFFF_FFFF],
/// ).unwrap();
/// assert_eq!(graph.node_count(), 2);
/// ```
pub mod live;

/// Liveness query: is variable `v` live at node `n`?
///
/// Build a live-at query Program:
///
/// ```no_run
/// use weir::live_at::live_at;
///
/// let program = live_at(4, "live_in", "query", "out");
/// ```
pub mod live_at;

/// Loop summarization with widening+narrowing (DF-10).
///
/// Build a loop-summary Program:
///
/// ```no_run
/// use weir::loop_sum::loop_summarize;
///
/// let program = loop_summarize("prev", "next", "out");
/// ```
pub mod loop_sum;

/// May-alias query packed as a bitset.
///
/// Build a may-alias Program:
///
/// ```no_run
/// use weir::may_alias::may_alias;
///
/// let program = may_alias(4, "pts_p", "pts_q", "scratch", "out");
/// ```
pub mod may_alias;

/// Must-initialization analysis.
///
/// Build a must-init query Program:
///
/// ```no_run
/// use weir::must_init::must_init;
///
/// let program = must_init(4, "def_dominates", "use_set", "out");
/// ```
pub mod must_init;

#[cfg(any(test, feature = "cpu-parity"))]
/// CPU parity oracle dispatch surface.
///
/// ```ignore
/// use weir::oracle;
/// ```
pub mod oracle;

/// Relation import/export fixtures for IFDS and differential evidence.
///
/// ```ignore
/// use weir::relation_interchange::{
///     export_relation_interchange_bytes, import_relation_interchange_bytes,
/// };
/// ```
pub mod relation_interchange;

mod output_scratch;

/// Andersen points-to analysis (DF-3).
///
/// Prepare a graph for points-to subset closure:
///
/// ```
/// use weir::points_to::prepare_points_to_subset_graph;
///
/// let graph = prepare_points_to_subset_graph(
///     2,
///     &[0, 1, 1],
///     &[1],
///     &[0xFFFF_FFFF],
/// ).unwrap();
/// assert_eq!(graph.node_count(), 2);
/// ```
pub mod points_to;

/// Post-dominator tree query.
///
/// Build a post-dominates query Program:
///
/// ```no_run
/// use weir::post_dominates::post_dominates;
///
/// let program = post_dominates(4, "pdom_set", "target_set", "out");
/// ```
pub mod post_dominates;

/// Interval range propagation (DF-7).
///
/// Build a range-propagation Program:
///
/// ```no_run
/// use weir::range::range_propagate;
///
/// let program = range_propagate("defs_in", "edges_in", "ranges_out");
/// ```
pub mod range;

/// Interval bound check for VSA results.
///
/// Build a range-check Program:
///
/// ```no_run
/// use weir::range_check::range_check;
///
/// let program = range_check(4, "interval_hi", "bound", "out");
/// ```
pub mod range_check;

/// Witness extraction from IFDS reachability results.
///
/// Prepare a witness graph and extract a source-to-sink path:
///
/// ```
/// use weir::reachability_witness::{
///     prepare_witness_graph, extract_path_prepared, NodeAttr, PathSeed,
/// };
///
/// let attrs = vec![
///     NodeAttr { byte_start: 0, byte_end: 4, file_idx: 0 },
///     NodeAttr { byte_start: 5, byte_end: 9, file_idx: 0 },
/// ];
/// let files = vec!["example.c".to_string()];
/// let descriptions = vec!["source".to_string(), "sink".to_string()];
/// let edge_offsets = vec![0, 1, 1];
/// let edge_targets = vec![1];
/// let edge_kind_mask = vec![1u32];
///
/// let graph = prepare_witness_graph(
///     &edge_offsets, &edge_targets, &edge_kind_mask,
///     &attrs, &files, &descriptions, "c-c11",
/// );
///
/// let seed = PathSeed {
///     source_file: "example.c".to_string(),
///     source_node: 0,
///     sink_file: "example.c".to_string(),
///     sink_node: 1,
/// };
/// let source_reach = vec![u32::MAX; 1];
/// let path = extract_path_prepared(&seed, &source_reach, &[], &graph).unwrap();
/// assert_eq!(path.statements.len(), 2);
/// ```
pub mod reachability_witness;

/// Reaching definitions analysis (DF-2).
///
/// Prepare a graph for forward reaching-definitions closure:
///
/// ```
/// use weir::reaching::prepare_reaching_graph;
///
/// let graph = prepare_reaching_graph(
///     2,
///     &[0, 1, 1],
///     &[1],
///     &[0xFFFF_FFFF],
/// ).unwrap();
/// assert_eq!(graph.node_count(), 2);
/// assert_eq!(graph.edge_count(), 1);
/// ```
pub mod reaching;

/// Reaching-definitions query packed as a bitset.
///
/// Build a reaching-def query Program:
///
/// ```no_run
/// use weir::reaching_def::reaching_def;
///
/// let program = reaching_def(4, "gen_kill_in", "use_set", "out");
/// ```
pub mod reaching_def;

/// Compact reaching-definition summary queries.
///
/// Fold partial summary triples into a single summary:
///
/// ```
/// use weir::reaching_def_summary::fold_summary_partials;
///
/// let partials = [3, 1, 0xAB, 2, 0, 0xCD, 5, 1, 0xEF];
/// let [count, any, checksum] = fold_summary_partials(&partials);
/// assert_eq!(count, 10);
/// assert_eq!(any, 1);
/// assert_eq!(checksum, 0xAB ^ 0xEF);
/// ```
pub mod reaching_def_summary;

mod resident_cache_lru;

/// Strongly-connected-component membership query.
///
/// Build an SCC-membership query Program:
///
/// ```no_run
/// use weir::scc_query::scc_query;
///
/// let program = scc_query(4, "same_scc", "query", "out");
/// ```
pub mod scc_query;

/// Backward program slicer (DF-6).
///
/// Prepare a graph for backward slicing:
///
/// ```
/// use weir::slice::prepare_slice_graph;
///
/// let graph = prepare_slice_graph(
///     2,
///     &[0, 1, 1],
///     &[1],
///     &[0xFFFF_FFFF],
/// ).unwrap();
/// assert_eq!(graph.node_count(), 2);
/// ```
pub mod slice;

/// Soundness regime markers and evidence types.
///
/// Tag a dataflow result with its soundness regime:
///
/// ```
/// use weir::soundness::{DataflowEvidence, Soundness, PrimitiveSoundness, PrecisionContract};
///
/// let evidence = DataflowEvidence::new(vec![1u32, 2, 3], Soundness::Exact);
/// assert_eq!(evidence.soundness, Soundness::Exact);
///
/// let primitive = PrimitiveSoundness::new("weir::ssa", Soundness::Exact);
/// assert_eq!(primitive.op_id, "weir::ssa");
/// let contract = PrecisionContract::ZeroFalsePositive;
/// ```
pub mod soundness;

/// SSA construction via Cytron's algorithm (DF-1).
///
/// Compute immediate dominators for a diamond CFG:
///
/// ```
/// use std::collections::{HashMap, HashSet};
/// use weir::ssa::{try_compute_dominators, Block, Cfg};
///
/// let mut blocks = HashMap::new();
/// for (id, preds, succs) in [
///     (0u32, vec![], vec![1, 2]),
///     (1, vec![0], vec![3]),
///     (2, vec![0], vec![3]),
///     (3, vec![1, 2], vec![]),
/// ] {
///     blocks.insert(id, Block { id, preds, succs, defs: HashSet::new(), uses: HashSet::new() });
/// }
///
/// let idoms = try_compute_dominators(&Cfg { entry: 0, blocks }).unwrap();
/// assert_eq!(idoms[&1], 0);
/// assert_eq!(idoms[&2], 0);
/// assert_eq!(idoms[&3], 0);
/// ```
pub mod ssa;

mod staging_reserve;

/// Persistent procedure summaries (DF-9).
///
/// Build a summary-computation Program:
///
/// ```no_run
/// use weir::summary::summarize_function;
///
/// let program = summarize_function(
///     "fn_ast_in", "callgraph_in", "cached_summary_in", "summary_out",
/// );
/// ```
pub mod summary;

#[cfg(any(test, feature = "test-harness"))]
/// Test harness for parity and conformance testing.
///
/// ```ignore
/// use weir::test_harness;
/// ```
#[cfg(feature = "test-harness")]
pub mod test_harness;

/// Forward and backward CFG traversal step builders.
///
/// Build a forward CFG propagation step:
///
/// ```no_run
/// use weir::traversal_step::forward_cfg_step;
/// use vyre_primitives::graph::program_graph::ProgramGraphShape;
///
/// let shape = ProgramGraphShape::new(4, 4);
/// let step = forward_cfg_step(shape, "fin", "fout");
/// ```
pub mod traversal_step;

/// Constant-value-set reachability query.
///
/// Build a value-set query Program:
///
/// ```no_run
/// use weir::value_set::value_set;
///
/// let program = value_set(4, "const_in", "query", "out");
/// ```
pub mod value_set;

#[cfg(test)]
mod tests {
    mod test_ssa;

    #[test]
    fn crate_private_cpu_helpers_are_explicit_reference_oracles() {
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let src = manifest_dir.join("src");
        let mut stack = vec![src];
        let mut findings = Vec::new();
        while let Some(path) = stack.pop() {
            let entries = std::fs::read_dir(&path)
                .unwrap_or_else(|error| panic!("failed to read {}: {error}", path.display()));
            for entry in entries {
                let entry = entry.unwrap_or_else(|error| {
                    panic!(
                        "failed to read directory entry under {}: {error}",
                        path.display()
                    )
                });
                let path = entry.path();
                if path.is_dir() {
                    stack.push(path);
                    continue;
                }
                if path.extension().and_then(std::ffi::OsStr::to_str) != Some("rs") {
                    continue;
                }
                let source = std::fs::read_to_string(&path)
                    .unwrap_or_else(|error| panic!("failed to read {}: {error}", path.display()));
                let lines = source.lines().collect::<Vec<_>>();
                for (line_index, line) in lines.iter().enumerate() {
                    let trimmed = line.trim_start();
                    if !trimmed.starts_with("pub(crate) fn ") || !trimmed.contains("cpu") {
                        continue;
                    }
                    let context_start = line_index.saturating_sub(4);
                    let context = lines[context_start..=line_index].join("\n");
                    if !context.contains("#[deprecated")
                        || !context.contains("reference oracle only")
                    {
                        findings.push(format!(
                            "{}:{}: {line}",
                            path.strip_prefix(manifest_dir).unwrap_or(&path).display(),
                            line_index + 1
                        ));
                    }
                }
            }
        }
        assert!(
            findings.is_empty(),
            "crate-private CPU helpers must be explicit deprecated reference oracles, never production fallback hooks:\n{}",
            findings.join("\n")
        );
    }

    #[test]
    fn production_modules_do_not_call_cpu_oracles_directly() {
        const CPU_ORACLE_NAMES: &[&str] = &[
            "callgraph_build_cpu",
            "compute_cpu",
            "cpu_ref",
            "cpu_ref_sharded",
            "cpu_subset_closure",
            "ifds_reach_closure_cpu",
            "live_closure_cpu",
            "loop_summarize_cpu",
            "range_propagate_cpu",
            "reaching_closure_cpu",
            "slice_closure_cpu",
            "solve_cpu",
            "summarize_function_cpu",
        ];

        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let src = manifest_dir.join("src");
        let mut stack = vec![src];
        let mut findings = Vec::new();
        while let Some(path) = stack.pop() {
            let entries = std::fs::read_dir(&path)
                .unwrap_or_else(|error| panic!("failed to read {}: {error}", path.display()));
            for entry in entries {
                let entry = entry.unwrap_or_else(|error| {
                    panic!(
                        "failed to read directory entry under {}: {error}",
                        path.display()
                    )
                });
                let path = entry.path();
                if path.is_dir() {
                    stack.push(path);
                    continue;
                }
                if path.extension().and_then(std::ffi::OsStr::to_str) != Some("rs") {
                    continue;
                }
                let relative = path.strip_prefix(manifest_dir).unwrap_or(&path);
                let relative_text = relative.to_string_lossy();
                if relative_text.contains("/oracle/")
                    || relative_text.contains("_tests/")
                    || relative_text.contains("/test_harness/")
                    || relative_text.ends_with("_tests.rs")
                    || relative_text.ends_with("/tests.rs")
                    || relative_text.ends_with("_cpu_oracle.rs")
                    || relative_text.ends_with("/cpu_oracle.rs")
                    || relative_text.ends_with("/oracle.rs")
                {
                    continue;
                }
                let source = std::fs::read_to_string(&path)
                    .unwrap_or_else(|error| panic!("failed to read {}: {error}", path.display()));
                let mut deprecated_attr_body = false;
                let mut pending_reference_oracle_deprecation = false;
                let mut reference_oracle_body_depth = 0i32;
                let mut pending_test_cfg = false;
                let mut test_module_depth = 0i32;
                for (line_index, line) in source.lines().enumerate() {
                    let trimmed = line.trim_start();
                    if test_module_depth > 0 {
                        test_module_depth += super::brace_delta(line);
                        continue;
                    }
                    if reference_oracle_body_depth > 0 {
                        reference_oracle_body_depth += super::brace_delta(line);
                        continue;
                    }
                    if trimmed.starts_with("#[cfg(test)]") {
                        pending_test_cfg = true;
                        continue;
                    }
                    if pending_test_cfg {
                        if trimmed.starts_with("mod ") {
                            test_module_depth = super::brace_delta(line).max(1);
                            pending_test_cfg = false;
                            continue;
                        }
                        if !trimmed.starts_with("#[") {
                            pending_test_cfg = false;
                        }
                    }
                    if deprecated_attr_body {
                        pending_reference_oracle_deprecation |=
                            trimmed.contains("reference oracle only");
                        deprecated_attr_body = !trimmed.contains(")]");
                        continue;
                    }
                    if trimmed.starts_with("#[deprecated") {
                        pending_reference_oracle_deprecation =
                            trimmed.contains("reference oracle only");
                        deprecated_attr_body = !trimmed.contains(")]");
                        continue;
                    }
                    if pending_reference_oracle_deprecation && trimmed.starts_with("pub(crate) fn ")
                    {
                        reference_oracle_body_depth = super::brace_delta(line).max(1);
                        pending_reference_oracle_deprecation = false;
                        continue;
                    }
                    if !trimmed.starts_with("#[") {
                        pending_reference_oracle_deprecation = false;
                    }
                    if trimmed.starts_with("pub(crate) fn ")
                        || trimmed.starts_with("pub(crate) use ")
                        || trimmed.starts_with("use ")
                        || trimmed.starts_with("pub use ")
                        || trimmed.starts_with("///")
                        || trimmed.starts_with("//!")
                    {
                        continue;
                    }
                    if CPU_ORACLE_NAMES.iter().any(|name| trimmed.contains(name)) {
                        findings.push(format!("{}:{}: {line}", relative.display(), line_index + 1));
                    }
                }
            }
        }
        assert!(
            findings.is_empty(),
            "production Weir modules must dispatch GPU Programs and may only reach CPU oracles through weir::oracle parity APIs:\n{}",
            findings.join("\n")
        );
    }
}

#[cfg(test)]
fn brace_delta(line: &str) -> i32 {
    line.bytes().fold(0i32, |depth, byte| match byte {
        b'{' => depth + 1,
        b'}' => depth - 1,
        _ => depth,
    })
}

pub use soundness::{
    validate_dynamic_pipeline, validate_dynamic_primitive, validate_pipeline, validate_primitive,
    DataflowEvidence, DynamicPrimitiveSoundness, DynamicSoundnessViolation, PrecisionContract,
    PrimitiveSoundness, Soundness, SoundnessTagged, SoundnessViolation,
};