feat(work): recover text and attachment delivery independently

This commit is contained in:
ex_tianzy
2026-11-23 14:49:51 +08:00
parent 1b3fded4ae
commit 3f4b8f983b
7 changed files with 210 additions and 24 deletions
+19 -4
View File
@@ -259,6 +259,8 @@ def create_app(settings=None, redis=None, platform=None):
if s.work_files_enabled:
from .work_files import WorkFiles
broker.files=WorkFiles(s,oauth,store.lifecycle,f)
if deliveries.cards:
deliveries.cards.file_receipts=broker.files.output_receipts
else:
oauth = OAuth(s, r, f)
oauth.store = store
@@ -308,14 +310,27 @@ def create_app(settings=None, redis=None, platform=None):
await asyncio.sleep(5)
try:
await lifecycle.maintain()
await deliveries.recover_interrupted_sends()
if broker.files:await broker.files.flush()
await deliveries.flush()
if approvals:await approvals.maintain()
except Exception:
# No credentials or raw exception text in background logs.
pass
lifecycle_task = asyncio.create_task(maintenance()) if lifecycle else None
async def text_delivery_tick():
await deliveries.recover_interrupted_sends()
await deliveries.flush()
async def delivery_loop(tick):
while True:
await asyncio.sleep(5)
# A slow or failing file upload must not stall text delivery.
with contextlib.suppress(Exception):
await tick()
delivery_tasks = []
if lifecycle:
delivery_tasks.append(asyncio.create_task(delivery_loop(text_delivery_tick)))
if broker.files:
delivery_tasks.append(asyncio.create_task(delivery_loop(broker.files.flush)))
async def card_maintenance():
while True:
await asyncio.sleep(5)
@@ -324,7 +339,7 @@ def create_app(settings=None, redis=None, platform=None):
try:
yield
finally:
work = [reply_task,sweep_task,*background] + ([lifecycle_task] if lifecycle_task else []) + ([cards_task] if cards_task else [])
work = [reply_task,sweep_task,*background,*delivery_tasks] + ([lifecycle_task] if lifecycle_task else []) + ([cards_task] if cards_task else [])
for task in work:
task.cancel()
await asyncio.gather(*work, return_exceptions=True)
+16 -3
View File
@@ -7,10 +7,12 @@ import time
EXECUTION={'queued':'排队中','running':'执行中','waiting_for_approval':'等待本人确认',
'completed':'执行完成','failed':'执行失败','cancelled':'已取消','interrupted':'已中断','unknown':'状态待核对'}
DELIVERY={None:'尚未接收结果','ready':'已接收结果,等待投递','sending':'正在投递结果',
'replied':'结果已发送到当前会话','unknown':'结果投递待核对','discarded':'结果已停止交付'}
'replied':'结果已发送到当前会话','unknown':'结果投递待核对','discarded':'结果已停止交付',
'failed':'结果未能投递'}
def card_content(task_id,execution,delivery,files=None,connection_lost=False,remote_approvals=False):
def card_content(task_id,execution,delivery,files=None,connection_lost=False,remote_approvals=False,
attachment_exception=None):
execution=execution if execution in EXECUTION else 'unknown'
color='green' if execution=='completed' else 'red' if execution in {'failed','interrupted'} else 'orange' if execution in {'waiting_for_approval','unknown'} else 'blue'
if execution=='cancelled':color='grey'
@@ -26,6 +28,8 @@ def card_content(task_id,execution,delivery,files=None,connection_lost=False,rem
elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':hint}})
if execution=='completed' and delivery!='replied':
elements.insert(1,{'tag':'div','text':{'tag':'plain_text','content':'任务已执行完成,结果交付请看下方状态。'}})
if attachment_exception:
elements.insert(-1,{'tag':'div','text':{'tag':'plain_text','content':attachment_exception}})
return {'config':{'wide_screen_mode':True,'enable_forward':False},
'header':{'template':color,'title':{'tag':'plain_text','content':'海诺任务进度'}},'elements':elements}
@@ -34,6 +38,7 @@ class TaskCards:
def __init__(self,state,platform,worker_id,clock=time.time,files_enabled=False,remote_approvals=False):
self.state,self.db,self.platform,self.worker_id,self.clock=state,state.db,platform,worker_id,clock
self.files_enabled=files_enabled
self.file_receipts=None
self.remote_approvals=remote_approvals
with self.db:
self.db.execute('''CREATE TABLE IF NOT EXISTS work_task_connection_v3(
@@ -61,8 +66,16 @@ class TaskCards:
if task['status']=='unknown' and execution not in {'completed','failed','cancelled','interrupted'}:execution='unknown'
if task['deadline']<=self.clock() and execution not in {'completed','failed','cancelled','interrupted'}:execution='unknown'
lost=self.db.execute('SELECT reason FROM work_task_connection_v3 WHERE task_id=?',(task['turn_id'],)).fetchone()
exceptions=[]
if self.file_receipts:
receipts=self.file_receipts(task)
unknown=sum(r['status']=='unknown' for r in receipts)
failed=sum(r['status'] in {'failed','expired','discarded'} for r in receipts)
if unknown:exceptions.append(f'{unknown} 份附件的送达结果待核对。')
if failed:exceptions.append(f'{failed} 份附件未能交付。')
return card_content(task['turn_id'],execution,delivery['status'] if delivery else None,
connection_lost=bool(lost),remote_approvals=self.remote_approvals)
connection_lost=bool(lost),remote_approvals=self.remote_approvals,
attachment_exception=''.join(exceptions))
async def flush(self):
# Bound one maintenance pass; business result delivery remains independent.
+40 -10
View File
@@ -38,6 +38,7 @@ class TaskDelivery:
status TEXT NOT NULL,updated_at DOUBLE PRECISION NOT NULL)""")
self.router=APIRouter()
self.router.add_api_route('/work/v2/tasks/state',self.status,methods=['POST'])
self.router.add_api_route('/work/v2/tasks/delivery',self.delivery_status,methods=['POST'])
self.router.add_api_route('/work/v2/tasks/progress',self.progress,methods=['POST'])
self.router.add_api_route('/work/v2/tasks/result',self.submit,methods=['POST'])
self.cards=None
@@ -47,16 +48,23 @@ class TaskDelivery:
remote_approvals=auth.s.work_remote_approvals_enabled)
broker.task_cards=self.cards
def current(self, body):
def current(self, body, *, read_receipt=False):
self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation)
task=self.state.task(body.task_id)
if (not self.state.task_current(task) or
if (not task or
not task['source_message_id'] or
(task['host_id'],task['owner'],task['binding_generation']) !=
(body.host_id,body.binding_owner,body.binding_generation) or
task['status'] in {'unbound','revoked','result_discarded'}):
raise HTTPException(403,'task_not_recoverable')
known=self.db.execute('SELECT task_id FROM work_result_outbox_v2 WHERE task_id=?',(body.task_id,)).fetchone()
if not self.state.task_current(task):
age=time.time()-task['deadline']
files=getattr(self.broker,'files',None)
if (read_receipt and 0<=age<7*86400
and (known or (files and files.output_receipts(task)))):
return task
raise HTTPException(403,'task_not_recoverable')
if not known and task['status'] not in {'inflight','unknown'}:
raise HTTPException(403,'task_not_recoverable')
return task
@@ -65,12 +73,19 @@ class TaskDelivery:
row=self.db.execute('SELECT status,digest FROM work_result_outbox_v2 WHERE task_id=?',
(task['turn_id'],)).fetchone()
execution=self.db.execute('SELECT execution_state,status_sequence FROM work_execution_state_v3 WHERE task_id=?',(task['turn_id'],)).fetchone()
file_service=getattr(self.broker,'files',None)
delivery={
'protocol':'work-delivery-v1',
'text':{'status':row['status'] if row else 'not_received',
'platform_sent':bool(row and row['status']=='replied')},
'attachments':file_service.output_receipts(task) if file_service else [],
}
return {'task_id':task['turn_id'],'status':row['status'] if row else task['status'],
'progress_protocol':'work-progress-v1',
'execution_state':execution['execution_state'] if execution else 'unknown',
'status_sequence':execution['status_sequence'] if execution else 0,
'result_received':bool(row),'result_digest':row['digest'] if row else None,
'deadline':task['deadline']}
'deadline':task['deadline'],'delivery':delivery}
async def status(self,body:TaskRequest,request:Request):
await self.auth.authenticate(body,request)
@@ -79,6 +94,12 @@ class TaskDelivery:
if pending and pending.host==body.host_id:pending.progress.set()
return no_cache(JSONResponse(self.receipt(task)))
async def delivery_status(self,body:TaskRequest,request:Request):
await self.auth.authenticate(body,request)
task=self.current(body,read_receipt=True)
# Receipt checks never touch the execution watchdog.
return no_cache(JSONResponse({'task_id':body.task_id,'delivery':self.receipt(task)['delivery']}))
async def progress(self,body:StateRequest,request:Request):
await self.auth.authenticate(body,request)
with self.db:
@@ -155,17 +176,26 @@ class TaskDelivery:
try:
result=self.keyring.decrypt(row['key_id'],row['ciphertext'],aad).decode()
if hashlib.sha256(result.encode()).hexdigest()!=row['digest']:raise ValueError()
await self.platform.reply(task['source_message_id'],result)
outcome='replied'
except Exception:pass
except Exception:
outcome='failed'
else:
try:
await self.platform.reply(task['source_message_id'],result)
outcome='replied'
except Exception:pass
with self.db:
self.db.execute("UPDATE work_result_outbox_v2 SET status=?,ciphertext=?,updated_at=? WHERE task_id=? AND status='sending'",(outcome,'' if outcome=='replied' else row['ciphertext'],time.time(),row['task_id']))
self.db.execute("UPDATE work_tasks_v2 SET status=?,updated_at=? WHERE turn_id=? AND status='delivery_ready'",
('replied' if outcome=='replied' else 'reply_unknown',time.time(),row['task_id']))
changed=self.db.execute("UPDATE work_result_outbox_v2 SET status=?,ciphertext=?,updated_at=? WHERE task_id=? AND status='sending' AND worker_id=?",(outcome,row['ciphertext'] if outcome=='unknown' else '',time.time(),row['task_id'],self.broker.worker_id)).rowcount
if changed==1:
self.db.execute("UPDATE work_tasks_v2 SET status=?,updated_at=? WHERE turn_id=? AND status='delivery_ready'",
({'replied':'replied','unknown':'reply_unknown','failed':'reply_failed'}[outcome],time.time(),row['task_id']))
async def recover_interrupted_sends(self):
rows=self.db.execute("SELECT task_id,worker_id,updated_at FROM work_result_outbox_v2 WHERE environment=? AND app_id=? AND status='sending'",(self.state.environment,self.state.app_id)).fetchall()
for row in rows:
if time.time()-row['updated_at']<60 or await self.auth.r.exists('hn:task-worker:'+row['worker_id']):continue
with self.db:
self.db.execute("UPDATE work_result_outbox_v2 SET status='unknown',updated_at=? WHERE task_id=? AND status='sending' AND worker_id=?",(time.time(),row['task_id'],row['worker_id']))
now=time.time()
changed=self.db.execute("UPDATE work_result_outbox_v2 SET status='unknown',updated_at=? WHERE task_id=? AND status='sending' AND worker_id=?",(now,row['task_id'],row['worker_id'])).rowcount
if changed==1:
self.db.execute("UPDATE work_tasks_v2 SET status='reply_unknown',updated_at=? WHERE turn_id=? AND status='delivery_ready'",
(now,row['task_id']))
+29 -7
View File
@@ -55,6 +55,8 @@ class WorkFiles:
key_id TEXT NOT NULL,ciphertext TEXT NOT NULL,status TEXT NOT NULL,
platform_key TEXT NOT NULL,platform_message TEXT NOT NULL,
updated DOUBLE PRECISION NOT NULL,expires DOUBLE PRECISION NOT NULL)''')
self.db.execute('''CREATE INDEX IF NOT EXISTS work_files_task_receipts_idx
ON work_files_v1(environment,app_id,task_id,direction)''')
self.router=APIRouter()
self.router.add_api_route('/work/v2/files/list',self.list_files,methods=['POST'])
self.router.add_api_route('/work/v2/files/download',self.download,methods=['POST'])
@@ -144,6 +146,16 @@ class WorkFiles:
def metadata(self,row):
return {k:row[k]for k in ('file_id','direction','name','size','sha256','status')}
def output_receipts(self,task):
"""Project persisted output states for an already authenticated task."""
rows=self.db.execute("""SELECT file_id,name,size,sha256,status FROM work_files_v1
WHERE environment=? AND app_id=? AND task_id=? AND owner=? AND host_id=?
AND binding_generation=? AND chat_id=? AND source_message_id=? AND direction='output'
ORDER BY file_id""",
(self.environment,self.app_id,task['turn_id'],task['owner'],task['host_id'],
task['binding_generation'],task['chat_id'],task['source_message_id'])).fetchall()
return [{**dict(row),'platform_sent':row['status']=='sent'} for row in rows]
async def list_files(self,body:TaskRequest,request:Request):
await self.auth.authenticate(body,request);self.current(body)
rows=self.db.execute("SELECT * FROM work_files_v1 WHERE environment=? AND app_id=? AND task_id=? AND expires>? ORDER BY file_id",(self.environment,self.app_id,body.task_id,time.time())).fetchall()
@@ -181,7 +193,7 @@ class WorkFiles:
with self.db:
self.state._owner_lock(task['owner']);self.current(body)
old=self.db.execute('SELECT * FROM work_files_v1 WHERE file_id=?',(fid,)).fetchone()
if old and (old['expires']<=time.time()or old['status']in {'expired','discarded'}):raise HTTPException(410,'file_expired')
if old and (old['expires']<=time.time()or old['status']in {'expired','discarded','failed'}):raise HTTPException(410,'file_not_available')
if not old:
count=self.db.execute("SELECT COUNT(*) AS n FROM work_files_v1 WHERE task_id=? AND direction='output'",(body.task_id,)).fetchone()['n']
if count>=self.s.work_file_batch_limit:raise HTTPException(413,'artifact_count_limit')
@@ -198,7 +210,10 @@ class WorkFiles:
async def flush(self):
now=time.time()
with self.db:
self.db.execute("UPDATE work_files_v1 SET status='expired',ciphertext='',platform_key='' WHERE environment=? AND app_id=? AND expires<? AND ciphertext!=''",(self.environment,self.app_id,now))
self.db.execute("""UPDATE work_files_v1 SET status=CASE WHEN status IN ('uploading','sending','unknown')
THEN 'unknown' ELSE 'expired' END,ciphertext='',platform_key='',updated=?
WHERE environment=? AND app_id=? AND expires<=? AND ciphertext!=''""",
(now,self.environment,self.app_id,now))
self.db.execute("UPDATE work_files_v1 SET status='failed',size=0,ciphertext='',updated=? WHERE environment=? AND app_id=? AND status='receiving' AND updated<?",(now,self.environment,self.app_id,now-120))
# Interrupted mutating platform calls remain ambiguous, never replayed.
self.db.execute("UPDATE work_files_v1 SET status='unknown',updated=? WHERE environment=? AND app_id=? AND status IN ('uploading','sending') AND updated<?",(now,self.environment,self.app_id,now-120))
@@ -206,7 +221,7 @@ class WorkFiles:
for raw_row in rows:
row=dict(raw_row);task=self.state.task(row['task_id'])
if not self.state.task_current(task):
with self.db:self.db.execute("UPDATE work_files_v1 SET status='discarded',ciphertext='',platform_key='' WHERE file_id=?",(row['file_id'],))
with self.db:self.db.execute("UPDATE work_files_v1 SET status='discarded',ciphertext='',platform_key='' WHERE file_id=? AND status=?",(row['file_id'],row['status']))
continue
try:token=await self.platform.tenant_token()
except Exception:continue
@@ -214,13 +229,20 @@ class WorkFiles:
self.state._owner_lock(row['owner'])
if not self.state.task_current(self.state.task(row['task_id'])):continue
working='uploading'if row['status']=='ready'else'sending'
changed=self.db.execute('UPDATE work_files_v1 SET status=?,updated=? WHERE file_id=? AND status=?',(working,time.time(),row['file_id'],row['status'])).rowcount
claimed_at=time.time()
changed=self.db.execute('UPDATE work_files_v1 SET status=?,updated=? WHERE file_id=? AND status=? AND expires>?',(working,claimed_at,row['file_id'],row['status'],claimed_at)).rowcount
if changed!=1:continue
if working=='uploading':
try:
content=self.keyring.decrypt(row['key_id'],row['ciphertext'],self._aad(row))
if len(content)!=row['size'] or hashlib.sha256(content).hexdigest()!=row['sha256']:raise ValueError()
mime=FORMATS[PurePosixPath(row['name']).suffix.lower()]
except Exception:
with self.db:self.db.execute("UPDATE work_files_v1 SET status='failed',ciphertext='',updated=? WHERE file_id=? AND status='uploading'",(time.time(),row['file_id']))
continue
try:
if working=='uploading':
content=self.keyring.decrypt(row['key_id'],row['ciphertext'],self._aad(row))
if hashlib.sha256(content).hexdigest()!=row['sha256']:raise ValueError()
key=await self.platform.upload_file(row['name'],content,FORMATS[PurePosixPath(row['name']).suffix.lower()],token=token)
key=await self.platform.upload_file(row['name'],content,mime,token=token)
with self.db:self.db.execute("UPDATE work_files_v1 SET status='uploaded',platform_key=?,updated=? WHERE file_id=? AND status='uploading'",(key,time.time(),row['file_id']))
else:
response=await self.platform.reply_file(task['source_message_id'],row['platform_key'],hashlib.sha256(row['file_id'].encode()).hexdigest()[:32],token=token)