Initial import of DxDesigner part replacement tool (r21)

This commit is contained in:
阿白叔 committed 2026-09-29 15:42:21 +08:00
commit ffe066cb1e
151 files changed
+58745

No files matched your search

+183
View File
@@ -0,0 +1,183 @@
from __future__ import annotations
from pathlib import Path
import os
import subprocess
import sys
def test_default_data_root_uses_windows_known_folder_without_environment(tmp_path: Path, monkeypatch) -> None:
from dx_productivity.trial_task_center import application
known_folder = tmp_path / "Local App Data"
monkeypatch.delenv("LOCALAPPDATA", raising=False)
monkeypatch.setattr(application, "_windows_local_app_data", lambda: known_folder)
assert application.resolve_data_root(None) == (
known_folder / "DxProductivity" / "trial-task-center"
).resolve()
def test_frozen_application_keeps_data_beside_the_executable(tmp_path: Path, monkeypatch) -> None:
from dx_productivity.trial_task_center import application
executable = tmp_path / "DxPartReplace" / "DxPartReplace.exe"
monkeypatch.setattr(application.sys, "frozen", True, raising=False)
monkeypatch.setattr(application.sys, "executable", str(executable))
assert application.resolve_data_root(None) == (executable.parent / "data").resolve()
def test_explicit_data_root_still_overrides_frozen_portable_default(tmp_path: Path, monkeypatch) -> None:
from dx_productivity.trial_task_center import application
monkeypatch.setattr(application.sys, "frozen", True, raising=False)
monkeypatch.setattr(application.sys, "executable", str(tmp_path / "app" / "DxPartReplace.exe"))
override = tmp_path / "override"
assert application.resolve_data_root(override) == override.resolve()
def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path: Path, monkeypatch) -> None:
"""Moving logging after Qt creation would lose startup and recovery diagnostics."""
from dx_productivity.trial_task_center import application
from dx_productivity.trial_task_center.logging_setup import configure_logging
events: list[str] = []
context = configure_logging(tmp_path)
class Store:
path = tmp_path / "task-center.db"
def __init__(self, path: Path) -> None:
assert events == ["logging"]
self.path = path
def recover_interrupted_work(self) -> tuple[str, ...]:
return ("project-1",)
def close(self) -> None:
events.append("closed")
class Application:
def __init__(self, _argv: list[str]) -> None:
assert events == ["logging"]
def exec(self) -> int:
return 0
class Service:
def __init__(self, _store, _context) -> None:
assert events == ["logging"]
class Window:
def __init__(self, _service) -> None:
events.append("window")
def show(self) -> None:
events.append("shown")
monkeypatch.setattr(application, "configure_logging", lambda _root: events.append("logging") or context)
monkeypatch.setattr(application, "TaskStore", Store)
monkeypatch.setattr(application, "TaskCenterService", Service)
monkeypatch.setattr(application, "QApplication", Application)
monkeypatch.setattr(application, "_load_window", lambda: Window)
assert application.main(["--data-root", str(tmp_path)]) == 0
assert events == ["logging", "window", "shown", "closed"]
assert "recovered_interrupted_projects=project-1" in context.application_log_path.read_text(encoding="utf-8")
assert f"version={application.VERSION}" in context.application_log_path.read_text(encoding="utf-8")
def test_smoke_test_closes_window_with_zero_delay_timer_and_reopens_database(tmp_path: Path, monkeypatch) -> None:
"""A packaged smoke run must exit cleanly and leave its SQLite database reusable."""
from dx_productivity.trial_task_center import application
calls: list[object] = []
class Application:
def __init__(self, _argv: list[str]) -> None:
calls.append("application")
def quit(self) -> None:
calls.append("quit")
def exec(self) -> int:
return 0
class Timer:
@staticmethod
def singleShot(delay: int, callback) -> None:
calls.append(delay)
callback()
class Window:
def __init__(self, _service) -> None:
calls.append("window")
def show(self) -> None:
calls.append("shown")
def close(self) -> None:
calls.append("closed")
monkeypatch.setattr(application, "QApplication", Application)
monkeypatch.setattr(application, "QTimer", Timer)
monkeypatch.setattr(application, "_load_window", lambda: Window)
arguments = ["--smoke-test", "--data-root", str(tmp_path)]
assert application.main(arguments) == 0
assert application.main(arguments) == 0
assert calls == [
"application", "window", "shown", 0, "closed", "quit",
"application", "window", "shown", 0, "closed", "quit",
]
assert (tmp_path / "task-center.db").exists()
def test_fatal_startup_exception_is_logged_with_traceback_and_nonzero_exit(tmp_path: Path, monkeypatch) -> None:
"""A database startup crash must be diagnosable without presenting a half-built window."""
from dx_productivity.trial_task_center import application
def fail_store(_path: Path):
raise RuntimeError("database unavailable")
monkeypatch.setattr(application, "TaskStore", fail_store)
assert application.main(["--data-root", str(tmp_path)]) == 1
application_log = (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
assert "RuntimeError: database unavailable" in application_log
assert "operation=startup" in application_log
def test_native_helper_mode_skips_database_logging_and_qt(tmp_path: Path, monkeypatch) -> None:
"""The helper subprocess must attach to DxDesigner without starting another GUI shell."""
from dx_productivity.trial_task_center import application, native_helper
snapshot = tmp_path / "snapshot.tsv"
snapshot.touch()
calls: list[Path] = []
monkeypatch.setattr(native_helper, "run", lambda path: calls.append(path) or 7)
monkeypatch.setattr(application, "configure_logging", lambda _root: (_ for _ in ()).throw(AssertionError("logging started")))
assert application.main(["--native-helper", "--snapshot", str(snapshot)]) == 7
assert calls == [snapshot]
def test_application_module_runs_as_a_script_for_the_frozen_entrypoint(tmp_path: Path) -> None:
"""Relative imports would make a PyInstaller script entrypoint fail before logging starts."""
source_root = Path(__file__).resolve().parents[2] / "src"
script = source_root / "dx_productivity" / "trial_task_center" / "application.py"
environment = os.environ | {"PYTHONPATH": str(source_root), "QT_QPA_PLATFORM": "offscreen"}
result = subprocess.run(
[sys.executable, str(script), "--smoke-test", "--data-root", str(tmp_path)],
capture_output=True,
text=True,
timeout=15,
env=environment,
check=False,
)
assert result.returncode == 0, result.stderr
assert "application_clean_shutdown" in (tmp_path / "logs" / "application.log").read_text(encoding="utf-8")
File diff suppressed because it is too large. Load diff
+170
View File
@@ -0,0 +1,170 @@
from __future__ import annotations
import copy
import json
from pathlib import Path
import pytest
from dx_productivity.part_replace.models import MappingRule
from dx_productivity.trial_task_center.comparison import compare_profiles
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _profile(name: str) -> dict[str, object]:
return json.loads((FIXTURES / name).read_text(encoding="utf-8"))
def _codes(result: object) -> set[str]:
return {issue.code for issue in result.issues}
def test_compare_profiles_matches_material_numbers_and_serializes_canonically() -> None:
result = compare_profiles(
_profile("profile-before.json"),
_profile("profile-after-valid.json"),
(MappingRule(" old-1 ", "NEW-1"), MappingRule("OLD-2", "NEW-2")),
)
assert result.passed
assert result.matched_logical_identities[MappingRule(" old-1 ", "NEW-1")] == ("/MAIN|R1",)
assert result.matched_logical_identities[MappingRule("OLD-2", "NEW-2")] == ()
assert {warning.code for warning in result.warnings} == {"no_matching_source_part"}
assert result.to_json() == result.to_json()
assert json.loads(result.to_json())["passed"] is True
def test_compare_profiles_rejects_wrong_target_and_missing_or_duplicate_identity() -> None:
before = _profile("profile-before.json")
invalid = _profile("profile-after-invalid.json")
result = compare_profiles(before, invalid, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert {"wrong_target_part_number", "duplicate_logical_identity"} <= _codes(result)
def test_compare_profiles_detects_protected_changes_and_unrelated_changes() -> None:
before = _profile("profile-before.json")
after = copy.deepcopy(_profile("profile-after-valid.json"))
component = after["components"][0]
component["refdes"] = "R9"
component["hierarchy"] = "/OTHER"
component["units"] = 2
component["origin"]["x"] = 11
component["position"]["y"] = 99
component["rotation"] = 90
component["mirror"] = True
component["pins"][0]["number"] = "9"
component["nets"] = ["GND"]
after["components"][1]["refdes"] = "C9"
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert {
"refdes_changed", "hierarchy_changed", "unit_count_changed", "origin_changed",
"position_changed", "rotation_changed", "mirror_changed", "pins_changed",
"nets_changed", "unrelated_component_changed",
} <= _codes(result)
def test_compare_profiles_reports_parameter_presentation_as_warning_not_a_pass() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
after["interfaces"]["parameter_probe"] = {"available": False}
after["components"][0]["parameter_probe"] = None
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert result.passed
assert {warning.code for warning in result.warnings} == {"parameter_presentation_unavailable"}
def test_compare_profiles_keeps_part_label_and_value_differences_as_warnings() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
after["components"][0]["attributes"] = [
{"name": "Part Label", "value": "R-ALT"},
{"name": "Value", "value": "12K"},
]
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert result.passed
assert {warning.code for warning in result.warnings} == {"part_label_changed", "value_changed"}
def test_compare_profiles_canonical_json_does_not_depend_on_rule_input_order() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
first = MappingRule("OLD-1", "NEW-1")
second = MappingRule("OLD-2", "NEW-2")
forward = compare_profiles(before, after, (first, second))
reverse = compare_profiles(before, after, (second, first))
assert forward.to_json() == reverse.to_json()
def test_compare_profiles_does_not_pass_when_part_number_evidence_is_missing() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
before["components"][0]["part_number"] = None
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert "missing_protected_evidence" in _codes(result)
def test_compare_profiles_rejects_part_number_changes_on_unmatched_components() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
after["components"][1]["part_number"] = "SURPRISE-PART"
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert "unrelated_component_changed" in _codes(result)
@pytest.mark.parametrize(
("field", "value"),
(
("refdes", ""),
("hierarchy", ""),
("origin", []),
("position", {"x": 1}),
("units", 1.5),
("pins", {"number": "1"}),
("nets", [1]),
),
)
def test_compare_profiles_rejects_invalid_protected_component_schema(field: str, value: object) -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
before["components"][0][field] = value
after["components"][0][field] = copy.deepcopy(value)
result = compare_profiles(before, after, (MappingRule("OLD-1", "NEW-1"),))
assert not result.passed
assert "invalid_protected_evidence" in _codes(result)
def test_compare_profiles_canonical_json_does_not_depend_on_component_input_order() -> None:
before = _profile("profile-before.json")
after = _profile("profile-after-valid.json")
reversed_before = copy.deepcopy(before)
reversed_after = copy.deepcopy(after)
reversed_before["components"].reverse()
reversed_after["components"].reverse()
rules = (MappingRule("OLD-1", "NEW-1"), MappingRule("OLD-2", "NEW-2"))
forward = compare_profiles(before, after, rules)
reversed_result = compare_profiles(reversed_before, reversed_after, rules)
assert forward.to_json() == reversed_result.to_json()
+233
View File
@@ -0,0 +1,233 @@
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
import dx_productivity.trial_task_center.evidence as evidence_module
from dx_productivity.trial_task_center.evidence import capture_profile, profile_stamp
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _copy_fixture(name: str, destination: Path) -> bytes:
data = (FIXTURES / name).read_bytes()
destination.write_bytes(data)
return data
def _directory_alias(alias: Path, target: Path) -> None:
if os.name == "nt":
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(alias), str(target)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
else:
try:
alias.symlink_to(target, target_is_directory=True)
except OSError as error:
pytest.skip(f"directory aliases unavailable: {error}")
def test_profile_stamp_returns_exact_hash_for_a_stable_snapshot(tmp_path: Path) -> None:
source = tmp_path / "profile.json"
data = _copy_fixture("profile-before.json", source)
stamp = profile_stamp(source)
assert stamp is not None
assert stamp.size == len(data)
assert stamp.sha256 == hashlib.sha256(data).hexdigest()
assert stamp.modified_ns == source.stat().st_mtime_ns
assert profile_stamp(tmp_path / "missing.json") is None
@pytest.mark.parametrize(
("contents", "code"),
(
(b"{", "profile_json"),
(b'{"format_version": 1, "format_version": 1}', "profile_duplicate_key"),
(b'{"format_version": 2, "project": {"identity": "C:/Projects/Board.prj"}}', "profile_version"),
(b'{"format_version": 1, "project": {"identity": "C:/Other/Board.prj"}}', "profile_project"),
),
)
def test_capture_profile_rejects_untrustworthy_probe_output(
tmp_path: Path, contents: bytes, code: str
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "captured.json"
source.write_bytes(contents)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == code
assert not destination.exists()
def test_capture_profile_requires_new_evidence_and_publishes_exact_bytes_atomically(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "captured.json"
original = _copy_fixture("profile-before.json", source)
previous = profile_stamp(source)
assert previous is not None
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), previous)
assert raised.value.code == "profile_unchanged"
updated = json.loads(original)
updated["capture"] = "after operator action"
data = json.dumps(updated, sort_keys=True, separators=(",", ":")).encode("utf-8")
source.write_bytes(data)
os.utime(source, ns=(previous.modified_ns + 1, previous.modified_ns + 1))
captured = capture_profile(source, destination, Path("c:\\projects\\board.prj"), previous)
assert captured.source == source
assert captured.destination == destination
assert captured.project_identity == "C:/Projects/Board.PRJ"
assert captured.stamp.sha256 == hashlib.sha256(data).hexdigest()
assert destination.read_bytes() == data
assert source.read_bytes() == data
assert not list(tmp_path.glob(".captured.json.*"))
@pytest.mark.parametrize("constant", ("NaN", "Infinity", "-Infinity"))
def test_capture_profile_rejects_non_finite_json_constants(tmp_path: Path, constant: str) -> None:
source = tmp_path / "menu-probe.json"
source.write_bytes(
('{"format_version":1,"project":{"identity":"C:/Projects/Board.PRJ"},"value":' + constant + "}").encode("ascii")
)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, tmp_path / "captured.json", Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_json"
def test_capture_profile_accepts_a_canonical_project_alias(tmp_path: Path) -> None:
real_project = tmp_path / "projects" / "Board.prj"
alias = tmp_path / "alias" / "Board.prj"
real_project.parent.mkdir()
real_project.write_text("project", encoding="utf-8")
_directory_alias(alias.parent, real_project.parent)
source = tmp_path / "menu-probe.json"
profile = json.loads((FIXTURES / "profile-before.json").read_text(encoding="utf-8"))
profile["project"]["identity"] = str(alias)
source.write_text(json.dumps(profile), encoding="utf-8")
captured = capture_profile(source, tmp_path / "captured.json", real_project, None)
assert captured.project_identity == str(alias)
def test_capture_profile_rejects_a_reparse_destination_parent(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
_copy_fixture("profile-before.json", source)
target = tmp_path / "target"
target.mkdir()
alias = tmp_path / "alias"
_directory_alias(alias, target)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, alias / "captured.json", Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_publish_path"
def test_capture_profile_rejects_staged_path_hardlink_substitution(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "published" / "captured.json"
attacker = tmp_path / "attacker.json"
_copy_fixture("profile-before.json", source)
destination.parent.mkdir()
destination.write_bytes(b"previous-profile")
attacker.write_bytes(b"attacker-controlled-bytes")
def substitute(_: Path, temporary: Path) -> None:
temporary.unlink()
os.link(attacker, temporary)
monkeypatch.setattr(evidence_module, "_publication_hook", substitute, raising=False)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_publish"
assert destination.read_bytes() == b"previous-profile"
assert attacker.read_bytes() == b"attacker-controlled-bytes"
def test_capture_profile_rejects_source_destination_alias_without_mutating_source(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
_copy_fixture("profile-before.json", source)
before = source.stat()
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, source, Path("C:/Projects/Board.PRJ"), None)
after = source.stat()
assert raised.value.code == "profile_source_destination_alias"
assert (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) == (
before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns,
)
def test_capture_profile_rejects_hardlink_destination_alias(tmp_path: Path) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "destination.json"
_copy_fixture("profile-before.json", source)
os.link(source, destination)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_source_destination_alias"
def test_capture_profile_rejects_junction_or_symlink_destination_alias(tmp_path: Path) -> None:
source_parent = tmp_path / "source-parent"
source = source_parent / "menu-probe.json"
alias_parent = tmp_path / "alias-parent"
source_parent.mkdir()
_copy_fixture("profile-before.json", source)
_directory_alias(alias_parent, source_parent)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, alias_parent / source.name, Path("C:/Projects/Board.PRJ"), None)
assert raised.value.code == "profile_source_destination_alias"
def test_capture_profile_rejects_non_windows_publication_before_destination_write(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
source = tmp_path / "menu-probe.json"
destination = tmp_path / "not-created" / "captured.json"
original = _copy_fixture("profile-before.json", source)
before = source.stat()
monkeypatch.setattr(evidence_module, "_WINDOWS_EVIDENCE_PUBLICATION", False, raising=False)
with pytest.raises(TaskCenterError) as raised:
capture_profile(source, destination, Path("C:/Projects/Board.PRJ"), None)
after = source.stat()
assert raised.value.code == "unsupported_platform"
assert source.read_bytes() == original
assert (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns) == (
before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns,
)
assert not destination.parent.exists()
@@ -0,0 +1,94 @@
import ast
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center import native_helper
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, RuleRecord
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
SOURCE = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
def test_native_route_never_injects_global_mouse_or_keyboard():
tree = ast.parse(Path(native_helper.__file__).read_text(encoding='utf-8'))
forbidden = {'SetCursorPos', 'mouse_event', 'keybd_event', 'click_input', 'SetForegroundWindow', 'BlockInput'}
used = {node.attr for node in ast.walk(tree) if isinstance(node, ast.Attribute)}
assert not used & forbidden
def test_installed_resource_resolves_without_attaching_to_cad():
executable = Path('D:/Mentor/7.9.5EE/SDD_HOME/wv/win32/bin/viewdraw.exe')
if not executable.is_file():
pytest.skip('Installed DxDesigner resource not available')
assert native_helper.replacement_command_from_resources(executable) == 33977
def test_mixed_no_match_queue_resumes_without_blocking_or_false_success(tmp_path):
projects = tuple(ProjectRecord(f'project-{index}', 'task', f'Project {index}',
tmp_path / f'project-{index}.prj', tmp_path, True, True,
ProjectStatus.PENDING, 0) for index in range(3))
rules = (RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True),)
states = ['no_match', 'restored_ok', 'no_match']
called = []
def worker(command, timeout):
rows = [line.split('\t') for line in (tmp_path / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()[1:]]
row = rows[len(called)]
assert command[-1] == row[1]
state = states[len(called)]
with (tmp_path / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
if state == 'restored_ok':
handle.write(f'{row[1]}\tawaiting_native_replace\t\tcaptured\n')
handle.write(f'{row[1]}\t{state}\t\tchecked current sheet\n')
called.append(row[1])
return subprocess.CompletedProcess(command, 0, '', '')
def preparer():
return QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
runner = preparer()
for index in range(3):
result = runner.execute_step('task', projects, rules)
assert result.state == states[index]
runner = preparer()
progress = runner.progress('task', projects, rules)
assert progress.completed_items == index + 1
assert progress.no_match_items == [1, 1, 2][index]
assert progress.queue_complete and result.next_project_path is None
assert runner.current_phase('task', projects, rules) == 'complete'
with pytest.raises(TaskCenterError, match='quick_run_complete'):
runner.execute_step('task', projects, rules)
assert len(called) == 3
def test_no_match_cannot_mask_a_previously_captured_replacement(tmp_path):
from dx_productivity.trial_task_center.quick_run import _correlated_status_change
commands = (('task', 'job', 'project', 'OLD', 'NEW'),)
before = (('job', 'awaiting_native_replace', '', 'captured'),)
after = (*before, ('job', 'no_match', '', 'not found'))
assert _correlated_status_change(commands, before, after) is None
def test_invalid_transaction_evidence_never_promotes_pins(monkeypatch, tmp_path):
from types import SimpleNamespace
components = [SimpleNamespace(UID='outside-snapshot')]
monkeypatch.setattr(native_helper, 'read_snapshot', lambda path: (['M', 'project', 'OLD', 'NEW', 'sheet'],
[['C', 'recorded', 'R1', '0', '0', '0', '1', 'net']]))
monkeypatch.setattr(native_helper, 'attach', lambda: (object(), object()))
monkeypatch.setattr(native_helper, 'check_active_context', lambda *args: None)
monkeypatch.setattr(native_helper, 'components_on_sheet', lambda *args: components)
monkeypatch.setattr(native_helper, 'attribute_value', lambda *args: 'OLD')
calls = []
monkeypatch.setattr(native_helper, 'promote_pin_numbers', lambda *args: calls.append(args))
report = {}
with pytest.raises(ValueError, match='Cannot prove'):
native_helper.run_native(tmp_path / 'snapshot.tsv', report)
assert calls == []
assert report == {}
@@ -0,0 +1,180 @@
import json
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
import sys
import threading
import time
import dx_productivity.trial_task_center.logging_setup as logging_setup
from dx_productivity.trial_task_center.logging_setup import (
_next_event_sequence,
_tail_utf8_lines,
append_task_event,
capture_subprocess_output,
configure_logging,
install_exception_hooks,
)
def test_configure_logging_creates_utf8_rotating_application_log(tmp_path: Path) -> None:
"""A long-running trial must retain bounded readable diagnostics."""
context = configure_logging(tmp_path)
handlers = [handler for handler in context.logger.handlers if isinstance(handler, RotatingFileHandler)]
assert context.application_log_path == tmp_path / "logs" / "application.log"
assert context.application_log_path.exists()
assert len(handlers) == 1
assert handlers[0].maxBytes == 5 * 1024 * 1024
assert handlers[0].backupCount == 5
assert handlers[0].encoding == "utf-8"
def test_relative_logging_root_reuses_one_utc_handler(tmp_path: Path, monkeypatch) -> None:
"""Repeated startup from a relative storage root must neither duplicate nor mislabel timestamps."""
monkeypatch.chdir(tmp_path)
first = configure_logging(Path("task-center"))
second = configure_logging(Path("task-center"))
handlers = [handler for handler in first.logger.handlers if isinstance(handler, RotatingFileHandler)]
record = logging.LogRecord("trial", logging.INFO, __file__, 1, "message", (), None)
record.created = 0
assert first.root == tmp_path / "task-center"
assert first.application_log_path == tmp_path / "task-center" / "logs" / "application.log"
assert first.logger is second.logger
assert len(handlers) == 1
assert handlers[0].formatter.converter is time.gmtime
assert handlers[0].formatter.format(record).startswith("1970-01-01T00:00:00Z")
def test_task_events_are_canonical_json_and_visible_before_return(tmp_path: Path) -> None:
"""The UI must not report an action before its task event is durable and readable."""
context = configure_logging(tmp_path)
first = append_task_event(
context,
level="INFO",
task_id="task-1",
project_id="project-1",
operation="scan",
state_before="pending",
state_after="pending",
message="scan complete",
details={"count": 2},
)
second = append_task_event(context, level="WARNING", task_id="task-1", operation="rescan")
event_path = tmp_path / "tasks" / "task-1" / "events.jsonl"
lines = event_path.read_text(encoding="utf-8").splitlines()
decoded = json.loads(lines[0])
assert first["sequence"] == 1
assert second["sequence"] == 2
assert list(decoded) == [
"sequence",
"timestamp_utc",
"level",
"task_id",
"project_id",
"operation",
"state_before",
"state_after",
"error_id",
"message",
"details",
]
assert decoded["details"] == {"count": 2}
assert json.loads(lines[1])["operation"] == "rescan"
def test_tail_reader_handles_large_utf8_lines_and_sequence_without_full_text_read(tmp_path: Path) -> None:
path = tmp_path / "events.jsonl"
large_prefix = "汉" * 5000
records = [
json.dumps({"sequence": 40, "message": large_prefix}, ensure_ascii=False),
json.dumps({"sequence": 41, "message": "倒数第二条"}, ensure_ascii=False),
json.dumps({"sequence": 42, "message": "最后一条"}, ensure_ascii=False),
]
path.write_text("\n".join(records) + "\n", encoding="utf-8")
assert _tail_utf8_lines(path, 2) == tuple(records[-2:])
assert _next_event_sequence(path) == 43
def test_task_event_rotation_keeps_sequence_contiguous_across_segments(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setattr(logging_setup, "_MAX_EVENT_LOG_BYTES", 300)
context = configure_logging(tmp_path)
for index in range(12):
append_task_event(
context,
level="INFO",
task_id="rotating-task",
operation="stress_event",
message=f"event-{index}-" + "x" * 80,
)
current = tmp_path / "tasks" / "rotating-task" / "events.jsonl"
segments = [current.with_name(f"{current.name}.{index}") for index in range(5, 0, -1)]
segments.append(current)
records = [
json.loads(line)
for segment in segments
if segment.exists()
for line in segment.read_text(encoding="utf-8").splitlines()
]
assert [record["sequence"] for record in records] == list(range(7, 13))
assert _next_event_sequence(current) == 13
def test_exception_and_subprocess_helpers_record_traceback_and_streams(tmp_path: Path) -> None:
"""Unhandled details stay in the log, while the stable error ID is available to callers."""
context = configure_logging(tmp_path)
try:
raise RuntimeError("broken command")
except RuntimeError as error:
reported = context.report_exception("probe", error)
capture_subprocess_output(
context,
operation="probe-command",
returncode=4,
stdout="probe stdout",
stderr="probe stderr",
)
application_log = context.application_log_path.read_text(encoding="utf-8")
assert reported.error_id.startswith("DXT-")
assert "RuntimeError: broken command" in application_log
assert reported.error_id in application_log
assert "probe stdout" in application_log
assert "probe stderr" in application_log
assert "returncode=4" in application_log
def test_exception_hooks_log_worker_exception_with_error_id(tmp_path: Path) -> None:
"""A worker crash must be correlated in application.log rather than silently disappearing."""
context = configure_logging(tmp_path)
previous_sys_hook = sys.excepthook
previous_thread_hook = threading.excepthook
try:
install_exception_hooks(context)
def fail_worker() -> None:
raise RuntimeError("worker failure")
worker = threading.Thread(target=fail_worker, name="test-worker")
worker.start()
worker.join()
finally:
sys.excepthook = previous_sys_hook
threading.excepthook = previous_thread_hook
application_log = context.application_log_path.read_text(encoding="utf-8")
assert "worker failure" in application_log
assert "test-worker" in application_log
assert "DXT-" in application_log
@@ -0,0 +1,108 @@
from pathlib import Path
import sqlite3
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.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService, _quick_run_lease
from dx_productivity.trial_task_center.store import TaskStore
@pytest.fixture
def populated(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
data = tmp_path / 'data'
service = TaskCenterService(store, configure_logging(data))
task = service.create_task('Delete me')
other = service.create_task('Keep me')
project_file = tmp_path / 'keep.prj'
project_file.write_text('original engineering data', encoding='utf-8')
project = service.scan_projects(task.task_id, tmp_path)[0]
service.add_rule(task.task_id, 'OLD', 'NEW')
with store.transaction():
store._connection.execute('INSERT INTO attempts(project_id,attempt_number,probe_source,baseline_size,baseline_sha256,baseline_modified_ns,rules_json) VALUES(?,1,?,0,?,0,?)',
(project.project_id, 'probe', 'hash', '[]'))
store._connection.execute('INSERT INTO migration_recoveries(project_id,task_id,project_before,project_after,error_id,project_summary) VALUES(?,?,?,?,?,?)',
(project.project_id, task.task_id, 'pending', 'failed', 'error', 'history'))
yield store, service, task, other, project_file, data
store.close()
def test_permanent_delete_removes_relations_and_releases_name(populated):
store, service, task, other, project_file, data = populated
service.delete_task(task.task_id)
evidence = data / 'tasks' / task.task_id / 'evidence.txt'
evidence.parent.mkdir(parents=True, exist_ok=True)
evidence.write_text('retained diagnostic evidence', encoding='utf-8')
assert service.purge_task(task.task_id, confirmed=True) == task.task_id
with pytest.raises(TaskCenterError, match='unknown_task'):
store.get_task(task.task_id)
for table in ('rules', 'projects', 'attempts', 'migration_recoveries'):
assert store._connection.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0] == 0
assert store._connection.execute('PRAGMA foreign_key_check').fetchall() == []
assert service.get_task(other.task_id).name == 'Keep me'
assert service.create_task('Delete me').task_id != task.task_id
assert project_file.read_text(encoding='utf-8') == 'original engineering data'
assert evidence.read_text(encoding='utf-8') == 'retained diagnostic evidence'
def test_purge_requires_deleted_state_and_explicit_confirmation(populated):
store, service, task, _, _, _ = populated
with pytest.raises(TaskCenterError, match='task_not_deleted'):
service.purge_task(task.task_id, confirmed=True)
service.delete_task(task.task_id)
with pytest.raises(TaskCenterError, match='permanent_delete_confirmation'):
service.purge_task(task.task_id)
assert store.get_task(task.task_id).status is TaskStatus.DELETED
def test_failed_delete_rolls_back_all_child_deletions(populated):
store, service, task, _, _, _ = populated
service.delete_task(task.task_id)
store._connection.execute("CREATE TRIGGER reject_purge BEFORE DELETE ON projects BEGIN SELECT RAISE(ABORT, 'injected failure'); END")
with pytest.raises(sqlite3.IntegrityError, match='injected failure'):
store.purge_task(task.task_id)
for table in ('rules', 'projects', 'attempts', 'migration_recoveries'):
assert store._connection.execute(f'SELECT COUNT(*) FROM {table}').fetchone()[0] == 1
assert store.get_task(task.task_id).status is TaskStatus.DELETED
def test_purge_deleted_task_bypasses_execution_lease(populated):
store, service, task, _, _, data = populated
service.delete_task(task.task_id)
with _quick_run_lease(data):
assert service.purge_task(task.task_id, confirmed=True) == task.task_id
with pytest.raises(TaskCenterError, match='unknown_task'):
store.get_task(task.task_id)
@pytest.mark.parametrize('state', ['awaiting_native_replace', 'hard_failure', 'invalid_state'])
def test_unresolved_queue_evidence_is_retained_after_task_purge(populated, state):
store, service, task, _, project_file, data = populated
service.delete_task(task.task_id)
queue = data / 'quick-run'
queue.mkdir()
(queue / 'command.tsv').write_text(f'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\n{task.task_id}\tjob\t{project_file}\tOLD\tNEW\tpreserve\n', encoding='utf-8')
(queue / 'status.tsv').write_text(f'job_id\tstate\tcode\tmessage\njob\t{state}\t\tretained\n', encoding='utf-8')
assert service.purge_task(task.task_id, confirmed=True) == task.task_id
with pytest.raises(TaskCenterError, match='unknown_task'):
store.get_task(task.task_id)
assert (queue / 'command.tsv').is_file()
assert (queue / 'status.tsv').is_file()
assert project_file.read_text(encoding='utf-8') == 'original engineering data'
def test_deleted_completed_queue_can_be_viewed_and_purged(populated):
store, service, task, _, project_file, data = populated
service.set_project_selected(service.projects(task.task_id)[0].project_id, True)
queue = data / 'quick-run'
queue.mkdir()
(queue / 'command.tsv').write_text(f'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\n{task.task_id}\tjob\t{project_file}\tOLD\tNEW\tpreserve\n', encoding='utf-8')
(queue / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\njob\tno_match\t\tno changes\n', encoding='utf-8')
service.delete_task(task.task_id)
assert service.quick_run_progress(task.task_id).queue_complete
assert store.get_task(task.task_id).status is TaskStatus.DELETED
service.purge_task(task.task_id, confirmed=True)
assert (queue / 'command.tsv').is_file()
+980
View File
@@ -0,0 +1,980 @@
from __future__ import annotations
from datetime import datetime, timezone
from pathlib import Path
import json
import subprocess
from threading import Event, Thread
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.models import ProjectRecord, ProjectStatus, RuleRecord, TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
def _runtime_script(tmp_path: Path) -> Path:
script = tmp_path / "QuickPartReplace.vbs"
script.write_text("' fixture runtime\n", encoding="ascii")
return script
def _command_field(command_path: Path, name: str) -> str:
lines = command_path.read_text(encoding="utf-8").splitlines()
return lines[1].split("\t")[lines[0].split("\t").index(name)]
def _service(tmp_path: Path, runtime_script: Path) -> TaskCenterService:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
return TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage", script_source=runtime_script, run_token_factory=lambda: "run_abcdef"
),
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
)
def test_prepare_quick_run_exports_selected_available_projects_and_enabled_rules_as_utf8_jobs(tmp_path: Path) -> None:
"""A command that includes hidden rows can apply replacement to an unapproved project or rule."""
service = _service(tmp_path, _runtime_script(tmp_path))
task = service.create_task("Quick")
first_rule = service.add_rule(task.task_id, "OLD-1", "NEW-1")
disabled_rule = service.add_rule(task.task_id, "OLD-2", "NEW-2")
service.update_rule(disabled_rule.rule_id, old_part_number="OLD-2", new_part_number="NEW-2", enabled=False)
root = tmp_path / "projects"
root.mkdir()
(root / "first.prj").touch()
(root / "second.prj").touch()
projects = service.scan_projects(task.task_id, root)
service.set_project_selected(projects[0].project_id, True)
result = service.prepare_quick_run(task.task_id)
assert result.script_path.read_text(encoding="ascii") == "' fixture runtime\n"
assert result.command_path.read_bytes().decode("utf-8") == (
"task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode\r\n"
f"{task.task_id}\trun_abcdef_0\t{projects[0].path}\t{first_rule.old_part_number}\t{first_rule.new_part_number}\tpreserve\t\t1\tpreserve\r\n"
)
assert result.status_path == tmp_path / "storage" / "quick-run" / "status.tsv"
assert result.log_path == tmp_path / "storage" / "quick-run" / "quick-part-replace.log"
assert result.status_path.read_text(encoding="utf-8") == "job_id\tstate\tcode\tmessage\n"
assert result.log_path.is_file()
application_log = (tmp_path / "storage" / "logs" / "application.log").read_text(encoding="utf-8")
assert "quick_run_prepared" in application_log
def test_vbs_field_encoding_round_trips_unicode_delimiters_and_percent() -> None:
from dx_productivity.trial_task_center.quick_run import _decode_vbs_field, _encode_vbs_field
value = "中文%值\tline\r\nemoji:\U0001f600"
encoded = _encode_vbs_field(value)
assert encoded.isascii()
assert _decode_vbs_field(encoded) == value
def test_malformed_vbs_utf16_status_uses_stable_task_center_error(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import _read_status_details
status = tmp_path / "status.tsv"
status.write_text(
"job_id\tstate\tcode\tmessage\njob\trestored_ok\t\t%D800\n",
encoding="ascii",
)
with pytest.raises(TaskCenterError) as raised:
_read_status_details(status)
assert raised.value.code == "quick_run_status"
def test_prepare_quick_run_appends_its_log_and_uses_a_new_safe_run_token(tmp_path: Path) -> None:
"""Repreparing must not erase VBS evidence or reuse a snapshot filename from an earlier run."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
tokens = iter(("first", "second"))
runtime = _runtime_script(tmp_path)
preparer = QuickRunPreparer(
tmp_path,
script_source=runtime,
run_token_factory=lambda: next(tokens),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
first = preparer.prepare("task", (project,), (rule,))
first.log_path.write_text("vbs evidence\n", encoding="utf-8")
second = preparer.prepare("task", (project,), (rule,))
assert "vbs evidence" in second.log_path.read_text(encoding="utf-8")
assert _command_field(second.command_path, "job_id") == "second_0"
def test_prepare_quick_run_does_not_overwrite_an_awaiting_native_replace_status(tmp_path: Path) -> None:
"""A second export during manual replacement would orphan the VBS snapshot and its pending job."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), run_token_factory=lambda: "next")
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
root = tmp_path / "quick-run"
root.mkdir()
command = root / "command.tsv"
status = root / "status.tsv"
command.write_text("old command\n", encoding="utf-8")
status.write_bytes(
"job_id\tstate\tcode\tmessage\r\npending_job\tawaiting_native_replace\t\tmanual selection\r\n".encode("utf-8-sig")
)
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_pending"
assert command.read_text(encoding="utf-8") == "old command\n"
assert "quick_run_pending" in (root / "quick-part-replace.log").read_text(encoding="utf-8")
def test_quick_run_queue_isolated_by_task_id_even_when_paths_and_rules_match(tmp_path: Path) -> None:
"""A completed queue for one task must be archived before a same-shaped task starts."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
import subprocess
calls: list[tuple[str, ...]] = []
opened: list[Path] = []
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
assert timeout == 150
calls.append(command)
command_path = tmp_path / "storage" / "quick-run" / "command.tsv"
job_id = _command_field(command_path, "job_id")
(tmp_path / "storage" / "quick-run" / "status.tsv").write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tSnapshot captured.\n"
f"{job_id}\trestored_ok\t\tAutomatic replacement verified.\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=opened.append,
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
script_source=_runtime_script(tmp_path),
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
),
)
root = tmp_path / "projects"
root.mkdir()
(root / "same.prj").touch()
first = service.create_task("First")
first_project = service.scan_projects(first.task_id, root)[0]
service.set_project_selected(first_project.project_id, True)
service.add_rule(first.task_id, "OLD-1", "NEW-1")
second = service.create_task("Second")
second_project = service.scan_projects(second.task_id, root)[0]
service.set_project_selected(second_project.project_id, True)
service.add_rule(second.task_id, "OLD-1", "NEW-1")
service.execute_quick_run(first.task_id)
assert service.quick_run_phase(first.task_id) == "complete"
assert service.get_task(first.task_id).status is TaskStatus.COMPLETED
assert service.projects(first.task_id)[0].status is ProjectStatus.COMPLETED
assert service.open_evidence(first.task_id, first_project.project_id) == tmp_path / "storage" / "quick-run"
assert opened == [tmp_path / "storage" / "quick-run"]
assert service.quick_run_phase(second.task_id) == "selection"
assert service.execute_quick_run(second.task_id).state == "restored_ok"
assert len(calls) == 2
history = tmp_path / "storage" / "quick-run-history"
assert len(tuple(history.glob("obsolete-*"))) == 1
archived_evidence = service.open_evidence(first.task_id, first_project.project_id)
assert archived_evidence.parent == history
assert archived_evidence.name.startswith("obsolete-")
def test_service_rejects_concurrent_quick_run_execution(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
started = Event()
release = Event()
def blocking_runner(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
started.set()
release.wait(5)
root = tmp_path / "storage" / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
(root / "status.tsv").write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tcaptured\n"
f"{job_id}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
quick_run_preparer=QuickRunPreparer(
tmp_path / "storage",
script_source=_runtime_script(tmp_path),
process_runner=blocking_runner,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
),
)
project_root = tmp_path / "projects"
project_root.mkdir()
(project_root / "one.prj").touch()
task = service.create_task("Concurrent")
project = service.scan_projects(task.task_id, project_root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD", "NEW")
result: list[object] = []
worker = Thread(target=lambda: result.append(service.execute_quick_run(task.task_id)))
worker.start()
try:
assert started.wait(2)
with pytest.raises(TaskCenterError) as raised:
service.execute_quick_run(task.task_id)
assert raised.value.code == "quick_run_busy"
with pytest.raises(TaskCenterError) as delete_error:
service.delete_task(task.task_id)
assert delete_error.value.code == "quick_run_busy"
with pytest.raises(TaskCenterError) as rule_error:
service.add_rule(task.task_id, "OTHER", "TARGET")
assert rule_error.value.code == "quick_run_busy"
finally:
release.set()
worker.join(5)
assert len(result) == 1
def test_prepare_quick_run_rejects_malformed_status_without_overwriting_command(tmp_path: Path) -> None:
"""Treating a damaged status file as empty would overwrite an unknown operator state."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
root = tmp_path / "quick-run"
root.mkdir()
command = root / "command.tsv"
command.write_text("old command\n", encoding="utf-8")
(root / "status.tsv").write_text("not a status file\n", encoding="utf-8")
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_status"
assert command.read_text(encoding="utf-8") == "old command\n"
assert "quick_run_status_invalid" in (root / "quick-part-replace.log").read_text(encoding="utf-8")
def test_service_default_quick_run_uses_its_logging_data_root(tmp_path: Path) -> None:
"""The Python worker now passes this custom root to VBS instead of warning about a default-root mismatch."""
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "selected-data-root"),
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
)
task = service.create_task("Quick")
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, "OLD", "NEW")
result = service.prepare_quick_run(task.task_id)
assert result.script_path.parent == tmp_path / "selected-data-root" / "quick-run"
assert result.vbs_root_compatible
application_log = (tmp_path / "selected-data-root" / "logs" / "application.log").read_text(encoding="utf-8")
assert "quick_run_vbs_root_mismatch" not in application_log
def test_prepare_quick_run_rejects_tab_or_newline_fields_before_writing_command(tmp_path: Path) -> None:
"""A TSV field containing a record delimiter could turn one approved mapping into extra commands."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD\tINJECTED", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_field"
assert not (tmp_path / "quick-run" / "command.tsv").exists()
def test_prepare_quick_run_reports_a_missing_runtime_resource(tmp_path: Path) -> None:
"""An empty frozen resource directory must fail before an operator receives a non-runnable script path."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=tmp_path / "missing.vbs")
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.prepare("task", (project,), (rule,))
assert raised.value.code == "quick_run_script_missing"
def test_execute_quick_step_launches_automatic_runtime_and_reports_completion(tmp_path: Path) -> None:
"""The GUI click must pass the hidden helper entry and finish restoration in one process."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _native_helper_launch_arguments
calls: list[tuple[tuple[str, ...], int]] = []
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
calls.append((command, timeout))
status = tmp_path / "quick-run" / "status.tsv"
job_id = _command_field(tmp_path / "quick-run" / "command.tsv", "job_id")
status.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tSnapshot captured.\n"
f"{job_id}\trestored_ok\t\tReplaced and verified 2 current-sheet matches.\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
run_token_factory=lambda: "one_click",
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
result = preparer.execute_step("task", (project,), (rule,))
assert calls == [
((
"C:\\Windows\\SysWOW64\\cscript.exe",
"//nologo",
str(result.script_path),
str(tmp_path / "quick-run"),
*_native_helper_launch_arguments(),
_command_field(result.command_path, "job_id"),
), 150)
]
assert result.state == "restored_ok"
assert result.message == "Replaced and verified 2 current-sheet matches."
def test_execute_quick_step_accepts_capture_and_restore_rows_from_one_worker(tmp_path: Path) -> None:
"""Automatic VBS appends both durable transitions during the same invocation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
command_bytes: list[bytes] = []
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
command_path = tmp_path / "quick-run" / "command.tsv"
status_path = tmp_path / "quick-run" / "status.tsv"
command_bytes.append(command_path.read_bytes())
job_id = _command_field(command_path, "job_id")
existing = status_path.read_text(encoding="utf-8")
status_path.write_text(
existing
+ f"{job_id}\tawaiting_native_replace\t\tcaptured\n"
+ f"{job_id}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
runtime = _runtime_script(tmp_path)
preparer = QuickRunPreparer(
tmp_path,
script_source=runtime,
run_token_factory=lambda: "stable_run",
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
first = preparer.execute_step("task", (project,), (rule,))
assert first.state == "restored_ok"
assert len(command_bytes) == 1
def test_execute_quick_step_keeps_the_vbs_attach_failure_retriable(tmp_path: Path) -> None:
"""VBS exit 2 without a status row means DxDesigner was unavailable, not an uncertain mutation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def attach_failure(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
return subprocess.CompletedProcess(command, 2, "", "DxDesigner unavailable")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=attach_failure,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as retry:
preparer.execute_step("task", (project,), (rule,))
assert calls == 2
assert raised.value.code == "quick_run_session"
assert retry.value.code == "quick_run_session"
assert not (tmp_path / "quick-run" / "uncertain.flag").exists()
assert "DxDesigner unavailable" in (tmp_path / "quick-run" / "quick-part-replace.log").read_text(encoding="utf-8")
def test_execute_quick_step_keeps_a_pre_mutation_vbs_failure_retriable(tmp_path: Path) -> None:
"""Exit 3 before a VBS job is selected cannot have modified the current sheet."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def wrong_project(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
return subprocess.CompletedProcess(command, 3, "", "The open project has no pending quick-run rule")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=wrong_project,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as first:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as retry:
preparer.execute_step("task", (project,), (rule,))
assert calls == 2
assert first.value.code == "quick_run_session"
assert retry.value.code == "quick_run_session"
assert not (tmp_path / "quick-run" / "uncertain.flag").exists()
def test_execute_quick_step_locks_a_pre_mutation_exit_with_a_status_change(tmp_path: Path) -> None:
"""An exit 3 accompanied by a row is contradictory evidence and must not be retried."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def contradictory_result(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
status = tmp_path / "quick-run" / "status.tsv"
job_id = _command_field(tmp_path / "quick-run" / "command.tsv", "job_id")
status.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tunexpected selection\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 3, "", "pre-mutation failure")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=contradictory_result,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert raised.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_current_phase_is_complete_when_every_matching_job_was_restored(tmp_path: Path) -> None:
"""A fully restored durable queue must not offer a new selection step."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), run_token_factory=lambda: "complete")
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
handoff = preparer.prepare("task", (project,), (rule,))
job_id = _command_field(handoff.command_path, "job_id")
handoff.status_path.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\trestored_ok\t\trestored\n",
encoding="utf-8",
)
assert preparer.current_phase("task", (project,), (rule,)) == "complete"
def test_verified_rollback_clears_native_mutation_evidence(tmp_path: Path) -> None:
"""A queue may be replaced after VBS proves native Undo restored the exact snapshot."""
from dx_productivity.trial_task_center.quick_run import _queue_has_mutation_evidence
root = tmp_path / "quick-run"
root.mkdir()
report = root / "snapshot-job.tsv.native.json"
report.write_text('{"stage":"native_replace_verified","ok":true}', encoding="utf-8")
assert _queue_has_mutation_evidence(root)
(root / "snapshot-job.tsv.native.rolled-back").write_text("verified\n", encoding="utf-8")
assert not _queue_has_mutation_evidence(root)
def test_preflight_hard_failure_retries_only_its_job_in_a_partly_completed_queue(tmp_path: Path) -> None:
"""Mutation evidence from completed jobs must not block a preflight-only failed job."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def complete_retry(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
del command, timeout
calls += 1
root = tmp_path / "quick-run"
lines = (root / "command.tsv").read_text(encoding="utf-8").splitlines()
second_job = lines[2].split("\t")[1]
status = root / "status.tsv"
assert status.read_text(encoding="utf-8").splitlines()[-1].split("\t")[:2] == [
second_job,
"awaiting_native_replace",
]
status.write_text(
status.read_text(encoding="utf-8") + f"{second_job}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess((), 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
run_token_factory=lambda: "mixed",
process_runner=complete_retry,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
first = ProjectRecord("p1", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
second = ProjectRecord("p2", "task", "Two", Path("C:/two.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
handoff = preparer.prepare("task", (first, second), (rule,))
command_lines = handoff.command_path.read_text(encoding="utf-8").splitlines()
first_job = command_lines[1].split("\t")[1]
second_job = command_lines[2].split("\t")[1]
handoff.status_path.write_text(
"job_id\tstate\tcode\tmessage\n"
f"{first_job}\tawaiting_native_replace\t\tcaptured\n"
f"{first_job}\trestored_ok\t\tverified\n"
f"{second_job}\tawaiting_native_replace\t\tcaptured\n"
f"{second_job}\thard_failure\t1\tcursor API failed\n",
encoding="utf-8",
)
Path(str(tmp_path / "quick-run" / f"snapshot-{first_job}.tsv") + ".native.json").write_text(
'{"stage":"native_replace_verified","ok":true}', encoding="utf-8"
)
Path(str(tmp_path / "quick-run" / f"snapshot-{second_job}.tsv") + ".native.json").write_text(
'{"stage":"preflight","ok":false}', encoding="utf-8"
)
result = preparer.execute_step("task", (first, second), (rule,))
assert calls == 1
assert result.state == "restored_ok"
states = [(job_id, state) for job_id, state, _, _ in __import__(
"dx_productivity.trial_task_center.quick_run", fromlist=["_read_status_details"]
)._read_status_details(handoff.status_path)]
assert states == [
(first_job, "awaiting_native_replace"),
(first_job, "restored_ok"),
(second_job, "awaiting_native_replace"),
(second_job, "restored_ok"),
]
def test_mutation_stage_hard_failure_still_blocks_a_partly_completed_queue(tmp_path: Path) -> None:
"""A failed job with possible native writes must never be made pending automatically."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
run_token_factory=lambda: "mixed",
process_runner=lambda command, timeout: pytest.fail("unsafe queue was executed"),
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
first = ProjectRecord("p1", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
second = ProjectRecord("p2", "task", "Two", Path("C:/two.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
handoff = preparer.prepare("task", (first, second), (rule,))
command_lines = handoff.command_path.read_text(encoding="utf-8").splitlines()
first_job = command_lines[1].split("\t")[1]
second_job = command_lines[2].split("\t")[1]
original_status = (
"job_id\tstate\tcode\tmessage\n"
f"{first_job}\tawaiting_native_replace\t\tcaptured\n"
f"{first_job}\trestored_ok\t\tverified\n"
f"{second_job}\tawaiting_native_replace\t\tcaptured\n"
f"{second_job}\thard_failure\t1\tnative write failed\n"
)
handoff.status_path.write_text(original_status, encoding="utf-8")
Path(str(tmp_path / "quick-run" / f"snapshot-{first_job}.tsv") + ".native.json").write_text(
'{"stage":"native_replace_verified","ok":true}', encoding="utf-8"
)
Path(str(tmp_path / "quick-run" / f"snapshot-{second_job}.tsv") + ".native.json").write_text(
'{"stage":"native_replace_started","ok":false}', encoding="utf-8"
)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (first, second), (rule,))
assert raised.value.code == "quick_run_execution"
assert handoff.status_path.read_text(encoding="utf-8") == original_status
def test_execute_quick_step_locks_a_zero_exit_without_status(tmp_path: Path) -> None:
"""A successful process exit without an expected VBS status can still hide an uncertain native mutation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def no_status(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=no_status,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as first:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as second:
preparer.execute_step("task", (project,), (rule,))
assert calls == 1
assert first.value.code == "quick_run_uncertain"
assert second.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_execute_quick_step_rejects_an_appended_status_for_an_unrelated_job(tmp_path: Path) -> None:
"""Another Task Center instance must not be able to satisfy this execution with its status row."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
status = tmp_path / "quick-run" / "status.tsv"
status.write_text(
status.read_text(encoding="utf-8") + "other_job\tawaiting_native_replace\t\tunrelated\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert raised.value.code == "quick_run_uncertain"
@pytest.mark.parametrize("report", [None, '{"stage":"native_replace_started","transaction":{}}', '{"stage":"preflight","ok":false}'])
def test_native_failure_exposes_recovery_unless_preflight_proves_no_mutation(tmp_path: Path, report) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def native_failure(command, timeout):
root = tmp_path / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
(root / "status.tsv").write_text(
"job_id\tstate\tcode\tmessage\n"
f"{job_id}\tawaiting_native_replace\t\tstarted\n"
f"{job_id}\thard_failure\t1\tnative failure\n", encoding="utf-8")
if report is not None:
(root / f"snapshot-{job_id}.tsv.native.json").write_text(report, encoding="utf-8")
return subprocess.CompletedProcess(command, 1, "", "native failure")
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), process_runner=native_failure,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
safe = report is not None and 'preflight' in report
assert raised.value.code == ("quick_run_preflight" if safe else "quick_run_uncertain")
assert (tmp_path / "quick-run/uncertain.flag").exists() is not safe
@pytest.mark.parametrize("exit_code", [0, 91])
def test_worker_exit_without_native_completion_requires_reconciliation(tmp_path: Path, exit_code) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def interrupted_worker(command, timeout):
root = tmp_path / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
(root / "status.tsv").write_text("job_id\tstate\tcode\tmessage\n" +
f"{job_id}\tawaiting_native_replace\t\tstarted\n", encoding="utf-8")
return subprocess.CompletedProcess(command, exit_code, "", "")
preparer = QuickRunPreparer(tmp_path, script_source=_runtime_script(tmp_path), process_runner=interrupted_worker,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"))
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert raised.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run/uncertain.flag").is_file()
def test_execute_quick_step_blocks_retry_after_a_worker_timeout(tmp_path: Path) -> None:
"""A killed COM worker may have changed the design and must require manual reconciliation."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def time_out(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
raise subprocess.TimeoutExpired(command, timeout)
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=time_out,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError):
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (rule,))
assert calls == 1
assert raised.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_execute_quick_step_keeps_timeout_lock_when_the_queue_input_changes(tmp_path: Path) -> None:
"""Changing a rule after a timeout must not turn an uncertain native mutation into a fresh queue."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def time_out(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
calls += 1
raise subprocess.TimeoutExpired(command, timeout)
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=time_out,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
first_rule = RuleRecord("rule-1", "task", 0, "OLD", "NEW", True)
changed_rule = RuleRecord("rule-2", "task", 0, "OTHER", "NEWER", True)
with pytest.raises(TaskCenterError):
preparer.execute_step("task", (project,), (first_rule,))
with pytest.raises(TaskCenterError) as raised:
preparer.execute_step("task", (project,), (changed_rule,))
assert calls == 1
assert raised.value.code == "quick_run_uncertain"
def test_execute_quick_step_marks_two_appended_status_rows_as_uncertain(tmp_path: Path) -> None:
"""A valid worker row plus a concurrent append leaves correlation ambiguous and must lock execution."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def append_two_rows(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
del timeout
calls += 1
root = tmp_path / "quick-run"
job_id = _command_field(root / "command.tsv", "job_id")
status = root / "status.tsv"
status.write_text(
status.read_text(encoding="utf-8")
+ f"{job_id}\tawaiting_native_replace\t\tselected\n"
+ "other_job\thard_failure\t\tconcurrent\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=append_two_rows,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError) as first:
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError) as second:
preparer.execute_step("task", (project,), (rule,))
assert calls == 1
assert first.value.code == "quick_run_uncertain"
assert second.value.code == "quick_run_uncertain"
assert (tmp_path / "quick-run" / "uncertain.flag").is_file()
def test_verified_native_rollback_stops_without_uncertain_lock(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def rolled_back(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
root = tmp_path / "quick-run"
job_id = command[-1]
snapshot = root / f"snapshot-{job_id}.tsv"
snapshot.write_text("snapshot", encoding="utf-8")
snapshot.with_suffix(".tsv.native.json").write_text(
json.dumps({"stage": "native_replace_verified", "ok": False}), encoding="utf-8"
)
Path(str(snapshot) + ".native.rolled-back").write_text(
"native replacement rollback verified\n", encoding="utf-8"
)
with (root / "status.tsv").open("a", encoding="utf-8") as stream:
stream.write(f"{job_id}\tawaiting_native_replace\t\tstarted\n")
return subprocess.CompletedProcess(command, 1, "", "validation failed")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=rolled_back,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError, match="quick_run_rollback_verified") as raised:
preparer.execute_step("task", (project,), (rule,))
assert "已恢复到替换前状态" in raised.value.message
assert not (tmp_path / "quick-run/uncertain.flag").exists()
assert "rollback_verified" in (tmp_path / "quick-run/status.tsv").read_text(encoding="utf-8")
def test_verified_rollback_terminal_failure_can_be_retried_without_recovery_lock(tmp_path: Path) -> None:
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
calls = 0
def worker(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
nonlocal calls
del timeout
calls += 1
root = tmp_path / "quick-run"
job_id = command[-1]
with (root / "status.tsv").open("a", encoding="utf-8") as stream:
if calls == 1:
stream.write(f"{job_id}\tawaiting_native_replace\t\tstarted\n")
stream.write(f"{job_id}\thard_failure\trollback_verified\trolled back\n")
snapshot = root / f"snapshot-{job_id}.tsv"
snapshot.write_text("snapshot", encoding="utf-8")
snapshot.with_suffix(".tsv.native.json").write_text(
json.dumps({"stage": "native_replace_verified", "ok": False}), encoding="utf-8"
)
Path(str(snapshot) + ".native.rolled-back").write_text(
"native replacement rollback verified\n", encoding="utf-8"
)
return subprocess.CompletedProcess(command, 1, "", "validation failed")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=worker,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
project = ProjectRecord("project", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
with pytest.raises(TaskCenterError, match="quick_run_rollback_verified"):
preparer.execute_step("task", (project,), (rule,))
with pytest.raises(TaskCenterError, match="quick_run_rollback_verified"):
preparer.execute_step("task", (project,), (rule,))
assert calls == 2
assert not (tmp_path / "quick-run/uncertain.flag").exists()
def test_resolve_cscript_requires_syswow64_on_a_64_bit_host(tmp_path: Path) -> None:
"""Falling back to a 64-bit script host cannot attach reliably to 32-bit EE 7.9.5 COM."""
from dx_productivity.trial_task_center.quick_run import _resolve_cscript
system32 = tmp_path / "System32"
system32.mkdir()
(system32 / "cscript.exe").touch()
with pytest.raises(TaskCenterError) as raised:
_resolve_cscript(tmp_path, is_64_bit=True)
assert raised.value.code == "quick_run_cscript"
def test_restored_step_reports_the_next_project_that_must_be_opened(tmp_path: Path) -> None:
"""A batch queue must tell the operator which project to open before launching its next rule."""
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
def run_script(command: tuple[str, ...], timeout: int) -> subprocess.CompletedProcess[str]:
del timeout
command_path = tmp_path / "quick-run" / "command.tsv"
status_path = tmp_path / "quick-run" / "status.tsv"
first_job = _command_field(command_path, "job_id")
status_path.write_text(
status_path.read_text(encoding="utf-8")
+ f"{first_job}\tawaiting_native_replace\t\tcaptured\n"
+ f"{first_job}\trestored_ok\t\tverified\n",
encoding="utf-8",
)
return subprocess.CompletedProcess(command, 0, "", "")
preparer = QuickRunPreparer(
tmp_path,
script_source=_runtime_script(tmp_path),
process_runner=run_script,
cscript_resolver=lambda: Path("C:/Windows/SysWOW64/cscript.exe"),
)
first = ProjectRecord("p1", "task", "One", Path("C:/one.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
second = ProjectRecord("p2", "task", "Two", Path("C:/two.prj"), Path("C:/"), True, True, ProjectStatus.PENDING, 0)
rule = RuleRecord("rule", "task", 0, "OLD", "NEW", True)
result = preparer.execute_step("task", (first, second), (rule,))
assert result.state == "restored_ok"
assert result.next_project_path == second.path
assert result.next_old_part_number == "OLD"
assert result.next_new_part_number == "NEW"
+288
View File
@@ -0,0 +1,288 @@
import json
from pathlib import Path
import subprocess
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _read_commands, _read_status_details
from dx_productivity.trial_task_center.recovery import _is_link_or_reparse, _recovery_hashes, recover
def test_link_detection_does_not_require_path_is_junction():
path = SimpleNamespace(lstat=lambda: SimpleNamespace(st_mode=0, st_file_attributes=0))
assert not _is_link_or_reparse(path)
def test_locked_recovery_files_return_stable_recovery_error(tmp_path, monkeypatch):
import dx_productivity.trial_task_center.recovery as recovery_module
def locked(_root):
raise PermissionError('locked')
monkeypatch.setattr(recovery_module, '_hashes', locked)
with pytest.raises(TaskCenterError) as raised:
_recovery_hashes(tmp_path)
assert raised.value.code == 'quick_run_recovery'
assert '占用' in raised.value.message
@pytest.fixture
def interrupted(tmp_path):
project = tmp_path / 'project' / 'one.prj'
project.parent.mkdir()
project.write_text('project')
script = tmp_path / 'runtime.vbs'
script.write_text('fixture runtime')
root = tmp_path / 'data'
preparer = QuickRunPreparer(root, script_source=script, run_token_factory=lambda: 'first',
cscript_resolver=lambda: Path('cscript.exe'))
projects = (SimpleNamespace(path=project, selected=True, available=True),)
rules = (SimpleNamespace(old_part_number='OLD', new_part_number='NEW', enabled=True),)
handoff = preparer.prepare('task', projects, rules, copy_part_number_to_value=True)
job = _read_commands(handoff.command_path)[0][1]
snapshot = handoff.command_path.parent / f'snapshot-{job}.tsv'
snapshot.write_text(f'M\t{project}\tOLD\tNEW\tA:1\tpart_label\nC\tuid\tR1\t0\t0\t0\t1\tpins\n', encoding='utf-8')
metadata, components = read_snapshot(snapshot)
report = {'stage': 'native_replace_verified', 'transaction': transaction_binding(
snapshot, metadata, components, ['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol')}
snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(report), encoding='utf-8')
handoff.status_path.write_text('job_id\tstate\tcode\tmessage\n' + job + '\tawaiting_native_replace\t\tstarted\n', encoding='utf-8')
lock = handoff.command_path.parent / 'uncertain.flag'
lock.write_text('old timeout')
return SimpleNamespace(preparer=preparer, root=root, projects=projects, rules=rules, snapshot=snapshot,
job=job, handoff=handoff, lock=lock, report=report)
def invoke(fixture, **kwargs):
return recover(fixture.preparer, 'task', fixture.projects, fixture.rules,
copy_part_number_to_value=True, confirmed=True, **kwargs)
def worker_result(fixture, state='restored_ok', job=None, code=0):
def run(command, timeout):
worker = Path(command[3])
assert worker != fixture.lock.parent
assert (worker / 'recovery.request').read_text() == fixture.job
assert timeout == 150
assert fixture.lock.exists()
(worker / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n' + (job or fixture.job) + '\t' + state + '\t\tverified\n')
return subprocess.CompletedProcess(command, code, '', '')
return run
@pytest.mark.parametrize('hard_failure', [False, True])
def test_legacy_interruption_without_flag_can_be_reconciled_only_with_bound_evidence(interrupted, hard_failure):
interrupted.lock.unlink()
if hard_failure:
with interrupted.handoff.status_path.open('a', encoding='utf-8') as stream:
stream.write(interrupted.job + '\thard_failure\t1\tnative write failed\n')
assert interrupted.preparer.has_interrupted('task')
assert not interrupted.preparer.has_interrupted('other-task')
interrupted.preparer._process_runner = worker_result(interrupted, 'retry_ready')
result = invoke(interrupted)
assert result.state == 'retry_ready'
assert not interrupted.lock.exists()
assert not interrupted.preparer.has_interrupted('task')
def test_preflight_failure_without_transaction_does_not_offer_unsafe_recovery(interrupted):
interrupted.lock.unlink()
with interrupted.handoff.status_path.open('a', encoding='utf-8') as stream:
stream.write(interrupted.job + '\thard_failure\t1\tmissing target\n')
interrupted.snapshot.with_suffix('.tsv.native.json').write_text('{"stage":"preflight","ok":false}', encoding='utf-8')
assert not interrupted.preparer.has_interrupted('task')
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert not interrupted.lock.exists()
def test_recovery_requires_explicit_confirmation(interrupted):
with pytest.raises(TaskCenterError, match='quick_run_recovery_confirmation'):
recover(interrupted.preparer, 'task', interrupted.projects, interrupted.rules)
assert interrupted.lock.exists()
def test_verified_recovery_preserves_evidence_and_commits_once(interrupted):
interrupted.preparer._process_runner = worker_result(interrupted)
snapshot = interrupted.snapshot.read_bytes()
result = invoke(interrupted)
assert result.state == 'restored_ok'
assert result.next_project_path is None
assert not interrupted.lock.exists()
assert interrupted.snapshot.read_bytes() == snapshot
assert _read_status_details(interrupted.handoff.status_path)[-1][1] == 'restored_ok'
audit = next((interrupted.root / 'quick-run-history').glob('recovery-*'))
assert (audit / 'resolved-uncertain.flag').read_text() == 'old timeout'
assert (audit / 'evidence-before' / interrupted.snapshot.name).read_bytes() == snapshot
with pytest.raises(TaskCenterError):
invoke(interrupted)
def test_r12_part_number_queue_keeps_recorded_policy_during_recovery(interrupted):
command_path = interrupted.handoff.command_path
lines = [line.split('\t') for line in command_path.read_text(encoding='utf-8').splitlines()]
for column in ('value_mode', 'base_value_mode'):
lines[1][lines[0].index(column)] = 'part_number'
command_path.write_text('\n'.join('\t'.join(line) for line in lines) + '\n', encoding='utf-8')
interrupted.snapshot.write_text(
interrupted.snapshot.read_text(encoding='utf-8').replace('\tpart_label\n', '\tpart_number\n'),
encoding='utf-8',
)
metadata, components = read_snapshot(interrupted.snapshot)
report = {'stage': 'native_replace_verified', 'transaction': transaction_binding(
interrupted.snapshot, metadata, components,
['library', 'NEW', 'symbol', '', 'cap', 'label'], 'symbol')}
interrupted.snapshot.with_suffix('.tsv.native.json').write_text(json.dumps(report), encoding='utf-8')
def worker(command, timeout):
worker_root = Path(command[3])
assert '\tpart_number\t' in (worker_root / 'command.tsv').read_text(encoding='utf-8')
return worker_result(interrupted)(command, timeout)
interrupted.preparer._process_runner = worker
result = invoke(interrupted)
assert result.state == 'restored_ok'
assert result.next_project_path is None
assert interrupted.preparer.progress(
'task', interrupted.projects, interrupted.rules, copy_part_number_to_value=True
).queue_complete
def test_page_addressed_recovery_keeps_the_original_sheet_binding(interrupted):
project = interrupted.projects[0].path
interrupted.handoff.command_path.write_text(
'task_id\tjob_id\tproject_path\tschematic_name\tsheet_number\told_part\tnew_part\tvalue_mode\n'
f'task\t{interrupted.job}\t{project}\tA\t1\tOLD\tNEW\tpart_label\n',
encoding='utf-8',
)
(interrupted.handoff.command_path.parent / 'sheets.tsv').write_text(
'project_path\tschematic_name\tsheet_number\n'
f'{project}\tA\t1\n',
encoding='utf-8',
)
def worker(command, timeout):
worker_root = Path(command[3])
header = (worker_root / 'command.tsv').read_text(encoding='utf-8').splitlines()[0].split('\t')
row = (worker_root / 'command.tsv').read_text(encoding='utf-8').splitlines()[1].split('\t')
assert row[header.index('schematic_name')] == 'A'
assert row[header.index('sheet_number')] == '1'
assert (worker_root / 'sheets.tsv').is_file()
(worker_root / 'status.tsv').write_text(
f'job_id\tstate\tcode\tmessage\n{interrupted.job}\trestored_ok\t\tverified\n',
encoding='utf-8',
)
return subprocess.CompletedProcess(command, 0, '', '')
interrupted.preparer._process_runner = worker
result = invoke(interrupted)
assert result.state == 'restored_ok'
assert result.next_project_path is None
def test_unsaved_recovery_creates_fresh_job_without_replacing(interrupted):
interrupted.preparer._process_runner = worker_result(interrupted, 'retry_ready')
result = invoke(interrupted)
assert result.state == 'retry_ready'
assert result.next_project_path == interrupted.projects[0].path
assert _read_commands(interrupted.handoff.command_path)[0][1] != interrupted.job
assert _read_status_details(interrupted.handoff.status_path) == ()
assert interrupted.snapshot.exists()
@pytest.mark.parametrize(('state', 'job', 'code'), [('hard_failure', None, 1), ('restored_ok', 'foreign', 0),
('awaiting_native_replace', None, 0), ('restored_ok', None, 2)])
def test_uncorrelated_or_failed_recovery_never_unlocks(interrupted, state, job, code):
before = interrupted.handoff.status_path.read_bytes()
interrupted.preparer._process_runner = worker_result(interrupted, state, job, code)
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.exists()
assert interrupted.handoff.status_path.read_bytes() == before
def test_recovery_timeout_keeps_old_lock(interrupted):
def timeout(command, seconds):
raise subprocess.TimeoutExpired(command, seconds)
interrupted.preparer._process_runner = timeout
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.read_text() == 'old timeout'
def test_snapshot_binding_mismatch_prevents_worker_start(interrupted):
interrupted.snapshot.write_text(interrupted.snapshot.read_text() + '\n')
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.exists()
assert not (interrupted.root / 'quick-run-history').exists()
def test_concurrent_evidence_change_does_not_commit(interrupted):
worker = worker_result(interrupted)
def change(command, seconds):
result = worker(command, seconds)
interrupted.lock.write_text('new protection')
return result
interrupted.preparer._process_runner = change
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.read_text() == 'new protection'
def test_other_pending_job_prevents_global_unlock(interrupted):
with interrupted.handoff.status_path.open('a') as stream:
stream.write('other-job\thard_failure\t\tunknown\n')
with pytest.raises(TaskCenterError):
invoke(interrupted)
assert interrupted.lock.exists()
def test_failed_commit_restores_status_and_lock(interrupted, monkeypatch):
from dx_productivity.trial_task_center import recovery
interrupted.preparer._process_runner = worker_result(interrupted)
original = interrupted.handoff.status_path.read_bytes()
real_replace = recovery.os.replace
def fail_unlock(source, target):
if Path(source) == interrupted.lock:
raise PermissionError('locked')
return real_replace(source, target)
monkeypatch.setattr(recovery.os, 'replace', fail_unlock)
with pytest.raises(PermissionError):
invoke(interrupted)
assert interrupted.lock.exists()
assert interrupted.handoff.status_path.read_bytes() == original
@pytest.mark.parametrize('initial', ['ready', 'paused', 'failed'])
def test_service_recovery_updates_queue_and_database(interrupted, initial):
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
store = TaskStore(interrupted.root / 'task-center.db')
service = TaskCenterService(store, configure_logging(interrupted.root), quick_run_preparer=interrupted.preparer)
task = service.create_task('Interrupted')
service.set_copy_part_number_to_value(task.task_id, True)
projects = service.scan_projects(task.task_id, interrupted.projects[0].path.parent)
service.set_project_selected(projects[0].project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
command_path = interrupted.handoff.command_path
command_path.write_text(command_path.read_text().replace('task\t', task.task_id + '\t'), encoding='utf-8')
if store.get_task(task.task_id).status is TaskStatus.DRAFT:
store.set_task_status(task.task_id, TaskStatus.READY)
if initial == 'paused':
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_task_status(task.task_id, TaskStatus.PAUSED)
elif initial == 'failed':
store.set_task_status(task.task_id, TaskStatus.FAILED)
interrupted.preparer._process_runner = worker_result(interrupted)
result = service.recover_quick_run(task.task_id, confirmed=True)
assert result.state == 'restored_ok'
assert store.get_task(task.task_id).status is TaskStatus.COMPLETED
assert service.quick_run_progress(task.task_id).queue_complete
assert not service.has_interrupted_quick_run(task.task_id)
+74
View File
@@ -0,0 +1,74 @@
from __future__ import annotations
import os
from pathlib import Path
from dx_productivity.trial_task_center.retention import (
maintain_quick_run_storage,
rotate_text_log,
)
def test_log_rotation_preserves_three_newest_complete_segments(tmp_path: Path) -> None:
log = tmp_path / "quick-part-replace.log"
for text in ("first", "second", "third", "fourth"):
log.write_text(text * 4, encoding="utf-8")
assert rotate_text_log(log, max_bytes=10, backup_count=3)
assert not log.exists()
assert log.with_name(f"{log.name}.1").read_text(encoding="utf-8") == "fourth" * 4
assert log.with_name(f"{log.name}.2").read_text(encoding="utf-8") == "third" * 4
assert log.with_name(f"{log.name}.3").read_text(encoding="utf-8") == "second" * 4
def test_history_retention_removes_only_oldest_recognized_entries(tmp_path: Path) -> None:
history = tmp_path / "quick-run-history"
history.mkdir()
now = 2_000_000_000.0
for index in range(6):
entry = history / f"batch-{index}"
entry.mkdir()
(entry / "evidence.bin").write_bytes(bytes(index + 1))
os.utime(entry, (now - 100 + index, now - 100 + index))
unknown = history / "operator-notes"
unknown.mkdir()
(unknown / "keep.txt").write_text("keep", encoding="utf-8")
result = maintain_quick_run_storage(
tmp_path,
now=now,
max_age_days=30,
max_entries=3,
max_bytes=1024,
min_entries=2,
)
assert result.removed_entries == ("batch-0", "batch-1", "batch-2")
assert result.removed_bytes == 1 + 2 + 3
assert result.skipped_entries == ()
assert {path.name for path in history.iterdir()} == {
"batch-3", "batch-4", "batch-5", "operator-notes"
}
def test_history_age_and_size_limits_never_delete_minimum_recent_entries(tmp_path: Path) -> None:
history = tmp_path / "quick-run-history"
history.mkdir()
now = 2_000_000_000.0
for index in range(4):
entry = history / f"recovery-{index}"
entry.mkdir()
(entry / "backup.bin").write_bytes(b"x" * 20)
os.utime(entry, (now - 40 * 86400 + index, now - 40 * 86400 + index))
result = maintain_quick_run_storage(
tmp_path,
now=now,
max_age_days=30,
max_entries=100,
max_bytes=25,
min_entries=2,
)
assert result.removed_entries == ("recovery-0", "recovery-1")
assert {path.name for path in history.iterdir()} == {"recovery-2", "recovery-3"}
+682
View File
@@ -0,0 +1,682 @@
from __future__ import annotations
import json
import os
from pathlib import Path
import sqlite3
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.models import ProjectStatus, TaskStatus
import dx_productivity.trial_task_center.runner as runner_module
from dx_productivity.trial_task_center.runner import TrialRunner
from dx_productivity.trial_task_center.store import TaskStore
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _write_profile(name: str, destination: Path, project: Path) -> None:
profile = json.loads((FIXTURES / name).read_text(encoding="utf-8"))
profile["project"]["identity"] = str(project)
destination.write_text(json.dumps(profile), encoding="utf-8")
def _runner_with_selected_projects(tmp_path: Path, count: int = 1) -> tuple[TrialRunner, TaskStore, str, tuple[str, ...]]:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
store.add_rule(task.task_id, "OLD-1", "NEW-1")
root = tmp_path / "projects"
root.mkdir()
paths = []
for number in range(count):
path = root / f"project-{number + 1}.prj"
path.write_text("project", encoding="utf-8")
paths.append(path)
projects = store.sync_projects(task.task_id, root, paths)
for project in projects:
store.set_project_selected(project.project_id, True)
probe_source = tmp_path / "menu-probe-default.json"
probe_source.write_text("baseline", encoding="utf-8")
return (
TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
),
store,
task.task_id,
tuple(project.project_id for project in projects),
)
def _runner_with_probe_source(
tmp_path: Path, count: int = 1
) -> tuple[TrialRunner, TaskStore, str, tuple[str, ...], Path]:
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count)
probe_source = tmp_path / "menu-probe.json"
probe_source.write_text("baseline", encoding="utf-8")
return (
TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
),
store,
task_id,
project_ids,
probe_source,
)
def test_start_requires_disposable_confirmation_and_activates_exact_first_selected_project(tmp_path: Path) -> None:
"""Removing the confirmation or choosing an unselected project must block the trial."""
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count=2)
store.set_project_selected(project_ids[0], False)
with pytest.raises(TaskCenterError) as raised:
runner.start_task(task_id, disposable_copy_confirmed=False)
assert raised.value.code == "disposable_copy_required"
snapshot = runner.start_task(task_id, disposable_copy_confirmed=True)
assert snapshot.task.status is TaskStatus.RUNNING
assert snapshot.active_project is not None
assert snapshot.active_project.project_id == project_ids[1]
assert snapshot.active_project.status is ProjectStatus.CAPTURING_BEFORE
def test_before_capture_supplies_project_and_matching_rules_to_operator(tmp_path: Path) -> None:
"""A before profile must be captured before native replacement guidance is shown."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
probe = tmp_path / "before.json"
_write_profile("profile-before.json", probe, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
snapshot = runner.capture_before(task_id, project_id, probe)
assert snapshot.active_project is not None
assert snapshot.active_project.status is ProjectStatus.AWAITING_OPERATOR
assert snapshot.instruction is not None
assert snapshot.instruction.project_path == project.path
assert [(rule.old_part_number, rule.new_part_number, rule.match_count) for rule in snapshot.instruction.rules] == [
("OLD-1", "NEW-1", 1)
]
assert snapshot.evidence_directory.joinpath("before.json").exists()
def test_operator_confirmation_does_not_mark_project_successful(tmp_path: Path) -> None:
"""Changing confirmation into completion would let an assertion bypass machine verification."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
_write_profile("profile-before.json", before, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
snapshot = runner.confirm_native_attempt(task_id, project_id)
assert snapshot.task.status is TaskStatus.RUNNING
assert snapshot.active_project is not None
assert snapshot.active_project.status is ProjectStatus.AWAITING_OPERATOR
assert store.get_task(task_id).status is not TaskStatus.COMPLETED
def test_fresh_after_capture_that_passes_completes_project_and_advances_queue(tmp_path: Path) -> None:
"""Skipping comparison or next-project activation would leave verified work unsafe or stranded."""
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count=2)
first, second = (store.list_projects(task_id)[index] for index in range(2))
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, first.path)
_write_profile("profile-after-valid.json", after, first.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_ids[0], before)
runner.confirm_native_attempt(task_id, project_ids[0])
snapshot = runner.capture_after(task_id, project_ids[0], after)
assert store.list_projects(task_id)[0].status is ProjectStatus.COMPLETED
assert snapshot.task.status is TaskStatus.RUNNING
assert snapshot.active_project is not None
assert snapshot.active_project.project_id == second.project_id
assert snapshot.active_project.status is ProjectStatus.CAPTURING_BEFORE
def test_hard_comparison_failure_keeps_project_failed_and_task_failed(tmp_path: Path) -> None:
"""Treating a hard profile mismatch as success would violate the trial safety gate."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
with pytest.raises(TaskCenterError) as raised:
runner.capture_after(task_id, project_id, after)
assert raised.value.code == "comparison_failed"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
assert store.get_task(task_id).status is TaskStatus.FAILED
def test_paused_commit_still_records_a_failed_comparison_as_task_failure(tmp_path: Path) -> None:
"""Leaving a paused task nonfailed after a rejected commit would hide a hard safety failure."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
runner.pause_task(task_id)
with pytest.raises(TaskCenterError, match="comparison_failed"):
runner.capture_after(task_id, project_id, after)
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
assert store.get_task(task_id).status is TaskStatus.FAILED
def test_pause_prevents_next_project_then_resume_reactivates_it(tmp_path: Path) -> None:
"""Starting another project while paused would defeat the operator's pause request."""
runner, store, task_id, project_ids = _runner_with_selected_projects(tmp_path, count=2)
first = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, first.path)
_write_profile("profile-after-valid.json", after, first.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_ids[0], before)
runner.pause_task(task_id)
paused = runner.capture_after(task_id, project_ids[0], after)
assert paused.task.status is TaskStatus.PAUSED
assert paused.active_project is None
assert store.list_projects(task_id)[1].status is ProjectStatus.PENDING
resumed = runner.resume_task(task_id)
assert resumed.task.status is TaskStatus.RUNNING
assert resumed.active_project is not None
assert resumed.active_project.project_id == project_ids[1]
def test_retry_uses_new_attempt_directory_and_skip_finishes_queue(tmp_path: Path) -> None:
"""Reusing a failed attempt's evidence or failing to finish skipped work loses auditability."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
with pytest.raises(TaskCenterError):
runner.capture_after(task_id, project_id, after)
failed_directory = runner.snapshot(task_id).evidence_directory
retried = runner.retry_project(task_id, project_id)
assert retried.active_project is not None
assert retried.evidence_directory != failed_directory
assert retried.evidence_directory.name == "attempt-2"
completed = runner.skip_project(task_id, project_id)
assert store.list_projects(task_id)[0].status is ProjectStatus.SKIPPED
assert completed.task.status is TaskStatus.COMPLETED
def test_passing_final_project_completes_the_task(tmp_path: Path) -> None:
"""Omitting terminal task completion would strand a verified one-project trial."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", before, project.path)
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
completed = runner.capture_after(task_id, project_id, after)
assert completed.task.status is TaskStatus.COMPLETED
assert completed.active_project is None
def test_restart_recovery_uses_store_state_and_records_transition_events(tmp_path: Path) -> None:
"""A restarted process must recover durable work instead of trusting a stale runner instance."""
runner, store, task_id, (project_id,) = _runner_with_selected_projects(tmp_path)
runner.start_task(task_id, disposable_copy_confirmed=True)
restarted = TrialRunner(store, configure_logging(tmp_path / "logs"))
snapshot = restarted.snapshot(task_id)
events = [
json.loads(line)
for line in (tmp_path / "logs" / "tasks" / task_id / "events.jsonl").read_text(encoding="utf-8").splitlines()
]
assert snapshot.task.status is TaskStatus.PAUSED
assert snapshot.active_project is None
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
recovery_events = [
event
for event in events
if event["operation"] == "recover_interrupted_work" and event["project_id"] == project_id
]
assert [event["details"]["phase"] for event in recovery_events] == ["before", "after"]
assert [event["state_before"] for event in recovery_events] == [
ProjectStatus.CAPTURING_BEFORE.value,
ProjectStatus.CAPTURING_BEFORE.value,
]
def test_restart_awaiting_operator_uses_persisted_before_stamp_and_instruction(tmp_path: Path) -> None:
"""Dropping an attempt context on restart must fail closed instead of accepting the old probe as after evidence."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
_write_profile("profile-after-valid.json", probe_source, project.path)
_write_profile("profile-after-valid.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "new-before-probe"
before.write_text(json.dumps(before_profile), encoding="utf-8")
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
restarted = TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
)
recovered = restarted.snapshot(task_id)
assert recovered.instruction is not None
with pytest.raises(TaskCenterError) as raised:
restarted.capture_after(task_id, project_id, before)
assert raised.value.code == "profile_unchanged"
assert store.get_task(task_id).status is TaskStatus.FAILED
def test_restart_without_persisted_before_stamp_fails_closed(tmp_path: Path) -> None:
"""A damaged attempt record cannot safely advance from operator state to verification."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
store.set_project_status(project_id, ProjectStatus.AWAITING_OPERATOR)
restarted = TrialRunner(
store,
configure_logging(tmp_path / "logs"),
probe_source_resolver=lambda _task, _project: probe_source,
)
with pytest.raises(TaskCenterError) as raised:
restarted.capture_after(task_id, project_id, after)
assert raised.value.code == "attempt_before_missing"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
def test_capture_after_rechecks_persisted_before_content_hash(tmp_path: Path) -> None:
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
_write_profile("profile-before.json", probe_source, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
before = json.loads(probe_source.read_text(encoding="utf-8"))
before["capture"] = "fresh-before"
probe_source.write_text(json.dumps(before), encoding="utf-8")
runner.capture_before(task_id, project_id, probe_source)
context = store.current_attempt(project_id)
assert context is not None and context.before_path is not None
altered = json.loads(context.before_path.read_text(encoding="utf-8"))
altered["components"][0]["pins"][0]["x"] = 999
context.before_path.write_text(json.dumps(altered), encoding="utf-8")
_write_profile("profile-after-valid.json", probe_source, project.path)
with pytest.raises(TaskCenterError) as raised:
runner.capture_after(task_id, project_id, probe_source)
assert raised.value.code == "evidence_integrity"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
def test_attempt_freezes_rules_for_instruction_and_comparison(tmp_path: Path) -> None:
"""Comparing with an edited mapping rather than the attempt mapping must reject the UI edit race."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "new-before-probe"
before.write_text(json.dumps(before_profile), encoding="utf-8")
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
rule = store.list_rules(task_id)[0]
store.update_rule(rule.rule_id, old_part_number="OLD-1", new_part_number="OTHER-1", enabled=True)
completed = runner.capture_after(task_id, project_id, after)
assert completed.task.status is TaskStatus.COMPLETED
def test_start_baseline_rejects_unchanged_before_probe(tmp_path: Path) -> None:
"""Capturing the probe present at Start as a before profile would permit stale evidence."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
_write_profile("profile-before.json", probe_source, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
runner.capture_before(task_id, project_id, probe_source)
assert raised.value.code == "profile_unchanged"
def test_global_active_project_gate_blocks_second_task(tmp_path: Path) -> None:
"""Selecting one active project per task still permits dangerous concurrent native work."""
first, store, first_task_id, _, probe_source = _runner_with_probe_source(tmp_path)
second_task = store.create_task("Second")
store.add_rule(second_task.task_id, "OLD-1", "NEW-1")
second_path = tmp_path / "second.prj"
second_path.write_text("project", encoding="utf-8")
second_project = store.sync_projects(second_task.task_id, tmp_path, (second_path,))[0]
store.set_project_selected(second_project.project_id, True)
second = TrialRunner(store, configure_logging(tmp_path / "logs"), probe_source_resolver=lambda _task, _project: probe_source)
first.start_task(first_task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
second.start_task(second_task.task_id, disposable_copy_confirmed=True)
assert raised.value.code == "active_project_exists"
assert store.get_task(second_task.task_id).status is TaskStatus.DRAFT
def test_retry_slot_conflict_leaves_failed_task_and_project_unchanged(tmp_path: Path) -> None:
"""A rejected retry claim must not first persist a runnable task or pending project."""
blocker, store, blocker_task_id, _, probe_source = _runner_with_probe_source(tmp_path)
blocked_task = store.create_task("Blocked retry")
store.add_rule(blocked_task.task_id, "OLD-1", "NEW-1")
path = tmp_path / "blocked-retry.prj"
path.write_text("project", encoding="utf-8")
blocked_project = store.sync_projects(blocked_task.task_id, tmp_path, (path,))[0]
store.set_project_selected(blocked_project.project_id, True)
store.set_task_status(blocked_task.task_id, TaskStatus.RUNNING)
store.set_project_status(blocked_project.project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(blocked_project.project_id, ProjectStatus.FAILED)
store.set_task_status(blocked_task.task_id, TaskStatus.FAILED)
blocker.start_task(blocker_task_id, disposable_copy_confirmed=True)
events_path = tmp_path / "logs" / "tasks" / blocked_task.task_id / "events.jsonl"
with pytest.raises(TaskCenterError) as raised:
blocker.retry_project(blocked_task.task_id, blocked_project.project_id)
assert raised.value.code == "active_project_exists"
assert store.get_task(blocked_task.task_id).status is TaskStatus.FAILED
assert store.list_projects(blocked_task.task_id)[0].status is ProjectStatus.FAILED
assert not events_path.exists() or "retry started" not in events_path.read_text(encoding="utf-8")
def test_resume_slot_conflict_leaves_paused_task_and_pending_project_unchanged(tmp_path: Path) -> None:
"""A rejected resume claim must not advertise success after another task owns the slot."""
blocker, store, blocker_task_id, _, probe_source = _runner_with_probe_source(tmp_path)
blocked_task = store.create_task("Blocked resume")
store.add_rule(blocked_task.task_id, "OLD-1", "NEW-1")
path = tmp_path / "blocked-resume.prj"
path.write_text("project", encoding="utf-8")
blocked_project = store.sync_projects(blocked_task.task_id, tmp_path, (path,))[0]
store.set_project_selected(blocked_project.project_id, True)
store.set_task_status(blocked_task.task_id, TaskStatus.RUNNING)
store.set_task_status(blocked_task.task_id, TaskStatus.PAUSED)
blocker.start_task(blocker_task_id, disposable_copy_confirmed=True)
events_path = tmp_path / "logs" / "tasks" / blocked_task.task_id / "events.jsonl"
with pytest.raises(TaskCenterError) as raised:
blocker.resume_task(blocked_task.task_id)
assert raised.value.code == "active_project_exists"
assert store.get_task(blocked_task.task_id).status is TaskStatus.PAUSED
assert store.list_projects(blocked_task.task_id)[0].status is ProjectStatus.PENDING
assert not events_path.exists() or "trial resumed" not in events_path.read_text(encoding="utf-8")
def test_resume_completes_terminal_task_while_another_task_owns_the_active_slot(tmp_path: Path) -> None:
"""A finished queue needs no native-work slot, so resuming it must be allowed to complete."""
blocker, store, blocker_task_id, _, _ = _runner_with_probe_source(tmp_path)
completed_task = store.create_task("Completed queue")
path = tmp_path / "completed-queue.prj"
path.write_text("project", encoding="utf-8")
completed_project = store.sync_projects(completed_task.task_id, tmp_path, (path,))[0]
store.set_project_selected(completed_project.project_id, True)
store.set_task_status(completed_task.task_id, TaskStatus.RUNNING)
for status in (
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
ProjectStatus.COMPLETED,
):
store.set_project_status(completed_project.project_id, status)
store.set_task_status(completed_task.task_id, TaskStatus.PAUSED)
blocker.start_task(blocker_task_id, disposable_copy_confirmed=True)
resumed = blocker.resume_task(completed_task.task_id)
assert resumed.task.status is TaskStatus.COMPLETED
assert resumed.active_project is None
def test_v1_migration_recovery_emits_before_and_after_events(tmp_path: Path) -> None:
"""Fail-closed v1 migration must retain enough durable context for recovery audit events."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first.sync_projects(task.task_id, tmp_path, (path,))[0]
first.set_task_status(task.task_id, TaskStatus.RUNNING)
first.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
TrialRunner(migrated, configure_logging(tmp_path / "logs"))
events = [
json.loads(line)
for line in (tmp_path / "logs" / "tasks" / task.task_id / "events.jsonl").read_text(encoding="utf-8").splitlines()
]
project_events = [
event for event in events if event["operation"] == "recover_v1_attemptless_work" and event["project_id"] == project.project_id
]
task_events = [
event for event in events if event["operation"] == "recover_v1_attemptless_work" and event["project_id"] is None
]
assert [event["details"]["phase"] for event in project_events] == ["before", "after"]
assert [event["state_before"] for event in project_events] == [ProjectStatus.CAPTURING_BEFORE.value] * 2
assert [event["state_after"] for event in project_events] == [ProjectStatus.FAILED.value] * 2
assert [event["details"]["phase"] for event in task_events] == ["before", "after"]
assert [event["state_before"] for event in task_events] == [TaskStatus.RUNNING.value] * 2
assert [event["state_after"] for event in task_events] == [TaskStatus.PAUSED.value] * 2
@pytest.mark.parametrize("failure_point", ("append_after_write", "acknowledge_before_delete"))
def test_v1_migration_recovery_events_are_idempotent_across_restart(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, failure_point: str
) -> None:
"""Restarting after a partial recovery must not duplicate an event that is already durable."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first.sync_projects(task.task_id, tmp_path, (path,))[0]
first.set_task_status(task.task_id, TaskStatus.RUNNING)
first.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
logging_context = configure_logging(tmp_path / "logs")
original_append = runner_module.append_task_event
original_acknowledge = TaskStore.acknowledge_migration_recoveries
append_count = 0
if failure_point == "append_after_write":
def append_then_fail(*args: object, **kwargs: object) -> dict[str, object]:
nonlocal append_count
event = original_append(*args, **kwargs)
append_count += 1
if append_count == 2:
raise TaskCenterError("event_write_failed", "simulated crash after durable append")
return event
monkeypatch.setattr(runner_module, "append_task_event", append_then_fail)
else:
def fail_acknowledge(_store: TaskStore, _project_ids: object) -> None:
raise TaskCenterError("recovery_ack_failed", "simulated crash before recovery acknowledgement")
monkeypatch.setattr(TaskStore, "acknowledge_migration_recoveries", fail_acknowledge)
with pytest.raises(TaskCenterError):
TrialRunner(migrated, logging_context)
migrated.close()
monkeypatch.setattr(runner_module, "append_task_event", original_append)
monkeypatch.setattr(TaskStore, "acknowledge_migration_recoveries", original_acknowledge)
restarted_store = TaskStore(database)
TrialRunner(restarted_store, configure_logging(tmp_path / "logs"))
events = [
json.loads(line)
for line in (tmp_path / "logs" / "tasks" / task.task_id / "events.jsonl").read_text(encoding="utf-8").splitlines()
]
recovery_events = [event for event in events if event["operation"] == "recover_v1_attemptless_work"]
assert len(recovery_events) == 4
assert len({event["details"]["recovery_event_id"] for event in recovery_events}) == 4
assert restarted_store.pending_migration_recoveries() == ()
def test_completed_project_event_failure_reconciles_task_without_illegal_failure(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""An event-write failure after completion must not attempt an illegal completed-to-failed transition."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
os.utime(probe_source, ns=(1_700_000_000_000_000_000, 1_700_000_000_000_000_000))
os.utime(before, ns=(1_700_000_001_000_000_000, 1_700_000_001_000_000_000))
_write_profile("profile-after-valid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
original_append = runner_module.append_task_event
def fail_terminal_event(*args: object, **kwargs: object) -> dict[str, object]:
if kwargs.get("operation") == "compare_profiles" and kwargs.get("details") == {"phase": "after"}:
raise TaskCenterError("event_write_failed", "cannot append task event")
return original_append(*args, **kwargs)
monkeypatch.setattr(runner_module, "append_task_event", fail_terminal_event)
with pytest.raises(TaskCenterError, match="event_write_failed"):
runner.capture_after(task_id, project_id, after)
assert store.list_projects(task_id)[0].status is ProjectStatus.COMPLETED
assert store.get_task(task_id).status is TaskStatus.COMPLETED
def test_restart_reconciles_completed_project_when_task_completion_was_interrupted(tmp_path: Path) -> None:
"""A crash after project completion must not leave a restartable trial permanently running."""
runner, store, task_id, (project_id,), _ = _runner_with_probe_source(tmp_path)
runner.start_task(task_id, disposable_copy_confirmed=True)
store.set_project_status(project_id, ProjectStatus.FAILED)
store.set_project_status(project_id, ProjectStatus.PENDING)
store.set_project_status(project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(project_id, ProjectStatus.AWAITING_OPERATOR)
store.set_project_status(project_id, ProjectStatus.CAPTURING_AFTER)
store.set_project_status(project_id, ProjectStatus.VERIFYING)
store.set_project_status(project_id, ProjectStatus.COMPLETED)
restarted = TrialRunner(store, configure_logging(tmp_path / "logs"))
assert restarted.snapshot(task_id).task.status is TaskStatus.COMPLETED
def test_retry_uses_blank_current_instruction_without_mutating_prior_attempt_evidence(tmp_path: Path) -> None:
"""Reusing a previous attempt instruction can direct the operator with stale match evidence."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "new-before-probe"
before.write_text(json.dumps(before_profile), encoding="utf-8")
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
first_attempt = runner.capture_before(task_id, project_id, before)
original_before = (first_attempt.evidence_directory / "before.json").read_bytes()
with pytest.raises(TaskCenterError):
runner.capture_after(task_id, project_id, after)
retried = runner.retry_project(task_id, project_id)
assert retried.instruction is None
assert (first_attempt.evidence_directory / "before.json").read_bytes() == original_before
def test_before_capture_rejects_duplicate_logical_identity(tmp_path: Path) -> None:
"""Ignoring malformed components before operator action creates unverified replacement guidance."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
_write_profile("profile-before.json", probe_source, project.path)
profile = json.loads((FIXTURES / "profile-before.json").read_text(encoding="utf-8"))
profile["project"]["identity"] = str(project.path)
profile["components"].append(dict(profile["components"][0]))
before.write_text(json.dumps(profile), encoding="utf-8")
runner.start_task(task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
runner.capture_before(task_id, project_id, before)
assert raised.value.code == "before_profile_invalid"
assert store.list_projects(task_id)[0].status is ProjectStatus.FAILED
def test_failed_project_can_be_deselected_and_reconciles_task(tmp_path: Path) -> None:
"""A failed deselected project must not keep an otherwise empty queue in failed state forever."""
runner, store, task_id, (project_id,), probe_source = _runner_with_probe_source(tmp_path)
project = store.list_projects(task_id)[0]
before = tmp_path / "before.json"
after = tmp_path / "after.json"
_write_profile("profile-before.json", probe_source, project.path)
_write_profile("profile-before.json", before, project.path)
before_profile = json.loads(before.read_text(encoding="utf-8"))
before_profile["capture"] = "before-evidence"
before.write_text(json.dumps(before_profile), encoding="utf-8")
_write_profile("profile-after-invalid.json", after, project.path)
runner.start_task(task_id, disposable_copy_confirmed=True)
runner.capture_before(task_id, project_id, before)
with pytest.raises(TaskCenterError):
runner.capture_after(task_id, project_id, after)
snapshot = runner.set_project_selected(task_id, project_id, False)
assert not store.list_projects(task_id)[0].selected
assert snapshot.task.status is TaskStatus.PAUSED
+210
View File
@@ -0,0 +1,210 @@
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.scanner import scan_projects
SCHEMATIC_PROJECT = '''SECTION DesignInfo
KEY FrontEndSnapshot "DxD"
ENDSECTION
SECTION iCDB
KEY iCDBDir ".\\database"
ENDSECTION
'''
def _write_schematic_project(path: Path) -> None:
path.write_text(SCHEMATIC_PROJECT, encoding="utf-8")
def test_scan_projects_discovers_case_insensitive_prj_files_in_canonical_order(tmp_path: Path) -> None:
root = tmp_path / "projects"
first = root / "z" / "B.PRJ"
second = root / "a" / "a.PrJ"
first.parent.mkdir(parents=True)
second.parent.mkdir()
_write_schematic_project(first)
_write_schematic_project(second)
before = sorted(path.relative_to(root) for path in root.rglob("*"))
result = scan_projects(root)
assert result == tuple(sorted((first.resolve(), second.resolve()), key=lambda path: str(path).casefold()))
assert sorted(path.relative_to(root) for path in root.rglob("*")) == before
def test_scan_projects_stops_at_selected_project_directory_when_it_contains_prj_files(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Descending past a directly selected project can expose backups as separate projects."""
root = tmp_path / "selected-project"
first = root / "A.PRJ"
second = root / "Board.prj"
nested_backup = root / "backup" / "Board-old.prj"
nested_generated = root / "generated" / "Board-copy.PRJ"
nested_backup.parent.mkdir(parents=True)
nested_generated.parent.mkdir()
_write_schematic_project(first)
_write_schematic_project(second)
_write_schematic_project(nested_backup)
_write_schematic_project(nested_generated)
real_scandir = os.scandir
def reject_nested(path: str | bytes | int) -> object:
if Path(path) != root:
raise AssertionError(f"unexpected nested scan: {path}")
return real_scandir(path)
monkeypatch.setattr("dx_productivity.trial_task_center.scanner.os.scandir", reject_nested)
result = scan_projects(root)
assert result == (first.resolve(), second.resolve())
def test_scan_projects_reads_batch_root_once_before_recursive_fallback(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Enumerating a live root twice can mix two different filesystem snapshots."""
root = tmp_path / "projects"
child = root / "child"
project = child / "Board.prj"
child.mkdir(parents=True)
_write_schematic_project(project)
real_scandir = os.scandir
root_reads = 0
def count_root(path: str | bytes | int) -> object:
nonlocal root_reads
if Path(path) == root:
root_reads += 1
return real_scandir(path)
monkeypatch.setattr("dx_productivity.trial_task_center.scanner.os.scandir", count_root)
result = scan_projects(root)
assert result == (project.resolve(),)
assert root_reads == 1
def test_scan_projects_skips_portable_task_data_and_its_backups(tmp_path: Path) -> None:
root = tmp_path / "DxPartReplace"
project = root / "projects" / "Board" / "Board.prj"
backup = root / "data" / "quick-run-history" / "batch-test" / "project-1" / "Board.prj"
project.parent.mkdir(parents=True)
backup.parent.mkdir(parents=True)
_write_schematic_project(project)
_write_schematic_project(backup)
assert scan_projects(root, excluded_roots=(root / "data",)) == (project.resolve(),)
def test_scan_projects_rejects_task_data_as_the_selected_root(tmp_path: Path) -> None:
data = tmp_path / "data"
data.mkdir()
with pytest.raises(TaskCenterError) as raised:
scan_projects(data, excluded_roots=(data,))
assert raised.value.code == "discovery_root"
def test_scan_projects_wraps_invalid_roots_without_losing_input_error_code(tmp_path: Path) -> None:
missing = tmp_path / "missing"
file_root = tmp_path / "not-a-directory.prj"
_write_schematic_project(file_root)
for root in (missing, file_root):
with pytest.raises(TaskCenterError) as raised:
scan_projects(root)
assert raised.value.code == "discovery_root"
def test_scan_projects_turns_inaccessible_subtree_errors_into_explicit_task_errors(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
root = tmp_path / "projects"
denied = root / "denied"
denied.mkdir(parents=True)
real_scandir = __import__("os").scandir
def deny(path: str | bytes | int) -> object:
if Path(path) == denied:
raise PermissionError("denied subtree")
return real_scandir(path)
monkeypatch.setattr("dx_productivity.trial_task_center.scanner.os.scandir", deny)
with pytest.raises(TaskCenterError) as raised:
scan_projects(root)
assert raised.value.code == "discovery_access"
@pytest.mark.skipif(os.name != "nt", reason="Windows junction coverage")
def test_scan_projects_rejects_junction_subtrees_without_scanning_them(tmp_path: Path) -> None:
root = tmp_path / "projects"
outside = tmp_path / "outside"
junction = root / "junction"
normal = root / "normal.prj"
outside_project = outside / "outside.prj"
root.mkdir()
outside.mkdir()
_write_schematic_project(normal)
_write_schematic_project(outside_project)
created = subprocess.run(
["cmd", "/c", "mklink", "/J", str(junction), str(outside)],
check=False,
capture_output=True,
text=True,
)
if created.returncode != 0:
pytest.skip(f"junctions unavailable: {created.stderr or created.stdout}")
try:
with pytest.raises(TaskCenterError) as raised:
scan_projects(root)
finally:
junction.rmdir()
assert raised.value.code == "discovery_reparse"
assert normal.exists()
assert outside_project.exists()
def test_scan_projects_ignores_pcb_and_other_prj_files(tmp_path: Path) -> None:
root = tmp_path / "projects"
schematic = root / "Schematic.prj"
pcb = root / "PCB.prj"
vivado = root / "vlog.prj"
schematic.parent.mkdir(parents=True)
_write_schematic_project(schematic)
pcb.write_text(
'SECTION DesignInfo\nKEY FrontEndSnapshot "PCB"\nENDSECTION\n'
'SECTION Board\nKEY PCBDesignPath "PCB\\Board.pcb"\nENDSECTION\n',
encoding="utf-8",
)
vivado.write_text("verilog work source.v\n", encoding="utf-8")
assert scan_projects(root) == (schematic.resolve(),)
def test_scan_projects_keeps_schematic_projects_that_also_contain_pcb_configuration(tmp_path: Path) -> None:
root = tmp_path / "projects"
integrated = root / "Integrated.prj"
integrated.parent.mkdir(parents=True)
integrated.write_text(
SCHEMATIC_PROJECT
+ 'SECTION Board1\nKEY ConfigType "PCB"\nKEY PCBDesignPath "PCB\\Board1.pcb"\nENDSECTION\n',
encoding="utf-8",
)
assert scan_projects(root) == (integrated.resolve(),)
@@ -0,0 +1,81 @@
from __future__ import annotations
from io import StringIO
import json
from pathlib import Path
import sqlite3
from dx_productivity.trial_task_center.sceneos_cli import run
from dx_productivity.trial_task_center.store import TaskStore
def test_sceneos_cli_creates_scans_and_reuses_one_task(tmp_path: Path) -> None:
projects = tmp_path / "projects"
projects.mkdir()
(projects / "alpha.prj").touch()
(projects / "beta.prj").touch()
data_root = tmp_path / "data"
payload = {
"protocol": "sceneos-cli/v1",
"input": {"taskName": "SceneOS scan", "projectRoot": str(projects.resolve())},
"context": {"runId": "run-1", "stepId": "create", "idempotencyKey": "run-1:create"},
}
first_output = StringIO()
repeated_output = StringIO()
assert run(data_root, StringIO(json.dumps(payload)), first_output) == 0
assert run(data_root, StringIO(json.dumps(payload)), repeated_output) == 0
first = json.loads(first_output.getvalue())
repeated = json.loads(repeated_output.getvalue())
assert first["created"] is True
assert first["projectCount"] == 2
assert repeated == first | {"created": False}
with sqlite3.connect(data_root / "task-center.db") as connection:
assert connection.execute("SELECT COUNT(*) FROM tasks").fetchone()[0] == 1
assert connection.execute("SELECT COUNT(*) FROM external_requests").fetchone()[0] == 1
def test_sceneos_cli_rejects_conflicting_input_for_the_same_key(tmp_path: Path) -> None:
first_root = tmp_path / "first"
second_root = tmp_path / "second"
first_root.mkdir()
second_root.mkdir()
context = {"runId": "run-1", "stepId": "create", "idempotencyKey": "fixed-key"}
first = _invoke(tmp_path / "data", "First", first_root, context)
conflict = _invoke(tmp_path / "data", "Second", second_root, context)
assert first[0] == 0
assert conflict[0] == 2
assert conflict[1]["error"] == "external_request_conflict"
def test_sceneos_cli_request_can_be_recreated_after_task_is_purged(tmp_path: Path) -> None:
projects = tmp_path / "projects"
projects.mkdir()
data_root = tmp_path / "data"
context = {"runId": "run-1", "stepId": "create", "idempotencyKey": "purged-key"}
first = _invoke(data_root, "Replace scan", projects, context)
store = TaskStore(data_root / "task-center.db")
try:
store.soft_delete_task(str(first[1]["taskId"]))
store.purge_task(str(first[1]["taskId"]))
finally:
store.close()
recreated = _invoke(data_root, "Replace scan", projects, context)
assert recreated[0] == 0
assert recreated[1]["created"] is True
assert recreated[1]["taskId"] != first[1]["taskId"]
def _invoke(data_root: Path, name: str, project_root: Path, context: dict[str, str]) -> tuple[int, dict[str, object]]:
output = StringIO()
code = run(data_root, StringIO(json.dumps({
"protocol": "sceneos-cli/v1",
"input": {"taskName": name, "projectRoot": str(project_root.resolve())},
"context": context,
})), output)
return code, json.loads(output.getvalue())
+251
View File
@@ -0,0 +1,251 @@
from __future__ import annotations
import json
from datetime import datetime, timezone
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.quick_run import QuickRunProgress
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
FIXTURES = Path(__file__).parents[1] / "fixtures" / "trial_task_center"
def _service(tmp_path: Path, opened: list[Path] | None = None) -> TaskCenterService:
probe_source = tmp_path / "menu-probe.json"
probe_source.write_text("baseline", encoding="utf-8")
return TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
configure_logging(tmp_path / "storage"),
path_opener=(opened.append if opened is not None else lambda _: None),
clock=lambda: datetime(2026, 9, 4, tzinfo=timezone.utc),
probe_source_resolver=lambda _task, _project: probe_source,
)
def _write_profile(name: str, destination: Path, project: Path) -> None:
profile = json.loads((FIXTURES / name).read_text(encoding="utf-8"))
profile["project"]["identity"] = str(project)
destination.write_text(json.dumps(profile), encoding="utf-8")
def test_task_crud_scan_and_selection_commands_keep_previous_operator_choice(tmp_path: Path) -> None:
"""Replacing service delegation with UI-local state would lose the durable selection."""
service = _service(tmp_path)
root = tmp_path / "projects"
root.mkdir()
first = root / "one.prj"
second = root / "two.prj"
first.touch()
second.touch()
task = service.create_task("Trial", note="first")
service.update_task(task.task_id, name="Renamed", note="updated")
scanned = service.scan_projects(task.task_id, root)
service.set_project_selected(scanned[0].project_id, True)
rescan = service.scan_projects(task.task_id, root)
selected = service.select_all_projects(task.task_id)
cleared = service.clear_project_selection(task.task_id)
assert service.get_task(task.task_id).name == "Renamed"
assert next(project for project in rescan if project.project_id == scanned[0].project_id).selected
assert all(project.selected for project in selected)
assert not any(project.selected for project in cleared)
def test_bulk_selection_has_constant_project_list_queries(tmp_path: Path, monkeypatch) -> None:
service = _service(tmp_path)
root = tmp_path / "projects"
root.mkdir()
for index in range(200):
(root / f"project-{index:04d}.prj").touch()
task = service.create_task("Bulk")
service.scan_projects(task.task_id, root)
calls = 0
original = service._store.list_projects
def counted(task_id: str):
nonlocal calls
calls += 1
return original(task_id)
monkeypatch.setattr(service._store, "list_projects", counted)
selected = service.select_all_projects(task.task_id)
select_calls = calls
calls = 0
cleared = service.clear_project_selection(task.task_id)
assert all(project.selected for project in selected)
assert not any(project.selected for project in cleared)
assert select_calls <= 4
assert calls <= 4
def test_repeated_completed_progress_skips_redundant_database_sync(tmp_path: Path, monkeypatch) -> None:
service = _service(tmp_path)
root = tmp_path / "projects"
root.mkdir()
project_path = root / "one.prj"
project_path.touch()
task = service.create_task("Progress")
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
progress = QuickRunProgress(
1,
1,
None,
None,
None,
(project_path,),
True,
project_summaries=((project_path, "quick_run_result:1:0:saved"),),
saved_items=1,
)
service._synchronize_quick_run_progress(task.task_id, progress=progress)
sync_calls = 0
original = service._store.record_quick_run_progress
def counted(*args, **kwargs):
nonlocal sync_calls
sync_calls += 1
return original(*args, **kwargs)
monkeypatch.setattr(service._store, "record_quick_run_progress", counted)
service._synchronize_quick_run_progress(task.task_id, progress=progress)
assert sync_calls == 0
def test_operation_log_records_distinct_completion_time(tmp_path: Path) -> None:
timestamps = iter((
datetime(2026, 9, 7, 10, 0, tzinfo=timezone.utc),
datetime(2026, 9, 7, 10, 0, 3, tzinfo=timezone.utc),
))
logging = configure_logging(tmp_path / "storage")
service = TaskCenterService(
TaskStore(tmp_path / "task-center.db"),
logging,
clock=lambda: next(timestamps),
)
service.tasks()
log = logging.application_log_path.read_text(encoding="utf-8")
assert "operation_start=list_tasks task_id= at=2026-09-07T10:00:00+00:00" in log
assert "operation_complete=list_tasks task_id= at=2026-09-07T10:00:03+00:00" in log
def test_task_delete_and_restore_delegate_to_durable_store(tmp_path: Path) -> None:
"""Keeping deletion only in UI state would lose the audit-preserving soft-delete contract."""
service = _service(tmp_path)
task = service.create_task("Trial")
deleted = service.delete_task(task.task_id)
restored = service.restore_task(task.task_id)
assert deleted.task_id == task.task_id
assert restored.task_id == task.task_id
assert service.tasks() == (restored,)
def test_rule_validation_errors_are_task_center_errors_with_stable_ids(tmp_path: Path) -> None:
"""Leaking parser errors would deny the UI a support identifier for invalid mappings."""
service = _service(tmp_path)
task = service.create_task("Trial")
service.add_rule(task.task_id, "OLD-1", "NEW-1")
with pytest.raises(TaskCenterError) as raised:
service.add_rule(task.task_id, "NEW-1", "OLD-2")
assert raised.value.code == "mapping_chain"
assert raised.value.error_id.startswith("DXT-")
def test_current_instruction_log_tailing_and_injected_evidence_opener(tmp_path: Path) -> None:
"""The UI must receive guidance and paths through the service without launching Explorer itself."""
opened: list[Path] = []
service = _service(tmp_path, opened)
task = service.create_task("Trial")
service.add_rule(task.task_id, "OLD-1", "NEW-1")
root = tmp_path / "projects"
root.mkdir()
project_path = root / "one.prj"
project_path.touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
before = tmp_path / "before.json"
_write_profile("profile-before.json", before, project_path)
service.start_task(task.task_id, disposable_copy_confirmed=True)
service.capture_before(task.task_id, project.project_id, before)
instruction = service.current_instruction(task.task_id)
evidence_path = service.open_evidence(task.task_id, project.project_id)
log_lines = service.tail_log(task.task_id, limit=4)
assert instruction is not None
assert instruction.project_path == project_path
assert instruction.rules[0].old_part_number == "OLD-1"
assert evidence_path == opened[0]
assert any("capture_before" in line for line in log_lines)
def test_tail_log_does_not_amplify_the_application_log(tmp_path: Path) -> None:
service = _service(tmp_path)
task = service.create_task("Log polling")
application_log = service._logging.application_log_path
before = application_log.read_text(encoding="utf-8")
assert service.tail_log(task.task_id, limit=10) == ()
assert application_log.read_text(encoding="utf-8") == before
def test_service_rejects_mapping_edits_while_an_attempt_is_active(tmp_path: Path) -> None:
"""Changing rules mid-attempt would make UI mappings disagree with captured evidence."""
service = _service(tmp_path)
task = service.create_task("Trial")
rule = service.add_rule(task.task_id, "OLD-1", "NEW-1")
root = tmp_path / "projects"
root.mkdir()
project_path = root / "one.prj"
project_path.touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
service.start_task(task.task_id, disposable_copy_confirmed=True)
with pytest.raises(TaskCenterError) as raised:
service.update_rule(rule.rule_id, old_part_number="OLD-1", new_part_number="OTHER-1", enabled=True)
assert raised.value.code == "rules_locked"
with pytest.raises(TaskCenterError, match="rules_locked"):
service.add_rule(task.task_id, "OLD-2", "NEW-2")
with pytest.raises(TaskCenterError, match="rules_locked"):
service.delete_rule(rule.rule_id)
with pytest.raises(TaskCenterError, match="rules_locked"):
service.move_rule(rule.rule_id, 1)
def test_prepared_queue_freezes_project_inventory_and_rule_options(tmp_path: Path) -> None:
service = _service(tmp_path)
task = service.create_task("Frozen queue")
root = tmp_path / "projects"
root.mkdir()
(root / "one.prj").touch()
project = service.scan_projects(task.task_id, root)[0]
service.set_project_selected(project.project_id, True)
rule = service.add_rule(task.task_id, "OLD", "NEW")
service.prepare_quick_run(task.task_id)
with pytest.raises(TaskCenterError, match="quick_run_options_locked"):
service.set_project_selected(project.project_id, False)
with pytest.raises(TaskCenterError, match="quick_run_options_locked"):
service.scan_projects(task.task_id, root)
with pytest.raises(TaskCenterError, match="rules_locked"):
service.update_rule(rule.rule_id, old_part_number="OLD", new_part_number="OTHER", enabled=True)
@@ -0,0 +1,20 @@
import pytest
from dx_productivity.trial_task_center import quick_run
@pytest.mark.parametrize('detail,expected', [
('stage=launch_designer COM: failed', '自动启动'),
('stage=wait_designer timeout', '未启动第二个实例'),
('stage=check_project another project is already open', '其他工程'),
('stage=open_sheet project has multiple sheets', '多张图页'),
('stage=open_sheet target project has no available schematic sheets', '没有可用原理图'),
])
def test_startup_errors_explain_action_without_losing_original(detail, expected):
message = quick_run._session_failure_message(detail)
assert expected in message
assert detail in message
def test_non_session_worker_error_is_not_misreported_as_startup():
assert quick_run._session_failure_message('original attachment error') == 'original attachment error'
+512
View File
@@ -0,0 +1,512 @@
from dataclasses import FrozenInstanceError
from pathlib import Path
import sqlite3
import threading
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.models import ProjectRecord, ProjectStatus, TaskRecord, TaskStatus
from dx_productivity.trial_task_center.store import TaskStore
def test_task_records_are_immutable_and_task_crud_round_trips(tmp_path: Path) -> None:
"""Changing a task through its record must not mutate durable state."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("试验任务", note="first")
assert isinstance(task, TaskRecord)
assert store.get_task(task.task_id).name == "试验任务"
with pytest.raises(FrozenInstanceError):
task.name = "not permitted" # type: ignore[misc]
renamed = store.update_task(task.task_id, name="单项目替换", note="updated")
assert renamed.name == "单项目替换"
assert renamed.note == "updated"
assert renamed.updated_utc > task.updated_utc
def test_task_names_must_be_unique_and_nonblank(tmp_path: Path) -> None:
"""A duplicate or blank draft name would make task selection ambiguous."""
store = TaskStore(tmp_path / "task-center.db")
store.create_task("Trial")
with pytest.raises(TaskCenterError, match="task_name"):
store.create_task(" trial ")
with pytest.raises(TaskCenterError, match="task_name"):
store.create_task(" \t ")
def test_soft_delete_restore_and_running_delete_rejection(tmp_path: Path) -> None:
"""A running task must remain available until the operator pauses it."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
deleted = store.soft_delete_task(task.task_id)
assert deleted.status is TaskStatus.DELETED
assert store.list_tasks() == ()
assert store.list_tasks(TaskStatus.DELETED)[0].task_id == task.task_id
assert store.restore_task(task.task_id).status is TaskStatus.DRAFT
store.set_task_status(task.task_id, TaskStatus.RUNNING)
with pytest.raises(TaskCenterError, match="task_running"):
store.soft_delete_task(task.task_id)
def test_rule_crud_reordering_enablement_and_validation_rollback(tmp_path: Path) -> None:
"""A rejected mapping edit must leave the prior valid ordered rules intact."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
first = store.add_rule(task.task_id, " OLD-1 ", "NEW-1")
second = store.add_rule(task.task_id, "OLD-2", "NEW-2")
updated = store.update_rule(
first.rule_id,
old_part_number="OLD-1",
new_part_number="NEW-1",
enabled=False,
)
moved = store.move_rule(second.rule_id, -1)
assert updated.enabled is False
assert [rule.rule_id for rule in moved] == [second.rule_id, first.rule_id]
assert [rule.position for rule in moved] == [0, 1]
with pytest.raises(TaskCenterError, match="mapping_chain"):
store.update_rule(
first.rule_id,
old_part_number="OLD-1",
new_part_number="OLD-2",
enabled=True,
)
restored = store.list_rules(task.task_id)
assert [(rule.old_part_number, rule.new_part_number, rule.enabled) for rule in restored] == [
("OLD-2", "NEW-2", True),
("OLD-1", "NEW-1", False),
]
store.delete_rule(first.rule_id)
assert [rule.rule_id for rule in store.list_rules(task.task_id)] == [second.rule_id]
def test_project_rescan_preserves_existing_selection_and_marks_missing_unavailable(tmp_path: Path) -> None:
"""Rescanning must never silently alter an operator's prior selection."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
root = tmp_path / "projects"
root.mkdir()
first_path = root / "one.prj"
second_path = root / "two.prj"
first_path.touch()
second_path.touch()
first_scan = store.sync_projects(task.task_id, root, (first_path, second_path))
selected = store.set_project_selected(first_scan[0].project_id, True)
second_scan = store.sync_projects(task.task_id, root, (second_path,))
assert selected.selected is True
by_path = {project.path.name: project for project in second_scan}
assert by_path["one.prj"].selected is True
assert by_path["one.prj"].available is False
assert by_path["two.prj"].selected is False
assert by_path["two.prj"].available is True
def test_bulk_project_selection_updates_available_inventory_in_one_operation(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
root = tmp_path / "projects"
root.mkdir()
first_path = root / "one.prj"
second_path = root / "two.prj"
first_path.touch()
second_path.touch()
store.sync_projects(task.task_id, root, (first_path, second_path))
projects = store.sync_projects(task.task_id, root, (second_path,))
selected = store.set_projects_selected(task.task_id, True, available_only=True)
by_path = {project.path.name: project for project in selected}
assert by_path["one.prj"].selected is False
assert by_path["two.prj"].selected is True
cleared = store.set_projects_selected(task.task_id, False)
assert not any(project.selected for project in cleared)
def test_project_scan_new_root_replaces_unstarted_inventory(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
first_root = tmp_path / "first"
second_root = tmp_path / "second"
first_root.mkdir()
second_root.mkdir()
first_path = first_root / "old.prj"
second_path = second_root / "new.prj"
first_path.touch()
second_path.touch()
first = store.sync_projects(task.task_id, first_root, (first_path,))[0]
store.set_project_selected(first.project_id, True)
second = store.sync_projects(task.task_id, second_root, (second_path,))
assert [project.path for project in second] == [second_path.resolve()]
assert store.list_projects(task.task_id) == second
assert second[0].selected is False
def test_project_scan_new_root_preserves_started_inventory_and_fails_closed(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
first_root = tmp_path / "first"
second_root = tmp_path / "second"
first_root.mkdir()
second_root.mkdir()
first_path = first_root / "old.prj"
second_path = second_root / "new.prj"
first_path.touch()
second_path.touch()
first = store.sync_projects(task.task_id, first_root, (first_path,))[0]
store.set_project_status(first.project_id, ProjectStatus.CAPTURING_BEFORE)
with pytest.raises(TaskCenterError) as raised:
store.sync_projects(task.task_id, second_root, (second_path,))
projects = store.list_projects(task.task_id)
assert raised.value.code == "discovery_root_locked"
assert store.get_task(task.task_id).discovery_root == first_root.resolve()
assert len(projects) == 1
assert projects[0].path == first_path.resolve()
assert projects[0].status is ProjectStatus.CAPTURING_BEFORE
def test_same_project_path_can_belong_to_independent_tasks(tmp_path: Path) -> None:
"""Project records must be scoped to their owning task, not globally by path."""
store = TaskStore(tmp_path / "task-center.db")
first_task = store.create_task("First trial")
second_task = store.create_task("Second trial")
project_path = tmp_path / "shared.prj"
project_path.touch()
first_project = store.sync_projects(first_task.task_id, tmp_path, (project_path,))[0]
second_project = store.sync_projects(second_task.task_id, tmp_path, (project_path,))[0]
assert first_project.task_id == first_task.task_id
assert second_project.task_id == second_task.task_id
assert first_project.project_id != second_project.project_id
def test_reader_cannot_observe_a_task_that_later_rolls_back(tmp_path: Path) -> None:
"""A second thread must wait for a transaction rather than observe its uncommitted rows."""
store = TaskStore(tmp_path / "task-center.db")
reader_started = threading.Event()
reader_finished = threading.Event()
observed: list[tuple[TaskRecord, ...]] = []
def read_tasks() -> None:
reader_started.set()
observed.append(store.list_tasks())
reader_finished.set()
reader = threading.Thread(target=read_tasks, name="transaction-reader")
try:
with pytest.raises(RuntimeError, match="abort"):
with store.transaction():
store.create_task("Uncommitted")
reader.start()
assert reader_started.wait(timeout=1)
assert not reader_finished.wait(timeout=0.2)
raise RuntimeError("abort")
finally:
reader.join(timeout=1)
assert not reader.is_alive()
assert reader_finished.is_set()
assert observed == [()]
def test_project_and_task_state_transitions_are_persisted(tmp_path: Path) -> None:
"""Execution state changes must survive the write before UI can observe them."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
project_path = tmp_path / "one.prj"
project_path.touch()
project = store.sync_projects(task.task_id, tmp_path, (project_path,))[0]
store.set_task_status(task.task_id, TaskStatus.READY)
store.set_task_status(task.task_id, TaskStatus.RUNNING)
captured = store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
waiting = store.set_project_status(project.project_id, ProjectStatus.AWAITING_OPERATOR)
assert captured.status is ProjectStatus.CAPTURING_BEFORE
assert waiting.status is ProjectStatus.AWAITING_OPERATOR
assert store.get_task(task.task_id).status is TaskStatus.RUNNING
def test_transaction_rollback_leaves_no_partial_task(tmp_path: Path) -> None:
"""A failed grouped write must not expose a partially-created task."""
store = TaskStore(tmp_path / "task-center.db")
with pytest.raises(RuntimeError, match="abort"):
with store.transaction():
store.create_task("Uncommitted")
raise RuntimeError("abort")
assert store.list_tasks() == ()
def test_schema_reopens_and_recovers_interrupted_work(tmp_path: Path) -> None:
"""A crash mid-capture must become a paused task and failed retryable project."""
database = tmp_path / "task-center.db"
first_store = TaskStore(database)
task = first_store.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first_store.sync_projects(task.task_id, tmp_path, (path,))[0]
first_store.set_task_status(task.task_id, TaskStatus.RUNNING)
first_store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
first_store.set_project_status(project.project_id, ProjectStatus.AWAITING_OPERATOR)
first_store.set_project_status(project.project_id, ProjectStatus.CAPTURING_AFTER)
first_store.close()
reopened = TaskStore(database)
recovered = reopened.recover_interrupted_work()
recovered_task = reopened.get_task(task.task_id)
recovered_project = reopened.list_projects(task.task_id)[0]
assert recovered == (project.project_id,)
assert recovered_task.status is TaskStatus.PAUSED
assert recovered_project.status is ProjectStatus.FAILED
assert recovered_project.error_id is not None
assert "interrupted" in recovered_project.summary.casefold()
def test_completed_task_delete_and_restore_preserves_completed_status(tmp_path: Path) -> None:
"""Archiving a completed task must not turn it into a draft on restore."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Completed trial")
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_task_status(task.task_id, TaskStatus.COMPLETED)
deleted = store.soft_delete_task(task.task_id)
restored = store.restore_task(task.task_id)
assert deleted.status is TaskStatus.DELETED
assert restored.status is TaskStatus.COMPLETED
def test_restore_completed_task_preserves_original_completed_timestamp(tmp_path: Path) -> None:
"""Restoring an archived completed task must not manufacture a new completion event."""
database = tmp_path / "task-center.db"
store = TaskStore(database)
task = store.create_task("Timestamp trial")
store.set_task_status(task.task_id, TaskStatus.RUNNING)
completed = store.set_task_status(task.task_id, TaskStatus.COMPLETED)
with sqlite3.connect(database) as connection:
original_timestamp = connection.execute(
"SELECT completed_utc FROM tasks WHERE task_id = ?", (task.task_id,)
).fetchone()[0]
store.soft_delete_task(task.task_id)
restored = store.restore_task(task.task_id)
with sqlite3.connect(database) as connection:
restored_timestamp = connection.execute(
"SELECT completed_utc FROM tasks WHERE task_id = ?", (task.task_id,)
).fetchone()[0]
assert restored.status is TaskStatus.COMPLETED
assert restored.completed_utc == completed.completed_utc
assert restored_timestamp == original_timestamp
def test_attempt_context_is_durable_and_claims_the_only_active_project(tmp_path: Path) -> None:
"""Attempt evidence metadata must survive restart and atomically exclude another active project."""
database = tmp_path / "task-center.db"
store = TaskStore(database)
first_task = store.create_task("First")
second_task = store.create_task("Second")
first_path = tmp_path / "first.prj"
second_path = tmp_path / "second.prj"
first_path.touch()
second_path.touch()
first = store.sync_projects(first_task.task_id, tmp_path, (first_path,))[0]
second = store.sync_projects(second_task.task_id, tmp_path, (second_path,))[0]
store.set_project_selected(first.project_id, True)
store.set_project_selected(second.project_id, True)
store.begin_project_attempt(
first_task.task_id,
first.project_id,
probe_source=tmp_path / "menu-probe.json",
baseline_size=7,
baseline_sha256="a" * 64,
baseline_modified_ns=11,
rules_json='[{"old_part_number":"OLD-1","new_part_number":"NEW-1"}]',
)
store.save_attempt_before(first.project_id, before_path=tmp_path / "before.json", before_size=8, before_sha256="b" * 64, before_modified_ns=12, instruction_json='{"rules":[]}')
with pytest.raises(TaskCenterError, match="active_project_exists"):
store.begin_project_attempt(
second_task.task_id,
second.project_id,
probe_source=tmp_path / "menu-probe.json",
baseline_size=7,
baseline_sha256="a" * 64,
baseline_modified_ns=11,
rules_json="[]",
)
store.close()
reopened = TaskStore(database)
attempt = reopened.current_attempt(first.project_id)
assert attempt is not None
assert attempt.baseline_sha256 == "a" * 64
assert attempt.before_sha256 == "b" * 64
assert attempt.instruction_json == '{"rules":[]}'
def test_v1_database_migrates_to_attempt_metadata_schema(tmp_path: Path) -> None:
"""Upgrading an existing task database must add durable attempt storage without losing tasks."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
assert migrated.get_task(task.task_id).name == "Trial"
with sqlite3.connect(database) as connection:
assert connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == "5"
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'attempts'").fetchone()
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'external_requests'").fetchone()
def test_rule_value_and_nc_options_round_trip_and_preserve_on_legacy_update(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Rule options")
rule = store.add_rule(
task.task_id,
"OLD",
"NEW",
custom_value_enabled=True,
custom_value="10k",
sync_nc=False,
)
assert (rule.custom_value_enabled, rule.custom_value, rule.sync_nc) == (True, "10k", False)
updated = store.update_rule(
rule.rule_id,
old_part_number="OLD",
new_part_number="NEWER",
enabled=False,
)
assert (updated.custom_value_enabled, updated.custom_value, updated.sync_nc) == (True, "10k", False)
def test_custom_value_must_be_nonblank_and_single_line(tmp_path: Path) -> None:
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Rule validation")
with pytest.raises(TaskCenterError, match="custom_value"):
store.add_rule(task.task_id, "OLD", "NEW", custom_value_enabled=True, custom_value=" ")
with pytest.raises(TaskCenterError, match="custom_value"):
store.add_rule(task.task_id, "OLD", "NEW", custom_value_enabled=True, custom_value="A\tB")
@pytest.mark.parametrize(
"active_status",
(
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
),
)
def test_v1_migration_fails_attemptless_active_project_closed(tmp_path: Path, active_status: ProjectStatus) -> None:
"""A v1 active project has no attempt context and must not retain the global native-work slot."""
database = tmp_path / "task-center.db"
first = TaskStore(database)
task = first.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = first.sync_projects(task.task_id, tmp_path, (path,))[0]
first.set_task_status(task.task_id, TaskStatus.RUNNING)
transitions = (
ProjectStatus.CAPTURING_BEFORE,
ProjectStatus.AWAITING_OPERATOR,
ProjectStatus.CAPTURING_AFTER,
ProjectStatus.VERIFYING,
)
for status in transitions[: transitions.index(active_status) + 1]:
first.set_project_status(project.project_id, status)
first.close()
with sqlite3.connect(database) as connection:
connection.execute("DROP TABLE attempts")
connection.execute("UPDATE metadata SET value = '1' WHERE key = 'schema_version'")
migrated = TaskStore(database)
recovered = migrated.list_projects(task.task_id)[0]
assert migrated.get_task(task.task_id).status is TaskStatus.PAUSED
assert recovered.status is ProjectStatus.FAILED
assert active_status.value in recovered.summary
assert recovered.error_id is not None
def test_claim_project_attempt_uses_declared_failed_retry_transitions(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A retry claim must traverse the task and project state graph inside its transaction."""
store = TaskStore(tmp_path / "task-center.db")
task = store.create_task("Trial")
path = tmp_path / "one.prj"
path.touch()
project = store.sync_projects(task.task_id, tmp_path, (path,))[0]
store.set_project_selected(project.project_id, True)
store.set_task_status(task.task_id, TaskStatus.RUNNING)
store.set_project_status(project.project_id, ProjectStatus.CAPTURING_BEFORE)
store.set_project_status(project.project_id, ProjectStatus.FAILED)
store.set_task_status(task.task_id, TaskStatus.FAILED)
task_transitions: list[tuple[TaskStatus, TaskStatus]] = []
project_transitions: list[tuple[ProjectStatus, ProjectStatus]] = []
set_task_status = store.set_task_status
set_project_status = store.set_project_status
def record_task_transition(task_id: str, status: TaskStatus, **kwargs: object) -> TaskRecord:
current = store.get_task(task_id).status
if current is not status:
task_transitions.append((current, status))
return set_task_status(task_id, status, **kwargs)
def record_project_transition(project_id: str, status: ProjectStatus, **kwargs: object) -> ProjectRecord:
current = store.list_projects(task.task_id)[0].status
if current is not status:
project_transitions.append((current, status))
return set_project_status(project_id, status, **kwargs)
monkeypatch.setattr(store, "set_task_status", record_task_transition)
monkeypatch.setattr(store, "set_project_status", record_project_transition)
claimed_task, claimed_project = store.claim_project_attempt(
task.task_id,
project.project_id,
expected_task_status=TaskStatus.FAILED,
expected_project_status=ProjectStatus.FAILED,
probe_source=tmp_path / "probe.json",
baseline_size=1,
baseline_sha256="a" * 64,
baseline_modified_ns=1,
rules_json="[]",
task_summary="retry started",
project_summary="project selected for retry",
)
assert task_transitions == [(TaskStatus.FAILED, TaskStatus.PAUSED), (TaskStatus.PAUSED, TaskStatus.RUNNING)]
assert project_transitions == [(ProjectStatus.FAILED, ProjectStatus.PENDING)]
assert claimed_task.status is TaskStatus.RUNNING
assert claimed_project.status is ProjectStatus.CAPTURING_BEFORE
@@ -0,0 +1,213 @@
from pathlib import Path
import subprocess
import sqlite3
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.models import ProjectRecord, ProjectStatus, RuleRecord
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
SOURCE = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
def inputs():
projects = tuple(ProjectRecord(f'project-{index}', 'task', f'Project {index}',
Path(f'C:/review/project-{index}.prj'), Path('C:/review'),
True, True, ProjectStatus.PENDING, 0) for index in range(2))
return projects, (RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True),)
def test_task_value_option_defaults_off_and_survives_reopen(tmp_path):
database = TaskStore(tmp_path / 'tasks.db')
task = database.create_task('Option')
assert task.copy_part_number_to_value is False
database.set_copy_part_number_to_value(task.task_id, True)
database.close()
database = TaskStore(tmp_path / 'tasks.db')
try:
assert database.get_task(task.task_id).copy_part_number_to_value is True
finally:
database.close()
@pytest.mark.parametrize('enabled,mode', [(False, 'preserve'), (True, 'part_label')])
def test_queue_records_explicit_value_policy(tmp_path, enabled, mode):
projects, rules = inputs()
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE)
result = preparer.prepare('task', projects, rules, copy_part_number_to_value=enabled)
lines = result.command_path.read_text(encoding='utf-8').splitlines()
header = lines[0].split('\t')
assert 'value_mode' in header
assert {line.split('\t')[header.index('value_mode')] for line in lines[1:]} == {mode}
def test_queue_freezes_custom_value_and_nc_policy_per_rule(tmp_path):
projects, _ = inputs()
rules = (RuleRecord('rule', 'task', 0, 'OLD', 'NEW', True, True, '100nF', False),)
result = QuickRunPreparer(tmp_path, script_source=SOURCE).prepare(
'task', projects, rules, copy_part_number_to_value=True
)
lines = result.command_path.read_text(encoding='utf-8').splitlines()
header = lines[0].split('\t')
row = dict(zip(header, lines[1].split('\t'), strict=True))
assert row['value_mode'] == 'custom'
assert row['custom_value'] == '100nF'
assert row['sync_nc'] == '0'
assert row['base_value_mode'] == 'part_label'
def test_result_for_other_queued_project_is_rejected(tmp_path):
projects, rules = inputs()
def worker(command, timeout):
rows = (tmp_path / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()
wrong_job = rows[2].split('\t')[1]
with (tmp_path / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
handle.write(f'{wrong_job}\tawaiting_native_replace\t\tcaptured\n{wrong_job}\trestored_ok\t\tverified\n')
return subprocess.CompletedProcess(command, 0, '', '')
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
with pytest.raises(TaskCenterError, match='quick_run_uncertain'):
preparer.execute_step('task', projects, rules)
assert (tmp_path / 'quick-run/uncertain.flag').exists()
def test_policy_change_cannot_reinterpret_partial_queue(tmp_path):
projects, rules = inputs()
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE)
result = preparer.prepare('task', projects, rules)
job = result.command_path.read_text(encoding='utf-8').splitlines()[1].split('\t')[1]
result.status_path.write_text(f'job_id\tstate\tcode\tmessage\n{job}\tawaiting_native_replace\t\tcaptured\n', encoding='utf-8')
with pytest.raises(TaskCenterError, match='quick_run_pending'):
preparer.execute_step('task', projects, rules, copy_part_number_to_value=True)
def test_service_freezes_setting_after_queue_is_prepared(tmp_path):
database = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(database, configure_logging(tmp_path / 'data'))
task = service.create_task('Freeze')
service.set_copy_part_number_to_value(task.task_id, True)
assert service.get_task(task.task_id).copy_part_number_to_value is True
queue = tmp_path / 'data/quick-run'
queue.mkdir()
(queue / 'command.tsv').write_text(
f'task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\n{task.task_id}\tjob\tC:/test.prj\tOLD\tNEW\tpart_number\n',
encoding='utf-8')
(queue / 'status.tsv').write_text('job_id\tstate\tcode\tmessage\n', encoding='utf-8')
try:
with pytest.raises(TaskCenterError, match='quick_run_options_locked'):
service.set_copy_part_number_to_value(task.task_id, False)
finally:
database.close()
def test_v2_task_migration_defaults_off_without_changing_task(tmp_path):
path = tmp_path / 'old.db'
database = TaskStore(path)
task = database.create_task('Existing task', 'Keep this note')
database.close()
with sqlite3.connect(path) as connection:
connection.execute('ALTER TABLE tasks DROP COLUMN copy_part_number_to_value')
connection.execute("UPDATE metadata SET value='2' WHERE key='schema_version'")
database = TaskStore(path)
try:
migrated = database.get_task(task.task_id)
assert migrated.name == task.name and migrated.note == task.note
assert migrated.status is task.status
assert migrated.copy_part_number_to_value is False
finally:
database.close()
def test_checked_service_uses_same_policy_for_execution_and_progress(tmp_path):
root = tmp_path / 'data'
def worker(command, timeout):
lines = (root / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()
row = lines[1].split('\t')
assert row[-1] == 'part_label'
assert command[-1] == row[1]
with (root / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
handle.write(f'{row[1]}\tawaiting_native_replace\t\tcaptured\n{row[1]}\trestored_ok\t\tverified\n')
return subprocess.CompletedProcess(command, 0, '', '')
preparer = QuickRunPreparer(root, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
database = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(database, configure_logging(root), quick_run_preparer=preparer)
task = service.create_task('Checked')
(tmp_path / 'one.prj').touch()
project = service.scan_projects(task.task_id, tmp_path)[0]
service.set_project_selected(project.project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
service.set_copy_part_number_to_value(task.task_id, True)
try:
result = service.execute_quick_run(task.task_id, expected_item=(str(project.path), 'OLD', 'NEW', 'part_label'))
assert result.state == 'restored_ok'
assert service.quick_run_progress(task.task_id).queue_complete
finally:
database.close()
def test_changed_confirmation_never_starts_worker(tmp_path):
projects, rules = inputs()
calls = []
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=lambda *args: calls.append(args))
with pytest.raises(TaskCenterError, match='quick_run_selection_changed'):
preparer.execute_step('task', projects, rules, expected_item=(str(projects[1].path), 'OLD', 'NEW', 'preserve'))
assert calls == []
def test_serial_three_project_two_rule_queue_pins_each_job(tmp_path):
selected, _ = inputs()
third = ProjectRecord('third', 'task', 'Third', Path('C:/review/third.prj'), Path('C:/review'), True, True, ProjectStatus.PENDING, 0)
projects = (*selected, third)
rules = (RuleRecord('first', 'task', 0, 'OLD', 'NEW', True), RuleRecord('second', 'task', 1, 'OLD2', 'NEW2', True))
completed = []
def worker(command, timeout):
rows = [line.split('\t') for line in (tmp_path / 'quick-run/command.tsv').read_text(encoding='utf-8').splitlines()[1:]]
row = rows[len(completed)]
assert command[-1] == row[1]
with (tmp_path / 'quick-run/status.tsv').open('a', encoding='utf-8') as handle:
handle.write(f'{row[1]}\tawaiting_native_replace\t\tcaptured\n{row[1]}\trestored_ok\t\tverified\n')
completed.append((row[2], row[3]))
return subprocess.CompletedProcess(command, 0, '', '')
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE, process_runner=worker,
cscript_resolver=lambda: Path('C:/Windows/SysWOW64/cscript.exe'))
for index in range(6):
preparer.execute_step('task', projects, rules)
assert len(completed) == index + 1
assert completed == [(str(project.path), rule.old_part_number) for project in projects for rule in rules]
assert preparer.progress('task', projects, rules).queue_complete
def test_old_queue_snapshot_blocks_policy_reinterpretation_without_status(tmp_path):
projects, rules = inputs()
preparer = QuickRunPreparer(tmp_path, script_source=SOURCE)
result = preparer.prepare('task', projects, rules)
lines = [line.split('\t') for line in result.command_path.read_text(encoding='utf-8').splitlines()]
value_mode_index = lines[0].index('value_mode')
result.command_path.write_text(
'\n'.join('\t'.join(fields[:value_mode_index] + fields[value_mode_index + 1:]) for fields in lines) + '\n',
encoding='utf-8',
)
(result.command_path.parent / 'snapshot-old.tsv').write_text('retained evidence', encoding='utf-8')
with pytest.raises(TaskCenterError, match='quick_run_pending'):
preparer.execute_step('task', projects, rules)
def test_frozen_launcher_reserves_helper_script_slot(monkeypatch, tmp_path):
import sys
from dx_productivity.trial_task_center.quick_run import _native_helper_launch_arguments
monkeypatch.setattr(sys, 'frozen', True, raising=False)
monkeypatch.setattr(sys, 'executable', str(tmp_path / 'DxPartReplace.exe'))
assert _native_helper_launch_arguments() == (str((tmp_path / 'DxPartReplace.exe').resolve()), '')
@@ -0,0 +1,193 @@
import json
from pathlib import Path
import subprocess
import sys
import pytest
from dx_productivity.trial_task_center import worker_monitor
def frame(sequence, stage='capture', done=1, total=18, safe=1, token='token', job='job'):
return f'DX_PROGRESS\t{token}\t{job}\t{sequence}\t{stage}\t{done}\t{total}\t{safe}\n'.encode()
def test_progress_allows_total_runtime_to_exceed_idle_limit():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
for sequence, now in enumerate(range(100, 1001, 100), 1):
assert watch.accept(frame(sequence), now)
assert watch.action(now) is None
assert not watch.stop_requested
def test_idle_requests_stop_before_emergency_timeout():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.action(149) is None
assert watch.action(150) == 'request_stop'
assert watch.action(151) is None
assert watch.action(299) is None
assert watch.action(300) == 'unresponsive'
def test_progress_during_drain_prevents_emergency_kill():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.action(150) == 'request_stop'
for sequence, now in enumerate((200, 350, 490, 630), 1):
assert watch.accept(frame(sequence, safe=0), now)
assert watch.action(now) is None
assert watch.stop_requested
@pytest.mark.parametrize('line', [
frame(1, token='stale'), frame(1, job='other'), frame(0),
frame(1, done=19), frame(1, safe=3), b'garbage\n', frame(1, stage='bad\tstage'),
])
def test_invalid_or_foreign_frames_do_not_extend_deadline(line):
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert not watch.accept(line, 140)
assert watch.action(150) == 'request_stop'
def test_replayed_sequence_does_not_extend_deadline():
watch = worker_monitor.ProgressWatch('token', 'job', 150, 0)
assert watch.accept(frame(2), 10)
assert not watch.accept(frame(2), 155)
assert not watch.accept(frame(1), 155)
assert watch.action(160) == 'request_stop'
def toy_worker(tmp_path: Path, body: str):
script = tmp_path / 'toy.py'
script.write_text('''
import pathlib,sys,time
root=pathlib.Path(sys.argv[1])
job=sys.argv[4]
token=sys.argv[5]
ready=root/f'monitor-{token}.ready'
stop=root/f'monitor-{token}.stop'
while not ready.exists(): time.sleep(0.01)
def emit(sequence):
print(f'DX_PROGRESS\\t{token}\\t{job}\\t{sequence}\\tverify\\t{sequence}\\t10\\t0',flush=True)
''' + body, encoding='utf-8')
return (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
def test_real_process_with_progress_outlives_idle_timeout(tmp_path):
command = toy_worker(tmp_path, '''
for sequence in range(1,6):
emit(sequence)
time.sleep(0.4)
print('DONE',flush=True)
''')
result = worker_monitor.run_monitored_process(command, 1.0)
assert result.returncode == 0
assert 'DONE' in result.stdout
assert 'DX_PROGRESS' not in result.stdout
progress = json.loads((tmp_path / 'worker-progress.json').read_text(encoding='utf-8'))
assert progress['sequence'] == 5
assert not progress['stop_requested']
def test_idle_worker_can_acknowledge_cooperative_stop(tmp_path):
command = toy_worker(tmp_path, '''
while not stop.exists(): time.sleep(0.01)
print('stopped before mutation',flush=True)
sys.exit(3)
''')
result = worker_monitor.run_monitored_process(command, 0.5)
assert result.returncode == 3
assert 'stopped before mutation' in result.stdout
progress = json.loads((tmp_path / 'worker-progress.json').read_text(encoding='utf-8'))
assert progress['stop_requested']
def test_unresponsive_worker_is_not_left_running(tmp_path):
command = toy_worker(tmp_path, '''
import os,subprocess
child=subprocess.Popen([sys.executable,'-c','import time;time.sleep(60)'])
(root/'pids.json').write_text(__import__('json').dumps([os.getpid(),child.pid]))
time.sleep(60)
''')
with pytest.raises(subprocess.TimeoutExpired):
worker_monitor.run_monitored_process(command, 0.7)
import win32api
import win32con
import win32event
for pid in json.loads((tmp_path / 'pids.json').read_text()):
try:
handle = win32api.OpenProcess(win32con.SYNCHRONIZE, False, pid)
except Exception:
continue
try:
assert win32event.WaitForSingleObject(handle, 2000) == win32event.WAIT_OBJECT_0
finally:
handle.Close()
def test_real_vbs_monitor_handshake_fails_before_cad_for_missing_project(tmp_path):
script = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
(tmp_path / 'command.tsv').write_text('job_id\tproject_path\njob\tC:\\nonexistent-monitor-fixture\\missing.prj\n', encoding='utf-8')
status = tmp_path / 'status.tsv'
status.write_text('job_id\tstate\tcode\tmessage\n', encoding='utf-8')
before = status.read_bytes()
command = (r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(script), str(tmp_path), sys.executable, '', 'job')
result = worker_monitor.run_monitored_process(command, 5)
assert result.returncode == 2
assert 'confirmed project file does not exist' in result.stderr
assert status.read_bytes() == before
progress = json.loads((tmp_path / 'worker-progress.json').read_text(encoding='utf-8'))
assert progress['stage'] == 'session_startup'
assert progress['sequence'] == 1
assert not progress['stop_requested']
def test_monitor_io_failure_remains_an_uncertain_execution(tmp_path, monkeypatch):
command = toy_worker(tmp_path, 'time.sleep(60)\n')
def fail_write(path, text):
raise OSError('disk not writable')
monkeypatch.setattr(worker_monitor, '_atomic_text', fail_write)
with pytest.raises(worker_monitor.WorkerMonitorError, match='disk not writable'):
worker_monitor.run_monitored_process(command, 1)
def test_locked_progress_display_does_not_interrupt_real_worker(tmp_path):
import win32con
import win32file
progress = tmp_path / 'worker-progress.json'
progress.write_text('{}', encoding='utf-8')
handle = win32file.CreateFile(str(progress), win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None, win32con.OPEN_EXISTING, 0, None)
try:
command = toy_worker(tmp_path, '''
for sequence in range(1,6):
emit(sequence)
time.sleep(0.25)
print('DONE',flush=True)
''')
result = worker_monitor.run_monitored_process(command, 0.8)
assert result.returncode == 0
assert 'DONE' in result.stdout
assert not list(tmp_path.glob('monitor-*.stop'))
finally:
handle.Close()
worker_monitor._publish_progress(progress, {'sequence': 6})
assert json.loads(progress.read_text()) == {'sequence': 6}
def test_progress_contention_does_not_hide_control_file_failure(tmp_path, monkeypatch):
original = worker_monitor._atomic_text
def locked_ready(path, text):
if path.suffix == '.ready':
raise PermissionError('control file locked')
return original(path, text)
monkeypatch.setattr(worker_monitor, '_atomic_text', locked_ready)
with pytest.raises(worker_monitor.WorkerMonitorError, match='control file locked'):
worker_monitor.run_monitored_process(toy_worker(tmp_path, 'time.sleep(60)\n'), 1)
def test_chinese_worker_diagnostics_are_not_replaced_with_garbage():
assert worker_monitor._decode('对象不支持此属性或方法'.encode('mbcs')) == '对象不支持此属性或方法'