Add scanner API integration, workflow components, execution-bound live images and 3D model viewing. Harden task control, parameters, resource protection and reports, with automated regressions and detailed verification records.
255 lines
16 KiB
Python
255 lines
16 KiB
Python
"""Remove marked development verification data; dry-run unless --apply is given.
|
|
|
|
Never touches source projects, credentials, menus, or the persistent simulated
|
|
robot/device. --prefix scopes cleanup to a successful verification run.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import sys
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / '.tools/python'))
|
|
MARKERS = ('SCANQA-', 'CMVR_VERIFY_', 'CMVR_HOST_', 'CMVR_HOST_CONTROL_', 'E2E-')
|
|
LAB_TABLES = '''lab_test_task lab_execution lab_task_scan_config lab_task_sample_unit
|
|
lab_task_assignment lab_task_sample lab_task_fixture lab_task_scan_plan_selection lab_task_timeline
|
|
lab_task_import_batch lab_task_import_row lab_cmvr_execution lab_scan_attachment lab_scan_robot_occupation
|
|
lab_execution_command lab_execution_event lab_execution_exception lab_execution_precheck lab_execution_precheck_item
|
|
lab_execution_resource lab_execution_step lab_resource_readiness lab_resource_readiness_item
|
|
lab_sample_transfer lab_device_reservation lab_lab_reservation lab_material_issue
|
|
lab_measurement_batch lab_measurement_item lab_measurement_disposition lab_result_artifact_link
|
|
lab_report lab_report_version lab_report_result_batch_rel lab_report_link lab_original_record lab_original_record_revision
|
|
lab_artifact_file lab_artifact_biz_link lab_artifact_version_link lab_file_transfer lab_export_package
|
|
lab_detection_item lab_detection_version lab_detection_run lab_test_method_ref
|
|
lab_sample lab_fixture lab_fixture_applicable lab_laboratory lab_material lab_master_attachment lab_resource_occupation lab_resource_occupation_event'''.split()
|
|
NATIVE_TABLES = '''aima_test_case aima_task aima_task_test_case aima_task_instance aima_test_log
|
|
te_detection_item te_detection_item_version te_task_config_info te_task_orchestration
|
|
te_task_inst te_task_inst_flow_version te_node_inst te_ai_evaluation'''.split()
|
|
TABLES = LAB_TABLES + NATIVE_TABLES + ['infra_file','lab_device','lab_scanner_command']
|
|
|
|
|
|
def plan_rows(data, prefixes=None):
|
|
if prefixes and any(not p.startswith(MARKERS) or len(p) < 9 for p in prefixes):
|
|
raise ValueError('清理前缀必须是完整的开发验证批次前缀')
|
|
def marked(value):
|
|
return str(value or '').startswith(tuple(prefixes or MARKERS))
|
|
selected = {table: set() for table in data}
|
|
def choose(table, predicate):
|
|
selected.setdefault(table, set()).update(i for i, row in enumerate(data.get(table, [])) if predicate(row))
|
|
def rows(table):
|
|
return [data[table][i] for i in sorted(selected.get(table, set()))]
|
|
def ids(table, key='id'):
|
|
return {str(row[key]) for row in rows(table) if row.get(key) is not None}
|
|
def has(row, field, values):
|
|
return row.get(field) is not None and str(row[field]) in values
|
|
choose('lab_test_task', lambda r: marked(r.get('external_task_no')))
|
|
choose('aima_test_case', lambda r: marked(r.get('case_code')) or marked(r.get('case_name')) or
|
|
(not prefixes and r.get('case_code') == 'SIM_AGV_WORKFLOW'))
|
|
choose('aima_task', lambda r: marked(r.get('task_code')) or marked(r.get('task_name')))
|
|
choose('lab_detection_item', lambda r: marked(r.get('code')))
|
|
for table, code in [('lab_sample', 'sample_code'), ('lab_fixture', 'fixture_code'), ('lab_laboratory','lab_code')]:
|
|
choose(table, lambda r, code=code: marked(r.get(code)))
|
|
for table,code in [('lab_device','device_code'),('lab_material','material_code'),('lab_test_method_ref','method_code')]:
|
|
choose(table,lambda r,code=code:marked(r.get(code)))
|
|
case_ids = ids('aima_test_case')
|
|
item_ids = {str(r['detect_item_id']) for r in rows('aima_test_case') if r.get('detect_item_id')}
|
|
choose('te_detection_item', lambda r: str(r['id']) in item_ids)
|
|
choose('lab_test_method_ref', lambda r: r.get('external_id') in
|
|
{'CMVR:' + i for i in case_ids} | {'LOCAL:' + i for i in ids('lab_detection_item')})
|
|
attachment_owners={kind:ids(table) for kind,table in
|
|
[('SAMPLE','lab_sample'),('DEVICE','lab_device'),('FIXTURE','lab_fixture'),('METHOD','lab_test_method_ref'),('MATERIAL','lab_material'),('LAB','lab_laboratory')]}
|
|
choose('lab_master_attachment',lambda r:has(r,'biz_id',attachment_owners.get(r.get('biz_type'),set())) or marked(r.get('file_name')))
|
|
task_ids = ids('lab_test_task')
|
|
for table in LAB_TABLES:
|
|
if table != 'lab_task_import_row':
|
|
choose(table, lambda r: has(r, 'task_id', task_ids))
|
|
execution_ids = ids('lab_execution')
|
|
choose('lab_cmvr_execution', lambda r: has(r, 'execution_id', execution_ids))
|
|
native_task_ids = {str(r['task_config_id']) for r in rows('aima_task') if r.get('task_config_id')}
|
|
native_task_ids |= {str(r['cmvr_task_id']) for r in rows('lab_cmvr_execution') if r.get('cmvr_task_id')}
|
|
for task in data.get('te_task_config_info', []):
|
|
entries = [r for r in data.get('te_task_orchestration', []) if str(r.get('task_id')) == str(task['id'])]
|
|
if marked(task.get('task_name')) or (str(task.get('task_name', '')).startswith('TRIAL_') and entries
|
|
and all(str(r.get('item_id')) in item_ids for r in entries)):
|
|
native_task_ids.add(str(task['id']))
|
|
choose('te_task_config_info', lambda r: str(r['id']) in native_task_ids)
|
|
choose('te_task_inst', lambda r: has(r, 'task_id', native_task_ids))
|
|
native_inst_ids = ids('te_task_inst')
|
|
choose('lab_scanner_command', lambda r: r.get('owner_ref') in
|
|
{kind+i for i in native_inst_ids for kind in ('workflow:','resume:')}
|
|
or (str(r.get('owner_ref','')).startswith('stop:') and marked(str(r.get('owner_ref'))[5:])))
|
|
if any(r.get('active_endpoint') is not None for r in rows('lab_scanner_command')):
|
|
raise ValueError('扫描命令尚未确认终态,拒绝清理')
|
|
choose('lab_resource_occupation_event',lambda r: r.get('owner_key') in {'NATIVE:'+i for i in native_inst_ids} or marked(r.get('reason')))
|
|
choose('lab_resource_occupation',lambda r: r.get('owner_key') in {'NATIVE:'+i for i in native_inst_ids})
|
|
# Imports are cleaned only as a whole batch; a mixed customer batch is preserved.
|
|
for batch in data.get('lab_task_import_batch', []):
|
|
entries = [r for r in data.get('lab_task_import_row', []) if str(r.get('batch_id')) == str(batch['id'])]
|
|
if entries and all(marked(r.get('external_task_no')) or has(r, 'generated_task_id', task_ids) for r in entries):
|
|
choose('lab_task_import_batch', lambda r: r['id'] == batch['id'])
|
|
choose('lab_task_import_row', lambda r: str(r.get('batch_id')) == str(batch['id']))
|
|
# All other descendants are selected by explicit foreign identities, never by dates or a "test" substring.
|
|
for _ in range(5):
|
|
relations = {
|
|
'execution_id': execution_ids,
|
|
'report_id': ids('lab_report'),
|
|
'artifact_id': ids('lab_artifact_file'),
|
|
'precheck_id': ids('lab_execution_precheck'),
|
|
'readiness_id': ids('lab_resource_readiness'),
|
|
'batch_id': ids('lab_measurement_batch'),
|
|
'record_id': ids('lab_original_record'),
|
|
}
|
|
for table in LAB_TABLES:
|
|
if table in ('lab_task_import_row', 'lab_task_import_batch', 'lab_test_task', 'lab_report', 'lab_original_record'):
|
|
continue
|
|
choose(table, lambda r: (r.get('task_id') is None or has(r, 'task_id', task_ids)) and
|
|
any(has(r, field, values) for field, values in relations.items()))
|
|
for table in ['lab_detection_run', 'lab_detection_version']:
|
|
choose(table, lambda r: has(r, 'item_id', ids('lab_detection_item')))
|
|
choose('lab_fixture_applicable', lambda r: has(r, 'fixture_id', ids('lab_fixture')))
|
|
for table in NATIVE_TABLES:
|
|
if table in ('aima_test_case', 'aima_task', 'te_detection_item', 'te_task_config_info'):
|
|
continue
|
|
choose(table, lambda r: has(r, 'inst_id', native_inst_ids) or has(r, 'task_ins_id', native_inst_ids)
|
|
or has(r, 'task_id', native_task_ids | ids('aima_task'))
|
|
or has(r, 'task_instance_id', ids('aima_task_instance'))
|
|
or (table == 'te_detection_item_version' and has(r, 'detection_item_id', item_ids)))
|
|
# Refuse deletion if any non-test business object depends on the selected definitions.
|
|
guards = [
|
|
('lab_device_reservation',[('resource_id',ids('lab_device'))]),
|
|
('lab_material_issue',[('material_id',ids('lab_material'))]),
|
|
('lab_task_assignment',[('device_id',ids('lab_device'))]),
|
|
('lab_device',[('laboratory_id',ids('lab_laboratory'))]),
|
|
('lab_task_scan_config', [('selected_test_case_id', case_ids), ('fixture_id', ids('lab_fixture')),('laboratory_id',ids('lab_laboratory'))]),
|
|
('lab_lab_reservation',[('resource_id',ids('lab_laboratory'))]),
|
|
('lab_test_task', [('method_id', ids('lab_test_method_ref'))]),
|
|
('lab_task_scan_plan_selection', [('scan_plan_ref_id', ids('lab_test_method_ref'))]),
|
|
('lab_task_sample', [('sample_id', ids('lab_sample'))]),
|
|
('lab_task_fixture', [('fixture_id', ids('lab_fixture'))]),
|
|
('lab_cmvr_execution', [('test_case_id', case_ids)]),
|
|
('aima_task_test_case', [('test_case_id', case_ids)]),
|
|
('te_task_orchestration', [('item_id', item_ids)]),
|
|
]
|
|
for table, checks in guards:
|
|
for i, row in enumerate(data.get(table, [])):
|
|
if i not in selected.get(table, set()) and any(has(row, field, values) for field, values in checks):
|
|
raise ValueError('非测试业务仍引用待清理定义:' + table)
|
|
for i,row in enumerate(data.get('lab_resource_occupation',[])):
|
|
if i not in selected.get('lab_resource_occupation',set()) and row.get('resource_type')=='DEVICE' and has(row,'resource_id',ids('lab_device')):
|
|
raise ValueError('非测试占用仍引用待清理设备')
|
|
if i not in selected.get('lab_resource_occupation',set()) and row.get('resource_type')=='LAB' and has(row,'resource_id',ids('lab_laboratory')):
|
|
raise ValueError('非测试占用仍引用待清理实验室')
|
|
for table in LAB_TABLES:
|
|
for i, row in enumerate(data.get(table, [])):
|
|
if i not in selected.get(table, set()) and any(has(row, field, values) for field, values in relations.items()):
|
|
raise ValueError('非测试业务仍引用待清理执行或文件:' + table)
|
|
if any(r.get('status') not in ('SUCCEEDED', 'FAILED', 'CANCELLED') for r in rows('lab_execution')):
|
|
raise ValueError('测试执行仍在运行,必须先通过正常停止流程释放资源')
|
|
if rows('lab_resource_occupation'):
|
|
raise ValueError('资源仍被实际占用,必须先正常停止并释放')
|
|
if any(str(r.get('status')) not in ('0', '2', '4') for r in rows('te_task_inst')) or rows('lab_scan_robot_occupation'):
|
|
raise ValueError('原生实例仍在运行或机器人仍被占用,拒绝清理')
|
|
url_sources = [(table, field) for table in LAB_TABLES for field in ('original_file_url', 'file_url')]
|
|
urls = {r.get(field) for table, field in url_sources
|
|
for r in rows(table) if r.get(field)}
|
|
kept_urls = {r.get(field) for table, field in url_sources
|
|
for i, r in enumerate(data.get(table, [])) if i not in selected.get(table, set()) and r.get(field)}
|
|
choose('infra_file', lambda r: r.get('url') not in kept_urls and (r.get('url') in urls or
|
|
any(str(r.get('path', '')).startswith('scan-task/' + task_id + '/') for task_id in task_ids)))
|
|
return {table: rows(table) for table in data if selected.get(table)}
|
|
|
|
|
|
def local_payload(root, value):
|
|
if not value:
|
|
return None
|
|
path = Path(value).resolve()
|
|
for sub in ('.local/artifacts', '.local/files'):
|
|
if path.is_relative_to((Path(root) / sub).resolve()):
|
|
return path
|
|
return None
|
|
|
|
|
|
def cleanup(prefixes=None, apply=False):
|
|
from bootstrap_db import validate_target
|
|
import pymysql
|
|
config = json.loads((ROOT / '.local/runtime.json').read_text(encoding='utf-8-sig'))['mysql']
|
|
validate_target(config)
|
|
connection = pymysql.connect(host=config['host'], port=int(config.get('port', 3306)), user=config['user'],
|
|
password=config['password'], database=config['database'], charset='utf8mb4',
|
|
cursorclass=pymysql.cursors.DictCursor, autocommit=False)
|
|
try:
|
|
with connection.cursor() as cur:
|
|
cur.execute('SELECT DATABASE() db')
|
|
if cur.fetchone()['db'] != 'am-freescan':
|
|
raise ValueError('Refusing another database')
|
|
cur.execute('SELECT table_name,column_name FROM information_schema.columns WHERE table_schema=DATABASE()')
|
|
columns = {}
|
|
for r in cur.fetchall():
|
|
columns.setdefault(r['TABLE_NAME'], set()).add(r['COLUMN_NAME'])
|
|
data = {}
|
|
for table in TABLES:
|
|
if table not in columns:
|
|
continue
|
|
cur.execute('SELECT * FROM `' + table + '`' + (' WHERE deleted=0' if 'deleted' in columns[table] else '') +
|
|
(' FOR UPDATE' if apply else ''))
|
|
data[table] = cur.fetchall()
|
|
plan = plan_rows(data, prefixes)
|
|
result = dict(applied=apply, counts={t: len(rows) for t, rows in plan.items()}, removedFiles=0,
|
|
preserved=['simulated robot/device', 'customer data', 'automated regression code'])
|
|
if not apply:
|
|
return result
|
|
# Collect real payloads before removing records. Do not follow arbitrary paths from the database.
|
|
paths = set()
|
|
for table, field in [('lab_artifact_file', 'storage_path'), ('lab_task_sample_unit', 'output_path')]:
|
|
for row in plan.get(table, []):
|
|
p = local_payload(ROOT, row.get(field))
|
|
if p:
|
|
paths.add(p)
|
|
for row in plan.get('infra_file', []):
|
|
p = local_payload(ROOT, str(ROOT / '.local/files' / row['path']))
|
|
if p:
|
|
paths.add(p)
|
|
# Include terminal tombstones so retrying cleanup also removes payloads from an earlier run.
|
|
cur.execute('SELECT e.id,e.status,t.external_task_no FROM lab_execution e JOIN lab_test_task t ON t.id=e.task_id')
|
|
payload_executions = [r for r in cur.fetchall() if str(r.get('external_task_no', '')).startswith(tuple(prefixes or MARKERS))
|
|
and r['status'] in ('SUCCEEDED', 'FAILED', 'CANCELLED')]
|
|
for row in payload_executions:
|
|
folder = local_payload(ROOT, str(ROOT / '.local/artifacts/1' / str(row['id'])))
|
|
if folder and folder.is_dir():
|
|
paths.update(p for candidate in folder.rglob('*')
|
|
if (p := local_payload(ROOT, str(candidate))) and p.is_file())
|
|
cur.execute("SELECT table_name,column_name FROM information_schema.statistics WHERE table_schema=DATABASE() AND index_name='PRIMARY' ORDER BY table_name,seq_in_index")
|
|
keys = {}
|
|
for row in cur.fetchall():
|
|
keys.setdefault(row['TABLE_NAME'], []).append(row['COLUMN_NAME'])
|
|
for table, rows in plan.items():
|
|
if not keys.get(table):
|
|
raise ValueError('清理表缺少主键:' + table)
|
|
where = ' AND '.join('`' + key + '`=%s' for key in keys[table])
|
|
# These rows have passed explicit batch/ownership/reference guards.
|
|
# Physical removal avoids colliding with older soft-delete tombstones
|
|
# after a development Redis sequence has been reset.
|
|
sql = 'DELETE FROM `' + table + '` WHERE ' + where
|
|
cur.executemany(sql, [tuple(row[k] for k in keys[table]) for row in rows])
|
|
for path in paths:
|
|
if path.is_file():
|
|
path.unlink()
|
|
result['removedFiles'] += 1
|
|
connection.commit()
|
|
return result
|
|
except Exception:
|
|
connection.rollback()
|
|
raise
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--apply', action='store_true')
|
|
parser.add_argument('--prefix', action='append')
|
|
args = parser.parse_args()
|
|
print(json.dumps(cleanup(args.prefix, args.apply), ensure_ascii=False))
|