2026-10-22 16:18:37 +08:00
""" Real API acceptance for quantity-based scan-only tasks in am-freescan.
Run after the additive migration , rebuilt backend , and simulated robot start .
Creates clearly marked software - validation cases / tasks / fixture and keeps their
records only until validation passes , then cleans the current run .
- - exercise - stop - failure briefly stops only the opt - in local robot simulator to
verify that failed stop acknowledgement retains task occupation .
"""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import io
import json
from pathlib import Path
import subprocess
import sys
import time
import urllib . error
import urllib . parse
import urllib . request
import uuid
from robot_simulator import DEVICE_ID , ROBOT_ID , read_json , write_json
from verify_cmvr_native import Client , NativeVerifier , require , safe , stamp
from verify_simulated_robot import demo_flow
ROOT = Path ( __file__ ) . resolve ( ) . parents [ 1 ]
REPORT = ROOT / ' .local/scan-only-verification.json '
NOTE = ' SIMULATED / 扫描任务逐件执行验收记录,通过后自动清理;无真实硬件运动 '
RESERVED = ( ' sampleUnitNo ' , ' attemptNo ' , ' sampleUnitId ' , ' taskId ' , ' executionId ' )
def scan_flow ( fail_second = False , sleep_ms = 0 ) :
graph = demo_flow ( )
graph [ ' nodes ' ] = [ node for node in graph [ ' nodes ' ] if node [ ' id ' ] != ' move ' ]
start = graph [ ' nodes ' ] [ 0 ] [ ' properties ' ]
start [ ' inputParams ' ] = [ dict ( name = name , type = ' number ' if name == ' attemptNo ' else ' string ' ,
required = False ) for name in RESERVED ]
start [ ' inputParams ' ] . append ( dict ( name = ' verificationMarker ' , type = ' String ' , required = True , input = ' SIMULATED-default ' ) )
code = next ( node for node in graph [ ' nodes ' ] if node [ ' id ' ] == ' code ' ) [ ' properties ' ]
script = ( ' function handler(params) { '
+ ( " if (Number(String(params.sampleUnitNo).split( ' - ' ).pop()) === 2 && Number(params.attemptNo) === 1) "
" { throw new Error( ' SIMULATED: intentional unit002 first-attempt failure ' ); } " if fail_second else ' ' )
+ ' return { simulated:true,marker: " SIMULATED " ,sampleUnitNo:params.sampleUnitNo, '
' sampleUnitId:params.sampleUnitId,attemptNo:params.attemptNo,taskId:params.taskId, '
' executionId:params.executionId,verificationMarker:params.verificationMarker}; } ' )
code [ ' nodeParams ' ] = [ dict ( name = ' code ' , type = ' input ' , input = script ) ] + [
dict ( name = name , type = ' quote ' , quoteType = ' input ' , quote = [ ' start ' , ' input ' , name ] )
for name in ( * RESERVED , ' verificationMarker ' ) ]
if sleep_ms :
graph [ ' nodes ' ] . insert ( 2 , dict ( id = ' sleep ' , type = ' sleep ' , x = 700 , y = 180 ,
properties = dict ( name = ' SIMULATED 控制验证等待 ' , action = ' SLEEP ' , inputParams = [ ] ,
nodeParams = [ dict ( name = ' delayMs ' , type = ' input ' , input = str ( sleep_ms ) ) ] ) ) )
graph [ ' edges ' ] = [ dict ( id = ' scan-edge- ' + str ( index ) , sourceNodeId = graph [ ' nodes ' ] [ index ] [ ' id ' ] ,
targetNodeId = graph [ ' nodes ' ] [ index + 1 ] [ ' id ' ] , sourceAnchorId = graph [ ' nodes ' ] [ index ] [ ' id ' ] + ' _out ' ,
targetAnchorId = graph [ ' nodes ' ] [ index + 1 ] [ ' id ' ] + ' _in ' ) for index in range ( len ( graph [ ' nodes ' ] ) - 1 ) ]
return graph
class ScanOnlyVerifier :
def __init__ ( self ) :
self . client = Client ( ) . login ( )
self . native = NativeVerifier ( self . client )
self . prefix = ' SCANQA- ' + dt . datetime . now ( ) . strftime ( ' % m %d % H % M % S- ' ) + uuid . uuid4 ( ) . hex [ : 4 ]
self . sample_code = self . prefix + ' -SAMPLE '
self . fixture_id = None
self . active_tasks = set ( )
self . report = dict ( startedAt = stamp ( ) , prefix = self . prefix , simulated = True , checks = [ ] , artifacts = [ ] ,
databaseAccess = ' Verification SELECT-only; scoped success cleanup; 192.168.28.10/am-freescan ' )
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 api ( self , method , path , body = None , query = None , rejected = False ) :
result = self . client . request ( method , ' /admin-api ' + path , body , query ,
expected = None if rejected else ( 0 , ) )
if rejected :
require ( result . get ( ' code ' ) not in ( 0 , 200 ) , ' Expected rejected request: ' + path )
return result
return result . get ( ' data ' )
def task ( self , task_id ) :
return self . api ( ' GET ' , ' /lab/scan-task/get ' , query = dict ( taskId = task_id ) )
def upload ( self , rows ) :
columns = [ ' 外部任务编号 ' , ' 试验名称 ' , ' 项目名称 ' , ' 车型/产品 ' , ' 试验类型 ' , ' 试验要求 ' ,
' 优先级 ' , ' 计划完成日期 ' , ' 申请人 ' , ' 样品编号 ' , ' 样品数量 ' , ' 方法号 ' , ' 备注 ' , ' 样品名称 ' , ' 零件号 ' ]
content = io . StringIO ( newline = ' ' )
writer = csv . DictWriter ( content , fieldnames = columns )
writer . writeheader ( )
writer . writerows ( rows )
boundary = ' ----AMFreeScanQA ' + uuid . uuid4 ( ) . hex
raw = ( f ' -- { boundary } \r \n Content-Disposition: form-data; name= " templateVersion " \r \n \r \n v2.0 \r \n '
f ' -- { boundary } \r \n Content-Disposition: form-data; name= " file " ; filename= " scan-only-qa.csv " \r \n '
' Content-Type: text/csv \r \n \r \n ' ) . encode ( )
raw + = content . getvalue ( ) . encode ( ' utf-8-sig ' ) + f ' \r \n -- { boundary } -- \r \n ' . encode ( )
request = urllib . request . Request ( self . client . base_url + ' /admin-api/lab/task/import/upload ' ,
data = raw , headers = { ' tenant-id ' : ' 1 ' , ' Authorization ' : ' Bearer ' + self . client . _token ,
' Content-Type ' : ' multipart/form-data; boundary= ' + boundary } , method = ' POST ' )
try :
with urllib . request . urlopen ( request , timeout = 40 ) as response :
result = json . loads ( response . read ( ) )
except urllib . error . HTTPError as error :
result = json . loads ( error . read ( ) )
require ( result . get ( ' code ' ) == 0 , ' Import upload failed: ' + str ( result . get ( ' msg ' ) ) )
return result [ ' data ' ]
def row ( self , suffix , case_id , quantity = 3 ) :
return dict ( zip ( [ ' 外部任务编号 ' , ' 试验名称 ' , ' 项目名称 ' , ' 车型/产品 ' , ' 试验类型 ' , ' 试验要求 ' ,
' 优先级 ' , ' 计划完成日期 ' , ' 申请人 ' , ' 样品编号 ' , ' 样品数量 ' , ' 方法号 ' , ' 备注 ' , ' 样品名称 ' , ' 零件号 ' ] ,
[ self . prefix + ' - ' + suffix , ' 【模拟验收】逐件扫描任务 ' + suffix , ' AM FreeScan SIMULATED ' , ' ' , ' OTHER ' ,
NOTE , ' NORMAL ' , ( dt . datetime . now ( ) + dt . timedelta ( days = 7 ) ) . strftime ( ' % Y- % m- %d ' ) , ' admin ' ,
self . sample_code , str ( quantity ) , case_id , NOTE , ' 【模拟验收】测试样件 ' , self . prefix + ' -PART ' ] ) )
def create_case ( self , suffix , fail_second = False , sleep_ms = 0 ) :
case_id = uuid . uuid4 ( ) . hex
self . client . native ( ' POST ' , ' /aima/testcase ' , dict ( id = case_id , caseCode = ( self . prefix + ' - ' + suffix ) [ : 49 ] ,
caseName = ' 【模拟验收】 ' + suffix + ' ' + self . prefix , caseCategory = ' 功能测试 ' , enabled = ' 0 ' , priority = ' 2 ' ,
testDescription = NOTE , precondition = ' 仅限本机模拟AGV ' , testSteps = ' 模拟AGV站点导航→脚本输出 ' ,
expectedResult = ' SIMULATED标记及逐件记录, 不代表实际检测结果 ' , remark = NOTE ) )
case = self . client . native ( ' GET ' , ' /aima/testcase/ ' + case_id ) [ ' data ' ]
graph = scan_flow ( fail_second , sleep_ms )
release = self . native . publish ( case [ ' detectItemId ' ] , graph , NOTE )
artifact = dict ( caseId = case_id , itemId = case [ ' detectItemId ' ] , graph = graph ,
versionId = release [ ' id ' ] , versionNo = release [ ' versionNo ' ] )
self . report [ ' artifacts ' ] . append ( dict ( kind = ' test-case ' , * * { k : v for k , v in artifact . items ( ) if k != ' graph ' } ) )
return artifact
def import_task ( self , suffix , case_id , quantity = 3 ) :
row = self . row ( suffix , case_id , quantity )
batch = self . upload ( [ row ] )
if batch . get ( ' errorRows ' ) :
preview = self . api ( ' GET ' , f " /lab/task/import/ { batch [ ' id ' ] } /rows/page " , query = dict ( pageNo = 1 , pageSize = 100 ) )
raise AssertionError ( ' Valid scan import rejected: ' + json . dumps ( preview , ensure_ascii = False ) )
response = self . api ( ' POST ' , f " /lab/task/import/ { batch [ ' id ' ] } /commit " , dict ( importValidOnly = False ) )
require ( response [ ' generatedCount ' ] == 1 , ' Expected one task from valid quantity import ' )
again = self . api ( ' POST ' , f " /lab/task/import/ { batch [ ' id ' ] } /commit " , dict ( importValidOnly = False ) )
require ( again [ ' generatedCount ' ] == 0 , ' Repeated commit created another task ' )
page = self . api ( ' GET ' , ' /lab/task/page ' , query = dict ( pageNo = 1 , pageSize = 100 , externalTaskNo = row [ ' 外部任务编号 ' ] ) )
matches = [ task for task in page [ ' list ' ] if task [ ' externalTaskNo ' ] == row [ ' 外部任务编号 ' ] ]
require ( len ( matches ) == 1 , ' Import generated duplicate or missing task ' )
task_id = matches [ 0 ] [ ' id ' ]
detail = self . task ( task_id )
require ( len ( detail [ ' units ' ] ) == quantity , ' Quantity did not create independent sample units ' )
require ( str ( detail [ ' config ' ] [ ' importedTestCaseId ' ] ) == case_id , ' Imported method ID not linked to exact test case ' )
require ( str ( detail [ ' config ' ] [ ' selectedTestCaseId ' ] ) == case_id , ' Default case differs from imported method ID ' )
rows = self . native . db . select ( ' SELECT COUNT(*) AS n FROM lab_task_sample_unit WHERE task_id= %s AND deleted=0 ' , ( task_id , ) )
require ( rows [ 0 ] [ ' n ' ] == quantity , ' Repeated commit changed unit count ' )
visible = self . api ( ' GET ' , ' /lab/scan-task/page ' , query = dict ( pageNo = 1 , pageSize = 100 , taskNo = matches [ 0 ] [ ' taskNo ' ] ) )
require ( any ( str ( item [ ' id ' ] ) == str ( task_id ) for item in visible [ ' list ' ] ) , ' Unexecuted imported task missing from execution page ' )
self . report [ ' artifacts ' ] . append ( dict ( kind = ' scan-task ' , id = task_id , batchId = batch [ ' id ' ] , quantity = quantity ) )
return task_id
def fixture ( self ) :
if self . fixture_id is None :
self . fixture_id = self . api ( ' POST ' , ' /lab/master/fixture/create ' , dict ( fixtureCode = self . prefix + ' -FIXTURE ' ,
fixtureName = ' 【模拟验收】小型夹具 ' , fixtureSize = ' S ' , status = ' ENABLED ' , installDesc = NOTE ,
remark = NOTE , applicables = [ ] ) )
self . api ( ' PUT ' , ' /lab/scan-task/fixture-range ' , dict ( fixtureId = self . fixture_id ,
maxLengthMm = 100 , maxWidthMm = 100 , maxHeightMm = 100 , maxWeightKg = 10 ) )
self . report [ ' artifacts ' ] . append ( dict ( kind = ' fixture ' , id = self . fixture_id ) )
return self . fixture_id
def prepare_body ( self , task_id , case_id , * * overrides ) :
detail = self . task ( task_id )
body = dict ( taskId = task_id , expectedRevision = detail [ ' config ' ] [ ' revision ' ] , testCaseId = case_id ,
sampleReceived = True , fixtureId = self . fixture ( ) , fixtureConfirmed = True , requireFixture = True ,
lengthMm = 10 , widthMm = 20 , heightMm = 30 , weightKg = 1 ,
runParams = { } , robotId = ROBOT_ID ,
runtimeAssignments = [ dict ( roleKey = ' sim-robot ' , members = [ dict ( memberKey = ' sim-1 ' , robotId = ROBOT_ID ,
devices = { ' chassis ' : DEVICE_ID } ) ] ) ] )
body . update ( overrides )
return body
def prepare ( self , task_id , case_id , expect_ready = True ) :
body = self . prepare_body ( task_id , case_id )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , body )
precheck = self . api ( ' POST ' , ' /lab/scan-task/precheck ' , dict ( taskId = task_id ) )
require ( bool ( precheck [ ' passed ' ] ) == expect_ready ,
' Prepared simulator readiness differs from expected: ' + json . dumps ( precheck , ensure_ascii = False ) )
require ( not self . native . db . select ( ' SELECT id FROM lab_execution WHERE task_id= %s AND deleted=0 ' , ( task_id , ) ) ,
' Saving preparation unexpectedly created an execution ' )
return self . task ( task_id )
def start ( self , task_id , unit , reason = None , key = None ) :
body = dict ( taskId = task_id , unitId = unit [ ' id ' ] , expectedRevision = self . task ( task_id ) [ ' config ' ] [ ' revision ' ] ,
loadedConfirmed = True , idempotencyKey = key or ( ' SCANQA- ' + uuid . uuid4 ( ) . hex ) ,
physicalSerial = ' SIMULATED- ' + str ( unit [ ' unitNo ' ] ) )
if reason :
body [ ' reason ' ] = reason
execution_id = self . api ( ' POST ' , ' /lab/scan-task/start-unit ' , body )
self . active_tasks . add ( task_id )
return execution_id , body
def wait_execution ( self , execution_id , status = ' SUCCEEDED ' , timeout = 40 ) :
deadline = time . monotonic ( ) + timeout
last = None
while time . monotonic ( ) < deadline :
2026-11-02 17:38:34 +08:00
try : last = self . api ( ' GET ' , ' /lab/execution/get ' , query = dict ( id = execution_id ) )
except TimeoutError :
self . report . setdefault ( ' pollTimeouts ' , [ ] ) . append ( dict ( executionId = str ( execution_id ) , endpoint = ' /lab/execution/get ' ) )
print ( ' WARN read-only execution poll timed out; retrying within the original deadline ' , flush = True )
if time . monotonic ( ) > = deadline : raise
continue
2026-10-22 16:18:37 +08:00
if last [ ' status ' ] == status :
return last
if last [ ' status ' ] in ( ' SUCCEEDED ' , ' FAILED ' , ' CANCELLED ' ) :
raise AssertionError ( ' Execution ended unexpectedly: ' + json . dumps ( safe ( last ) , ensure_ascii = False ) )
time . sleep ( 0.2 )
raise AssertionError ( ' Execution did not reach ' + status + ' : ' + str ( last and last [ ' status ' ] ) )
2026-11-02 17:38:34 +08:00
def cancel_for_cleanup ( self , task_id , reason ) :
try : self . api ( ' POST ' , ' /lab/scan-task/cancel ' , dict ( taskId = task_id , reason = reason ) )
except AssertionError :
# Completion can commit between the cleanup status read and cancel.
if self . task ( task_id ) [ ' task ' ] [ ' status ' ] not in ( ' COMPLETED ' , ' CANCELLED ' ) : raise
2026-10-23 09:03:27 +08:00
def wait_stop_confirmation ( self , task_id , timeout = 30 ) :
# Execution failure is persisted before the physical stop ACK. Do not
# race the safety gate by retrying as soon as FAILED becomes visible.
deadline = time . monotonic ( ) + timeout
while time . monotonic ( ) < deadline :
if not self . task ( task_id ) [ ' config ' ] . get ( ' stopPending ' ) :
return
time . sleep ( .2 )
raise AssertionError ( ' Physical stop is still unconfirmed; retry must remain blocked ' )
2026-10-22 16:18:37 +08:00
def binding ( self , execution_id ) :
deadline = time . monotonic ( ) + 15
while time . monotonic ( ) < deadline :
rows = self . native . db . select ( ' SELECT * FROM lab_cmvr_execution WHERE execution_id= %s AND deleted=0 ' , ( execution_id , ) )
if rows and rows [ 0 ] [ ' cmvr_inst_id ' ] :
return rows [ 0 ]
time . sleep ( 0.15 )
raise AssertionError ( ' Native instance binding missing ' )
def assert_occupied ( self , task_id , occupied = True ) :
rows = self . native . db . select ( ' SELECT task_id,status FROM lab_scan_robot_occupation WHERE robot_id= %s AND deleted=0 ' , ( ROBOT_ID , ) )
require ( bool ( rows ) == occupied , ' Unexpected task-level robot occupation ' )
if occupied :
require ( str ( rows [ 0 ] [ ' task_id ' ] ) == str ( task_id ) , ' Robot occupation belongs to a different task ' )
def blocked_trial ( self , case ) :
response = self . client . native ( ' POST ' , ' /flow/executeTrial ' , dict ( itemId = case [ ' itemId ' ] ,
flowData = json . dumps ( case [ ' graph ' ] , ensure_ascii = False ) , robotId = ROBOT_ID ,
runtimeAssignments = [ dict ( roleKey = ' sim-robot ' , members = [ dict ( memberKey = ' sim-1 ' , robotId = ROBOT_ID ,
devices = { ' chassis ' : DEVICE_ID } ) ] ) ] , runParams = { } ) , expected = None )
require ( response . get ( ' code ' ) != 200 , ' Native trial bypassed scan task occupation ' )
def verify_import_validation ( self , case ) :
invalid = [ self . row ( ' missing-method ' , ' ' , 1 ) , self . row ( ' unknown-method ' , uuid . uuid4 ( ) . hex , 1 ) ,
self . row ( ' fractional ' , case [ ' caseId ' ] , ' 1.5 ' ) , self . row ( ' zero-quantity ' , case [ ' caseId ' ] , 0 ) ]
batch = self . upload ( invalid )
2026-11-06 10:50:49 +08:00
require ( batch . get ( ' errorRows ' ) == 3 and batch . get ( ' validRows ' ) == 1 , ' Missing method should create a draft; explicit unknown method and invalid quantities must fail ' )
2026-10-22 16:18:37 +08:00
self . api ( ' POST ' , f " /lab/task/import/ { batch [ ' id ' ] } /commit " , dict ( importValidOnly = False ) , rejected = True )
2026-11-06 10:50:49 +08:00
self . check ( ' 缺少方法号可建草稿;显式无效方法号及非正整数量阻止导入 ' , invalidBatchId = batch [ ' id ' ] )
2026-10-22 16:18:37 +08:00
def verify_draft_reimport ( self , case ) :
suffix = ' draft-resize '
task_id = self . import_task ( suffix , case [ ' caseId ' ] , 3 )
sample = self . native . db . select ( ' SELECT id,sample_name,sample_source,sample_type,part_no FROM lab_sample WHERE sample_code= %s AND deleted=0 ' ,
( self . sample_code , ) )
require ( len ( sample ) == 1 and sample [ 0 ] [ ' sample_source ' ] and sample [ 0 ] [ ' sample_type ' ] ,
' Imported sample lacks required independently initialized master fields ' )
if self . sample_code . startswith ( self . prefix ) :
require ( sample [ 0 ] [ ' sample_name ' ] == ' 【模拟验收】测试样件 ' and sample [ 0 ] [ ' part_no ' ] == self . prefix + ' -PART ' ,
' New sample name/part number were not preserved from import ' )
self . report [ ' artifacts ' ] . append ( dict ( kind = ' sample ' , id = sample [ 0 ] [ ' id ' ] , sampleCode = self . sample_code ) )
self . check ( ' 导入未知样品时创建独立样品主数据,必填默认值及名称/零件号完整 ' , sampleId = sample [ 0 ] [ ' id ' ] )
original_numbers = [ unit [ ' unitNo ' ] for unit in self . task ( task_id ) [ ' units ' ] ]
for quantity in ( 1 , 3 ) :
batch = self . upload ( [ self . row ( suffix , case [ ' caseId ' ] , quantity ) ] )
require ( not batch . get ( ' errorRows ' ) , ' Draft reimport was incorrectly rejected during preview ' )
changed = self . api ( ' POST ' , f " /lab/task/import/ { batch [ ' id ' ] } /commit " , dict ( importValidOnly = False ) )
require ( changed [ ' generatedCount ' ] == 0 and changed [ ' updatedDraftCount ' ] == 1 ,
' Draft reimport created another task instead of updating the original ' )
detail = self . task ( task_id )
require ( len ( detail [ ' units ' ] ) == quantity , ' Draft quantity change did not resize unstarted sample units ' )
require ( [ unit [ ' unitNo ' ] for unit in detail [ ' units ' ] ] == original_numbers [ : quantity ] ,
' Draft resize changed the stable sample unit numbering ' )
require ( not self . native . db . select ( ' SELECT id FROM lab_execution WHERE task_id= %s AND deleted=0 ' , ( task_id , ) ) ,
' Draft reimport unexpectedly created executions ' )
again = self . api ( ' POST ' , f " /lab/task/import/ { batch [ ' id ' ] } /commit " , dict ( importValidOnly = False ) )
require ( again [ ' generatedCount ' ] == 0 and again [ ' updatedDraftCount ' ] == 0 , ' Repeated draft commit was not idempotent ' )
relations = self . native . db . select ( ' SELECT quantity FROM lab_task_sample WHERE task_id= %s AND deleted=0 ' , ( task_id , ) )
require ( len ( relations ) == 1 and int ( relations [ 0 ] [ ' quantity ' ] ) == 3 ,
' Repeated draft imports duplicated or lost the task/sample relationship ' )
self . check ( ' 同一外部草稿任务数量3→1→3重复导入, 无唯一键冲突、重复关系或执行 ' , taskId = task_id )
def verify_preparation ( self , task_id , case , alternate ) :
body = self . prepare_body ( task_id , alternate [ ' caseId ' ] )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , body , rejected = True )
reserved = self . prepare_body ( task_id , case [ ' caseId ' ] , runParams = dict ( attemptNo = 999 ) )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , reserved , rejected = True )
stale = dict ( body , changeReason = ' SIMULATED 更换用例审计验证 ' )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , stale )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , stale , rejected = True )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , self . prepare_body ( task_id , case [ ' caseId ' ] , changeReason = ' SIMULATED 恢复导入指定用例 ' ) )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , self . prepare_body ( task_id , case [ ' caseId ' ] , requireFixture = False ) )
bypass = self . api ( ' POST ' , ' /lab/scan-task/precheck ' , dict ( taskId = task_id ) )
require ( not bypass [ ' passed ' ] and any ( item [ ' code ' ] == ' FIXTURE ' and not item [ ' passed ' ] for item in bypass [ ' items ' ] ) ,
' Physical EDGE workflow bypassed fixture requirement ' )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , self . prepare_body ( task_id , case [ ' caseId ' ] , lengthMm = 1000 ) )
oversize = self . api ( ' POST ' , ' /lab/scan-task/precheck ' , dict ( taskId = task_id ) )
require ( not oversize [ ' passed ' ] , ' Oversize sample was accepted by small fixture ' )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , self . prepare_body ( task_id , case [ ' caseId ' ] ) )
original_case = self . client . native ( ' GET ' , ' /aima/testcase/ ' + case [ ' caseId ' ] ) [ ' data ' ]
disabled_case = dict ( original_case , enabled = ' 1 ' )
try :
self . client . native ( ' PUT ' , ' /aima/testcase ' , disabled_case )
disabled = self . api ( ' POST ' , ' /lab/scan-task/precheck ' , dict ( taskId = task_id ) )
require ( not disabled [ ' passed ' ] and any ( item [ ' code ' ] == ' RELEASE ' and not item [ ' passed ' ] for item in disabled [ ' items ' ] ) ,
' Disabled prepared case did not return structured failed RELEASE precheck ' )
finally :
self . client . native ( ' PUT ' , ' /aima/testcase ' , original_case )
self . api ( ' POST ' , ' /lab/execution/create ' , dict ( taskId = task_id ,
idempotencyKey = ' SCANQA-LEGACY- ' + uuid . uuid4 ( ) . hex ) , rejected = True )
detail = self . task ( task_id )
require ( str ( detail [ ' config ' ] [ ' importedTestCaseId ' ] ) == case [ ' caseId ' ] , ' Case change overwrote original method ID ' )
timeline = self . native . db . select ( ' SELECT * FROM lab_task_timeline WHERE task_id= %s AND deleted=0 ' , ( task_id , ) )
require ( any ( ' SIMULATED ' in str ( row ) for row in timeline ) , ' Case change reason not retained in timeline ' )
require ( not self . native . db . select ( ' SELECT id FROM lab_execution WHERE task_id= %s AND deleted=0 ' , ( task_id , ) ) ,
' Case selection implicitly created execution ' )
self . check ( ' 用例更换审计、修订冲突、夹具越界/跳过阻断及旧执行入口禁用,保存不触发执行 ' , taskId = task_id )
self . check ( ' 准备后停用用例返回结构化RELEASE失败, 恢复用例后可继续 ' , taskId = task_id )
def verify_cancelled_draft ( self , case ) :
task_id = self . import_task ( ' cancelled-draft ' , case [ ' caseId ' ] , 1 )
self . api ( ' POST ' , ' /lab/scan-task/cancel ' , dict ( taskId = task_id , reason = ' SIMULATED 取消未执行草稿 ' ) )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , self . prepare_body ( task_id , case [ ' caseId ' ] ) , rejected = True )
require ( self . task ( task_id ) [ ' task ' ] [ ' status ' ] == ' CANCELLED ' , ' Preparation revived a cancelled draft task ' )
require ( not self . native . db . select ( ' SELECT id FROM lab_execution WHERE task_id= %s AND deleted=0 ' , ( task_id , ) ) ,
' Cancelled draft unexpectedly acquired an execution ' )
self . check ( ' 已取消草稿不能重新准备或恢复执行,取消状态保持 ' , taskId = task_id )
def verify_three_units ( self , task_id , case ) :
detail = self . prepare ( task_id , case [ ' caseId ' ] )
units = sorted ( detail [ ' units ' ] , key = lambda row : row [ ' unitNo ' ] )
frozen_version = detail [ ' config ' ] [ ' versionId ' ]
first_id , first_body = self . start ( task_id , units [ 0 ] )
duplicate = self . api ( ' POST ' , ' /lab/scan-task/start-unit ' , first_body )
require ( str ( first_id ) == str ( duplicate ) , ' Repeated start request created another execution ' )
self . wait_execution ( first_id )
self . assert_occupied ( task_id )
self . blocked_trial ( case )
rerun = self . client . native ( ' POST ' , ' /test/inst/rerun/ ' + self . binding ( first_id ) [ ' cmvr_inst_id ' ] , expected = None )
require ( rerun . get ( ' code ' ) != 200 , ' Native rerun bypassed per-unit lifecycle after unit success ' )
second_task = self . import_task ( ' competing-task ' , case [ ' caseId ' ] , 1 )
competing = self . prepare ( second_task , case [ ' caseId ' ] , expect_ready = False )
second_start = dict ( taskId = second_task , unitId = competing [ ' units ' ] [ 0 ] [ ' id ' ] ,
expectedRevision = competing [ ' config ' ] [ ' revision ' ] , loadedConfirmed = True ,
idempotencyKey = ' SCANQA-CONFLICT- ' + uuid . uuid4 ( ) . hex )
self . api ( ' POST ' , ' /lab/scan-task/start-unit ' , second_start , rejected = True )
self . api ( ' POST ' , ' /lab/scan-task/cancel ' , dict ( taskId = second_task , reason = NOTE ) )
self . assert_occupied ( task_id )
self . check ( ' 任务批次占用覆盖换件等待,原生试运行及竞争任务均不能抢占 ' , taskId = task_id )
# A new published version after unit001 must not replace this task's
# frozen manifest for the remaining units.
later_graph = json . loads ( json . dumps ( case [ ' graph ' ] ) )
later_code = next ( node for node in later_graph [ ' nodes ' ] if node [ ' id ' ] == ' code ' ) [ ' properties ' ] [ ' nodeParams ' ] [ 0 ]
later_code [ ' input ' ] = later_code [ ' input ' ] . replace ( ' marker: " SIMULATED " ' , ' marker: " SIMULATED-PUBLISHED-LATER " ' )
later_release = self . native . publish ( case [ ' itemId ' ] , later_graph , ' SIMULATED frozen batch version verification ' )
require ( str ( later_release [ ' id ' ] ) != str ( frozen_version ) , ' Verification did not create a distinct newer published version ' )
self . api ( ' PUT ' , ' /lab/scan-task/prepare ' , self . prepare_body ( task_id , case [ ' caseId ' ] ) , rejected = True )
first_again = dict ( first_body , idempotencyKey = ' SCANQA-DUPLICATE- ' + uuid . uuid4 ( ) . hex )
self . api ( ' POST ' , ' /lab/scan-task/start-unit ' , first_again , rejected = True )
failed_id , _ = self . start ( task_id , units [ 1 ] )
self . wait_execution ( failed_id , ' FAILED ' )
self . assert_occupied ( task_id )
2026-10-23 09:03:27 +08:00
self . wait_stop_confirmation ( task_id )
2026-10-22 16:18:37 +08:00
failed_unit = next ( row for row in self . task ( task_id ) [ ' units ' ] if str ( row [ ' id ' ] ) == str ( units [ 1 ] [ ' id ' ] ) )
missing_reason = dict ( taskId = task_id , unitId = failed_unit [ ' id ' ] , expectedRevision = self . task ( task_id ) [ ' config ' ] [ ' revision ' ] ,
loadedConfirmed = True , idempotencyKey = ' SCANQA-NOREASON- ' + uuid . uuid4 ( ) . hex )
self . api ( ' POST ' , ' /lab/scan-task/start-unit ' , missing_reason , rejected = True )
retry_id , _ = self . start ( task_id , failed_unit , reason = ' SIMULATED 修复首次故障后仅重试002 ' )
self . wait_execution ( retry_id )
third_id , _ = self . start ( task_id , units [ 2 ] )
self . wait_execution ( third_id )
final = self . task ( task_id )
require ( final [ ' task ' ] [ ' status ' ] == ' COMPLETED ' , ' Three successful physical units did not complete scan task ' )
require ( all ( row [ ' status ' ] == ' SUCCEEDED ' for row in final [ ' units ' ] ) , ' A unit did not retain its own success ' )
require ( sorted ( row [ ' attemptNo ' ] for row in final [ ' units ' ] ) == [ 1 , 1 , 2 ] , ' Retry re-executed other units ' )
execution_rows = self . native . db . select ( ' SELECT id,sample_unit_id,attempt_no FROM lab_execution WHERE task_id= %s AND deleted=0 ORDER BY id ' , ( task_id , ) )
require ( len ( execution_rows ) == 4 , ' Expected three units plus one retry attempt ' )
for execution_id in ( first_id , failed_id , retry_id , third_id ) :
binding = self . binding ( execution_id )
require ( str ( binding [ ' version_id ' ] ) == str ( frozen_version ) , ' Batch silently upgraded to a newer case version ' )
outputs = [ ]
for execution_id in ( first_id , retry_id , third_id ) :
result = self . native . code_results ( self . binding ( execution_id ) [ ' cmvr_inst_id ' ] )
require ( result and result [ - 1 ] . get ( ' simulated ' ) is True , ' Execution output missing simulation flag ' )
require ( result [ - 1 ] . get ( ' marker ' ) == ' SIMULATED ' , ' Later published code replaced frozen batch code ' )
require ( str ( result [ - 1 ] . get ( ' executionId ' ) ) == str ( execution_id ) , ' Full execution ID did not reach native script ' )
require ( result [ - 1 ] . get ( ' verificationMarker ' ) == ' SIMULATED-default ' , ' Published parameter default was lost ' )
outputs . append ( result [ - 1 ] )
require ( len ( { output [ ' sampleUnitNo ' ] for output in outputs } ) == 3 , ' Units share the same native output identity ' )
paths = [ row . get ( ' outputPath ' ) for row in final [ ' units ' ] ]
require ( all ( paths ) and len ( set ( paths ) ) == 3 , ' Per-unit output file references are not distinct ' )
for table in ( ' lab_measurement_batch ' , ' lab_report ' ) :
require ( not self . native . db . select ( f ' SELECT id FROM { table } WHERE task_id=%s AND deleted=0 ' , ( task_id , ) ) ,
' Scan task unexpectedly entered results/report business stage ' )
self . assert_occupied ( task_id , False )
completed_rerun = self . client . native ( ' POST ' , ' /test/inst/rerun/ ' + self . binding ( first_id ) [ ' cmvr_inst_id ' ] , expected = None )
require ( completed_rerun . get ( ' code ' ) != 200 , ' Completed task native rerun bypassed scan lifecycle after lease release ' )
self . active_tasks . discard ( task_id )
self . check ( ' 数量3逐件执行、002单独失败重试、统一冻结版本、独立输出且无需报告完成 ' ,
taskId = task_id , executionIds = [ first_id , failed_id , retry_id , third_id ] , outputPaths = paths )
def simulator ( self , action ) :
subprocess . run ( [ sys . executable , str ( ROOT / ' scripts/robot_simulator.py ' ) , action ] , cwd = ROOT ,
check = True , timeout = 25 , stdout = subprocess . DEVNULL )
if action == ' start ' :
# gRPC can bind just before the daemon commits its first heartbeat.
# Wait for the same application readiness check used by execution.
deadline = time . monotonic ( ) + 10
while time . monotonic ( ) < deadline :
response = self . client . native ( ' POST ' , ' /resource/robots/ ' + ROBOT_ID + ' /sync-runtime ' , expected = None )
if response . get ( ' code ' ) == 200 :
return
time . sleep ( 0.2 )
raise AssertionError ( ' Restarted simulator did not become ready through the original backend ' )
def verify_controls ( self , case , stop_failure = False ) :
task_id = self . import_task ( ' pause-resume ' , case [ ' caseId ' ] , 1 )
detail = self . prepare ( task_id , case [ ' caseId ' ] )
execution_id , _ = self . start ( task_id , detail [ ' units ' ] [ 0 ] )
binding = self . binding ( execution_id )
deadline = time . monotonic ( ) + 15
while time . monotonic ( ) < deadline :
if any ( row . get ( ' action ' ) == ' SLEEP ' and str ( row . get ( ' status ' ) ) in ( ' RUNNING ' , ' 1 ' )
for row in self . native . node_logs ( binding [ ' cmvr_inst_id ' ] ) ) :
break
time . sleep ( 0.15 )
self . api ( ' POST ' , ' /lab/scan-task/pause ' , dict ( taskId = task_id ) )
self . wait_execution ( execution_id , ' PAUSED ' , timeout = 5 )
self . assert_occupied ( task_id )
self . api ( ' POST ' , ' /lab/scan-task/resume ' , dict ( taskId = task_id ) )
self . wait_execution ( execution_id , timeout = 40 )
self . assert_occupied ( task_id , False )
self . active_tasks . discard ( task_id )
self . check ( ' 逐件执行暂停恢复并保留占用,恢复后正常完成 ' , taskId = task_id , executionId = execution_id )
task_id = self . import_task ( ' cancel ' , case [ ' caseId ' ] , 1 )
detail = self . prepare ( task_id , case [ ' caseId ' ] )
execution_id , _ = self . start ( task_id , detail [ ' units ' ] [ 0 ] )
self . binding ( execution_id )
if stop_failure :
self . simulator ( ' stop ' )
try :
self . api ( ' POST ' , ' /lab/scan-task/cancel ' , dict ( taskId = task_id , reason = ' SIMULATED 取消及停止确认验收 ' ) )
state = self . task ( task_id )
if stop_failure :
require ( state [ ' config ' ] [ ' stopPending ' ] is True , ' Failed hardware stop was treated as acknowledged ' )
self . assert_occupied ( task_id )
self . check ( ' 停止应答失败保持STOP_PENDING及机器人占用 ' , taskId = task_id )
finally :
if stop_failure :
self . simulator ( ' start ' )
if stop_failure or self . task ( task_id ) [ ' config ' ] . get ( ' stopPending ' ) :
self . api ( ' POST ' , ' /lab/scan-task/confirm-stop ' , dict ( taskId = task_id , reason = ' SIMULATED gRPC停止应答恢复后确认 ' ) )
deadline = time . monotonic ( ) + 10
while self . task ( task_id ) [ ' config ' ] . get ( ' stopPending ' ) and time . monotonic ( ) < deadline :
time . sleep ( 0.2 )
require ( self . task ( task_id ) [ ' task ' ] [ ' status ' ] == ' CANCELLED ' , ' Acknowledged cancel did not close task ' )
self . assert_occupied ( task_id , False )
self . active_tasks . discard ( task_id )
self . check ( ' 原SystemService停止真实应答后取消收口并释放资源 ' , taskId = task_id , executionId = execution_id )
def verify_menus ( self ) :
rows = self . native . db . select ( ' SELECT id,parent_id,path FROM system_menu WHERE id IN (20310,20210,20220,20230,20240) AND deleted=0 AND status=0 ' )
by_id = { row [ ' id ' ] : row for row in rows }
require ( by_id [ 20310 ] [ ' parent_id ' ] == 23000 and by_id [ 20310 ] [ ' path ' ] == ' execution ' , ' Execution menu not under intelligence test ' )
require ( all ( by_id [ identifier ] [ ' parent_id ' ] == 23010 for identifier in ( 20210 , 20220 , 20230 , 20240 ) ) , ' Resource collaboration menus not under resource center ' )
require ( not self . native . db . select ( ' SELECT id FROM system_menu WHERE id IN (23002,23003,23004,23005,20200,20300) AND deleted=0 AND status=0 ' ) ,
' Retired menu returned ' )
self . check ( ' 智能检测统一执行入口,资源协同子菜单归资源中心,旧菜单已停用 ' )
def final_resource_state ( self ) :
occupations = self . native . db . select ( ' SELECT COUNT(*) AS n FROM lab_scan_robot_occupation WHERE deleted=0 ' ) [ 0 ] [ ' n ' ]
require ( occupations == 0 , ' Verification left task-level robot occupation behind ' )
self . client . native ( ' POST ' , ' /resource/robots/ ' + ROBOT_ID + ' /sync-runtime ' )
rows = self . client . native ( ' GET ' , ' /resource/robots ' , query = dict ( robotId = ROBOT_ID ) ) [ ' rows ' ]
require ( len ( rows ) == 1 and rows [ 0 ] [ ' connectStatus ' ] == ' 1 ' and rows [ 0 ] [ ' onlineDeviceCount ' ] == 1 ,
' Verification did not leave the simulated robot and device online ' )
return dict ( outstandingRobotOccupations = occupations , robotId = ROBOT_ID , deviceId = DEVICE_ID ,
robotOnline = True , onlineDeviceCount = 1 , nativeReadinessPassed = True , simulated = True )
def cleanup_failed_run ( self ) :
""" Release only this run ' s simulated tasks through their own APIs. """
outcomes = [ ]
if not self . active_tasks :
return outcomes
try :
self . simulator ( ' start ' )
except Exception as error :
outcomes . append ( dict ( action = ' restore-local-simulator ' , error = type ( error ) . __name__ + ' : ' + str ( error ) ) )
for task_id in list ( self . active_tasks ) :
try :
detail = self . task ( task_id )
require ( str ( detail [ ' task ' ] . get ( ' externalTaskNo ' , ' ' ) ) . startswith ( self . prefix + ' - ' ) ,
' Refusing cleanup of a task not created by this verification run ' )
if detail [ ' task ' ] [ ' status ' ] == ' COMPLETED ' :
self . active_tasks . discard ( task_id )
continue
if detail [ ' task ' ] [ ' status ' ] != ' CANCELLED ' :
self . api ( ' POST ' , ' /lab/scan-task/cancel ' , dict ( taskId = task_id , reason = ' SIMULATED 验收中断,释放本次测试任务 ' ) )
deadline = time . monotonic ( ) + 15
while time . monotonic ( ) < deadline :
detail = self . task ( task_id )
if not detail [ ' config ' ] . get ( ' stopPending ' ) :
break
self . api ( ' POST ' , ' /lab/scan-task/confirm-stop ' ,
dict ( taskId = task_id , reason = ' SIMULATED 验收清理,实际设备停止应答确认 ' ) )
time . sleep ( 0.2 )
detail = self . task ( task_id )
require ( detail [ ' task ' ] [ ' status ' ] == ' CANCELLED ' and not detail [ ' config ' ] . get ( ' stopPending ' ) ,
' Verification cleanup retained unconfirmed task occupation ' )
self . active_tasks . discard ( task_id )
outcomes . append ( dict ( taskId = task_id , status = ' CANCELLED ' , simulated = True ) )
except Exception as error :
outcomes . append ( dict ( taskId = task_id , error = type ( error ) . __name__ + ' : ' + str ( error ) ) )
return outcomes
def run ( self , stop_failure = False ) :
try :
self . api ( ' GET ' , ' /lab/scan-task/page ' , query = dict ( pageNo = 1 , pageSize = 1 ) )
self . verify_menus ( )
self . client . native ( ' POST ' , ' /resource/robots/ ' + ROBOT_ID + ' /sync-runtime ' )
main = self . create_case ( ' 逐件失败重试 ' , fail_second = True )
alternate = self . create_case ( ' 更换审计备选 ' )
controls = self . create_case ( ' 暂停取消验证 ' , sleep_ms = 12000 )
self . verify_import_validation ( main )
self . verify_draft_reimport ( main )
task_id = self . import_task ( ' three-units ' , main [ ' caseId ' ] , 3 )
self . check ( ' 导入方法号关联测试用例且数量3生成3单件, 重复提交幂等, 待执行任务可见 ' , taskId = task_id )
self . verify_preparation ( task_id , main , alternate )
self . verify_cancelled_draft ( alternate )
self . verify_three_units ( task_id , main )
self . verify_controls ( controls , stop_failure )
self . report [ ' postconditions ' ] = self . final_resource_state ( )
self . report . update ( passed = True , finishedAt = stamp ( ) , requestCount = len ( self . client . events ) )
except Exception as error :
self . report . update ( passed = False , finishedAt = stamp ( ) , error = type ( error ) . __name__ + ' : ' + str ( error ) ,
activeTaskIds = list ( self . active_tasks ) )
self . report [ ' failureCleanup ' ] = self . cleanup_failed_run ( )
self . report [ ' remainingActiveTaskIds ' ] = list ( self . active_tasks )
raise
finally :
try :
if self . report . get ( ' passed ' ) :
from cleanup_verification import cleanup
self . report [ ' cleanup ' ] = cleanup ( [ self . prefix ] , apply = True )
REPORT . unlink ( missing_ok = True )
else :
write_json ( REPORT , self . report )
finally :
if self . native . _db :
self . native . db . close ( )
print ( json . dumps ( self . report , ensure_ascii = False ) , flush = True )
if __name__ == ' __main__ ' :
parser = argparse . ArgumentParser ( description = __doc__ )
parser . add_argument ( ' --exercise-stop-failure ' , action = ' store_true ' )
args = parser . parse_args ( )
ScanOnlyVerifier ( ) . run ( args . exercise_stop_failure )