query-flow 0.17.0

A high-level query framework built on whale for incremental computation.
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
//! Tests for QueryError::UserError functionality.

use query_flow::{query, Db, QueryError, QueryRuntime};

// =============================================================================
// Basic Error Conversion Tests
// =============================================================================

#[test]
fn test_user_error_from_io_error() {
    let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
    // Convert via anyhow::Error
    let query_err: QueryError = anyhow::Error::from(io_err).into();

    assert!(matches!(query_err, QueryError::UserError(_)));
    assert!(query_err.to_string().contains("file not found"));
}

#[test]
fn test_user_error_from_anyhow() {
    let anyhow_err = anyhow::anyhow!("something went wrong");
    let query_err: QueryError = anyhow_err.into();

    assert!(matches!(query_err, QueryError::UserError(_)));
    assert!(query_err.to_string().contains("something went wrong"));
}

#[derive(Debug, Clone, PartialEq)]
struct CustomError {
    code: i32,
    message: String,
}

impl std::fmt::Display for CustomError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "CustomError({}): {}", self.code, self.message)
    }
}

impl std::error::Error for CustomError {}

#[test]
fn test_user_error_from_custom_error() {
    let custom_err = CustomError {
        code: 42,
        message: "custom error".to_string(),
    };
    // Convert via anyhow::Error
    let query_err: QueryError = anyhow::Error::from(custom_err).into();

    assert!(matches!(query_err, QueryError::UserError(_)));
    assert!(query_err.to_string().contains("custom error"));
}

// =============================================================================
// Question Mark Operator Tests
// =============================================================================

#[query]
fn parse_number(db: &impl Db, input: String) -> Result<i32, QueryError> {
    let _ = db;
    // The ? operator converts ParseIntError to QueryError::UserError automatically
    let num: i32 = input.parse()?;
    Ok(num)
}

#[test]
fn test_question_mark_propagation_success() {
    let runtime = QueryRuntime::new();
    let result = runtime.query(ParseNumber::new("42".to_string()));
    assert_eq!(*result.unwrap(), 42);
}

#[test]
fn test_question_mark_propagation_error() {
    let runtime = QueryRuntime::new();
    let result = runtime.query(ParseNumber::new("not_a_number".to_string()));

    match result {
        Err(QueryError::UserError(e)) => {
            assert!(e.to_string().contains("invalid digit"));
        }
        other => panic!("Expected UserError, got {:?}", other),
    }
}

#[query]
fn fallible_io(db: &impl Db, should_fail: bool) -> Result<String, QueryError> {
    let _ = db;
    if should_fail {
        return Err(anyhow::anyhow!("not found").into());
    }
    Ok("success".to_string())
}

#[test]
fn test_io_error_propagation() {
    let runtime = QueryRuntime::new();

    // Success case
    let result = runtime.query(FallibleIo::new(false));
    assert_eq!(*result.unwrap(), "success");

    // Error case
    let result = runtime.query(FallibleIo::new(true));
    assert!(matches!(result, Err(QueryError::UserError(_))));
}

// =============================================================================
// Error Caching Tests (in separate modules to avoid static variable conflicts)
// =============================================================================

mod error_caching_error {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static FALLIBLE_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    #[query]
    fn fallible_cached(db: &impl Db, id: u32) -> Result<i32, QueryError> {
        let _ = db;
        FALLIBLE_CALL_COUNT.fetch_add(1, Ordering::SeqCst);

        if id == 0 {
            return Err(anyhow::anyhow!("id cannot be zero").into());
        }
        Ok(id as i32 * 10)
    }

    #[test]
    fn test_user_error_cached() {
        FALLIBLE_CALL_COUNT.store(0, Ordering::SeqCst);
        let runtime = QueryRuntime::new();

        // First call - executes query, returns error
        let result1 = runtime.query(FallibleCached::new(0));
        assert!(matches!(result1, Err(QueryError::UserError(_))));
        assert_eq!(FALLIBLE_CALL_COUNT.load(Ordering::SeqCst), 1);

        // Second call - should return cached error
        let result2 = runtime.query(FallibleCached::new(0));
        assert!(matches!(result2, Err(QueryError::UserError(_))));
        assert_eq!(FALLIBLE_CALL_COUNT.load(Ordering::SeqCst), 1); // Still 1, not recomputed
    }
}

mod error_caching_success {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static FALLIBLE_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    #[query]
    fn fallible_cached(db: &impl Db, id: u32) -> Result<i32, QueryError> {
        let _ = db;
        FALLIBLE_CALL_COUNT.fetch_add(1, Ordering::SeqCst);

        if id == 0 {
            return Err(anyhow::anyhow!("id cannot be zero").into());
        }
        Ok(id as i32 * 10)
    }

    #[test]
    fn test_success_cached() {
        FALLIBLE_CALL_COUNT.store(0, Ordering::SeqCst);
        let runtime = QueryRuntime::new();

        // First call
        let result1 = runtime.query(FallibleCached::new(5));
        assert_eq!(*result1.unwrap(), 50);
        assert_eq!(FALLIBLE_CALL_COUNT.load(Ordering::SeqCst), 1);

        // Second call - should return cached
        let result2 = runtime.query(FallibleCached::new(5));
        assert_eq!(*result2.unwrap(), 50);
        assert_eq!(FALLIBLE_CALL_COUNT.load(Ordering::SeqCst), 1); // Still 1
    }
}

// =============================================================================
// Error Comparator Tests (in separate modules to avoid static variable conflicts)
// =============================================================================

mod error_comparator_default {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static ERROR_LEVEL1_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static ERROR_LEVEL2_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static ERROR_LEVEL3_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    /// Level 1: Base query that may return an error
    #[query]
    fn error_level1(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        let _ = db;
        ERROR_LEVEL1_CALL_COUNT.fetch_add(1, Ordering::SeqCst);

        if code < 0 {
            return Err(CustomError {
                code,
                message: "negative code".to_string(),
            }
            .into());
        }
        Ok(code * 2)
    }

    /// Level 2: Depends on Level 1
    #[query]
    fn error_level2(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        ERROR_LEVEL2_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let base = db.query(ErrorLevel1::new(code))?;
        Ok(*base + 1)
    }

    /// Level 3: Depends on Level 2 (transitively on Level 1)
    #[query]
    fn error_level3(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        ERROR_LEVEL3_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let base = db.query(ErrorLevel2::new(code))?;
        Ok(*base + 10)
    }

    #[test]
    fn test_error_comparator_default_false() {
        // Default comparator returns false, so errors are always "different"
        // This means all downstream queries will be recomputed
        ERROR_LEVEL1_CALL_COUNT.store(0, Ordering::SeqCst);
        ERROR_LEVEL2_CALL_COUNT.store(0, Ordering::SeqCst);
        ERROR_LEVEL3_CALL_COUNT.store(0, Ordering::SeqCst);

        let runtime = QueryRuntime::new();

        // First call through Level 3 -> Level 2 -> Level 1
        let result1 = runtime.query(ErrorLevel3::new(-1));
        assert!(matches!(result1, Err(QueryError::UserError(_))));
        assert_eq!(ERROR_LEVEL1_CALL_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(ERROR_LEVEL2_CALL_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(ERROR_LEVEL3_CALL_COUNT.load(Ordering::SeqCst), 1);

        // Invalidate Level 1 and rerun Level 3
        runtime.invalidate(&ErrorLevel1::new(-1));

        let result2 = runtime.query(ErrorLevel3::new(-1));
        assert!(matches!(result2, Err(QueryError::UserError(_))));
        // Level 1 is recomputed
        assert_eq!(ERROR_LEVEL1_CALL_COUNT.load(Ordering::SeqCst), 2);
        // With default comparator (always different), Level 2 is also recomputed
        assert_eq!(ERROR_LEVEL2_CALL_COUNT.load(Ordering::SeqCst), 2);
        // Level 3 is also recomputed
        assert_eq!(ERROR_LEVEL3_CALL_COUNT.load(Ordering::SeqCst), 2);
    }
}

mod error_comparator_custom {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static ERROR_LEVEL1_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static ERROR_LEVEL2_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static ERROR_LEVEL3_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    /// Level 1: Base query that may return an error
    #[query]
    fn error_level1(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        let _ = db;
        ERROR_LEVEL1_CALL_COUNT.fetch_add(1, Ordering::SeqCst);

        if code < 0 {
            return Err(CustomError {
                code,
                message: "negative code".to_string(),
            }
            .into());
        }
        Ok(code * 2)
    }

    /// Level 2: Depends on Level 1
    #[query]
    fn error_level2(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        ERROR_LEVEL2_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let base = db.query(ErrorLevel1::new(code))?;
        Ok(*base + 1)
    }

    /// Level 3: Depends on Level 2 (transitively on Level 1)
    #[query]
    fn error_level3(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        ERROR_LEVEL3_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let base = db.query(ErrorLevel2::new(code))?;
        Ok(*base + 10)
    }

    #[test]
    fn test_error_comparator_custom() {
        // Custom comparator that considers CustomErrors equal if they have the same code
        // With early cutoff, downstream queries should NOT be recomputed
        ERROR_LEVEL1_CALL_COUNT.store(0, Ordering::SeqCst);
        ERROR_LEVEL2_CALL_COUNT.store(0, Ordering::SeqCst);
        ERROR_LEVEL3_CALL_COUNT.store(0, Ordering::SeqCst);

        let runtime = QueryRuntime::builder()
            .error_comparator(|a, b| {
                match (
                    a.downcast_ref::<CustomError>(),
                    b.downcast_ref::<CustomError>(),
                ) {
                    (Some(a), Some(b)) => a.code == b.code,
                    _ => false,
                }
            })
            .build();

        // First call through Level 3 -> Level 2 -> Level 1
        let result1 = runtime.query(ErrorLevel3::new(-1));
        assert!(matches!(result1, Err(QueryError::UserError(_))));
        assert_eq!(ERROR_LEVEL1_CALL_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(ERROR_LEVEL2_CALL_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(ERROR_LEVEL3_CALL_COUNT.load(Ordering::SeqCst), 1);

        // Invalidate Level 1 and rerun Level 3
        runtime.invalidate(&ErrorLevel1::new(-1));

        let result2 = runtime.query(ErrorLevel3::new(-1));
        assert!(matches!(result2, Err(QueryError::UserError(_))));
        // Level 1 is recomputed
        assert_eq!(ERROR_LEVEL1_CALL_COUNT.load(Ordering::SeqCst), 2);
        // With custom comparator, same error means Level 2 gets early cutoff
        // Level 2 is still checked (executed), but since Level 1 returned same error,
        // its downstream (Level 3) should benefit from early cutoff
        // Note: Level 2 is executed because we need to verify its output hasn't changed
        assert_eq!(ERROR_LEVEL2_CALL_COUNT.load(Ordering::SeqCst), 2);
        // Level 3 benefits from early cutoff (Level 2's error is unchanged)
        assert_eq!(ERROR_LEVEL3_CALL_COUNT.load(Ordering::SeqCst), 1);
    }
}

mod error_comparator_always_equal {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static ERROR_LEVEL1_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static ERROR_LEVEL2_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static ERROR_LEVEL3_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    /// Level 1: Base query that may return an error
    #[query]
    fn error_level1(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        let _ = db;
        ERROR_LEVEL1_CALL_COUNT.fetch_add(1, Ordering::SeqCst);

        if code < 0 {
            return Err(CustomError {
                code,
                message: "negative code".to_string(),
            }
            .into());
        }
        Ok(code * 2)
    }

    /// Level 2: Depends on Level 1
    #[query]
    fn error_level2(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        ERROR_LEVEL2_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let base = db.query(ErrorLevel1::new(code))?;
        Ok(*base + 1)
    }

    /// Level 3: Depends on Level 2 (transitively on Level 1)
    #[query]
    fn error_level3(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        ERROR_LEVEL3_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let base = db.query(ErrorLevel2::new(code))?;
        Ok(*base + 10)
    }

    #[test]
    fn test_error_comparator_always_equal() {
        // Comparator that treats all errors as equal
        // With 3-level chain, early cutoff at Level 2 should prevent Level 3 recomputation
        ERROR_LEVEL1_CALL_COUNT.store(0, Ordering::SeqCst);
        ERROR_LEVEL2_CALL_COUNT.store(0, Ordering::SeqCst);
        ERROR_LEVEL3_CALL_COUNT.store(0, Ordering::SeqCst);

        let runtime = QueryRuntime::builder()
            .error_comparator(|_, _| true)
            .build();

        // First call through Level 3 -> Level 2 -> Level 1
        let result1 = runtime.query(ErrorLevel3::new(-1));
        assert!(matches!(result1, Err(QueryError::UserError(_))));
        assert_eq!(ERROR_LEVEL1_CALL_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(ERROR_LEVEL2_CALL_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(ERROR_LEVEL3_CALL_COUNT.load(Ordering::SeqCst), 1);

        // Invalidate Level 1 and rerun Level 3
        runtime.invalidate(&ErrorLevel1::new(-1));

        let result2 = runtime.query(ErrorLevel3::new(-1));
        assert!(matches!(result2, Err(QueryError::UserError(_))));

        // Level 1 is recomputed
        assert_eq!(ERROR_LEVEL1_CALL_COUNT.load(Ordering::SeqCst), 2);
        // Level 2 is executed to verify its output
        assert_eq!(ERROR_LEVEL2_CALL_COUNT.load(Ordering::SeqCst), 2);
        // Level 3 benefits from early cutoff (all errors are "equal")
        assert_eq!(ERROR_LEVEL3_CALL_COUNT.load(Ordering::SeqCst), 1);
    }
}

// =============================================================================
// Mixed Ok/Error Chain Tests
// =============================================================================

mod mixed_chain {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static MIXED_BASE_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static MIXED_MIDDLE_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static MIXED_TOP_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    #[query]
    fn mixed_base(db: &impl Db, value: i32) -> Result<i32, QueryError> {
        let _ = db;
        MIXED_BASE_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        Ok(value * 2)
    }

    #[query]
    fn mixed_middle(db: &impl Db, value: i32) -> Result<i32, QueryError> {
        MIXED_MIDDLE_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let base = db.query(MixedBase::new(value))?;

        if *base > 100 {
            return Err(anyhow::anyhow!("value too large: {}", base).into());
        }
        Ok(*base + 10)
    }

    #[query]
    fn mixed_top(db: &impl Db, value: i32) -> Result<String, QueryError> {
        MIXED_TOP_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let middle = db.query(MixedMiddle::new(value))?;
        Ok(format!("result: {}", middle))
    }

    #[test]
    fn test_mixed_ok_and_error_chain() {
        MIXED_BASE_CALL_COUNT.store(0, Ordering::SeqCst);
        MIXED_MIDDLE_CALL_COUNT.store(0, Ordering::SeqCst);
        MIXED_TOP_CALL_COUNT.store(0, Ordering::SeqCst);

        let runtime = QueryRuntime::new();

        // Success path
        let result = runtime.query(MixedTop::new(10));
        assert_eq!(*result.unwrap(), "result: 30"); // 10 * 2 + 10 = 30

        // Error path
        let result = runtime.query(MixedTop::new(100));
        match result {
            Err(QueryError::UserError(e)) => {
                assert!(e.to_string().contains("value too large"));
            }
            other => panic!("Expected UserError, got {:?}", other),
        }
    }
}

// =============================================================================
// Error Downcast Tests
// =============================================================================

mod error_downcast {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static ERROR_LEVEL1_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    /// Level 1: Base query that may return an error
    #[query]
    fn error_level1(db: &impl Db, code: i32) -> Result<i32, QueryError> {
        let _ = db;
        ERROR_LEVEL1_CALL_COUNT.fetch_add(1, Ordering::SeqCst);

        if code < 0 {
            return Err(CustomError {
                code,
                message: "negative code".to_string(),
            }
            .into());
        }
        Ok(code * 2)
    }

    #[test]
    fn test_error_downcast() {
        let runtime = QueryRuntime::new();

        // Create error with CustomError using ErrorLevel1
        let result = runtime.query(ErrorLevel1::new(-42));

        match result {
            Err(QueryError::UserError(e)) => {
                // Downcast to original error type
                let custom = e.downcast_ref::<CustomError>();
                assert!(custom.is_some());
                let custom = custom.unwrap();
                assert_eq!(custom.code, -42);
                assert_eq!(custom.message, "negative code");
            }
            other => panic!("Expected UserError, got {:?}", other),
        }
    }
}

// =============================================================================
// Transition Tests (Ok -> Error, Error -> Ok)
// =============================================================================

mod transition_ok_to_error {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static TRANSITION_VALUE: AtomicU32 = AtomicU32::new(10);
    static TRANSITION_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static TRANSITION_DEPENDENT_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    #[query]
    fn transition_source(db: &impl Db) -> Result<i32, QueryError> {
        let _ = db;
        TRANSITION_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let value = TRANSITION_VALUE.load(Ordering::SeqCst) as i32;

        if value < 0 {
            return Err(anyhow::anyhow!("negative value").into());
        }
        Ok(value)
    }

    #[query]
    fn transition_dependent(db: &impl Db) -> Result<i32, QueryError> {
        TRANSITION_DEPENDENT_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let source = db.query(TransitionSource::new())?;
        Ok(*source * 2)
    }

    #[test]
    fn test_ok_to_error_transition() {
        TRANSITION_VALUE.store(10, Ordering::SeqCst);
        TRANSITION_CALL_COUNT.store(0, Ordering::SeqCst);
        TRANSITION_DEPENDENT_CALL_COUNT.store(0, Ordering::SeqCst);

        let runtime = QueryRuntime::new();

        // Start with Ok
        let result = runtime.query(TransitionDependent::new());
        assert_eq!(*result.unwrap(), 20);
        assert_eq!(TRANSITION_CALL_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(TRANSITION_DEPENDENT_CALL_COUNT.load(Ordering::SeqCst), 1);

        // Change to error state
        TRANSITION_VALUE.store(u32::MAX, Ordering::SeqCst); // Will be -1 as i32
        runtime.invalidate(&TransitionSource {});

        // Should now get error
        let result = runtime.query(TransitionDependent::new());
        assert!(matches!(result, Err(QueryError::UserError(_))));
        assert_eq!(TRANSITION_CALL_COUNT.load(Ordering::SeqCst), 2);
        assert_eq!(TRANSITION_DEPENDENT_CALL_COUNT.load(Ordering::SeqCst), 2);
    }
}

mod transition_error_to_ok {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static TRANSITION_VALUE: AtomicU32 = AtomicU32::new(10);
    static TRANSITION_CALL_COUNT: AtomicU32 = AtomicU32::new(0);
    static TRANSITION_DEPENDENT_CALL_COUNT: AtomicU32 = AtomicU32::new(0);

    #[query]
    fn transition_source(db: &impl Db) -> Result<i32, QueryError> {
        let _ = db;
        TRANSITION_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let value = TRANSITION_VALUE.load(Ordering::SeqCst) as i32;

        if value < 0 {
            return Err(anyhow::anyhow!("negative value").into());
        }
        Ok(value)
    }

    #[query]
    fn transition_dependent(db: &impl Db) -> Result<i32, QueryError> {
        TRANSITION_DEPENDENT_CALL_COUNT.fetch_add(1, Ordering::SeqCst);
        let source = db.query(TransitionSource::new())?;
        Ok(*source * 2)
    }

    #[test]
    fn test_error_to_ok_transition() {
        TRANSITION_VALUE.store(u32::MAX, Ordering::SeqCst); // -1 as i32, will error
        TRANSITION_CALL_COUNT.store(0, Ordering::SeqCst);
        TRANSITION_DEPENDENT_CALL_COUNT.store(0, Ordering::SeqCst);

        let runtime = QueryRuntime::new();

        // Start with error
        let result = runtime.query(TransitionDependent::new());
        assert!(matches!(result, Err(QueryError::UserError(_))));

        // Change to Ok state
        TRANSITION_VALUE.store(5, Ordering::SeqCst);
        runtime.invalidate(&TransitionSource {});

        // Should now get Ok
        let result = runtime.query(TransitionDependent::new());
        assert_eq!(*result.unwrap(), 10);
    }
}

// =============================================================================
// Error Display and Source Tests
// =============================================================================

#[test]
fn test_error_display() {
    let err: QueryError = anyhow::Error::from(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        "test error",
    ))
    .into();
    let display = err.to_string();
    assert!(display.contains("user error"));
    assert!(display.contains("test error"));
}

#[test]
fn test_error_source() {
    // Create an error chain using anyhow context
    let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "original error");
    let anyhow_err = anyhow::Error::from(io_err).context("wrapped error");
    let _query_err: QueryError = anyhow_err.into();

    // QueryError::UserError with context should have a source
    // let source = query_err.source();
    // assert!(source.is_some());
}

// =============================================================================
// QueryResultExt and downcast_err Tests
// =============================================================================

mod downcast_err_tests {
    use query_flow::{query, Db, QueryError, QueryResultExt, QueryRuntime};

    #[derive(Debug, Clone, PartialEq)]
    struct MyError {
        code: i32,
        message: String,
    }

    impl std::fmt::Display for MyError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "MyError({}): {}", self.code, self.message)
        }
    }

    impl std::error::Error for MyError {}

    #[derive(Debug, Clone, PartialEq)]
    struct OtherError {
        reason: String,
    }

    impl std::fmt::Display for OtherError {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            write!(f, "OtherError: {}", self.reason)
        }
    }

    impl std::error::Error for OtherError {}

    #[query]
    fn may_fail(db: &impl Db, code: i32) -> Result<String, QueryError> {
        let _ = db;
        if code < 0 {
            return Err(MyError {
                code,
                message: "negative code".to_string(),
            }
            .into());
        }
        if code == 0 {
            return Err(OtherError {
                reason: "zero is not allowed".to_string(),
            }
            .into());
        }
        Ok(format!("success: {}", code))
    }

    #[test]
    fn test_downcast_err_success() {
        let runtime = QueryRuntime::new();
        let result = runtime.query(MayFail::new(42)).downcast_err::<MyError>();

        // Should be Ok(Ok(value))
        let inner = result.expect("should not be system error");
        let value = inner.expect("should be success");
        assert_eq!(*value, "success: 42");
    }

    #[test]
    fn test_downcast_err_matching_error() {
        let runtime = QueryRuntime::new();
        let result = runtime.query(MayFail::new(-1)).downcast_err::<MyError>();

        // Should be Ok(Err(TypedErr<MyError>))
        let inner = result.expect("should not be system error");
        let typed_err = inner.expect_err("should be user error");

        // TypedErr derefs to MyError
        assert_eq!(typed_err.code, -1);
        assert_eq!(typed_err.message, "negative code");

        // Also works with explicit get()
        assert_eq!(typed_err.get().code, -1);
    }

    #[test]
    fn test_downcast_err_non_matching_error() {
        let runtime = QueryRuntime::new();
        let result = runtime.query(MayFail::new(0)).downcast_err::<MyError>();

        // Should be Err(QueryError::UserError) because OtherError != MyError
        let err = result.expect_err("should return error for non-matching type");
        assert!(matches!(err, QueryError::UserError(_)));
        assert!(err.to_string().contains("zero is not allowed"));
    }

    #[test]
    fn test_downcast_err_with_question_mark() {
        fn handle_query(runtime: &QueryRuntime) -> Result<String, QueryError> {
            let result = runtime.query(MayFail::new(-5)).downcast_err::<MyError>()?;

            match result {
                Ok(value) => Ok(format!("got value: {}", value)),
                Err(my_err) => Ok(format!("handled MyError with code {}", my_err.code)),
            }
        }

        let runtime = QueryRuntime::new();
        let result = handle_query(&runtime);
        assert_eq!(result.unwrap(), "handled MyError with code -5");
    }

    #[test]
    fn test_downcast_err_propagate_non_matching() {
        fn handle_query(runtime: &QueryRuntime) -> Result<String, QueryError> {
            // This will propagate OtherError as QueryError since it doesn't match MyError
            let result = runtime.query(MayFail::new(0)).downcast_err::<MyError>()?;

            match result {
                Ok(value) => Ok(format!("got value: {}", value)),
                Err(my_err) => Ok(format!("handled MyError with code {}", my_err.code)),
            }
        }

        let runtime = QueryRuntime::new();
        let result = handle_query(&runtime);

        // Should propagate as error
        let err = result.expect_err("should propagate non-matching error");
        assert!(err.to_string().contains("zero is not allowed"));
    }

    #[test]
    fn test_downcast_err_map_err_pattern() {
        fn handle_query(runtime: &QueryRuntime, code: i32) -> Result<String, String> {
            let result = runtime
                .query(MayFail::new(code))
                .downcast_err::<MyError>()
                .map_err(|e| format!("system or other error: {}", e))?;

            match result {
                Ok(value) => Ok((*value).clone()),
                Err(e) => Err(format!("MyError: code={}", e.code)),
            }
        }

        let runtime = QueryRuntime::new();

        // Success case
        assert_eq!(handle_query(&runtime, 10).unwrap(), "success: 10");

        // MyError case - handled via map_err
        assert_eq!(handle_query(&runtime, -1).unwrap_err(), "MyError: code=-1");

        // OtherError case - propagated as system error
        assert!(handle_query(&runtime, 0)
            .unwrap_err()
            .contains("system or other error"));
    }

    #[test]
    fn test_typed_err_display_and_debug() {
        let runtime = QueryRuntime::new();
        let result = runtime.query(MayFail::new(-42)).downcast_err::<MyError>();

        let typed_err = result.unwrap().unwrap_err();

        // Test Display
        let display = format!("{}", typed_err);
        assert!(display.contains("MyError"));
        assert!(display.contains("-42"));

        // Test Debug
        let debug = format!("{:?}", typed_err);
        assert!(debug.contains("MyError"));
        assert!(debug.contains("-42"));
    }

    #[test]
    fn test_typed_err_clone() {
        let runtime = QueryRuntime::new();
        let result = runtime.query(MayFail::new(-1)).downcast_err::<MyError>();

        let typed_err = result.unwrap().unwrap_err();
        let cloned = typed_err.clone();

        assert_eq!(typed_err.code, cloned.code);
        assert_eq!(typed_err.message, cloned.message);
    }

    #[test]
    fn test_query_error_downcast_ref() {
        let runtime = QueryRuntime::new();
        let result = runtime.query(MayFail::new(-1));

        let err = result.unwrap_err();

        // Test downcast_ref on QueryError directly
        assert!(err.is::<MyError>());
        assert!(!err.is::<OtherError>());

        let my_err = err.downcast_ref::<MyError>().unwrap();
        assert_eq!(my_err.code, -1);
    }

    #[test]
    fn test_query_error_user_error() {
        let runtime = QueryRuntime::new();
        let result = runtime.query(MayFail::new(-1));

        let err = result.unwrap_err();

        // Test user_error() method
        let arc = err.user_error().expect("should be UserError");
        assert!(arc.downcast_ref::<MyError>().is_some());
    }
}