"""Durable bid steps. HTTP enqueues/polls; bounded workers use the model. The PMS database owns the workflow. This private SQLite queue stores immutable step inputs, leases and cached outputs so browser closure/restarts lose no work. """ import json import logging import math import threading import time from app.modules.work_assistant.bid_writing import BidStep, bid_step, RULE_VERSION from app.modules.work_assistant.model_gateway import ModelUnavailable, routing_revision from app.modules.work_assistant.model_dispatch import DispatchUnavailable, model_turn, parallel_model_turn from app.modules.work_assistant.review_jobs import review_jobs, JobPaused, service_ready_at, job_ready_at from app.modules.work_assistant.bid_progress import BidProgress, current_progress from app.modules.work_assistant.bid_timing import LEASE_SECONDS, RECOVERY_SECONDS from app.modules.work_assistant.bid_ownership import execution_lock logger = logging.getLogger(__name__) class BidQueue: def __init__(self, jobs=review_jobs, action=bid_step, turn=model_turn, rule=None, worker_count=None): self.jobs, self.action, self.turn = jobs, action, turn self.rule = rule or (lambda: RULE_VERSION + ':' + routing_revision()) self.stop = threading.Event() self.wake = threading.Event() self.lock = threading.Lock() self.worker = None self.reconcile_worker = None if worker_count is None: from app.core.config import get_settings worker_count = get_settings().work_assistant_bid_workers self.worker_count = max(1, min(16, worker_count)) self.workers = [] def connect(self): db = self.jobs.connect() db.execute('BEGIN IMMEDIATE') db.execute('CREATE TABLE IF NOT EXISTS bid_queue (' 'job_key TEXT PRIMARY KEY, payload TEXT NOT NULL, rule TEXT NOT NULL, created_at REAL NOT NULL)') if 'task_id' not in {row['name'] for row in db.execute('PRAGMA table_info(bid_queue)')}: db.execute('ALTER TABLE bid_queue ADD COLUMN task_id TEXT') for row in db.execute('SELECT job_key,payload FROM bid_queue').fetchall(): db.execute('UPDATE bid_queue SET task_id=? WHERE job_key=?', (self.scope(json.loads(row['payload'])), row['job_key'])) db.execute('CREATE INDEX IF NOT EXISTS bid_queue_task ON bid_queue(task_id)') db.execute('CREATE TABLE IF NOT EXISTS bid_control (' 'task_id TEXT PRIMARY KEY, revision INTEGER NOT NULL, paused INTEGER NOT NULL)') db.execute('CREATE TABLE IF NOT EXISTS bid_execution_owner (' 'job_key TEXT PRIMARY KEY, lease TEXT NOT NULL, probe_until REAL NOT NULL)') db.commit() return db def _recover_abandoned(self, db, task_id=None): """Reclaim only leases registered while holding the OS execution lock. A live worker keeps that lock across model calls and database finalization. Unknown legacy owners retain their original deadline; stale timestamps or slow output alone never justify stealing an executing request. """ now = time.time() rows = db.execute('SELECT j.job_key,j.lease,o.probe_until FROM review_job j ' 'JOIN bid_queue q USING(job_key) JOIN bid_execution_owner o ' 'ON o.job_key=j.job_key AND o.lease=j.lease ' 'WHERE j.status=\'running\' AND j.lease_until>?' + (' AND q.task_id=?' if task_id else ''), (now, task_id) if task_id else (now,)).fetchall() for row in rows: with execution_lock(self.jobs.path, row['job_key']) as acquired: if not acquired: continue changed = db.execute("UPDATE review_job SET status='queued',lease=NULL,lease_until=0," "retry_at=0,reason='review_continuation',attempts=MAX(0,attempts-1),updated_at=? " "WHERE job_key=? AND lease=? AND status='running'", (now, row['job_key'], row['lease'])).rowcount if changed and row['probe_until']: db.execute('UPDATE review_service SET probe_until=0 WHERE id=1 AND probe_until=?', (row['probe_until'],)) if changed: logger.info('bid_abandoned_execution_recovered') @staticmethod def _register_owner(db, key, lease, probe_until): db.execute('INSERT INTO bid_execution_owner VALUES(?,?,?) ON CONFLICT(job_key) ' 'DO UPDATE SET lease=excluded.lease,probe_until=excluded.probe_until', (key, lease, probe_until)) @staticmethod def scope(payload): # Existing step IDs are task UUID:nonce:stage:cursor. Keep payloads and # their cache keys unchanged, including jobs created before this feature. return payload['request_id'].split(':', 1)[0] def control(self, task_id, revision, paused): db = self.connect() try: db.execute('BEGIN IMMEDIATE') self._recover_abandoned(db, task_id) db.execute('INSERT INTO bid_control VALUES(?,?,?) ON CONFLICT(task_id) DO UPDATE SET ' 'revision=excluded.revision,paused=excluded.paused WHERE excluded.revision>bid_control.revision', (task_id, revision, int(paused))) control = db.execute('SELECT * FROM bid_control WHERE task_id=?', (task_id,)).fetchone() active = db.execute('SELECT 1 FROM bid_queue q JOIN review_job j USING(job_key) ' 'WHERE q.task_id=? AND j.lease_until>? LIMIT 1', (task_id, time.time())).fetchone() state = ('pausing' if active else 'paused') if control['paused'] else 'queued' # Include only this task's newest checkpoint, so pausing preserves # the latest preview even when the PMS poll had not seen it yet. row = db.execute('SELECT j.checkpoint,q.payload FROM bid_queue q JOIN review_job j USING(job_key) ' 'WHERE q.task_id=? AND j.checkpoint IS NOT NULL ORDER BY j.updated_at DESC LIMIT 1', (task_id,)).fetchone() answer = dict(rule_version=RULE_VERSION, job_status=state, revision=control['revision']) if row: preview = json.loads(row['checkpoint']).get('preview') if preview: answer.update(preview=preview, request_id=json.loads(row['payload'])['request_id']) db.commit() finally: db.close() self.wake.set() return answer def submit(self, request, *, start=True): payload, rule = request.model_dump(), self.rule() key, now = self.jobs.key(payload, rule), time.time() db = self.connect() try: db.execute('BEGIN IMMEDIATE') task_id = self.scope(payload) self._recover_abandoned(db, task_id) db.execute('INSERT OR IGNORE INTO bid_queue(job_key,payload,rule,created_at,task_id) VALUES(?,?,?,?,?)', (key, json.dumps(payload, ensure_ascii=False), rule, now, task_id)) db.execute("INSERT OR IGNORE INTO review_job(job_key,status,updated_at) VALUES(?,'queued',?)", (key, now)) row = db.execute('SELECT j.*, q.created_at AS queued_at FROM review_job j JOIN bid_queue q USING(job_key) WHERE j.job_key=?', (key,)).fetchone() control = db.execute('SELECT paused FROM bid_control WHERE task_id=?', (task_id,)).fetchone() # One-time migration of pre-existing section-recovery failures. # Keep the immutable request key and saved units; never reopen a # paused task, a live lease, or unrelated validation failures. if (request.workbench.get('version') == 2 and request.workbench.get('phase') == 'writing' and row['status'] == 'suspended' and row['reason'] == 'validation_blocked' and not (control and control['paused']) and (row['lease_until'] or 0) <= now): checkpoint = json.loads(row['checkpoint']) if row['checkpoint'] else {} recovery = checkpoint.get('studio_writing_recovery', {}) exhausted = (any(count >= 2 for count in recovery.get('failures', {}).values()) or recovery.get('expansion_round', 0) >= 3) if exhausted and not checkpoint.get('studio_partial_recovery_v1'): checkpoint['studio_partial_recovery_v1'] = True db.execute("UPDATE review_job SET status='queued',reason='review_continuation',retry_at=0," "checkpoint=?,updated_at=? WHERE job_key=?", (json.dumps(checkpoint, ensure_ascii=False), now, key)) row = db.execute('SELECT j.*,q.created_at AS queued_at FROM review_job j ' 'JOIN bid_queue q USING(job_key) WHERE j.job_key=?', (key,)).fetchone() service = db.execute('SELECT * FROM review_service WHERE id=1').fetchone() db.commit() finally: db.close() if start: self.start() self.wake.set() paused = control is not None and control['paused'] if row['status'] == 'ready' and not paused: return json.loads(row['result']) if row['status'] == 'suspended' and not paused: if request.workbench.get('version') in {1, 2}: checkpoint = json.loads(row['checkpoint']) if row['checkpoint'] else {} answer = {'rule_version': RULE_VERSION, 'job_status': 'blocked', 'message': checkpoint.get('workbench_failure', '本步骤尚未通过内容校验,请核对要求后重试。')[:1500]} if checkpoint.get('preview'): answer['preview'] = checkpoint['preview'] return answer raise ModelUnavailable('review_suspended') retry_at = max(job_ready_at(row, service, True), service_ready_at(service, True)) reason = row['reason'] or '' dispatch_reason, dispatch_delay = '', 0 if self.turn is model_turn: from .model_dispatch import dispatch dispatch_reason, dispatch_delay = dispatch.waiting_state() retry_at = max(retry_at, now + dispatch_delay if dispatch_delay else 0) if service_ready_at(service, True) > now or dispatch_delay: reason = 'circuit_open' if paused: state = 'pausing' if row['lease_until'] and row['lease_until'] > now else 'paused' elif row['lease_until'] and row['lease_until'] > now: state = 'running' reason = '' elif retry_at > now and (reason != 'review_continuation' or retry_at > row['retry_at']): state = 'retrying' else: state = 'queued' reason = 'model_recovery_probe' if service['probe_until'] > now else dispatch_reason or ( 'review_continuation' if reason == 'review_continuation' else '') checkpoint = json.loads(row['checkpoint']) if row['checkpoint'] else {} answer = {'rule_version': RULE_VERSION, 'job_status': state, 'reason': reason, 'last_failure_reason': row['reason'] or '', 'queued_at': int(row['queued_at']*1000), 'retry_after': max(2, min(900, math.ceil(retry_at - now))) if state == 'retrying' else 2} if state == 'running' and checkpoint.get('execution'): answer['execution'] = {k:checkpoint['execution'].get(k, 0) for k in ['started_at', 'last_output_at', 'received_chars']} if checkpoint.get('preview'): answer['preview'] = checkpoint['preview'] return answer def run_once(self, *, reconcile_only=False): db = self.connect() try: db.execute('BEGIN IMMEDIATE') self._recover_abandoned(db) db.commit() now = time.time() service = db.execute('SELECT * FROM review_service WHERE id=1').fetchone() if max(service_ready_at(service, True), service['probe_until']) > now: return False row = db.execute("SELECT q.*,COALESCE(c.revision,0) AS control_revision FROM bid_queue q JOIN review_job j ON j.job_key=q.job_key " "LEFT JOIN bid_control c ON c.task_id=q.task_id " "WHERE q.rule=? AND j.status NOT IN ('ready','suspended') " "AND (?=0 OR json_extract(q.payload,'$.action') IN ('reconcile','analyze','outline') OR json_extract(q.payload,'$.workbench.version') IN (1,2)) " "AND COALESCE(c.paused,0)=0 " "AND COALESCE(j.lease_until,0)<=? " "AND (MIN(j.retry_at,COALESCE(j.updated_at,0)+?)<=? OR j.updated_at 0}, name=f'bid-model-queue-{index + 1}', daemon=True) if index < len(self.workers): self.workers[index] = worker else: self.workers.append(worker) worker.start() self.worker = self.workers[0] self.reconcile_worker = self.workers[1] if len(self.workers) > 1 else None def _loop(self, *, reconcile_only=False): while not self.stop.is_set(): try: if self.run_once(reconcile_only=reconcile_only): continue except Exception as exc: logger.warning('bid_queue_waiting type=%s', type(exc).__name__) self.wake.wait(1) self.wake.clear() def close(self): self.stop.set() self.wake.set() for worker in self.workers: if worker: worker.join(timeout=2) bid_queue = BidQueue()