fix: preserve live verification owners across windows and durable stops

This commit is contained in:
阿白叔 committed 2026-11-17 18:44:02 +08:00
1 parent 6175bdb254
commit a606ed9179
5 files changed
+170 -12

No files matched your search

@@ -4,12 +4,14 @@ from threading import Event,Thread,RLock
from uuid import uuid4
from .contracts import ACTIVE,digest,fail
from .store import encode,now
from .ownership import owner_path,write_owner,read_owner,RunStop
class VerificationControl:
def __init__(self,service):
self.service=service;self.repo=service.repo;self.lock=RLock();self.events={};self.thread=None;self.closing=False
self.last_error=None
self.owner_id=uuid4().hex;self._owned_runs=set()
@property
def busy(self):
@@ -40,14 +42,18 @@ class VerificationControl:
if wanted and wanted-{(m['item_id'],m['input_version']) for m in members}:fail('所选版本已变化或正在执行,请刷新。')
self.repo.connection.execute('INSERT INTO verification_runs(run_id,task_id,members_json,state,created) VALUES (?,?,?,?,?)',
(run_id,task_id,encode(members),'queued' if members else 'completed',now()))
write_owner(self.service,'runs',run_id,self.owner_id)
result={'run_id':run_id,'members':members}
self.repo._remember('start',request_id,body,result)
owner=read_owner(self.service,'runs',result['run_id'])
if owner.get('owner_id')==self.owner_id and result['members']:
with self.lock:self._owned_runs.add(result['run_id'])
self.wake()
return result
def wake(self):
with self.lock:
if not self.closing and not self.busy:
if self._owned_runs and not self.closing and not self.busy:
self.thread=Thread(target=self._dispatch,name='verification-runner',daemon=True);self.thread.start()
def stop(self,run_id,*,request_id):
@@ -55,7 +61,7 @@ class VerificationControl:
old=self.repo._request('stop',request_id,run_id)
if old is not None:return old
run=self.repo._one('verification_runs','run_id',run_id)
self.repo.connection.execute("UPDATE verification_runs SET stop_requested=1,state=CASE WHEN state IN ('queued','running') THEN 'stopping' ELSE state END WHERE run_id=?",(run_id,))
self.repo.connection.execute("UPDATE verification_runs SET stop_requested=1,state=CASE WHEN state='queued' THEN 'stopped' WHEN state='running' THEN 'stopping' ELSE state END WHERE run_id=?",(run_id,))
for member in json.loads(run['members_json']):
self.repo.connection.execute("UPDATE verification_attempts SET state='cancelled',reason='run_stopped_before_dispatch',resource_state='released',updated=? WHERE attempt_id=? AND state='queued'",(now(),member['attempt_id']))
self.repo._touch(run['task_id']);result={'run_id':run_id,'stop_requested':True}
@@ -63,31 +69,39 @@ class VerificationControl:
with self.lock:self.events.setdefault(run_id,Event()).set()
return result
def _next_run(self):
with self.lock:owned=tuple(self._owned_runs)
if not owned:return None
placeholders=','.join('?' for _ in owned)
return self.repo.connection.execute(f"SELECT * FROM verification_runs WHERE state='queued' AND run_id IN ({placeholders}) ORDER BY created LIMIT 1",owned).fetchone()
def _dispatch(self):
from .runner import run_attempt
try:
while not self.closing:
with self.repo.store.transaction():
run=self.repo.connection.execute("SELECT * FROM verification_runs WHERE state IN ('queued','running','stopping') ORDER BY created LIMIT 1").fetchone()
run=self._next_run()
if run is None:return
run=dict(run)
if not run['stop_requested']:
self.repo.connection.execute("UPDATE verification_runs SET state='running' WHERE run_id=?",(run['run_id'],))
with self.lock:event=self.events.setdefault(run['run_id'],Event())
stop=RunStop(self.service,run['run_id'],event)
if run['stop_requested']:event.set()
blocked=False
for member in json.loads(run['members_json']):
result={}
if event.is_set() or self.closing:break
while not event.is_set() and not self.closing:
if stop.is_set() or self.closing:break
while not stop.is_set() and not self.closing:
result=run_attempt(self.service,member['attempt_id'],stop_event=event)
if not result.get('waiting'):break
event.wait(.2)
if result.get('blocked'):blocked=True;break
with self.repo.store.transaction():
state='blocked' if blocked else 'stopped' if event.is_set() or self.closing else 'completed'
state='blocked' if blocked else 'stopped' if stop.is_set() or self.closing else 'completed'
self.repo.connection.execute('UPDATE verification_runs SET state=? WHERE run_id=?',(state,run['run_id']))
self.repo._touch(run['task_id'])
with self.lock:self._owned_runs.discard(run['run_id'])
except Exception as error:
self.closing=True;self.last_error=str(error)
from ..batch_resources import write_record
@@ -100,16 +114,26 @@ class VerificationControl:
# Close the enqueue/empty-dispatch race without polling from the UI.
if not self.closing:
with self.repo.store._lock:
pending=self.repo.connection.execute("SELECT 1 FROM verification_runs WHERE state IN ('queued','running','stopping') LIMIT 1").fetchone()
pending=self._next_run()
if pending:self.wake()
def recover(self):
if self.busy:return {'interrupted':0,'blocked':0,'published':0}
result={'interrupted':0,'blocked':0,'published':0}
result={'interrupted':0,'blocked':0,'published':0,'live_owners':0}
with self.repo.store.transaction():
active_runs=self.repo.connection.execute("SELECT run_id FROM verification_runs WHERE state IN ('queued','running','stopping')").fetchall()
protected=set()
for run in active_runs:
owner=read_owner(self.service,'runs',run[0])
if owner['state']=='live' and owner.get('owner_id')!=self.owner_id:protected.add(run[0])
rows=self.repo.connection.execute("SELECT * FROM verification_attempts WHERE state IN ('queued','running','publishing','stopping')").fetchall()
for raw in rows:
row=dict(raw);identity=row['attempt_id'];directory=self.service.data_root/'verification'/'attempts'/identity
if row['run_id'] in protected:continue
owner=read_owner(self.service,'attempts',identity,row['owner_id'])
if owner['state']=='live' and owner.get('owner_id')!=self.owner_id:
if row['run_id']:protected.add(row['run_id'])
continue
if row['state']=='queued':state,resource='interrupted','released'
else:
try:
@@ -130,14 +154,15 @@ class VerificationControl:
(state,resource,'上次执行中断;未自动重跑' if resource=='released' else '上次原生进程退出缺少证明,保留现场',now(),identity))
self.repo._touch(self.repo.item(row['item_id'])['task_id'])
result['blocked' if resource=='unknown' else 'interrupted']+=1
self.repo.connection.execute("UPDATE verification_runs SET state='interrupted' WHERE state IN ('queued','running','stopping')")
for run in active_runs:
if run[0] not in protected:self.repo.connection.execute("UPDATE verification_runs SET state='interrupted' WHERE run_id=?",(run[0],))
result['live_owners']=len(protected)
return result
def begin_shutdown(self):
if self.closing:return
self.closing=True
with self.repo.store._lock:
runs=[r[0] for r in self.repo.connection.execute("SELECT run_id FROM verification_runs WHERE state IN ('queued','running','stopping')")]
with self.lock:runs=tuple(self._owned_runs)
for identity in runs:self.stop(identity,request_id='shutdown:'+identity)
with self.lock:
for event in self.events.values():event.set()
@@ -0,0 +1,56 @@
"""Process creation identities for recovery; never terminate a recorded PID."""
import json
import os
from pathlib import Path
import re
import time
from types import SimpleNamespace
from ..batch_resources import process_identity,_process_gone,write_record
from .contracts import fail
def owner_path(service,kind,identity):
if kind not in {'runs','attempts'} or re.fullmatch('[0-9a-f]{32}',identity or '') is None:fail('执行归属标识无效。')
root=(service.data_root/'verification').resolve()
path=root/kind/identity/'owner.json'
if not path.resolve().is_relative_to(root):fail('执行归属目录越界。')
return path
def write_owner(service,kind,identity,owner_id):
process={'pid':os.getpid(),'creation_time':None}
if os.name=='nt':
import win32api
process=process_identity(SimpleNamespace(pid=os.getpid(),handle=win32api.GetCurrentProcess()))
write_record(owner_path(service,kind,identity),{'version':1,'identity':identity,'owner_id':owner_id,
'process':process,'scope':'OwnedCliScope','kill_on_owner_exit':True})
def read_owner(service,kind,identity,expected_owner=None):
try:
value=json.loads(owner_path(service,kind,identity).read_text(encoding='utf-8'))
if (value.get('version')!=1 or value.get('identity')!=identity or value.get('scope')!='OwnedCliScope'
or value.get('kill_on_owner_exit') is not True or not isinstance(value.get('owner_id'),str)
or (expected_owner and value['owner_id']!=expected_owner)):raise ValueError('归属证明不符')
identity_record=value['process']
if type(identity_record.get('pid')) is not int or identity_record['pid']<=0:raise ValueError('进程证明无效')
if os.name!='nt' or not identity_record.get('creation_time'):state='unknown'
else:state='gone' if _process_gone(identity_record) else 'live'
return dict(value,state=state)
except Exception:return {'state':'unknown'} # An inaccessible process is never proof of release.
class RunStop:
"""An Event-compatible token that observes another window's durable stop."""
def __init__(self,service,run_id,event):self.service=service;self.run_id=run_id;self.event=event
def is_set(self):
if self.event.is_set():return True
with self.service.repo.store._lock:
row=self.service.repo.connection.execute('SELECT stop_requested FROM verification_runs WHERE run_id=?',(self.run_id,)).fetchone()
return row is None or bool(row[0])
def wait(self,timeout=None):
deadline=None if timeout is None else time.monotonic()+timeout
while not self.is_set():
if deadline is not None and time.monotonic()>=deadline:return False
self.event.wait(.05 if deadline is None else min(.05,max(0,deadline-time.monotonic())))
return True
@@ -35,8 +35,13 @@ def run_attempt(service,attempt_id,*,stop_event):
attempt=None
try:
check_cancelled(stop_event)
attempt=service.repo.claim(attempt_id,owner_id=uuid4().hex)
from .ownership import write_owner,RunStop
with service.repo.store.transaction():
attempt=service.repo.claim(attempt_id,owner_id=service.control.owner_id)
if attempt:write_owner(service,'attempts',attempt_id,attempt['owner_id'])
if attempt is None:return {'published':False}
if attempt['run_id']:stop_event=RunStop(service,attempt['run_id'],stop_event)
check_cancelled(stop_event)
payload=service.repo.revision(attempt['item_id'],attempt['input_version'])['payload']
output=service.data_root/'verification'/'attempts'/attempt_id
left,right=export_inputs(service,payload['before_ref'],payload['after_ref'],output=output,stop_event=stop_event)
+70
View File
@@ -89,3 +89,73 @@ def test_storage_failure_pauses_dispatcher_without_replaying_forever(service,tmp
service.start(task,request_id='run');wait_idle(service)
assert service.control.closing and len(calls)<=2
assert (service.data_root/'verification/engine-paused.json').is_file()
def test_other_window_recovery_and_close_do_not_interrupt_live_owner(service,tmp_path,monkeypatch):
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.verification.service import VerificationService
from dx_productivity.trial_task_center import netlist_verification
entered=Event();release=Event()
def native(capture,output,*,stop_event):
entered.set();release.wait(5);output.mkdir(parents=True,exist_ok=True)
return {'status':'success','complete':True,'graph':graph(output),'outputs':{}}
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
task,item=imported(service,tmp_path);run=service.start(task,request_id='owner');assert entered.wait(3)
other_store=TaskStore(service.repo.store.path);other=VerificationService(other_store,service.data_root)
try:
recovered=other.recover()
assert recovered.get('live_owners')==1
assert service.repo.latest_attempt(item,1)['state']=='running'
other.start(task,request_id='observe')
assert not other.busy
other.begin_shutdown()
assert not service.repo._one('verification_runs','run_id',run['run_id'])['stop_requested']
finally:release.set();wait_idle(service);other.begin_shutdown();other_store.close()
assert service.read_item(item)['status']=='consistent'
def test_stop_from_another_window_is_observed_during_native_export(service,tmp_path,monkeypatch):
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.verification.service import VerificationService
from dx_productivity.trial_task_center import netlist_verification
entered=Event()
def native(capture,output,*,stop_event):
entered.set();stop_event.wait(2)
return {'status':'cancelled','complete':False}
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
task,item=imported(service,tmp_path);run=service.start(task,request_id='owner');assert entered.wait(3)
other_store=TaskStore(service.repo.store.path);other=VerificationService(other_store,service.data_root)
try:
other.stop(run['run_id'],request_id='foreign-stop');wait_idle(service)
assert service.read_item(item)['status']=='stopped'
finally:other.begin_shutdown();other_store.close()
def test_owner_exit_without_cli_exit_proof_remains_unknown(service,tmp_path,monkeypatch):
from dx_productivity.trial_task_center.verification import ownership
task,item=imported(service,tmp_path)
attempt=service.repo.create_attempt(item,1,request_id='lost')
service.repo.claim(attempt['attempt_id'],owner_id=service.control.owner_id)
ownership.write_owner(service,'attempts',attempt['attempt_id'],service.control.owner_id)
# This includes a reused PID: the original creation identity is gone.
monkeypatch.setattr(ownership,'_process_gone',lambda identity:True)
recovered=service.recover()
assert recovered['blocked']==1 and recovered['published']==0
assert service.repo.attempt(attempt['attempt_id'])['resource_state']=='unknown'
def test_recovery_publishes_intact_staged_result_without_reexport(service,tmp_path,monkeypatch):
from dx_productivity.trial_task_center import netlist_verification
from dx_productivity.trial_task_center.verification.runner import run_attempt
calls=[]
def native(capture,output,*,stop_event):
calls.append(1);output.mkdir(parents=True,exist_ok=True)
return {'status':'success','complete':True,'graph':graph(output),'outputs':{}}
monkeypatch.setattr(netlist_verification,'_export_saved_capture',native)
_,item=imported(service,tmp_path);attempt=service.repo.create_attempt(item,1,request_id='staged')
with monkeypatch.context() as patch:
patch.setattr(service.repo,'finish',lambda *args,**kwargs:False)
assert not run_attempt(service,attempt['attempt_id'],stop_event=Event())['published']
recovered=service.recover()
assert recovered['published']==1 and len(calls)==2
assert service.read_item(item)['status']=='consistent' and not service.busy
+2
View File
@@ -2,6 +2,8 @@
import argparse
import json
from pathlib import Path
import sys
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'src'))
from dx_productivity.trial_task_center.verification.pin_metadata import inspect_pin_metadata