fix(startup): run recovery once and avoid scanning idle projects
This commit is contained in:
1 parent
45a9cc6e0c
commit
224f4e7c1e
6 files changed
+133
-22
No files matched your search
@@ -0,0 +1,54 @@
|
||||
# 1.1.2 代码精简与启动/BOM 审查
|
||||
|
||||
审查起点:`136d7ff`。本轮不打包、不发布,不启动 CAD;原始工程、BOM 与既有实测证据不参与写入。
|
||||
|
||||
## 结论与已处理项
|
||||
|
||||
代码确实有历史包袱,但不能按文件大小直接删除。审查起点 Python 生产源码 86 个文件、22,564 行,其中旧 `part_replace` 为 7,503 行;测试目录约 30,337 行,不属于生产包源码。通过检查 GUI、CLI、VBS 动态调用和打包入口,本轮确认并处理以下内容。
|
||||
|
||||
1. 删除 `ui/project_table.py` 的孤立工程列表控件(122 行)。当前窗口使用单工程摘要与位号计划;生产代码、工具、菜单和打包配置均未引用旧控件。
|
||||
2. 删除 `TargetTable.item()` / `_CellAdapter`。它们只为测试模拟旧 QTableWidget 接口;相关用例现直接通过真实 QTableView model 修改、勾选与读取,排序后的 UID 绑定覆盖继续保留。
|
||||
3. 删除未使用的私有导入,保留真实使用的批量备份、协议和包导出。
|
||||
4. 合并 BOM 普通预览与报告校验引擎。`preview_batch` 保留严格调用接口,以同一份 `inspect_batch` 结果返回预览或报错,不再独立维护采集、路由、匹配和编辑保留逻辑。
|
||||
5. `BomMatcher` 对一个工程的位号清单只建立一次索引,逐行仅返回实际命中的目标。每行校验与最终合并校验均保留,继续拒绝重复目标、歧义位号、替换链和循环;未导入位号的原编辑保留。
|
||||
6. 修复损坏 Excel 在普通预览中被误报为未处理异常的问题;按 BOM 导入错误报告。
|
||||
7. 修复读表过程中取消被 ValueError 捕获并转成 BOM 错误的问题。`TaskCenterError` 是 ValueError 子类,需先传播操作异常;inspect/strict 两入口均验证保留 `operation_cancelled`,没有采集或部分保存。
|
||||
8. 启动恢复统一由 runner 完成,删除 application 提前恢复。旧顺序会先修改数据库,使 runner 来不及记录恢复前/后事件。迁移恢复、确认迁移记录和旧运行任务协调均保留。
|
||||
9. 通过按中断状态过滤的一次 SQL 查询替代逐任务读取工程;30 个空闲任务场景不再产生 30 次逐任务工程读取。
|
||||
10. Windows 启动诊断改用 `sys.getwindowsversion()`,避免仅为了记录 OS 信息就启动 WMI 查询。审查期间真实遇到 `platform._wmi_query` 的 `0x8007000e` 异常;这项修正与 CAD COM 绑定问题分别处理。
|
||||
|
||||
生产源码相对起点净减少 **186 行**,减少 1 个模块。新增的索引类替代重复构建和扫描,不是简单把大文件挪到另一个文件。
|
||||
|
||||
## 保留依据
|
||||
|
||||
| 范围 | 仍存在的调用 |
|
||||
| --- | --- |
|
||||
| 旧 `part_replace` CLI | pyproject 公开入口、`python -m dx_productivity`、Start-PartReplacement.ps1 的 discover/status/create/operator-step |
|
||||
| 人工 runner / comparison / evidence | 旧服务入口、历史任务恢复、迁移事件与证据校验;GUI 的规则检查仍跨包复用 inputs |
|
||||
| SceneOS | application 的 `--sceneos-cli` 分派仍存在 |
|
||||
| 菜单和 VBS 桥 | MenuRuntime 的 ExecuteGlobal 动态加载,不能仅依靠 Python import 搜索判死 |
|
||||
| QuickPartReplace / native_helper | 当前原生替换、私有桌面子进程仍使用,打包配置显式包含 VBS |
|
||||
|
||||
`quick_run.py`、`service.py`、`store.py` 仍然偏大。进一步分职责需要检查协议和兼容入口;本轮未引入另一套执行架构或删除仍被调用的功能。
|
||||
|
||||
## 验证
|
||||
|
||||
- 位号编辑、排序和单工程 UI:11 passed。
|
||||
- BOM、库存扩展、事务、任务上下文、UI 草稿和重复轮次选定回归:99 passed,31.19 秒。
|
||||
- 启动、旧人工流程和应用引导:37 passed,21.39 秒,包括历史迁移恢复和恢复前/后事件。
|
||||
- 审查末尾读表取消与启动恢复检查:12 passed,23.55 秒。上述检查有重叠,不相加为总用例数。
|
||||
- 另运行真实 Qt 的 offscreen 应用启动/关闭 smoke;数据目录位于 `build/code-pruning-startup-smoke-20261015`。
|
||||
- 只读复核代理确认原生保存/恢复事务、目标身份、NC 与 Value 处理边界未削弱;其指出的读表取消错误已修复。
|
||||
|
||||
## BOM 模拟规模测量
|
||||
|
||||
使用 1000 个模拟位号、真实 XLSX 的 200 条替换行,包含工程匹配、逐行校验和预览构建,不启动 CAD。
|
||||
|
||||
| 版本 | 结果 |
|
||||
| --- | --- |
|
||||
| 精简前 | 探针进程运行 285.36 秒仍未完成,主动停止;该值包含建库和生成模板,不能视为完整匹配耗时 |
|
||||
| 精简后 | 校验阶段 5.920 秒,200 行通过、0 行失败,1000 个位号中恰好启用 200 个 |
|
||||
|
||||
临时探针位于 `build/probe-bom-scale-audit.py`,前后结果分别保留在 `build/bom-scale-before-20261015/metrics.json` 和 `build/bom-scale-after-20261015/metrics.json`。未将一次性探针加入生产代码。
|
||||
|
||||
此结果不能换算成完整 CAD 替换速度。上一轮千步执行测试未达到 30 秒目标、CAD COM 启动偶发阻塞,仍是独立的未解决项。
|
||||
@@ -75,11 +75,15 @@ def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
|
||||
|
||||
def _log_startup(context: LoggingContext, data_root: Path, database_path: Path) -> None:
|
||||
# platform.platform() queries WMI on Windows; diagnostics must not delay or
|
||||
# fail CAD startup because the WMI provider is slow or out of resources.
|
||||
version = sys.getwindowsversion() if os.name == 'nt' else None
|
||||
os_description = f'Windows {version.major}.{version.minor}.{version.build}' if version else platform.platform()
|
||||
context.logger.info(
|
||||
"application_start version=%s executable=%s os=%s data_root=%s database=%s application_log=%s",
|
||||
VERSION,
|
||||
sys.executable,
|
||||
platform.platform(),
|
||||
os_description,
|
||||
data_root,
|
||||
database_path,
|
||||
context.application_log_path,
|
||||
@@ -117,11 +121,6 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
database_path = data_root / "task-center.db"
|
||||
_log_startup(logging_context, data_root, database_path)
|
||||
store = TaskStore(database_path)
|
||||
recovered = store.recover_interrupted_work()
|
||||
if recovered:
|
||||
logging_context.logger.warning("recovered_interrupted_projects=%s", ",".join(recovered))
|
||||
else:
|
||||
logging_context.logger.info("recovered_interrupted_projects=none")
|
||||
service = TaskCenterService(store, logging_context)
|
||||
qt_application = QApplication([sys.executable, *(argv or ())])
|
||||
window = _load_window()(service)
|
||||
|
||||
@@ -112,17 +112,7 @@ class TrialRunner:
|
||||
recovery_event_id=f"v1-attemptless:{recovery.project_id}:task:after",
|
||||
)
|
||||
self._store.acknowledge_migration_recoveries(tuple(recovery.project_id for recovery in migration_recoveries))
|
||||
interrupted_states = {
|
||||
ProjectStatus.CAPTURING_BEFORE,
|
||||
ProjectStatus.CAPTURING_AFTER,
|
||||
ProjectStatus.VERIFYING,
|
||||
}
|
||||
interrupted = tuple(
|
||||
project
|
||||
for task in self._store.list_tasks()
|
||||
for project in self._store.list_projects(task.task_id)
|
||||
if project.status in interrupted_states
|
||||
)
|
||||
interrupted = self._store.interrupted_projects()
|
||||
running_task_ids = {project.task_id for project in interrupted if self._store.get_task(project.task_id).status is TaskStatus.RUNNING}
|
||||
for project in interrupted:
|
||||
self._event_transition(
|
||||
@@ -147,6 +137,8 @@ class TrialRunner:
|
||||
"before",
|
||||
)
|
||||
recovered_project_ids = self._store.recover_interrupted_work()
|
||||
log_recovery = self._logging.logger.warning if recovered_project_ids else self._logging.logger.info
|
||||
log_recovery('recovered_interrupted_projects=%s', ','.join(recovered_project_ids) or 'none')
|
||||
for project_id in recovered_project_ids:
|
||||
project = self._project(project_id)
|
||||
self._event_transition(
|
||||
|
||||
@@ -923,6 +923,16 @@ class TaskStore:
|
||||
with self._lock:
|
||||
return self._project_record(self._project_row(project_id))
|
||||
|
||||
def interrupted_projects(self) -> tuple[ProjectRecord, ...]:
|
||||
"""Read recovery candidates directly, without walking every idle task."""
|
||||
with self._lock:
|
||||
states = tuple(status.value for status in _INTERRUPTED_PROJECT_STATES)
|
||||
rows = self._connection.execute(
|
||||
f"SELECT * FROM projects WHERE status IN ({', '.join('?' for _ in states)}) ORDER BY project_id",
|
||||
states,
|
||||
).fetchall()
|
||||
return tuple(self._project_record(row) for row in rows)
|
||||
|
||||
def recover_interrupted_work(self) -> tuple[str, ...]:
|
||||
"""Mark projects interrupted during capture or verification as retryable failures."""
|
||||
with self.transaction():
|
||||
|
||||
@@ -38,7 +38,7 @@ def test_explicit_data_root_still_overrides_frozen_portable_default(tmp_path: Pa
|
||||
assert application.resolve_data_root(override) == override.resolve()
|
||||
|
||||
|
||||
def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path: Path, monkeypatch) -> None:
|
||||
def test_main_configures_logging_before_qapplication(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
|
||||
@@ -53,9 +53,6 @@ def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path:
|
||||
assert events == ["logging"]
|
||||
self.path = path
|
||||
|
||||
def recover_interrupted_work(self) -> tuple[str, ...]:
|
||||
return ("project-1",)
|
||||
|
||||
def close(self) -> None:
|
||||
events.append("closed")
|
||||
|
||||
@@ -85,7 +82,6 @@ def test_main_configures_logging_before_qapplication_and_logs_recovery(tmp_path:
|
||||
|
||||
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")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import json
|
||||
|
||||
from dx_productivity.trial_task_center import application
|
||||
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
||||
from dx_productivity.trial_task_center.models import ProjectStatus, TaskStatus
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
|
||||
|
||||
def test_idle_startup_does_not_read_projects_of_every_task(tmp_path):
|
||||
store = TaskStore(tmp_path / 'tasks.db')
|
||||
for index in range(30):
|
||||
task = store.create_task(f'Board {index}')
|
||||
store.sync_projects(task.task_id, tmp_path, (tmp_path / f'{index}.prj',))
|
||||
queries = []
|
||||
store._connection.set_trace_callback(queries.append)
|
||||
try:
|
||||
TaskCenterService(store, configure_logging(tmp_path / 'data'))
|
||||
project_reads = [q for q in queries if q.startswith('SELECT * FROM projects WHERE task_id')]
|
||||
assert not project_reads, 'startup scans projects of every idle task'
|
||||
finally:
|
||||
store._connection.set_trace_callback(None)
|
||||
store.close()
|
||||
|
||||
|
||||
def test_application_restart_preserves_before_and_after_recovery_events(tmp_path, monkeypatch):
|
||||
store = TaskStore(tmp_path / 'task-center.db')
|
||||
task = store.create_task('Interrupted')
|
||||
project_path = tmp_path / 'board.prj'
|
||||
project_path.touch()
|
||||
project = store.sync_projects(task.task_id, tmp_path, (project_path,))[0]
|
||||
store.set_project_selected(project.project_id, True)
|
||||
store.add_rule(task.task_id, 'OLD', 'NEW')
|
||||
probe = tmp_path / 'probe.json'
|
||||
probe.write_text('baseline')
|
||||
service = TaskCenterService(store, configure_logging(tmp_path), probe_source_resolver=lambda *_: probe)
|
||||
service.start_task(task.task_id, disposable_copy_confirmed=True)
|
||||
store.close()
|
||||
|
||||
class Application:
|
||||
def __init__(self, _args):
|
||||
pass
|
||||
def exec(self):
|
||||
return 0
|
||||
|
||||
class Window:
|
||||
def __init__(self, service):
|
||||
assert service.get_task(task.task_id).status is TaskStatus.PAUSED
|
||||
assert service.projects(task.task_id)[0].status is ProjectStatus.FAILED
|
||||
def show(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(application, 'QApplication', Application)
|
||||
monkeypatch.setattr(application, '_load_window', lambda: Window)
|
||||
assert application.main(['--data-root', str(tmp_path)]) == 0
|
||||
events = [json.loads(line) for line in (tmp_path / 'tasks' / task.task_id / 'events.jsonl').read_text().splitlines()]
|
||||
recovery = [event for event in events if event['operation'] == 'recover_interrupted_work'
|
||||
and event['project_id'] == project.project_id]
|
||||
assert [event['details']['phase'] for event in recovery] == ['before', 'after']
|
||||
assert f'recovered_interrupted_projects={project.project_id}' in (tmp_path / 'logs/application.log').read_text()
|
||||
Reference in new issue
Block a user