domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
//! Run metadata insertion.
//!
//! This module handles inserting and updating run-level metadata and statistics.

use sqlx::{Row, SqlitePool};

use crate::error_handling::DatabaseError;

/// Metadata for a scan run, recorded at start.
pub struct RunMetadata<'a> {
    pub run_id: &'a str,
    pub start_time_ms: i64,
    pub version: &'a str,
    pub fingerprints_source: Option<&'a str>,
    pub fingerprints_version: Option<&'a str>,
    pub geoip_version: Option<&'a str>,
}

/// Statistics for a completed scan run, recorded at end.
pub struct RunStats<'a> {
    pub run_id: &'a str,
    pub total_urls: i32,
    pub successful_urls: i32,
    pub failed_urls: i32,
    pub skipped_urls: i32,
    pub elapsed_seconds: f64,
}

/// Inserts or updates run metadata in the runs table.
///
/// This should be called at the start of a run to record run-level information
/// like application version, `fingerprints_source`, `fingerprints_version`, and `geoip_version`.
pub async fn insert_run_metadata(
    pool: &SqlitePool,
    meta: &RunMetadata<'_>,
) -> Result<(), DatabaseError> {
    sqlx::query(
        "INSERT INTO runs (run_id, version, fingerprints_source, fingerprints_version, geoip_version, start_time_ms)
         VALUES (?, ?, ?, ?, ?, ?)
         ON CONFLICT(run_id) DO UPDATE SET
             version=excluded.version,
             fingerprints_source=excluded.fingerprints_source,
             fingerprints_version=excluded.fingerprints_version,
             geoip_version=excluded.geoip_version,
             start_time_ms=excluded.start_time_ms",
    )
    .bind(meta.run_id)
    .bind(meta.version)
    .bind(meta.fingerprints_source)
    .bind(meta.fingerprints_version)
    .bind(meta.geoip_version)
    .bind(meta.start_time_ms)
    .execute(pool)
    .await
    .map_err(DatabaseError::SqlError)?;

    Ok(())
}

/// Updates run statistics when a run completes.
///
/// Stores all statistics from a `ScanReport` including elapsed time for easy querying.
pub async fn update_run_stats(
    pool: &SqlitePool,
    stats: &RunStats<'_>,
) -> Result<(), DatabaseError> {
    let end_time_ms = chrono::Utc::now().timestamp_millis();

    sqlx::query(
        "UPDATE runs
         SET end_time_ms = ?, total_urls = ?, successful_urls = ?, failed_urls = ?, skipped_urls = ?, elapsed_seconds = ?
         WHERE run_id = ?",
    )
    .bind(end_time_ms)
    .bind(stats.total_urls)
    .bind(stats.successful_urls)
    .bind(stats.failed_urls)
    .bind(stats.skipped_urls)
    .bind(stats.elapsed_seconds)
    .bind(stats.run_id)
    .execute(pool)
    .await
    .map_err(DatabaseError::SqlError)
    .map(|result| {
        if result.rows_affected() == 0 {
            log::warn!(
                "update_run_stats: run_id '{}' not found (0 rows updated) — stats not persisted",
                stats.run_id
            );
        }
    })?;

    Ok(())
}

/// Fact-table row counts for a run (`url_status` / `url_failures`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RunFactCounts {
    pub successful_urls: i64,
    pub failed_urls: i64,
}

/// Counts committed success and failure rows for `run_id`.
///
/// In-memory atomics can undercount when a commit succeeds and `select!` then
/// cancels before `handle_success` / `handle_failure` increment counters.
pub(crate) async fn count_run_fact_rows(
    pool: &SqlitePool,
    run_id: &str,
) -> Result<RunFactCounts, DatabaseError> {
    let successful_urls: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM url_status WHERE run_id = ?")
            .bind(run_id)
            .fetch_one(pool)
            .await
            .map_err(DatabaseError::SqlError)?;
    let failed_urls: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM url_failures WHERE run_id = ?")
        .bind(run_id)
        .fetch_one(pool)
        .await
        .map_err(DatabaseError::SqlError)?;
    Ok(RunFactCounts {
        successful_urls,
        failed_urls,
    })
}

/// `url_partial_failures` counts for a run (does not affect `failed_urls`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct RunPartialFailureCounts {
    pub total: i64,
    pub satellite_insert_errors: i64,
}

/// Counts persisted partial-failure rows for `run_id`.
pub(crate) async fn count_run_partial_failures(
    pool: &SqlitePool,
    run_id: &str,
) -> Result<RunPartialFailureCounts, DatabaseError> {
    let total: i64 =
        sqlx::query_scalar("SELECT COUNT(*) FROM url_partial_failures WHERE run_id = ?")
            .bind(run_id)
            .fetch_one(pool)
            .await
            .map_err(DatabaseError::SqlError)?;
    let satellite_insert_errors: i64 = sqlx::query_scalar(
        "SELECT COUNT(*) FROM url_partial_failures WHERE run_id = ? AND error_type = ?",
    )
    .bind(run_id)
    .bind(crate::error_handling::ErrorType::SatelliteInsertError.as_str())
    .fetch_one(pool)
    .await
    .map_err(DatabaseError::SqlError)?;
    Ok(RunPartialFailureCounts {
        total,
        satellite_insert_errors,
    })
}

/// Saturating `COUNT(*)` → `i32` for `runs.*_urls` columns.
pub(crate) fn saturating_i32_count(count: i64) -> i32 {
    i32::try_from(count.max(0)).unwrap_or(i32::MAX)
}

/// Query run history from the database.
///
/// Returns all completed runs sorted by `start_time_ms` (most recent first).
/// Useful for reviewing past scan results after closing the terminal.
///
/// # Example
///
/// ```no_run
/// use domain_status::query_run_history;
/// use sqlx::SqlitePool;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let pool = SqlitePool::connect("sqlite:./domain_status.db").await?;
/// let runs = query_run_history(&pool, Some(10)).await?;
/// for run in runs {
///     println!("Run {}: {} URLs ({} succeeded, {} failed) in {:.1}s",
///              run.run_id, run.total_urls, run.successful_urls,
///              run.failed_urls, run.elapsed_seconds.unwrap_or(0.0));
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns `Err` when the database query fails.
pub async fn query_run_history(
    pool: &SqlitePool,
    limit: Option<usize>,
) -> Result<Vec<RunSummary>, DatabaseError> {
    let query = if let Some(limit) = limit {
        format!(
            "SELECT run_id, version, start_time_ms, end_time_ms, total_urls, successful_urls, failed_urls, skipped_urls, elapsed_seconds
             FROM runs
             WHERE end_time_ms IS NOT NULL
             ORDER BY start_time_ms DESC
             LIMIT {limit}"
        )
    } else {
        "SELECT run_id, version, start_time_ms, end_time_ms, total_urls, successful_urls, failed_urls, skipped_urls, elapsed_seconds
         FROM runs
         WHERE end_time_ms IS NOT NULL
         ORDER BY start_time_ms DESC"
            .to_string()
    };

    let rows = crate::sql::query(query)
        .fetch_all(pool)
        .await
        .map_err(DatabaseError::SqlError)?;

    Ok(rows
        .into_iter()
        .map(|row| run_summary_from_row(&row))
        .collect())
}

fn run_summary_from_row(row: &sqlx::sqlite::SqliteRow) -> RunSummary {
    RunSummary {
        run_id: row.get("run_id"),
        version: row.get("version"),
        start_time_ms: row.get("start_time_ms"),
        end_time_ms: row.get("end_time_ms"),
        total_urls: row.get("total_urls"),
        successful_urls: row.get("successful_urls"),
        failed_urls: row.get("failed_urls"),
        skipped_urls: row.get("skipped_urls"),
        elapsed_seconds: row.get("elapsed_seconds"),
    }
}

/// Looks up a run by id, including in-progress runs (`end_time_ms` may be NULL).
///
/// Unlike [`query_run_history`], this does not require the run to be completed.
pub(crate) async fn query_run_by_id(
    pool: &SqlitePool,
    run_id: &str,
) -> Result<Option<RunSummary>, DatabaseError> {
    let row = sqlx::query(
        "SELECT run_id, version, start_time_ms, end_time_ms, total_urls, successful_urls, \
         failed_urls, skipped_urls, elapsed_seconds \
         FROM runs WHERE run_id = ?",
    )
    .bind(run_id)
    .fetch_optional(pool)
    .await
    .map_err(DatabaseError::SqlError)?;

    Ok(row.map(|row| run_summary_from_row(&row)))
}

/// Summary of a completed run, suitable for displaying run history.
#[derive(Debug, Clone)]
pub struct RunSummary {
    /// Unique identifier for this run (e.g., "`run_1765150444953`").
    pub run_id: String,
    /// Application version that ran this scan (e.g., "0.1.4").
    pub version: Option<String>,
    /// Start time as milliseconds since Unix epoch.
    pub start_time_ms: i64,
    /// End time as milliseconds since Unix epoch (None if run still in progress).
    pub end_time_ms: Option<i64>,
    /// Total number of URLs processed in this run.
    pub total_urls: i32,
    /// Number of URLs that were successfully processed.
    pub successful_urls: i32,
    /// Number of URLs that failed to process.
    pub failed_urls: i32,
    /// Number of URLs intentionally skipped (e.g. duplicate domain in same run).
    pub skipped_urls: i32,
    /// Total execution time in seconds (None if run still in progress).
    pub elapsed_seconds: Option<f64>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use sqlx::Row;

    use crate::storage::test_helpers::{create_test_pool, create_test_url_status};

    #[tokio::test]
    async fn test_insert_run_metadata_basic() {
        let pool = create_test_pool().await;

        let meta = RunMetadata {
            run_id: "test-run-123",
            start_time_ms: 1704067200000, // 2024-01-01 00:00:00 UTC
            version: "0.1.4",
            fingerprints_source: Some("https://github.com/wappalyzer/wappalyzer"),
            fingerprints_version: Some("abc123def456"),
            geoip_version: Some("2024-01-01"),
        };
        let result = insert_run_metadata(&pool, &meta).await;

        assert!(result.is_ok());

        // Verify insertion
        let row = sqlx::query(
            "SELECT run_id, fingerprints_source, fingerprints_version, geoip_version, start_time_ms FROM runs WHERE run_id = ?",
        )
        .bind("test-run-123")
        .fetch_one(&pool)
        .await
        .expect("Failed to fetch run metadata");

        assert_eq!(row.get::<String, _>("run_id"), "test-run-123");
        assert_eq!(
            row.get::<Option<String>, _>("fingerprints_source"),
            Some("https://github.com/wappalyzer/wappalyzer".to_string())
        );
        assert_eq!(
            row.get::<Option<String>, _>("fingerprints_version"),
            Some("abc123def456".to_string())
        );
        assert_eq!(
            row.get::<Option<String>, _>("geoip_version"),
            Some("2024-01-01".to_string())
        );
        assert_eq!(row.get::<i64, _>("start_time_ms"), 1704067200000);
    }

    #[tokio::test]
    async fn test_insert_run_metadata_with_none_values() {
        let pool = create_test_pool().await;

        let meta = RunMetadata {
            run_id: "test-run-456",
            start_time_ms: 1704067200000,
            version: "0.1.4",
            fingerprints_source: None,
            fingerprints_version: None,
            geoip_version: None,
        };
        let result = insert_run_metadata(&pool, &meta).await;

        assert!(result.is_ok());

        // Verify insertion with None values
        let row = sqlx::query(
            "SELECT version, fingerprints_source, fingerprints_version, geoip_version FROM runs WHERE run_id = ?",
        )
        .bind("test-run-456")
        .fetch_one(&pool)
        .await
        .expect("Failed to fetch run metadata");

        assert_eq!(
            row.get::<Option<String>, _>("version"),
            Some("0.1.4".to_string())
        );
        assert_eq!(row.get::<Option<String>, _>("fingerprints_source"), None);
        assert_eq!(row.get::<Option<String>, _>("fingerprints_version"), None);
        assert_eq!(row.get::<Option<String>, _>("geoip_version"), None);
    }

    #[tokio::test]
    async fn test_insert_run_metadata_upsert() {
        let pool = create_test_pool().await;

        // Insert initial metadata
        let meta1 = RunMetadata {
            run_id: "test-run-789",
            start_time_ms: 1704067200000,
            version: "0.1.4",
            fingerprints_source: Some("https://github.com/wappalyzer/wappalyzer"),
            fingerprints_version: Some("abc123"),
            geoip_version: Some("2024-01-01"),
        };
        insert_run_metadata(&pool, &meta1)
            .await
            .expect("Failed to insert initial metadata");

        // Update with new values
        let meta2 = RunMetadata {
            run_id: "test-run-789",
            start_time_ms: 1704153600000, // New start time
            version: "0.1.5",             // Updated version
            fingerprints_source: Some("https://github.com/wappalyzer/wappalyzer"),
            fingerprints_version: Some("def456"), // Updated version
            geoip_version: Some("2024-01-02"),    // Updated GeoIP version
        };
        let result = insert_run_metadata(&pool, &meta2).await;

        assert!(result.is_ok());

        // Verify update
        let row = sqlx::query(
            "SELECT version, fingerprints_version, geoip_version, start_time_ms FROM runs WHERE run_id = ?",
        )
        .bind("test-run-789")
        .fetch_one(&pool)
        .await
        .expect("Failed to fetch run metadata");

        assert_eq!(
            row.get::<Option<String>, _>("version"),
            Some("0.1.5".to_string())
        );
        assert_eq!(
            row.get::<Option<String>, _>("fingerprints_version"),
            Some("def456".to_string())
        );
        assert_eq!(
            row.get::<Option<String>, _>("geoip_version"),
            Some("2024-01-02".to_string())
        );
        assert_eq!(row.get::<i64, _>("start_time_ms"), 1704153600000);

        // Verify only one row exists (UPSERT, not INSERT)
        let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM runs WHERE run_id = ?")
            .bind("test-run-789")
            .fetch_one(&pool)
            .await
            .expect("Failed to count runs");

        assert_eq!(count, 1);
    }

    #[test]
    fn test_saturating_i32_count_clamps_non_negative() {
        assert_eq!(saturating_i32_count(0), 0);
        assert_eq!(saturating_i32_count(42), 42);
        assert_eq!(saturating_i32_count(-1), 0);
        assert_eq!(saturating_i32_count(i64::from(i32::MAX)), i32::MAX);
        assert_eq!(saturating_i32_count(i64::from(i32::MAX) + 1), i32::MAX);
    }

    #[tokio::test]
    async fn test_count_run_fact_rows() {
        let pool = create_test_pool().await;
        insert_run_metadata(
            &pool,
            &RunMetadata {
                run_id: "count-run",
                start_time_ms: 1,
                version: "0.1.0",
                fingerprints_source: None,
                fingerprints_version: None,
                geoip_version: None,
            },
        )
        .await
        .expect("insert run");

        create_test_url_status(
            &pool,
            "a.example.com",
            "a.example.com",
            200,
            Some("count-run"),
            1,
        )
        .await;
        create_test_url_status(
            &pool,
            "b.example.com",
            "b.example.com",
            200,
            Some("count-run"),
            1,
        )
        .await;
        sqlx::query(
            "INSERT INTO url_failures (
                attempted_url, initial_domain, error_type, error_message,
                retry_count, observed_at_ms, run_id
            ) VALUES ('https://fail.example.com/', 'fail.example.com', 'timeout', 't', 0, 1, 'count-run')",
        )
        .execute(&pool)
        .await
        .expect("insert failure");

        let facts = count_run_fact_rows(&pool, "count-run")
            .await
            .expect("count facts");
        assert_eq!(facts.successful_urls, 2);
        assert_eq!(facts.failed_urls, 1);

        let empty = count_run_fact_rows(&pool, "missing-run")
            .await
            .expect("count missing run");
        assert_eq!(
            empty,
            RunFactCounts {
                successful_urls: 0,
                failed_urls: 0,
            }
        );
    }

    #[tokio::test]
    async fn test_count_run_partial_failures() {
        let pool = create_test_pool().await;
        insert_run_metadata(
            &pool,
            &RunMetadata {
                run_id: "partial-run",
                start_time_ms: 1,
                version: "0.1.0",
                fingerprints_source: None,
                fingerprints_version: None,
                geoip_version: None,
            },
        )
        .await
        .expect("insert run");
        let url_status_id = create_test_url_status(
            &pool,
            "a.example.com",
            "a.example.com",
            200,
            Some("partial-run"),
            1,
        )
        .await;
        sqlx::query(
            "INSERT INTO url_partial_failures (
                url_status_id, error_type, error_message, observed_at_ms, run_id
            ) VALUES (?, ?, 'mx timeout', 1, 'partial-run')",
        )
        .bind(url_status_id)
        .bind(crate::error_handling::ErrorType::DnsMxLookupError.as_str())
        .execute(&pool)
        .await
        .expect("insert dns partial");
        sqlx::query(
            "INSERT INTO url_partial_failures (
                url_status_id, error_type, error_message, observed_at_ms, run_id
            ) VALUES (?, ?, 'url_cookies: constraint', 1, 'partial-run')",
        )
        .bind(url_status_id)
        .bind(crate::error_handling::ErrorType::SatelliteInsertError.as_str())
        .execute(&pool)
        .await
        .expect("insert satellite partial");

        let counts = count_run_partial_failures(&pool, "partial-run")
            .await
            .expect("count partials");
        assert_eq!(counts.total, 2);
        assert_eq!(counts.satellite_insert_errors, 1);
        let empty = count_run_partial_failures(&pool, "missing-run")
            .await
            .expect("count missing");
        assert_eq!(
            empty,
            RunPartialFailureCounts {
                total: 0,
                satellite_insert_errors: 0,
            }
        );
    }

    #[tokio::test]
    async fn test_update_run_stats_basic() {
        let pool = create_test_pool().await;

        // First insert run metadata
        let meta = RunMetadata {
            run_id: "test-run-stats",
            start_time_ms: 1704067200000,
            version: "0.1.4",
            fingerprints_source: Some("https://github.com/wappalyzer/wappalyzer"),
            fingerprints_version: Some("abc123"),
            geoip_version: None,
        };
        insert_run_metadata(&pool, &meta)
            .await
            .expect("Failed to insert run metadata");

        // Update run stats
        let stats = RunStats {
            run_id: "test-run-stats",
            total_urls: 100,
            successful_urls: 95,
            failed_urls: 5,
            skipped_urls: 0,
            elapsed_seconds: 10.5,
        };
        let result = update_run_stats(&pool, &stats).await;

        assert!(result.is_ok());

        // Verify update
        let row = sqlx::query(
            "SELECT end_time_ms, total_urls, successful_urls, failed_urls, skipped_urls, elapsed_seconds FROM runs WHERE run_id = ?",
        )
        .bind("test-run-stats")
        .fetch_one(&pool)
        .await
        .expect("Failed to fetch run stats");

        let end_time_ms: i64 = row.get("end_time_ms");
        assert!(end_time_ms > 0); // Should be set to current time
        assert_eq!(row.get::<i32, _>("total_urls"), 100);
        assert_eq!(row.get::<i32, _>("successful_urls"), 95);
        assert_eq!(row.get::<i32, _>("failed_urls"), 5);
        assert_eq!(row.get::<i32, _>("skipped_urls"), 0);
        assert_eq!(row.get::<Option<f64>, _>("elapsed_seconds"), Some(10.5));
    }

    #[tokio::test]
    async fn test_update_run_stats_zero_values() {
        let pool = create_test_pool().await;

        // Insert run metadata
        let meta = RunMetadata {
            run_id: "test-run-zero",
            start_time_ms: 1704067200000,
            version: "0.1.4",
            fingerprints_source: None,
            fingerprints_version: None,
            geoip_version: None,
        };
        insert_run_metadata(&pool, &meta)
            .await
            .expect("Failed to insert run metadata");

        // Update with zero values
        let stats = RunStats {
            run_id: "test-run-zero",
            total_urls: 0,
            successful_urls: 0,
            failed_urls: 0,
            skipped_urls: 0,
            elapsed_seconds: 0.0,
        };
        let result = update_run_stats(&pool, &stats).await;

        assert!(result.is_ok());

        // Verify update
        let row = sqlx::query(
            "SELECT total_urls, successful_urls, failed_urls, skipped_urls, elapsed_seconds FROM runs WHERE run_id = ?",
        )
        .bind("test-run-zero")
        .fetch_one(&pool)
        .await
        .expect("Failed to fetch run stats");

        assert_eq!(row.get::<i32, _>("total_urls"), 0);
        assert_eq!(row.get::<i32, _>("successful_urls"), 0);
        assert_eq!(row.get::<i32, _>("failed_urls"), 0);
        assert_eq!(row.get::<i32, _>("skipped_urls"), 0);
        assert_eq!(row.get::<Option<f64>, _>("elapsed_seconds"), Some(0.0));
    }

    #[tokio::test]
    async fn test_update_run_stats_nonexistent_run() {
        let pool = create_test_pool().await;

        // Try to update stats for non-existent run
        let stats = RunStats {
            run_id: "nonexistent-run",
            total_urls: 100,
            successful_urls: 95,
            failed_urls: 5,
            skipped_urls: 0,
            elapsed_seconds: 15.0,
        };
        let result = update_run_stats(&pool, &stats).await;

        // Should succeed but update 0 rows
        assert!(result.is_ok());

        // Verify no row was created
        let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM runs WHERE run_id = ?")
            .bind("nonexistent-run")
            .fetch_one(&pool)
            .await
            .expect("Failed to count runs");

        assert_eq!(count, 0);
    }

    #[tokio::test]
    async fn test_insert_and_update_run_complete_flow() {
        let pool = create_test_pool().await;

        // Step 1: Insert run metadata at start
        let meta = RunMetadata {
            run_id: "complete-run",
            start_time_ms: 1704067200000,
            version: "0.1.4",
            fingerprints_source: Some("https://github.com/wappalyzer/wappalyzer"),
            fingerprints_version: Some("abc123"),
            geoip_version: Some("2024-01-01"),
        };
        insert_run_metadata(&pool, &meta)
            .await
            .expect("Failed to insert run metadata");

        // Step 2: Update stats at end
        let stats = RunStats {
            run_id: "complete-run",
            total_urls: 50,
            successful_urls: 48,
            failed_urls: 2,
            skipped_urls: 0,
            elapsed_seconds: 25.3,
        };
        let result = update_run_stats(&pool, &stats).await;
        assert!(result.is_ok());

        // Verify complete record
        let row = sqlx::query(
            "SELECT run_id, version, fingerprints_source, fingerprints_version, geoip_version, start_time_ms, end_time_ms, total_urls, successful_urls, failed_urls, skipped_urls, elapsed_seconds FROM runs WHERE run_id = ?",
        )
        .bind("complete-run")
        .fetch_one(&pool)
        .await
        .expect("Failed to fetch complete run record");

        assert_eq!(row.get::<String, _>("run_id"), "complete-run");
        assert_eq!(
            row.get::<Option<String>, _>("version"),
            Some("0.1.4".to_string())
        );
        assert_eq!(
            row.get::<Option<String>, _>("fingerprints_source"),
            Some("https://github.com/wappalyzer/wappalyzer".to_string())
        );
        assert_eq!(row.get::<i64, _>("start_time_ms"), 1704067200000);
        let end_time_ms: i64 = row.get("end_time_ms");
        assert!(end_time_ms > 0);
        assert_eq!(row.get::<i32, _>("total_urls"), 50);
        assert_eq!(row.get::<i32, _>("successful_urls"), 48);
        assert_eq!(row.get::<i32, _>("failed_urls"), 2);
        assert_eq!(row.get::<i32, _>("skipped_urls"), 0);
        assert_eq!(row.get::<Option<f64>, _>("elapsed_seconds"), Some(25.3));
    }

    #[tokio::test]
    async fn test_query_run_history_with_limit() {
        // Test that query_run_history respects the limit parameter
        // This is critical - prevents loading too many runs into memory
        let pool = create_test_pool().await;

        // Create multiple completed runs
        for i in 0..5 {
            let run_id = format!("test-run-limit-{}", i);
            let meta = RunMetadata {
                run_id: &run_id,
                start_time_ms: 1704067200000 + (i64::from(i) * 1000),
                version: "0.1.4",
                fingerprints_source: None,
                fingerprints_version: None,
                geoip_version: None,
            };
            insert_run_metadata(&pool, &meta)
                .await
                .expect("Failed to insert run metadata");
            let stats = RunStats {
                run_id: &run_id,
                total_urls: 10,
                successful_urls: 9,
                failed_urls: 1,
                skipped_urls: 0,
                elapsed_seconds: 5.0,
            };
            update_run_stats(&pool, &stats)
                .await
                .expect("Failed to update run stats");
        }

        // Query with limit of 3
        let result = query_run_history(&pool, Some(3)).await;
        assert!(result.is_ok());
        let runs = result.unwrap();
        assert_eq!(
            runs.len(),
            3,
            "Should return exactly 3 runs when limit is 3"
        );
    }

    #[tokio::test]
    async fn test_query_run_history_without_limit() {
        // Test that query_run_history returns all runs when limit is None
        // This is critical - ensures unlimited queries work correctly
        let pool = create_test_pool().await;

        // Create multiple completed runs
        for i in 0..5 {
            let run_id = format!("test-run-unlimited-{}", i);
            let meta = RunMetadata {
                run_id: &run_id,
                start_time_ms: 1704067200000 + (i64::from(i) * 1000),
                version: "0.1.4",
                fingerprints_source: None,
                fingerprints_version: None,
                geoip_version: None,
            };
            insert_run_metadata(&pool, &meta)
                .await
                .expect("Failed to insert run metadata");
            let stats = RunStats {
                run_id: &run_id,
                total_urls: 10,
                successful_urls: 9,
                failed_urls: 1,
                skipped_urls: 0,
                elapsed_seconds: 5.0,
            };
            update_run_stats(&pool, &stats)
                .await
                .expect("Failed to update run stats");
        }

        // Query without limit
        let result = query_run_history(&pool, None).await;
        assert!(result.is_ok());
        let runs = result.unwrap();
        assert_eq!(runs.len(), 5, "Should return all 5 runs when limit is None");
    }

    #[tokio::test]
    async fn test_query_run_history_empty_result() {
        // Test that query_run_history returns empty vector when no completed runs exist
        // This is critical - edge case handling prevents panics
        let pool = create_test_pool().await;

        // Create a run but don't complete it (no end_time_ms)
        let meta = RunMetadata {
            run_id: "test-run-incomplete",
            start_time_ms: 1704067200000,
            version: "0.1.4",
            fingerprints_source: None,
            fingerprints_version: None,
            geoip_version: None,
        };
        insert_run_metadata(&pool, &meta)
            .await
            .expect("Failed to insert run metadata");
        // Don't call update_run_stats - this keeps end_time_ms as NULL

        // Query should return empty (only completed runs are returned)
        let result = query_run_history(&pool, None).await;
        assert!(result.is_ok());
        let runs = result.unwrap();
        assert!(
            runs.is_empty(),
            "Should return empty vector when no completed runs exist"
        );
    }

    #[tokio::test]
    async fn test_query_run_history_sorted_by_start_time_desc() {
        // Test that query_run_history returns runs sorted by start_time_ms DESC (most recent first)
        // This is critical - ensures correct ordering for display
        let pool = create_test_pool().await;

        // Create runs with different start times
        let run_ids = ["run-1", "run-2", "run-3"];
        let start_times = [1704067200000, 1704067300000, 1704067400000]; // Increasing times

        for (run_id, start_time) in run_ids.iter().zip(start_times.iter()) {
            let meta = RunMetadata {
                run_id,
                start_time_ms: *start_time,
                version: "0.1.4",
                fingerprints_source: None,
                fingerprints_version: None,
                geoip_version: None,
            };
            insert_run_metadata(&pool, &meta)
                .await
                .expect("Failed to insert run metadata");
            let stats = RunStats {
                run_id,
                total_urls: 10,
                successful_urls: 9,
                failed_urls: 1,
                skipped_urls: 0,
                elapsed_seconds: 5.0,
            };
            update_run_stats(&pool, &stats)
                .await
                .expect("Failed to update run stats");
        }

        // Query should return runs in descending order (most recent first)
        let result = query_run_history(&pool, None).await;
        assert!(result.is_ok());
        let runs = result.unwrap();
        assert_eq!(runs.len(), 3);
        // Most recent should be first
        assert_eq!(runs[0].run_id, "run-3");
        assert_eq!(runs[0].start_time_ms, 1704067400000);
        // Oldest should be last
        assert_eq!(runs[2].run_id, "run-1");
        assert_eq!(runs[2].start_time_ms, 1704067200000);
    }
}