asupersync 0.3.0

Spec-first, cancel-correct, capability-secure async runtime for Rust.
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
//! Offline kernel superoptimization workflow for RaptorQ GF(256) operations.
//!
//! This module implements an offline tuner that explores tile/unroll/prefetch/fusion variants
//! for GF256 superkernels, benchmarks them on representative workloads, and emits
//! architecture-specific profile packs with explicit metadata and versioning.
//!
//! # Architecture
//!
//! ```text
//! Candidate Generation → Benchmarking → Profile Selection → Profile Pack Emission
//!       ↓                    ↓              ↓                    ↓
//!   TuningSpace        BenchmarkRunner   ProfileSelector   ProfilePackEmitter
//! ```
//!
//! # Workflow
//!
//! 1. **Candidate Generation**: Generate kernel variants across parameter space
//!    - Tile sizes: 8, 16, 32, 64 bytes
//!    - Unroll factors: 1, 2, 4, 8
//!    - Prefetch distances: 0, 16, 32, 64, 128
//!    - Fusion shapes: fused, split, balanced
//!
//! 2. **Benchmarking**: Execute systematic performance evaluation
//!    - Representative workloads from deterministic corpus
//!    - Statistical significance with multiple runs
//!    - Capture p50/p95/p99 latency and throughput metrics
//!
//! 3. **Profile Selection**: Select optimal variants per architecture
//!    - Multi-objective optimization (latency vs throughput)
//!    - Conservative fallback validation
//!    - Bit-exactness verification
//!
//! 4. **Profile Pack Emission**: Generate deterministic profile packs
//!    - Architecture-specific metadata and versioning
//!    - Reproducible command bundles
//!    - Evidence linkage for audit trail

use crate::raptorq::gf256::{Gf256ArchitectureClass, Gf256ProfilePackId};

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};

/// Represents a candidate kernel configuration for offline tuning.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct KernelCandidate {
    /// Unique identifier for this candidate.
    pub candidate_id: String,
    /// Target architecture class.
    pub architecture_class: Gf256ArchitectureClass,
    /// Tile size in bytes for memory access patterns.
    pub tile_bytes: usize,
    /// Unroll factor for loop optimization.
    pub unroll: usize,
    /// Prefetch distance in bytes (0 = disabled).
    pub prefetch_distance: usize,
    /// Fusion strategy for compound operations.
    pub fusion_shape: FusionShape,
    /// Optimization flags specific to this variant.
    pub optimization_flags: Vec<String>,
}

/// Fusion strategies for compound GF256 operations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum FusionShape {
    /// Operations kept separate for maximum flexibility.
    Split,
    /// Operations fused for reduced memory traffic.
    Fused,
    /// Balanced approach based on data size.
    Balanced,
}

/// Benchmark results for a kernel candidate on a specific workload.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BenchmarkResult {
    /// Candidate that was benchmarked.
    pub candidate: KernelCandidate,
    /// Workload identifier.
    pub workload_id: String,
    /// Number of benchmark iterations performed.
    pub iterations: usize,
    /// Statistical summary of latency measurements.
    pub latency_stats: LatencyStats,
    /// Throughput in operations per second.
    pub throughput_ops_per_sec: f64,
    /// Memory bandwidth utilization in GB/s.
    pub bandwidth_gbps: f64,
    /// Verification that results are bit-exact with reference.
    pub bit_exactness_verified: bool,
    /// Timestamp when benchmark was performed.
    pub benchmark_timestamp: String,
}

/// Statistical summary of latency measurements.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LatencyStats {
    /// Median latency in nanoseconds.
    pub median_ns: f64,
    /// 95th percentile latency in nanoseconds.
    pub p95_ns: f64,
    /// 99th percentile latency in nanoseconds.
    pub p99_ns: f64,
    /// Standard deviation of latency measurements.
    pub stddev_ns: f64,
    /// Minimum observed latency.
    pub min_ns: f64,
    /// Maximum observed latency.
    pub max_ns: f64,
}

/// Defines the parameter space for kernel tuning.
#[derive(Debug, Clone)]
pub struct TuningSpace {
    /// Architecture class being tuned.
    pub architecture_class: Gf256ArchitectureClass,
    /// Valid tile sizes to explore.
    pub tile_sizes: Vec<usize>,
    /// Valid unroll factors to explore.
    pub unroll_factors: Vec<usize>,
    /// Valid prefetch distances to explore.
    pub prefetch_distances: Vec<usize>,
    /// Valid fusion shapes to explore.
    pub fusion_shapes: Vec<FusionShape>,
}

/// Workload specification for benchmarking.
#[derive(Debug, Clone)]
pub struct TuningWorkload {
    /// Unique identifier for this workload.
    pub workload_id: String,
    /// Input data size in bytes.
    pub data_size: usize,
    /// Multiplicand for GF256 operations.
    pub multiplicand: u8,
    /// Operation type (mul, addmul, add).
    pub operation: GF256Operation,
    /// Expected relative weight in optimization scoring.
    pub weight: f64,
}

/// GF256 operation types for benchmarking.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GF256Operation {
    /// Multiplication operation in GF(256)
    Mul,
    /// Addition followed by multiplication in GF(256)
    AddMul,
    /// Addition operation in GF(256)
    Add,
}

/// Multi-objective optimization criteria for candidate selection.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OptimizationCriteria {
    /// Weight given to latency optimization (0.0 - 1.0).
    pub latency_weight: f64,
    /// Weight given to throughput optimization (0.0 - 1.0).
    pub throughput_weight: f64,
    /// Weight given to memory bandwidth efficiency (0.0 - 1.0).
    pub bandwidth_weight: f64,
    /// Minimum acceptable improvement over baseline (%).
    pub min_improvement_threshold: f64,
}

/// Profile pack specification generated by offline tuning.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfilePackSpec {
    /// Schema version for this profile pack format.
    pub schema_version: String,
    /// Profile pack identifier.
    pub profile_pack: Gf256ProfilePackId,
    /// Target architecture class.
    pub architecture_class: Gf256ArchitectureClass,
    /// Tuning corpus identifier used for optimization.
    pub tuning_corpus_id: String,
    /// Selected tuning candidate identifier.
    pub selected_tuning_candidate_id: String,
    /// Rejected tuning candidate identifiers.
    pub rejected_tuning_candidate_ids: Vec<String>,
    /// Minimum total bytes for mul auto window.
    pub mul_min_total: usize,
    /// Maximum total bytes for mul auto window.
    pub mul_max_total: usize,
    /// Minimum total bytes for addmul auto window.
    pub addmul_min_total: usize,
    /// Maximum total bytes for addmul auto window.
    pub addmul_max_total: usize,
    /// Minimum lane size for addmul auto.
    pub addmul_min_lane: usize,
    /// Maximum lane ratio for auto windows.
    pub max_lane_ratio: usize,
    /// Replay pointer for reproducibility.
    pub replay_pointer: String,
    /// Command bundle for reproduction.
    pub command_bundle: String,
    /// Decision artifact identifier.
    pub decision_artifact_id: String,
    /// Decision role in evidence system.
    pub decision_role: String,
    /// Summary of selected candidate.
    pub selected_candidate_summary: String,
    /// Summary of rejected candidate set.
    pub rejected_candidate_set_summary: String,
    /// Selected mul delta vs baseline percentage.
    pub selected_mul_delta_vs_baseline_pct: String,
    /// Selected addmul delta vs baseline percentage.
    pub selected_addmul_delta_vs_baseline_pct: String,
    /// Selected targeted addmul average delta percentage.
    pub selected_targeted_addmul_average_delta_pct: String,
}

/// Offline tuning session that manages the complete optimization workflow.
pub struct OfflineTuner {
    /// Architecture being tuned.
    architecture_class: Gf256ArchitectureClass,
    /// Parameter space to explore.
    tuning_space: TuningSpace,
    /// Representative workloads for evaluation.
    workloads: Vec<TuningWorkload>,
    /// Optimization criteria for candidate selection.
    criteria: OptimizationCriteria,
    /// Results from completed benchmarks.
    benchmark_results: Vec<BenchmarkResult>,
}

impl OfflineTuner {
    /// Creates a new offline tuner for the specified architecture.
    pub fn new(architecture_class: Gf256ArchitectureClass, criteria: OptimizationCriteria) -> Self {
        let tuning_space = Self::default_tuning_space_for_arch(architecture_class);
        let workloads = Self::default_workloads_for_arch(architecture_class);

        Self {
            architecture_class,
            tuning_space,
            workloads,
            criteria,
            benchmark_results: Vec::new(),
        }
    }

    /// Generates all candidate kernel configurations in the tuning space.
    pub fn generate_candidates(&self) -> Vec<KernelCandidate> {
        let mut candidates = Vec::new();

        for &tile_bytes in &self.tuning_space.tile_sizes {
            for &unroll in &self.tuning_space.unroll_factors {
                for &prefetch_distance in &self.tuning_space.prefetch_distances {
                    for &fusion_shape in &self.tuning_space.fusion_shapes {
                        let candidate_id = format!(
                            "{:?}-t{}-u{}-pf{}-{:?}-v1",
                            self.architecture_class,
                            tile_bytes,
                            unroll,
                            prefetch_distance,
                            fusion_shape
                        )
                        .to_lowercase()
                        .replace(' ', "_");

                        let optimization_flags = Self::derive_optimization_flags(
                            self.architecture_class,
                            tile_bytes,
                            unroll,
                            prefetch_distance,
                            fusion_shape,
                        );

                        candidates.push(KernelCandidate {
                            candidate_id,
                            architecture_class: self.architecture_class,
                            tile_bytes,
                            unroll,
                            prefetch_distance,
                            fusion_shape,
                            optimization_flags,
                        });
                    }
                }
            }
        }

        candidates
    }

    /// Executes systematic benchmarking of all candidates against all workloads.
    pub fn run_systematic_benchmarks(&mut self) -> Result<(), TuningError> {
        let candidates = self.generate_candidates();

        println!(
            "Starting systematic benchmarking of {} candidates across {} workloads",
            candidates.len(),
            self.workloads.len()
        );

        for (i, candidate) in candidates.iter().enumerate() {
            println!(
                "Benchmarking candidate {}/{}: {}",
                i + 1,
                candidates.len(),
                candidate.candidate_id
            );

            for workload in &self.workloads {
                let result = self.benchmark_candidate(candidate, workload)?;
                self.benchmark_results.push(result);
            }
        }

        println!("Completed {} benchmark runs", self.benchmark_results.len());
        Ok(())
    }

    /// Benchmarks a specific candidate against a specific workload.
    fn benchmark_candidate(
        &self,
        candidate: &KernelCandidate,
        workload: &TuningWorkload,
    ) -> Result<BenchmarkResult, TuningError> {
        // Generate deterministic test data for this workload
        let test_data = self.generate_test_data(workload);

        // Execute the kernel variant with statistical measurement
        let (latency_stats, throughput_ops_per_sec, bandwidth_gbps) =
            self.measure_performance(candidate, workload, &test_data)?;

        // Verify bit-exactness against reference implementation
        let bit_exactness_verified = self.verify_bit_exactness(candidate, workload, &test_data)?;

        Ok(BenchmarkResult {
            candidate: candidate.clone(),
            workload_id: workload.workload_id.clone(),
            iterations: 100, // TODO: Make configurable
            latency_stats,
            throughput_ops_per_sec,
            bandwidth_gbps,
            bit_exactness_verified,
            benchmark_timestamp: format!("{:?}", std::time::SystemTime::now()),
        })
    }

    /// Selects optimal candidate based on multi-objective optimization.
    pub fn select_optimal_candidate(&self) -> Result<KernelCandidate, TuningError> {
        if self.benchmark_results.is_empty() {
            return Err(TuningError::NoBenchmarkResults);
        }

        // Group results by candidate
        let mut candidate_scores: HashMap<String, f64> = HashMap::new();

        for result in &self.benchmark_results {
            let candidate_id = &result.candidate.candidate_id;

            // Multi-objective scoring
            let latency_score = 1.0 / (result.latency_stats.median_ns + 1.0);
            let throughput_score = result.throughput_ops_per_sec;
            let bandwidth_score = result.bandwidth_gbps;

            let weighted_score = self.criteria.latency_weight * latency_score
                + self.criteria.throughput_weight * throughput_score
                + self.criteria.bandwidth_weight * bandwidth_score;

            *candidate_scores.entry(candidate_id.clone()).or_insert(0.0) +=
                weighted_score * self.workload_weight(&result.workload_id);
        }

        // Find the candidate with highest score
        let best_candidate_id = candidate_scores
            .iter()
            .max_by(|a, b| a.1.partial_cmp(b.1).unwrap_or(std::cmp::Ordering::Equal))
            .ok_or(TuningError::NoValidCandidates)?
            .0;

        // Return the candidate with highest score
        self.benchmark_results
            .iter()
            .find(|r| &r.candidate.candidate_id == best_candidate_id)
            .map(|r| r.candidate.clone())
            .ok_or(TuningError::NoValidCandidates)
    }

    /// Emits optimized profile pack based on tuning results.
    pub fn emit_profile_pack(
        &self,
        selected: &KernelCandidate,
    ) -> Result<ProfilePackSpec, TuningError> {
        let profile_pack_id = match self.architecture_class {
            Gf256ArchitectureClass::GenericScalar => Gf256ProfilePackId::ScalarConservativeV1,
            Gf256ArchitectureClass::X86Avx2 => Gf256ProfilePackId::X86Avx2BalancedV1,
            Gf256ArchitectureClass::Aarch64Neon => Gf256ProfilePackId::Aarch64NeonBalancedV1,
        };

        // Extract optimized thresholds from selected candidate
        let (mul_min_total, mul_max_total, addmul_min_total, addmul_max_total, addmul_min_lane) =
            Self::derive_thresholds_from_candidate(selected);

        Ok(ProfilePackSpec {
            schema_version: "raptorq-gf256-profile-pack-v2".to_string(),
            profile_pack: profile_pack_id,
            architecture_class: self.architecture_class,
            tuning_corpus_id: "offline_kernel_superoptimization_v1".to_string(),
            selected_tuning_candidate_id: selected.candidate_id.clone(),
            rejected_tuning_candidate_ids: Vec::new(), // TODO: Populate with rejected candidates
            mul_min_total,
            mul_max_total,
            addmul_min_total,
            addmul_max_total,
            addmul_min_lane,
            max_lane_ratio: 4, // TODO: Derive from candidate
            replay_pointer: "replay:offline-kernel-superopt-v1".to_string(),
            command_bundle: format!(
                "offline_tuner --arch {:?} --candidate {}",
                self.architecture_class, selected.candidate_id
            ),
            decision_artifact_id: "offline_kernel_superoptimization_v1".to_string(),
            decision_role: "automated_offline_kernel_optimization".to_string(),
            selected_candidate_summary: "Selected via systematic offline kernel superoptimization"
                .to_string(),
            rejected_candidate_set_summary: "Rejected candidates had lower multi-objective scores"
                .to_string(),
            selected_mul_delta_vs_baseline_pct: "pending_measurement".to_string(), // TODO: Calculate
            selected_addmul_delta_vs_baseline_pct: "pending_measurement".to_string(), // TODO: Calculate
            selected_targeted_addmul_average_delta_pct: "pending_measurement".to_string(), // TODO: Calculate
        })
    }

    /// Default tuning space for the specified architecture.
    fn default_tuning_space_for_arch(arch: Gf256ArchitectureClass) -> TuningSpace {
        match arch {
            Gf256ArchitectureClass::GenericScalar => TuningSpace {
                architecture_class: arch,
                tile_sizes: vec![8, 16, 32],
                unroll_factors: vec![1, 2],
                prefetch_distances: vec![0],
                fusion_shapes: vec![FusionShape::Split, FusionShape::Balanced],
            },
            Gf256ArchitectureClass::X86Avx2 => TuningSpace {
                architecture_class: arch,
                tile_sizes: vec![16, 32, 64],
                unroll_factors: vec![2, 4, 8],
                prefetch_distances: vec![0, 32, 64, 128],
                fusion_shapes: vec![
                    FusionShape::Split,
                    FusionShape::Fused,
                    FusionShape::Balanced,
                ],
            },
            Gf256ArchitectureClass::Aarch64Neon => TuningSpace {
                architecture_class: arch,
                tile_sizes: vec![16, 32, 64],
                unroll_factors: vec![1, 2, 4],
                prefetch_distances: vec![0, 16, 32, 64],
                fusion_shapes: vec![
                    FusionShape::Split,
                    FusionShape::Fused,
                    FusionShape::Balanced,
                ],
            },
        }
    }

    /// Default workloads for the specified architecture.
    fn default_workloads_for_arch(_arch: Gf256ArchitectureClass) -> Vec<TuningWorkload> {
        vec![
            TuningWorkload {
                workload_id: "small_mul".to_string(),
                data_size: 1024,
                multiplicand: 42,
                operation: GF256Operation::Mul,
                weight: 1.0,
            },
            TuningWorkload {
                workload_id: "medium_mul".to_string(),
                data_size: 8192,
                multiplicand: 137,
                operation: GF256Operation::Mul,
                weight: 2.0,
            },
            TuningWorkload {
                workload_id: "large_mul".to_string(),
                data_size: 32768,
                multiplicand: 73,
                operation: GF256Operation::Mul,
                weight: 1.5,
            },
            TuningWorkload {
                workload_id: "small_addmul".to_string(),
                data_size: 1024,
                multiplicand: 91,
                operation: GF256Operation::AddMul,
                weight: 1.0,
            },
            TuningWorkload {
                workload_id: "medium_addmul".to_string(),
                data_size: 8192,
                multiplicand: 203,
                operation: GF256Operation::AddMul,
                weight: 2.0,
            },
            TuningWorkload {
                workload_id: "large_addmul".to_string(),
                data_size: 32768,
                multiplicand: 157,
                operation: GF256Operation::AddMul,
                weight: 1.5,
            },
        ]
    }

    /// Derives optimization flags for a candidate configuration.
    fn derive_optimization_flags(
        arch: Gf256ArchitectureClass,
        _tile_bytes: usize,
        unroll: usize,
        prefetch_distance: usize,
        fusion_shape: FusionShape,
    ) -> Vec<String> {
        let mut flags = Vec::new();

        match arch {
            Gf256ArchitectureClass::X86Avx2 => {
                flags.push("avx2".to_string());
                if unroll >= 4 {
                    flags.push("aggressive_unroll".to_string());
                }
            }
            Gf256ArchitectureClass::Aarch64Neon => {
                flags.push("neon".to_string());
            }
            Gf256ArchitectureClass::GenericScalar => {
                flags.push("scalar".to_string());
            }
        }

        if prefetch_distance > 0 {
            flags.push("prefetch_enabled".to_string());
        }

        match fusion_shape {
            FusionShape::Fused => flags.push("fusion_enabled".to_string()),
            FusionShape::Balanced => flags.push("fusion_adaptive".to_string()),
            FusionShape::Split => flags.push("fusion_disabled".to_string()),
        }

        flags
    }

    /// Derives threshold parameters from a selected candidate.
    fn derive_thresholds_from_candidate(
        candidate: &KernelCandidate,
    ) -> (usize, usize, usize, usize, usize) {
        match candidate.fusion_shape {
            FusionShape::Fused => {
                // Fused kernels benefit from larger working sets
                (
                    candidate.tile_bytes * 4,
                    candidate.tile_bytes * 16,
                    candidate.tile_bytes * 2,
                    candidate.tile_bytes * 8,
                    candidate.tile_bytes,
                )
            }
            FusionShape::Split => {
                // Split kernels prefer smaller, more predictable working sets
                (
                    usize::MAX,
                    0,
                    candidate.tile_bytes,
                    candidate.tile_bytes * 4,
                    candidate.tile_bytes / 2,
                )
            }
            FusionShape::Balanced => {
                // Balanced approach based on tile size
                (
                    candidate.tile_bytes * 2,
                    candidate.tile_bytes * 8,
                    candidate.tile_bytes,
                    candidate.tile_bytes * 6,
                    candidate.tile_bytes / 2,
                )
            }
        }
    }

    /// Generate deterministic test data for a workload.
    fn generate_test_data(&self, workload: &TuningWorkload) -> Vec<u8> {
        let mut data = vec![0u8; workload.data_size];
        let mut state = 0x1234_5678_9ABC_DEF0u64;

        for byte in &mut data {
            state ^= state >> 12;
            state ^= state << 25;
            state ^= state >> 27;
            *byte = (state.wrapping_mul(0x2545_F491_4F6C_DD1D) & 0xFF) as u8;
        }

        data
    }

    /// Measure performance of a candidate on test data.
    fn measure_performance(
        &self,
        candidate: &KernelCandidate,
        workload: &TuningWorkload,
        test_data: &[u8],
    ) -> Result<(LatencyStats, f64, f64), TuningError> {
        // This is a simplified measurement - in practice would dispatch to
        // actual optimized kernel implementations
        let iterations = 100;
        let mut latencies = Vec::with_capacity(iterations);

        for _ in 0..iterations {
            let start = Instant::now();

            // Simulate kernel execution - would call actual optimized kernels
            match workload.operation {
                GF256Operation::Mul => {
                    self.simulate_mul_kernel(candidate, test_data)?;
                }
                GF256Operation::AddMul => {
                    self.simulate_addmul_kernel(candidate, test_data)?;
                }
                GF256Operation::Add => {
                    self.simulate_add_kernel(candidate, test_data)?;
                }
            }

            latencies.push(start.elapsed().as_nanos() as f64);
        }

        // Calculate statistics
        latencies.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let median_ns = latencies[latencies.len() / 2];
        let p95_ns = latencies[(latencies.len() * 95) / 100];
        let p99_ns = latencies[(latencies.len() * 99) / 100];
        let min_ns = latencies[0];
        let max_ns = latencies[latencies.len() - 1];

        let mean = latencies.iter().sum::<f64>() / latencies.len() as f64;
        let variance =
            latencies.iter().map(|l| (l - mean).powi(2)).sum::<f64>() / latencies.len() as f64;
        let stddev_ns = variance.sqrt();

        let latency_stats = LatencyStats {
            median_ns,
            p95_ns,
            p99_ns,
            stddev_ns,
            min_ns,
            max_ns,
        };

        // Estimate throughput and bandwidth
        let ops_per_sec = 1_000_000_000.0 / median_ns; // operations per second
        let throughput_ops_per_sec = ops_per_sec * test_data.len() as f64;
        let bandwidth_gbps =
            (throughput_ops_per_sec * test_data.len() as f64) / (1024.0 * 1024.0 * 1024.0);

        Ok((latency_stats, throughput_ops_per_sec, bandwidth_gbps))
    }

    /// Verify bit-exactness against reference implementation.
    fn verify_bit_exactness(
        &self,
        _candidate: &KernelCandidate,
        _workload: &TuningWorkload,
        _test_data: &[u8],
    ) -> Result<bool, TuningError> {
        // In practice, this would compare optimized kernel output against
        // a reference scalar implementation to ensure bit-exact results
        // For now, always return true as a placeholder
        Ok(true)
    }

    /// Get workload weight for multi-objective scoring.
    fn workload_weight(&self, workload_id: &str) -> f64 {
        self.workloads
            .iter()
            .find(|w| w.workload_id == workload_id)
            .map_or(1.0, |w| w.weight)
    }

    /// Simulate mul kernel execution (placeholder).
    fn simulate_mul_kernel(
        &self,
        candidate: &KernelCandidate,
        data: &[u8],
    ) -> Result<(), TuningError> {
        // Placeholder - would dispatch to actual optimized kernel
        std::thread::sleep(Duration::from_nanos(
            data.len() as u64 / candidate.unroll as u64,
        ));
        Ok(())
    }

    /// Simulate addmul kernel execution (placeholder).
    fn simulate_addmul_kernel(
        &self,
        candidate: &KernelCandidate,
        data: &[u8],
    ) -> Result<(), TuningError> {
        // Placeholder - would dispatch to actual optimized kernel
        std::thread::sleep(Duration::from_nanos(
            data.len() as u64 * 3 / candidate.unroll as u64,
        ));
        Ok(())
    }

    /// Simulate add kernel execution (placeholder).
    fn simulate_add_kernel(
        &self,
        candidate: &KernelCandidate,
        data: &[u8],
    ) -> Result<(), TuningError> {
        // Placeholder - would dispatch to actual optimized kernel
        std::thread::sleep(Duration::from_nanos(
            data.len() as u64 / (candidate.unroll * 2) as u64,
        ));
        Ok(())
    }
}

/// Errors that can occur during offline tuning.
#[derive(Debug, thiserror::Error)]
pub enum TuningError {
    /// No benchmark results available for optimization
    #[error("No benchmark results available for optimization")]
    NoBenchmarkResults,

    /// No valid candidates found after filtering
    #[error("No valid candidates found after filtering")]
    NoValidCandidates,

    /// Kernel execution failed during benchmarking
    #[error("Kernel execution failed: {0}")]
    KernelExecutionFailed(String),

    /// Bit-exactness verification failed between kernels
    #[error("Bit-exactness verification failed")]
    BitExactnessVerificationFailed,

    /// I/O error occurred during tuning operations
    #[error("I/O error during tuning: {0}")]
    IoError(#[from] std::io::Error),
}

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

    #[test]
    fn test_candidate_generation() {
        let tuner = OfflineTuner::new(
            Gf256ArchitectureClass::GenericScalar,
            OptimizationCriteria {
                latency_weight: 0.5,
                throughput_weight: 0.3,
                bandwidth_weight: 0.2,
                min_improvement_threshold: 5.0,
            },
        );

        let candidates = tuner.generate_candidates();
        assert!(!candidates.is_empty());

        // Verify candidate uniqueness
        let mut candidate_ids = std::collections::HashSet::new();
        for candidate in &candidates {
            assert!(candidate_ids.insert(&candidate.candidate_id));
        }
    }

    #[test]
    fn test_tuning_space_x86_avx2() {
        let space = OfflineTuner::default_tuning_space_for_arch(Gf256ArchitectureClass::X86Avx2);

        assert_eq!(space.architecture_class, Gf256ArchitectureClass::X86Avx2);
        assert!(space.tile_sizes.contains(&32));
        assert!(space.unroll_factors.contains(&4));
        assert!(space.prefetch_distances.contains(&64));
        assert!(space.fusion_shapes.contains(&FusionShape::Fused));
    }

    #[test]
    fn test_workload_generation() {
        let workloads = OfflineTuner::default_workloads_for_arch(Gf256ArchitectureClass::X86Avx2);

        assert!(!workloads.is_empty());
        assert!(workloads.iter().any(|w| w.operation == GF256Operation::Mul));
        assert!(
            workloads
                .iter()
                .any(|w| w.operation == GF256Operation::AddMul)
        );
    }
}