captchaforge 0.2.34

Automatic CAPTCHA detection and multi-strategy solving for chromiumoxide-driven headless browsers (Cloudflare Turnstile, reCAPTCHA v2/v3, hCaptcha, image grids, audio, sliders).
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
//! Solver telemetry — structured event hooks for external analytics.
//!
//! The solver chain already logs to `tracing` and updates the
//! [`crate::solver::PatternStore`] for routing decisions, but
//! neither is suitable for durable metrics: tracing output is
//! operator-facing text, and the pattern store is a learned-routing
//! cache that prunes old entries. Production users want to know
//! per-solver success rates, p50/p95 solve times, fallback rates
//! per domain, and time-series trends.
//!
//! [`SolverTelemetry`] is a tiny trait the chain calls at every
//! solver-attempt outcome. The default implementation is a no-op, so
//! adding telemetry is opt-in: pass an `Arc<dyn SolverTelemetry>` via
//! [`crate::solver::CaptchaSolverChain::with_telemetry`] and your
//! impl receives every event.
//!
//! Implementations are free to: write to Prometheus, push to a
//! statsd/OTel collector, batch into SQLite, post to Sentry, mirror
//! into the pattern store, or ignore the events entirely. The trait
//! is intentionally allocation-light — events borrow strings where
//! possible — so a high-throughput impl can avoid heap churn.
use crate::captcha_detect::DetectedCaptcha;
use crate::solver::{CaptchaType, SolveMethod};

/// What happened during a single solver attempt.
///
/// `Success`/`Failure` correspond to the solver returning
/// `Ok(result)` with `result.success = true`/`false`. `Error` means
/// the solver returned `Err`. `Timeout` means the chain's per-solver
/// deadline elapsed before the solver returned anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SolveOutcome {
    Success,
    Failure,
    Error,
    Timeout,
}

/// One solver attempt's telemetry event. Borrowed where possible so
/// hot-path implementations can avoid allocation.
///
/// `confidence` is only present on `Success` outcomes — the other
/// outcomes have no meaningful confidence value.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SolveEvent<'a> {
    /// Stable solver identifier (e.g. `"VlmCaptchaSolver"`).
    pub solver: &'static str,
    /// Captcha type the chain mapped from the detection.
    pub captcha_type: &'a CaptchaType,
    /// Original detected captcha kind from the detector.
    pub kind: &'a DetectedCaptcha,
    /// Domain the solve targeted, parsed from `CaptchaInfo.page_url`.
    pub domain: &'a str,
    /// What happened.
    pub outcome: SolveOutcome,
    /// Wall-clock duration of the attempt, in milliseconds.
    pub time_ms: u64,
    /// Solve confidence in 0.0–1.0; `None` for non-Success outcomes.
    pub confidence: Option<f32>,
    /// Which solver strategy the attempt used.
    pub method: &'a SolveMethod,
}

impl<'a> SolveEvent<'a> {
    /// Construct a `SolveEvent`. Required for external callers because
    /// the struct is `#[non_exhaustive]` (so the crate can add fields
    /// without a SemVer break) — direct struct-literal construction is
    /// not allowed across crate boundaries.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        solver: &'static str,
        captcha_type: &'a CaptchaType,
        kind: &'a DetectedCaptcha,
        domain: &'a str,
        outcome: SolveOutcome,
        time_ms: u64,
        confidence: Option<f32>,
        method: &'a SolveMethod,
    ) -> Self {
        Self {
            solver,
            captcha_type,
            kind,
            domain,
            outcome,
            time_ms,
            confidence,
            method,
        }
    }
}

/// Hook the solver chain calls at every attempt outcome.
///
/// Implementations MUST be cheap — the chain calls `record` from the
/// hot solve path. Slow implementations (network writes, blocking
/// I/O) should buffer or spawn so they don't extend solve latency.
pub trait SolverTelemetry: Send + Sync {
    /// Called once per solver attempt. The reference is short-lived;
    /// implementations that need to persist must clone.
    fn record(&self, evt: &SolveEvent<'_>);
}

/// Default zero-overhead implementation — drops every event.
///
/// Used as the chain's telemetry until a real implementation is
/// installed via [`crate::solver::CaptchaSolverChain::with_telemetry`].
pub struct NoopTelemetry;

impl SolverTelemetry for NoopTelemetry {
    fn record(&self, _evt: &SolveEvent<'_>) {}
}

/// Compose multiple telemetry sinks. Each `record` call fans out to
/// every wrapped sink in registration order. Use this when an
/// operator wants both in-process `MetricsTelemetry` (for `/metrics`)
/// AND a `JsonTelemetry` log stream AND a custom exporter pointed at
/// Datadog / Sentry / Honeycomb / etc.
///
/// All sinks share the same event; if one is slow it will block the
/// solve hot path — wrap slow sinks in their own buffering layer
/// before adding here.
///
/// # Example
///
/// ```rust,ignore
/// use std::sync::Arc;
/// use captchaforge::telemetry::{FanoutTelemetry, JsonTelemetry, MetricsTelemetry};
///
/// let metrics = Arc::new(MetricsTelemetry::new());
/// let fanout = Arc::new(
///     FanoutTelemetry::new()
///         .with_sink(metrics.clone())
///         .with_sink(Arc::new(JsonTelemetry))
/// );
/// let chain = captchaforge::solver::CaptchaSolverChain::default_chain()
///     .with_telemetry(fanout);
/// ```
pub struct FanoutTelemetry {
    sinks: Vec<std::sync::Arc<dyn SolverTelemetry>>,
}

impl FanoutTelemetry {
    pub fn new() -> Self {
        Self { sinks: Vec::new() }
    }

    /// Append a sink. Fanout calls record on every sink in
    /// registration order.
    #[must_use = "FanoutTelemetry::with_sink returns Self; assign or chain it"]
    pub fn with_sink(mut self, sink: std::sync::Arc<dyn SolverTelemetry>) -> Self {
        self.sinks.push(sink);
        self
    }

    pub fn len(&self) -> usize {
        self.sinks.len()
    }

    pub fn is_empty(&self) -> bool {
        self.sinks.is_empty()
    }
}

impl Default for FanoutTelemetry {
    fn default() -> Self {
        Self::new()
    }
}

impl SolverTelemetry for FanoutTelemetry {
    fn record(&self, evt: &SolveEvent<'_>) {
        for sink in &self.sinks {
            sink.record(evt);
        }
    }
}

/// Telemetry that emits each event as a `tracing::info!` with
/// structured fields — pairs naturally with `tracing-subscriber`'s
/// JSON layer for routing into ELK / Loki / Datadog without any
/// extra integration code on the operator side.
///
/// Each event becomes one log line tagged with target
/// `"captchaforge.solve"`; consumer queries:
///
/// - `target == "captchaforge.solve" && outcome == "success"` →
///   per-solver success rate.
/// - `histogram(time_ms)` over `target == "captchaforge.solve"` →
///   p50/p95/p99 solve latency by `solver` + `domain`.
/// - `outcome == "timeout"` → per-vendor timeout rate.
///
/// Use [`MetricsTelemetry`] when you want in-process aggregation
/// (Prometheus-style); use this when you want raw events flowing
/// through your existing log pipeline.
pub struct JsonTelemetry;

impl SolverTelemetry for JsonTelemetry {
    fn record(&self, evt: &SolveEvent<'_>) {
        // `tracing::info!` macro doesn't accept dynamic `target`,
        // so emit via `event!` with explicit target. Field names
        // are stable — consumers join on them.
        //
        // `kind` is rendered through [`safe_kind_label`] so the
        // operator's custom rule names from `DetectedCaptcha::Custom`
        // don't get logged verbatim — those strings come from
        // user-supplied TOML and can encode sensitive info (vendor
        // names, internal product codenames, customer identifiers).
        // Built-in variants log their canonical name; Custom logs
        // `custom:<8-hex-chars-of-sha256>` so cardinality is bounded
        // and the operator's secret label is not in the log stream.
        tracing::event!(
            target: "captchaforge.solve",
            tracing::Level::INFO,
            solver = %evt.solver,
            outcome = %outcome_label(evt.outcome),
            domain = %evt.domain,
            captcha_type = ?evt.captcha_type,
            kind = %safe_kind_label(evt.kind),
            method = ?evt.method,
            time_ms = evt.time_ms,
            confidence = evt.confidence.unwrap_or(f32::NAN),
        );
    }
}

/// Render a `DetectedCaptcha` for telemetry without leaking the
/// operator's `Custom(name)` label verbatim. Built-in variants
/// produce their `Debug` form; `Custom` produces `custom:<hex8>` so
/// cardinality stays bounded.
fn safe_kind_label(kind: &crate::detect::DetectedCaptcha) -> String {
    use crate::detect::DetectedCaptcha;
    match kind {
        DetectedCaptcha::Custom(name) => {
            use sha2::{Digest, Sha256};
            let mut h = Sha256::new();
            h.update(name.as_bytes());
            let d = h.finalize();
            format!(
                "custom:{:02x}{:02x}{:02x}{:02x}",
                d[0], d[1], d[2], d[3]
            )
        }
        other => format!("{other:?}"),
    }
}

/// Stable string label for an outcome. Used by both
/// [`JsonTelemetry`]'s log fields and [`MetricsTelemetry`]'s
/// counter keys so a Prometheus query and a log query see the same
/// label values.
fn outcome_label(o: SolveOutcome) -> &'static str {
    match o {
        SolveOutcome::Success => "success",
        SolveOutcome::Failure => "failure",
        SolveOutcome::Error => "error",
        SolveOutcome::Timeout => "timeout",
    }
}

/// In-process metrics aggregator for solver telemetry.
///
/// Maintains per-`(solver, outcome)` event counts plus
/// per-`(solver, outcome)` time-histogram buckets. Cheap enough to
/// be the default in production: each `record` call takes a brief
/// mutex + 2 small map lookups + a counter increment.
///
/// Read with [`MetricsTelemetry::snapshot`]; that returns a flat
/// [`MetricsSnapshot`] you can serialise to Prometheus / OpenMetrics
/// / JSON / your dashboard format of choice. The snapshot is a
/// point-in-time copy — concurrent `record` calls don't block the
/// reader, and the reader doesn't reset counters.
///
/// Histogram buckets are fixed at `[10ms, 50ms, 100ms, 500ms, 1s,
/// 5s, 10s, 30s, +inf]` — covers the typical captcha-solve latency
/// envelope (10ms cache hit → 30s VLM + retry).
pub struct MetricsTelemetry {
    inner: std::sync::Mutex<MetricsState>,
}

/// Mutex-protected aggregation state for [`MetricsTelemetry`].
#[derive(Default)]
struct MetricsState {
    counts: std::collections::HashMap<(String, &'static str), u64>,
    histograms: std::collections::HashMap<(String, &'static str), [u64; 9]>,
}

impl MetricsTelemetry {
    pub fn new() -> Self {
        Self {
            inner: std::sync::Mutex::new(MetricsState::default()),
        }
    }

    /// Take a point-in-time snapshot of every metric this telemetry
    /// has accumulated. Cheap to call repeatedly; doesn't reset.
    pub fn snapshot(&self) -> MetricsSnapshot {
        let inner = self.inner.lock().expect("metrics mutex poisoned");
        let counts = inner
            .counts
            .iter()
            .map(|((solver, outcome), n)| MetricCount {
                solver: solver.clone(),
                outcome,
                count: *n,
            })
            .collect();
        let histograms = inner
            .histograms
            .iter()
            .map(|((solver, outcome), buckets)| MetricHistogram {
                solver: solver.clone(),
                outcome,
                bucket_upper_bounds_ms: HISTOGRAM_BUCKETS_MS.to_vec(),
                bucket_counts: buckets.to_vec(),
            })
            .collect();
        MetricsSnapshot { counts, histograms }
    }
}

impl Default for MetricsTelemetry {
    fn default() -> Self {
        Self::new()
    }
}

impl SolverTelemetry for MetricsTelemetry {
    fn record(&self, evt: &SolveEvent<'_>) {
        let mut inner = self.inner.lock().expect("metrics mutex poisoned");
        let key = (evt.solver.to_string(), outcome_label(evt.outcome));
        *inner.counts.entry(key.clone()).or_insert(0) += 1;
        let buckets = inner.histograms.entry(key).or_insert([0u64; 9]);
        let bucket_idx = histogram_bucket_index(evt.time_ms);
        buckets[bucket_idx] += 1;
    }
}

/// Histogram bucket upper bounds in milliseconds. The final
/// `u64::MAX` is the +inf bucket (everything slower than 30s).
const HISTOGRAM_BUCKETS_MS: [u64; 9] = [10, 50, 100, 500, 1_000, 5_000, 10_000, 30_000, u64::MAX];

/// Index of the smallest bucket whose upper bound is ≥ `time_ms`.
/// Branch-light so the hot record path stays cheap.
fn histogram_bucket_index(time_ms: u64) -> usize {
    for (i, upper) in HISTOGRAM_BUCKETS_MS.iter().enumerate() {
        if time_ms <= *upper {
            return i;
        }
    }
    HISTOGRAM_BUCKETS_MS.len() - 1
}

/// Point-in-time snapshot of every metric a [`MetricsTelemetry`]
/// has accumulated. Implements `Serialize` so callers can hand it
/// straight to a JSON / Prometheus exposition layer.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MetricsSnapshot {
    pub counts: Vec<MetricCount>,
    pub histograms: Vec<MetricHistogram>,
}

/// One `(solver, outcome) → count` entry.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MetricCount {
    pub solver: String,
    pub outcome: &'static str,
    pub count: u64,
}

/// One `(solver, outcome) → bucketed time-histogram` entry.
///
/// `bucket_upper_bounds_ms` and `bucket_counts` are parallel: the
/// nth count belongs to the bucket with the nth upper bound. The
/// final `u64::MAX` bucket is the catch-all for events slower than
/// every other bound.
#[derive(Debug, Clone, serde::Serialize)]
pub struct MetricHistogram {
    pub solver: String,
    pub outcome: &'static str,
    pub bucket_upper_bounds_ms: Vec<u64>,
    pub bucket_counts: Vec<u64>,
}

impl MetricsSnapshot {
    /// Render every metric in Prometheus exposition-format text.
    /// Callers can serve this directly from a `/metrics` HTTP
    /// endpoint without any extra exporter library.
    ///
    /// Format reference:
    /// <https://prometheus.io/docs/instrumenting/exposition_formats/>
    pub fn to_prometheus(&self) -> String {
        use std::fmt::Write;
        let mut out = String::with_capacity(self.counts.len() * 64 + self.histograms.len() * 256);
        // Counter family
        out.push_str(
            "# HELP captchaforge_solve_total Total solver attempts by solver + outcome.\n",
        );
        out.push_str("# TYPE captchaforge_solve_total counter\n");
        for c in &self.counts {
            let _ = writeln!(
                out,
                r#"captchaforge_solve_total{{solver="{}",outcome="{}"}} {}"#,
                escape_label(&c.solver),
                c.outcome,
                c.count
            );
        }
        // Histogram family
        out.push_str("# HELP captchaforge_solve_duration_ms Solve duration in milliseconds.\n");
        out.push_str("# TYPE captchaforge_solve_duration_ms histogram\n");
        for h in &self.histograms {
            let mut cumulative = 0u64;
            for (upper, count) in h.bucket_upper_bounds_ms.iter().zip(h.bucket_counts.iter()) {
                cumulative += count;
                let upper_label = if *upper == u64::MAX {
                    "+Inf".to_string()
                } else {
                    upper.to_string()
                };
                let _ = writeln!(
                    out,
                    r#"captchaforge_solve_duration_ms_bucket{{solver="{}",outcome="{}",le="{}"}} {}"#,
                    escape_label(&h.solver),
                    h.outcome,
                    upper_label,
                    cumulative
                );
            }
            let total: u64 = h.bucket_counts.iter().sum();
            let _ = writeln!(
                out,
                r#"captchaforge_solve_duration_ms_count{{solver="{}",outcome="{}"}} {}"#,
                escape_label(&h.solver),
                h.outcome,
                total
            );
        }
        out
    }
}

/// Escape a Prometheus label value per the exposition format —
/// backslash + quote + newline. Conservative; never strips chars
/// (would mask real solver-name typos).
fn escape_label(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for c in value.chars() {
        match c {
            '\\' => out.push_str(r"\\"),
            '"' => out.push_str(r#"\""#),
            '\n' => out.push_str(r"\n"),
            other => out.push(other),
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    /// In-memory telemetry sink for assertion in tests / examples.
    struct CapturingTelemetry {
        events: Mutex<Vec<(SolveOutcome, String, u64)>>,
    }

    impl CapturingTelemetry {
        fn new() -> Self {
            Self {
                events: Mutex::new(Vec::new()),
            }
        }
    }

    impl SolverTelemetry for CapturingTelemetry {
        fn record(&self, evt: &SolveEvent<'_>) {
            self.events
                .lock()
                .unwrap()
                .push((evt.outcome, evt.domain.to_owned(), evt.time_ms));
        }
    }

    #[test]
    fn noop_telemetry_drops_events() {
        let t = NoopTelemetry;
        let kind = DetectedCaptcha::Turnstile;
        let captcha_type = CaptchaType::CloudflareTurnstile;
        let method = SolveMethod::BehavioralBypass;
        let evt = SolveEvent {
            solver: "TestSolver",
            captcha_type: &captcha_type,
            kind: &kind,
            domain: "example.com",
            outcome: SolveOutcome::Success,
            time_ms: 1234,
            confidence: Some(0.95),
            method: &method,
        };
        t.record(&evt);
        // No assertion needed; we're verifying it doesn't panic.
    }

    #[test]
    fn metrics_telemetry_aggregates_per_solver_outcome_counts() {
        let m = MetricsTelemetry::new();
        let kind = DetectedCaptcha::Turnstile;
        let captcha_type = CaptchaType::CloudflareTurnstile;
        let method = SolveMethod::BehavioralBypass;

        for (solver, outcome) in [
            ("BehavioralCaptchaSolver", SolveOutcome::Success),
            ("BehavioralCaptchaSolver", SolveOutcome::Success),
            ("BehavioralCaptchaSolver", SolveOutcome::Failure),
            ("VlmCaptchaSolver", SolveOutcome::Success),
        ] {
            m.record(&SolveEvent {
                solver,
                captcha_type: &captcha_type,
                kind: &kind,
                domain: "ex.com",
                outcome,
                time_ms: 100,
                confidence: None,
                method: &method,
            });
        }
        let snap = m.snapshot();
        let beh_succ = snap
            .counts
            .iter()
            .find(|c| c.solver == "BehavioralCaptchaSolver" && c.outcome == "success");
        assert_eq!(beh_succ.map(|c| c.count), Some(2));
        let beh_fail = snap
            .counts
            .iter()
            .find(|c| c.solver == "BehavioralCaptchaSolver" && c.outcome == "failure");
        assert_eq!(beh_fail.map(|c| c.count), Some(1));
    }

    #[test]
    fn metrics_histogram_bucket_index_partitions_correctly() {
        // Boundary values land in the bucket whose upper bound
        // they exactly equal, not the next one up.
        assert_eq!(histogram_bucket_index(0), 0);
        assert_eq!(histogram_bucket_index(10), 0);
        assert_eq!(histogram_bucket_index(11), 1);
        assert_eq!(histogram_bucket_index(50), 1);
        assert_eq!(histogram_bucket_index(100), 2);
        assert_eq!(histogram_bucket_index(500), 3);
        assert_eq!(histogram_bucket_index(1_000), 4);
        assert_eq!(histogram_bucket_index(5_000), 5);
        assert_eq!(histogram_bucket_index(10_000), 6);
        assert_eq!(histogram_bucket_index(30_000), 7);
        // Anything past 30s lands in the +inf bucket.
        assert_eq!(histogram_bucket_index(31_000), 8);
        assert_eq!(histogram_bucket_index(u64::MAX), 8);
    }

    #[test]
    fn metrics_to_prometheus_renders_valid_exposition_format() {
        let m = MetricsTelemetry::new();
        let kind = DetectedCaptcha::Turnstile;
        let captcha_type = CaptchaType::CloudflareTurnstile;
        let method = SolveMethod::BehavioralBypass;
        m.record(&SolveEvent {
            solver: "TestSolver",
            captcha_type: &captcha_type,
            kind: &kind,
            domain: "ex.com",
            outcome: SolveOutcome::Success,
            time_ms: 250,
            confidence: Some(0.9),
            method: &method,
        });
        let prom = m.snapshot().to_prometheus();
        // Must contain the documented metric names + label format.
        assert!(prom.contains("# HELP captchaforge_solve_total"));
        assert!(prom.contains("# TYPE captchaforge_solve_total counter"));
        assert!(
            prom.contains(r#"captchaforge_solve_total{solver="TestSolver",outcome="success"} 1"#)
        );
        assert!(prom.contains("# HELP captchaforge_solve_duration_ms"));
        assert!(prom.contains("# TYPE captchaforge_solve_duration_ms histogram"));
        // Cumulative bucket count: a single 250ms event lands in
        // bucket 3 (le=500), so every bucket from le=500 onward
        // should report cumulative >=1.
        assert!(prom.contains(r#"captchaforge_solve_duration_ms_bucket{solver="TestSolver",outcome="success",le="500"} 1"#));
        assert!(prom.contains(r#"captchaforge_solve_duration_ms_bucket{solver="TestSolver",outcome="success",le="+Inf"} 1"#));
        // Smaller buckets should report 0.
        assert!(prom.contains(r#"captchaforge_solve_duration_ms_bucket{solver="TestSolver",outcome="success",le="10"} 0"#));
    }

    #[test]
    fn metrics_to_prometheus_escapes_problematic_label_chars() {
        let m = MetricsTelemetry::new();
        let kind = DetectedCaptcha::Turnstile;
        let captcha_type = CaptchaType::CloudflareTurnstile;
        let method = SolveMethod::BehavioralBypass;
        // Solver name with backslash + quote — must escape so the
        // exposition format stays parseable.
        m.record(&SolveEvent {
            solver: "Solver\"with\\quotes",
            captcha_type: &captcha_type,
            kind: &kind,
            domain: "ex.com",
            outcome: SolveOutcome::Success,
            time_ms: 10,
            confidence: None,
            method: &method,
        });
        let prom = m.snapshot().to_prometheus();
        // Quote → \", backslash → \\.
        assert!(prom.contains(r#"solver="Solver\"with\\quotes""#));
    }

    #[test]
    fn outcome_label_returns_stable_strings() {
        // Stability matters: Prometheus / log queries join on these
        // exact strings. A typo here breaks every dashboard.
        assert_eq!(outcome_label(SolveOutcome::Success), "success");
        assert_eq!(outcome_label(SolveOutcome::Failure), "failure");
        assert_eq!(outcome_label(SolveOutcome::Error), "error");
        assert_eq!(outcome_label(SolveOutcome::Timeout), "timeout");
    }

    #[test]
    fn json_telemetry_does_not_panic_on_record() {
        // We can't easily intercept the tracing output here without
        // a subscriber; the lightest assertion is just "doesn't
        // panic + doesn't allocate-bomb".
        let t = JsonTelemetry;
        let kind = DetectedCaptcha::Turnstile;
        let captcha_type = CaptchaType::CloudflareTurnstile;
        let method = SolveMethod::BehavioralBypass;
        for outcome in [
            SolveOutcome::Success,
            SolveOutcome::Failure,
            SolveOutcome::Error,
            SolveOutcome::Timeout,
        ] {
            t.record(&SolveEvent {
                solver: "TestSolver",
                captcha_type: &captcha_type,
                kind: &kind,
                domain: "x.test",
                outcome,
                time_ms: 100,
                confidence: None,
                method: &method,
            });
        }
    }

    #[test]
    fn capturing_telemetry_round_trips_event_fields() {
        let cap = Arc::new(CapturingTelemetry {
            events: Mutex::new(Vec::new()),
        });
        let kind = DetectedCaptcha::HCaptcha;
        let captcha_type = CaptchaType::HCaptcha;
        let method = SolveMethod::VisionLLM;

        for (outcome, ms) in [
            (SolveOutcome::Success, 1000_u64),
            (SolveOutcome::Failure, 2000),
            (SolveOutcome::Error, 50),
            (SolveOutcome::Timeout, 30000),
        ] {
            let evt = SolveEvent {
                solver: "TestSolver",
                captcha_type: &captcha_type,
                kind: &kind,
                domain: "x.test",
                outcome,
                time_ms: ms,
                confidence: None,
                method: &method,
            };
            cap.record(&evt);
        }
        let events = cap.events.lock().unwrap();
        assert_eq!(events.len(), 4);
        assert_eq!(events[0].0, SolveOutcome::Success);
        assert_eq!(events[3].2, 30000);
    }

    #[test]
    fn fanout_telemetry_dispatches_to_every_sink_in_order() {
        use std::sync::Arc;
        let a = Arc::new(CapturingTelemetry::new());
        let b = Arc::new(CapturingTelemetry::new());
        let c = Arc::new(CapturingTelemetry::new());
        let fanout = FanoutTelemetry::new()
            .with_sink(a.clone() as Arc<dyn SolverTelemetry>)
            .with_sink(b.clone() as Arc<dyn SolverTelemetry>)
            .with_sink(c.clone() as Arc<dyn SolverTelemetry>);
        assert_eq!(fanout.len(), 3);
        assert!(!fanout.is_empty());

        let kind = crate::detect::DetectedCaptcha::Turnstile;
        let captcha_type = crate::solver::CaptchaType::CloudflareTurnstile;
        let method = crate::solver::SolveMethod::BehavioralBypass;
        let evt = SolveEvent::new(
            "S",
            &captcha_type,
            &kind,
            "ex.com",
            SolveOutcome::Success,
            42,
            Some(0.91),
            &method,
        );
        fanout.record(&evt);
        // All three sinks observed the event exactly once.
        assert_eq!(a.events.lock().unwrap().len(), 1);
        assert_eq!(b.events.lock().unwrap().len(), 1);
        assert_eq!(c.events.lock().unwrap().len(), 1);
    }

    #[test]
    fn fanout_telemetry_empty_default_is_noop() {
        let fanout = FanoutTelemetry::default();
        assert!(fanout.is_empty());
        let kind = crate::detect::DetectedCaptcha::Turnstile;
        let captcha_type = crate::solver::CaptchaType::CloudflareTurnstile;
        let method = crate::solver::SolveMethod::BehavioralBypass;
        let evt = SolveEvent::new(
            "S",
            &captcha_type,
            &kind,
            "ex.com",
            SolveOutcome::Success,
            0,
            None,
            &method,
        );
        // Must not panic.
        fanout.record(&evt);
    }
}