"""Durable checkpoints for project reviews; business records remain in PMS.""" import hashlib import json import sqlite3 import time import uuid from pathlib import Path from app.modules.work_assistant.model_gateway import ModelUnavailable, model_successes from app.modules.work_assistant.bid_timing import RECOVERY_SECONDS def service_ready_at(service, continuous=False): until = service['open_until'] or 0 if continuous and until: previous_delay = min(900, 60 * 2 ** min(4, max(0, service['failures'] - 3))) # Reinterpret existing persisted outages too, without erasing them. # run() still atomically grants only one recovery probe across workers. until = min(until, until - previous_delay + RECOVERY_SECONDS) return until def job_ready_at(row, service, continuous=False): if row['reason'] == 'annual_panel_retry': return row['retry_at'] or 0 if service['recovered_at'] > (row['updated_at'] or 0): return 0 until = row['retry_at'] or 0 if continuous and until: until = min(until, (row['updated_at'] or 0) + RECOVERY_SECONDS) return until class JobPaused(ModelUnavailable): def __init__(self): super().__init__('bid_paused') class JobDeferred(ModelUnavailable): """A saved substep needs a fresh time slice, not outage backoff.""" def __init__(self): super().__init__('review_continuation', retry_after=2) class JobValidationBlocked(ValueError): """An irreducible content failure needs attention, not unlimited retries.""" class ReviewJobs: def __init__(self, path=None): self.path = Path(path) if path else Path(__file__).resolve().parents[3] / '.private' / 'review-jobs.sqlite3' def connect(self): self.path.parent.mkdir(parents=True, exist_ok=True) db = sqlite3.connect(self.path, timeout=5) db.row_factory = sqlite3.Row db.execute('CREATE TABLE IF NOT EXISTS review_job (job_key TEXT PRIMARY KEY, ' 'status TEXT NOT NULL, lease TEXT, lease_until REAL, attempts INTEGER NOT NULL DEFAULT 0, ' 'retry_at REAL NOT NULL DEFAULT 0, reason TEXT, checkpoint TEXT, result TEXT, updated_at REAL)') db.execute('CREATE TABLE IF NOT EXISTS review_service (id INTEGER PRIMARY KEY, failures INTEGER, ' 'open_until REAL, probe_until REAL, recovered_at REAL)') db.execute('INSERT OR IGNORE INTO review_service VALUES(1,0,0,0,0)') db.commit() return db @staticmethod def key(payload, rule): return hashlib.sha256((rule + '\n' + json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))).encode()).hexdigest() def run(self, payload, rule, action, *, lease_seconds=90, continuous=False, rapid_recovery=False, guard=None, register_owner=None, progress_recovery=False, resume_context_failures=False, resume_incomplete=None, resume_ready=None): if not 30 <= lease_seconds <= 600: raise ValueError("Invalid review lease") # Scope changes (including date) invalidate completed results and checkpoints. key = self.key(payload, rule) now = time.time() lease = uuid.uuid4().hex db = self.connect() try: db.execute('BEGIN IMMEDIATE') if guard: guard(db) row = db.execute('SELECT * FROM review_job WHERE job_key=?', (key,)).fetchone() service = db.execute('SELECT * FROM review_service WHERE id=1').fetchone() probe = service['failures'] >= 3 ready_checkpoint = None if row: if row['status'] == 'ready' or (resume_ready and row['reason']=='internal' and row['result'] and not row['checkpoint']): result = json.loads(row['result']) ready_checkpoint = resume_ready(result) if resume_ready else None if ready_checkpoint is None and row['status']=='ready':return result context_resume = resume_context_failures and row['status'] == 'suspended' and row['reason'] in {'model_context_full','context_capacity'} profile_resume = (progress_recovery and resume_context_failures and row['status'] == 'suspended' and row['reason'] in {'validation', 'attempt_limit', 'profile_context_limit', 'direct_output_truncated', 'gateway_output_truncated'}) internal_resume = progress_recovery and resume_context_failures and row['status']=='suspended' and row['reason']=='internal' reopen = context_resume or profile_resume or internal_resume if row['status'] == 'suspended' and not reopen and not (continuous and row['reason'] in {'validation', 'attempt_limit'}): raise ModelUnavailable('review_suspended') if row['lease_until'] and row['lease_until'] > now: raise ModelUnavailable('review_in_progress', retry_after=row['lease_until'] - now) recovered = service['recovered_at'] > row['updated_at'] ready_at = job_ready_at(row, service, continuous or rapid_recovery) if ready_at > now and (not reopen or internal_resume): raise ModelUnavailable('review_backoff', retry_after=ready_at - now) checkpoint = ready_checkpoint if ready_checkpoint is not None else json.loads(row['checkpoint']) if row['checkpoint'] else None attempts = 1 if reopen or recovered or probe else row['attempts'] + 1 if progress_recovery: # A worker can be restarted after saving but before it # releases its lease. Recover that same attempt safely. attempts = min(attempts, 3) else: checkpoint, attempts = None, 1 ready_at = max(service_ready_at(service, continuous or rapid_recovery), service['probe_until']) if ready_at > now: raise ModelUnavailable('circuit_open', retry_after=ready_at - now) if attempts > 3 and not probe and not continuous: db.execute("UPDATE review_job SET status='suspended', reason='attempt_limit' WHERE job_key=?", (key,)) db.commit() raise ModelUnavailable('review_suspended') if probe: db.execute('UPDATE review_service SET probe_until=? WHERE id=1', (now + lease_seconds,)) db.execute("INSERT INTO review_job(job_key,status,lease,lease_until,attempts,updated_at) " "VALUES(?,'running',?,?,?,?) ON CONFLICT(job_key) DO UPDATE SET " "status='running',lease=excluded.lease,lease_until=excluded.lease_until," "attempts=excluded.attempts,updated_at=excluded.updated_at", (key, lease, now + lease_seconds, attempts, now)) if ready_checkpoint is not None: db.execute('UPDATE review_job SET checkpoint=? WHERE job_key=?',(json.dumps(ready_checkpoint,ensure_ascii=False),key)) if register_owner: register_owner(db, key, lease, now + lease_seconds if probe else 0) db.commit() finally: db.close() def save(candidate): nonlocal attempts,checkpoint if progress_recovery: from .personnel_workflow import progress if progress(candidate)['token']!=progress(checkpoint or {})['token']: attempts=1 checkpoint=candidate self.update(key, lease, guard=guard, checkpoint=json.dumps(candidate, ensure_ascii=False)) successes_before = model_successes.get() try: result = action(checkpoint, save) if resume_incomplete is not None: pending = resume_incomplete(result) update = dict(status='queued', lease_until=0, attempts=0, retry_at=0, reason='review_continuation' if pending else None) if not pending: update['checkpoint'] = None self.update(key, lease, guard=guard, **update) self.service_result(False, release_only=bool(pending) and model_successes.get()==successes_before, probe=probe) return result incomplete = result.get('requires_manual', False) self.update(key, lease, guard=guard, status=('suspended' if attempts >= 3 else 'failed') if incomplete else 'ready', result=json.dumps(result, ensure_ascii=False), retry_at=time.time() + 30 if incomplete else 0, lease_until=0, checkpoint=None, reason='incomplete' if incomplete else None) except JobDeferred: self.update(key, lease, status='queued', lease_until=0, retry_at=time.time() + 2, reason='review_continuation', attempts=max(0, attempts - 1)) # A successful model substep proves the outage is over. Waiting # for an entire multi-step report otherwise serializes the queue # behind the recovery probe for minutes or hours. self.service_result(False, release_only=model_successes.get()==successes_before, probe=probe) raise except JobPaused: # Keep the last durable checkpoint. Hold the lease until execution # actually exits, so resume cannot overlap an old model request. self.update(key, lease, status='queued', lease_until=0, retry_at=0, reason=None, attempts=max(0, attempts - 1)) self.service_result(False, release_only=True, probe=probe) raise except JobValidationBlocked: self.update(key, lease, status='suspended', reason='validation_blocked', lease_until=0, retry_at=0) self.service_result(False, release_only=True, probe=probe) raise except (ValueError, TypeError): # The pipeline has already used its one correction opportunity. # Bid tasks remain durable and retry with bounded backoff. Each # individual attempt is still time-limited and strictly validated. self.update(key, lease, status='failed' if continuous else 'suspended', reason='validation', lease_until=0, retry_at=time.time() + min(60, 10 * 2 ** min(3, max(0, attempts - 1))) if continuous else 0) self.service_result(False, probe=probe) raise except ModelUnavailable as exc: admission = exc.reason in {'circuit_open', 'queue_full', 'queue_timeout','token_count_unavailable'} content_retry = exc.reason in {'annual_panel_retry','leadership_retry','annual_output_retry','role_fit_retry'} transient = continuous or exc.retryable or admission delay = min(900, 60 * 2 ** min(4, max(0, attempts - 1))) if continuous or rapid_recovery: delay = min(delay, RECOVERY_SECONDS) if content_retry: delay = max(delay, min(900, exc.retry_after or 300)) if progress_recovery and rapid_recovery: # Personnel content corrections are local resumable work, # not a model-service outage. Do not inherit a five-minute # cooldown from an old failed validation round. delay = min(delay, 30) if exc.reason in {'queue_full', 'queue_timeout'}: delay = min(delay, 5) if continuous and exc.reason in {'direct_output_truncated', 'gateway_output_truncated'}: delay = min(60, 10 * 2 ** min(3, max(0, attempts - 1))) # A durable personnel step should survive an outage even when # other requests succeed between its model attempts. retry_attempts = min(attempts, 2) if progress_recovery and exc.retryable else attempts - int(admission) self.update(key, lease, status='failed' if transient else 'suspended', reason=exc.reason, lease_until=0, attempts=retry_attempts, retry_at=time.time() + delay) exc.retry_after = delay self.service_result(not admission and not content_retry and exc.retryable, release_only=admission or (content_retry and model_successes.get()==successes_before) or (continuous and not exc.retryable), probe=probe) raise except Exception: self.update(key, lease, status='failed' if progress_recovery else 'suspended', reason='internal', lease_until=0, retry_at=time.time()+300 if progress_recovery else 0, attempts=min(attempts,2) if progress_recovery else attempts) self.service_result(False, release_only=True, probe=probe) raise self.service_result(False, probe=probe) return result def service_result(self, failed, release_only=False, probe=False): db = self.connect() try: db.execute('BEGIN IMMEDIATE') row = db.execute('SELECT * FROM review_service WHERE id=1').fetchone() if release_only: if probe: db.execute('UPDATE review_service SET probe_until=0 WHERE id=1') elif failed: count = row['failures'] + 1 db.execute('UPDATE review_service SET failures=?, open_until=?, probe_until=? WHERE id=1', (count, time.time() + min(900, 60 * 2 ** min(4, count - 3)) if count >= 3 else 0, 0 if probe else row['probe_until'])) elif row['failures'] and (probe or row['failures'] < 3): # An overlapping successful request may have started before a # neighbor failed. It resets the failure streak, but must not # waive that neighbor's persisted backoff or attempt count. # Only the exclusive recovery probe advances the recovery epoch. db.execute('UPDATE review_service SET failures=0,open_until=0,probe_until=0,' 'recovered_at=CASE WHEN ? THEN ? ELSE recovered_at END WHERE id=1', (int(probe), time.time())) db.commit() finally: db.close() def update(self, key, lease, *, guard=None, **fields): fields['updated_at'] = time.time() db = self.connect() try: db.execute('BEGIN IMMEDIATE') if guard: guard(db) db.execute('UPDATE review_job SET ' + ','.join(name + '=?' for name in fields) + ' WHERE job_key=? AND lease=?', (*fields.values(), key, lease)) db.commit() finally: db.close() review_jobs = ReviewJobs()