splice 2.6.1

Span-safe refactoring kernel for 7 languages with Magellan code graph integration
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
//! Performance tests for context extraction on large files.
//!
//! This test suite validates that context extraction using ropey scales efficiently
//! for large files as specified in Phase 17 success criteria.
//!
//! Performance expectations:
//! - 32KB files: < 100ms
//! - 64KB files: < 200ms
//! - 128KB files: < 400ms
//!
//! Context extraction uses ropey Rope for O(log n) line calculations,
//! which should scale efficiently even for very large files.
//!
//! Tests include:
//! - Basic context extraction on 32KB, 64KB, 128KB files
//! - Asymmetric context extraction (different before/after counts)
//! - Context extraction with symbol expansion (expand_to_body_with_docs)
//! - File boundary extraction (start and end of file)
//! - Linear scaling verification across different file sizes

use splice::context::{extract_context, extract_context_asymmetric};
use splice::expand::expand_to_body_with_docs;
use splice::symbol::Language;
use std::io::Write;
use std::path::Path;
use std::time::Instant;
use tempfile::TempDir;

/// Create a large Rust file with repeated function definitions.
///
/// Each function pair is approximately 100-110 bytes, so num_functions * 100 ≈ file size.
/// Functions include doc comments to enable expansion testing.
///
/// # Arguments
///
/// * `dir` - Temporary directory to create the file in
/// * `name` - Base name for the file
/// * `num_functions` - Number of function pairs to create
///
/// # Returns
///
/// The path to the created file
fn create_large_rust_file(dir: &Path, name: &str, num_functions: usize) -> std::path::PathBuf {
    let file_path = dir.join(name);
    let mut file = std::fs::File::create(&file_path).unwrap();

    for i in 0..num_functions {
        writeln!(
            file,
            r#"/// Documentation for function {}
/// This function adds two numbers together.
pub fn add_{}(x: i32, y: i32) -> i32 {{
    // Line 1 of function body
    // Line 2 of function body
    // Line 3 of function body
    x + y
}}

/// Another function for multiplication
pub fn multiply_{}(x: i32, y: i32) -> i32 {{
    x * y
}}
"#,
            i, i, i
        )
        .unwrap();
    }

    file_path
}

/// Test context extraction on 32KB file.
///
/// Verifies:
/// - Context extraction works on files >32KB
/// - Performance is < 100ms
/// - Before, selected, and after context are all extracted
#[test]
fn test_context_extraction_32kb_file() {
    let dir = TempDir::new().unwrap();

    // Create file with ~350 functions (~35KB)
    let file_path = create_large_rust_file(dir.path(), "large_32kb.rs", 350);

    let file_size = std::fs::metadata(&file_path).unwrap().len();
    assert!(
        file_size > 32_000,
        "Test file should exceed 32KB, got {} bytes",
        file_size
    );

    let source = std::fs::read_to_string(&file_path).unwrap();

    // Find a symbol in the middle of the file
    let offset = source.find("add_175").expect("Symbol not found");

    let start = Instant::now();
    let ctx = extract_context(&file_path, offset, offset + 50, 3).unwrap();
    let duration = start.elapsed();

    // Verify context was extracted
    assert!(!ctx.before.is_empty(), "Should have context before");
    assert!(!ctx.selected.is_empty(), "Should have selected context");
    assert!(!ctx.after.is_empty(), "Should have context after");

    // Verify performance: < 100ms
    assert!(
        duration.as_millis() < 100,
        "Context extraction on 32KB file took {}ms, expected < 100ms",
        duration.as_millis()
    );

    println!(
        "Context extraction on {}KB file took {}ms",
        file_size / 1024,
        duration.as_millis()
    );
}

/// Test context extraction on 64KB file.
///
/// Verifies:
/// - Context extraction works on files >64KB
/// - Performance is < 200ms
/// - All context components are extracted
#[test]
fn test_context_extraction_64kb_file() {
    let dir = TempDir::new().unwrap();

    // Create file with ~700 functions (~70KB)
    let file_path = create_large_rust_file(dir.path(), "large_64kb.rs", 700);

    let file_size = std::fs::metadata(&file_path).unwrap().len();
    assert!(
        file_size > 64_000,
        "Test file should exceed 64KB, got {} bytes",
        file_size
    );

    let source = std::fs::read_to_string(&file_path).unwrap();

    // Find a symbol in the middle of the file
    let offset = source.find("add_350").expect("Symbol not found");

    let start = Instant::now();
    let ctx = extract_context(&file_path, offset, offset + 50, 3).unwrap();
    let duration = start.elapsed();

    // Verify context was extracted
    assert!(!ctx.before.is_empty(), "Should have context before");
    assert!(!ctx.selected.is_empty(), "Should have selected context");
    assert!(!ctx.after.is_empty(), "Should have context after");

    // Verify performance: < 200ms
    assert!(
        duration.as_millis() < 200,
        "Context extraction on 64KB file took {}ms, expected < 200ms",
        duration.as_millis()
    );

    println!(
        "Context extraction on {}KB file took {}ms",
        file_size / 1024,
        duration.as_millis()
    );
}

/// Test context extraction on 128KB file.
///
/// Verifies:
/// - Context extraction works on files >128KB
/// - Performance is < 400ms
/// - Scaling remains acceptable at larger file sizes
#[test]
fn test_context_extraction_128kb_file() {
    let dir = TempDir::new().unwrap();

    // Create file with ~1400 functions (~140KB)
    let file_path = create_large_rust_file(dir.path(), "large_128kb.rs", 1400);

    let file_size = std::fs::metadata(&file_path).unwrap().len();
    assert!(
        file_size > 128_000,
        "Test file should exceed 128KB, got {} bytes",
        file_size
    );

    let source = std::fs::read_to_string(&file_path).unwrap();

    // Find a symbol in the middle of the file
    let offset = source.find("add_700").expect("Symbol not found");

    let start = Instant::now();
    let ctx = extract_context(&file_path, offset, offset + 50, 3).unwrap();
    let duration = start.elapsed();

    // Verify context was extracted
    assert!(!ctx.before.is_empty(), "Should have context before");
    assert!(!ctx.selected.is_empty(), "Should have selected context");
    assert!(!ctx.after.is_empty(), "Should have context after");

    // Verify performance: < 400ms
    assert!(
        duration.as_millis() < 400,
        "Context extraction on 128KB file took {}ms, expected < 400ms",
        duration.as_millis()
    );

    println!(
        "Context extraction on {}KB file took {}ms",
        file_size / 1024,
        duration.as_millis()
    );
}

/// Test context extraction with expansion on large file.
///
/// Verifies:
/// - expand_to_body_with_docs works on 64KB files
/// - Combined expansion + context extraction performance
/// - Performance is < 300ms for the combined operation
#[test]
fn test_context_extraction_with_expansion_64kb() {
    let dir = TempDir::new().unwrap();

    // Create file with ~700 functions (~70KB)
    let file_path = create_large_rust_file(dir.path(), "large_expand.rs", 700);

    let file_size = std::fs::metadata(&file_path).unwrap().len();
    assert!(
        file_size > 64_000,
        "Test file should exceed 64KB, got {} bytes",
        file_size
    );

    let source = std::fs::read_to_string(&file_path).unwrap();
    let offset = source.find("add_350").expect("Symbol not found");

    let start = Instant::now();

    // First expand to body (with docs)
    let (expanded_start, expanded_end) =
        expand_to_body_with_docs(&file_path, offset, Language::Rust).unwrap();

    // Then extract context from expanded span
    let ctx = extract_context(&file_path, expanded_start, expanded_end, 3).unwrap();

    let duration = start.elapsed();

    // Verify expansion worked
    assert!(
        expanded_end > expanded_start,
        "Should expand to larger span"
    );
    assert!(!ctx.before.is_empty(), "Should have context before");
    assert!(
        !ctx.selected.is_empty(),
        "Should have selected content from expanded span"
    );

    // Verify performance: < 300ms (expansion + context)
    assert!(
        duration.as_millis() < 300,
        "Expansion + context extraction on 64KB file took {}ms, expected < 300ms",
        duration.as_millis()
    );

    println!(
        "Expansion + context extraction on {}KB file took {}ms",
        file_size / 1024,
        duration.as_millis()
    );
}

/// Test asymmetric context extraction on large file.
///
/// Verifies:
/// - extract_context_asymmetric works on 64KB files
/// - Different before/after context counts are respected
/// - Performance is < 150ms for asymmetric extraction
#[test]
fn test_asymmetric_context_extraction_64kb() {
    let dir = TempDir::new().unwrap();

    // Create file with ~700 functions (~70KB)
    let file_path = create_large_rust_file(dir.path(), "large_asymmetric.rs", 700);

    let file_size = std::fs::metadata(&file_path).unwrap().len();
    assert!(
        file_size > 64_000,
        "Test file should exceed 64KB, got {} bytes",
        file_size
    );

    let source = std::fs::read_to_string(&file_path).unwrap();
    let offset = source.find("add_350").expect("Symbol not found");

    let start = Instant::now();

    // Extract asymmetric context (5 before, 2 after)
    let ctx = extract_context_asymmetric(&file_path, offset, offset + 50, 5, 2).unwrap();

    let duration = start.elapsed();

    // Verify asymmetric counts (exact count may vary based on file position)
    assert!(
        ctx.before.len() <= 5,
        "Should have at most 5 lines before, got {}",
        ctx.before.len()
    );
    assert!(
        ctx.after.len() <= 2,
        "Should have at most 2 lines after, got {}",
        ctx.after.len()
    );
    assert!(!ctx.selected.is_empty(), "Should have selected content");

    // Verify performance: < 150ms
    assert!(
        duration.as_millis() < 150,
        "Asymmetric context extraction on 64KB file took {}ms, expected < 150ms",
        duration.as_millis()
    );

    println!(
        "Asymmetric context extraction ({} before, {} after) on {}KB file took {}ms",
        ctx.before.len(),
        ctx.after.len(),
        file_size / 1024,
        duration.as_millis()
    );
}

/// Test context extraction at file boundaries.
///
/// Verifies:
/// - Context extraction works at the start of a file
/// - Context extraction works at the end of a file
/// - Boundary conditions don't cause errors
/// - Performance at boundaries is acceptable (< 50ms)
#[test]
fn test_context_extraction_at_file_boundaries() {
    let dir = TempDir::new().unwrap();

    // Create file with ~350 functions (~35KB)
    let file_path = create_large_rust_file(dir.path(), "large_boundary.rs", 350);

    let source = std::fs::read_to_string(&file_path).unwrap();

    // Test at beginning of file (first function)
    let first_offset = source.find("add_0").expect("Symbol not found");
    let start = Instant::now();
    let ctx_start = extract_context(&file_path, first_offset, first_offset + 50, 3).unwrap();
    let duration_start = start.elapsed();

    assert!(
        !ctx_start.selected.is_empty(),
        "Should extract at file start"
    );
    // At file start, before should be empty or minimal
    assert!(
        ctx_start.before.len() <= 3,
        "At file start, before context should be minimal"
    );

    // Test at end of file (last function)
    let last_offset = source.rfind("multiply_").expect("Symbol not found");
    let start = Instant::now();
    let ctx_end = extract_context(&file_path, last_offset, last_offset + 50, 3).unwrap();
    let duration_end = start.elapsed();

    assert!(!ctx_end.selected.is_empty(), "Should extract at file end");
    // At file end, after should be empty or minimal
    assert!(
        ctx_end.after.len() <= 1,
        "At file end, after context should be minimal"
    );

    // Both should be fast (< 50ms)
    assert!(
        duration_start.as_millis() < 50,
        "Context extraction at file start took {}ms, expected < 50ms",
        duration_start.as_millis()
    );
    assert!(
        duration_end.as_millis() < 50,
        "Context extraction at file end took {}ms, expected < 50ms",
        duration_end.as_millis()
    );

    println!(
        "Boundary extraction: start {}ms, end {}ms",
        duration_start.as_millis(),
        duration_end.as_millis()
    );
}

/// Test performance scaling is linear.
///
/// Verifies:
/// - Context extraction scales roughly linearly with file size
/// - Small files (100 functions) complete quickly
/// - Medium files (200 functions) complete in reasonable time
/// - Larger files (400 functions) still perform well
///
/// This test ensures the O(log n) behavior of ropey is providing
/// efficient line calculations without unexpected overhead.
#[test]
fn test_context_extraction_linear_scaling() {
    let dir = TempDir::new().unwrap();

    // Create files of different sizes and measure performance
    let test_cases = vec![
        (100, 50),  // 100 functions, max 50ms
        (200, 100), // 200 functions, max 100ms
        (400, 200), // 400 functions, max 200ms
    ];

    let mut timings = Vec::new();

    for (num_functions, expected_max_ms) in test_cases {
        let file_path = create_large_rust_file(
            dir.path(),
            &format!("scale_{}.rs", num_functions),
            num_functions,
        );

        let source = std::fs::read_to_string(&file_path).unwrap();
        let offset = source.find("add_").expect("Symbol not found");

        let start = Instant::now();
        let ctx = extract_context(&file_path, offset, offset + 50, 3).unwrap();
        let duration = start.elapsed();

        assert!(
            !ctx.before.is_empty(),
            "Should extract context for {} functions",
            num_functions
        );

        let duration_ms = duration.as_millis();
        timings.push((num_functions, duration_ms));

        assert!(
            duration_ms < expected_max_ms,
            "Context extraction on {}-function file took {}ms, expected < {}ms",
            num_functions,
            duration_ms,
            expected_max_ms
        );

        println!("{} functions: {}ms", num_functions, duration_ms);
    }

    // Verify linear-ish scaling: each doubling should not more than triple the time
    // This is a loose check to catch严重的 performance regressions
    if timings.len() >= 2 {
        let (_, time1) = timings[0];
        let (count2, time2) = timings[1];

        // Going from ~100 to ~200 functions should not take more than 3x the time
        let ratio = time2 as f64 / time1.max(1) as f64;
        assert!(
            ratio < 3.0,
            "Performance scaling seems non-linear: {} functions took {:.2}x the time of {} functions",
            count2,
            ratio,
            timings[0].0
        );
    }
}

/// Test context extraction with zero context lines.
///
/// Verifies the edge case where no context is requested.
#[test]
fn test_context_extraction_zero_context_large_file() {
    let dir = TempDir::new().unwrap();

    let file_path = create_large_rust_file(dir.path(), "large_zero.rs", 350);

    let source = std::fs::read_to_string(&file_path).unwrap();
    let offset = source.find("add_175").expect("Symbol not found");

    let start = Instant::now();
    let ctx = extract_context(&file_path, offset, offset + 50, 0).unwrap();
    let duration = start.elapsed();

    // With zero context, before and after should be empty
    assert_eq!(ctx.before.len(), 0, "Should have no context before");
    assert_eq!(ctx.after.len(), 0, "Should have no context after");
    assert!(!ctx.selected.is_empty(), "Should have selected content");

    // Should still be very fast with no context
    assert!(
        duration.as_millis() < 50,
        "Zero-context extraction took {}ms, expected < 50ms",
        duration.as_millis()
    );
}

/// Test context extraction with large context window.
///
/// Verifies performance when requesting many lines of context.
#[test]
fn test_context_extraction_large_context_window() {
    let dir = TempDir::new().unwrap();

    let file_path = create_large_rust_file(dir.path(), "large_window.rs", 700);

    let source = std::fs::read_to_string(&file_path).unwrap();
    let offset = source.find("add_350").expect("Symbol not found");

    let start = Instant::now();
    let ctx = extract_context(&file_path, offset, offset + 50, 20).unwrap();
    let duration = start.elapsed();

    // Should extract up to 20 lines before and after
    assert!(
        ctx.before.len() <= 20,
        "Should have at most 20 lines before, got {}",
        ctx.before.len()
    );
    assert!(
        ctx.after.len() <= 20,
        "Should have at most 20 lines after, got {}",
        ctx.after.len()
    );

    // Even with large context window, should be reasonably fast
    assert!(
        duration.as_millis() < 200,
        "Large context window extraction took {}ms, expected < 200ms",
        duration.as_millis()
    );

    println!(
        "Large context window (up to 20 lines): {}ms",
        duration.as_millis()
    );
}