Add live CAD marker publication failure acceptance evidence

This commit is contained in:
阿白叔 committed 2026-10-23 16:22:05 +08:00
1 parent f3d7423d02
commit 01d1b54caa
2 files changed
+354

No files matched your search

+310
View File
@@ -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))