224 lines
11 KiB
Python
224 lines
11 KiB
Python
"""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
|
|
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 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):
|
|
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
|
|
if row:
|
|
if row['status'] == 'ready':
|
|
return json.loads(row['result'])
|
|
if row['status'] == 'suspended' 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:
|
|
raise ModelUnavailable('review_backoff', retry_after=ready_at - now)
|
|
checkpoint = json.loads(row['checkpoint']) if row['checkpoint'] else None
|
|
attempts = 1 if recovered or probe else row['attempts'] + 1
|
|
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 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))
|
|
|
|
try:
|
|
result = action(checkpoint, save)
|
|
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))
|
|
self.service_result(False, release_only=True, 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'}
|
|
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 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)))
|
|
self.update(key, lease, status='failed' if transient else 'suspended',
|
|
reason=exc.reason, lease_until=0, attempts=attempts - int(admission),
|
|
retry_at=time.time() + delay)
|
|
exc.retry_after = delay
|
|
self.service_result(not admission and exc.retryable, release_only=admission or (continuous and not exc.retryable), probe=probe)
|
|
raise
|
|
except Exception:
|
|
self.update(key, lease, status='suspended', reason='internal', lease_until=0)
|
|
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()
|