"""Durable SQLite-backed ingestion jobs and a single-process worker."""
from __future__ import annotations
import json
import logging
import math
import random
import re
import sqlite3
import threading
import uuid
from collections.abc import Callable
from dataclasses import asdict, dataclass
from datetime import UTC, datetime, timedelta
from pathlib import Path
from typing import Any, Self
from .ingestion import DocumentIngestionPipeline
from .logging_config import correlation_context
logger = logging.getLogger(__name__)
def _utc_now() -> datetime:
return datetime.now(UTC)
def _timestamp(value: datetime) -> str:
return value.isoformat(timespec="microseconds")
[docs]
@dataclass(frozen=True, slots=True)
class IngestionJob:
"""Public, serialisable state for one queued document ingestion."""
id: str
source: str
status: str
created_at: str
updated_at: str
attempts: int
started_at: str | None = None
completed_at: str | None = None
available_at: str | None = None
error_type: str | None = None
error_message: str | None = None
result: dict[str, Any] | None = None
idempotency_key: str | None = None
[docs]
def to_dict(self) -> dict[str, Any]:
"""Return a JSON-compatible public representation."""
return asdict(self)
[docs]
class SQLiteJobStore:
"""Transactional persistent queue for ingestion jobs.
The store is safe to share between threads and uses ``BEGIN IMMEDIATE``
when claiming work so multiple worker processes cannot claim the same job.
A deployment should still run one worker per queue database unless it has
an explicit multi-process capacity plan.
"""
[docs]
def __init__(self, database: str | Path, *, timeout: float = 5.0) -> None:
if not math.isfinite(timeout) or timeout <= 0:
raise ValueError("timeout must be finite and positive")
self.database = str(database)
if self.database != ":memory:":
Path(self.database).expanduser().parent.mkdir(parents=True, exist_ok=True)
self._lock = threading.RLock()
self._connection = sqlite3.connect(
self.database, timeout=timeout, check_same_thread=False
)
self._connection.row_factory = sqlite3.Row
self._connection.execute("PRAGMA busy_timeout = 5000")
if self.database != ":memory:":
self._connection.execute("PRAGMA journal_mode = WAL")
self._connection.execute(
"""
CREATE TABLE IF NOT EXISTS ingestion_jobs (
id TEXT PRIMARY KEY,
source TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled')),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
started_at TEXT,
completed_at TEXT,
available_at TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
error_type TEXT,
error_message TEXT,
result_json TEXT,
idempotency_key TEXT
)
"""
)
schema_row = self._connection.execute(
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'ingestion_jobs'"
).fetchone()
if schema_row and "'cancelled'" not in schema_row["sql"]:
# Upgrade the early queue schema without losing pending job history.
self._connection.execute("BEGIN IMMEDIATE")
self._connection.execute(
"ALTER TABLE ingestion_jobs RENAME TO ingestion_jobs_legacy"
)
self._connection.execute(
"""CREATE TABLE ingestion_jobs (
id TEXT PRIMARY KEY,
source TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('queued', 'running', 'succeeded', 'failed', 'cancelled')),
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
started_at TEXT,
completed_at TEXT,
available_at TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts >= 0),
error_type TEXT,
error_message TEXT,
result_json TEXT,
idempotency_key TEXT
)"""
)
self._connection.execute(
"""INSERT INTO ingestion_jobs
SELECT id, source, status, created_at, updated_at, started_at,
completed_at, available_at, attempts, error_type,
error_message, result_json, NULL
FROM ingestion_jobs_legacy"""
)
self._connection.execute("DROP TABLE ingestion_jobs_legacy")
self._connection.commit()
columns = {
row["name"]
for row in self._connection.execute("PRAGMA table_info(ingestion_jobs)")
}
if "idempotency_key" not in columns:
self._connection.execute(
"ALTER TABLE ingestion_jobs ADD COLUMN idempotency_key TEXT"
)
self._connection.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS idx_ingestion_jobs_idempotency "
"ON ingestion_jobs(idempotency_key) WHERE idempotency_key IS NOT NULL"
)
self._connection.execute(
"CREATE INDEX IF NOT EXISTS idx_ingestion_jobs_queue "
"ON ingestion_jobs(status, available_at, created_at)"
)
self._connection.commit()
self._closed = False
def _ensure_open(self) -> None:
if self._closed:
raise RuntimeError("SQLiteJobStore is closed")
@staticmethod
def _from_row(row: sqlite3.Row | None) -> IngestionJob | None:
if row is None:
return None
return IngestionJob(
id=row["id"],
source=row["source"],
status=row["status"],
created_at=row["created_at"],
updated_at=row["updated_at"],
attempts=row["attempts"],
started_at=row["started_at"],
completed_at=row["completed_at"],
available_at=row["available_at"],
error_type=row["error_type"],
error_message=row["error_message"],
result=json.loads(row["result_json"]) if row["result_json"] else None,
idempotency_key=row["idempotency_key"],
)
[docs]
def enqueue(
self, source: str | Path, *, idempotency_key: str | None = None
) -> IngestionJob:
"""Persist a new job or return the existing job for an idempotency key."""
return self.enqueue_with_status(source, idempotency_key=idempotency_key)[0]
[docs]
def enqueue_with_status(
self, source: str | Path, *, idempotency_key: str | None = None
) -> tuple[IngestionJob, bool]:
"""Enqueue atomically and report whether a new job was created."""
source_text = str(source).strip()
if not source_text:
raise ValueError("source must not be empty")
if idempotency_key is not None:
idempotency_key = idempotency_key.strip()
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", idempotency_key):
raise ValueError("idempotency_key must be 1-128 safe ASCII characters")
now = _timestamp(_utc_now())
job_id = str(uuid.uuid4())
with self._lock:
self._ensure_open()
try:
self._connection.execute("BEGIN IMMEDIATE")
if idempotency_key is not None:
row = self._connection.execute(
"SELECT * FROM ingestion_jobs WHERE idempotency_key = ?",
(idempotency_key,),
).fetchone()
if row is not None:
existing = self._from_row(row)
if existing.source != source_text:
raise ValueError(
"idempotency_key was already used for a different source"
)
self._connection.commit()
return existing, False # type: ignore[return-value]
self._connection.execute(
"""INSERT INTO ingestion_jobs
(id, source, status, created_at, updated_at, available_at, idempotency_key)
VALUES (?, ?, 'queued', ?, ?, ?, ?)""",
(job_id, source_text, now, now, now, idempotency_key),
)
self._connection.commit()
return self.get(job_id), True # type: ignore[return-value]
except Exception:
self._connection.rollback()
raise
[docs]
def get_by_idempotency_key(self, idempotency_key: str) -> IngestionJob | None:
"""Return the durable job associated with an idempotency key."""
with self._lock:
self._ensure_open()
row = self._connection.execute(
"SELECT * FROM ingestion_jobs WHERE idempotency_key = ?",
(idempotency_key,),
).fetchone()
return self._from_row(row)
[docs]
def get(self, job_id: str) -> IngestionJob | None:
"""Return a job by ID, or ``None`` when it does not exist."""
with self._lock:
self._ensure_open()
row = self._connection.execute(
"SELECT * FROM ingestion_jobs WHERE id = ?", (job_id,)
).fetchone()
return self._from_row(row)
[docs]
def list_jobs(
self, *, limit: int = 50, status: str | None = None
) -> tuple[IngestionJob, ...]:
"""List recent jobs, optionally filtered by lifecycle status."""
if not 1 <= limit <= 500:
raise ValueError("limit must be between 1 and 500")
if status is not None and status not in {
"queued",
"running",
"succeeded",
"failed",
"cancelled",
}:
raise ValueError("invalid job status")
query = "SELECT * FROM ingestion_jobs"
parameters: tuple[Any, ...] = ()
if status is not None:
query += " WHERE status = ?"
parameters = (status,)
query += " ORDER BY created_at DESC, id DESC LIMIT ?"
parameters += (limit,)
with self._lock:
self._ensure_open()
rows = self._connection.execute(query, parameters).fetchall()
return tuple(self._from_row(row) for row in rows if row is not None)
[docs]
def counts(self) -> dict[str, int]:
"""Return counts by lifecycle state for health and operations."""
with self._lock:
self._ensure_open()
rows = self._connection.execute(
"SELECT status, COUNT(*) AS count FROM ingestion_jobs GROUP BY status"
).fetchall()
result = {
name: 0
for name in ("queued", "running", "succeeded", "failed", "cancelled")
}
result.update({row["status"]: row["count"] for row in rows})
return result
[docs]
def recover_interrupted(self, *, max_attempts: int = 3) -> int:
"""Requeue interrupted jobs with attempts remaining; fail exhausted jobs."""
if (
isinstance(max_attempts, bool)
or not isinstance(max_attempts, int)
or max_attempts < 1
):
raise ValueError("max_attempts must be a positive integer")
now = _timestamp(_utc_now())
with self._lock:
self._ensure_open()
cursor = self._connection.execute(
"""UPDATE ingestion_jobs
SET status = CASE WHEN attempts < ? THEN 'queued' ELSE 'failed' END,
updated_at = ?, available_at = ?, started_at = NULL,
completed_at = CASE WHEN attempts < ? THEN NULL ELSE ? END,
error_type = 'WorkerInterrupted',
error_message = 'Worker stopped before recording completion'
WHERE status = 'running'""",
(max_attempts, now, now, max_attempts, now),
)
self._connection.commit()
return cursor.rowcount
[docs]
def claim_next(self) -> IngestionJob | None:
"""Atomically claim the oldest available queued job."""
now = _timestamp(_utc_now())
with self._lock:
self._ensure_open()
try:
self._connection.execute("BEGIN IMMEDIATE")
row = self._connection.execute(
"""SELECT id FROM ingestion_jobs
WHERE status = 'queued' AND available_at <= ?
ORDER BY created_at, id LIMIT 1""",
(now,),
).fetchone()
if row is None:
self._connection.commit()
return None
self._connection.execute(
"""UPDATE ingestion_jobs
SET status = 'running', attempts = attempts + 1,
started_at = ?, updated_at = ?, error_type = NULL,
error_message = NULL
WHERE id = ? AND status = 'queued'""",
(now, now, row["id"]),
)
self._connection.commit()
return self.get(row["id"])
except Exception:
self._connection.rollback()
raise
[docs]
def complete(self, job_id: str, result: dict[str, Any]) -> IngestionJob:
"""Mark a running job successful and persist its compact result."""
payload = json.dumps(result, ensure_ascii=False, allow_nan=False)
now = _timestamp(_utc_now())
with self._lock:
self._ensure_open()
cursor = self._connection.execute(
"""UPDATE ingestion_jobs
SET status = 'succeeded', updated_at = ?, completed_at = ?,
result_json = ?, error_type = NULL, error_message = NULL
WHERE id = ? AND status = 'running'""",
(now, now, payload, job_id),
)
if cursor.rowcount != 1:
raise ValueError("job is not in the running state")
self._connection.commit()
return self.get(job_id) # type: ignore[return-value]
[docs]
def fail(
self,
job_id: str,
*,
error_type: str,
error_message: str,
max_attempts: int,
retry_delay: float,
) -> IngestionJob:
"""Record failure and schedule a bounded retry when attempts remain."""
if (
isinstance(max_attempts, bool)
or not isinstance(max_attempts, int)
or max_attempts < 1
or not math.isfinite(retry_delay)
or retry_delay < 0
):
raise ValueError(
"max_attempts must be a positive integer and retry_delay finite and non-negative"
)
now_dt = _utc_now()
now = _timestamp(now_dt)
with self._lock:
self._ensure_open()
row = self._connection.execute(
"SELECT attempts FROM ingestion_jobs WHERE id = ? AND status = 'running'",
(job_id,),
).fetchone()
if row is None:
raise ValueError("job is not in the running state")
retry = row["attempts"] < max_attempts
status = "queued" if retry else "failed"
available = _timestamp(now_dt + timedelta(seconds=retry_delay))
self._connection.execute(
"""UPDATE ingestion_jobs
SET status = ?, updated_at = ?, available_at = ?,
completed_at = ?, error_type = ?, error_message = ?
WHERE id = ?""",
(
status,
now,
available,
None if retry else now,
error_type[:200],
error_message[:4000],
job_id,
),
)
self._connection.commit()
return self.get(job_id) # type: ignore[return-value]
[docs]
def cancel(self, job_id: str) -> IngestionJob:
"""Cancel a queued job; running and terminal jobs cannot be cancelled."""
now = _timestamp(_utc_now())
with self._lock:
self._ensure_open()
cursor = self._connection.execute(
"""UPDATE ingestion_jobs
SET status = 'cancelled', updated_at = ?, completed_at = ?
WHERE id = ? AND status = 'queued'""",
(now, now, job_id),
)
if cursor.rowcount != 1:
self._connection.rollback()
raise ValueError("only queued jobs can be cancelled")
self._connection.commit()
return self.get(job_id) # type: ignore[return-value]
[docs]
def retry(self, job_id: str) -> IngestionJob:
"""Manually requeue a terminal failed job and reset its attempt count."""
now = _timestamp(_utc_now())
with self._lock:
self._ensure_open()
cursor = self._connection.execute(
"""UPDATE ingestion_jobs
SET status = 'queued', updated_at = ?, available_at = ?,
started_at = NULL, completed_at = NULL, attempts = 0,
error_type = NULL, error_message = NULL, result_json = NULL
WHERE id = ? AND status = 'failed'""",
(now, now, job_id),
)
if cursor.rowcount != 1:
self._connection.rollback()
raise ValueError("only failed jobs can be retried")
self._connection.commit()
return self.get(job_id) # type: ignore[return-value]
[docs]
def health_check(self) -> bool:
"""Run a lightweight database round-trip without scanning job history."""
with self._lock:
self._ensure_open()
self._connection.execute("SELECT 1").fetchone()
return True
[docs]
def close(self) -> None:
"""Close the underlying SQLite connection."""
with self._lock:
if not self._closed:
self._connection.close()
self._closed = True
def __enter__(self) -> Self:
self._ensure_open()
return self
def __exit__(self, *_: object) -> None:
self.close()
[docs]
class IngestionWorker:
"""Single-threaded background worker with durable retries and recovery."""
[docs]
def __init__(
self,
job_store: SQLiteJobStore,
pipeline: DocumentIngestionPipeline,
*,
poll_interval: float = 0.5,
max_attempts: int = 3,
retry_base_delay: float = 1.0,
retry_max_delay: float = 30.0,
retry_jitter_fraction: float = 0.2,
retryable_exceptions: tuple[type[Exception], ...] = (
TimeoutError,
ConnectionError,
OSError,
sqlite3.OperationalError,
),
random_uniform: Callable[[float, float], float] | None = None,
source_validator: Callable[[str], str | Path] | None = None,
) -> None:
if not math.isfinite(poll_interval) or poll_interval <= 0:
raise ValueError("poll_interval must be finite and positive")
if (
isinstance(max_attempts, bool)
or not isinstance(max_attempts, int)
or max_attempts < 1
):
raise ValueError("max_attempts must be a positive integer")
if (
not math.isfinite(retry_base_delay)
or not math.isfinite(retry_max_delay)
or retry_base_delay < 0
or retry_max_delay < retry_base_delay
):
raise ValueError(
"retry delays must be finite, non-negative and max >= base"
)
if (
isinstance(retry_jitter_fraction, bool)
or not isinstance(retry_jitter_fraction, (int, float))
or not math.isfinite(retry_jitter_fraction)
or not 0 <= retry_jitter_fraction <= 1
):
raise ValueError("retry_jitter_fraction must be between 0 and 1")
if not isinstance(retryable_exceptions, tuple) or any(
not isinstance(item, type) or not issubclass(item, Exception)
for item in retryable_exceptions
):
raise TypeError("retryable_exceptions must be a tuple of Exception types")
self.job_store = job_store
self.pipeline = pipeline
self.poll_interval = poll_interval
self.max_attempts = max_attempts
self.retry_base_delay = retry_base_delay
self.retry_max_delay = retry_max_delay
self.retry_jitter_fraction = float(retry_jitter_fraction)
self.retryable_exceptions = retryable_exceptions
self.random_uniform = random_uniform or random.uniform
self.source_validator = source_validator
self.pipeline_lock = threading.RLock()
self._stop_event = threading.Event()
self._pause_event = threading.Event()
self._thread: threading.Thread | None = None
self._state_lock = threading.Lock()
self._last_error: str | None = None
self._last_completed_at: str | None = None
@property
def is_running(self) -> bool:
"""Whether the worker thread is currently alive."""
return self._thread is not None and self._thread.is_alive()
[docs]
def health(self) -> dict[str, Any]:
"""Return a small operational snapshot."""
with self._state_lock:
return {
"running": self.is_running,
"paused": self._pause_event.is_set(),
"last_error": self._last_error,
"last_completed_at": self._last_completed_at,
}
[docs]
def start(self) -> None:
"""Recover interrupted jobs and start the worker thread once."""
if self.is_running:
return
self.job_store.recover_interrupted(max_attempts=self.max_attempts)
self._stop_event.clear()
self._thread = threading.Thread(
target=self._run,
name="adp-ingestion-worker",
daemon=True,
)
self._thread.start()
[docs]
def stop(self, *, timeout: float | None = 30.0) -> bool:
"""Request a graceful stop; ``None`` waits for the active job to finish."""
if timeout is not None and (not math.isfinite(timeout) or timeout < 0):
raise ValueError("timeout must be finite and non-negative or None")
self._stop_event.set()
thread = self._thread
if thread is not None:
thread.join(timeout=timeout)
return not self.is_running
[docs]
def pause(self) -> None:
"""Pause new claims while allowing an active job to finish."""
self._pause_event.set()
[docs]
def resume(self) -> None:
"""Resume claiming queued work."""
self._pause_event.clear()
def _retry_delay(self, attempts: int) -> float:
"""Return capped exponential backoff with bounded multiplicative jitter."""
base = min(
self.retry_base_delay * (2 ** max(attempts - 1, 0)),
self.retry_max_delay,
)
if base == 0 or self.retry_jitter_fraction == 0:
return base
fraction = self.retry_jitter_fraction
jittered = base * self.random_uniform(1 - fraction, 1 + fraction)
return min(self.retry_max_delay, max(0.0, jittered))
def _is_retryable(self, error: Exception) -> bool:
"""Avoid retrying invalid inputs and missing/forbidden local files."""
if isinstance(
error, (FileNotFoundError, PermissionError, ValueError, TypeError)
):
return False
return isinstance(error, self.retryable_exceptions)
def _run(self) -> None:
while not self._stop_event.is_set():
if self._pause_event.is_set():
self._stop_event.wait(self.poll_interval)
continue
job = self.job_store.claim_next()
if job is None:
self._stop_event.wait(self.poll_interval)
continue
try:
source = (
self.source_validator(job.source)
if self.source_validator is not None
else job.source
)
with correlation_context(job.id):
logger.info(
"Ingestion job started",
extra={
"event": "job_started",
"job_id": job.id,
"attempt": job.attempts,
"source_name": Path(job.source).name,
},
)
with self.pipeline_lock:
result = self.pipeline.ingest(source)
self.job_store.complete(
job.id,
{
"ingestion_id": result.ingestion_id,
"source": result.source,
"content_sha256": result.content_sha256,
"chunks": len(result.chunks),
"embedded_chunks": result.embedded_chunks,
"stored_chunks": result.stored_chunks,
"classification": (
result.classification.label
if result.classification
else None
),
"entities": len(result.entities),
"redactions": (
result.redaction.redaction_count if result.redaction else 0
),
"stage_durations_ms": dict(result.stage_durations_ms),
},
)
with correlation_context(job.id):
logger.info(
"Ingestion job completed",
extra={
"event": "job_completed",
"job_id": job.id,
"attempt": job.attempts,
"ingestion_id": result.ingestion_id,
"chunk_count": len(result.chunks),
"duration_ms": result.stage_durations_ms.get("total"),
},
)
with self._state_lock:
self._last_error = None
self._last_completed_at = _timestamp(_utc_now())
except Exception as exc:
retryable = self._is_retryable(exc)
delay = self._retry_delay(job.attempts) if retryable else 0.0
attempt_limit = self.max_attempts if retryable else job.attempts
with correlation_context(job.id):
logger.exception(
"Ingestion job failed",
extra={
"event": "job_failed",
"job_id": job.id,
"attempt": job.attempts,
"error_type": type(exc).__name__,
"retry_delay_seconds": delay,
"retryable": retryable,
},
)
try:
updated = self.job_store.fail(
job.id,
error_type=type(exc).__name__,
error_message=str(exc),
max_attempts=attempt_limit,
retry_delay=delay,
)
with self._state_lock:
self._last_error = (
f"{updated.error_type}: {updated.error_message}"
)
except Exception:
logger.exception("Unable to persist failure for job %s", job.id)
with self._state_lock:
self._last_error = f"Unable to persist failure for job {job.id}"