fix: cancel inventory reads safely and compare canonical discovery content

This commit is contained in:
阿白叔 committed 2026-10-15 16:40:35 +08:00
1 parent 0f0d6a7103
commit a1f924295c
9 files changed
+287 -25

No files matched your search

+1
View File
@@ -17,3 +17,4 @@ __pycache__/
.coverage
coverage.xml
/.worktrees/
/.superpowers/
@@ -15,9 +15,10 @@ import stat
from threading import RLock
from .errors import TaskCenterError
from .operation_control import check_cancelled
def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
def project_fingerprint(project: Path, excluded_root: Path, *, stop_event=None) -> tuple | None:
try:
project = Path(project).absolute()
root = project.parent
@@ -31,6 +32,7 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
def fail(error):
raise error
for current, dirs, files in os.walk(root, onerror=fail, followlinks=False):
check_cancelled(stop_event)
current = Path(current)
kept = []
for name in sorted(dirs):
@@ -47,6 +49,7 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
kept.append(name)
dirs[:] = kept
for name in sorted(files):
check_cancelled(stop_event)
path = current / name
relative = tuple(part.casefold() for part in path.relative_to(root).parts)
if path.suffix.casefold() == '.log' or relative == ('log files', 'projectbackuplog.txt'):
@@ -62,7 +65,14 @@ def project_fingerprint(project: Path, excluded_root: Path) -> tuple | None:
# each source's full stamp against itself after hashing.
if handle_before[:4] != before[:4]:
return None
digest = hashlib.file_digest(stream, 'sha256').digest()
if stop_event is None:
digest = hashlib.file_digest(stream, 'sha256').digest()
else:
digestor = hashlib.sha256()
while chunk := stream.read(1024 * 1024):
check_cancelled(stop_event)
digestor.update(chunk)
digest = digestor.digest()
if _file_stamp(os.fstat(stream.fileno())) != handle_before:
return None
# Check the path as well as the handle: atomic replacement can
@@ -99,6 +109,16 @@ def _only_database_changed(before, after):
return design is not None and before != after and design == _without_runtime_database(after)
def _discovery_identity(discovery):
sheets = discovery.sheets
components = getattr(discovery, 'components', ())
if len(set(sheets)) != len(sheets) or len({row.key for row in components}) != len(components):
raise TaskCenterError('target_identity', '原生采集返回重复图页或位号身份,请核对工程')
return (tuple(sorted(sheets)),
tuple(sorted((sheet, tuple(sorted(parts))) for sheet, parts in discovery.matched_old_parts.items())),
tuple(sorted((row.key, row.refdes, row.old_part_number, row.old_value) for row in components)))
class DiscoveryCache:
"""One preparer owns one cache; the lock also serializes cache discovery."""
def __init__(self, data_root: Path, capacity: int = 32):
@@ -111,22 +131,30 @@ class DiscoveryCache:
with self.lock:
self._entries.pop(_key(project), None)
def discover(self, project, parts, collect_components, loader):
def discover(self, project, parts, collect_components, loader, *, stop_event=None):
with self.lock:
check_cancelled(stop_event)
def fingerprint():
check_cancelled(stop_event)
return project_fingerprint(project, self.data_root, **({'stop_event': stop_event} if stop_event is not None else {}))
key = _key(project)
requested = frozenset(part.casefold() for part in parts)
before = project_fingerprint(project, self.data_root)
before = fingerprint()
entry = self._entries.pop(key, None)
if entry is not None:
stamp, covered, has_components, discovery = entry
if (before is not None and before == stamp and requested <= covered
and (not collect_components or has_components)):
self._entries[key] = entry
check_cancelled(stop_event)
return deepcopy(discovery)
# Fingerprinting is an optimization: an initially unverifiable
# project still gets fresh native discovery, with no cache reuse.
if before is None:
return loader()
discovery = loader()
check_cancelled(stop_event)
_discovery_identity(discovery)
return discovery
# Native opens may update database session metadata on every read.
# Accept that case only after two equal native results while every
# other design file stays stable across both passes. The complete
@@ -136,20 +164,23 @@ class DiscoveryCache:
attempt, limit = 0, 2
while attempt < limit:
if attempt:
before = project_fingerprint(project, self.data_root)
before = fingerprint()
check_cancelled(stop_event)
discovery = loader()
after = project_fingerprint(project, self.data_root)
check_cancelled(stop_event)
identity = _discovery_identity(discovery)
after = fingerprint()
if before is not None and before == after:
break
if _only_database_changed(before, after):
design = _without_runtime_database(after)
if previous is not None and previous == discovery and previous_design == design:
if previous is not None and previous == identity and previous_design == design:
break
# First-open normalization can precede the two stable
# inventory reads. Allow one extra pass only in that case.
if attempt == 1 and previous is None:
limit = 3
previous, previous_design = deepcopy(discovery), design
previous, previous_design = identity, design
else:
previous = previous_design = None
attempt += 1
@@ -159,6 +190,7 @@ class DiscoveryCache:
# Refuse incomplete inventories and bound both projects and row count.
sheets = getattr(discovery, 'sheets', ())
matches = getattr(discovery, 'matched_old_parts', {})
check_cancelled(stop_event)
if (after is not None and sheets
and set(sheets) == set(matches)
and (len(getattr(discovery, 'components', ())) + len(sheets)
@@ -41,7 +41,11 @@ def read_component_inventory(path: Path, project_path: Path,
def collect_target_inventory(preparer, project_path: Path,
old_part_numbers: tuple[str, ...]) -> tuple[ComponentTarget, ...]:
old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None) -> tuple[ComponentTarget, ...]:
if not old_part_numbers:
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
return preparer.collect_inventory(project_path, old_part_numbers)
from .operation_control import check_cancelled, control_options
check_cancelled(stop_event)
rows = preparer.collect_inventory(project_path, old_part_numbers, **control_options(stop_event, on_progress))
check_cancelled(stop_event)
return rows
@@ -175,11 +175,12 @@ class IsolatedCadSession:
self._record(state='uncertain', error=message)
def run_isolated_process(command, timeout, *, abort_event=None):
def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abort=False):
from .worker_monitor import run_monitored_process
try:
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker)
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker,
**({'cooperative_abort': True} if cooperative_abort else {}))
except PrivateCadStartupError as error:
# The existing handoff recognizes exit=2 with unchanged status as a
# retryable pre-mutation startup failure, without an uncertainty lock.
@@ -0,0 +1,16 @@
"""Cooperative read-only operation control, independent of Qt and CAD."""
from .errors import TaskCenterError
def check_cancelled(stop_event):
if stop_event is not None and stop_event.is_set():
raise TaskCenterError('operation_cancelled', '已取消采集;当前私有 CAD 会话已安全收尾,未保存部分计划。')
def control_options(stop_event=None, on_progress=None):
return {key: value for key, value in (('stop_event', stop_event), ('on_progress', on_progress)) if value is not None}
def report_progress(on_progress, message):
if on_progress is not None:
on_progress(message)
@@ -10,6 +10,7 @@ from uuid import uuid4
from .errors import TaskCenterError
from .quick_run_protocol import ProjectDiscovery, _encode_vbs_field
from .operation_control import check_cancelled, report_progress
@dataclass(frozen=True, slots=True)
@@ -33,8 +34,11 @@ def discover_project(
script_source: Path,
runtime: DiscoveryRuntime,
collect_components: bool = False,
stop_event=None,
on_progress=None,
) -> ProjectDiscovery:
"""Enumerate sheets and requested source parts while the owned project is open."""
check_cancelled(stop_event)
project = project_path.resolve(strict=True)
token = uuid4().hex
job_id = "discover_" + token
@@ -74,12 +78,19 @@ def discover_project(
job_id,
)
try:
report_progress(on_progress, f'正在启动工程读取会话:{project.name}')
check_cancelled(stop_event)
completed = runtime.process_runner(command, runtime.timeout)
except (OSError, subprocess.SubprocessError) as error:
_require_released_reader(root)
check_cancelled(stop_event)
raise TaskCenterError(
"quick_run_sheet_discovery",
f"枚举工程图页时执行器未能安全结束:{project};{error}",
) from error
_require_released_reader(root)
check_cancelled(stop_event)
report_progress(on_progress, f'读取会话已结束,正在核对位号清单:{project.name}')
(root / "worker-output.txt").write_text(completed.stdout + "\n" + completed.stderr, encoding="utf-8")
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip() or "sheet discovery failed"
@@ -91,5 +102,11 @@ def discover_project(
components = read_component_inventory(root / "components.tsv", project, sheets)
else:
components = ()
check_cancelled(stop_event)
return ProjectDiscovery(sheets, matches, components)
def _require_released_reader(root):
if (root / 'uncertain.flag').exists():
raise TaskCenterError('inventory_cleanup', f'采集会话未能正常收尾,请检查诊断记录后重试:{root}')
@@ -668,22 +668,33 @@ class QuickRunPreparer:
self._discovery_cache.invalidate(project_path)
def discover_project(self, project_path: Path, old_part_numbers: tuple[str, ...], *,
collect_components: bool = False) -> ProjectDiscovery:
collect_components: bool = False, stop_event=None, on_progress=None) -> ProjectDiscovery:
from .operation_control import check_cancelled, control_options, report_progress
check_cancelled(stop_event)
controls = control_options(stop_event, on_progress)
attempt = 0
def load():
nonlocal attempt
attempt += 1
check_cancelled(stop_event)
report_progress(on_progress, f'正在读取工程 {project_path.name}(第 {attempt} 次核对),请等待当前会话安全收尾…')
check_cancelled(stop_event)
if collect_components:
return self._discover_project_sheets(project_path, old_part_numbers,
collect_components=True)
return self._discover_project_sheets(project_path, old_part_numbers)
collect_components=True, **controls)
return self._discover_project_sheets(project_path, old_part_numbers, **controls)
return self._discovery_cache.discover(
Path(project_path), old_part_numbers, collect_components, load)
Path(project_path), old_part_numbers, collect_components, load,
**({'stop_event': stop_event} if stop_event is not None else {}))
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...]) -> tuple:
def collect_inventory(self, project_path: Path, old_part_numbers: tuple[str, ...], *, stop_event=None, on_progress=None) -> tuple:
"""Collect validated component targets, retaining reusable sheet evidence."""
if not old_part_numbers:
raise TaskCenterError("target_inventory", "at least one old Part Number is required")
requested = {part.casefold() for part in old_part_numbers}
from .operation_control import control_options
return tuple(component for component in self.discover_project(
project_path, old_part_numbers, collect_components=True).components
project_path, old_part_numbers, collect_components=True, **control_options(stop_event, on_progress)).components
if component.old_part_number.casefold() in requested)
def _discover_project_sheets(
@@ -692,15 +703,24 @@ class QuickRunPreparer:
old_part_numbers: tuple[str, ...],
*,
collect_components: bool = False,
stop_event=None,
on_progress=None,
) -> _ProjectDiscovery:
"""Enumerate sheets and requested source parts while the owned project is open."""
from .project_discovery import DiscoveryRuntime, discover_project
from .operation_control import control_options
process_runner = self._process_runner
if stop_event is not None and process_runner is _run_process:
def process_runner(command, timeout):
return _run_process(command, timeout, abort_event=stop_event)
return discover_project(project_path, old_part_numbers,
data_root=self._data_root, script_source=self._required_script_source(),
collect_components=collect_components,
**control_options(stop_event, on_progress),
runtime=DiscoveryRuntime(
self._process_runner, self._cscript_resolver, _vbs_worker_paths,
process_runner, self._cscript_resolver, _vbs_worker_paths,
_native_helper_launch_arguments, _session_failure_message,
_read_discovered_sheets, _read_discovery_inventory,
IDLE_PROGRESS_TIMEOUT_SECONDS))
@@ -1070,7 +1090,7 @@ def _queue_has_mutation_evidence(root: Path) -> bool:
report = json.loads(report_path.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError):
return True
if report.get("ok") is True or report.get("stage") in {"native_replace_started", "native_replace_verified"}:
if report.get("ok") is True or report.get("stage") in {"native_replace_started", "native_replace_applied", "pin_promotion_started", "native_replace_verified"}:
return True
return False
@@ -1685,10 +1705,11 @@ def _cached_native_helper_launch_arguments(frozen: bool, executable: str) -> tup
return (resolved_executable, str(Path(__file__).with_name("application.py")))
def _run_process(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
def _run_process(command: tuple[str, ...], timeout: int, *, abort_event=None) -> subprocess.CompletedProcess[str]:
from .isolated_cad import run_isolated_process
return run_isolated_process(command, timeout)
return run_isolated_process(command, timeout,
**({'abort_event': abort_event, 'cooperative_abort': True} if abort_event is not None else {}))
def _log_text(value: str) -> str:
@@ -158,7 +158,7 @@ class _OwnedWorkers:
def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abort_event=None,
process_factory=None) -> subprocess.CompletedProcess[str]:
process_factory=None, cooperative_abort=False) -> subprocess.CompletedProcess[str]:
root = Path(command[3]).resolve()
job_id = command[-1]
token = uuid4().hex
@@ -212,7 +212,15 @@ def run_monitored_process(command: tuple[str, ...], idle_timeout: float, *, abor
_atomic_text(ready, token)
while process.poll() is None:
if abort_event is not None and abort_event.is_set():
raise WorkerMonitorError('project session supervisor requested worker cleanup')
if not cooperative_abort:
raise WorkerMonitorError('project session supervisor requested worker cleanup')
if not watch.stop_requested:
# Read-only callers request the VBS safe boundary first.
# The existing idle watchdog still bounds a stalled COM call.
watch.stop_requested = True
watch.last_progress = time.monotonic()
_atomic_text(stop, token)
_publish_progress(progress_path, watch.snapshot())
try:
receive(*messages.get(timeout=min(0.1, idle_timeout / 10)))
for pending in range(128):
+162
View File
@@ -0,0 +1,162 @@
from dataclasses import replace
from pathlib import Path
from subprocess import CompletedProcess
from threading import Event
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _ProjectDiscovery, _queue_has_mutation_evidence
from dx_productivity.trial_task_center.target_plan import ComponentTarget
def project_fixture(tmp_path):
project = tmp_path / 'project' / 'board.prj'
project.parent.mkdir()
project.write_text('project')
database = project.parent / 'database' / 'icdb.dat'
database.parent.mkdir()
database.write_text('session 0')
rows = tuple(ComponentTarget(project, 'MAIN', str(i), f'u{i}', f'R{i}', 'OLD', 'V') for i in (1, 2))
preparer = QuickRunPreparer(tmp_path / 'data')
return project, database, rows, preparer
def test_two_native_reads_ignore_component_and_sheet_enumeration_order(tmp_path):
project, database, rows, preparer = project_fixture(tmp_path)
calls = []
def loader(*args, **kwargs):
calls.append(1)
database.write_text(f'session {len(calls)}')
ordered = rows if len(calls) % 2 else rows[::-1]
sheets = tuple((r.schematic_name, r.sheet_number) for r in ordered)
return _ProjectDiscovery(sheets, {s: frozenset({'old'}) for s in sheets}, ordered)
preparer._discover_project_sheets = loader
assert {r.uid for r in preparer.collect_inventory(project, ('OLD',))} == {'u1', 'u2'}
assert len(calls) == 2
preparer.collect_inventory(project, ('OLD',))
assert len(calls) == 2
@pytest.mark.parametrize('change', ['value', 'duplicate', 'missing', 'refdes'])
def test_native_comparison_rejects_actual_content_changes(tmp_path, change):
project, database, rows, preparer = project_fixture(tmp_path)
calls = []
def loader(*args, **kwargs):
calls.append(1)
database.write_text(f'session {len(calls)}')
altered = rows
if len(calls) > 1:
if change == 'value':
altered = (replace(rows[0], old_value='changed'), rows[1])
elif change == 'refdes':
altered = (replace(rows[0], refdes='R99'), rows[1])
elif change == 'duplicate':
altered = rows + (rows[0],)
else:
altered = rows[1:]
sheets = (('MAIN', '1'), ('MAIN', '2'))
return _ProjectDiscovery(sheets, {s: frozenset({'old'}) for s in sheets}, altered)
preparer._discover_project_sheets = loader
with pytest.raises(TaskCenterError):
preparer.collect_inventory(project, ('OLD',))
def test_cancel_after_reader_returns_prevents_cache_and_next_read(tmp_path):
project, database, rows, preparer = project_fixture(tmp_path)
stop = Event()
calls = []
def loader(*args, **kwargs):
calls.append(kwargs)
assert kwargs['stop_event'] is stop
stop.set()
return _ProjectDiscovery((('MAIN', '1'),), {('MAIN', '1'): frozenset({'old'})}, rows[:1])
preparer._discover_project_sheets = loader
with pytest.raises(TaskCenterError) as cancelled:
preparer.collect_inventory(project, ('OLD',), stop_event=stop)
assert cancelled.value.code == 'operation_cancelled'
assert len(calls) == 1 and not preparer._discovery_cache._entries
with pytest.raises(TaskCenterError):
preparer.collect_inventory(project, ('OLD',), stop_event=stop)
assert len(calls) == 1
def test_default_discovery_forwards_abort_to_private_runner_and_waits_cleanup(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import isolated_cad, quick_run
project, _, _, preparer = project_fixture(tmp_path)
source = tmp_path / 'runtime.vbs'
source.write_text('runtime')
stop = Event()
cleanup = []
def run(command, timeout, *, abort_event=None, cooperative_abort=False):
assert abort_event is stop
assert cooperative_abort
stop.set()
cleanup.append('released')
return CompletedProcess(command, 2, '', 'cancelled')
monkeypatch.setattr(isolated_cad, 'run_isolated_process', run)
monkeypatch.setattr(quick_run, '_native_helper_launch_arguments', lambda: ())
preparer = QuickRunPreparer(tmp_path / 'data', script_source=source,
cscript_resolver=lambda: Path('cscript.exe'))
messages = []
with pytest.raises(TaskCenterError) as cancelled:
preparer.collect_inventory(project, ('OLD',), stop_event=stop, on_progress=messages.append)
assert cancelled.value.code == 'operation_cancelled'
assert cleanup == ['released'] and messages
assert not preparer._discovery_cache._entries
def test_cancel_does_not_hide_native_cleanup_failure(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import isolated_cad, quick_run
project, _, _, _ = project_fixture(tmp_path)
source = tmp_path / 'runtime.vbs'
source.write_text('runtime')
stop = Event()
def run(command, timeout, **controls):
stop.set()
root = Path(command[3]).resolve()
(root / 'uncertain.flag').write_text('owned CAD did not quit')
raise OSError('cleanup failure')
monkeypatch.setattr(isolated_cad, 'run_isolated_process', run)
monkeypatch.setattr(quick_run, '_native_helper_launch_arguments', lambda: ())
preparer = QuickRunPreparer(tmp_path / 'data', script_source=source,
cscript_resolver=lambda: Path('cscript.exe'))
with pytest.raises(TaskCenterError) as error:
preparer.collect_inventory(project, ('OLD',), stop_event=stop)
assert error.value.code == 'inventory_cleanup'
def test_read_cancellation_requests_cooperative_stop_in_real_child_process(tmp_path):
import json
import sys
from threading import Timer
from dx_productivity.trial_task_center.worker_monitor import run_monitored_process
script = tmp_path / 'reader.py'
script.write_text('''import pathlib,sys,time
root=pathlib.Path(sys.argv[1])
token=sys.argv[-1]
stop=root / f'monitor-{token}.stop'
ready=root / f'monitor-{token}.ready'
while not ready.exists(): time.sleep(.01)
while not stop.exists(): time.sleep(.01)
(root / 'cooperatively-closed.txt').write_text('closed')
print('safe read cleanup finished', flush=True)
''')
stop = Event()
timer = Timer(.2, stop.set)
timer.start()
try:
result = run_monitored_process((sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job'),
2, abort_event=stop, cooperative_abort=True)
finally:
timer.join()
assert result.returncode == 0
assert (tmp_path / 'cooperatively-closed.txt').read_text() == 'closed'
assert json.loads((tmp_path / 'worker-progress.json').read_text())['stop_requested']
@pytest.mark.parametrize('stage', ['native_replace_applied', 'pin_promotion_started'])
def test_mutation_evidence_keeps_recovery_for_later_native_stages(tmp_path, stage):
import json
(tmp_path / 'snapshot-job.tsv.native.json').write_text(json.dumps({'ok': False, 'stage': stage}))
assert _queue_has_mutation_evidence(tmp_path)