frozen-duckdb 0.1.0

Pre-compiled DuckDB binary for fast Rust builds - Drop-in replacement for duckdb-rs
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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
# Testing Strategy Guide

## Overview

Frozen DuckDB follows a **comprehensive testing strategy** that ensures **reliability**, **performance**, and **correctness** across all components. This guide outlines the **testing philosophy**, **test categories**, and **validation procedures** required for **production-quality code**.

## Testing Philosophy

### Core Team Requirements

**Multiple Test Runs:**
```bash
# Core team requirement: Run tests 3+ times to catch flaky behavior
cargo test --all && cargo test --all && cargo test --all
```

**Test Consistency:**
```bash
# Run with different configurations
cargo test --release --all
ARCH=x86_64 source prebuilt/setup_env.sh && cargo test --all
ARCH=arm64 source prebuilt/setup_env.sh && cargo test --all
```

**Performance Validation:**
```bash
# Ensure performance targets are met
cargo test --test performance_tests

# Validate build time requirements
time cargo build --release  # Should be <10s
```

## Test Categories

### 1. Unit Tests

**Purpose**: Test individual functions and modules in isolation

**Location**: `src/` directory, alongside implementation code

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

    #[test]
    fn test_detect_architecture() {
        let arch = detect();
        assert!(!arch.is_empty());
        assert!(matches!(arch.as_str(), "x86_64" | "arm64" | "aarch64"));
    }

    #[test]
    fn test_binary_validation() {
        // Test with valid binary path
        std::env::set_var("DUCKDB_LIB_DIR", "/valid/path");
        assert!(validate_binary().is_ok());

        // Test with invalid binary path
        std::env::set_var("DUCKDB_LIB_DIR", "/invalid/path");
        assert!(validate_binary().is_err());
        std::env::remove_var("DUCKDB_LIB_DIR");
    }
}
```

### 2. Integration Tests

**Purpose**: Test component interactions and end-to-end functionality

**Location**: `tests/` directory

**Example Structure:**
```
tests/
├── core_functionality_tests.rs    # Core DuckDB operations
├── arrow_tests.rs                # Arrow integration
├── parquet_tests.rs              # Parquet integration
├── flock_tests.rs                # LLM/Flock extension
└── performance_tests.rs          # Performance validation
```

### 3. Property Tests

**Purpose**: Test properties and invariants using generated test data

**Tools**: `proptest` crate for property-based testing

**Example:**
```rust
use proptest::prelude::*;

proptest! {
    #[test]
    fn test_architecture_detection_consistency(arch in "x86_64|arm64|aarch64") {
        std::env::set_var("ARCH", arch);
        let detected = detect();
        assert_eq!(detected, arch);
        std::env::remove_var("ARCH");
    }

    #[test]
    fn test_binary_name_generation(input_arch in "x86_64|arm64|aarch64|unknown") {
        std::env::set_var("ARCH", input_arch);
        let binary_name = get_binary_name();
        assert!(binary_name.starts_with("libduckdb"));
        assert!(binary_name.ends_with(".dylib"));
        std::env::remove_var("ARCH");
    }
}
```

### 4. Performance Tests

**Purpose**: Validate performance requirements and detect regressions

**Example:**
```rust
#[cfg(test)]
mod performance_tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_build_time_requirements() {
        let duration = benchmark::measure_build_time(|| {
            // Simulate build operation
            std::thread::sleep(Duration::from_millis(10));
            Ok(())
        });

        // Validate performance requirement
        assert!(
            duration.as_secs() < 10,
            "Build time exceeded 10s requirement: {:?}",
            duration
        );
    }

    #[test]
    fn test_query_performance() {
        let conn = Connection::open_in_memory().unwrap();

        // Setup test data
        conn.execute("CREATE TABLE test (id INTEGER, data TEXT)", []).unwrap();
        for i in 0..1000 {
            conn.execute(
                "INSERT INTO test VALUES (?, ?)",
                [i, &format!("data_{}", i)],
            ).unwrap();
        }

        // Measure query performance
        let start = std::time::Instant::now();
        let count: i64 = conn.query_row("SELECT COUNT(*) FROM test", [], |row| row.get(0)).unwrap();
        let duration = start.elapsed();

        assert_eq!(count, 1000);
        assert!(
            duration.as_millis() < 100,
            "Query too slow: {:?}",
            duration
        );
    }
}
```

### 5. LLM Integration Tests

**Purpose**: Test Flock extension and Ollama integration

**Requirements**: Ollama server running with required models

**Example:**
```rust
#[cfg(test)]
mod flock_tests {
    use super::*;

    #[test]
    fn test_flock_extension_loading() {
        let conn = Connection::open_in_memory().unwrap();

        // Install and load Flock extension
        conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

        // Verify extension loaded
        let extension: String = conn.query_row(
            "SELECT extension_name FROM duckdb_extensions() WHERE extension_name = 'flock'",
            [],
            |row| row.get(0),
        ).unwrap();

        assert_eq!(extension, "flock");
    }

    #[test]
    fn test_llm_completion() {
        let conn = Connection::open_in_memory().unwrap();
        conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

        // Create models
        conn.execute("CREATE MODEL('test_coder', 'qwen3-coder:30b', 'ollama')", []).unwrap();
        conn.execute("CREATE PROMPT('test_prompt', 'Complete: {{text}}')", []).unwrap();

        // Test completion
        let result: String = conn.query_row(
            "SELECT llm_complete({'model_name': 'test_coder'}, {'prompt_name': 'test_prompt', 'context_columns': [{'data': 'Hello'}]})",
            [],
            |row| row.get(0),
        ).unwrap();

        assert!(!result.is_empty());
        assert!(result.to_lowercase().contains("hello"));
    }
}
```

## Test Data Management

### 1. Test Dataset Generation

**Automated Test Data Setup:**
```rust
// In test setup code
fn setup_test_datasets() -> Result<(), Box<dyn std::error::Error>> {
    // Generate Chinook dataset
    let dataset_manager = DatasetManager::new()?;
    dataset_manager.download_chinook("test_datasets", "parquet")?;

    // Generate TPC-H dataset
    dataset_manager.download_tpch("test_datasets", "parquet")?;

    Ok(())
}

#[test]
fn test_with_real_data() {
    setup_test_datasets().expect("Failed to setup test data");

    // Test with real data
    let conn = Connection::open("test_datasets/tpch.duckdb").unwrap();
    let count: i64 = conn.query_row("SELECT COUNT(*) FROM customer", [], |row| row.get(0)).unwrap();
    assert!(count > 0);
}
```

**Test Data Validation:**
```sql
-- Validate test data integrity
SELECT
    'customer' as table_name,
    COUNT(*) as row_count,
    COUNT(DISTINCT c_custkey) as unique_customers,
    MIN(c_acctbal) as min_balance,
    MAX(c_acctbal) as max_balance
FROM customer

UNION ALL

SELECT
    'orders' as table_name,
    COUNT(*) as row_count,
    COUNT(DISTINCT o_orderkey) as unique_orders,
    MIN(o_totalprice) as min_total,
    MAX(o_totalprice) as max_total
FROM orders

ORDER BY table_name;
```

### 2. Test Fixtures

**Reusable Test Components:**
```rust
// test_fixtures.rs
use duckdb::Connection;

pub struct TestDatabase {
    conn: Connection,
}

impl TestDatabase {
    pub fn new() -> Result<Self, Box<dyn std::error::Error>> {
        let conn = Connection::open_in_memory()?;
        Ok(Self { conn })
    }

    pub fn create_test_table(&self) -> Result<(), Box<dyn std::error::Error>> {
        self.conn.execute(
            "CREATE TABLE test (id INTEGER, name TEXT, value DECIMAL)",
            [],
        )?;
        Ok(())
    }

    pub fn insert_test_data(&self, count: i32) -> Result<(), Box<dyn std::error::Error>> {
        for i in 0..count {
            self.conn.execute(
                "INSERT INTO test VALUES (?, ?, ?)",
                [i, &format!("item_{}", i), (i as f64) * 1.5],
            )?;
        }
        Ok(())
    }

    pub fn get_connection(&self) -> &Connection {
        &self.conn
    }
}

// Usage in tests
#[test]
fn test_data_operations() {
    let db = TestDatabase::new().unwrap();
    db.create_test_table().unwrap();
    db.insert_test_data(100).unwrap();

    let count: i64 = db.get_connection()
        .query_row("SELECT COUNT(*) FROM test", [], |row| row.get(0))
        .unwrap();

    assert_eq!(count, 100);
}
```

## Test Execution Strategy

### 1. Local Testing

**Development Testing:**
```bash
# Quick unit tests during development
cargo test --lib

# Test specific modules
cargo test architecture
cargo test benchmark

# Test with verbose output
cargo test -- --nocapture

# Run specific test
cargo test test_detect_architecture
```

**Integration Testing:**
```bash
# Test all components together
cargo test --all

# Test with release build
cargo test --release --all

# Test with different architectures
ARCH=x86_64 source prebuilt/setup_env.sh && cargo test --all
ARCH=arm64 source prebuilt/setup_env.sh && cargo test --all
```

### 2. CI/CD Testing

**Automated Testing Pipeline:**
```yaml
# .github/workflows/test.yml
- name: Run tests multiple times
  run: |
    for i in {1..3}; do
      echo "Test run $i of 3"
      cargo test --all
    done

- name: Test with different configurations
  run: |
    cargo test --release --all
    ARCH=x86_64 source prebuilt/setup_env.sh && cargo test --all
    ARCH=arm64 source prebuilt/setup_env.sh && cargo test --all

- name: Performance validation
  run: |
    cargo test --test performance_tests
    # Validate build time requirements
```

### 3. Property-Based Testing

**Comprehensive Input Testing:**
```rust
proptest! {
    #[test]
    fn test_binary_validation_with_various_paths(
        lib_dir in "(/[a-zA-Z0-9/_-]+)",
        include_dir in "(/[a-zA-Z0-9/_-]+)"
    ) {
        std::env::set_var("DUCKDB_LIB_DIR", lib_dir);
        std::env::set_var("DUCKDB_INCLUDE_DIR", include_dir);

        // Test should handle various path formats gracefully
        let _ = validate_binary(); // Should not panic

        std::env::remove_var("DUCKDB_LIB_DIR");
        std::env::remove_var("DUCKDB_INCLUDE_DIR");
    }

    #[test]
    fn test_architecture_detection_robustness(input in ".*") {
        std::env::set_var("ARCH", input);

        // Should handle any input gracefully
        let arch = detect();
        assert!(!arch.is_empty());

        std::env::remove_var("ARCH");
    }
}
```

## Test Data Generation

### 1. Automated Test Data

**Test Data Generation Script:**
```bash
#!/bin/bash
# generate_test_data.sh

echo "🧪 Generating test datasets..."

# Generate Chinook dataset
frozen-duckdb download --dataset chinook --format parquet --output-dir test_data

# Generate TPC-H dataset
frozen-duckdb download --dataset tpch --format parquet --output-dir test_data

# Generate custom test data
duckdb test_data/custom.duckdb -c "
CREATE TABLE custom_test AS
SELECT
    id,
    'item_' || id as name,
    id * 1.5 as value,
    CASE WHEN id % 2 = 0 THEN 'even' ELSE 'odd' END as category
FROM generate_series(1, 1000) as id;
"

echo "✅ Test data generation complete"
ls -la test_data/
```

### 2. Test Data Validation

**Data Quality Checks:**
```sql
-- Validate generated datasets
CREATE TABLE data_quality_report AS

-- Chinook validation
SELECT
    'chinook' as dataset,
    'artists' as table_name,
    COUNT(*) as row_count,
    COUNT(DISTINCT ArtistId) as unique_ids,
    MIN(LENGTH(Name)) as min_name_length,
    MAX(LENGTH(Name)) as max_name_length
FROM 'test_data/chinook.parquet'

UNION ALL

-- TPC-H validation
SELECT
    'tpch' as dataset,
    'customer' as table_name,
    COUNT(*) as row_count,
    COUNT(DISTINCT c_custkey) as unique_ids,
    MIN(c_acctbal) as min_balance,
    MAX(c_acctbal) as max_balance
FROM 'test_data/customer.parquet'

ORDER BY dataset, table_name;
```

## Performance Testing

### 1. Build Performance Tests

**Build Time Validation:**
```rust
#[test]
fn test_build_time_requirements() {
    let duration = benchmark::measure_build_time(|| {
        // Simulate build operation
        std::thread::sleep(Duration::from_millis(50));
        Ok(())
    });

    // Validate against SLO
    assert!(
        duration.as_secs() < 10,
        "Build time exceeded 10s requirement: {:?}",
        duration
    );
}

#[test]
fn test_incremental_build_performance() {
    // Test that incremental builds are fast
    let first_build = benchmark::measure_build_time(|| Ok(()));
    let second_build = benchmark::measure_build_time(|| Ok(()));

    // Incremental should be much faster
    assert!(
        second_build < first_build,
        "Incremental build should be faster: {:?} vs {:?}",
        second_build, first_build
    );
}
```

### 2. Runtime Performance Tests

**Query Performance Validation:**
```rust
#[test]
fn test_query_performance_requirements() {
    let conn = Connection::open_in_memory().unwrap();

    // Setup test data
    conn.execute("CREATE TABLE perf_test (id INTEGER, data TEXT)", []).unwrap();
    for i in 0..10000 {
        conn.execute(
            "INSERT INTO perf_test VALUES (?, ?)",
            [i, &format!("data_{}", i)],
        ).unwrap();
    }

    // Test query performance
    let start = Instant::now();
    let count: i64 = conn.query_row("SELECT COUNT(*) FROM perf_test WHERE id > 5000", [], |row| row.get(0)).unwrap();
    let duration = start.elapsed();

    assert_eq!(count, 5000);
    assert!(
        duration.as_millis() < 100,
        "Query performance requirement not met: {:?}",
        duration
    );
}

#[test]
fn test_llm_performance_requirements() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

    // Test completion performance
    let start = Instant::now();
    let result: String = conn.query_row(
        "SELECT llm_complete({'model_name': 'test_coder'}, {'prompt_name': 'test_prompt', 'context_columns': [{'data': 'test'}]})",
        [],
        |row| row.get(0),
    ).unwrap();
    let duration = start.elapsed();

    assert!(!result.is_empty());
    assert!(
        duration.as_secs() < 10,
        "LLM operation too slow: {:?}",
        duration
    );
}
```

## Test Organization

### 1. Test Module Structure

**Library Tests:**
```
src/
├── lib.rs
│   └── tests for library entry point
├── architecture.rs
│   └── mod tests for architecture detection
├── benchmark.rs
│   └── mod tests for performance measurement
└── env_setup.rs
    └── mod tests for environment validation
```

**Integration Tests:**
```
tests/
├── core_functionality_tests.rs    # Core DuckDB operations
├── arrow_tests.rs                # Arrow integration
├── parquet_tests.rs              # Parquet integration
├── polars_tests.rs               # Polars integration
├── flock_tests.rs                # LLM/Flock extension
├── vss_tests.rs                  # Vector similarity search
└── tpch_integration_test.rs      # TPC-H benchmark tests
```

### 2. Test Naming Conventions

**Unit Tests:**
```rust
#[test]
fn test_function_name() {
    // Test specific function
}

#[test]
fn test_error_condition() {
    // Test error handling
}

#[test]
fn test_edge_case() {
    // Test boundary conditions
}
```

**Integration Tests:**
```rust
#[test]
fn test_component_integration() {
    // Test multiple components working together
}

#[test]
fn test_end_to_end_workflow() {
    // Test complete user workflows
}

#[test]
fn test_performance_integration() {
    // Test performance across integrated components
}
```

## Test Coverage Requirements

### 1. Code Coverage

**Coverage Targets:**
- **Core library**: >90% coverage
- **CLI functionality**: >85% coverage
- **LLM integration**: >80% coverage (considering external dependencies)
- **Error paths**: >95% coverage

**Coverage Measurement:**
```bash
# Install coverage tools
cargo install cargo-llvm-cov

# Generate coverage report
cargo llvm-cov --all --lcov --output-path coverage.lcov

# View coverage report
cargo llvm-cov --all --html

# Check coverage thresholds
cargo llvm-cov --all --text | grep -E "(Total|Functions|Lines|Branches)"
```

### 2. Test Scenarios

**Core Functionality:**
- [ ] Architecture detection on all supported platforms
- [ ] Environment validation with various configurations
- [ ] Binary validation with missing/corrupted files
- [ ] Performance measurement accuracy
- [ ] Error handling for all failure modes

**Integration Scenarios:**
- [ ] End-to-end dataset generation and usage
- [ ] Format conversion between all supported types
- [ ] LLM operations with various models and prompts
- [ ] Cross-component interactions
- [ ] Performance across different architectures

**Edge Cases:**
- [ ] Empty inputs and outputs
- [ ] Very large datasets
- [ ] Network failures and timeouts
- [ ] Disk space limitations
- [ ] Permission restrictions

## Flaky Test Detection

### 1. Multiple Run Strategy

**Core Team Requirement:**
```bash
# Run tests multiple times to detect flakiness
for run in {1..3}; do
    echo "=== Test Run $run ==="
    cargo test --all
    echo "=== End Run $run ==="
done
```

**Automated Flaky Detection:**
```bash
#!/bin/bash
# detect_flaky_tests.sh

TEST_RESULTS=()

# Run tests multiple times
for i in {1..5}; do
    echo "Test run $i of 5"
    if cargo test --all --quiet; then
        TEST_RESULTS+=("PASS")
    else
        TEST_RESULTS+=("FAIL")
    fi
done

# Analyze results for flakiness
PASS_COUNT=$(echo "${TEST_RESULTS[@]}" | tr ' ' '\n' | grep -c "PASS")
FAIL_COUNT=$(echo "${TEST_RESULTS[@]}" | tr ' ' '\n' | grep -c "FAIL")

echo "Results: $PASS_COUNT passes, $FAIL_COUNT failures out of 5 runs"

if (( FAIL_COUNT > 0 && PASS_COUNT > 0 )); then
    echo "⚠️  Potential flaky tests detected!"
    echo "   Consider investigating test reliability"
fi
```

### 2. Test Stability Metrics

**Test Execution Tracking:**
```sql
-- Track test execution stability
CREATE TABLE test_execution_log (
    test_name TEXT,
    execution_time_ms INTEGER,
    result TEXT, -- 'PASS' or 'FAIL'
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    run_id INTEGER
);

-- Log test execution
INSERT INTO test_execution_log (test_name, execution_time_ms, result, run_id)
SELECT
    'test_detect_architecture' as test_name,
    5 as execution_time_ms,
    'PASS' as result,
    1 as run_id;
```

## Error Testing Strategy

### 1. Error Condition Coverage

**Comprehensive Error Testing:**
```rust
#[test]
fn test_error_conditions() {
    // Test missing environment variables
    std::env::remove_var("DUCKDB_LIB_DIR");
    assert!(!is_configured());

    // Test invalid binary paths
    std::env::set_var("DUCKDB_LIB_DIR", "/nonexistent/path");
    assert!(validate_binary().is_err());
    std::env::remove_var("DUCKDB_LIB_DIR");

    // Test network failures (LLM operations)
    // Mock network failure and verify graceful handling

    // Test malformed inputs
    let result = validate_binary_with_malformed_input();
    assert!(result.is_err());
}
```

### 2. Error Message Quality

**Actionable Error Messages:**
```rust
#[test]
fn test_error_message_quality() {
    // Test that error messages are actionable
    std::env::set_var("DUCKDB_LIB_DIR", "/nonexistent");
    let result = validate_binary();
    std::env::remove_var("DUCKDB_LIB_DIR");

    assert!(result.is_err());
    let error_msg = format!("{}", result.unwrap_err());

    // Error message should be actionable
    assert!(error_msg.contains("DUCKDB_LIB_DIR"));
    assert!(error_msg.contains("setup_env.sh"));
    assert!(error_msg.to_lowercase().contains("run"));
}
```

## Performance Testing

### 1. Build Performance Tests

**Build Time Validation:**
```rust
#[test]
fn test_build_performance_slo() {
    // Test first build performance
    let first_build = benchmark::measure_build_time(|| {
        // Simulate first build (heavier)
        std::thread::sleep(Duration::from_secs(8));
        Ok(())
    });

    assert!(
        first_build.as_secs() < 10,
        "First build exceeded 10s SLO: {:?}",
        first_build
    );

    // Test incremental build performance
    let incremental_build = benchmark::measure_build_time(|| {
        // Simulate incremental build (lighter)
        std::thread::sleep(Duration::from_millis(100));
        Ok(())
    });

    assert!(
        incremental_build.as_millis() < 1000,
        "Incremental build exceeded 1s SLO: {:?}",
        incremental_build
    );
}
```

### 2. Runtime Performance Tests

**Query Performance:**
```rust
#[test]
fn test_query_performance_requirements() {
    let conn = Connection::open_in_memory().unwrap();

    // Setup large dataset
    conn.execute("CREATE TABLE large_test (id INTEGER, data TEXT)", []).unwrap();
    for i in 0..100000 {
        conn.execute(
            "INSERT INTO large_test VALUES (?, ?)",
            [i, &format!("data_{}", i)],
        ).unwrap();
    }

    // Test complex query performance
    let start = Instant::now();
    let result: i64 = conn.query_row(
        "SELECT COUNT(*) FROM large_test WHERE id > 50000 AND LENGTH(data) > 8",
        [],
        |row| row.get(0),
    ).unwrap();
    let duration = start.elapsed();

    assert_eq!(result, 25000);
    assert!(
        duration.as_millis() < 200,
        "Query performance requirement not met: {:?}",
        duration
    );
}
```

## LLM Testing Strategy

### 1. Flock Extension Testing

**Extension Loading Tests:**
```rust
#[test]
fn test_flock_extension_loading() {
    let conn = Connection::open_in_memory().unwrap();

    // Test extension installation
    conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

    // Verify extension loaded
    let extension: String = conn.query_row(
        "SELECT extension_name FROM duckdb_extensions() WHERE extension_name = 'flock'",
        [],
        |row| row.get(0),
    ).unwrap();

    assert_eq!(extension, "flock");
}

#[test]
fn test_ollama_secret_creation() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

    // Test secret creation
    conn.execute(
        "CREATE SECRET ollama_secret (TYPE OLLAMA, API_URL 'http://localhost:11434')",
        [],
    ).unwrap();

    // Verify secret exists
    let secret_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM duckdb_secrets() WHERE secret_name = 'ollama_secret'",
        [],
        |row| row.get(0),
    ).unwrap();

    assert_eq!(secret_count, 1);
}
```

### 2. Model Management Tests

**Model Creation Tests:**
```rust
#[test]
fn test_model_creation() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

    // Create test models
    conn.execute("CREATE MODEL('test_coder', 'qwen3-coder:30b', 'ollama')", []).unwrap();
    conn.execute("CREATE MODEL('test_embedder', 'qwen3-embedding:8b', 'ollama')", []).unwrap();

    // Verify models exist
    let model_count: i64 = conn.query_row(
        "SELECT COUNT(*) FROM duckdb_models()",
        [],
        |row| row.get(0),
    ).unwrap();

    assert_eq!(model_count, 2);
}
```

### 3. LLM Operation Tests

**Text Completion Tests:**
```rust
#[test]
fn test_llm_completion() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

    // Setup minimal test environment
    conn.execute("CREATE MODEL('test_coder', 'qwen3-coder:7b', 'ollama')", []).unwrap();
    conn.execute("CREATE PROMPT('test_prompt', 'Complete: {{text}}')", []).unwrap();

    // Test completion
    let result: String = conn.query_row(
        "SELECT llm_complete({'model_name': 'test_coder'}, {'prompt_name': 'test_prompt', 'context_columns': [{'data': 'Hello'}]})",
        [],
        |row| row.get(0),
    ).unwrap();

    // Basic validation
    assert!(!result.is_empty());
    assert!(result.to_lowercase().contains("hello"));
}

#[test]
fn test_embedding_generation() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch("INSTALL flock FROM community; LOAD flock;").unwrap();

    // Create embedding model
    conn.execute("CREATE MODEL('test_embedder', 'qwen3-embedding:8b', 'ollama')", []).unwrap();

    // Test embedding generation
    let embedding: Vec<f32> = conn.query_row(
        "SELECT llm_embedding({'model_name': 'test_embedder'}, [{'data': 'test text'}])",
        [],
        |row| {
            let embedding_str: String = row.get(0).unwrap();
            serde_json::from_str(&embedding_str).unwrap_or_default()
        },
    ).unwrap();

    // Validate embedding properties
    assert_eq!(embedding.len(), 1024);
    assert!(embedding.iter().all(|&x| x.is_finite()));
}
```

## Test Maintenance

### 1. Test Data Updates

**Regular Test Data Refresh:**
```bash
#!/bin/bash
# refresh_test_data.sh

echo "🔄 Refreshing test datasets..."

# Update Chinook dataset
frozen-duckdb download --dataset chinook --format parquet --output-dir test_data

# Update TPC-H dataset
frozen-duckdb download --dataset tpch --format parquet --output-dir test_data

# Validate updated data
duckdb test_data/chinook.duckdb -c "
SELECT 'Chinook' as dataset, COUNT(*) as tracks FROM tracks;
"

duckdb test_data/tpch.duckdb -c "
SELECT 'TPC-H' as dataset, COUNT(*) as customers FROM customer;
"

echo "✅ Test data refresh complete"
```

### 2. Test Performance Monitoring

**Performance Regression Detection:**
```sql
-- Track test performance over time
CREATE TABLE test_performance_history (
    test_name TEXT,
    execution_time_ms INTEGER,
    memory_usage_mb INTEGER,
    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Log test performance
INSERT INTO test_performance_history (test_name, execution_time_ms, memory_usage_mb)
SELECT
    'test_large_dataset_query' as test_name,
    150 as execution_time_ms,
    200 as memory_usage_mb;
```

## Summary

The testing strategy for Frozen DuckDB ensures **comprehensive validation** of **functionality**, **performance**, and **reliability** through **multiple test categories**, **property-based testing**, and **performance validation**. The strategy follows **core team requirements** for **multiple test runs** and **performance SLO validation**.

**Key Testing Components:**
- **Unit tests**: Individual function and module testing
- **Integration tests**: End-to-end component interaction testing
- **Property tests**: Comprehensive input validation with generated data
- **Performance tests**: SLO validation and regression detection
- **LLM tests**: Flock extension and Ollama integration testing

**Testing Best Practices:**
- **Multiple runs**: Catch flaky behavior through repeated execution
- **Configuration testing**: Validate across different environments and architectures
- **Performance validation**: Ensure SLO requirements are consistently met
- **Error coverage**: Comprehensive testing of all failure modes

**Quality Assurance:**
- **High coverage targets**: >90% for core functionality
- **Flaky test detection**: Automated identification of unreliable tests
- **Performance monitoring**: Track and prevent performance regressions
- **Error message quality**: Actionable guidance for troubleshooting

**Next Steps:**
1. Implement the testing patterns described in this guide
2. Set up automated flaky test detection in CI/CD
3. Establish performance baselines for regression detection
4. Review the [Coding Standards Guide]./coding-standards.md for code quality requirements