thread-flow 0.1.0

Thread dataflow integration for data processing pipelines, using CocoIndex.
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
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
// SPDX-FileCopyrightText: 2025 Knitli Inc. <knitli@knit.li>
// SPDX-FileCopyrightText: 2026 Knitli Inc.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! Comprehensive tests for extractor functions
//!
//! This test suite validates the three extractor factories:
//! - ExtractSymbolsFactory (extracts field 0 from parsed document)
//! - ExtractImportsFactory (extracts field 1 from parsed document)
//! - ExtractCallsFactory (extracts field 2 from parsed document)
//!
//! Coverage targets:
//! - Factory trait implementations (name, analyze, build_executor)
//! - Schema generation and validation
//! - Behavior version reporting
//! - Executor evaluation with valid/invalid inputs
//! - Cache and timeout settings
//! - Edge cases (empty input, wrong types, missing fields)

use recoco::base::schema::{TableKind, TableSchema, ValueType};
use recoco::base::value::{BasicValue, FieldValues, ScopeValue, Value};
use recoco::ops::factory_bases::SimpleFunctionFactoryBase;
use recoco::ops::interface::{FlowInstanceContext, SimpleFunctionFactory};
use recoco::setup::AuthRegistry;
use std::sync::Arc;
use thread_flow::functions::calls::ExtractCallsFactory;
use thread_flow::functions::imports::ExtractImportsFactory;
use thread_flow::functions::parse::ThreadParseFactory;
use thread_flow::functions::symbols::ExtractSymbolsFactory;

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

/// Helper to create a mock FlowInstanceContext
fn create_mock_context() -> Arc<FlowInstanceContext> {
    Arc::new(FlowInstanceContext {
        flow_instance_name: "test_flow".to_string(),
        auth_registry: Arc::new(AuthRegistry::new()),
    })
}

/// Helper to create empty spec (ReCoco expects {} not null)
fn empty_spec() -> serde_json::Value {
    serde_json::json!({})
}

/// Helper to create a mock parsed document struct with symbols, imports, calls, fingerprint
fn create_mock_parsed_doc(symbols_count: usize, imports_count: usize, calls_count: usize) -> Value {
    // Create mock symbols table
    let symbols: Vec<ScopeValue> = (0..symbols_count)
        .map(|i| {
            ScopeValue(FieldValues {
                fields: vec![
                    Value::Basic(BasicValue::Str(format!("symbol_{}", i).into())),
                    Value::Basic(BasicValue::Str("Function".to_string().into())),
                    Value::Basic(BasicValue::Str("global".to_string().into())),
                ],
            })
        })
        .collect();

    // Create mock imports table
    let imports: Vec<ScopeValue> = (0..imports_count)
        .map(|i| {
            ScopeValue(FieldValues {
                fields: vec![
                    Value::Basic(BasicValue::Str(format!("import_{}", i).into())),
                    Value::Basic(BasicValue::Str("module/path".to_string().into())),
                    Value::Basic(BasicValue::Str("Named".to_string().into())),
                ],
            })
        })
        .collect();

    // Create mock calls table
    let calls: Vec<ScopeValue> = (0..calls_count)
        .map(|i| {
            ScopeValue(FieldValues {
                fields: vec![
                    Value::Basic(BasicValue::Str(format!("call_{}", i).into())),
                    Value::Basic(BasicValue::Int64(i as i64)),
                ],
            })
        })
        .collect();

    // Mock fingerprint
    let fingerprint = Value::Basic(BasicValue::Bytes(bytes::Bytes::from(vec![1, 2, 3, 4])));

    Value::Struct(FieldValues {
        fields: vec![
            Value::LTable(symbols),
            Value::LTable(imports),
            Value::LTable(calls),
            fingerprint,
        ],
    })
}

/// Helper to execute ThreadParse with given inputs
async fn execute_parse(
    content: &str,
    language: &str,
    file_path: &str,
) -> Result<Value, recoco::prelude::Error> {
    let factory = Arc::new(ThreadParseFactory);
    let context = create_mock_context();

    let build_output = factory.build(empty_spec(), vec![], context).await?;
    let executor = build_output.executor.await?;

    let inputs = vec![
        Value::Basic(BasicValue::Str(content.to_string().into())),
        Value::Basic(BasicValue::Str(language.to_string().into())),
        Value::Basic(BasicValue::Str(file_path.to_string().into())),
    ];

    executor.evaluate(inputs).await
}

// =============================================================================
// ExtractSymbolsFactory Tests
// =============================================================================

#[tokio::test]
async fn test_extract_symbols_factory_name() {
    let factory = ExtractSymbolsFactory;
    assert_eq!(factory.name(), "extract_symbols");
}

#[tokio::test]
async fn test_extract_symbols_factory_build() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let result = factory.build(empty_spec(), vec![], context).await;

    assert!(result.is_ok(), "Build should succeed");

    let build_output = result.unwrap();
    assert_eq!(
        build_output.behavior_version,
        Some(1),
        "Behavior version should be 1"
    );
}

#[tokio::test]
async fn test_extract_symbols_schema() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");

    let schema = build_output.output_type;
    assert!(!schema.nullable, "Schema should not be nullable");

    // Verify it's a table with the correct row structure
    match schema.typ {
        ValueType::Table(TableSchema { kind, row }) => {
            assert_eq!(kind, TableKind::LTable, "Should be LTable");

            // Verify row structure has 3 fields: name, kind, scope
            let fields = row.fields.as_ref();
            assert_eq!(fields.len(), 3, "Symbol should have 3 fields");
            assert_eq!(fields[0].name, "name");
            assert_eq!(fields[1].name, "kind");
            assert_eq!(fields[2].name, "scope");
        }
        _ => panic!("Expected Table type"),
    }
}

#[tokio::test]
async fn test_extract_symbols_executor_creation() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");

    let executor = build_output.executor.await;
    assert!(executor.is_ok(), "Executor creation should succeed");
}

#[tokio::test]
async fn test_extract_symbols_executor_evaluate() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // Create mock parsed document
    let mock_doc = create_mock_parsed_doc(3, 2, 1);

    let result = executor.evaluate(vec![mock_doc]).await;
    assert!(result.is_ok(), "Evaluation should succeed");

    // Verify we got the symbols table (field 0)
    match result.unwrap() {
        Value::LTable(symbols) => {
            assert_eq!(symbols.len(), 3, "Should have 3 symbols");

            // Check first symbol structure
            match &symbols[0].0.fields[0] {
                Value::Basic(BasicValue::Str(name)) => {
                    assert_eq!(name.as_ref(), "symbol_0");
                }
                _ => panic!("Expected string for symbol name"),
            }
        }
        _ => panic!("Expected LTable"),
    }
}

#[tokio::test]
async fn test_extract_symbols_empty_input() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let result = executor.evaluate(vec![]).await;
    assert!(result.is_err(), "Should error on empty input");
    assert!(result.unwrap_err().to_string().contains("Missing"));
}

#[tokio::test]
async fn test_extract_symbols_invalid_type() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let invalid_input = Value::Basic(BasicValue::Str("not a struct".to_string().into()));
    let result = executor.evaluate(vec![invalid_input]).await;

    assert!(result.is_err(), "Should error on invalid type");
    assert!(result.unwrap_err().to_string().contains("Expected Struct"));
}

#[tokio::test]
async fn test_extract_symbols_missing_field() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // Create struct with zero fields - missing the symbols field (field 0)
    let invalid_struct = Value::Struct(FieldValues { fields: vec![] });

    let result = executor.evaluate(vec![invalid_struct]).await;
    assert!(result.is_err(), "Should error on missing symbols field");
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Missing symbols field"),
        "Error should mention missing symbols field"
    );
}

#[tokio::test]
async fn test_extract_symbols_cache_enabled() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    assert!(executor.enable_cache(), "Cache should be enabled");
}

#[tokio::test]
async fn test_extract_symbols_timeout() {
    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // NOTE: ReCoco's SimpleFunctionFactoryBase wrapper doesn't delegate timeout()
    // This is a known limitation in recoco v0.2.1 - the wrapper only delegates enable_cache()
    // The executor implements timeout() but it's not accessible through the wrapper
    let timeout = executor.timeout();
    // For now, we just verify the method can be called without panicking
    assert!(
        timeout.is_none() || timeout.is_some(),
        "Timeout method should be callable"
    );
}

#[tokio::test]
async fn test_extract_symbols_from_real_parse() {
    // Parse a simple Rust file and extract symbols
    let content = "fn test() {}";
    let parsed = execute_parse(content, "rs", "test.rs")
        .await
        .expect("Parse should succeed");

    let factory = Arc::new(ExtractSymbolsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let result = executor.evaluate(vec![parsed]).await;
    assert!(result.is_ok(), "Extraction should succeed");

    match result.unwrap() {
        Value::LTable(symbols) => {
            // May be empty if pattern matching doesn't work, that's okay
            println!("Extracted {} symbols from real parse", symbols.len());
        }
        _ => panic!("Expected LTable"),
    }
}

// =============================================================================
// ExtractImportsFactory Tests
// =============================================================================

#[tokio::test]
async fn test_extract_imports_factory_name() {
    let factory = ExtractImportsFactory;
    assert_eq!(factory.name(), "extract_imports");
}

#[tokio::test]
async fn test_extract_imports_factory_build() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let result = factory.build(empty_spec(), vec![], context).await;

    assert!(result.is_ok(), "Build should succeed");

    let build_output = result.unwrap();
    assert_eq!(
        build_output.behavior_version,
        Some(1),
        "Behavior version should be 1"
    );
}

#[tokio::test]
async fn test_extract_imports_schema() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");

    let schema = build_output.output_type;
    assert!(!schema.nullable, "Schema should not be nullable");

    // Verify it's a table with the correct row structure
    match schema.typ {
        ValueType::Table(TableSchema { kind, row }) => {
            assert_eq!(kind, TableKind::LTable, "Should be LTable");

            // Verify row structure has 3 fields: symbol_name, source_path, kind
            let fields = row.fields.as_ref();
            assert_eq!(fields.len(), 3, "Import should have 3 fields");
            assert_eq!(fields[0].name, "symbol_name");
            assert_eq!(fields[1].name, "source_path");
            assert_eq!(fields[2].name, "kind");
        }
        _ => panic!("Expected Table type"),
    }
}

#[tokio::test]
async fn test_extract_imports_executor_creation() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");

    let executor = build_output.executor.await;
    assert!(executor.is_ok(), "Executor creation should succeed");
}

#[tokio::test]
async fn test_extract_imports_executor_evaluate() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // Create mock parsed document
    let mock_doc = create_mock_parsed_doc(3, 5, 1);

    let result = executor.evaluate(vec![mock_doc]).await;
    assert!(result.is_ok(), "Evaluation should succeed");

    // Verify we got the imports table (field 1)
    match result.unwrap() {
        Value::LTable(imports) => {
            assert_eq!(imports.len(), 5, "Should have 5 imports");

            // Check first import structure
            match &imports[0].0.fields[0] {
                Value::Basic(BasicValue::Str(name)) => {
                    assert_eq!(name.as_ref(), "import_0");
                }
                _ => panic!("Expected string for import name"),
            }
        }
        _ => panic!("Expected LTable"),
    }
}

#[tokio::test]
async fn test_extract_imports_empty_input() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let result = executor.evaluate(vec![]).await;
    assert!(result.is_err(), "Should error on empty input");
    assert!(result.unwrap_err().to_string().contains("Missing"));
}

#[tokio::test]
async fn test_extract_imports_invalid_type() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let invalid_input = Value::Basic(BasicValue::Int64(42));
    let result = executor.evaluate(vec![invalid_input]).await;

    assert!(result.is_err(), "Should error on invalid type");
    assert!(result.unwrap_err().to_string().contains("Expected Struct"));
}

#[tokio::test]
async fn test_extract_imports_missing_field() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // Create struct with only 1 field instead of 4
    let invalid_struct = Value::Struct(FieldValues {
        fields: vec![Value::LTable(vec![])],
    });

    let result = executor.evaluate(vec![invalid_struct]).await;
    assert!(result.is_err(), "Should error on missing field");
}

#[tokio::test]
async fn test_extract_imports_cache_enabled() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    assert!(executor.enable_cache(), "Cache should be enabled");
}

#[tokio::test]
async fn test_extract_imports_timeout() {
    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // NOTE: ReCoco's SimpleFunctionFactoryBase wrapper doesn't delegate timeout()
    // This is a known limitation in recoco v0.2.1 - the wrapper only delegates enable_cache()
    // The executor implements timeout() but it's not accessible through the wrapper
    let timeout = executor.timeout();
    // For now, we just verify the method can be called without panicking
    assert!(
        timeout.is_none() || timeout.is_some(),
        "Timeout method should be callable"
    );
}

#[tokio::test]
async fn test_extract_imports_from_real_parse() {
    // Parse a simple Python file with imports and extract them
    let content = "import os\nfrom sys import argv";
    let parsed = execute_parse(content, "py", "test.py")
        .await
        .expect("Parse should succeed");

    let factory = Arc::new(ExtractImportsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let result = executor.evaluate(vec![parsed]).await;
    assert!(result.is_ok(), "Extraction should succeed");

    match result.unwrap() {
        Value::LTable(imports) => {
            // May be empty if pattern matching doesn't work, that's okay
            println!("Extracted {} imports from real parse", imports.len());
        }
        _ => panic!("Expected LTable"),
    }
}

// =============================================================================
// ExtractCallsFactory Tests
// =============================================================================

#[tokio::test]
async fn test_extract_calls_factory_name() {
    let factory = ExtractCallsFactory;
    assert_eq!(factory.name(), "extract_calls");
}

#[tokio::test]
async fn test_extract_calls_factory_build() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let result = factory.build(empty_spec(), vec![], context).await;

    assert!(result.is_ok(), "Build should succeed");

    let build_output = result.unwrap();
    assert_eq!(
        build_output.behavior_version,
        Some(1),
        "Behavior version should be 1"
    );
}

#[tokio::test]
async fn test_extract_calls_schema() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");

    let schema = build_output.output_type;
    assert!(!schema.nullable, "Schema should not be nullable");

    // Verify it's a table with the correct row structure
    match schema.typ {
        ValueType::Table(TableSchema { kind, row }) => {
            assert_eq!(kind, TableKind::LTable, "Should be LTable");

            // Verify row structure has 2 fields: function_name, arguments_count
            let fields = row.fields.as_ref();
            assert_eq!(fields.len(), 2, "Call should have 2 fields");
            assert_eq!(fields[0].name, "function_name");
            assert_eq!(fields[1].name, "arguments_count");
        }
        _ => panic!("Expected Table type"),
    }
}

#[tokio::test]
async fn test_extract_calls_executor_creation() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");

    let executor = build_output.executor.await;
    assert!(executor.is_ok(), "Executor creation should succeed");
}

#[tokio::test]
async fn test_extract_calls_executor_evaluate() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // Create mock parsed document
    let mock_doc = create_mock_parsed_doc(3, 2, 7);

    let result = executor.evaluate(vec![mock_doc]).await;
    assert!(result.is_ok(), "Evaluation should succeed");

    // Verify we got the calls table (field 2)
    match result.unwrap() {
        Value::LTable(calls) => {
            assert_eq!(calls.len(), 7, "Should have 7 calls");

            // Check first call structure
            match &calls[0].0.fields[0] {
                Value::Basic(BasicValue::Str(name)) => {
                    assert_eq!(name.as_ref(), "call_0");
                }
                _ => panic!("Expected string for call name"),
            }

            // Check argument count
            match &calls[0].0.fields[1] {
                Value::Basic(BasicValue::Int64(count)) => {
                    assert_eq!(*count, 0);
                }
                _ => panic!("Expected Int64 for argument count"),
            }
        }
        _ => panic!("Expected LTable"),
    }
}

#[tokio::test]
async fn test_extract_calls_empty_input() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let result = executor.evaluate(vec![]).await;
    assert!(result.is_err(), "Should error on empty input");
    assert!(result.unwrap_err().to_string().contains("Missing"));
}

#[tokio::test]
async fn test_extract_calls_invalid_type() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let invalid_input = Value::LTable(vec![]);
    let result = executor.evaluate(vec![invalid_input]).await;

    assert!(result.is_err(), "Should error on invalid type");
    assert!(result.unwrap_err().to_string().contains("Expected Struct"));
}

#[tokio::test]
async fn test_extract_calls_missing_field() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // Create struct with only 2 fields instead of 4 - missing the calls field (field 2)
    let invalid_struct = Value::Struct(FieldValues {
        fields: vec![Value::LTable(vec![]), Value::LTable(vec![])],
    });

    let result = executor.evaluate(vec![invalid_struct]).await;
    assert!(result.is_err(), "Should error on missing calls field");
    assert!(
        result
            .unwrap_err()
            .to_string()
            .contains("Missing calls field"),
        "Error should mention missing calls field"
    );
}

#[tokio::test]
async fn test_extract_calls_cache_enabled() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    assert!(executor.enable_cache(), "Cache should be enabled");
}

#[tokio::test]
async fn test_extract_calls_timeout() {
    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    // NOTE: ReCoco's SimpleFunctionFactoryBase wrapper doesn't delegate timeout()
    // This is a known limitation in recoco v0.2.1 - the wrapper only delegates enable_cache()
    // The executor implements timeout() but it's not accessible through the wrapper
    let timeout = executor.timeout();
    // For now, we just verify the method can be called without panicking
    assert!(
        timeout.is_none() || timeout.is_some(),
        "Timeout method should be callable"
    );
}

#[tokio::test]
async fn test_extract_calls_from_real_parse() {
    // Parse a simple TypeScript file with function calls and extract them
    let content = "console.log('hello');\nsetTimeout(fn, 100);";
    let parsed = execute_parse(content, "ts", "test.ts")
        .await
        .expect("Parse should succeed");

    let factory = Arc::new(ExtractCallsFactory);
    let context = create_mock_context();

    let build_output = factory
        .build(empty_spec(), vec![], context)
        .await
        .expect("Build should succeed");
    let executor = build_output.executor.await.expect("Executor should build");

    let result = executor.evaluate(vec![parsed]).await;
    assert!(result.is_ok(), "Extraction should succeed");

    match result.unwrap() {
        Value::LTable(calls) => {
            // May be empty if pattern matching doesn't work, that's okay
            println!("Extracted {} calls from real parse", calls.len());
        }
        _ => panic!("Expected LTable"),
    }
}

// =============================================================================
// Cross-Extractor Tests
// =============================================================================

#[tokio::test]
async fn test_all_extractors_on_same_document() {
    // Create a mock document and verify all three extractors work correctly
    let mock_doc = create_mock_parsed_doc(3, 2, 5);
    let context = create_mock_context();

    // Test symbols extractor
    let symbols_factory = Arc::new(ExtractSymbolsFactory);
    let symbols_output = symbols_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");
    let symbols_executor = symbols_output
        .executor
        .await
        .expect("Executor should build");
    let symbols_result = symbols_executor.evaluate(vec![mock_doc.clone()]).await;
    assert!(symbols_result.is_ok(), "Symbols extraction should succeed");

    if let Value::LTable(symbols) = symbols_result.unwrap() {
        assert_eq!(symbols.len(), 3, "Should extract 3 symbols");
    }

    // Test imports extractor
    let imports_factory = Arc::new(ExtractImportsFactory);
    let imports_output = imports_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");
    let imports_executor = imports_output
        .executor
        .await
        .expect("Executor should build");
    let imports_result = imports_executor.evaluate(vec![mock_doc.clone()]).await;
    assert!(imports_result.is_ok(), "Imports extraction should succeed");

    if let Value::LTable(imports) = imports_result.unwrap() {
        assert_eq!(imports.len(), 2, "Should extract 2 imports");
    }

    // Test calls extractor
    let calls_factory = Arc::new(ExtractCallsFactory);
    let calls_output = calls_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");
    let calls_executor = calls_output.executor.await.expect("Executor should build");
    let calls_result = calls_executor.evaluate(vec![mock_doc.clone()]).await;
    assert!(calls_result.is_ok(), "Calls extraction should succeed");

    if let Value::LTable(calls) = calls_result.unwrap() {
        assert_eq!(calls.len(), 5, "Should extract 5 calls");
    }
}

#[tokio::test]
async fn test_extractors_with_empty_tables() {
    // Test all extractors with empty tables
    let mock_doc = create_mock_parsed_doc(0, 0, 0);
    let context = create_mock_context();

    let symbols_factory = Arc::new(ExtractSymbolsFactory);
    let symbols_output = symbols_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");
    let symbols_executor = symbols_output
        .executor
        .await
        .expect("Executor should build");
    let symbols_result = symbols_executor.evaluate(vec![mock_doc.clone()]).await;

    if let Ok(Value::LTable(symbols)) = symbols_result {
        assert_eq!(symbols.len(), 0, "Empty document should have no symbols");
    }

    let imports_factory = Arc::new(ExtractImportsFactory);
    let imports_output = imports_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");
    let imports_executor = imports_output
        .executor
        .await
        .expect("Executor should build");
    let imports_result = imports_executor.evaluate(vec![mock_doc.clone()]).await;

    if let Ok(Value::LTable(imports)) = imports_result {
        assert_eq!(imports.len(), 0, "Empty document should have no imports");
    }

    let calls_factory = Arc::new(ExtractCallsFactory);
    let calls_output = calls_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Build should succeed");
    let calls_executor = calls_output.executor.await.expect("Executor should build");
    let calls_result = calls_executor.evaluate(vec![mock_doc.clone()]).await;

    if let Ok(Value::LTable(calls)) = calls_result {
        assert_eq!(calls.len(), 0, "Empty document should have no calls");
    }
}

#[tokio::test]
async fn test_extractors_behavior_versions_match() {
    // Verify all three extractors report the same behavior version
    let context = create_mock_context();

    let symbols_factory = Arc::new(ExtractSymbolsFactory);
    let imports_factory = Arc::new(ExtractImportsFactory);
    let calls_factory = Arc::new(ExtractCallsFactory);

    let symbols_output = symbols_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Symbols build should succeed");

    let imports_output = imports_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Imports build should succeed");

    let calls_output = calls_factory
        .build(empty_spec(), vec![], context.clone())
        .await
        .expect("Calls build should succeed");

    assert_eq!(
        symbols_output.behavior_version, imports_output.behavior_version,
        "Symbols and Imports should have same behavior version"
    );
    assert_eq!(
        imports_output.behavior_version, calls_output.behavior_version,
        "Imports and Calls should have same behavior version"
    );
}