From 01d1b54caa05e5b22b75301022348c9e913b140d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Fri, 23 Oct 2026 16:22:05 +0800 Subject: [PATCH] Add live CAD marker publication failure acceptance evidence --- ...2026-10-23-issue-3-marker-write-failure.md | 44 +++ tools/probe_marker_write_failure_live.py | 310 ++++++++++++++++++ 2 files changed, 354 insertions(+) create mode 100644 docs/testing/2026-10-23-issue-3-marker-write-failure.md create mode 100644 tools/probe_marker_write_failure_live.py diff --git a/docs/testing/2026-10-23-issue-3-marker-write-failure.md b/docs/testing/2026-10-23-issue-3-marker-write-failure.md new file mode 100644 index 0000000..01eb876 --- /dev/null +++ b/docs/testing/2026-10-23-issue-3-marker-write-failure.md @@ -0,0 +1,44 @@ +# Issue 3:真实写保护使 mutation marker 发布失败 + +2026-10-23,在 Windows 本机独占 CAD 验收窗口,使用全新复制的 `Audio_D2128` 工程运行源码生产 `TaskCenterService → execute_task_queue → QuickPartReplace.vbs → native_helper`。替换意图为 RV05 的 `4100-CA0000-T7 → 4100-CA0000-T0`,不勾选复制料号到 Value。中央库为 `mentor_lib.lmc`。未修改 `src`、生产 VBS 或根代理的 `build/issue-3-ui-acceptance`。 + +实际工作目录为 `build/issue-3-marker-failure/run-e361ef90cd1d4145b1c68cdfb067f4a6`。工程从原 checkout 的 `build/cbb-bom-import-live-20261015/projects/Audio_D2128` 单独复制。执行前检查没有其他 CAD 实机测试进程,并与冻结 UI 验收协调串行进行。 + +测试进程仅包装 `BatchCadRuntime._prepare_attempts`:生产方法返回并发布 `prepared` 记录后,对该 JSON 调用真实 `win32file.CreateFile`,以 `GENERIC_READ`、`FILE_SHARE_READ | FILE_SHARE_WRITE` 打开,明确不允许 `FILE_SHARE_DELETE`。该句柄不妨碍读取 prepared 记录,但阻止 helper 的 `os.replace` 原子发布。句柄保持到该次生产队列退出,并在 `finally` 关闭;没有添加生产故障开关。 + +实际证据: + +| 检查 | 结果 | +| --- | --- | +| prepared 发布与读取 | 成功;真实测试句柄 1524,可读取原 JSON | +| helper 首次发布 mutation marker | `PermissionError: [WinError 5]`,拒绝原子替换 | +| 真实调用栈 | `run_native → mark_snapshot_mutation → mark_mutation_possible → _publish → os.replace` | +| 原生提交边界 | 失败发生于 `mark_snapshot_mutation`,在原生 Replace 按钮 `click(...)` 之前 | +| VBS 状态 | `awaiting_native_replace → batch_failed`,失败工程关闭且未保存 | +| 队列结果 | `blocked`、`paused=true`,没有 `saved_ok` | +| 重复执行 | `_prepare_attempts` 只调用 1 次;本批 `retries={}`;没有再次执行替换 | +| 标记内容 | 保持 `state=prepared`,执行前后 SHA256 完全一致 | +| 资源 | 批次 session 为 `released`;CAD 退出与桌面消失均已确认 | +| 独立回读 | 私有 CAD 枚举工程全部图页,并读取所有器件属性、位置、方向、缩放及引脚位置、编号、net UID/name;前后结构化数据完全相同 | +| 对照范围 | 1 图页 `Audio-D2128:S905L CVBS-LR`,57 器件,103 引脚 | +| RV05 | UID `$2I2014`、料号 `4100-CA0000-T7`、Value `0R`,属性及两条引脚连接保持原样 | +| 原始输入 | 源工程目录完整文件哈希与中央库 LMC 哈希保持不变 | +| 可见性 | 输入桌面前后均为 Default;自有 CAD 未出现在输入桌面或成为前台 | + +prepared 文件前后 SHA256 为 `a2ee4d65d953613c50fa14fb49a22159a7d4cc3b9c3685281ffb672962c41d17`。 + +native report 的 `stage=native_replace_started` 在源码中位于 marker 写入之前,不能仅凭该 stage 判断已提交原生修改。本轮以真实异常调用栈、prepared 标记未变化、未保存状态,以及完整原理图前后独立对照共同判定。 + +首轮工具错误地要求出现后置 VBS guard 文案 `durable mutation proof failed`。实际上 native helper 更早的 marker guard 已经失败,因此该工具文案断言退出码为 1;原始 `report.json` 保留此失败,未删除或改写。修正测试识别真实 helper `_publish/os.replace` 异常后,只对同一次已执行工程运行 `--verify-existing` 只读回读,退出码为 0;该分支没有导入或队列执行调用,没有重放业务。 + +主要证据文件: + +- `report.json`:生产队列结果、唯一 attempt、真实拒绝删除共享句柄、prepared 前后哈希、原输入不变及首轮工具断言失败记录。 +- `data/tasks/*/quick-run/status.tsv` 与 `snapshot-*.tsv.native.json`:真实生产状态、WinError 5 与调用栈。 +- `data/batch-resources/*/session.json`:释放确认与空重试记录。 +- `before.json`、`readback-only/after.json`:完整结构化读取结果;JSON 对象内容比较一致,属性枚举顺序可能不同,不以文本字节哈希代替结构比较。 +- `readback-only/verification.json`:`verified=true`、`graph_identical=true`、`marker_unchanged=true`、`resources_released=true`、`business_replayed=false`。 +- 两阶段的 `desktop-observation.json`:真实 CAD 退出、桌面消失及前台/输入桌面观察。 +- `source-under-test.json`:本轮源代码与 VBS 哈希清单。 + +本例覆盖源码服务/队列/真实 VBS/helper/真实私有 CAD 的实际 Windows 写保护失败。通过测试进程包装方法实施故障注入,没有覆盖冻结 EXE 的同类注入;冻结 UI 正常流程由另一轮验收单独覆盖,不混记为本例通过。 diff --git a/tools/probe_marker_write_failure_live.py b/tools/probe_marker_write_failure_live.py new file mode 100644 index 0000000..887ab50 --- /dev/null +++ b/tools/probe_marker_write_failure_live.py @@ -0,0 +1,310 @@ +"""Source-only real CAD fail-closed probe using Windows deny-delete file handles. + +Only this test process patches _prepare_attempts. Production sources and VBS are +unchanged. All project operations target a newly copied disposable project. +""" +from __future__ import annotations + +import argparse +from dataclasses import asdict +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys +from threading import Event +import time +import traceback +from uuid import uuid4 + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO / 'src')) +sys.path.insert(0, str(REPO / 'tools')) + +from probe_batch_runtime_live import hashes, inspect_native, save + + +def read_all_sheets(spec_path): + """Discover all sheets in a private CAD, then use the independent full reader.""" + import pythoncom + import win32com.client + from dx_productivity.trial_task_center.cad_identity import project_file_path, verify_application + spec = json.loads(spec_path.read_text(encoding='utf-8')) + pythoncom.CoInitialize() + app = None + try: + app = win32com.client.GetActiveObject('Viewdraw.Application') + verify_application(app, require_view=False) + assert not project_file_path(app) + assert app.OpenProject(spec['project']) + documents = app.SchematicSheetDocuments() + spec['sheets'] = sorted((str(schematic), str(sheet)) + for schematic in documents.GetAvailableSchematics() + for sheet in documents.GetAvailableSheets(str(schematic))) + assert spec['sheets'] + documents = None + app.CloseProject() + assert not project_file_path(app) + save(spec_path, spec) + finally: + if app is not None and project_file_path(app): + app.CloseProject() + app = None + pythoncom.CoUninitialize() + inspect_native(spec_path) + + +def verify_publish_failure(output): + reports = list((output / 'data').rglob('*.native.json')) + matches = [] + for path in reports: + value = json.loads(path.read_text(encoding='utf-8')) + trace = value.get('traceback', '') + if ('mark_snapshot_mutation' in trace and 'mark_mutation_possible' in trace + and 'os.replace' in trace and 'PermissionError' in trace): + matches.append({'path': str(path.relative_to(output)), 'error': value['error'], + 'traceback': trace, 'stage': value.get('stage')}) + assert len(matches) == 1, 'expected one actual native marker publication failure' + return matches[0] + + +def verify_existing(output): + """Read back one already attempted run; never executes BOM or queue business.""" + import win32api + from dx_productivity.trial_task_center.batch_resources import pending_resources + from dx_productivity.trial_task_center.isolated_cad import IsolatedCadSession + from private_desktop_observer import PrivateDesktopObserver + output = output.resolve(strict=True) + assert output.is_relative_to(REPO / 'build/issue-3-marker-failure') + original = json.loads((output / 'report.json').read_text(encoding='utf-8')) + assert original['prepare_calls'] == 1 and len(original['locked_markers']) == 1 + assert original['queue_result']['entries'][0]['state'] == 'blocked' + assert all('\tsaved_ok\t' not in text for text in original['status_files'].values()) + failure = verify_publish_failure(output) + locked = original['locked_markers'][0] + marker = Path(locked['path']) + assert hashlib.sha256(marker.read_bytes()).hexdigest() == locked['sha256_before'] + assert json.loads(marker.read_bytes())['state'] == 'prepared' + resource = json.loads((marker.parents[3] / 'session.json').read_text(encoding='utf-8')) + assert resource['state'] == 'released' and resource['retries'] == {} + assert not pending_resources(output / 'data') + verification = output / 'readback-only' + verification.mkdir(exist_ok=False) + spec, destination = verification / 'spec.json', verification / 'after.json' + save(spec, {'project': original['project'], 'destination': str(destination)}) + report = {'mode': 'read_only_existing_marker_failure', 'business_replayed': False, + 'source_coverage': True, 'frozen_coverage': False, 'marker_publish_failure': failure} + started = time.monotonic() + try: + with PrivateDesktopObserver(verification) as observer: + with IsolatedCadSession(verification / 'private-cad') as cad: + observer.records[cad.desktop.name] = dict(cad.record) + observer.handles[cad.cad.pid] = win32api.OpenProcess(0x100000, False, cad.cad.pid) + process = cad.start_worker((sys.executable, str(Path(__file__).resolve()), + '--inspect-file', str(spec)), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + code = process.wait(timeout=240) + (verification / 'worker-output.txt').write_bytes(process.stdout.read() + b'\n' + process.stderr.read()) + assert code == 0, (verification / 'worker-output.txt').read_text(errors='replace') + finally: + process.close() + before = json.loads((output / 'before.json').read_text(encoding='utf-8')) + after = json.loads(destination.read_text(encoding='utf-8')) + assert before == after, 'complete schematic attributes/pins changed' + observation = json.loads((verification / 'desktop-observation.json').read_text(encoding='utf-8')) + assert not observation['observer_errors'] + assert all(observation['cad_exit_confirmed'].values()) and all(observation['desktop_absent'].values()) + assert not observation['owned_cad_became_foreground'] and not observation['owned_cad_on_input_desktop'] + assert observation['input_desktop_before'] == observation['input_desktop_after'] + assert hashes(Path(original['source'])) == original['source_files_before'] + assert hashlib.sha256(Path(original['library']).read_bytes()).hexdigest() == original['library_sha256'] + assert hashlib.sha256(marker.read_bytes()).hexdigest() == locked['sha256_before'] + report.update(verified=True, graph_identical=True, components=len(before), + pins=sum(len(row['pins']) for row in before.values()), + sheets=sorted({(row['schematic'], row['sheet']) for row in before.values()}), + target=[row for row in after.values() if row['refdes'] == 'RV05'], + marker_unchanged=True, resources_released=True, source_unchanged=True, library_unchanged=True) + finally: + from dx_productivity.trial_task_center.legacy_paths import cleanup_worker_aliases + report['alias_cleanup_errors'] = list(map(str, cleanup_worker_aliases())) + report['elapsed_seconds'] = time.monotonic() - started + save(verification / 'verification.json', report) + print(json.dumps(report, ensure_ascii=False), flush=True) + return 0 if report.get('verified') and not report['alias_cleanup_errors'] else 1 + + +def run(source, library, base): + from dx_productivity.trial_task_center.batch_resources import pending_resources + from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime + from dx_productivity.trial_task_center.bom_plan import write_bom_template + from dx_productivity.trial_task_center.isolated_cad import IsolatedCadSession + from dx_productivity.trial_task_center.logging_setup import configure_logging + from dx_productivity.trial_task_center.path_access import internal_path + from dx_productivity.trial_task_center.service import TaskCenterService + from dx_productivity.trial_task_center.store import TaskStore + from dx_productivity.trial_task_center.task_queue import execute_task_queue + from private_desktop_observer import PrivateDesktopObserver + import win32con + import win32file + + source, library = source.resolve(strict=True), library.resolve(strict=True) + output = base.resolve() / ('run-' + uuid4().hex) + assert output.is_relative_to(REPO / 'build' / 'issue-3-marker-failure') + output.mkdir(parents=True, exist_ok=False) + source_before, library_before = hashes(source), hashlib.sha256(library.read_bytes()).hexdigest() + folder = output / 'projects' / source.name + shutil.copytree(source, folder) + project = folder / (source.name + '.prj') + text, count = re.subn(r'(?m)^KEY CentralLibrary .*$', + lambda _: f'KEY CentralLibrary "{library.as_posix()}"', project.read_text(encoding='utf-8-sig')) + assert count == 1 + project.write_text(text, encoding='utf-8') + report = {'mode': 'source_real_cad_marker_publish_failure', 'frozen_coverage': False, + 'source': str(source), 'project': str(project), 'library': str(library), + 'old': '4100-CA0000-T7', 'new': '4100-CA0000-T0', 'refdes': 'RV05', + 'copy_part_number_to_value': False, 'locked_markers': [], 'prepare_calls': 0, + 'steps': [], 'source_files_before': source_before, 'library_sha256': library_before} + save(output / 'source-under-test.json', {'git_head': subprocess.check_output( + ['git', 'rev-parse', 'HEAD'], cwd=REPO, text=True).strip(), + 'sha256': {str(path.relative_to(REPO)): hashlib.sha256(path.read_bytes()).hexdigest() + for folder_name, pattern in (('src', '*.py'), ('integration', '*.vbs')) + for path in (REPO / folder_name).rglob(pattern)}}) + store = TaskStore(output / 'tasks.db') + service = TaskCenterService(store, configure_logging(output / 'data')) + handles = [] + original_prepare = BatchCadRuntime._prepare_attempts + runtime = None + def guarded_prepare(owner, root, command, attempt_id, generation): + result = original_prepare(owner, root, command, attempt_id, generation) + report['prepare_calls'] += 1 + _, directory, expected = result + for path, record in expected: + assert record['state'] == 'prepared' + raw = internal_path(path).read_bytes() + handle = win32file.CreateFile(str(internal_path(path)), win32con.GENERIC_READ, + win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, + win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None) + handles.append(handle) + assert internal_path(path).read_bytes() == raw + report['locked_markers'].append({'path': str(path), 'handle': int(handle), + 'share_read': True, 'share_write': True, 'share_delete': False, + 'sha256_before': hashlib.sha256(raw).hexdigest(), 'prepared': record}) + save(output / 'report.json', report) + return result + def independent(label): + evidence = output / 'independent-read' / 'quick-run-history' / ('sheet-discovery-' + label) + evidence.mkdir(parents=True) + destination, spec = output / (label + '.json'), evidence / 'spec.json' + save(spec, {'project': str(project), 'destination': str(destination)}) + with IsolatedCadSession(evidence) as cad: + process = cad.start_worker((sys.executable, str(Path(__file__).resolve()), + '--inspect-file', str(spec)), stdout=subprocess.PIPE, stderr=subprocess.PIPE) + try: + code = process.wait(timeout=240) + (evidence / 'worker-output.txt').write_bytes(process.stdout.read() + b'\n' + process.stderr.read()) + assert code == 0, (evidence / 'worker-output.txt').read_text(errors='replace') + finally: + process.close() + return json.loads(destination.read_text(encoding='utf-8')) + started = time.monotonic() + try: + with PrivateDesktopObserver(output): + print('Independent full-project BEFORE read', flush=True) + before = independent('before') + assert [row['part_number'] for row in before.values() if row['refdes'] == 'RV05'] == [report['old']] + tasks = service.create_project_tasks(output / 'projects', selected_paths=(project,)) + assert len(tasks) == 1 + bom = write_bom_template(output / 'input.xlsx', ({'project_path': str(project), + 'old_part_number': report['old'], 'new_part_number': report['new'], + 'refdes': 'RV05', 'enabled': True, 'sync_nc': True},)) + imported = service.inspect_bom_batch(tasks[0].task_id, bom, + on_progress=lambda message: print(message, flush=True)) + assert imported.passed_rows == 1 and imported.preview is not None + service.save_bom_batch(imported.preview, {item.task_id: item.rows for item in imported.preview.projects}) + print('Production queue with real deny-delete prepared marker handle', flush=True) + BatchCadRuntime._prepare_attempts = guarded_prepare + runtime = BatchCadRuntime(output / 'data', 'marker_write_failure') + try: + with runtime: + result = execute_task_queue(service, (tasks[0].task_id,), stop_event=Event(), runtime=runtime) + runtime.result = result + report['queue_result'] = asdict(result) + finally: + BatchCadRuntime._prepare_attempts = original_prepare + for handle in handles: + handle.Close() + handles.clear() + assert report['prepare_calls'] == 1 and len(report['locked_markers']) == 1 + assert all(entry.state != 'completed' for entry in result.entries) + for locked in report['locked_markers']: + raw = internal_path(locked['path']).read_bytes() + locked['sha256_after'] = hashlib.sha256(raw).hexdigest() + assert locked['sha256_after'] == locked['sha256_before'] + assert json.loads(raw)['state'] == 'prepared' + statuses = {str(path.relative_to(output)): path.read_text(encoding='utf-8-sig') + for path in (output / 'data').rglob('status.tsv')} + report['status_files'] = statuses + assert statuses and not any('\tsaved_ok\t' in text for text in statuses.values()) + report['marker_publish_failure'] = verify_publish_failure(output) + assert not pending_resources(output / 'data') + report['resource_record'] = json.loads(runtime.path.read_text(encoding='utf-8')) + assert report['resource_record']['state'] == 'released' + assert report['resource_record']['retries'] == {} + report['business_execution_attempts'] = report['prepare_calls'] + print('Independent full-project AFTER read', flush=True) + after = independent('after') + assert before == after, 'full component attributes or pin connectivity changed' + report['graph_comparison'] = {'identical': True, 'components': len(before), + 'sheets': sorted({(row['schematic'], row['sheet']) for row in before.values()}), + 'pins': sum(len(row['pins']) for row in before.values()), + 'all_component_attributes_positions_and_pin_connections_compared': True} + observation = json.loads((output / 'desktop-observation.json').read_text(encoding='utf-8')) + assert not observation['observer_errors'] + assert observation['input_desktop_before'] == observation['input_desktop_after'] + assert not observation['owned_cad_became_foreground'] and not observation['owned_cad_on_input_desktop'] + assert all(observation['cad_exit_confirmed'].values()) and all(observation['desktop_absent'].values()) + report['verified'] = True + except BaseException as failure: + report.update(verified=False, error=repr(failure), traceback=traceback.format_exc()) + traceback.print_exc() + finally: + BatchCadRuntime._prepare_attempts = original_prepare + for handle in handles: + handle.Close() + if runtime is not None: + try: + runtime.close(reason='probe_finally') + except Exception as failure: + report['final_cleanup_error'] = repr(failure) + store.close() + from dx_productivity.trial_task_center.legacy_paths import cleanup_worker_aliases + report['alias_cleanup_errors'] = list(map(str, cleanup_worker_aliases())) + report['source_unchanged'] = hashes(source) == source_before + report['library_unchanged'] = hashlib.sha256(library.read_bytes()).hexdigest() == library_before + report['elapsed_seconds'] = time.monotonic() - started + save(output / 'report.json', report) + print(json.dumps({'output': str(output), **{key: report.get(key) for key in + ('verified', 'error', 'source_unchanged', 'library_unchanged', 'graph_comparison', 'elapsed_seconds')}}, + ensure_ascii=False), flush=True) + return 0 if (report.get('verified') and report['source_unchanged'] and report['library_unchanged'] + and not report['alias_cleanup_errors'] and not report.get('final_cleanup_error')) else 1 + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--inspect-file', type=Path) + parser.add_argument('--verify-existing', type=Path, help='Read back only; no queue or business execution') + parser.add_argument('--source', type=Path) + parser.add_argument('--library', type=Path) + parser.add_argument('--output', type=Path, default=REPO / 'build/issue-3-marker-failure') + args = parser.parse_args() + if args.inspect_file: + read_all_sheets(args.inspect_file) + elif args.verify_existing: + raise SystemExit(verify_existing(args.verify_existing)) + else: + assert args.source and args.library + raise SystemExit(run(args.source, args.library, args.output))