# Quick Task: Periodic Checkpoint Persistence + DRY Consolidation

## Goal

Add periodic forming bar checkpoint persistence to survive SIGKILL/OOM, and consolidate duplicated code patterns identified by three audit agents.

## Tasks

### Task 1: Extract `cache_pool.py` (DRY)

**File**: `python/opendeviationbar/cache_pool.py` (NEW)

Extract thread-local ClickHouse cache pattern duplicated in:

- `python/opendeviationbar/kintsugi/_helpers.py:34-50`
- `scripts/repair_direct_parquet.py:82-107`

Functions:

- `get_thread_local_cache() -> OpenDeviationBarCache`
- `close_thread_local_cache() -> None`

Update both callers to import from `cache_pool.py`.

### Task 2: Extract `systemd_utils.py` (DRY)

**File**: `python/opendeviationbar/systemd_utils.py` (NEW)

Extract `is_systemd_service_active(unit_name)` duplicated in:

- `python/opendeviationbar/sidecar/aion_junction_heal.py:30-44`
- `scripts/heartbeat/checks/services.py:82-91`
- `python/opendeviationbar/kintsugi/discovery.py:610-630`

Single function, three callers updated.

### Task 3: Centralize repair checkpoint path (DRY)

**File**: Extend `python/opendeviationbar/sidecar/checkpoint.py`

Add `_repair_checkpoint_dir() -> Path` and `load_repair_checkpoint(symbol, threshold) -> dict | None`.

Currently hardcoded in:

- `scripts/repair_direct_parquet.py:355` (save)
- `python/opendeviationbar/sidecar/__init__.py:358` (load)
- `python/opendeviationbar/sidecar/bulk_populate.py` (if applicable)

### Task 4: Periodic forming bar checkpoint persistence (CORE FEATURE)

**File**: `python/opendeviationbar/sidecar/__init__.py` (main loop)

In the main loop, every 60 seconds:

1. Call `engine.collect_checkpoints(timeout_ms=5000)`
2. Parse the `"SYMBOL:THRESHOLD"` keyed dict
3. Save each via `_save_checkpoint(sym, thr, {}, processor_checkpoint=cp_dict)`
4. Log count + elapsed to NDJSON

This ensures the forming bar state is at most 60s stale on SIGKILL/OOM.

### Task 5: Wire checkpoint telemetry events

**File**: `python/opendeviationbar/sidecar/checkpoint.py` (extend)

Add NDJSON telemetry for:

- `checkpoint_persisted` — periodic save completed (pairs_saved, elapsed_ms)
- `checkpoint_loaded` — startup loaded forming bar state (pairs_restored)
- `checkpoint_stale` — loaded checkpoint older than 5 min (age_seconds)

Use existing `log_checkpoint_event()` from `opendeviationbar.logging`.

## Verification

- `ruff check` passes
- `git diff` shows no unintended changes
- Sidecar restart on bigblack loads checkpoints correctly
