# Implementation Plan: Safe Periodic Run Scheduler for Lead Generation

## Goal Description
Implement a domain-agnostic, safe periodic execution scheduler for the lead generation engine. The scheduler manages automated discovery and qualification jobs across multiple campaigns while strictly preventing runaway execution, overlapping runs, or quota blowouts.

Key capabilities required:
1. **Default-Disabled Guardrail**: The scheduler engine is disabled by default (`scheduler_enabled = False`) until explicitly enabled in production after passing all automated test suites.
2. **Per-Campaign Pause & State Control**: Ability to pause, resume, throttle, or terminate execution on a per-campaign basis without affecting other campaigns.
3. **Strict Concurrency Locks (No Overlap)**: Distributed/lease-based locking mechanism with heartbeats and TTL to ensure no two runs execute concurrently for the same campaign.
4. **Budget & Rate Quota Enforcement**: Pre-run and in-flight budget checks (e.g., maximum discovery queries, token/cost caps, lead intake ceilings) preventing runaway API or compute costs.
5. **Incremental Discovery & Cursor Persistence**: State/watermark tracking across runs so discovery engines only ingest new signals since the last successful checkpoint.
6. **Deduplication Engine**: Fingerprinting and deduplication across batches and historical runs to prevent reprocessing identical signals or target entities.
7. **Crash Recovery & Stale Lock Reaping**: Automatic recovery from abrupt process terminations or crashed workers, cleaning up abandoned locks and resuming safe state.
8. **Structured Run Logging & Audit Trail**: Full telemetry logging (run IDs, timing, items discovered, budget consumed, errors) with source and date provenance.

---

## User Review Required

> [!IMPORTANT]
> **Safety Default**: The scheduler will ship with `LEADGEN_SCHEDULER_ENABLED=False` as the default environment configuration. No background jobs will fire until end-to-end and safety tests pass and an administrator explicitly sets this flag to `True`.

> [!WARNING]
> **Domain-Agnostic Core**: The scheduler operates strictly on abstract campaign definitions and generic job interfaces. Campaign-specific rules (such as search parameters for the European Software Licensing pilot) are injected strictly via external campaign configuration.

---

## Open Questions

> [!NOTE]
> 1. **Persistence Backend for Locks & State**: Should the initial implementation rely on a filesystem/SQLite transactional store (zero external dependencies) or an external key-value store (e.g., Redis / Postgres)? *Recommendation: Implement a modular lock/state interface with a transactional SQLite/File implementation as the default built-in backend, allowing Redis/Postgres pluggability later.*
> 2. **Job Runner Model**: Should the scheduler execute tasks in-process via an async event loop/thread pool, or dispatch to external worker processes (e.g., Celery/subprocess)? *Recommendation: Lightweight internal worker executor with async task dispatch for MVP, keeping deployment simple while maintaining strict process isolation.*

---

## Architecture & Execution Flow

```mermaid
flowchart TD
    Tick["Scheduler Tick"] --> CheckGlobal{"Scheduler Enabled?"}
    CheckGlobal -- No --> Idle["Log & Sleep (Safe State)"]
    CheckGlobal -- Yes --> SweepLocks["Run Lock Reaper / Crash Recovery"]
    SweepLocks --> GetCampaigns["Fetch Active Campaigns"]
    
    GetCampaigns --> IterateCampaign["For Each Campaign"]
    IterateCampaign --> CheckPause{"Campaign Paused?"}
    CheckPause -- Yes --> SkipPaused["Skip Campaign"]
    CheckPause -- No --> CheckBudget{"Budget Remaining?"}
    CheckBudget -- No --> SkipBudget["Log Budget Exceeded & Skip"]
    CheckBudget -- Yes --> AcquireLock{"Acquire Run Lock (TTL)"}
    
    AcquireLock -- Failed --> SkipOverlap["Log Lock Contention (No Overlap)"]
    AcquireLock -- Acquired --> LoadCursor["Load Incremental Watermark / Cursor"]
    
    LoadCursor --> ExecuteJob["Execute Incremental Discovery & Qualify"]
    ExecuteJob --> Dedupe["Deduplicate Signals & Leads"]
    Dedupe --> Commit["Save Entities & Update Watermark"]
    Commit --> DeductBudget["Deduct Consumed Budget"]
    DeductBudget --> ReleaseLock["Release Lock & Write Audit Log"]
```

---

## Proposed Changes

### Core Scheduler & Execution Engine

---

#### [NEW] `core/scheduler/models.py`
Data schemas for campaign run state, execution budgets, scheduler configuration, and execution logs:
- `SchedulerConfig`:
  - `enabled: bool = False` (Safety guardrail)
  - `tick_interval_seconds: int = 60`
  - `max_concurrent_campaigns: int = 5`
  - `lock_ttl_seconds: int = 300`
- `CampaignRunBudget`:
  - `max_queries_per_run: int`
  - `max_signals_per_day: int`
  - `max_cost_units_per_day: float`
  - `current_day_cost_units: float`
  - `reset_at: datetime`
- `CampaignScheduleState`:
  - `campaign_id: str`
  - `is_paused: bool = False`
  - `last_run_started_at: Optional[datetime]`
  - `last_run_completed_at: Optional[datetime]`
  - `next_run_earliest_at: Optional[datetime]`
  - `last_watermark: Dict[str, Any]` (source offsets, timestamps)
- `RunAuditRecord`:
  - `run_id: str`
  - `campaign_id: str`
  - `status: Literal["SUCCESS", "FAILED", "SKIPPED", "TERMINATED"]`
  - `started_at: datetime`
  - `ended_at: datetime`
  - `items_discovered: int`
  - `items_deduplicated: int`
  - `budget_consumed: float`
  - `error_message: Optional[str]`

---

#### [NEW] `core/scheduler/lock_manager.py`
Lease-based lock provider ensuring strict run exclusivity:
- `LockManager` (Abstract interface) and `FileLockManager` / `SqliteLockManager`:
  - `acquire_lock(campaign_id: str, owner_id: str, ttl_seconds: int) -> bool`
  - `renew_lock(campaign_id: str, owner_id: str, ttl_seconds: int) -> bool`
  - `release_lock(campaign_id: str, owner_id: str) -> bool`
  - `reap_stale_locks(ttl_seconds: int) -> List[str]` (identifies dead processes and cleans up)
- Prevents overlapping runs if a previous run is still processing or hung.

---

#### [NEW] `core/scheduler/budget_manager.py`
Monitors and enforces operational spending and rate constraints:
- `BudgetManager`:
  - `has_available_budget(campaign_id: str, required_units: float = 1.0) -> bool`
  - `record_consumption(campaign_id: str, units: float)`
  - `reset_daily_quotas_if_expired(campaign_id: str)`
- Hard stops execution when limits are hit, emitting alerts and logging reason.

---

#### [NEW] `core/scheduler/state_store.py`
Persistent state, checkpointing, and incremental cursor tracking:
- `StateStore`:
  - `get_watermark(campaign_id: str, source_id: str) -> Optional[Dict[str, Any]]`
  - `update_watermark(campaign_id: str, source_id: str, cursor: Dict[str, Any])`
  - `set_campaign_pause(campaign_id: str, is_paused: bool)`
  - `get_campaign_status(campaign_id: str) -> CampaignScheduleState`

---

#### [NEW] `core/scheduler/deduplicator.py`
Idempotent deduplication engine for incremental signal and entity ingestion:
- `Deduplicator`:
  - Computes deterministic SHA-256 fingerprint from entity identifiers and evidence provenance (e.g., `source_url`, `signal_hash`, `entity_canonical_id`).
  - `is_duplicate(campaign_id: str, fingerprint: str) -> bool`
  - `register_fingerprints(campaign_id: str, fingerprints: List[str])`
  - Guarantees identical signals discovered across consecutive runs are discarded immediately before qualification.

---

#### [NEW] `core/scheduler/recovery.py`
Zombie run detection and safe recovery:
- `RecoveryManager`:
  - Detects runs marked `IN_PROGRESS` whose lock expired without completion.
  - Transitions run status to `RECOVERED_ZOMBIE`.
  - Reverts uncommitted watermarks to the last known healthy checkpoint.
  - Unlocks the campaign so subsequent scheduled ticks can safely resume.

---

#### [NEW] `core/scheduler/runner.py`
Main safe scheduler loop and job orchestrator:
- `SafeScheduler`:
  - Checks global `enabled` toggle. If `False`, ticks safely without starting jobs.
  - Periodic tick loop executing:
    1. Lock and crash recovery check.
    2. Active campaign enumeration.
    3. Filtering out paused or budget-exhausted campaigns.
    4. Acquiring per-campaign lock.
    5. Loading cursor & running incremental discovery callback.
    6. Passing new signals through `Deduplicator`.
    7. Updating cursor & committing batch results.
    8. Recording budget consumption and audit logs.
    9. Releasing lock.
  - Safe signal handlers (`SIGTERM`, `SIGINT`) allowing in-flight runs to finish or gracefully yield locks.

---

## Verification Plan

### Automated Tests

```bash
# Run all scheduler test suites
pytest tests/core/scheduler -v
```

1. **Safety Default Tests (`test_default_disabled.py`)**:
   - Verify scheduler instantiates with `enabled=False` by default.
   - Verify calling `scheduler.tick()` performs zero executions, no locks acquired, and logs safety idle status.
   - Verify explicit config override is required to enable.

2. **Per-Campaign Pause/Resume Tests (`test_campaign_pause.py`)**:
   - Pause campaign A, leave campaign B active.
   - Run tick: Verify campaign B executes, campaign A is bypassed with `SKIPPED_PAUSED` logged.
   - Unpause campaign A: Verify campaign A executes on next tick.

3. **Concurrency & Lock Exclusivity Tests (`test_locks_no_overlap.py`)**:
   - Start long-running job for Campaign X.
   - Trigger second concurrent run for Campaign X.
   - Verify second run fails to acquire lock, logs lock contention, and exits cleanly without overlapping.

4. **Crash Recovery & Zombie Reaping Tests (`test_recovery.py`)**:
   - Simulate crashed run by writing lock and `IN_PROGRESS` state with backdated timestamp.
   - Run scheduler tick: Verify lock reaper frees the lock, marks abandoned run as `RECOVERED_ZOMBIE`, restores watermark, and allows new run.

5. **Budget Enforcement Tests (`test_budget_enforcement.py`)**:
   - Set daily query limit to 10.
   - Execute job consuming 10 queries.
   - Trigger subsequent run: Verify job is blocked before executing discovery due to exhausted quota.

6. **Incremental Discovery & Deduplication Tests (`test_incremental_and_dedupe.py`)**:
   - Run 1: Discover 5 signals, verify cursor advances to latest timestamp.
   - Run 2: Provide overlapping batch; verify previously seen signals are rejected by deduplicator and only net-new items are processed.

### Manual Verification
1. Inspect CLI/Environment controls: run scheduler binary with default environment and confirm terminal outputs `"Scheduler is currently disabled by configuration (LEADGEN_SCHEDULER_ENABLED=false). No jobs scheduled."`
2. Run campaign simulation in dry-run mode with `LEADGEN_SCHEDULER_ENABLED=true` and confirm audit logs emit structured JSON records with zero external network outreach.