# SLO Usage Guide

This guide shows how to use Charon's blocked ratio SLOs to assess target website anti-bot postures.

## Overview

`stygian-charon` provides service-level objective (SLO) definitions for acceptable blocked request ratios. These thresholds vary by target class to accommodate different security expectations.

## Target Classes

| Class | Description | Typical Blocked Ratio | Use Case |
|-------|-------------|----------------------|----------|
| **API** | Machine-to-machine communication | 0-5% acceptable, 10% warning, >15% critical | REST/GraphQL endpoints, backend services |
| **ContentSite** | Public web content | 0-15% acceptable, 25% warning, >40% critical | News sites, blogs, public portals |
| **HighSecurity** | Banking, auth, sensitive data | 0-30% acceptable, 50% warning, >70% critical | Authentication flows, financial data |
| **Unknown** | Unclassified (conservative) | Same as API | Default fallback |

## Basic Usage

### Get SLO for a Target Class

```rust
use stygian_charon::BlockedRatioSlo;

// Get SLO for an API target
let api_slo = BlockedRatioSlo::api();
assert_eq!(api_slo.acceptable, 0.05);
assert_eq!(api_slo.warning, 0.10);
assert_eq!(api_slo.critical, 0.15);

// Get SLO for a content site
let content_slo = BlockedRatioSlo::content_site();
assert_eq!(content_slo.acceptable, 0.15);

// Dynamically select based on target class
use stygian_charon::TargetClass;
let target = TargetClass::HighSecurity;
let slo = BlockedRatioSlo::for_class(target);
assert_eq!(slo.critical, 0.70);
```

### Assess a Blocked Ratio Against SLO

```rust
use stygian_charon::BlockedRatioSlo;

let slo = BlockedRatioSlo::content_site();
let observed_ratio = 0.20;

// Returns (is_acceptable, is_warning, is_critical)
let (acceptable, warning, critical) = slo.assess(observed_ratio);
assert!(!acceptable);  // 0.20 > 0.15
assert!(warning);      // 0.15 < 0.20 <= 0.25
assert!(!critical);    // 0.20 <= 0.40
```

## Interpretation Guide

### Green Zone (Acceptable)

**Blocked ratio ≤ SLO.acceptable**

- Normal operation for the target class.
- No action required.
- Continue with standard retry/pacing policies.

### Yellow Zone (Warning)

**SLO.acceptable < Blocked ratio ≤ SLO.warning**

- Elevated block rate for the target class.
- Consider reducing concurrency or request rate.
- Monitor for escalation.
- May indicate need for additional anti-bot evasion.

### Red Zone (Critical)

**Blocked ratio > SLO.critical**

- Severe blocks; standard approaches insufficient.
- Switch to high-risk strategies:
  - Enable advanced stealth profiles
  - Use proxy rotation or residential proxies
  - Implement session warmup and human-like interaction
  - Consider browser-based acquisition instead of pure HTTP

## Example: HAR Investigation Workflow

```rust
use stygian_charon::{investigate_har, TargetClass, BlockedRatioSlo};

// Parse and investigate HAR file
let report = investigate_har(har_json)?;

// Determine or guess target class (in real use, this would be user input)
let target_class = TargetClass::ContentSite;
let slo = BlockedRatioSlo::for_class(target_class);

// Extract metrics
let observed_ratio = report.blocked_requests as f64 / report.total_requests as f64;
let (acceptable, warning, critical) = slo.assess(observed_ratio);

// Respond to SLO assessment
if critical {
    println!("🔴 CRITICAL: {} blocks—recommend advanced stealth", report.blocked_requests);
} else if warning {
    println!("🟡 WARNING: {} blocks—consider pacing adjustments", report.blocked_requests);
} else if acceptable {
    println!("🟢 OK: {} blocks—within SLO for {target_class:?}", report.blocked_requests);
}

// Requirements inference incorporates SLO implicitly
let requirements = infer_requirements(&report);
```

## Integration with Policy Planning

The `RuntimePolicy` structure generated by `build_runtime_policy()` already respects risk scoring derived from blocked ratios. SLOs provide context for interpreting those risk signals.

## Live Validation CLI (CHR-013)

Use the live validator to assess a real target URL or an existing HAR file and emit a full JSON report containing HAR data, investigation output, inferred requirements, and runtime policy.

### Validate a live URL

```bash
cargo run -p stygian-charon --example live_slo_validator --features live-validation -- \
    --url https://example.com \
    --target-class content-site \
    --stealth-level medium
```

### Validate from an existing HAR file

```bash
cargo run -p stygian-charon --example live_slo_validator --features live-validation -- \
    --har-path ./capture.har \
    --target-class api \
    --stealth-level low
```

### Output shape

The command prints JSON with these top-level fields:

- `input_url`
- `har_source`
- `target_class`
- `stealth_level`
- `slo_assessment` (including blocked ratio and thresholds)
- `escalation_level`
- `report`
- `requirements`
- `policy`
- `baseline_comparison` (present when `--baseline-compare` is provided)
- `har`

### Save a baseline artifact

```bash
cargo run -p stygian-charon --example live_slo_validator --features live-validation -- \
    --url https://example.com \
    --target-class content-site \
    --stealth-level medium \
    --baseline-out ./charon-baseline.json
```

### Compare against a stored baseline

```bash
cargo run -p stygian-charon --example live_slo_validator --features live-validation -- \
    --url https://example.com \
    --target-class content-site \
    --stealth-level medium \
    --baseline-compare ./charon-baseline.json
```

When a baseline comparison is requested, output includes `baseline_comparison` with:

- `blocked_ratio_delta`
- `risk_score_delta`
- `escalation_changed`
- `recommended_action` (`monitor`, `investigate_regression`, or `improved_stability`)

### Optional live smoke test

An ignored integration smoke test is available for manual runs:

```bash
STYGIAN_LIVE_URL=https://example.com \
cargo test -p stygian-charon --features live-validation --test live_slo_validator -- --ignored --nocapture
```

## Cached Investigation APIs (CHR-014)

The cache layer is opt-in and intended for repeated assessment of the same HAR payloads.

### Enable memory caching

```toml
stygian-charon = { path = "crates/stygian-charon", features = ["caching"] }
```

### Enable Redis-backed caching

```toml
stygian-charon = { path = "crates/stygian-charon", features = ["redis-cache"] }
```

See `docs/caching-integration-guide.md` for backend-specific examples and invalidation behavior.

## Monitoring Assets and Metric Interpretation (CHR-012)

Use the included starter assets for operator-facing monitoring:

- Prometheus scrape config: `docs/monitoring/prometheus-scrape-example.yml`
- Starter dashboard template: `docs/monitoring/slo-dashboard.json`

### Metric Semantics

| Metric | Type | Unit | Interpretation |
|---|---|---|---|
| `slo_assessment_total` | counter | assessments | Total number of SLO assessments processed. |
| `slo_escalation_warning_total` | counter | escalations | Count of assessments entering warning zone. |
| `slo_escalation_critical_total` | counter | escalations | Count of assessments entering critical zone. |
| `slo_blocked_ratio_min` | gauge | ratio (0.0-1.0) | Minimum blocked ratio observed across recorded assessments. |
| `slo_blocked_ratio_max` | gauge | ratio (0.0-1.0) | Maximum blocked ratio observed across recorded assessments. |
| `slo_blocked_ratio_avg` | gauge | ratio (0.0-1.0) | Average blocked ratio observed across recorded assessments. |
| `slo_target_class_total{class="..."}` | counter | assessments | Distribution of assessments by target class. |
| `slo_escalation_level_total{level="..."}` | counter | assessments | Distribution of outcomes by escalation level. |

### Alerting Hints

- Investigate sharp growth in `slo_escalation_critical_total` over short windows.
- Compare `slo_blocked_ratio_avg` with class-specific thresholds for sustained drift.
- Track class distribution changes via `slo_target_class_total` to avoid misinterpreting aggregate trends.

## Future Enhancements

- **CHR-008**: Dynamic SLO adjustment based on target content/domain patterns
- **CHR-009**: SLO-driven acquisition strategy escalation
- **CHR-010**: SLO dashboard and trending analytics
