ggen-core 26.7.3

Core graph-aware code generation engine
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
//! Pipeline optimization module for <60 second deployment target
//!
//! This module provides optimization strategies including:
//! - Parallel stage execution
//! - Container pre-warming
//! - Dependency caching
//! - Fast validation strategies

use super::{Context, Result};
use std::collections::HashMap;
use std::time::{Duration, Instant};
use tokio::task::JoinSet;

/// Performance targets for pipeline stages
#[derive(Debug, Clone)]
pub struct PerformanceTargets {
    /// Template selection target: <3s
    pub template_selection: Duration,
    /// Code generation target: <8s
    pub code_generation: Duration,
    /// Cleanroom setup target: <7s
    pub cleanroom_setup: Duration,
    /// Testing target: <15s
    pub testing: Duration,
    /// Validation target: <7s
    pub validation: Duration,
    /// Reporting target: <3s
    pub reporting: Duration,
    /// Total pipeline target: <45s (stretch) or <60s (required)
    pub total: Duration,
}

impl Default for PerformanceTargets {
    fn default() -> Self {
        Self {
            template_selection: Duration::from_secs(3),
            code_generation: Duration::from_secs(8),
            cleanroom_setup: Duration::from_secs(7),
            testing: Duration::from_secs(15),
            validation: Duration::from_secs(7),
            reporting: Duration::from_secs(3),
            total: Duration::from_secs(45), // Stretch goal
        }
    }
}

impl PerformanceTargets {
    /// Create targets for required <60s goal
    pub fn required() -> Self {
        Self {
            total: Duration::from_mins(1),
            ..Default::default()
        }
    }

    /// Create targets for stretch <45s goal
    pub fn stretch() -> Self {
        Self::default()
    }
}

/// Stage performance metrics
#[derive(Debug, Clone)]
pub struct StageMetrics {
    pub name: String,
    pub duration: Duration,
    pub target: Duration,
    pub met_target: bool,
}

impl StageMetrics {
    pub fn new(name: impl Into<String>, duration: Duration, target: Duration) -> Self {
        let met_target = duration <= target;
        Self {
            name: name.into(),
            duration,
            target,
            met_target,
        }
    }

    pub fn improvement_percent(&self) -> f64 {
        if self.duration <= self.target {
            let saved = self
                .target
                .checked_sub(self.duration)
                .unwrap_or_default()
                .as_secs_f64();
            (saved / self.target.as_secs_f64()) * 100.0
        } else {
            let exceeded = self
                .duration
                .checked_sub(self.target)
                .unwrap_or_default()
                .as_secs_f64();
            -((exceeded / self.target.as_secs_f64()) * 100.0)
        }
    }
}

/// Pipeline performance profiler
pub struct PipelineProfiler {
    stage_timings: HashMap<String, Duration>,
    targets: PerformanceTargets,
    total_start: Option<Instant>,
}

impl PipelineProfiler {
    pub fn new(targets: PerformanceTargets) -> Self {
        Self {
            stage_timings: HashMap::new(),
            targets,
            total_start: None,
        }
    }

    pub fn start_pipeline(&mut self) {
        self.total_start = Some(Instant::now());
    }

    pub async fn profile_stage<F, R>(&mut self, name: &str, f: F) -> R
    where
        F: std::future::Future<Output = R>,
    {
        let start = Instant::now();
        let result = f.await;
        let duration = start.elapsed();

        self.stage_timings.insert(name.to_string(), duration);

        // Get target for this stage
        let target = match name {
            "template_selection" => self.targets.template_selection,
            "code_generation" => self.targets.code_generation,
            "cleanroom_setup" => self.targets.cleanroom_setup,
            "testing" => self.targets.testing,
            "validation" => self.targets.validation,
            "reporting" => self.targets.reporting,
            _ => Duration::from_secs(10), // Default 10s threshold
        };

        if duration > target {
            tracing::warn!(
                stage = %name,
                duration_ms = duration.as_millis(),
                target_ms = target.as_millis(),
                "⚠️  Stage exceeded target"
            );
        } else {
            tracing::info!(
                stage = %name,
                duration_ms = duration.as_millis(),
                target_ms = target.as_millis(),
                "✅ Stage met target"
            );
        }

        result
    }

    pub fn get_metrics(&self) -> Vec<StageMetrics> {
        let mut metrics = Vec::new();

        for (name, duration) in &self.stage_timings {
            let target = match name.as_str() {
                "template_selection" => self.targets.template_selection,
                "code_generation" => self.targets.code_generation,
                "cleanroom_setup" => self.targets.cleanroom_setup,
                "testing" => self.targets.testing,
                "validation" => self.targets.validation,
                "reporting" => self.targets.reporting,
                _ => Duration::from_secs(10),
            };

            metrics.push(StageMetrics::new(name, *duration, target));
        }

        metrics.sort_by(|a, b| b.duration.cmp(&a.duration));
        metrics
    }

    pub fn total_duration(&self) -> Option<Duration> {
        self.total_start.map(|start| start.elapsed())
    }

    pub fn report(&self) {
        log::info!("\n📊 Pipeline Performance Report");
        log::info!("═══════════════════════════════════════════════");

        let metrics = self.get_metrics();
        for metric in &metrics {
            let status = if metric.met_target { "" } else { "" };
            let improvement = metric.improvement_percent();
            let sign = if improvement >= 0.0 { "" } else { "" };

            log::info!(
                "{} {:<20} {:>6.2}s / {:>6.2}s ({}{:>5.1}%)",
                status,
                metric.name,
                metric.duration.as_secs_f64(),
                metric.target.as_secs_f64(),
                sign,
                improvement.abs()
            );
        }

        if let Some(total) = self.total_duration() {
            let total_met = total <= self.targets.total;
            let status = if total_met { "" } else { "" };

            log::info!("───────────────────────────────────────────────");
            log::info!(
                "{} {:<20} {:>6.2}s / {:>6.2}s",
                status,
                "TOTAL PIPELINE",
                total.as_secs_f64(),
                self.targets.total.as_secs_f64()
            );

            if total_met {
                log::info!("\n🎉 Performance target achieved!");
            } else {
                let exceeded = total
                    .checked_sub(self.targets.total)
                    .unwrap_or_default()
                    .as_secs_f64();
                log::warn!("\n⚠️  Performance target missed by {:.2}s", exceeded);
            }
        }

        log::info!("═══════════════════════════════════════════════\n");
    }
}

/// Parallel stage orchestrator for independent tasks
pub struct ParallelOrchestrator {
    #[allow(dead_code)]
    max_parallelism: usize,
}

/// A named stage for parallel execution: (name, future producing a `Result<R>`)
pub type ParallelStage<'a, R> = (
    &'a str,
    Box<dyn std::future::Future<Output = Result<R>> + Send + Unpin>,
);

impl ParallelOrchestrator {
    pub fn new(max_parallelism: usize) -> Self {
        Self { max_parallelism }
    }

    /// Run multiple independent stages in parallel
    pub async fn run_parallel<R>(&self, stages: Vec<ParallelStage<'_, R>>) -> Result<Vec<R>>
    where
        R: Send + 'static,
    {
        let mut set = JoinSet::new();

        for (name, stage) in stages {
            let name = name.to_string();
            set.spawn(async move {
                tracing::info!(stage = %name, "Starting parallel stage");
                let result = stage.await;
                tracing::info!(stage = %name, "Completed parallel stage");
                result
            });
        }

        let mut results = Vec::new();
        while let Some(result) = set.join_next().await {
            results.push(result.map_err(|e| {
                super::LifecycleError::Other(format!("Parallel stage failed: {}", e))
            })??);
        }

        Ok(results)
    }
}

/// Optimized pipeline runner with parallel execution
pub async fn run_optimized_pipeline(ctx: &Context, phases: &[String]) -> Result<()> {
    let mut profiler = PipelineProfiler::new(PerformanceTargets::stretch());
    profiler.start_pipeline();

    // Stage 1: Parallel preparation (independent tasks)
    tracing::info!("Stage 1: Parallel preparation");
    profiler
        .profile_stage("preparation", async {
            // Simplified parallel execution for now
            tokio::join!(
                async {
                    tracing::debug!("Fetching dependencies...");
                    tokio::time::sleep(Duration::from_millis(100)).await;
                },
                async {
                    tracing::debug!("Pre-warming containers...");
                    tokio::time::sleep(Duration::from_millis(200)).await;
                },
                async {
                    tracing::debug!("Validating configuration...");
                    tokio::time::sleep(Duration::from_millis(50)).await;
                }
            );
            Ok::<_, super::LifecycleError>(())
        })
        .await?;

    // Stage 2: Execute phases (optimized)
    tracing::info!("Stage 2: Phase execution");
    for phase in phases {
        profiler
            .profile_stage(phase, async {
                super::run_phase(ctx, phase)?;
                Ok::<_, super::LifecycleError>(())
            })
            .await?;
    }

    // Stage 3: Generate report
    tracing::info!("Stage 3: Reporting");
    profiler
        .profile_stage("reporting", async {
            // Generate performance report
            tokio::time::sleep(Duration::from_millis(100)).await;
            Ok::<_, super::LifecycleError>(())
        })
        .await?;

    // Print performance report
    profiler.report();

    Ok(())
}

/// Fast validation strategy using cargo check instead of full build
pub async fn run_fast_validation(ctx: &Context) -> Result<()> {
    tracing::info!("Running fast validation (cargo check)");

    let check_result = tokio::process::Command::new("cargo")
        .args(["check", "--all-targets", "--all-features"])
        .current_dir(&ctx.root)
        .output()
        .await
        .map_err(|e| super::LifecycleError::Other(format!("cargo check failed: {}", e)))?;

    if !check_result.status.success() {
        let stderr = String::from_utf8_lossy(&check_result.stderr);
        return Err(super::LifecycleError::Other(format!(
            "Validation failed: {}",
            stderr
        )));
    }

    tracing::info!("Fast validation passed");
    Ok(())
}

/// Container pool for pre-warmed containers
pub struct ContainerPool {
    pool_size: usize,
    // In real implementation, this would hold actual container instances
    available_count: std::sync::atomic::AtomicUsize,
}

impl ContainerPool {
    pub async fn new(pool_size: usize) -> Result<Self> {
        tracing::info!(pool_size = %pool_size, "Initializing container pool");

        // Pre-warm containers in parallel
        let mut tasks = Vec::new();
        for i in 0..pool_size {
            tasks.push(tokio::spawn(async move {
                tracing::debug!(container = i, "Pre-warming container");
                // Simulate warm-up latency in production only; skip in tests to avoid hanging --lib
                #[cfg(not(test))]
                tokio::time::sleep(Duration::from_millis(100)).await;
                Ok::<_, super::LifecycleError>(())
            }));
        }

        for task in tasks {
            task.await
                .map_err(|e| super::LifecycleError::Other(format!("Pool init failed: {}", e)))??;
        }

        tracing::info!("Container pool ready");

        Ok(Self {
            pool_size,
            available_count: std::sync::atomic::AtomicUsize::new(pool_size),
        })
    }

    pub fn available(&self) -> usize {
        self.available_count
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    pub fn total(&self) -> usize {
        self.pool_size
    }
}

/// Dependency cache for faster builds
pub struct DependencyCache {
    cache_dir: std::path::PathBuf,
}

impl DependencyCache {
    pub fn new(cache_dir: std::path::PathBuf) -> Self {
        Self { cache_dir }
    }

    pub async fn prefetch(&self) -> Result<()> {
        tracing::info!("Pre-fetching dependencies");

        let fetch_result = tokio::process::Command::new("cargo")
            .arg("fetch")
            .current_dir(self.cache_dir.parent().unwrap_or(&self.cache_dir))
            .output()
            .await
            .map_err(|e| super::LifecycleError::Other(format!("cargo fetch failed: {}", e)))?;

        if !fetch_result.status.success() {
            let stderr = String::from_utf8_lossy(&fetch_result.stderr);
            return Err(super::LifecycleError::Other(format!(
                "Dependency prefetch failed: {}",
                stderr
            )));
        }

        tracing::info!("Dependencies prefetched successfully");
        Ok(())
    }

    pub fn is_cached(&self, package: &str) -> bool {
        let package_path = self.cache_dir.join(package);
        package_path.exists()
    }
}

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

    #[test]
    fn test_performance_targets() {
        let targets = PerformanceTargets::default();
        assert_eq!(targets.total, Duration::from_secs(45));

        let required = PerformanceTargets::required();
        assert_eq!(required.total, Duration::from_mins(1));

        let stretch = PerformanceTargets::stretch();
        assert_eq!(stretch.total, Duration::from_secs(45));
    }

    #[test]
    fn test_stage_metrics() {
        let metric = StageMetrics::new("test", Duration::from_secs(5), Duration::from_secs(10));
        assert!(metric.met_target);
        assert!(metric.improvement_percent() > 0.0);

        let metric_exceeded =
            StageMetrics::new("test", Duration::from_secs(15), Duration::from_secs(10));
        assert!(!metric_exceeded.met_target);
        assert!(metric_exceeded.improvement_percent() < 0.0);
    }

    #[tokio::test]
    async fn test_pipeline_profiler() {
        let mut profiler = PipelineProfiler::new(PerformanceTargets::default());
        profiler.start_pipeline();

        profiler
            .profile_stage("test_stage", async {
                tokio::time::sleep(Duration::from_millis(100)).await;
            })
            .await;

        let metrics = profiler.get_metrics();
        assert_eq!(metrics.len(), 1);
        assert_eq!(metrics[0].name, "test_stage");
    }

    #[tokio::test]
    async fn test_parallel_orchestrator() {
        let _orchestrator = ParallelOrchestrator::new(4);

        // Simplified test with tokio::join!
        let (r1, r2, r3) = tokio::join!(
            async { Ok::<i32, super::super::LifecycleError>(1) },
            async { Ok::<i32, super::super::LifecycleError>(2) },
            async { Ok::<i32, super::super::LifecycleError>(3) },
        );

        assert!(r1.is_ok());
        assert!(r2.is_ok());
        assert!(r3.is_ok());
    }

    #[tokio::test]
    async fn test_container_pool() {
        let pool = ContainerPool::new(3).await.unwrap();
        assert_eq!(pool.total(), 3);
        assert_eq!(pool.available(), 3);
    }

    #[test]
    fn test_improvement_calculation() {
        let metric = StageMetrics::new("test", Duration::from_secs(3), Duration::from_secs(5));
        assert!((metric.improvement_percent() - 40.0).abs() < 0.01);

        let metric_over = StageMetrics::new("test", Duration::from_secs(7), Duration::from_secs(5));
        assert!((metric_over.improvement_percent() + 40.0).abs() < 0.01);
    }

    // === CRITICAL 80/20 TESTS: High-Impact Scenarios ===

    #[test]
    fn test_performance_targets_defaults() {
        let targets = PerformanceTargets::default();
        assert!(targets.template_selection <= Duration::from_secs(3));
        assert!(targets.code_generation <= Duration::from_secs(8));
        assert!(targets.cleanroom_setup <= Duration::from_secs(7));
        assert!(targets.testing <= Duration::from_secs(15));
        assert!(targets.validation <= Duration::from_secs(7));
        assert!(targets.reporting <= Duration::from_secs(3));
        assert_eq!(targets.total, Duration::from_secs(45)); // Stretch goal
    }

    #[test]
    fn test_stage_metrics_boundary_conditions() {
        // Exact match on target
        let metric = StageMetrics::new("exact", Duration::from_secs(10), Duration::from_secs(10));
        assert!(metric.met_target);
        assert_eq!(metric.improvement_percent(), 0.0);

        // Just under target
        let metric_under = StageMetrics::new(
            "under",
            Duration::from_millis(9999),
            Duration::from_secs(10),
        );
        assert!(metric_under.met_target);
        assert!(metric_under.improvement_percent() > 0.0);

        // Just over target
        let metric_over = StageMetrics::new(
            "over",
            Duration::from_millis(10001),
            Duration::from_secs(10),
        );
        assert!(!metric_over.met_target);
        assert!(metric_over.improvement_percent() < 0.0);
    }

    #[tokio::test]
    async fn test_profiler_multiple_stages() {
        let mut profiler = PipelineProfiler::new(PerformanceTargets::default());
        profiler.start_pipeline();

        // Profile multiple stages
        profiler
            .profile_stage("stage1", async {
                tokio::time::sleep(Duration::from_millis(50)).await
            })
            .await;
        profiler
            .profile_stage("stage2", async {
                tokio::time::sleep(Duration::from_millis(30)).await
            })
            .await;
        profiler
            .profile_stage("stage3", async {
                tokio::time::sleep(Duration::from_millis(20)).await
            })
            .await;

        let metrics = profiler.get_metrics();
        assert_eq!(metrics.len(), 3);

        // Metrics should be sorted by duration (longest first)
        assert!(metrics[0].duration >= metrics[1].duration);
        assert!(metrics[1].duration >= metrics[2].duration);
    }

    #[tokio::test]
    async fn test_profiler_total_duration() {
        let mut profiler = PipelineProfiler::new(PerformanceTargets::default());
        profiler.start_pipeline();

        tokio::time::sleep(Duration::from_millis(100)).await;

        let total = profiler.total_duration();
        assert!(total.is_some());
        assert!(total.unwrap() >= Duration::from_millis(100));
    }

    #[test]
    fn test_profiler_no_start() {
        let profiler = PipelineProfiler::new(PerformanceTargets::default());
        assert!(profiler.total_duration().is_none());
    }

    #[tokio::test]
    async fn test_parallel_orchestrator_empty() {
        let orchestrator = ParallelOrchestrator::new(4);
        let results: Result<Vec<i32>> = orchestrator.run_parallel(vec![]).await;
        assert!(results.is_ok());
        assert_eq!(results.unwrap().len(), 0);
    }

    #[tokio::test]
    async fn test_container_pool_size() {
        let pool = ContainerPool::new(5).await.unwrap();
        assert_eq!(pool.total(), 5);
        assert_eq!(pool.available(), 5);
    }

    #[tokio::test]
    async fn test_container_pool_zero_size() {
        let pool = ContainerPool::new(0).await.unwrap();
        assert_eq!(pool.total(), 0);
        assert_eq!(pool.available(), 0);
    }

    #[tokio::test]
    async fn test_dependency_cache_is_cached() {
        let temp_dir = std::env::temp_dir().join("ggen_test_cache");
        std::fs::create_dir_all(&temp_dir).ok();

        let cache = DependencyCache::new(temp_dir.clone());

        // Non-existent package should not be cached
        assert!(!cache.is_cached("nonexistent_package_12345"));

        std::fs::remove_dir_all(&temp_dir).ok();
    }

    #[test]
    fn test_stage_metrics_sorting() {
        let metric1 = StageMetrics::new("fast", Duration::from_secs(1), Duration::from_secs(5));
        let metric2 = StageMetrics::new("slow", Duration::from_secs(10), Duration::from_secs(5));
        let metric3 = StageMetrics::new("medium", Duration::from_secs(5), Duration::from_secs(5));

        let mut metrics = [metric1.clone(), metric2.clone(), metric3.clone()];
        metrics.sort_by(|a, b| b.duration.cmp(&a.duration));

        assert_eq!(metrics[0].name, "slow");
        assert_eq!(metrics[1].name, "medium");
        assert_eq!(metrics[2].name, "fast");
    }

    #[tokio::test]
    async fn test_profiler_stage_target_matching() {
        let mut profiler = PipelineProfiler::new(PerformanceTargets::default());

        profiler
            .profile_stage("template_selection", async {
                tokio::time::sleep(Duration::from_millis(100)).await
            })
            .await;

        let metrics = profiler.get_metrics();
        assert_eq!(metrics.len(), 1);
        assert_eq!(metrics[0].target, profiler.targets.template_selection);
    }

    #[test]
    fn test_performance_targets_required_vs_stretch() {
        let required = PerformanceTargets::required();
        let stretch = PerformanceTargets::stretch();

        assert_eq!(required.total, Duration::from_mins(1));
        assert_eq!(stretch.total, Duration::from_secs(45));
        assert!(required.total > stretch.total);
    }

    #[tokio::test]
    async fn test_profiler_concurrent_stages() {
        let mut profiler = PipelineProfiler::new(PerformanceTargets::default());
        profiler.start_pipeline();

        // Simulate concurrent stage execution
        tokio::join!(
            profiler.profile_stage("concurrent1", async {
                tokio::time::sleep(Duration::from_millis(50)).await
            }),
            async {
                tokio::time::sleep(Duration::from_millis(25)).await;
                // Note: We can't profile the same stage concurrently with the same profiler
                // This is testing that the profiler doesn't deadlock
            }
        );

        let metrics = profiler.get_metrics();
        assert!(!metrics.is_empty());
    }

    #[test]
    fn test_stage_metrics_percentage_precision() {
        // Test edge case: very small durations
        let metric = StageMetrics::new("micro", Duration::from_micros(1), Duration::from_micros(2));
        assert!(metric.met_target);
        let pct = metric.improvement_percent();
        assert!((pct - 50.0).abs() < 1.0);
    }

    #[tokio::test]
    async fn test_container_pool_concurrent_init() {
        // Test that multiple container inits don't interfere
        let (pool1, pool2, pool3) = tokio::join!(
            ContainerPool::new(2),
            ContainerPool::new(3),
            ContainerPool::new(1)
        );

        assert!(pool1.is_ok());
        assert!(pool2.is_ok());
        assert!(pool3.is_ok());

        assert_eq!(pool1.unwrap().total(), 2);
        assert_eq!(pool2.unwrap().total(), 3);
        assert_eq!(pool3.unwrap().total(), 1);
    }

    #[test]
    fn test_parallel_orchestrator_max_parallelism() {
        let orch = ParallelOrchestrator::new(10);
        // Just verify construction doesn't panic
        assert_eq!(orch.max_parallelism, 10);
    }

    #[tokio::test]
    async fn test_profiler_report_output() {
        // Test that report generation doesn't panic
        let mut profiler = PipelineProfiler::new(PerformanceTargets::default());
        profiler.start_pipeline();

        profiler
            .profile_stage("test", async {
                tokio::time::sleep(Duration::from_millis(10)).await;
            })
            .await;

        // This should not panic
        profiler.report();
    }

    #[test]
    fn test_stage_metrics_zero_duration() {
        let metric = StageMetrics::new("instant", Duration::from_secs(0), Duration::from_secs(5));
        assert!(metric.met_target);
        assert_eq!(metric.improvement_percent(), 100.0);
    }
}