diff --git a/deployable/WORK_DISPATCH.md b/deployable/WORK_DISPATCH.md new file mode 100644 index 0000000..62c8e16 --- /dev/null +++ b/deployable/WORK_DISPATCH.md @@ -0,0 +1,10 @@ +# Work task dispatch and acceptance + +The broker advertises `work-dispatch-v1` through signed Work status and uses it only for a paired capable client's private-chat assistant tasks. Older clients and direct read-only commands retain their existing path. + +1. The connector atomically persists the original task identity, encrypted instruction and material assignments before it marks the event task as queued. Pending tasks are bounded per device (up to 20), subject to the original task deadline and binding generation. +2. A signed `POST /work/v2/tasks/next` returns the oldest eligible task for that same binding. Reading repeatedly does not mark it as accepted. The queued record does not depend on a WebSocket packet or the original connector process. +3. The client validates the task and digest and commits its encrypted local task record before signed `POST /work/v2/tasks/accept`. Identical acceptance retries return the original receipt. After acceptance the queue does not hand the task out again; the connector purges the queued body. +4. Execution starts only after confirmation. A client recovering a known native run polls the original run. If starting the run had an ambiguous outcome and no run ID was stored, the client does not start it again. Revoked, unbound and expired queued records cannot be accepted. + +The guarantee starts at **queue commit**. Platform acknowledgment before queue commit is a separate ingress task. This slice does not queue requests submitted while the device is offline, add cancellation, or promise automatic recovery from lost client storage after acceptance. diff --git a/deployable/relay/binding_state.py b/deployable/relay/binding_state.py index 2500cf0..1ebf8e8 100644 --- a/deployable/relay/binding_state.py +++ b/deployable/relay/binding_state.py @@ -88,7 +88,7 @@ class BindingState: (self.environment, self.app_id, device["host_id"], generation)) self.db.execute("""UPDATE work_tasks_v2 SET status=?,updated_at=? WHERE environment=? AND app_id=? AND host_id=? AND binding_generation<=? - AND status IN ('inflight','completed','replying','delivery_ready')""", + AND status IN ('queued','inflight','completed','replying','delivery_ready')""", ("revoked" if reason == "revoke" else "unbound", time.time(), self.environment, self.app_id, device["host_id"], generation)) event = uuid.uuid4().hex @@ -142,17 +142,20 @@ class BindingState: and task["deadline"] > time.time()) def create_task(self, turn, owner, host, generation, session, worker, deadline, chat_id="", message_id=""): - conversation = hashlib.sha256((self.environment+"\0"+self.app_id+"\0"+owner+"\0"+chat_id+"\0work-dm").encode()).hexdigest() with self.db: self._owner_lock(owner) - device = self.store.device(host) - if not device or device["revoked"] or device["owner"] != owner or device["binding_generation"] != generation: - raise ValueError("binding changed") - count = self.db.execute("""INSERT INTO work_tasks_v2 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) - ON CONFLICT DO NOTHING""", (turn,self.environment,self.app_id,owner,host,generation,session, - worker,conversation,chat_id,message_id,"inflight",deadline,time.time(),time.time())).rowcount - if count != 1: - raise ValueError("task already recorded") + return self.create_task_locked(turn,owner,host,generation,session,worker,deadline,chat_id,message_id) + + def create_task_locked(self,turn,owner,host,generation,session,worker,deadline,chat_id,message_id,status='inflight'): + conversation = hashlib.sha256((self.environment+"\0"+self.app_id+"\0"+owner+"\0"+chat_id+"\0work-dm").encode()).hexdigest() + device = self.store.device(host) + if not device or device["revoked"] or device["owner"] != owner or device["binding_generation"] != generation: + raise ValueError("binding changed") + count = self.db.execute("""INSERT INTO work_tasks_v2 VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) + ON CONFLICT DO NOTHING""", (turn,self.environment,self.app_id,owner,host,generation,session, + worker,conversation,chat_id,message_id,status,deadline,time.time(),time.time())).rowcount + if count != 1: + raise ValueError("task already recorded") return self.task(turn) def transition(self, turn, previous, status): diff --git a/deployable/relay/connector.py b/deployable/relay/connector.py index 9028422..9b97e17 100644 --- a/deployable/relay/connector.py +++ b/deployable/relay/connector.py @@ -71,6 +71,7 @@ class Broker: self.lifecycle = None self.files = None self.task_cards = None + self.dispatch_queue = None async def replies(self, pub): async for message in pub.listen(): @@ -156,6 +157,20 @@ class Broker: return {'status':'materials_receiving','turn_id':turn,'result':'材料仍在接收,尚未执行任务。请等附件接收回执后再发送任务要求。'} if self.files and self.files.pending_count(owner,host,device['binding_generation'],chat_id) and not file_capable: return {'status':'unavailable','turn_id':turn,'result':'材料已保留,但当前客户端尚未支持附件处理;请升级配套客户端后再发任务要求。'} + if (self.dispatch_queue and proof.get('durable_dispatch')=='work-dispatch-v1' + and text.startswith('/助手 ') and chat_id and source_message_id): + if len(text)>8010: + return {'status':'not_dispatched','turn_id':turn,'result':'任务文字超过长度限制,本条未入队。'} + try: + status=self.dispatch_queue.enqueue(owner,device,text,turn,chat_id=chat_id, + source_message_id=source_message_id,file_transfer=file_capable) + except ValueError: + return {'status':'not_dispatched','turn_id':turn, + 'result':'材料或绑定状态发生变化,任务未入队。'} + except HTTPException as error: + if error.detail!='device_queue_full':raise + return {'status':'not_dispatched','turn_id':turn,'result':'设备待执行任务已满,本条未入队。'} + return {'status':status,'turn_id':turn,'result':'任务已接收。'} if not self.store.begin_turn(turn, owner, host): return {"status": "duplicate", "turn_id": turn, "result": "该请求已接收,不会重复执行。"} task = None @@ -256,6 +271,8 @@ def create_app(settings=None, redis=None, platform=None): lifecycle = DeviceLifecycle(store.lifecycle,r,broker) from .task_delivery import TaskDelivery deliveries = TaskDelivery(oauth,store.lifecycle,broker,f) + from .task_dispatch import TaskDispatch + broker.dispatch_queue=TaskDispatch(oauth,store.lifecycle,broker) if s.work_files_enabled: from .work_files import WorkFiles broker.files=WorkFiles(s,oauth,store.lifecycle,f) @@ -310,6 +327,7 @@ def create_app(settings=None, redis=None, platform=None): await asyncio.sleep(5) try: await lifecycle.maintain() + broker.dispatch_queue.expire() if approvals:await approvals.maintain() except Exception: # No credentials or raw exception text in background logs. @@ -363,7 +381,9 @@ def create_app(settings=None, redis=None, platform=None): app.state.approvals=approvals if lifecycle: app.include_router(deliveries.router) + app.include_router(broker.dispatch_queue.router) app.state.deliveries=deliveries + app.state.dispatch_queue=broker.dispatch_queue if broker.files: app.include_router(broker.files.router) app.state.files=broker.files @@ -646,6 +666,9 @@ def create_app(settings=None, redis=None, platform=None): **({"chat_id":message["chat_id"],"source_message_id":message_id} if lifecycle else {})))["result"] turn = "msg_"+hashlib.sha256(message_id.encode()).hexdigest() task = store.lifecycle.task(turn) if lifecycle else None + if task and task['status']=='queued': + store.finish(event_turn,"task_queued") + return if task and not store.lifecycle.claim_reply(turn,owner,message_id): store.finish(event_turn,"result_discarded") return diff --git a/deployable/relay/credential_api.py b/deployable/relay/credential_api.py index b95faee..dd71890 100644 --- a/deployable/relay/credential_api.py +++ b/deployable/relay/credential_api.py @@ -121,6 +121,7 @@ class CredentialAPI: raise HTTPException(503, "credential_temporarily_unavailable") from None self.require_binding(body.host_id, device["owner"], device["binding_generation"]) return no_cache(JSONResponse({"credential_mode": "broker", "protocol_version": 2, + "dispatch_protocol": "work-dispatch-v1", "approval_protocol": "work-approval-v1" if self.s.work_remote_approvals_enabled else None, "binding_owner": device["owner"], "binding_generation": device["binding_generation"], diff --git a/deployable/relay/task_cards.py b/deployable/relay/task_cards.py index bdb5913..c8f3835 100644 --- a/deployable/relay/task_cards.py +++ b/deployable/relay/task_cards.py @@ -62,7 +62,7 @@ class TaskCards: def snapshot(self,task): row=self.db.execute('SELECT execution_state FROM work_execution_state_v3 WHERE task_id=?',(task['turn_id'],)).fetchone() delivery=self.db.execute('SELECT status FROM work_result_outbox_v2 WHERE task_id=?',(task['turn_id'],)).fetchone() - execution=row['execution_state'] if row else 'unknown' + execution=row['execution_state'] if row else 'queued' if task['status']=='queued' else 'unknown' 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() diff --git a/deployable/relay/task_delivery.py b/deployable/relay/task_delivery.py index 2b64bdb..5da1a65 100644 --- a/deployable/relay/task_delivery.py +++ b/deployable/relay/task_delivery.py @@ -48,7 +48,7 @@ class TaskDelivery: remote_approvals=auth.s.work_remote_approvals_enabled) broker.task_cards=self.cards - def current(self, body, *, read_receipt=False): + def current(self, body, *, read_receipt=False, read_queue=False): self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation) task=self.state.task(body.task_id) if (not task or @@ -65,6 +65,8 @@ class TaskDelivery: and (known or (files and files.output_receipts(task)))): return task raise HTTPException(403,'task_not_recoverable') + if read_queue and task['status']=='queued': + return task if not known and task['status'] not in {'inflight','unknown'}: raise HTTPException(403,'task_not_recoverable') return task @@ -82,14 +84,14 @@ class TaskDelivery: } 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', + 'execution_state':execution['execution_state'] if execution else 'queued' if task['status']=='queued' 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'],'delivery':delivery} async def status(self,body:TaskRequest,request:Request): await self.auth.authenticate(body,request) - task=self.current(body) + task=self.current(body,read_queue=True) pending=self.broker.pending.get(body.task_id) if pending and pending.host==body.host_id:pending.progress.set() return no_cache(JSONResponse(self.receipt(task))) diff --git a/deployable/relay/task_dispatch.py b/deployable/relay/task_dispatch.py new file mode 100644 index 0000000..bdfad61 --- /dev/null +++ b/deployable/relay/task_dispatch.py @@ -0,0 +1,132 @@ +"""C101 pull queue. No process-local state authorizes execution.""" +import hashlib +import time + +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import JSONResponse +from pydantic import Field + +from .common import no_cache +from .credential_api import DeviceRequest +from .crypto import canonical +from .task_delivery import TaskRequest + + +PROTOCOL = 'work-dispatch-v1' + + +class Acceptance(TaskRequest): + digest: str = Field(pattern=r'^[a-f0-9]{64}$') + + +class TaskDispatch: + def __init__(self, auth, state, broker): + self.auth, self.state, self.broker = auth, state, broker + self.db=state.db + self.keyring=auth.broker.store.keyring + with self.db: + self.db.execute("""CREATE TABLE IF NOT EXISTS work_dispatch_v1 ( + task_id TEXT PRIMARY KEY, digest TEXT NOT NULL, key_id TEXT NOT NULL, + ciphertext TEXT NOT NULL, file_transfer INTEGER NOT NULL, + accepted_at DOUBLE PRECISION)""") + self.router=APIRouter() + self.router.add_api_route('/work/v2/tasks/next',self.next_task,methods=['POST']) + self.router.add_api_route('/work/v2/tasks/accept',self.accept,methods=['POST']) + + def _aad(self, task, digest, files): + return canonical([PROTOCOL,*[task[k] for k in ('environment','app_id','owner','host_id', + 'binding_generation','turn_id','chat_id','source_message_id')],digest,bool(files)]) + + def enqueue(self, owner, device, text, turn, *, chat_id, source_message_id, file_transfer): + digest=hashlib.sha256(text.encode()).hexdigest() + now=time.time();host=device['host_id'];generation=device['binding_generation'] + with self.db: + self.state._owner_lock(owner) + if (self.broker.files and not file_transfer + and self.broker.files.pending_count(owner,host,generation,chat_id)): + raise ValueError('materials_require_file_capability') + inserted=self.db.execute("INSERT INTO turns VALUES(?,?,?,?,?) ON CONFLICT(turn_id) DO NOTHING", + (turn,owner,host,'queued',now)).rowcount + if inserted!=1:return 'duplicate' + count=self.db.execute("""SELECT COUNT(*) AS n FROM work_tasks_v2 WHERE environment=? AND app_id=? + AND host_id=? AND binding_generation=? AND status='queued' AND deadline>?""", + (self.state.environment,self.state.app_id,host,generation,now)).fetchone()['n'] + if count>=min(self.broker.s.max_pending,20): + raise HTTPException(503,'device_queue_full') + task=self.state.create_task_locked(turn,owner,host,generation,'',self.broker.worker_id, + now+self.broker.s.task_tracking_timeout,chat_id,source_message_id,status='queued') + if file_transfer: + self.broker.files.claim_locked(task) + key,cipher=self.keyring.encrypt(text.encode(),self._aad(task,digest,file_transfer)) + self.db.execute('INSERT INTO work_dispatch_v1 VALUES(?,?,?,?,?,NULL)', + (turn,digest,key,cipher,int(file_transfer))) + return 'queued' + + async def next_task(self,body:DeviceRequest,request:Request): + await self.auth.authenticate(body,request) + with self.db: + self.state._owner_lock(body.binding_owner) + self.auth.require_binding(body.host_id,body.binding_owner,body.binding_generation) + row=self.db.execute("""SELECT t.*,q.digest,q.key_id,q.ciphertext,q.file_transfer + FROM work_tasks_v2 t JOIN work_dispatch_v1 q ON q.task_id=t.turn_id + WHERE t.environment=? AND t.app_id=? AND t.owner=? AND t.host_id=? + AND t.binding_generation=? AND t.status='queued' AND t.deadline>? + AND q.accepted_at IS NULL + ORDER BY t.created_at,t.turn_id LIMIT 1 """, + (self.state.environment,self.state.app_id,body.binding_owner,body.host_id, + body.binding_generation,time.time())).fetchone() + job=None + if row: + text=self.keyring.decrypt(row['key_id'],row['ciphertext'], + self._aad(row,row['digest'],row['file_transfer'])).decode() + if hashlib.sha256(text.encode()).hexdigest()!=row['digest']: + raise HTTPException(409,'dispatch_integrity_failed') + context={k:row[k] for k in ('environment','app_id','owner','host_id','binding_generation', + 'chat_id','source_message_id','conversation_id')} + context.update(task_id=row['turn_id'],channel='work-dm') + job={'context':context,'text':text,'digest':row['digest'],'file_transfer':bool(row['file_transfer'])} + return no_cache(JSONResponse({'protocol':PROTOCOL,'task':job})) + + async def accept(self,body:Acceptance,request:Request): + await self.auth.authenticate(body,request) + with self.db: + self.state._owner_lock(body.binding_owner) + 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 (task['owner'],task['host_id'],task['binding_generation']) != + (body.binding_owner,body.host_id,body.binding_generation) + or task['status'] in {'unbound','revoked','expired','result_discarded'}): + raise HTTPException(403,'task_not_recoverable') + row=self.db.execute('SELECT digest,accepted_at FROM work_dispatch_v1 WHERE task_id=?', + (body.task_id,)).fetchone() + if not row: + raise HTTPException(403,'task_not_recoverable') + if row['digest']!=body.digest: + raise HTTPException(409,'dispatch_digest_mismatch') + if row['accepted_at'] is None: + if task['status']!='queued': + raise HTTPException(403,'task_not_recoverable') + now=time.time() + changed=self.db.execute("""UPDATE work_tasks_v2 SET status='inflight',worker_id=?,updated_at=? + WHERE turn_id=? AND status='queued' AND deadline>?""", + (self.broker.worker_id,now,body.task_id,now)).rowcount + if changed!=1: + raise HTTPException(403,'task_not_recoverable') + self.db.execute("UPDATE turns SET status='inflight' WHERE turn_id=?",(body.task_id,)) + self.db.execute("UPDATE work_dispatch_v1 SET accepted_at=?,ciphertext='' WHERE task_id=?", + (now,body.task_id)) + else: + now=row['accepted_at'] + return no_cache(JSONResponse({'protocol':PROTOCOL,'task_id':body.task_id, + 'digest':body.digest,'accepted':True,'accepted_at':now})) + + def expire(self): + now=time.time() + scope=(self.state.environment,self.state.app_id) + with self.db: + self.db.execute("""UPDATE work_tasks_v2 SET status='expired',updated_at=? + WHERE environment=? AND app_id=? AND status='queued' AND deadline<=?""",(now,*scope,now)) + self.db.execute("""UPDATE work_dispatch_v1 SET ciphertext='' WHERE ciphertext<>'' AND task_id IN + (SELECT turn_id FROM work_tasks_v2 WHERE environment=? AND app_id=? + AND status IN ('expired','unbound','revoked'))""",scope) diff --git a/deployable/relay/work_files.py b/deployable/relay/work_files.py index 080f933..f9382d6 100644 --- a/deployable/relay/work_files.py +++ b/deployable/relay/work_files.py @@ -131,16 +131,19 @@ class WorkFiles: def claim(self,task): with self.db: self.state._owner_lock(task['owner']) - if not self.state.task_current(task):raise ValueError('stale_task') - if self.pending_count(task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],True):raise ValueError('materials_still_receiving') - self.db.execute("UPDATE work_files_v1 SET task_id=?,status=CASE WHEN status='failed' THEN 'failed_assigned' ELSE 'assigned' END,updated=? WHERE environment=? AND app_id=? AND owner=? AND host_id=? AND binding_generation=? AND chat_id=? AND direction='input' AND status IN ('staged','failed') AND expires>?",(task['turn_id'],time.time(),self.environment,self.app_id,task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],time.time())) + self.claim_locked(task) + + def claim_locked(self,task): + if not self.state.task_current(task):raise ValueError('stale_task') + if self.pending_count(task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],True):raise ValueError('materials_still_receiving') + self.db.execute("UPDATE work_files_v1 SET task_id=?,status=CASE WHEN status='failed' THEN 'failed_assigned' ELSE 'assigned' END,updated=? WHERE environment=? AND app_id=? AND owner=? AND host_id=? AND binding_generation=? AND chat_id=? AND direction='input' AND status IN ('staged','failed') AND expires>?",(task['turn_id'],time.time(),self.environment,self.app_id,task['owner'],task['host_id'],task['binding_generation'],task['chat_id'],time.time())) def current(self,body): 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 not task['source_message_id']or (task['owner'],task['host_id'],task['binding_generation'])!=(body.binding_owner,body.host_id,body.binding_generation) - or task['status']in {'unbound','revoked','result_discarded','offline'}):raise HTTPException(403,'task_not_recoverable') + or task['status']in {'queued','expired','unbound','revoked','result_discarded','offline'}):raise HTTPException(403,'task_not_recoverable') return task def metadata(self,row): diff --git a/deployable/tests/test_device_lifecycle.py b/deployable/tests/test_device_lifecycle.py index 865626d..1cb920c 100644 --- a/deployable/tests/test_device_lifecycle.py +++ b/deployable/tests/test_device_lifecycle.py @@ -52,7 +52,7 @@ async def routed(env, tmp_path): await asyncio.wait_for(server_task,5) -async def device(env, host="a"*32, *, generation=None, legacy=False, work_files=False): +async def device(env, host="a"*32, *, generation=None, legacy=False, work_files=False,durable_dispatch=False): ws = await connect(env["url"],proxy=None) env["sessions"].append(ws) challenge = json.loads(await ws.recv())["challenge"] @@ -66,6 +66,7 @@ async def device(env, host="a"*32, *, generation=None, legacy=False, work_files= app_id=env["settings"].feishu_app_id,binding_owner=row["owner"] or "ou_a", binding_generation=row["binding_generation"] if generation is None else generation) if work_files:plain['work_files']='work-files-v1' + if durable_dispatch:plain['durable_dispatch']='work-dispatch-v1' await ws.send(json.dumps({"host_id":host,"cert":row["cert"],"proof":sign(plain,env["keys"][host])})) accepted = json.loads(await asyncio.wait_for(ws.recv(),3)) assert accepted["type"] == "connected" diff --git a/deployable/tests/test_task_dispatch.py b/deployable/tests/test_task_dispatch.py new file mode 100644 index 0000000..0ebc237 --- /dev/null +++ b/deployable/tests/test_task_dispatch.py @@ -0,0 +1,100 @@ +import asyncio +import hashlib +import time + +import httpx +import pytest + +from relay.connector import create_app +from relay.device_lifecycle import DeviceLifecycle +from test_credential_api import env, wire +from test_device_lifecycle import device, routed, event, send_event + + +async def rpc(client, env, action, host='a'*32, **fields): + path='/work/v2/tasks/'+action + return await client.post(path,json=wire(env,path,host=host,**fields)) + + +async def test_real_ingress_queued_task_survives_connector_reopen_without_receipt(routed): + env=routed + await device(env,durable_dispatch=True) + msg='om-durable-instruction' + text='synthetic restart request' + task_id='msg_'+hashlib.sha256(msg.encode()).hexdigest() + await send_event(env,event(env,msg,text)) + for _ in range(200): + if env['store'].lifecycle.task(task_id):break + await asyncio.sleep(.01) + assert env['store'].lifecycle.task(task_id)['status']=='queued' + assert (await rpc(env['client'],env,'state',task_id=task_id)).json()['execution_state']=='queued' + queued=env['app'].state.dispatch_queue + assert queued.enqueue('ou_a',env['store'].device('a'*32),'/助手 '+text,task_id,chat_id='chat-a', + source_message_id=msg,file_transfer=False)=='duplicate' + old=await rpc(env['client'],env,'next') + job=old.json()['task'] + assert job['context']['task_id']==task_id and job['text']=='/助手 '+text + assert text not in str(dict(env['store'].db.execute('SELECT * FROM work_dispatch_v1').fetchone())) + assert (await rpc(env['client'],env,'result',task_id=task_id,result='premature')).status_code==403 + assert not env['platform'].replies + + second=create_app(env['settings'],env['redis'],env['platform']) + try: + assert second.state.broker.worker_id!=env['app'].state.broker.worker_id + await env['redis'].delete('hn:task-worker:'+env['app'].state.broker.worker_id) + await DeviceLifecycle(second.state.store.lifecycle,env['redis'],second.state.broker).maintain() + async with httpx.AsyncClient(transport=httpx.ASGITransport(second),base_url='https://relay.example.test') as client: + assert (await rpc(client,env,'next')).json()['task']==job + assert (await rpc(client,env,'next',host='b'*32)).json()['task'] is None + fields={'task_id':task_id,'digest':job['digest']} + assert (await rpc(client,env,'accept',host='b'*32,**fields)).status_code==403 + assert (await rpc(client,env,'accept',task_id=task_id,digest='0'*64)).status_code==409 + first=(await rpc(client,env,'accept',**fields)).json() + assert first['accepted'] is True + assert (await rpc(client,env,'next')).json()['task'] is None + # The response may be lost after commit; retry returns the same receipt. + assert (await rpc(env['client'],env,'accept',**fields)).json()==first + assert (await rpc(client,env,'result',task_id=task_id,result='synthetic result')).status_code==200 + assert (await rpc(client,env,'accept',**fields)).json()==first + await second.state.deliveries.flush() + await env['app'].state.deliveries.flush() + assert env['platform'].replies==[(msg,'synthetic result')] + assert second.state.store.db.execute('SELECT ciphertext FROM work_dispatch_v1').fetchone()['ciphertext']=='' + finally: + second.state.store.close() + + +@pytest.mark.parametrize('invalidated',['expired','unbound']) +async def test_stale_queue_entries_cannot_be_recovered(env,invalidated): + api=env['app'].state.dispatch_queue + assert api.enqueue('ou_a',env['store'].device('a'*32),'/助手 synthetic','queued-test', + chat_id='chat-a',source_message_id='om-queued',file_transfer=False)=='queued' + if invalidated=='expired': + with api.db:api.db.execute('UPDATE work_tasks_v2 SET deadline=? WHERE turn_id=?', + (time.time()-1,'queued-test')) + assert (await rpc(env['client'],env,'next')).json()['task'] is None + assert (await rpc(env['client'],env,'accept',task_id='queued-test', + digest=hashlib.sha256('/助手 synthetic'.encode()).hexdigest())).status_code==403 + else: + env['store'].unbind('ou_a') + assert (await rpc(env['client'],env,'next')).status_code==403 + api.expire() + assert env['store'].lifecycle.task('queued-test')['status']==invalidated + assert api.db.execute('SELECT ciphertext FROM work_dispatch_v1').fetchone()['ciphertext']=='' + + +@pytest.mark.parametrize('env',[True],indirect=True) +async def test_failed_queue_commit_rolls_back_task_and_material_assignment(env,monkeypatch): + from test_work_files import fake_platform + fake_platform(env,monkeypatch) + files=env['app'].state.files + await files.receive('ou_a','chat-a','om-material',{'file_name':'sample.txt','file_key':'test-file'}) + api=env['app'].state.dispatch_queue + def interrupted(*args,**kwargs):raise RuntimeError('synthetic encryption failure') + monkeypatch.setattr(api.keyring,'encrypt',interrupted) + with pytest.raises(RuntimeError): + api.enqueue('ou_a',env['store'].device('a'*32),'/助手 synthetic','queue-rollback', + chat_id='chat-a',source_message_id='om-queued',file_transfer=True) + assert not env['store'].lifecycle.task('queue-rollback') + assert api.db.execute('SELECT status FROM turns WHERE turn_id=?',('queue-rollback',)).fetchone() is None + assert dict(api.db.execute('SELECT task_id,status FROM work_files_v1').fetchone())=={'task_id':'','status':'staged'}