am-freescan/scripts/verify_resource_scheduling.py

229 lines
16 KiB
Python
Raw Permalink Normal View History

2026-10-22 16:18:37 +08:00
"""Real local API regression for scan scheduling. Own SCANQA fixtures are cleaned on success.
Uses the opt-in simulator only. Keeps customer/DEMO data and the stable runtime
device representation. Never writes the source CMVR projects or another database.
"""
from __future__ import annotations
import datetime as dt
import json
import time
import uuid
import threading
from concurrent.futures import ThreadPoolExecutor
from verify_scan_only import ScanOnlyVerifier, ROOT, NOTE
from verify_cmvr_native import require, response_identifier, safe, stamp
from robot_simulator import ROBOT_ID, write_json
from cleanup_verification import cleanup
REPORT=ROOT/'.local/resource-scheduling-verification.json'
def moment(minutes=0,seconds=0):
return int((dt.datetime.now()+dt.timedelta(minutes=minutes,seconds=seconds)).replace(microsecond=0).timestamp()*1000)
class ResourceSchedulingVerifier(ScanOnlyVerifier):
def __init__(self):
super().__init__()
prefix_file=ROOT/'.local/resource-run-prefixes.json'
prefixes=json.loads(prefix_file.read_text()) if prefix_file.exists() else []
prefixes.append(self.prefix);prefix_file.write_text(json.dumps(prefixes))
self.device=None
self.native_instances=[]
self.manual_owners=[]
def check(self,name,**details):
self.report['checks'].append(dict(name=name,passed=True,**safe(details)))
print('PASS',name,flush=True);write_json(REPORT,self.report)
def import_task(self,*args,**kwargs):
task=super().import_task(*args,**kwargs);self.active_tasks.add(task);return task
def acquire(self,task):
return self.api('POST','/lab/scan-task/acquire-resources',dict(taskId=task,expectedRevision=self.task(task)['config']['revision']))
def cancel_task(self,task):
self.api('POST','/lab/scan-task/cancel',dict(taskId=task,reason=self.prefix+' verification finished'))
self.wait_task(task,'CANCELLED');self.active_tasks.discard(task)
def wait_task(self,task,status):
until=time.monotonic()+20
while time.monotonic()<until:
current=self.task(task)
if current['task']['status']==status:return current
time.sleep(.2)
raise AssertionError('Task did not reach '+status)
def leases(self,task):
return self.task(task)['resourceState']['leases']
def assert_lease_count(self,task,count):
require(len(self.leases(task))==count,'Unexpected actual occupation set')
def verify_concurrent_acquisition(self,case):
tasks=[self.import_task('concurrent-'+str(i),case['caseId'],1) for i in range(2)]
for task in tasks:self.prepare(task,case['caseId'])
revisions={task:self.task(task)['config']['revision'] for task in tasks}
barrier=threading.Barrier(2)
def acquire(task):
barrier.wait(timeout=10)
result=self.client.request('POST','/admin-api/lab/scan-task/acquire-resources',
dict(taskId=task,expectedRevision=revisions[task]),expected=None)
return task,result.get('code')
with ThreadPoolExecutor(max_workers=2) as pool:results=list(pool.map(acquire,tasks))
winners=[task for task,code in results if code==0];losers=[task for task,code in results if code!=0]
require(len(winners)==len(losers)==1,'Concurrent real MySQL acquisition must have exactly one winner')
self.assert_lease_count(winners[0],3);self.assert_lease_count(losers[0],0)
require(not self.task(losers[0])['resourceState']['bookings'],'Losing acquisition left partial bookings')
for task in tasks:self.cancel_task(task)
self.check('真实 MySQL 两任务并发申请仅一方成功,失败方无部分占用或预约,取消后释放')
def trial(self,case,rejected=False):
result=self.client.native('POST','/flow/executeTrial',dict(robotId=ROBOT_ID,itemId=case['itemId'],
flowData=json.dumps(case['graph'],ensure_ascii=False),
runtimeAssignments=self.prepare_body_for_roles(),runParams=dict(verificationMarker='SIMULATED-resource')),
expected=None if rejected else (200,))
if rejected:require(result.get('code')!=200,'Trial bypassed occupation');return
instance=response_identifier(result);self.native_instances.append(instance);return instance
@staticmethod
def prepare_body_for_roles():
from robot_simulator import DEVICE_ID
return [dict(roleKey='sim-robot',members=[dict(memberKey='sim-1',robotId=ROBOT_ID,devices=dict(chassis=DEVICE_ID))])]
def run(self,keep_for_browser=False):
passed=False
try:
self.client.native('POST','/resource/robots/'+ROBOT_ID+'/sync-runtime')
before=self.api('GET','/lab/scan-task/resource-occupations')
self.client.native('GET','/resource/robots/'+ROBOT_ID+'/devices')
self.client.native('GET','/resource/robots/'+ROBOT_ID+'/maps')
require(self.api('GET','/lab/scan-task/resource-occupations')==before,'Read-only resource queries created an occupation')
self.report['protectedBefore']=self.native.db.select("SELECT id,status FROM lab_test_task WHERE external_task_no LIKE %s AND deleted=0 ORDER BY id",('DEMO-20261022-091650%',))
case=self.create_case('resource-schedule',sleep_ms=5000)
quick=self.create_case('resource-quick')
first=self.import_task('scheduled-main',case['caseId'],3)
self.prepare(first,case['caseId'])
device=next(r for r in self.task(first)['resourceState']['resources'] if r['type']=='DEVICE')
self.device=self.api('GET','/lab/master/device/get',query=dict(id=device['id']))
lab=self.api('POST','/lab/master/lab/create',dict(labCode=self.prefix+'-LAB',labName='模拟独占工位',location='SIMULATED',exclusiveUse=True,status='ENABLED',remark=NOTE))
self.api('PUT','/lab/master/device/update',dict(self.device,laboratoryId=lab))
self.prepare(first,case['caseId'])
require(any(r['type']=='LAB' for r in self.task(first)['resourceState']['resources']),'Device exclusive lab was bypassed')
future=self.import_task('future-booking',quick['caseId'],1)
scheduled=self.prepare_body(future,quick['caseId'],reservationMode='SCHEDULED',plannedStartAt=moment(minutes=10),plannedEndAt=moment(minutes=20))
self.api('PUT','/lab/scan-task/prepare',scheduled)
state=self.task(future)['resourceState']
require(len(state['bookings'])==2 and not state['leases'],'Scheduled save should book device/lab without physical occupation')
self.api('POST','/lab/scan-task/acquire-resources',dict(taskId=future,expectedRevision=self.task(future)['config']['revision']),rejected=True)
blocked=self.api('POST','/lab/scan-task/precheck',dict(taskId=first))
require(not blocked['passed'],'Immediate 60-minute batch ignored upcoming booking')
self.api('PUT','/lab/scan-task/prepare',self.prepare_body(first,case['caseId'],expectedMinutes=1))
self.check('独占场地由设备推导;未来预约保存、提前启动阻断、整批时段冲突校验')
self.acquire(first);self.assert_lease_count(first,3)
self.client.native('GET','/resource/robots/'+ROBOT_ID+'/devices');self.assert_lease_count(first,3)
self.api('PUT','/lab/scan-task/prepare',self.prepare_body(first,case['caseId']),rejected=True)
self.trial(quick,rejected=True)
motion=self.client.native('POST','/resource/robots/'+ROBOT_ID+'/navigate-to-position',query=dict(x=0,y=0,theta=0),expected=None)
require(motion.get('code')!=200,'Manual movement bypassed task lease')
for booking in self.task(first)['resourceState']['bookings']:
endpoint='device-reservation' if booking['type']=='DEVICE' else 'lab-reservation'
self.api('POST',f"/lab/resource/{endpoint}/{booking['id']}/force-release",dict(reason=self.prefix),rejected=True)
self.api('POST','/lab/scan-task/extend-resources',dict(taskId=first,endAt=moment(minutes=15)),rejected=True)
self.api('POST','/lab/scan-task/extend-resources',dict(taskId=first,endAt=moment(minutes=2)))
self.check('装夹前原子占用;冻结准备;试运行/人工动作/预约强制释放不能绕过;延期尊重后续预约')
units=self.task(first)['units']
execution,_=self.start(first,units[0],key=uuid.uuid4().hex)
deadline=time.monotonic()+10
while time.monotonic()<deadline:
if self.api('GET','/lab/execution/get',query=dict(id=execution))['status']=='RUNNING':break
time.sleep(.1)
self.api('POST','/lab/scan-task/pause',dict(taskId=first))
time.sleep(.3);self.assert_lease_count(first,3)
self.api('POST','/lab/scan-task/resume',dict(taskId=first))
self.wait_execution(execution);self.assert_lease_count(first,3)
for unit in units[1:]:
execution,_=self.start(first,unit,key=uuid.uuid4().hex);self.wait_execution(execution)
self.wait_task(first,'COMPLETED');self.assert_lease_count(first,0);self.active_tasks.discard(first)
require(all(b['status']=='FINISHED' for b in self.task(first)['resourceState']['bookings']),'Normal batch did not finish its bookings')
self.cancel_task(future)
self.check('三件逐件执行:暂停/恢复/换件保留三类占用,整批完成释放并结束预约')
self.verify_concurrent_acquisition(quick)
expiry=self.import_task('expired-window',case['caseId'],2)
self.api('PUT','/lab/scan-task/prepare',self.prepare_body(expiry,case['caseId'],reservationMode='SCHEDULED',plannedStartAt=moment(seconds=-10),plannedEndAt=moment(seconds=4)))
self.acquire(expiry)
unit_list=self.task(expiry)['units'];execution,_=self.start(expiry,unit_list[0],key=uuid.uuid4().hex);self.wait_execution(execution)
self.assert_lease_count(expiry,3)
self.api('POST','/lab/scan-task/start-unit',dict(taskId=expiry,unitId=unit_list[1]['id'],expectedRevision=self.task(expiry)['config']['revision'],loadedConfirmed=True,idempotencyKey=uuid.uuid4().hex),rejected=True)
self.api('POST','/lab/scan-task/extend-resources',dict(taskId=expiry,endAt=moment(minutes=2)))
execution,_=self.start(expiry,unit_list[1],key=uuid.uuid4().hex);self.wait_execution(execution);self.active_tasks.discard(expiry)
self.check('预约过期仍占用,下一件受阻;检查冲突并延期后可继续完成')
preparation=self.import_task('release-preparation',quick['caseId'],1);self.prepare(preparation,quick['caseId']);self.acquire(preparation)
self.api('POST','/lab/scan-task/release-resources',dict(taskId=preparation,reason=self.prefix,unloadedConfirmed=False),rejected=True)
self.api('POST','/lab/scan-task/release-resources',dict(taskId=preparation,reason=self.prefix,unloadedConfirmed=True))
self.assert_lease_count(preparation,0);self.prepare(preparation,quick['caseId']);self.acquire(preparation);self.cancel_task(preparation)
self.check('未执行时确认卸件后可释放并重新准备;准备阶段取消经停止确认后释放')
native=self.trial(quick);self.native.wait_native(native)
require(not self.native.db.select('SELECT id FROM lab_resource_occupation WHERE owner_key=%s',('NATIVE:'+native,)),'Successful trial kept leases')
failed=self.create_case('resource-failed-trial')
script=next(n for n in failed['graph']['nodes'] if n['id']=='code')['properties']['nodeParams'][0]
script['input']="function handler(params) { throw new Error('SIMULATED native failure'); }"
self.native.publish(failed['itemId'],failed['graph'],NOTE)
failed_inst=self.trial(failed);self.native.wait_native(failed_inst,expected=2)
require(not [r for r in self.api('GET','/lab/scan-task/resource-occupations') if r['owner_key']=='NATIVE:'+failed_inst],'Acknowledged failure cleanup kept leases')
self.check('节点失败后设备停止成功应自动释放资源,不要求额外人工释放')
world=getattr(self,'fixture_world',None)
require(world is not None,'Stop-failure regression requires the isolated fixture; use verify_scan_only_isolated.py --resources')
world.stop_failure=True
failed_inst=self.trial(failed);self.native.wait_native(failed_inst,expected=2)
2026-10-22 16:18:37 +08:00
pending=[r for r in self.api('GET','/lab/scan-task/resource-occupations') if r['owner_key']=='NATIVE:'+failed_inst]
require(pending and all(r['status']=='STOP_PENDING' for r in pending),'Failed trial released resources without physical confirmation')
self.trial(quick,rejected=True)
world.stop_failure=False
2026-10-22 16:18:37 +08:00
self.api('POST','/lab/scan-task/clear-occupation',dict(ownerKey='NATIVE:'+failed_inst,reason=self.prefix+' failed trial stop'))
from robot_simulator import DEVICE_ID
self.client.native('POST','/api/agv/navigateToPose',dict(robotId=ROBOT_ID,deviceId=DEVICE_ID,x=0,y=0,theta=0))
self.client.native('POST','/resource/robots/'+ROBOT_ID+'/navigate-to-position',query=dict(x=0,y=0,theta=0))
manual=[r for r in self.api('GET','/lab/scan-task/resource-occupations') if r['owner_key'].startswith('MANUAL:') and r.get('robot_id')==ROBOT_ID]
require(manual,'Manual movement did not retain actual occupation')
owner=manual[0]['owner_key'];self.manual_owners.append(owner)
self.trial(quick,rejected=True)
self.api('POST','/lab/scan-task/clear-occupation',dict(ownerKey=owner,reason=self.prefix+' manual stop confirmed'))
self.manual_owners.remove(owner)
self.check('原生成功释放/失败保留待停止确认;直接调试和平面导航复用人工占用,停止后释放并审计')
shared=self.api('POST','/lab/master/lab/create',dict(labCode=self.prefix+'-SHARED',labName='模拟共享实验室',location='SIMULATED',exclusiveUse=False,status='ENABLED',remark=NOTE))
self.api('PUT','/lab/master/device/update',dict(self.device,laboratoryId=shared))
shared_task=self.import_task('shared-room',quick['caseId'],1);self.prepare(shared_task,quick['caseId'])
require(not any(r['type']=='LAB' for r in self.task(shared_task)['resourceState']['resources']),'Shared room was locked wholesale')
self.acquire(shared_task);self.assert_lease_count(shared_task,2)
self.api('POST','/lab/scan-task/release-resources',dict(taskId=shared_task,reason=self.prefix,unloadedConfirmed=True))
self.cancel_task(shared_task)
self.check('共享实验室只作为位置,未要求独占时仅占用机器人和设备')
require(self.native.db.select("SELECT id,status FROM lab_test_task WHERE external_task_no LIKE %s AND deleted=0 ORDER BY id",('DEMO-20261022-091650%',))==self.report['protectedBefore'],'Requested demo tasks changed')
self.report.update(passed=True,finishedAt=stamp(),requestCount=len(self.client.events));passed=True
finally:
if getattr(self,'fixture_world',None) is not None:self.fixture_world.stop_failure=False
2026-10-22 16:18:37 +08:00
if not passed:self.report['failureCleanup']=self.cleanup_failed_run()
if not passed:
for instance in self.native_instances:
try:
self.client.native('POST','/flow/stop/'+instance,expected=None)
owned=[r for r in self.api('GET','/lab/scan-task/resource-occupations') if r['owner_key']=='NATIVE:'+instance]
if owned:self.api('POST','/lab/scan-task/clear-occupation',dict(ownerKey='NATIVE:'+instance,reason=self.prefix+' failed-run native stop'))
except Exception:pass
for owner in self.manual_owners:
try:self.api('POST','/lab/scan-task/clear-occupation',dict(ownerKey=owner,reason=self.prefix+' failure cleanup'))
except Exception:pass
if self.device:
self.api('PUT','/lab/master/device/update',self.device)
if passed and not keep_for_browser:self.report['cleanup']=cleanup([self.prefix],apply=True)
write_json(REPORT,self.report)
if self.native._db:self.native.db.close()
print(json.dumps(safe(self.report),ensure_ascii=False),flush=True)
if __name__=='__main__':
ResourceSchedulingVerifier().run()