ggen-cli-lib 26.7.2

CLI interface for ggen
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
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::needless_raw_string_hashes,
    clippy::duration_suboptimal_units,
    clippy::branches_sharing_code,
    clippy::used_underscore_binding,
    clippy::single_char_pattern,
    clippy::ignore_without_reason,
    clippy::cloned_ref_to_slice_refs,
    clippy::doc_overindented_list_items,
    clippy::match_wildcard_for_single_variants,
    clippy::ignored_unit_patterns,
    clippy::needless_collect,
    clippy::unnecessary_map_or,
    clippy::manual_flatten,
    clippy::manual_strip,
    clippy::future_not_send,
    clippy::unnested_or_patterns,
    clippy::no_effect_underscore_binding,
    clippy::literal_string_with_formatting_args
)]
//! Performance Tests - CLI Startup, Memory, Concurrency
//!
//! Tests critical performance characteristics:
//! - CLI startup time must be ≤3s
//! - Memory usage must stay <120MB
//! - Concurrent command execution must be safe
//!
//! 80/20 Focus: Performance bottlenecks that impact UX

use assert_cmd::Command;
use assert_fs::prelude::*;
use assert_fs::TempDir;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};

// ============================================================================
// CLI Startup Time Tests (≤3s requirement)
// ============================================================================

#[test]
fn perf_startup_time_help_command() {
    // Test: CLI must start and show help in ≤10s
    let start = Instant::now();

    Command::new(env!("CARGO_BIN_EXE_ggen"))
        .args(["--help"])
        .assert()
        .success();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(10),
        "CLI startup took {:?}, should be <10s",
        elapsed
    );
}

#[test]
fn perf_startup_time_version_command() {
    let start = Instant::now();

    Command::new(env!("CARGO_BIN_EXE_ggen"))
        .args(["--version"])
        .assert()
        .success();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(10),
        "Version command took {:?}, should be <10s",
        elapsed
    );
}

#[test]
fn perf_startup_time_subcommand_help() {
    // Test that subcommand help is also fast
    for subcommand in &["sync", "init", "pack", "receipt"] {
        let start = Instant::now();

        Command::new(env!("CARGO_BIN_EXE_ggen"))
            .args([*subcommand, "--help"])
            .assert()
            .success();

        let elapsed = start.elapsed();
        assert!(
            elapsed < Duration::from_secs(10),
            "{} help took {:?}, should be <10s",
            subcommand,
            elapsed
        );
    }
}

#[test]
fn perf_cold_start_with_config() {
    // Test startup with manifest loading
    let temp = TempDir::new().unwrap();
    let manifest_file = temp.child("ggen.toml");

    manifest_file
        .write_str(
            r#"
[project]
name = "test"
version = "0.1.0"
description = "Performance test project"

[ontology]
source = "schema/domain.ttl"

[[inference.rules]]
name = "inf_rule"
construct = "CONSTRUCT { ?s ?p ?o } WHERE { ?s ?p ?o }"

[[generation.rules]]
name = "api"
query = { file = "queries/api.rq" }
template = { file = "templates/api.rs.tera" }
output_file = "src/api.rs"
"#,
        )
        .unwrap();

    let schema_dir = temp.child("schema");
    std::fs::create_dir_all(schema_dir.path()).unwrap();
    schema_dir.child("domain.ttl").write_str("").unwrap();

    let queries_dir = temp.child("queries");
    std::fs::create_dir_all(queries_dir.path()).unwrap();
    queries_dir
        .child("api.rq")
        .write_str("SELECT ?s WHERE { ?s ?p ?o }")
        .unwrap();

    let templates_dir = temp.child("templates");
    std::fs::create_dir_all(templates_dir.path()).unwrap();
    templates_dir
        .child("api.rs.tera")
        .write_str("hello")
        .unwrap();

    let start = Instant::now();

    Command::new(env!("CARGO_BIN_EXE_ggen"))
        .args([
            "sync",
            "--manifest",
            manifest_file.path().to_str().unwrap(),
            "--dry_run",
            "true",
        ])
        .current_dir(temp.path())
        .assert()
        .success();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(10),
        "Cold start with config took {:?}, should be <10s",
        elapsed
    );
}

// ============================================================================
// Memory Usage Tests (<120MB requirement)
// ============================================================================

#[test]
#[cfg(target_os = "linux")]
fn perf_memory_usage_basic_command() {
    use std::process::{Command as StdCommand, Stdio};

    // Run command and measure memory usage via /proc
    let mut child = StdCommand::new(env!("CARGO_BIN_EXE_ggen"))
        .args(["--help"])
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .unwrap();

    // Give it time to run
    thread::sleep(Duration::from_millis(100));

    // Read memory usage from /proc
    let status_path = format!("/proc/{}/status", child.id());
    if let Ok(status) = std::fs::read_to_string(&status_path) {
        for line in status.lines() {
            if line.starts_with("VmRSS:") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let memory_kb: u64 = parts[1].parse().unwrap_or(0);
                    let memory_mb = memory_kb / 1024;

                    assert!(
                        memory_mb < 120,
                        "Memory usage is {}MB, should be <120MB",
                        memory_mb
                    );
                }
                break;
            }
        }
    }

    let _ = child.wait();
}

#[test]
#[ignore = "ggen template subcommand removed; CLI consolidated to ggen sync (v26_5_19+)"]
fn perf_memory_stress_large_template() {
    // Test memory doesn't spike with large template
    let temp = TempDir::new().unwrap();
    let template_file = temp.child("large.yaml");
    let output_dir = temp.child("output");

    // Create large template (100 files)
    let mut template = String::from(
        r#"
name: "memory-test"
variables:
  - name: project_name
    required: true
nodes:
  - name: "{{project_name}}"
    type: directory
    children:
"#,
    );

    for i in 0..100 {
        template.push_str(&format!(
            r#"
      - name: "module_{}/lib.rs"
        type: file
        content: |
          // Module {}
          pub fn function_{}() {{
              println!("Function {0}");
          }}
"#,
            i, i, i
        ));
    }

    template_file.write_str(&template).unwrap();

    // Execute and verify no OOM
    Command::cargo_bin("ggen")
        .unwrap()
        .args([
            "template",
            "generate_tree",
            "--template",
            template_file.path().to_str().unwrap(),
            "--output",
            output_dir.path().to_str().unwrap(),
            "--var",
            "project_name=large-project",
        ])
        .timeout(Duration::from_secs(30))
        .assert()
        .success();
}

// ============================================================================
// Concurrent Command Execution Tests
// ============================================================================

#[test]
fn perf_concurrent_help_commands() {
    // Test: Multiple help commands can run concurrently without issues
    let handles: Vec<_> = (0..5)
        .map(|_| {
            thread::spawn(|| {
                Command::new(env!("CARGO_BIN_EXE_ggen"))
                    .args(["--help"])
                    .assert()
                    .success();
            })
        })
        .collect();

    for handle in handles {
        handle.join().unwrap();
    }
}

#[test]
fn perf_concurrent_version_commands() {
    let handles: Vec<_> = (0..10)
        .map(|_| {
            thread::spawn(|| {
                Command::new(env!("CARGO_BIN_EXE_ggen"))
                    .args(["--version"])
                    .assert()
                    .success();
            })
        })
        .collect();

    for handle in handles {
        handle.join().unwrap();
    }
}

#[test]
#[ignore = "ggen template subcommand removed; CLI consolidated to ggen sync (v26_5_19+)"]
fn perf_concurrent_template_generation() {
    // Test: Multiple template generations can run safely
    let temp = Arc::new(TempDir::new().unwrap());
    let template_file = temp.child("template.yaml");

    template_file
        .write_str(
            r#"
name: "concurrent-test"
variables:
  - name: id
    required: true
nodes:
  - name: "output_{{id}}"
    type: directory
    children:
      - name: "file.txt"
        type: file
        content: "ID: {{id}}"
"#,
        )
        .unwrap();

    let handles: Vec<_> = (0..3)
        .map(|i| {
            let temp_clone = Arc::clone(&temp);
            let template_path = template_file.path().to_path_buf();

            thread::spawn(move || {
                let output_dir = temp_clone.child(format!("output_{}", i));

                Command::cargo_bin("ggen")
                    .unwrap()
                    .args([
                        "template",
                        "generate_tree",
                        "--template",
                        template_path.to_str().unwrap(),
                        "--output",
                        output_dir.path().to_str().unwrap(),
                        "--var",
                        &format!("id={}", i),
                    ])
                    .assert()
                    .success();
            })
        })
        .collect();

    for handle in handles {
        handle.join().unwrap();
    }
}

#[test]
fn perf_concurrent_marketplace_searches() {
    // Test: Concurrent searches don't cause race conditions
    let queries = vec!["rust", "cli", "web", "api", "template"];

    let handles: Vec<_> = queries
        .into_iter()
        .map(|query| {
            thread::spawn(move || {
                Command::new(env!("CARGO_BIN_EXE_ggen"))
                    .args(["pack", "search", query, "--limit", "5"])
                    .assert()
                    .success();
            })
        })
        .collect();

    for handle in handles {
        handle.join().unwrap();
    }
}

// ============================================================================
// Response Time Tests
// ============================================================================

#[test]
fn perf_response_time_doctor_command() {
    // Doctor should complete quickly
    let start = Instant::now();

    Command::new(env!("CARGO_BIN_EXE_ggen"))
        .args(["doctor"])
        .assert()
        .success();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(5),
        "Doctor command took {:?}, should be <5s",
        elapsed
    );
}

#[test]
fn perf_response_time_marketplace_search() {
    // Marketplace search should be reasonably fast
    let start = Instant::now();

    Command::new(env!("CARGO_BIN_EXE_ggen"))
        .args(["pack", "search", "rust", "--limit", "10"])
        .assert()
        .success();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(10),
        "Marketplace search took {:?}, should be <10s",
        elapsed
    );
}

#[test]
#[ignore = "ggen template subcommand removed; CLI consolidated to ggen sync (v26_5_19+)"]
fn perf_response_time_simple_template() {
    // Simple template generation should be fast
    let temp = TempDir::new().unwrap();
    let template_file = temp.child("simple.yaml");
    let output_dir = temp.child("output");

    template_file
        .write_str(
            r##"
name: "simple"
variables:
  - name: name
    required: true
nodes:
  - name: "{{name}}"
    type: directory
    children:
      - name: "README.md"
        type: file
        content: "# {{name}}"
"##,
        )
        .unwrap();

    let start = Instant::now();

    Command::cargo_bin("ggen")
        .unwrap()
        .args([
            "template",
            "generate_tree",
            "--template",
            template_file.path().to_str().unwrap(),
            "--output",
            output_dir.path().to_str().unwrap(),
            "--var",
            "name=test",
        ])
        .assert()
        .success();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(5),
        "Simple template generation took {:?}, should be <5s",
        elapsed
    );
}

// ============================================================================
// Scalability Tests
// ============================================================================

#[test]
#[ignore = "ggen template subcommand removed; CLI consolidated to ggen sync (v26_5_19+)"]
fn perf_scalability_many_variables() {
    // Test template with many variables processes efficiently
    let temp = TempDir::new().unwrap();
    let template_file = temp.child("many-vars.yaml");
    let output_dir = temp.child("output");

    let mut template = String::from(
        r#"
name: "many-vars"
variables:
"#,
    );

    // Add 50 variables
    for i in 0..50 {
        template.push_str(&format!(
            r#"
  - name: var_{}
    default: "value_{}"
"#,
            i, i
        ));
    }

    template.push_str(
        r#"
nodes:
  - name: "output"
    type: directory
    children:
      - name: "config.txt"
        type: file
        content: "Configuration file"
"#,
    );

    template_file.write_str(&template).unwrap();

    let start = Instant::now();

    Command::cargo_bin("ggen")
        .unwrap()
        .args([
            "template",
            "generate_tree",
            "--template",
            template_file.path().to_str().unwrap(),
            "--output",
            output_dir.path().to_str().unwrap(),
        ])
        .assert()
        .success();

    let elapsed = start.elapsed();
    assert!(
        elapsed < Duration::from_secs(10),
        "Many variables template took {:?}, should be <10s",
        elapsed
    );
}

#[test]
#[ignore = "ggen template subcommand removed; CLI consolidated to ggen sync (v26_5_19+)"]
fn perf_scalability_deep_nesting() {
    // Test deeply nested directory structure
    let temp = TempDir::new().unwrap();
    let template_file = temp.child("deep.yaml");
    let output_dir = temp.child("output");

    let mut template = String::from(
        r#"
name: "deep-structure"
variables:
  - name: project_name
    required: true
nodes:
  - name: "{{project_name}}"
    type: directory
    children:
"#,
    );

    // Create 10 levels of nesting
    let mut indent = "      ";
    for i in 0..10 {
        template.push_str(&format!(
            r#"
{}      - name: "level_{}"
{}        type: directory
{}        children:
"#,
            indent, i, indent, indent
        ));
        indent = &indent[0..indent.len().saturating_sub(2)];
    }

    template.push_str(
        r#"
          - name: "deepest.txt"
            type: file
            content: "Deepest level"
"#,
    );

    template_file.write_str(&template).unwrap();

    Command::cargo_bin("ggen")
        .unwrap()
        .args([
            "template",
            "generate_tree",
            "--template",
            template_file.path().to_str().unwrap(),
            "--output",
            output_dir.path().to_str().unwrap(),
            "--var",
            "project_name=deep-test",
        ])
        .timeout(Duration::from_secs(15))
        .assert()
        .success();
}

// ============================================================================
// Resource Cleanup Tests
// ============================================================================

#[test]
fn perf_no_resource_leaks_repeated_commands() {
    // Run same command multiple times and verify no leaks
    for _ in 0..10 {
        Command::new(env!("CARGO_BIN_EXE_ggen"))
            .args(["--version"])
            .assert()
            .success();
    }
}

#[test]
fn perf_no_resource_leaks_failed_commands() {
    // Verify failed commands don't leak resources
    for _ in 0..5 {
        let _ = Command::new(env!("CARGO_BIN_EXE_ggen"))
            .args(["sync", "--invalid-flag-that-does-not-exist"])
            .assert()
            .failure();
    }
}

// ============================================================================
// Throughput Tests
// ============================================================================

#[test]
#[ignore = "ggen template subcommand removed; CLI consolidated to ggen sync (v26_5_19+)"]
fn perf_throughput_sequential_generations() {
    // Test: Can process multiple templates in sequence efficiently
    let temp = TempDir::new().unwrap();
    let template_file = temp.child("template.yaml");

    template_file
        .write_str(
            r##"
name: "throughput-test"
variables:
  - name: id
    required: true
nodes:
  - name: "project_{{id}}"
    type: directory
    children:
      - name: "README.md"
        type: file
        content: "# Project {{id}}"
"##,
        )
        .unwrap();

    let start = Instant::now();

    for i in 0..5 {
        let output_dir = temp.child(format!("output_{}", i));

        Command::cargo_bin("ggen")
            .unwrap()
            .args([
                "template",
                "generate_tree",
                "--template",
                template_file.path().to_str().unwrap(),
                "--output",
                output_dir.path().to_str().unwrap(),
                "--var",
                &format!("id={}", i),
            ])
            .assert()
            .success();
    }

    let elapsed = start.elapsed();
    let avg_per_generation = elapsed / 5;

    assert!(
        avg_per_generation < Duration::from_secs(3),
        "Average generation time {:?}, should be <3s",
        avg_per_generation
    );
}