feat: add V1.1.0 serial task scheduler and fast verification entrypoints

This commit is contained in:
阿白叔 committed 2026-10-14 12:02:46 +08:00
1 parent 210fae575d
commit a7e1b9bd33
10 files changed
+402 -6

No files matched your search

@@ -0,0 +1,37 @@
# V1.1.0 Project Tasks Implementation Plan
> **For agentic workers:** Use superpowers:subagent-driven-development task-by-task. Steps use checkbox syntax.
**Goal:** Iterate the existing replacement application with single-project tasks, editable per-component plans, optional Excel imports and serial task execution.
**Architecture:** Reuse the existing desktop service/store and native replacement helper. Add focused plan/inventory/queue modules with stable target identities and transactional persistence. Keep historic jobs and an explicit legacy test entry point.
**Tech Stack:** Python 3.12, SQLite, PySide6, ASCII VBScript; openpyxl for XLSX files.
**Spec:** docs/superpowers/specs/2026-10-14-v1.1.0-project-tasks-design.md
## Global Constraints
- Version 1.1.0; retain existing task view and direct editing.
- Each directory-created task owns exactly one .prj; historical tasks are preserved.
- Explicit empty targets never mean all matches.
- UID + schematic + sheet + expected RefDes + old Part Number identify targets.
- Default NC synchronization remains on and is editable in UI/import; independent /NC only.
- Existing Replace Part + Library Wins, backup and saved readback remain required.
- No production CAD writes for interface research or tests.
- Default tests are fast behavior tests; historic regressions are explicit and preserved.
---
## Task 2: Cross-task scheduler and existing UI integration
Files: task_queue.py; ui/main_window.py, task_list.py, mapping_table.py; tests/v1_1/test_task_queue.py, test_project_task_ui.py.
Consumed APIs: Task 1 report; existing service.execute_quick_run_queue/quick_run_progress and safe pause. Produced APIs: fixed ordered task queue runner and UI directory wizard/inventory target table/Excel optional entry points.
- [ ] Write failing scheduler test with fake runner logging starts/ends: A completes before B starts; pause leaves B unstarted; uncertain A prevents B; safe ordinary A failure allows B and summary records both.
- [ ] Implement scheduler with per-task evidence paths and fixed IDs/plan fingerprints; reject same-project concurrent tasks, preserve active task evidence on resume.
- [ ] Add directory scanner/create dialog to existing New action with project checkboxes and async scan; existing edit/name notes and historical view survive. Show counts and execution order, support ordering and group start/pause.
- [ ] Add Collect Targets action and editable target table: per row enabled/new part/custom Value/NC controls; preserve existing rule dialog/full-match path. Excel import/export optional actions use same plan validation; blank typed target lists rejected rather than matching all.
- [ ] Verify Qt widgets with offscreen smoke interactions and scheduler failure/lock tests. Commit after tests pass.
+11
View File
@@ -0,0 +1,11 @@
# V1.1.0 测试入口
默认 `python -m pytest -q` 仅运行 `tests/v1_1` 的功能行为测试。pytest 固定使用本仓库 src,避免与同名 dx_productivity 安装包混淆。
`tools/Test-V1.1.ps1` 是日常入口;`-Safety` 增加连接/引脚/非目标修改校验、执行互斥及应用启动回归。发布构建必须执行新测试和安全子集,失败立即停止,不继续打包。
`tools/Test-Legacy.ps1` 保留历史测试入口,`-TestPath` 可以指定某个旧模块。全量历史回归包含 subprocess/VBS/旧 UI 等耗时路径,默认开发循环不调用它。历史测试未删除,也没有被替换成伪通过。
新测试使用真实 SQLite 迁移、真实 XLSX 往返及真实计划验证,CAD/原生进程边界使用注入数据与协议桩。默认不启动 Mentor、不访问生产工程、不等待模拟的真实 150 秒无进展预算。Qt 核验设置 QT_QPA_PLATFORM=offscreen。
打包后的 `--smoke-test --data-root <临时目录>` 单独验证启动、数据存储和退出。真实中央库器件替换、保存回读和外部 Packager/ERC 验收由独立副本现场探针完成。
+3 -1
View File
@@ -69,10 +69,12 @@ try {
Push-Location $repositoryRoot
$locationPushed = $true
& $PythonExecutable -m pytest -q tests\trial_task_center\test_application.py tests\packaging\test_dx_part_replace_build.py
& $PythonExecutable -m pytest -q tests\v1_1 tests\trial_task_center\test_application.py tests\trial_task_center\test_execution_safety.py tests\part_replace\test_verification.py
if ($LASTEXITCODE -ne 0) { throw "Release verification failed; build stopped" }
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "build\DxPartReplace"
Remove-VerifiedBuildTarget -RepositoryRoot $repositoryRoot -RelativeTarget "dist\DxPartReplace"
& $PythonExecutable -m PyInstaller --noconfirm packaging\DxPartReplace.spec
if ($LASTEXITCODE -ne 0) { throw "PyInstaller failed; build stopped" }
$executable = [System.IO.Path]::GetFullPath((Join-Path $repositoryRoot "dist\DxPartReplace\DxPartReplace.exe"))
if (-not (Test-Path -LiteralPath $executable -PathType Leaf)) {
+4 -3
View File
@@ -4,9 +4,9 @@ build-backend = "setuptools.build_meta"
[project]
name = "dx-productivity"
version = "1.0.0"
version = "1.1.0"
requires-python = ">=3.12,<3.13"
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1"]
dependencies = ["PySide6>=6.7,<7", "pywin32>=306", "pywinauto>=0.6.9,<1", "openpyxl>=3.1,<4"]
[project.scripts]
dx-part-replace = "dx_productivity.part_replace.cli:main"
@@ -19,6 +19,7 @@ dev = ["pytest>=8,<9", "pytest-cov>=5,<7", "coverage>=7,<8", "build>=1.2,<2", "p
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
testpaths = ["tests/v1_1"]
pythonpath = ["src"]
addopts = "-ra"
cache_dir = "build/pytest-cache"
@@ -0,0 +1,206 @@
"""Durable serial scheduling of single-project tasks, above the existing runner."""
from contextlib import contextmanager
from dataclasses import asdict, dataclass, is_dataclass
import hashlib
import json
import os
from pathlib import Path
from threading import Event, Lock, get_ident
from uuid import uuid4
from .errors import TaskCenterError
from .quick_run import _write_atomic_queue_text
_QUEUE_LOCK = Lock()
_QUEUE_OWNER: int | None = None
_SAFE_FAILURES = frozenset({'quick_run_preflight', 'quick_run_session', 'quick_run_backup',
'target_identity', 'empty_target_scope', 'enabled_rule_required'})
_TERMINAL = frozenset({'completed', 'failed', 'skipped'})
@dataclass(frozen=True)
class TaskQueueEntry:
task_id: str
state: str
message: str = ''
@dataclass(frozen=True)
class TaskQueueResult:
queue_id: str
entries: tuple[TaskQueueEntry, ...]
paused: bool
current_task_id: str | None = None
def _os_lock(handle, acquire):
handle.seek(0)
if os.name == 'nt':
import msvcrt
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK if acquire else msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(handle.fileno(), (fcntl.LOCK_EX | fcntl.LOCK_NB) if acquire else fcntl.LOCK_UN)
def _lock_file(root: Path):
root.mkdir(parents=True, exist_ok=True)
handle = (root / '.task-queue.execution.lock').open('a+b')
if handle.seek(0, os.SEEK_END) == 0:
handle.write(b'\0')
handle.flush()
return handle
def assert_task_queue_idle(root: Path) -> None:
"""Reject external mutations while a queue owns CAD; its runner may call services."""
if _QUEUE_OWNER == get_ident():
return
if _QUEUE_LOCK.locked():
raise TaskCenterError('quick_run_busy', '任务队列正在执行,请先安全暂停。')
with _lock_file(Path(root)) as handle:
try:
_os_lock(handle, True)
except OSError as error:
raise TaskCenterError('quick_run_busy', '另一窗口正在执行任务队列。') from error
_os_lock(handle, False)
@contextmanager
def _queue_lease(root: Path):
global _QUEUE_OWNER
if not _QUEUE_LOCK.acquire(blocking=False):
raise TaskCenterError('quick_run_busy', '已有任务队列正在执行。')
handle = None
locked = False
try:
handle = _lock_file(root)
try:
_os_lock(handle, True)
locked = True
except OSError as error:
raise TaskCenterError('quick_run_busy', '另一窗口正在执行任务队列。') from error
_QUEUE_OWNER = get_ident()
yield
finally:
_QUEUE_OWNER = None
if handle is not None:
if locked:
_os_lock(handle, False)
handle.close()
_QUEUE_LOCK.release()
def _record(value):
if is_dataclass(value):
return asdict(value)
return vars(value)
def _plan_hash(child, task_id: str) -> str:
task = child.get_task(task_id)
payload = {
'projects': [str(project.path.resolve(strict=False)).casefold() for project in child.projects(task_id)],
'rules': [_record(rule) for rule in child.rules(task_id)],
'targets': [_record(row) for row in child.target_plan(task_id)],
'copy_value': task.copy_part_number_to_value,
}
return hashlib.sha256(json.dumps(payload, sort_keys=True, ensure_ascii=False,
default=str).encode('utf-8')).hexdigest()
def _save(path: Path, state: dict) -> None:
_write_atomic_queue_text(path, json.dumps(state, ensure_ascii=False, indent=2),
'task_queue_state', '不能保存任务队列检查点。')
def execute_task_queue(service, task_ids: tuple[str, ...], *, stop_event: Event,
queue_id: str | None = None) -> TaskQueueResult:
"""Execute the frozen order; uncertain state stops before the next project."""
ids = tuple(task_ids)
if not ids or len(set(ids)) != len(ids):
raise TaskCenterError('task_queue_selection', '请选择不同的单工程任务。')
root = service._logging.root
with _queue_lease(root):
children = {task_id: service.for_project_task(task_id) for task_id in ids}
project_paths = []
for task_id, child in children.items():
task = child.get_task(task_id)
projects = child.projects(task_id)
if not getattr(task, 'primary_project_id', None) or len(projects) != 1:
raise TaskCenterError('project_binding', '顺序执行仅支持绑定单个工程的任务。')
project_paths.append(str(projects[0].path.resolve(strict=False)).casefold())
if len(set(project_paths)) != len(ids):
raise TaskCenterError('task_queue_selection', '不能在同一队列重复处理同一个工程。')
hashes = {task_id: _plan_hash(child, task_id) for task_id, child in children.items()}
token = queue_id or uuid4().hex
if len(token) != 32 or any(char not in '0123456789abcdef' for char in token):
raise TaskCenterError('task_queue_state', '任务队列编号无效。')
path = root / 'task-queues' / f'{token}.json'
path.parent.mkdir(parents=True, exist_ok=True)
if queue_id is not None:
try:
state = json.loads(path.read_text(encoding='utf-8'))
if (state['version'] != 1 or state['task_ids'] != list(ids)
or state['plan_hashes'] != hashes or set(state['entries']) != set(ids)):
raise ValueError('queue inputs changed')
except (OSError, ValueError, KeyError, TypeError) as error:
raise TaskCenterError('task_queue_state', '任务顺序或计划已变化,不能恢复原队列。') from error
else:
state = {'version': 1, 'task_ids': list(ids), 'plan_hashes': hashes,
'entries': {task_id: {'state': 'pending', 'message': ''} for task_id in ids}}
_save(path, state)
paused = False
current = None
try:
for task_id in ids:
if state['entries'][task_id]['state'] in _TERMINAL:
continue
if stop_event.is_set():
paused = True
break
current = task_id
child = children[task_id]
service._task_queue_feedback = (token, task_id, ids.index(task_id) + 1, len(ids))
try:
if child.has_interrupted_quick_run(task_id):
raise TaskCenterError('quick_run_uncertain', '该任务有待核验步骤。')
progress = child.quick_run_progress(task_id)
if progress.queue_complete:
entry = {'state': 'failed' if getattr(progress, 'failed_items', 0) else 'completed',
'message': '该任务队列已有完整执行结果。'}
else:
state['entries'][task_id] = {'state': 'running', 'message': ''}
_save(path, state)
expected = (str(progress.next_project_path), progress.next_old_part_number,
progress.next_new_part_number,
'part_label' if child.get_task(task_id).copy_part_number_to_value else 'preserve')
result = child.execute_quick_run_queue(task_id, expected_item=expected,
stop_event=stop_event)
if child.has_interrupted_quick_run(task_id) or (
result.last_result is not None and result.last_result.state == 'batch_saved_unverified'
):
raise TaskCenterError('quick_run_uncertain', '保存结果尚未确认,任务队列已停止。')
incomplete = result.paused or not result.progress.queue_complete
entry = {'state': 'paused' if incomplete else (
'failed' if getattr(result.progress, 'failed_items', 0) else 'completed'),
'message': '已安全暂停。' if incomplete else '任务已收尾。'}
if incomplete:
paused = True
except TaskCenterError as error:
safe = error.code in _SAFE_FAILURES and not child.has_interrupted_quick_run(task_id)
entry = {'state': 'failed' if safe else 'blocked', 'message': error.message}
paused = not safe
except Exception as error:
entry = {'state': 'blocked', 'message': str(error)}
paused = True
state['entries'][task_id] = entry
_save(path, state)
if paused:
break
return TaskQueueResult(token, tuple(TaskQueueEntry(task_id, **state['entries'][task_id])
for task_id in ids), paused, current if paused else None)
finally:
service._task_queue_feedback = None
@@ -1 +1 @@
VERSION = "1.0.0"
VERSION = "1.1.0"
+1 -1
View File
@@ -7,7 +7,7 @@ from dx_productivity.part_replace.models import ComponentSnapshot, DesignSnapsho
@pytest.fixture(autouse=True)
def accept_minimal_project_placeholders(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> None:
if request.node.path.name != "test_scanner.py":
if "v1_1" not in request.node.path.parts and request.node.path.name != "test_scanner.py":
monkeypatch.setattr(
"dx_productivity.trial_task_center.scanner._is_schematic_project",
lambda _path: True,
+99
View File
@@ -0,0 +1,99 @@
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import execute_task_queue
class Service:
def __init__(self, root, outcomes=None):
self._logging = SimpleNamespace(root=root)
self.calls = []
self.outcomes = outcomes or {}
self.current = None
self._batch_feedback = None
def for_project_task(self, task_id):
parent = self
class Child:
def get_task(self, task_id):
return SimpleNamespace(primary_project_id=task_id, copy_part_number_to_value=False)
def projects(self, task_id):
return (SimpleNamespace(path=Path('C:/') / task_id / 'board.prj', selected=True, available=True),)
def rules(self, task_id):
return (SimpleNamespace(old_part_number='OLD', new_part_number='NEW', enabled=True),)
def target_plan(self, task_id):
return ()
def has_interrupted_quick_run(self, task_id):
return False
def quick_run_progress(self, task_id):
return SimpleNamespace(queue_complete=False, next_project_path=self.projects(task_id)[0].path,
next_old_part_number='OLD', next_new_part_number='NEW')
def execute_quick_run_queue(self, task_id, *, expected_item, stop_event):
parent.calls.append(('start', task_id))
outcome = parent.outcomes.get(task_id)
if isinstance(outcome, Exception):
raise outcome
if callable(outcome):
outcome(stop_event)
parent.calls.append(('end', task_id))
return SimpleNamespace(paused=stop_event.is_set(),
progress=SimpleNamespace(failed_items=int(outcome == 'failed'), queue_complete=True),
last_result=SimpleNamespace(state='saved_ok'))
return Child()
def test_tasks_execute_in_confirmed_order_and_finished_queue_does_not_repeat(tmp_path):
service = Service(tmp_path)
result = execute_task_queue(service, ('B', 'A'), stop_event=Event())
assert service.calls == [('start', 'B'), ('end', 'B'), ('start', 'A'), ('end', 'A')]
assert [entry.state for entry in result.entries] == ['completed', 'completed']
execute_task_queue(service, ('B', 'A'), stop_event=Event(), queue_id=result.queue_id)
assert len(service.calls) == 4
def test_safe_failure_is_reported_and_next_task_runs(tmp_path):
service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
assert [entry.state for entry in result.entries] == ['failed', 'completed']
assert service.calls[-1] == ('end', 'B')
def test_uncertain_result_blocks_next_task(tmp_path):
service = Service(tmp_path, {'A': TaskCenterError('quick_run_uncertain', 'unknown')})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
assert result.paused
assert result.entries[0].state == 'blocked'
assert service.calls == [('start', 'A')]
def test_pause_finishes_current_item_and_does_not_start_next_task(tmp_path):
service = Service(tmp_path, {'A': lambda stop: stop.set()})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
assert result.paused
assert service.calls == [('start', 'A'), ('end', 'A')]
def test_duplicate_tasks_and_projects_rejected_before_dispatch(tmp_path):
service = Service(tmp_path)
with pytest.raises(TaskCenterError):
execute_task_queue(service, ('A', 'A'), stop_event=Event())
assert service.calls == []
def test_resume_rejects_another_task_order(tmp_path):
service = Service(tmp_path)
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
with pytest.raises(TaskCenterError):
execute_task_queue(service, ('B', 'A'), stop_event=Event(), queue_id=result.queue_id)
+18
View File
@@ -0,0 +1,18 @@
[CmdletBinding()]
param([string]$PythonExecutable = 'python', [string[]]$TestPath = @('tests/part_replace', 'tests/trial_task_center', 'tests/ui', 'tests/integration', 'tests/packaging'))
$ErrorActionPreference = 'Stop'
$testRepository = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path
$testPreviousPythonPath = $env:PYTHONPATH
$testPreviousQtPlatform = $env:QT_QPA_PLATFORM
try {
$env:PYTHONPATH = Join-Path $testRepository 'src'
$env:QT_QPA_PLATFORM = 'offscreen'
Push-Location $testRepository
& $PythonExecutable -m pytest -q @TestPath --durations=10
$testResult = $LASTEXITCODE
} finally {
Pop-Location
$env:PYTHONPATH = $testPreviousPythonPath
$env:QT_QPA_PLATFORM = $testPreviousQtPlatform
}
exit $testResult
+22
View File
@@ -0,0 +1,22 @@
[CmdletBinding()]
param([string]$PythonExecutable = 'python', [switch]$Safety)
$ErrorActionPreference = 'Stop'
$testRepository = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot '..')).Path
$testPreviousPythonPath = $env:PYTHONPATH
$testPreviousQtPlatform = $env:QT_QPA_PLATFORM
try {
$env:PYTHONPATH = Join-Path $testRepository 'src'
$env:QT_QPA_PLATFORM = 'offscreen'
Push-Location $testRepository
if ($Safety) {
& $PythonExecutable -m pytest -q tests/v1_1 tests/part_replace/test_verification.py tests/trial_task_center/test_execution_safety.py tests/trial_task_center/test_application.py --durations=5
} else {
& $PythonExecutable -m pytest -q tests/v1_1 --durations=5
}
$testResult = $LASTEXITCODE
} finally {
Pop-Location
$env:PYTHONPATH = $testPreviousPythonPath
$env:QT_QPA_PLATFORM = $testPreviousQtPlatform
}
exit $testResult