fix: recover uncertain native failures and reopen long project paths safely
This commit is contained in:
1 parent
7f0ec29d31
commit
d832a1c736
15 files changed
+355
-36
No files matched your search
@@ -591,6 +591,7 @@ End Function
|
||||
Sub QPEnsureProject(ByRef App, ByVal TargetPath)
|
||||
Dim ProjectData, CurrentPath, Opened, View, Documents
|
||||
Dim Schematics, Schematic, Sheets, Sheet, SheetCount, OnlySchematic, OnlySheet, Document
|
||||
TargetPath = QPProjectAccessPath(TargetPath)
|
||||
If Not QP_Fso.FileExists(TargetPath) Then _
|
||||
Err.Raise vbObjectError + 850, "QuickPartReplace.Session", "confirmed project file does not exist: " & TargetPath
|
||||
QP_Stage = "check_project"
|
||||
@@ -1002,6 +1003,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
QP_NativeCallActive = True
|
||||
QPProgress "native_replace", 0, 1
|
||||
ExitCode = Shell.Run(CommandLine, 0, True)
|
||||
QPLog QP_Root, "INFO", "native_helper_exit code=" & CStr(ExitCode)
|
||||
QP_NativeMutationPossible = QPNativeReportShowsMutation(SnapshotPath & ".native.json")
|
||||
QP_NativeCallActive = False
|
||||
QPInvalidatePinIndex
|
||||
@@ -1016,7 +1018,7 @@ Sub QPNativeReplace(ByRef Command, ByVal SnapshotPath)
|
||||
"; report: " & SnapshotPath & ".native.json"
|
||||
Else
|
||||
Err.Raise vbObjectError + 839, "QuickPartReplace", _
|
||||
"automatic native replacement failed; see " & SnapshotPath & ".native.json"
|
||||
"automatic native replacement failed (exit=" & CStr(ExitCode) & "); see " & SnapshotPath & ".native.json"
|
||||
End If
|
||||
End If
|
||||
End Sub
|
||||
|
||||
@@ -25,22 +25,26 @@ def batch_rule_view(store, task_id, *, strict=False):
|
||||
task = store.get_task(task_id)
|
||||
if task.status is TaskStatus.DELETED or not task.group_id:
|
||||
return store.list_rules(task_id)
|
||||
seen, result = {}, []
|
||||
local = {r.old_part_number.casefold(): r for r in store.list_rules(task_id)}
|
||||
for item in tasks:
|
||||
for rule in store.list_rules(item.task_id):
|
||||
key = rule.old_part_number.casefold()
|
||||
if key in seen and seen[key] != _signature(rule):
|
||||
if strict:
|
||||
raise TaskCenterError('batch_rules_conflict', f'同批料号规则不一致:{rule.old_part_number},请编辑该规则统一默认值')
|
||||
result.append(rule)
|
||||
elif key not in seen:
|
||||
seen[key] = _signature(rule)
|
||||
preferred = local.get(key)
|
||||
result.append(preferred if preferred and _signature(preferred) == _signature(rule) else rule)
|
||||
if strict:
|
||||
validate_mapping_pairs((r.old_part_number, r.new_part_number) for r in result if r.enabled)
|
||||
return tuple(result)
|
||||
return merge_rule_view((rule for item in tasks for rule in store.list_rules(item.task_id)), local, strict=strict)
|
||||
|
||||
|
||||
def merge_rule_view(rules, local, *, strict=False):
|
||||
"""Merge already captured rows without reading a newer database generation."""
|
||||
seen, result = {}, []
|
||||
for rule in rules:
|
||||
key = rule.old_part_number.casefold()
|
||||
if key in seen and seen[key] != _signature(rule):
|
||||
if strict:
|
||||
raise TaskCenterError('batch_rules_conflict', f'同批料号规则不一致:{rule.old_part_number},请编辑该规则统一默认值')
|
||||
result.append(rule)
|
||||
elif key not in seen:
|
||||
seen[key] = _signature(rule)
|
||||
preferred = local.get(key)
|
||||
result.append(preferred if preferred and _signature(preferred) == _signature(rule) else rule)
|
||||
if strict:
|
||||
validate_mapping_pairs((r.old_part_number, r.new_part_number) for r in result if r.enabled)
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _options(rule):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Native current-sheet replacement adapter for the existing QuickPartReplace runner."""
|
||||
import argparse
|
||||
import faulthandler
|
||||
import ctypes
|
||||
import hashlib
|
||||
import json
|
||||
@@ -333,14 +334,21 @@ def existing_replacement_uids(components, records, target, binding, require_part
|
||||
return matches
|
||||
|
||||
|
||||
def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
|
||||
def promote_pin_numbers(app, api, replacement_uids, slot_count=1, on_progress=None):
|
||||
def progress(phase):
|
||||
if on_progress:
|
||||
on_progress(phase)
|
||||
progress('query_components')
|
||||
components = components_on_sheet(app, api)
|
||||
replacement_uids = set(replacement_uids)
|
||||
try:
|
||||
progress('select_replacements')
|
||||
for component in components:
|
||||
selection(component, str(component.UID) in replacement_uids)
|
||||
for slot in range(1, int(slot_count) + 1):
|
||||
progress(f'promote_slot_{slot}')
|
||||
app.ActiveView.Block.PromoteSymbolNumbers(1, slot)
|
||||
progress('query_promoted_pins')
|
||||
promoted = []
|
||||
for item in app.ActiveView.Query(4096, 0):
|
||||
pin = api.IVdCmpPin(item._oleobj_)
|
||||
@@ -352,8 +360,15 @@ def promote_pin_numbers(app, api, replacement_uids, slot_count=1):
|
||||
raise ValueError("Replacement produced no pins")
|
||||
return promoted
|
||||
finally:
|
||||
progress('deselect_components')
|
||||
for component in components:
|
||||
selection(component, False)
|
||||
progress('promotion_complete')
|
||||
|
||||
|
||||
def _promotion_phase(snapshot, report, phase):
|
||||
report['pin_promotion_phase'] = phase
|
||||
save_report(snapshot, report)
|
||||
|
||||
|
||||
def replacement_matches(components, records, target, require_part_label):
|
||||
@@ -420,7 +435,8 @@ def run_native(snapshot, report):
|
||||
slot_count = int(binding.get("slot_count", report.get("slot_count", 1)))
|
||||
if slot_count < 1:
|
||||
raise ValueError("Recorded replacement has no valid slots")
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count,
|
||||
lambda phase: _promotion_phase(snapshot, report, phase))
|
||||
report["already_replaced"] = True
|
||||
report["stage"] = "native_replace_verified"
|
||||
return
|
||||
@@ -617,7 +633,8 @@ def run_native(snapshot, report):
|
||||
save_report(snapshot, report)
|
||||
report["stage"] = "pin_promotion_started"
|
||||
save_report(snapshot, report)
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count)
|
||||
report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count,
|
||||
lambda phase: _promotion_phase(snapshot, report, phase))
|
||||
report["stage"] = "native_replace_verified"
|
||||
finally:
|
||||
if dialog and win32gui.IsWindow(dialog):
|
||||
@@ -644,13 +661,23 @@ def atomic_text(path, text):
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
break
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def run(snapshot):
|
||||
snapshot = Path(snapshot)
|
||||
fault_stream = Path(str(snapshot) + '.native.fault.txt').open('a', encoding='utf-8')
|
||||
faulthandler.enable(file=fault_stream, all_threads=True)
|
||||
report_path = Path(str(snapshot) + ".native.json")
|
||||
report = {}
|
||||
if report_path.is_file():
|
||||
@@ -681,7 +708,15 @@ def run(snapshot):
|
||||
return 1
|
||||
finally:
|
||||
watchdog.cancel()
|
||||
save_report(snapshot, report)
|
||||
try:
|
||||
save_report(snapshot, report)
|
||||
except Exception:
|
||||
traceback.print_exc(file=fault_stream)
|
||||
fault_stream.flush()
|
||||
raise
|
||||
finally:
|
||||
faulthandler.disable()
|
||||
fault_stream.close()
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
|
||||
@@ -14,6 +14,7 @@ import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from typing import Protocol
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -489,6 +490,12 @@ class QuickRunPreparer:
|
||||
_write_uncertain_flag(uncertain_path, "worker_exited_before_native_completion")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain worker_exited_before_native_completion")
|
||||
raise TaskCenterError("quick_run_uncertain", "执行器已退出,但未返回替换收尾结果;请核验恢复,不要重复替换。")
|
||||
from .quick_run_snapshot import failed_native_result_uncertain
|
||||
if state == BATCH_FAILED_STATE and failed_native_result_uncertain(
|
||||
handoff.command_path.parent, commands, after):
|
||||
_write_uncertain_flag(uncertain_path, "native_batch_failed_after_mutation")
|
||||
_append_log(handoff.log_path, "quick_run_uncertain native_batch_failed_after_mutation")
|
||||
raise TaskCenterError("quick_run_uncertain", "原生修改后未完成核验,队列已停止;请先核验恢复,不要直接重试。")
|
||||
if state == BATCH_SAVED_UNVERIFIED_STATE:
|
||||
_write_uncertain_flag(uncertain_path, "saved_readback_unverified")
|
||||
if state in {BATCH_FAILED_STATE, BATCH_SAVED_UNVERIFIED_STATE} and (not batch_mode or batch_session is None):
|
||||
@@ -934,7 +941,7 @@ def _advance_batch_session(
|
||||
|
||||
|
||||
def _is_saved_result(state: str, code: str) -> bool:
|
||||
return state == "saved_ok" or (state == "restored_ok" and code == "recovery_verified")
|
||||
return state == "saved_ok" or (state == "restored_ok" and code in {"recovery_verified", "recovery_saved_verified"})
|
||||
|
||||
|
||||
def _failure_details(
|
||||
@@ -1605,7 +1612,15 @@ def _write_atomic_queue_text(path: Path, text: str, code: str, message: str) ->
|
||||
handle.write(text)
|
||||
handle.flush()
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(temporary, path)
|
||||
deadline = time.monotonic() + 1.0
|
||||
while True:
|
||||
try:
|
||||
os.replace(temporary, path)
|
||||
break
|
||||
except PermissionError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(.02)
|
||||
except OSError as error:
|
||||
temporary.unlink(missing_ok=True)
|
||||
raise TaskCenterError(code, message) from error
|
||||
|
||||
@@ -1,11 +1,37 @@
|
||||
"""Read-only execution view reconstructed from one cached set of handoff files."""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass, replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from .errors import TaskCenterError
|
||||
from .quick_run_protocol import QuickRunProgress
|
||||
|
||||
|
||||
def failed_native_result_uncertain(root, commands, statuses, *, files=None):
|
||||
"""Closing an unsaved project is not proof that native mutation rolled back."""
|
||||
from . import quick_run as api
|
||||
latest = {job: state for job, state, _, _ in statuses}
|
||||
awaiting = {job for job, state, _, _ in statuses if state == 'awaiting_native_replace'}
|
||||
for _, job, *_ in commands:
|
||||
if latest.get(job) != api.BATCH_FAILED_STATE:
|
||||
continue
|
||||
if api._rollback_marker_verified(root, job):
|
||||
continue
|
||||
path = root / f'snapshot-{job}.tsv.native.json'
|
||||
try:
|
||||
report = json.loads(files.read(path) if files is not None else path.read_text(encoding='utf-8-sig'))
|
||||
except (OSError, UnicodeError, json.JSONDecodeError):
|
||||
if job in awaiting or path.exists():
|
||||
return True
|
||||
continue
|
||||
if not isinstance(report, dict):
|
||||
return True
|
||||
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
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class QuickRunSnapshot:
|
||||
progress: QuickRunProgress
|
||||
@@ -150,6 +176,7 @@ def _read_snapshot_once(preparer, task_id, projects, rules, *, copy_part_number_
|
||||
if root == current:
|
||||
latest = {job_id: state for job_id, state, _, _ in details}
|
||||
interrupted = interrupted or any(state == api.BATCH_SAVED_UNVERIFIED_STATE for state in latest.values())
|
||||
interrupted = interrupted or failed_native_result_uncertain(root, commands, details, files=files)
|
||||
unfinished = api._next_unfinished_command(commands, details)
|
||||
if unfinished is not None:
|
||||
final = latest.get(unfinished[1])
|
||||
|
||||
@@ -34,10 +34,12 @@ def _is_link_or_reparse(path: Path) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _recovery_command(commands, statuses):
|
||||
def _recovery_command(commands, statuses, *, root=None):
|
||||
from .quick_run_snapshot import failed_native_result_uncertain
|
||||
latest = {entry[0]: entry[1] for entry in statuses}
|
||||
unverified = tuple(command for command in commands
|
||||
if latest.get(command[1]) == 'batch_saved_unverified')
|
||||
if latest.get(command[1]) == 'batch_saved_unverified'
|
||||
or (root is not None and failed_native_result_uncertain(root, (command,), statuses)))
|
||||
if len(unverified) > 1:
|
||||
raise TaskCenterError('quick_run_recovery', '多个保存后未核验步骤需要逐项人工核对,保护状态保持。')
|
||||
if unverified:
|
||||
@@ -99,7 +101,7 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise TaskCenterError('quick_run_recovery', '当前工程或规则与中断队列不同,不能恢复其他任务。')
|
||||
if not _value_mode_matches_option(mode, copy_part_number_to_value) or len({command[1] for command in commands}) != len(commands):
|
||||
raise TaskCenterError('quick_run_recovery', 'Value 策略变化或队列编号重复,已停止恢复。')
|
||||
selected = _recovery_command(commands, before)
|
||||
selected = _recovery_command(commands, before, root=root)
|
||||
if selected is None:
|
||||
raise TaskCenterError('quick_run_recovery', '队列记录已完成但仍有保护锁,需要单独核对,未自动解除。')
|
||||
job_id = _safe_run_token(selected[1])
|
||||
|
||||
@@ -243,7 +243,7 @@ class TaskCenterService:
|
||||
legacy = bound is None
|
||||
if not allow_legacy and (task.primary_project_id is None or bound is None or len(projects) != 1):
|
||||
raise TaskCenterError("project_binding", "bound task must own exactly one project")
|
||||
rules, targets = (batch_rule_view(self._store, task_id) if task.group_id else bundle.rules), bundle.targets
|
||||
rules, targets = (bundle.batch_rules if bundle.batch_rules is not None else bundle.rules), bundle.targets
|
||||
facade = self._facade_for_task_record(task)
|
||||
effective_rules = compile_target_rules(tuple(targets)) if task.target_plan_mode else rules
|
||||
snapshot = facade._quick_run_preparer.read_snapshot(task_id, projects, effective_rules,
|
||||
@@ -691,6 +691,8 @@ class TaskCenterService:
|
||||
return delegated.prepare_failed_quick_run(task_id)
|
||||
def prepare_retry() -> QuickRunProgress:
|
||||
task = self._store.get_task(task_id)
|
||||
if self._quick_run_preparer.has_interrupted(task_id):
|
||||
raise TaskCenterError('quick_run_uncertain', '原生替换结果尚未核验,不能归档或重试。请先核验并恢复。')
|
||||
if task.status is not TaskStatus.RUNNING:
|
||||
raise TaskCenterError("quick_run_task_state", "当前任务没有可重试的失败项")
|
||||
progress = self._quick_run_preparer.progress(
|
||||
@@ -821,7 +823,9 @@ class TaskCenterService:
|
||||
if task.status is TaskStatus.DELETED:
|
||||
raise TaskCenterError("quick_run_recovery", "请先恢复已删除的任务记录,再核验其中断步骤。")
|
||||
projects = self._store.list_projects(task_id)
|
||||
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} for project in projects):
|
||||
if any(project.selected and project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED}
|
||||
and not (project.status is ProjectStatus.FAILED
|
||||
and project.summary.startswith('quick_run_result:')) for project in projects):
|
||||
raise TaskCenterError("quick_run_recovery", "工程包含手动执行阶段或失败记录,不能混用自动队列恢复。")
|
||||
result = recover(self._quick_run_preparer, task_id, projects,
|
||||
self._execution_rules(task_id), copy_part_number_to_value=task.copy_part_number_to_value,
|
||||
|
||||
@@ -438,10 +438,13 @@ class TaskStore:
|
||||
project = self._project_record(self._project_row(project_id))
|
||||
if project.task_id != task_id:
|
||||
raise TaskCenterError("project_task_mismatch", "project does not belong to the task")
|
||||
if project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED}:
|
||||
raise TaskCenterError("quick_run_project_state", "project state does not allow quick-run completion")
|
||||
summary = (project_summaries or {}).get(project_id, "current-sheet quick-run queue completed")
|
||||
if project.status is ProjectStatus.PENDING or project.summary != summary:
|
||||
recovered_native_failure = (project.status is ProjectStatus.FAILED
|
||||
and project.summary.startswith('quick_run_result:')
|
||||
and summary.startswith('quick_run_result:') and summary.endswith(':saved'))
|
||||
if project.status not in {ProjectStatus.PENDING, ProjectStatus.COMPLETED} and not recovered_native_failure:
|
||||
raise TaskCenterError("quick_run_project_state", "project state does not allow quick-run completion")
|
||||
if project.status is not ProjectStatus.COMPLETED or project.summary != summary:
|
||||
self._connection.execute(
|
||||
"UPDATE projects SET status = ?, error_id = NULL, summary = ? WHERE project_id = ?",
|
||||
(ProjectStatus.COMPLETED.value, summary, project_id),
|
||||
|
||||
@@ -5,7 +5,7 @@ from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from .models import TaskRecord, ProjectRecord, RuleRecord
|
||||
from .models import TaskRecord, ProjectRecord, RuleRecord, TaskStatus
|
||||
from .target_plan import ComponentTarget, TargetPlanRow
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ class TaskBundle:
|
||||
projects: tuple[ProjectRecord, ...]
|
||||
rules: tuple[RuleRecord, ...]
|
||||
targets: tuple[TargetPlanRow, ...]
|
||||
batch_rules: tuple[RuleRecord, ...] | None = None
|
||||
|
||||
|
||||
def checkpoint(read_control):
|
||||
@@ -66,6 +67,17 @@ def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
|
||||
rules = records(
|
||||
"SELECT * FROM rules WHERE task_id = ? ORDER BY position", store._rule_record,
|
||||
)
|
||||
batch_rules = None
|
||||
if task.group_id and task.status is not TaskStatus.DELETED:
|
||||
from .batch_rules import merge_rule_view
|
||||
group_rules = []
|
||||
for row in store._connection.execute(
|
||||
"SELECT r.* FROM rules r JOIN tasks t ON t.task_id = r.task_id "
|
||||
"WHERE t.group_id = ? AND t.status <> ? ORDER BY t.group_position, t.created_utc, t.task_id, r.position",
|
||||
(task.group_id, TaskStatus.DELETED.value)):
|
||||
checkpoint()
|
||||
group_rules.append(store._rule_record(row))
|
||||
batch_rules = merge_rule_view(group_rules, {r.old_part_number.casefold(): r for r in rules})
|
||||
def target_record(row):
|
||||
return TargetPlanRow(
|
||||
ComponentTarget(Path(row['project_path']), row['schematic_name'], row['sheet_number'],
|
||||
@@ -81,7 +93,7 @@ def read_task_bundle(store, task_id: str, read_control=None) -> TaskBundle:
|
||||
if started:
|
||||
store._connection.execute("COMMIT")
|
||||
started = False
|
||||
return TaskBundle(task, projects, rules, targets)
|
||||
return TaskBundle(task, projects, rules, targets, batch_rules)
|
||||
except BaseException:
|
||||
if started:
|
||||
store._connection.execute("ROLLBACK")
|
||||
|
||||
@@ -586,7 +586,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if not self.run_panel.recover_button.isEnabled():
|
||||
return
|
||||
if QMessageBox.question(self, '核验并恢复',
|
||||
'先备份工程和证据,再打开工程核验;不会重复调用原生替换,也不会自动保存。请先保存并关闭已有 CAD 工程。',
|
||||
'先备份工程和证据,再打开工程核验;如需补齐属性,会保存并重开回读,不会重复调用原生替换。请先保存并关闭已有 CAD 工程。',
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) != QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
|
||||
@@ -60,6 +60,25 @@ def run_queue(service, task, stop=None):
|
||||
return service.execute_quick_run_queue(task.task_id, expected_item=expected, stop_event=stop or Event())
|
||||
|
||||
|
||||
def test_native_mutation_failure_stops_before_next_batch_step(tmp_path):
|
||||
service, task, calls = setup_queue(tmp_path, ('batch_failed', 'saved_ok'))
|
||||
original_worker = service._quick_run_preparer._process_runner
|
||||
def failed_after_mutation(command, timeout):
|
||||
root = Path(command[3])
|
||||
job = command[-1]
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\tawaiting_native_replace\t\tsnapshot captured\n')
|
||||
(root / f'snapshot-{job}.tsv.native.json').write_text(
|
||||
json.dumps({'ok': False, 'stage': 'pin_promotion_started'}), encoding='utf-8')
|
||||
return original_worker(command, timeout)
|
||||
service._quick_run_preparer._process_runner = failed_after_mutation
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
run_queue(service, task)
|
||||
assert raised.value.code == 'quick_run_uncertain'
|
||||
assert len(calls) == 1
|
||||
assert (tmp_path / 'data/quick-run/uncertain.flag').exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('states', [('no_match',) * 20, ('no_match', 'saved_ok', 'no_match', 'saved_ok')])
|
||||
def test_queue_continues_after_misses_and_successes(tmp_path, states):
|
||||
service, task, calls = setup_queue(tmp_path, states)
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def failed_native(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
path = tmp_path / 'board.prj'
|
||||
path.touch()
|
||||
task = store.create_task('native failed')
|
||||
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
|
||||
project = store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(task.task_id, project.project_id, 'batch', 0)
|
||||
service.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
facade = service.for_project_task(task.task_id)
|
||||
handoff = facade._quick_run_preparer.prepare(task.task_id, (project,), store.list_rules(task.task_id))
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\n'
|
||||
f'{job}\tawaiting_native_replace\t\tprepared\n'
|
||||
f'{job}\tbatch_failed\t-2147220665\tfailed project closed without saving; native rollback not executed\n', encoding='utf-8')
|
||||
root = handoff.command_path.parent
|
||||
snapshot = root / f'snapshot-{job}.tsv'
|
||||
snapshot.write_text('original snapshot evidence')
|
||||
report = Path(str(snapshot) + '.native.json')
|
||||
report.write_text(json.dumps({'ok': False, 'stage': 'pin_promotion_started', 'replaced_uids': ['uid']}))
|
||||
service.quick_run_progress(task.task_id)
|
||||
yield service, store, task.task_id, handoff, report
|
||||
store.close()
|
||||
|
||||
|
||||
def test_failed_after_native_mutation_is_interrupted_and_retry_does_not_archive(failed_native):
|
||||
service, store, task_id, handoff, report = failed_native
|
||||
context = service.task_context(task_id)
|
||||
assert context.interrupted and service.has_interrupted_quick_run(task_id)
|
||||
originals = {p: p.read_bytes() for p in (handoff.command_path, handoff.status_path, report)}
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
service.prepare_failed_quick_run(task_id)
|
||||
assert error.value.code == 'quick_run_uncertain'
|
||||
assert all(path.read_bytes() == contents for path, contents in originals.items())
|
||||
assert not (handoff.command_path.parent.parent / 'quick-run-history').exists()
|
||||
|
||||
|
||||
def test_verified_rollback_resolves_failed_native_uncertainty(failed_native):
|
||||
service, _, task_id, _, report = failed_native
|
||||
Path(str(report)[:-len('.json')] + '.rolled-back').write_text('native replacement rollback verified')
|
||||
assert not service.task_context(task_id).interrupted
|
||||
|
||||
|
||||
@pytest.mark.parametrize('contents', [None, '{truncated'])
|
||||
def test_native_awaiting_then_failed_without_readable_report_stays_uncertain(failed_native, contents):
|
||||
service, _, task_id, _, report = failed_native
|
||||
if contents is None:
|
||||
report.unlink()
|
||||
else:
|
||||
report.write_text(contents)
|
||||
assert service.has_interrupted_quick_run(task_id)
|
||||
|
||||
|
||||
def test_preflight_native_failure_does_not_claim_mutation(failed_native):
|
||||
service, _, task_id, _, report = failed_native
|
||||
report.write_text(json.dumps({'ok': False, 'stage': 'preflight', 'error': 'library target absent'}))
|
||||
assert not service.has_interrupted_quick_run(task_id)
|
||||
|
||||
|
||||
def test_recovery_selects_failed_job_with_native_mutation_evidence(failed_native):
|
||||
from dx_productivity.trial_task_center import quick_run, recovery
|
||||
_, _, _, handoff, _ = failed_native
|
||||
commands = quick_run._read_commands(handoff.command_path)
|
||||
statuses = quick_run._read_status_details(handoff.status_path)
|
||||
assert recovery._recovery_command(commands, statuses, root=handoff.command_path.parent) == commands[0]
|
||||
|
||||
|
||||
def test_native_failure_status_reaches_bound_recovery_validation(failed_native, monkeypatch):
|
||||
from dx_productivity.trial_task_center import recovery
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus
|
||||
service, store, task_id, _, _ = failed_native
|
||||
project = store.list_projects(task_id)[0]
|
||||
assert project.status is ProjectStatus.FAILED
|
||||
def validate(*args, **kwargs):
|
||||
raise TaskCenterError('bound_recovery_reached', 'validate immutable native evidence')
|
||||
monkeypatch.setattr(recovery, 'recover', validate)
|
||||
with pytest.raises(TaskCenterError) as error:
|
||||
service.recover_quick_run(task_id, confirmed=True)
|
||||
assert error.value.code == 'bound_recovery_reached'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('code', ['recovery_verified', 'recovery_saved_verified'])
|
||||
def test_verified_recovery_synchronizes_previously_failed_project(failed_native, code):
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
|
||||
service, store, task_id, handoff, _ = failed_native
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
with handoff.status_path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\trestored_ok\t{code}\tsaved and verified\n')
|
||||
service.quick_run_progress(task_id)
|
||||
assert store.list_projects(task_id)[0].status is ProjectStatus.COMPLETED
|
||||
assert store.get_task(task_id).status is TaskStatus.COMPLETED
|
||||
|
||||
|
||||
def test_manual_failure_cannot_be_completed_by_native_progress(failed_native):
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus
|
||||
service, store, task_id, handoff, _ = failed_native
|
||||
project = store.list_projects(task_id)[0]
|
||||
store.set_project_status(project.project_id, ProjectStatus.FAILED, summary='manual failure')
|
||||
job = handoff.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
with handoff.status_path.open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\trestored_ok\trecovery_verified\tverified\n')
|
||||
with pytest.raises(TaskCenterError, match='quick_run_project_state'):
|
||||
service.quick_run_progress(task_id)
|
||||
|
||||
|
||||
def test_uncertain_batch_failed_blocks_next_project_in_task_queue(failed_native, tmp_path):
|
||||
from threading import Event
|
||||
from dx_productivity.trial_task_center.task_queue import execute_task_queue
|
||||
service, store, task_id, _, _ = failed_native
|
||||
other = store.create_task('next must not run')
|
||||
path = tmp_path / 'next.prj'
|
||||
path.touch()
|
||||
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
|
||||
result = execute_task_queue(service, (task_id, other.task_id), stop_event=Event())
|
||||
assert result.paused
|
||||
assert [entry.state for entry in result.entries] == ['blocked', 'pending']
|
||||
assert not (service.for_project_task(other.task_id)._quick_run_preparer.data_root / 'quick-run').exists()
|
||||
@@ -0,0 +1,24 @@
|
||||
from threading import Timer
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kind', ['native_report', 'queue_command'])
|
||||
def test_native_report_waits_for_reader_to_release_windows_replace_lock(tmp_path, kind):
|
||||
import win32file
|
||||
import win32con
|
||||
from dx_productivity.trial_task_center.native_helper import atomic_text
|
||||
from dx_productivity.trial_task_center.quick_run import _write_atomic_queue_text
|
||||
report = tmp_path / 'native.json'
|
||||
report.write_text('old complete report')
|
||||
held = win32file.CreateFile(str(report), win32con.GENERIC_READ,
|
||||
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, 0, None)
|
||||
timer = Timer(.2, held.Close)
|
||||
timer.start()
|
||||
try:
|
||||
if kind == 'native_report':
|
||||
atomic_text(report, 'new complete report')
|
||||
else:
|
||||
_write_atomic_queue_text(report, 'new complete report', 'quick_run_command', 'publish failed')
|
||||
finally:
|
||||
timer.join()
|
||||
assert report.read_text() == 'new complete report'
|
||||
@@ -61,6 +61,40 @@ def test_native_context_accepts_same_project_via_junction_and_rejects_foreign(tm
|
||||
assert not pool.close()
|
||||
|
||||
|
||||
def test_vbs_reopen_resolves_canonical_long_project_before_fso_check(tmp_path, monkeypatch):
|
||||
project = long_project(tmp_path)
|
||||
root = tmp_path / 'worker'
|
||||
root.mkdir()
|
||||
(root / 'command.tsv').write_text(f'project_path\n{project}\n', encoding='utf-8')
|
||||
pool = legacy_paths._AliasPool()
|
||||
monkeypatch.setattr(legacy_paths, '_aliases', pool)
|
||||
monkeypatch.setattr(legacy_paths, '_short_path', lambda _: None)
|
||||
source = (Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs').read_text(encoding='utf-8-sig')
|
||||
def function(name):
|
||||
return re.search(rf'(?ms)^Function {name}\(.*?^End Function', source).group()
|
||||
try:
|
||||
legacy_paths.worker_paths(root / 'worker.vbs', root)
|
||||
access = (root / 'project-access.tsv').read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
|
||||
# Execute the production reopen boundary against real legacy FSO,
|
||||
# stopping before CAD calls; no imitation of path resolution here.
|
||||
boundary = re.search(r'(?ms)^Sub QPEnsureProject\(.*?(?= QP_Stage = "check_project")', source).group()
|
||||
script = tmp_path / 'reopen-check.vbs'
|
||||
script.write_text('Dim QP_Fso, QP_Root, QP_ProjectAccess, QP_AccessProject, App\n'
|
||||
'Set QP_Fso=CreateObject("Scripting.FileSystemObject")\n'
|
||||
'QP_Root=WScript.Arguments(0)\nSet App=Nothing\n'
|
||||
'QPEnsureProject App, WScript.Arguments(1)\n'
|
||||
+ boundary + 'WScript.Echo TargetPath\nEnd Sub\n'
|
||||
+ function('QPProjectAccessPath') + '\n'
|
||||
+ re.search(r'(?ms)^Sub QPEnsureProjectAccess\(\).*?^End Sub', source).group() + '\n'
|
||||
+ function('QPReadUtf8'), encoding='utf-8')
|
||||
result = subprocess.run((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(script), str(root), str(project)),
|
||||
capture_output=True, text=True)
|
||||
assert result.returncode == 0, result.stdout + result.stderr
|
||||
assert Path(result.stdout.strip()) == Path(access)
|
||||
finally:
|
||||
assert not pool.close()
|
||||
|
||||
|
||||
def test_redirected_project_entry_is_rejected_before_native_launch(tmp_path, monkeypatch):
|
||||
import _winapi
|
||||
from dx_productivity.trial_task_center import quick_run
|
||||
|
||||
@@ -62,7 +62,8 @@ def test_recovery_selects_saved_unverified_job_before_next_pending_job():
|
||||
assert _recovery_command(commands, statuses) == commands[0]
|
||||
|
||||
|
||||
def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path):
|
||||
@pytest.mark.parametrize('code', ['recovery_verified', 'recovery_saved_verified'])
|
||||
def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path, code):
|
||||
script = tmp_path / 'QuickPartReplace.vbs'
|
||||
script.write_text("' fixture\n", encoding='ascii')
|
||||
preparer = QuickRunPreparer(tmp_path / 'data', script_source=script)
|
||||
@@ -74,9 +75,14 @@ def test_recovered_unverified_job_no_longer_blocks_queue(tmp_path):
|
||||
(root / 'status.tsv').write_text(
|
||||
'job_id\tstate\tcode\tmessage\n'
|
||||
'a\tbatch_saved_unverified\t\treadback failed\n'
|
||||
'a\trestored_ok\t\trecovered\n', encoding='utf-8')
|
||||
f'a\trestored_ok\t{code}\trecovered\n', encoding='utf-8')
|
||||
|
||||
assert preparer.has_interrupted('t') is False
|
||||
from dx_productivity.trial_task_center.quick_run import _progress_from_queue
|
||||
project = type('Project', (), {'path': Path('board.prj')})()
|
||||
progress = _progress_from_queue((project,), _read_commands(root / 'command.tsv'),
|
||||
(('a', 'restored_ok', code, 'recovered'),), None)
|
||||
assert progress.saved_items == 1
|
||||
|
||||
|
||||
def test_native_context_rejects_missing_or_changed_target_without_no_match():
|
||||
|
||||
Reference in new issue
Block a user