# Implementation Plan: Safe Periodic Run Scheduler (LEAD-GEN)

## 1. Goal & Architecture Overview

The objective is to implement an enterprise-grade, domain-agnostic, safe periodic run scheduler for the **LEAD-GEN** engine. The scheduler orchestrates recurring discovery and qualification cycles across configured campaigns while strictly enforcing safety invariants:

- **Zero Overlap**: Mutual exclusion across worker processes/threads per campaign.
- **Fail-Safe Defaults**: Disabled out-of-the-box (`enabled: false`) until end-to-end tests pass and explicit operator enablement.
- **Per-Campaign Granular Control**: Independent pause/resume switches and status flags.
- **Strict Budgeting & Throttling**: Execution count, discovery limit, and cost/API call caps per time window (hourly/daily).
- **Incremental Discovery & Deduplication**: Checkpoint/watermark state tracking to process only unseen signals, backed by fingerprint-based deduplication.
- **Resilient Recovery**: Stale lock eviction, process crash recovery, and transaction rollback/cleanup.
- **Comprehensive Audit Logging**: Structured execution logs capturing runtime metrics, step traces, item yields, and errors.

```mermaid
flowchart TD
    A[Scheduler Tick / Trigger] --> B{Global Scheduler Enabled?}
    B -- No --> C[Log Skip & Idle]
    B -- Yes --> D[Fetch Active Campaigns]
    
    D --> E[Iterate Campaign Configs]
    E --> F{Campaign Paused or Inactive?}
    F -- Yes --> G[Skip Campaign]
    F -- No --> H{Budget Exhausted?}
    H -- Yes --> I[Log Budget Capped & Skip]
    H -- No --> J[Acquire Campaign Lock]
    
    J -- Lock Busy --> K[Skip: Overlap Prevented]
    J -- Lock Acquired --> L[Execute Campaign Cycle]
    
    subgraph ExecutionCycle [Campaign Execution Cycle]
        L1[Load Watermark / Cursor] --> L2[Incremental Discovery Step]
        L2 --> L3[Deduplicate Signals / Entities]
        L3 --> L4[Process & Qualify Leads]
        L4 --> L5[Update Budgets & Checkpoints]
    end
    
    L --> ExecutionCycle
    ExecutionCycle --> M[Persist Run Audit Log]
    ExecutionCycle -- Crash / Failure --> N[Recover / Mark Failed & Release Lock]
    ExecutionCycle -- Success --> O[Mark Succeeded & Release Lock]
```

---

## 2. Key Components & Implementation Details

### A. Configuration & State Management
- **Scheduler Config (`config/scheduler.yaml` / Settings Schema)**:
  - `enabled: false` (default safety switch).
  - `tick_interval_seconds`: Scheduler evaluation cadence (e.g., 60s).
  - `max_concurrent_campaigns`: Global worker pool limit.
  - `stale_lock_timeout_seconds`: TTL after which orphaned locks are reclaimed (e.g., 300s).
- **Campaign Run State (`CampaignScheduleState`)**:
  - `campaign_id`: Unique identifier.
  - `is_paused`: Boolean flag for administrative hold.
  - `last_run_at`, `next_run_at`: Timestamp tracking.
  - `cursor_state`: Domain-agnostic dictionary storing source watermarks (e.g., `{"last_seen_timestamp": "...", "offset": 120}`).
  - `budget_usage`: Trackers for daily runs, discoveries, and API usage counters with reset intervals.

### B. Mutual Exclusion & Lock Manager (`scheduler/lock_manager.py`)
- Provides atomicity for both single-node and multi-process deployments.
- Implements `CampaignLockManager` supporting file-based lock leases with PID/heartbeat or database row locks (`SELECT ... FOR UPDATE` / atomic compare-and-swap).
- **Stale Lock Recovery**: Locks contain lease creation timestamps, hostnames, and TTLs. If a worker terminates abruptly, locks older than `stale_lock_timeout_seconds` without a valid heartbeat are safely evicted with an audit warning.

### C. Budget & Rate Limiting (`scheduler/budget_guard.py`)
- Configurable per-campaign budget constraints:
  - `max_runs_per_day`: Hard ceiling on invocation count.
  - `max_discoveries_per_run`: Cap on raw candidate entities pulled per cycle.
  - `max_leads_per_day`: Ceiling on newly qualified lead cards.
  - `cooldown_period_seconds`: Minimum elapsed time between completed cycles.
- When any threshold is exceeded, the run is skipped and annotated in the audit logs (`BUDGET_EXHAUSTED`).

### D. Incremental Discovery & Deduplication Pipeline (`scheduler/discovery_runner.py`)
- **Incremental State Cursor**:
  - Discovery workers accept the previous checkpoint cursor (timestamps, IDs, pagination tokens) and return updated checkpoints along with newly discovered candidates.
  - State updates are committed atomically alongside processed records.
- **Deduplication Engine**:
  - Canonical hash generator based on entity identifier fields (e.g., canonical domain, registration number, or normalized primary identifier).
  - Maintains persistent deduplication bloom filter or database unique indexes to reject already seen signals before qualifying leads.

### E. Crash Recovery & Resilience (`scheduler/recovery.py`)
- **Interrupted Run Detection**:
  - On scheduler startup, inspect runs in `RUNNING` status without active process heartbeats.
  - Transition orphaned runs to `FAILED_ABORTED` with clear diagnostic notes.
  - Roll back partial uncommitted lead cards or reset uncommitted cursor advances to prevent data loss or silent skips.

### F. Structured Audit Logging (`scheduler/audit_logger.py`)
- Standardized execution record for every run:
  - `run_id`: UUID4.
  - `campaign_id`: Target campaign.
  - `status`: `PENDING` | `RUNNING` | `COMPLETED` | `FAILED` | `SKIPPED_PAUSED` | `SKIPPED_LOCKED` | `SKIPPED_BUDGET`.
  - `start_time`, `end_time`, `duration_ms`.
  - `metrics`: `{ "discovered_count": int, "deduped_count": int, "qualified_count": int, "cost_units": float }`.
  - `error_details`: Exception type, stack trace, and recovery action taken.

---

## 3. Proposed File & Module Structure

```text
src/lead_gen/
├── core/
│   └── models/
│       ├── schedule.py          # Data models: ScheduleConfig, CampaignRunState, RunAuditLog
│       └── budget.py            # BudgetRules, BudgetUsageTracker
├── scheduler/
│   ├── __init__.py
│   ├── engine.py                # Main SchedulerEngine loop and tick handler
│   ├── lock_manager.py          # Atomic locking with lease TTL and stale-lock recovery
│   ├── budget_guard.py          # Budget limit checks and quota resets
│   ├── incremental.py           # Checkpoint state persistence & watermark tracking
│   ├── deduplication.py         # Entity & signal deduplication store
│   ├── runner.py                # Isolated execution wrapper per campaign
│   └── audit.py                 # Structured run auditing and event logger
tests/
├── scheduler/
│   ├── test_engine_safety.py    # Default disabled checks, pause/resume tests
│   ├── test_lock_manager.py     # Concurrency, anti-overlap, and stale lock recovery tests
│   ├── test_budget_guard.py     # Rate limit caps and daily budget exhaustion tests
│   ├── test_incremental.py      # Watermark progression and deduplication verification
│   └── test_crash_recovery.py   # Simulating crashes, stale lease clearing, and rollbacks
```

---

## 4. Verification & Testing Strategy

1. **Safety Default Verification**:
   - Assert engine initialization with unmodified configuration results in `state = DISABLED`.
   - Verify zero background tasks, timers, or worker loops spawn when `enabled: false`.

2. **Concurrency & No-Overlap Tests**:
   - Launch multiple parallel execution triggers for the same campaign.
   - Assert that exactly one execution acquires the lock; all concurrent attempts yield `SKIPPED_LOCKED` without blocking or throwing unhandled errors.

3. **Per-Campaign Pause & Resume**:
   - Toggle `is_paused = true` on active campaigns.
   - Verify ticks skip the paused campaign while continuing unaffected campaigns.
   - Resume campaign and verify execution proceeds seamlessly on next tick.

4. **Budget & Limit Enforcement**:
   - Set mock limits (e.g., `max_runs_per_day: 2`).
   - Execute 3 consecutive triggers; verify the 3rd trigger cleanly aborts with `BUDGET_EXHAUSTED` and records appropriate audit logs.

5. **Incremental Discovery & Deduplication**:
   - Simulate a discovery batch returning items with IDs `[A, B, C]`.
   - Verify cursor advances to `C`.
   - On the next run, return `[B, C, D]`; verify `[B, C]` are filtered out via deduplication and only `[D]` proceeds.

6. **Crash & Orphan Recovery**:
   - Create a lock file/record with an expired timestamp (simulating a dead worker process).
   - Verify the scheduler detects stale lease, logs an alert, frees the lock, and resumes scheduled runs cleanly.