Files
company-ai-platform/app/modules/work_assistant/bid_queue.py
T
2026-11-14 22:48:33 +08:00

280 lines
15 KiB
Python

"""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):
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
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()
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') == 1:
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')=1) "
"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<?) "
"ORDER BY q.created_at,q.rowid LIMIT 1", (self.rule(), int(reconcile_only), now, RECOVERY_SECONDS, now, service['recovered_at'])).fetchone()
finally:
db.close()
if row is None:
return False
def guard(db=None):
owned = db is None
db = self.jobs.connect() if owned else db
try:
control = db.execute('SELECT * FROM bid_control WHERE task_id=?', (row['task_id'],)).fetchone()
if control and (control['paused'] or control['revision'] != row['control_revision']):
raise JobPaused()
finally:
if owned:
db.close()
# Waiting for capacity precedes the execution lease and model deadline.
# Queue admission expiry never marks a job failed or spends an attempt.
try:
with execution_lock(self.jobs.path, row['job_key']) as acquired:
if not acquired:
return False
# Independent comparisons share the same two-call admission as
# extraction. Drafting and other actions keep their reservation.
payload = json.loads(row['payload'])
turn = parallel_model_turn if self.turn is model_turn and (payload['action'] in {'extract', 'reconcile', 'analyze', 'outline'} or payload.get('workbench')) else self.turn
with turn():
payload = json.loads(row['payload'])
def execute(checkpoint, save):
# The lease is now visible; wake the other worker so it
# can claim a different comparison without racing this one.
self.wake.set()
request = BidStep.model_validate(payload)
progress = BidProgress(request, checkpoint, save, check=guard)
progress.state.pop('execution', None)
token = current_progress.set(progress)
try:
return self.action(request)
finally:
current_progress.reset(token)
self.jobs.run(payload, row['rule'], execute, lease_seconds=LEASE_SECONDS, continuous=True,
guard=guard, register_owner=self._register_owner)
except DispatchUnavailable:
return False
except (ModelUnavailable, ValueError, TypeError):
# ReviewJobs persists the reason, delay, and original payload.
return False
return True
def start(self):
with self.lock:
self.stop.clear()
if not self.worker or not self.worker.is_alive():
self.worker = threading.Thread(target=self._loop, name='bid-model-queue', daemon=True)
self.worker.start()
# The second worker also accepts independent workspace jobs. PMS
# enforces ordering between continuation segments of one chapter.
if not self.reconcile_worker or not self.reconcile_worker.is_alive():
self.reconcile_worker = threading.Thread(target=self._loop, kwargs={'reconcile_only': True},
name='bid-reconcile-queue', daemon=True)
self.reconcile_worker.start()
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.worker, self.reconcile_worker):
if worker:
worker.join(timeout=2)
bid_queue = BidQueue()