ftui-harness 0.5.0

Test harness and reference fixtures for FrankenTUI.
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
#![forbid(unsafe_code)]

//! Large Buffer Regression Tests for Advanced Text Editor.
//!
//! Performance tests for the text editor operating on large buffers.
//! Verifies that operations complete within defined time budgets and
//! that behavior remains correct at scale.
//!
//! # Performance Budgets
//!
//! | Operation | 10K lines | 100K lines | 1M lines |
//! |-----------|-----------|------------|----------|
//! | Insert char | < 1ms | < 5ms | < 50ms |
//! | Delete char | < 1ms | < 5ms | < 50ms |
//! | Move cursor | < 1ms | < 2ms | < 10ms |
//! | Select all | < 1ms | < 5ms | < 20ms |
//! | Full render | < 10ms | < 50ms | N/A |
//!
//! # Invariants (Alien Artifact)
//!
//! 1. **Line count consistency**: rope.len_lines() always matches expected
//! 2. **Cursor validity**: cursor always within valid bounds after any operation
//! 3. **Undo reversibility**: undo always restores previous state exactly
//! 4. **Memory bound**: memory usage grows linearly with content size
//!
//! # Failure Modes
//!
//! | Scenario | Detection | Mitigation |
//! |----------|-----------|------------|
//! | O(n²) insertion | Timing regression | Rope rebalancing |
//! | Cursor calculation overflow | Property test failure | Use saturating math |
//! | Memory exhaustion | OOM on large buffers | Streaming/lazy loading |
//! | Stack overflow on deep undo | Panic | Iterative undo |
//!
//! # Running Performance Tests
//!
//! ```sh
//! # Run all performance tests
//! cargo test --package ftui-harness --test editor_perf -- --nocapture
//!
//! # Run with detailed timing
//! PERF_LOG=1 cargo test --package ftui-harness --test editor_perf -- --nocapture
//!
//! # Run specific size category
//! cargo test --package ftui-harness --test editor_perf large_buffer_10k
//! ```
//!
//! # JSONL Output Schema
//!
//! ```json
//! {"event":"perf_test","case":"insert_char_10k","lines":10000,"op":"insert","duration_us":523,"result":"pass"}
//! {"event":"perf_test","case":"cursor_move_100k","lines":100000,"op":"move_right","duration_us":1234,"result":"pass"}
//! ```

use std::time::{Duration, Instant};

use ftui_text::editor::Editor;

// ============================================================================
// Constants
// ============================================================================

/// Number of lines for 10K buffer tests.
const LINES_10K: usize = 10_000;

/// Number of lines for 100K buffer tests.
const LINES_100K: usize = 100_000;

/// Line content for test buffers (average line length ~40 chars).
const LINE_CONTENT: &str = "This is a test line with typical content";

const BUDGET_MULTIPLIER_DEFAULT: u128 = 1;
const BUDGET_MULTIPLIER_COVERAGE: u128 = 2;
const BUDGET_MULTIPLIER_SHARED_WORKER: u128 = 10;
const BUDGET_MULTIPLIER_ENV: &str = "FTUI_EDITOR_PERF_BUDGET_MULTIPLIER";
const SHARED_WORKER_ENV: &str = "FTUI_EDITOR_PERF_SHARED_WORKER";
const SHARED_WORKER_MARKERS: &[&str] = &[
    "CI",
    "RCH_JOB_ID",
    "RCH_REMOTE",
    "RCH_REQUIRE_REMOTE",
    "RCH_WORKER",
    "RCH_WORKER_ID",
];

// ============================================================================
// Test Helpers
// ============================================================================

/// Create a buffer with the specified number of lines.
fn create_large_buffer(lines: usize) -> Editor {
    let content: String = (0..lines)
        .map(|i| format!("{LINE_CONTENT} {i}\n"))
        .collect();
    Editor::with_text(&content)
}

/// Log a performance measurement in JSONL format.
fn log_perf(case: &str, lines: usize, op: &str, duration_us: u128, result: &str) {
    if std::env::var("PERF_LOG").is_ok() {
        println!(
            r#"{{"event":"perf_test","case":"{}","lines":{},"op":"{}","duration_us":{},"result":"{}"}}"#,
            case, lines, op, duration_us, result
        );
    }
}

fn is_coverage_run() -> bool {
    std::env::var("LLVM_PROFILE_FILE").is_ok()
        || std::env::var("CARGO_LLVM_COV").is_ok()
        || std::env::var("LLVM_COV").is_ok()
        || std::env::var("RUSTFLAGS").is_ok_and(|flags| flags.contains("instrument-coverage"))
}

fn parse_env_flag_value(value: &str) -> Option<bool> {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" => Some(false),
        _ => None,
    }
}

fn env_flag(name: &str) -> Option<bool> {
    std::env::var(name)
        .ok()
        .and_then(|value| parse_env_flag_value(&value))
}

fn env_present_and_not_false(name: &str) -> bool {
    match std::env::var(name) {
        Ok(value) => parse_env_flag_value(&value).unwrap_or_else(|| !value.trim().is_empty()),
        Err(_) => false,
    }
}

fn is_shared_worker_run() -> bool {
    if let Some(enabled) = env_flag(SHARED_WORKER_ENV) {
        return enabled;
    }
    is_rch_target_dir()
        || SHARED_WORKER_MARKERS
            .iter()
            .any(|name| env_present_and_not_false(name))
}

fn is_rch_target_dir() -> bool {
    std::env::var_os("CARGO_TARGET_DIR")
        .is_some_and(|path| is_rch_target_path(std::path::Path::new(&path)))
        || std::env::current_exe().is_ok_and(|path| is_rch_target_path(path.as_path()))
}

fn is_rch_target_path(path: &std::path::Path) -> bool {
    path.to_string_lossy().contains(".rch-target-")
}

fn budget_multiplier_for(
    coverage: bool,
    shared_worker: bool,
    override_value: Option<&str>,
) -> (u128, &'static str) {
    if let Some(value) = override_value
        .and_then(|value| value.trim().parse::<u128>().ok())
        .filter(|value| *value > 0)
    {
        return (value, "env");
    }

    if coverage {
        (BUDGET_MULTIPLIER_COVERAGE, "coverage")
    } else if shared_worker {
        (BUDGET_MULTIPLIER_SHARED_WORKER, "shared_worker")
    } else {
        (BUDGET_MULTIPLIER_DEFAULT, "default")
    }
}

fn budget_multiplier_with_mode() -> (u128, &'static str) {
    let override_value = std::env::var(BUDGET_MULTIPLIER_ENV).ok();
    budget_multiplier_for(
        is_coverage_run(),
        is_shared_worker_run(),
        override_value.as_deref(),
    )
}

fn timing_budget_us(base: u128) -> (u128, &'static str, u128) {
    let (multiplier, mode) = budget_multiplier_with_mode();
    (base.saturating_mul(multiplier), mode, multiplier)
}

#[test]
fn budget_multiplier_defaults_to_local_guardrail() {
    assert_eq!(
        budget_multiplier_for(false, false, None),
        (BUDGET_MULTIPLIER_DEFAULT, "default")
    );
}

#[test]
fn budget_multiplier_uses_coverage_guardrail() {
    assert_eq!(
        budget_multiplier_for(true, true, None),
        (BUDGET_MULTIPLIER_COVERAGE, "coverage")
    );
}

#[test]
fn budget_multiplier_uses_shared_worker_guardrail() {
    assert_eq!(
        budget_multiplier_for(false, true, None),
        (BUDGET_MULTIPLIER_SHARED_WORKER, "shared_worker")
    );
}

#[test]
fn budget_multiplier_explicit_override_wins() {
    assert_eq!(budget_multiplier_for(true, true, Some("3")), (3, "env"));
}

#[test]
fn editor_perf_env_flag_parser_accepts_common_forms() {
    assert_eq!(parse_env_flag_value(" yes "), Some(true));
    assert_eq!(parse_env_flag_value("OFF"), Some(false));
    assert_eq!(parse_env_flag_value("worker"), None);
}

#[test]
fn editor_perf_rch_target_path_recognizes_worker_targets() {
    assert!(is_rch_target_path(std::path::Path::new(
        "/data/projects/frankentui/.rch-target-vmi1152480-job-123/debug/deps/test"
    )));
    assert!(!is_rch_target_path(std::path::Path::new(
        "/data/projects/frankentui/target/debug/deps/test"
    )));
}

/// Assert operation completes within time budget.
fn assert_within_budget(duration: Duration, budget_us: u128, case: &str, lines: usize, op: &str) {
    let duration_us = duration.as_micros();
    let (budget_us, budget_mode, budget_multiplier) = timing_budget_us(budget_us);
    let result = if duration_us <= budget_us {
        "pass"
    } else {
        "fail"
    };
    log_perf(case, lines, op, duration_us, result);

    assert!(
        duration_us <= budget_us,
        "{} on {}K lines took {}us, budget was {}us (mode={}, multiplier={}x)",
        op,
        lines / 1000,
        duration_us,
        budget_us,
        budget_mode,
        budget_multiplier
    );
}

// ============================================================================
// 10K Line Tests
// ============================================================================

#[test]
fn large_buffer_10k_insert_char() {
    let mut editor = create_large_buffer(LINES_10K);

    let start = Instant::now();
    editor.insert_char('X');
    let duration = start.elapsed();

    assert_within_budget(duration, 1000, "insert_char_10k", LINES_10K, "insert_char");
}

#[test]
fn large_buffer_10k_delete_char() {
    let mut editor = create_large_buffer(LINES_10K);

    let start = Instant::now();
    editor.delete_backward();
    let duration = start.elapsed();

    assert_within_budget(
        duration,
        1000,
        "delete_char_10k",
        LINES_10K,
        "delete_backward",
    );
}

#[test]
fn large_buffer_10k_move_cursor() {
    let mut editor = create_large_buffer(LINES_10K);

    let start = Instant::now();
    editor.move_left();
    let duration = start.elapsed();

    assert_within_budget(duration, 1000, "move_cursor_10k", LINES_10K, "move_left");
}

#[test]
fn large_buffer_10k_select_all() {
    let mut editor = create_large_buffer(LINES_10K);

    let start = Instant::now();
    editor.select_all();
    let duration = start.elapsed();

    assert_within_budget(duration, 1000, "select_all_10k", LINES_10K, "select_all");
}

#[test]
fn large_buffer_10k_move_to_start() {
    let mut editor = create_large_buffer(LINES_10K);

    let start = Instant::now();
    editor.move_to_document_start();
    let duration = start.elapsed();

    assert_within_budget(duration, 1000, "move_start_10k", LINES_10K, "move_to_start");
}

#[test]
fn large_buffer_10k_move_up_down() {
    let mut editor = create_large_buffer(LINES_10K);
    // Start from middle
    editor.move_to_document_start();
    for _ in 0..5000 {
        editor.move_down();
    }

    let start = Instant::now();
    editor.move_up();
    let duration_up = start.elapsed();

    let start = Instant::now();
    editor.move_down();
    let duration_down = start.elapsed();

    assert_within_budget(duration_up, 1000, "move_up_10k", LINES_10K, "move_up");
    assert_within_budget(duration_down, 1000, "move_down_10k", LINES_10K, "move_down");
}

#[test]
fn large_buffer_10k_undo_redo() {
    let mut editor = create_large_buffer(LINES_10K);
    editor.insert_char('X');

    let start = Instant::now();
    editor.undo();
    let duration_undo = start.elapsed();

    let start = Instant::now();
    editor.redo();
    let duration_redo = start.elapsed();

    assert_within_budget(duration_undo, 1000, "undo_10k", LINES_10K, "undo");
    assert_within_budget(duration_redo, 1000, "redo_10k", LINES_10K, "redo");
}

// ============================================================================
// 100K Line Tests
// ============================================================================

#[test]
fn large_buffer_100k_insert_char() {
    let mut editor = create_large_buffer(LINES_100K);

    let start = Instant::now();
    editor.insert_char('X');
    let duration = start.elapsed();

    assert_within_budget(
        duration,
        5000,
        "insert_char_100k",
        LINES_100K,
        "insert_char",
    );
}

#[test]
fn large_buffer_100k_delete_char() {
    let mut editor = create_large_buffer(LINES_100K);

    let start = Instant::now();
    editor.delete_backward();
    let duration = start.elapsed();

    assert_within_budget(
        duration,
        5000,
        "delete_char_100k",
        LINES_100K,
        "delete_backward",
    );
}

#[test]
fn large_buffer_100k_move_cursor() {
    let mut editor = create_large_buffer(LINES_100K);

    let start = Instant::now();
    editor.move_left();
    let duration = start.elapsed();

    assert_within_budget(duration, 2000, "move_cursor_100k", LINES_100K, "move_left");
}

#[test]
fn large_buffer_100k_select_all() {
    let mut editor = create_large_buffer(LINES_100K);

    let start = Instant::now();
    editor.select_all();
    let duration = start.elapsed();

    assert_within_budget(duration, 5000, "select_all_100k", LINES_100K, "select_all");
}

#[test]
fn large_buffer_100k_move_to_start() {
    let mut editor = create_large_buffer(LINES_100K);

    let start = Instant::now();
    editor.move_to_document_start();
    let duration = start.elapsed();

    assert_within_budget(
        duration,
        2000,
        "move_start_100k",
        LINES_100K,
        "move_to_start",
    );
}

// ============================================================================
// Invariant Tests
// ============================================================================

/// Test that line count remains consistent after operations.
#[test]
fn invariant_line_count_consistency() {
    let mut editor = create_large_buffer(LINES_10K);
    let initial_lines = editor.line_count();

    // Insert char (should not change line count)
    editor.insert_char('X');
    assert_eq!(
        editor.line_count(),
        initial_lines,
        "insert_char changed line count"
    );

    // Delete char (should not change line count)
    editor.delete_backward();
    assert_eq!(
        editor.line_count(),
        initial_lines,
        "delete_backward changed line count"
    );

    // Insert newline (should increase by 1)
    editor.insert_newline();
    assert_eq!(
        editor.line_count(),
        initial_lines + 1,
        "insert_newline didn't increase"
    );

    // Undo (should restore)
    editor.undo();
    assert_eq!(
        editor.line_count(),
        initial_lines,
        "undo didn't restore line count"
    );
}

/// Test that cursor is always valid after operations.
#[test]
fn invariant_cursor_always_valid() {
    let mut editor = create_large_buffer(1000);

    // Move to extremes
    editor.move_to_document_start();
    let start_cursor = editor.cursor();
    assert_eq!(start_cursor.line, 0);
    assert_eq!(start_cursor.grapheme, 0);

    editor.move_to_document_end();
    let end_cursor = editor.cursor();
    assert!(end_cursor.line < editor.line_count() || editor.is_empty());

    // Move past bounds should clamp
    for _ in 0..100 {
        editor.move_right();
    }
    let cursor = editor.cursor();
    let text = editor.text();
    assert!(cursor.line <= text.lines().count());
}

/// Test that undo fully reverses operations.
#[test]
fn invariant_undo_reversibility() {
    let mut editor = create_large_buffer(1000);
    let original_text = editor.text();
    let _original_cursor = editor.cursor();

    // Perform operations
    editor.insert_text("INSERTED");
    editor.delete_backward();
    editor.insert_newline();

    assert_ne!(editor.text(), original_text);

    // Undo all
    editor.undo();
    editor.undo();
    editor.undo();

    assert_eq!(editor.text(), original_text, "undo didn't restore text");
    // Cursor may be at different position after undo
}

/// Test multiple insert/delete cycles maintain consistency.
#[test]
fn invariant_insert_delete_cycle() {
    let mut editor = create_large_buffer(1000);
    let original_len = editor.text().len();

    // Insert 100 characters
    for _ in 0..100 {
        editor.insert_char('X');
    }
    assert_eq!(editor.text().len(), original_len + 100);

    // Delete them all
    for _ in 0..100 {
        editor.delete_backward();
    }
    assert_eq!(editor.text().len(), original_len);
}

// ============================================================================
// Stress Tests
// ============================================================================

/// Stress test: many small insertions.
#[test]
fn stress_many_insertions() {
    let mut editor = Editor::new();

    let start = Instant::now();
    for i in 0..1000 {
        editor.insert_text(&format!("Line {i}\n"));
    }
    let duration = start.elapsed();

    assert_eq!(editor.line_count(), 1001); // 1000 lines + empty at end
    log_perf(
        "stress_insertions",
        1000,
        "1000_inserts",
        duration.as_micros(),
        "pass",
    );

    // Should complete in reasonable time
    assert!(
        duration < Duration::from_secs(1),
        "1000 insertions took {:?}",
        duration
    );
}

/// Stress test: rapid cursor movements.
#[test]
fn stress_cursor_movements() {
    let mut editor = create_large_buffer(10_000);

    let start = Instant::now();
    for _ in 0..1000 {
        editor.move_left();
        editor.move_right();
        editor.move_up();
        editor.move_down();
    }
    let duration = start.elapsed();

    log_perf(
        "stress_movements",
        10_000,
        "4000_moves",
        duration.as_micros(),
        "pass",
    );

    assert!(
        duration < Duration::from_secs(2),
        "4000 cursor movements took {:?}",
        duration
    );
}

/// Stress test: undo/redo cycles.
#[test]
fn stress_undo_redo() {
    let mut editor = Editor::new();

    // Create undo history
    for i in 0..100 {
        editor.insert_text(&format!("Edit {i} "));
    }

    let start = Instant::now();
    // Undo all
    for _ in 0..100 {
        editor.undo();
    }
    // Redo all
    for _ in 0..100 {
        editor.redo();
    }
    let duration = start.elapsed();

    log_perf(
        "stress_undo_redo",
        100,
        "200_undo_redo",
        duration.as_micros(),
        "pass",
    );

    assert!(
        duration < Duration::from_secs(1),
        "200 undo/redo took {:?}",
        duration
    );
}

// ============================================================================
// Property Tests
// ============================================================================

/// Property: text length is always sum of line lengths + newlines.
#[test]
fn property_text_length_equals_lines() {
    let editor = create_large_buffer(1000);
    let text = editor.text();

    // Count lines and their lengths
    let lines: Vec<&str> = text.lines().collect();
    let line_chars: usize = lines.iter().map(|l| l.len()).sum();
    let newlines = text.matches('\n').count();

    // Total should equal text length
    assert_eq!(line_chars + newlines, text.len());
}

/// Property: line count matches actual newlines + 1.
#[test]
fn property_line_count_matches_newlines() {
    let editor = create_large_buffer(500);
    let text = editor.text();
    let newlines = text.matches('\n').count();

    // Line count should be newlines + 1 (or newlines if ends with \n)
    let expected = if text.ends_with('\n') {
        newlines
    } else {
        newlines + 1
    };

    // Allow for edge cases in rope counting
    let line_count = editor.line_count();
    assert!(
        line_count == expected || line_count == expected + 1,
        "line_count {} didn't match expected {} (newlines={})",
        line_count,
        expected,
        newlines
    );
}

/// Property: cursor position is always reachable.
#[test]
fn property_cursor_reachable() {
    let mut editor = create_large_buffer(100);

    // Navigate to random positions and verify cursor is valid
    editor.move_to_document_start();
    for _ in 0..50 {
        editor.move_right();
    }

    let cursor = editor.cursor();

    // Should be able to get text at cursor line
    if cursor.line > 0 || cursor.grapheme > 0 {
        let line_text = editor.line_text(cursor.line);
        assert!(
            line_text.is_some(),
            "cursor line {} not accessible",
            cursor.line
        );
    }
}

// ============================================================================
// Regression Fixtures
// ============================================================================

/// Regression: inserting at document start in large buffer.
#[test]
fn regression_insert_at_start_large() {
    let mut editor = create_large_buffer(10_000);
    editor.move_to_document_start();

    let start = Instant::now();
    editor.insert_text("START: ");
    let duration = start.elapsed();

    assert!(editor.text().starts_with("START: "));
    assert_within_budget(
        duration,
        5000,
        "insert_at_start",
        LINES_10K,
        "insert_at_start",
    );
}

/// Regression: deleting at document start in large buffer.
#[test]
fn regression_delete_at_start_large() {
    let mut editor = create_large_buffer(10_000);
    editor.move_to_document_start();
    editor.move_right(); // Move past first char

    let start = Instant::now();
    editor.delete_backward();
    let duration = start.elapsed();

    assert_within_budget(
        duration,
        5000,
        "delete_at_start",
        LINES_10K,
        "delete_at_start",
    );
}

/// Regression: word movement in large buffer.
#[test]
fn regression_word_movement_large() {
    let mut editor = create_large_buffer(10_000);
    editor.move_to_document_start();

    let start = Instant::now();
    for _ in 0..100 {
        editor.move_word_right();
    }
    let duration = start.elapsed();

    assert_within_budget(
        duration,
        10_000,
        "word_movement",
        LINES_10K,
        "100_word_moves",
    );
}