fix: keep resource checks responsive and retain import diagnostics
This commit is contained in:
1 parent
7bdaaeb2ec
commit
656f43e2ff
20 files changed
+455
-48
No files matched your search
@@ -0,0 +1,50 @@
|
||||
# 2026-10-30 优化分支第二轮审查
|
||||
|
||||
本轮在 `.worktrees/project-optimization` 的 `codex/project-optimization` 分支执行。主工作区继续使用 DSH 分支,两个工作目录分别维护各自提交。
|
||||
|
||||
## 已复现并修复的问题
|
||||
|
||||
| 问题 | 触发条件和原因 | 修复 |
|
||||
| --- | --- | --- |
|
||||
| P1:历史资源记录使界面卡顿 | `_update_gates()` 同步调用资源扫描,搜索、选择规则和执行状态更新都会读取全部历史 JSON。500 条已释放记录的一次扫描约需 1.57–1.65 秒 | 新增 `ui/resource_status.py`,后台读取并保留状态快照;初始化、操作收尾和定时复查更新快照,按钮刷新直接读取快照 |
|
||||
| P1:异常退出丢失 BOM 逐行诊断 | `_finish_response()` 在资源复核通过后发现 CAD 退出异常,创建新的 `application_shutdown_failed` 错误,却没有携带原业务错误和 BOM 报告 | 在 `supervisor_result.py` 统一构造退出错误,保留原错误、清理错误和逐行报告;移除报告中的可执行预览 |
|
||||
| P2:规则窗口销毁后访问已释放控件 | 封装读取仍在运行时销毁规则窗口,成功和失败回调均只判断逻辑关闭标记,未判断 Qt 对象是否有效 | 回调先检查 `isValid(self)`,丢弃销毁后的结果;两条路径均有实际 Qt 生命周期回归 |
|
||||
| P2:已完成批次仍显示可执行按钮 | 按钮只判断批次存在;处理函数重新筛选任务后发现没有剩余任务,直接返回 | 抽取 `pending_batch_tasks()`,按钮门控、执行和确认范围共用待执行任务列表 |
|
||||
|
||||
资源快照采用保守处理:首次读取未完成或读取失败时阻断执行;操作结束触发的刷新会合并,操作前的旧快照不能解除门禁。周期检查不会取消慢读取。窗口关闭会停止周期检查并丢弃迟到结果。服务层原有执行前资源检查继续作为最终校验。
|
||||
|
||||
## 测量范围
|
||||
|
||||
使用独立临时目录创建合法的已释放资源记录,无 CAD 进程和工程写入。原同步扫描测得:
|
||||
|
||||
- 0 条:三次分别为 2.68、1.83、1.41 毫秒。
|
||||
- 100 条:293.55、277.36、313.80 毫秒。
|
||||
- 500 条:1650.06、1626.25、1569.35 毫秒。
|
||||
|
||||
接入后台快照后,在真实 `TrialTaskCenterWindow`、`TaskCenterService` 和 `TaskStore` 的空任务窗口中,500 条历史记录下连续调用按钮门控 100 次,总计 6.63 毫秒,期间文件扫描次数为 0。另有已选中任务的 Qt 回归验证后台慢读取期间仍能搜索和响应事件。该结果证明 GUI 热路径移除了扫描,不表示磁盘扫描本身变快,也不代表实际 CAD 替换速度。
|
||||
|
||||
## 前次结论修正
|
||||
|
||||
前次把停止事件轮询从 0.1 秒改成 0.01 秒,并将一次时序测试失败解释为阻塞根因,证据不足。`Event.wait()` 会在事件设置后立即唤醒;初次保护失败后的进度文件写入可能延后重试,固定等待 0.25 秒不能证明保护重试没有发生。
|
||||
|
||||
本轮恢复 0.1 秒等待,回归测试等待明确的强制结束拒绝状态,再检查线程仍存活和保护写入确已重试。不会把这项时序调整计作资源泄漏修复。
|
||||
|
||||
## 测试入口修正
|
||||
|
||||
全仓收集发现 `tests/ui/test_execution_feedback.py` 与 `tests/v1_1/test_execution_feedback.py` 的模块名冲突。UI 文件更名为 `test_ui_execution_feedback.py` 并更新文档引用。
|
||||
|
||||
默认 `python -m pytest -q` 仅覆盖 `tests/v1_1`,不能称为整个仓库测试。全仓历史测试曾启动,随后为实施新确认的 GUI 阻塞修复而主动停止,未将该次运行记作完整通过。当前验证覆盖新版测试、UI 和项目发布要求的安全子集。
|
||||
|
||||
本轮未进行真实 DxDesigner 工程替换或冻结包验收;现场桌面引用残留仍需实际故障机器的进程与句柄证据。
|
||||
|
||||
## 最终验证
|
||||
|
||||
```powershell
|
||||
python -m pytest -q tests/v1_1 tests/ui tests/part_replace/test_verification.py tests/trial_task_center/test_execution_safety.py tests/trial_task_center/test_application.py --durations=5
|
||||
```
|
||||
|
||||
结果:960 passed,1 项既有 pywinauto STA 警告,462.49 秒。此命令覆盖新版测试、UI 和发布安全子集。
|
||||
|
||||
安全停止的真实子进程测试曾在收到首条阶段进度前触发 0.6 秒启动超时,未进入其要验证的保存/强制结束路径。测试现将启动预算与阶段无进度时限区分,并断言目标阶段确实被接收;保存和只读阶段的原 0.3 秒时限继续有效。生产监控超时参数未修改。
|
||||
|
||||
`python -m compileall -q src` 和 `git diff --check` 均通过。
|
||||
@@ -30,7 +30,7 @@
|
||||
| 已完成任务状态、重试、重复执行新轮次 | tests/v1_1/test_ui_batch_retry.py;test_new_round.py |
|
||||
| 任务切换丢弃旧查询、执行期间只读浏览、归属不丢失 | tests/v1_1/test_ui_responsiveness.py |
|
||||
| 常规 mutation 禁止重入,退出等待安全收尾,强制销毁回调 | tests/ui/test_trial_task_center_workflow.py;tests/v1_1/test_ui_remediation.py |
|
||||
| 错误编号及日志格式、按需创建/关闭/重新打开日志 | tests/ui/test_execution_feedback.py;tests/v1_1/test_lazy_components.py;test_execution_results_view.py |
|
||||
| 错误编号及日志格式、按需创建/关闭/重新打开日志 | tests/ui/test_ui_execution_feedback.py;tests/v1_1/test_lazy_components.py;test_execution_results_view.py |
|
||||
| 小窗口和布局持久化 | tests/ui/test_value_options_layout.py;tests/v1_1/test_ui_workspace.py |
|
||||
|
||||
## 验收进度
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
|
||||
现在该异常同时保留在诊断字段和资源错误集合中,批次状态保持 `blocked`,不会继续重建。外层上下文再次退出时也不会立即重复 close 并把 blocked 改写为 released。已有 `manual_retry` 清理入口仍可在资源状态修复后重新尝试释放。
|
||||
|
||||
上一轮的安全停止证据重试修复仍在本分支中:保护记录 fsync 失败后采用短轮询,强制结束前必须成功写入保护证据。
|
||||
后续审查撤回了上一轮把等待间隔从 0.1 秒缩短到 0.01 秒的调整:事件设置会立即唤醒等待线程,原先的固定时长测试不足以证明该参数是阻塞根因。强制结束前必须成功写入保护证据的约束保留。详见 [第二轮审查](../reviews/2026-10-30-project-optimization-review.md)。
|
||||
|
||||
## 回归证据
|
||||
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"date": "2026-10-30",
|
||||
"scenario": "temporary directories containing valid released resource records; no CAD",
|
||||
"synchronous_scan_samples": [
|
||||
{"released_sessions": 0, "milliseconds": [2.68, 1.83, 1.41]},
|
||||
{"released_sessions": 100, "milliseconds": [293.55, 277.36, 313.8]},
|
||||
{"released_sessions": 500, "milliseconds": [1650.06, 1626.25, 1569.35]}
|
||||
],
|
||||
"gui_after_background_snapshot": {
|
||||
"released_sessions": 500,
|
||||
"gate_refreshes": 100,
|
||||
"total_milliseconds": 6.63,
|
||||
"filesystem_scans_during_gate_refreshes": 0
|
||||
}
|
||||
}
|
||||
@@ -218,7 +218,7 @@ def _environment():
|
||||
def _finish_response(root, journal, response, context):
|
||||
"""A supervisor exit may release its last USER reference. Never repeat work."""
|
||||
from .batch_resources import cleanup_pending_resources, write_record
|
||||
from .supervisor_result import validated_outcome, resource_pending_error
|
||||
from .supervisor_result import validated_outcome, resource_pending_error, application_shutdown_error
|
||||
result, error, primary = validated_outcome(journal['operation'], response)
|
||||
pending = cleanup_pending_resources(root, logging_context=context)
|
||||
related = tuple(item for item in pending if item.get('session_id') == journal['batch_id'] or not item.get('session_id'))
|
||||
@@ -238,10 +238,7 @@ def _finish_response(root, journal, response, context):
|
||||
if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
|
||||
or shutdown.get('diagnostic_errors')
|
||||
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
|
||||
failure = TaskCenterError('application_shutdown_failed',
|
||||
'已核验业务结果保留,但应用未正常收尾;请查看退出诊断,不能将资源消失视为正常退出。')
|
||||
failure.completed_result, failure.cleanup_error = result, error
|
||||
raise failure
|
||||
raise application_shutdown_error(result, error, primary)
|
||||
if response.get('business_succeeded'):
|
||||
if response.get('error'):
|
||||
context.logger.info('supervisor_resource_recovery_passed batch_id=%s business_replayed=false', journal['batch_id'])
|
||||
|
||||
@@ -68,11 +68,7 @@ def wait_for_resolution(control, root, error):
|
||||
resolution_error=str(error), stop_requested=True, safe_stop=False)
|
||||
_publish_progress(root / 'worker-progress.json', record)
|
||||
while True:
|
||||
# Keep the retry latency short. The caller may have already requested
|
||||
# force while the initial protection write was failing; a long polling
|
||||
# interval makes the UI appear stuck and widens the window in which a
|
||||
# forced-stop request can be observed before its evidence is retried.
|
||||
if control.force_event.wait(.01):
|
||||
if control.force_event.wait(.1):
|
||||
try:
|
||||
protect()
|
||||
except OSError as failure:
|
||||
|
||||
@@ -48,3 +48,24 @@ def resource_pending_error(operation, result, error, primary_error=None):
|
||||
elif getattr(error, 'bom_report', None) is not None:
|
||||
failure.bom_report = replace(error.bom_report, preview=None)
|
||||
return failure
|
||||
|
||||
|
||||
def application_shutdown_error(result, error, primary_error=None):
|
||||
"""Retain diagnostics, but never expose a plan after abnormal shutdown."""
|
||||
from dataclasses import replace
|
||||
from .bom_import_report import BomImportReport
|
||||
from .errors import TaskCenterError
|
||||
|
||||
if isinstance(result, BomImportReport):
|
||||
result = replace(result, preview=None)
|
||||
failure = TaskCenterError('application_shutdown_failed',
|
||||
'应用未正常收尾,已有报告和核验结果保留;请查看退出诊断。')
|
||||
failure.completed_result = result
|
||||
failure.cleanup_error = error
|
||||
failure.primary_error = primary_error
|
||||
for candidate in (result, getattr(error, 'bom_report', None),
|
||||
getattr(primary_error, 'bom_report', None)):
|
||||
if isinstance(candidate, BomImportReport):
|
||||
failure.bom_report = replace(candidate, preview=None)
|
||||
break
|
||||
return failure
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Task metadata and replacement-rule editing dialogs."""
|
||||
from PySide6.QtCore import QSignalBlocker, QThreadPool
|
||||
from shiboken6 import isValid
|
||||
from PySide6.QtWidgets import (QWidget, QDialog, QLineEdit, QTextEdit, QFormLayout, QLabel,
|
||||
QDialogButtonBox, QCheckBox, QComboBox, QPushButton, QHBoxLayout)
|
||||
from .workers import ServiceWorker
|
||||
@@ -151,7 +152,8 @@ class _MappingDialog(QDialog):
|
||||
worker = ServiceWorker(lambda: self._cell_loader(pn))
|
||||
self._cell_workers.add(worker)
|
||||
def current():
|
||||
if self._cell_closed or generation != self._cell_generation or pn != self.new_edit.text().strip():
|
||||
if (not isValid(self) or self._cell_closed or generation != self._cell_generation
|
||||
or pn != self.new_edit.text().strip()):
|
||||
return False
|
||||
try:
|
||||
same_context = context == self._cell_context()
|
||||
|
||||
@@ -3,6 +3,15 @@ from dataclasses import dataclass
|
||||
from ..models import TaskStatus
|
||||
|
||||
|
||||
def pending_batch_tasks(tasks, group_id):
|
||||
"""Use the persisted batch order for both execution and its UI controls."""
|
||||
if not group_id:
|
||||
return ()
|
||||
return tuple(sorted((task for task in tasks if task.group_id == group_id
|
||||
and task.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}),
|
||||
key=lambda task: task.group_position))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class ExecutionState:
|
||||
editable: bool = False
|
||||
|
||||
@@ -11,7 +11,7 @@ from ..errors import TaskCenterError
|
||||
from ..models import TaskStatus
|
||||
from ..version import VERSION
|
||||
from .dialogs import _TaskDialog, _MappingDialog
|
||||
from .execution_state import execution_state
|
||||
from .execution_state import execution_state, pending_batch_tasks
|
||||
from .mapping_table import MappingTable
|
||||
from .messages import ERROR_TEXT, _format_live_log_line, format_operation_error
|
||||
from .project_plan import DirectoryTaskDialog, ProjectPlanPanel
|
||||
@@ -21,6 +21,7 @@ from .styles import APP_STYLESHEET
|
||||
from .task_list import TaskList
|
||||
from .workers import ServiceWorker
|
||||
from .queries import LatestQuery
|
||||
from .resource_status import ResourceStatus
|
||||
from .task_log import TaskLogPresenter
|
||||
from .execution_feedback import format_feedback
|
||||
from .operation_state import ContextReadPhase, OperationPhase, OperationState
|
||||
@@ -52,6 +53,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._context_query = LatestQuery(self)
|
||||
self._task_query = LatestQuery(self)
|
||||
self._feedback_query = LatestQuery(self)
|
||||
self._resource_status = ResourceStatus(lambda: service.pending_batch_resources(), self)
|
||||
self._run_started_at = 0.0
|
||||
self._quick_run_elapsed = QElapsedTimer()
|
||||
self._quick_run_timer = QTimer(self)
|
||||
@@ -116,6 +118,8 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
saved = self._layout_settings.value(f'single_project/{name}')
|
||||
if saved is not None:
|
||||
widget.restoreState(saved)
|
||||
self._resource_status.changed.connect(self._update_gates)
|
||||
self._resource_status.refresh()
|
||||
self._refresh_task_list()
|
||||
self._update_gates()
|
||||
if getattr(service, '_supervised', False):
|
||||
@@ -248,6 +252,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._context_query.close()
|
||||
self._task_query.close()
|
||||
self._feedback_query.close()
|
||||
self._resource_status.close()
|
||||
self._log_presenter.query.close()
|
||||
self._quick_run_timer.stop()
|
||||
super().closeEvent(event)
|
||||
@@ -321,9 +326,9 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
|
||||
def _update_gates(self):
|
||||
busy = bool(self._workers) or self._loading
|
||||
resources_pending = bool(self.service.pending_batch_resources())
|
||||
self.run_panel.cleanup_resources_button.setVisible(resources_pending)
|
||||
self.run_panel.cleanup_resources_button.setEnabled(resources_pending and not busy)
|
||||
resources_pending = self._resource_status.blocked
|
||||
self.run_panel.cleanup_resources_button.setVisible(resources_pending and self._resource_status.known)
|
||||
self.run_panel.cleanup_resources_button.setEnabled(resources_pending and self._resource_status.known and not busy)
|
||||
state = execution_state(self._context, busy=busy, dirty=self.plan_panel.table.dirty)
|
||||
group_unsaved = self._group_has_unsaved_plans() if state.editable or state.new_round else False
|
||||
context = self._context
|
||||
@@ -377,7 +382,9 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
and t.status is not TaskStatus.DELETED}
|
||||
group_dirty = self.plan_panel.has_unsaved_plan(group_ids)
|
||||
group_active = any(t.status in {TaskStatus.RUNNING, TaskStatus.PAUSED} for t in self._tasks if t.task_id in group_ids)
|
||||
self.task_list.queue_button.setEnabled(grouped and not busy and not group_dirty and not bool(context.interrupted) and not resources_pending)
|
||||
batch_pending = pending_batch_tasks(self._tasks, context.task.group_id if grouped else None)
|
||||
self.task_list.queue_button.setEnabled(bool(batch_pending) and not busy and not group_dirty
|
||||
and not context.interrupted and not resources_pending)
|
||||
for button in (self.task_list.up_button, self.task_list.down_button):
|
||||
button.setEnabled(grouped and not busy and not group_active
|
||||
and self.task_list.sort.currentData() == 'execution'
|
||||
@@ -388,7 +395,9 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if self._loading and not self._message:
|
||||
self.run_panel.operator_band.setText('正在读取任务,可继续选择其他任务。')
|
||||
if not busy:
|
||||
self.run_panel.execution_status.setText('资源待清理' if resources_pending else '任务读取失败' if read_failed else
|
||||
self.run_panel.execution_status.setText('正在检查后台资源' if not self._resource_status.known else
|
||||
'资源状态读取失败' if self._resource_status.error is not None else
|
||||
'资源待清理' if resources_pending else '任务读取失败' if read_failed else
|
||||
'结果待核验' if context and context.interrupted else '空闲')
|
||||
|
||||
def _group_has_unsaved_plans(self):
|
||||
@@ -557,8 +566,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
if not self.task_list.queue_button.isEnabled():
|
||||
return
|
||||
group = self._context.task.group_id
|
||||
tasks = sorted((t for t in self._tasks if t.group_id == group and t.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED}),
|
||||
key=lambda t: t.group_position)
|
||||
tasks = pending_batch_tasks(self._tasks, group)
|
||||
if not tasks:
|
||||
return
|
||||
token, ids = self._project_queues.get(group, (None, tuple(t.task_id for t in tasks)))
|
||||
@@ -655,10 +663,10 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
def _startup_resource_recheck(self):
|
||||
if self._closed:
|
||||
return
|
||||
if self._workers or self._loading:
|
||||
if self._workers or self._loading or not self._resource_status.known or self._resource_status.busy:
|
||||
QTimer.singleShot(250, self._startup_resource_recheck)
|
||||
return
|
||||
if self.service.pending_batch_resources():
|
||||
if self._resource_status.blocked:
|
||||
self._update_gates()
|
||||
self._cleanup_batch_resources() # Resource-only; never resumes a queue.
|
||||
|
||||
@@ -757,8 +765,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
def _confirm_quick_run(self, scope, selected_projects, enabled_rules):
|
||||
context = self._context
|
||||
names = context.project.path if scope == 'current' else '\n'.join(
|
||||
f'{t.group_position+1}. {t.name}' for t in sorted(self._tasks, key=lambda t: t.group_position)
|
||||
if t.group_id == context.task.group_id and t.status not in {TaskStatus.DELETED, TaskStatus.COMPLETED})
|
||||
f'{t.group_position+1}. {t.name}' for t in pending_batch_tasks(self._tasks, context.task.group_id))
|
||||
text = (f'执行范围:{names}\n\n' + (f'勾选目标/规则:{enabled_rules}\n' if scope == 'current' else f'按顺序处理 {selected_projects} 个工程任务。\n')
|
||||
+ '逐项执行原生 Replace Part + Library Wins,保留每行 Value/NC 策略;创建备份并自动保存、关闭、重开核验。'
|
||||
+ '\n默认在受监督的私有桌面执行,结束后释放自有 CAD 会话;主桌面可继续查看其他文件。请确保待处理工程未在其他 CAD 会话中打开。'
|
||||
@@ -880,6 +887,7 @@ class TrialTaskCenterWindow(QMainWindow):
|
||||
self._workers.discard(worker)
|
||||
if not isValid(self) or self._closed:
|
||||
return
|
||||
self._resource_status.refresh()
|
||||
self.plan_panel.finish_operation(error=operation_error)
|
||||
self._close_saving = False
|
||||
if self._close_pending and not self._closed:
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Background resource checks with a conservative snapshot for UI controls."""
|
||||
from PySide6.QtCore import QObject, QTimer, Signal
|
||||
|
||||
from .queries import LatestQuery
|
||||
|
||||
|
||||
class ResourceStatus(QObject):
|
||||
changed = Signal()
|
||||
|
||||
def __init__(self, read, parent=None):
|
||||
super().__init__(parent)
|
||||
self._read = read
|
||||
self._query = LatestQuery(self)
|
||||
self._query.settled.connect(self._settled)
|
||||
self._refresh_again = False
|
||||
self._closed = False
|
||||
self.known = False
|
||||
self.records = ()
|
||||
self.error = None
|
||||
self._timer = QTimer(self)
|
||||
self._timer.setInterval(2000)
|
||||
self._timer.timeout.connect(self._poll)
|
||||
self._timer.start()
|
||||
|
||||
@property
|
||||
def busy(self):
|
||||
return self._query.busy
|
||||
|
||||
@property
|
||||
def blocked(self):
|
||||
return not self.known or self.error is not None or bool(self.records)
|
||||
|
||||
def refresh(self):
|
||||
if self._closed:
|
||||
return
|
||||
if self.busy:
|
||||
# An operation finished during this read. Recheck afterward rather
|
||||
# than letting an older result clear the resource gate.
|
||||
self._refresh_again = True
|
||||
return
|
||||
self._query.request(self._read, self._received, self._failed)
|
||||
|
||||
def _poll(self):
|
||||
# Slow reads must finish; periodic polling must not invalidate them.
|
||||
if not self.busy:
|
||||
self.refresh()
|
||||
|
||||
def _received(self, records):
|
||||
if self._refresh_again:
|
||||
return
|
||||
self.records = tuple(records)
|
||||
self.known = True
|
||||
self.error = None
|
||||
self.changed.emit()
|
||||
|
||||
def _failed(self, error):
|
||||
self.known = True
|
||||
self.error = error
|
||||
self.changed.emit()
|
||||
|
||||
def _settled(self):
|
||||
if self._refresh_again and not self._closed:
|
||||
self._refresh_again = False
|
||||
self.refresh()
|
||||
|
||||
def close(self):
|
||||
self._closed = True
|
||||
self._timer.stop()
|
||||
self._query.close()
|
||||
@@ -36,7 +36,7 @@ def ui(qtbot, tmp_path):
|
||||
def settle():
|
||||
qtbot.waitUntil(lambda:not window._workers and not window._task_query.busy
|
||||
and not window._context_query.busy and not window._feedback_query.busy
|
||||
and not window._log_presenter.query.busy,timeout=5000)
|
||||
and not window._log_presenter.query.busy and not window._resource_status.busy,timeout=5000)
|
||||
def open_task(task):
|
||||
window.open_task(task.task_id)
|
||||
qtbot.waitUntil(lambda:not window._context_query.busy and not window._loading,timeout=5000)
|
||||
|
||||
@@ -23,6 +23,20 @@ def test_current_task_executes_only_after_confirmation_and_no_match_is_completed
|
||||
assert w.run_panel.new_round_button.isEnabled()
|
||||
|
||||
|
||||
def test_batch_execute_button_tracks_remaining_tasks(ui):
|
||||
w = ui.window
|
||||
w._quick_run_confirmer = lambda *_args: True
|
||||
w._prepare_quick_run()
|
||||
ui.settle()
|
||||
# A completed selection must still allow execution of its pending sibling.
|
||||
assert w.task_list.queue_button.isEnabled()
|
||||
w.task_list.queue_button.click()
|
||||
ui.settle()
|
||||
assert len(ui.calls) == 2
|
||||
assert not w.task_list.queue_button.isEnabled(), 'a completed batch must not offer a no-op execution button'
|
||||
assert w.run_panel.new_round_button.isEnabled()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('value',[False,True])
|
||||
def test_changed_value_policy_stops_stale_confirmation_before_worker(ui,value):
|
||||
w=ui.window;task=ui.tasks[0]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Readable logs and execution feedback on the current project-task interface."""
|
||||
"""UI log and feedback coverage, collectable alongside the service feedback tests."""
|
||||
import json
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.ui.messages import (
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Resource snapshots stay conservative during slow, failed and repeated reads."""
|
||||
import os
|
||||
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
|
||||
|
||||
from threading import Event
|
||||
|
||||
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
|
||||
|
||||
|
||||
def test_resource_read_failure_blocks_until_a_successful_recheck(qtbot):
|
||||
outcome = [()]
|
||||
def read():
|
||||
if isinstance(outcome[0], Exception):
|
||||
raise outcome[0]
|
||||
return outcome[0]
|
||||
status = ResourceStatus(read)
|
||||
try:
|
||||
assert status.blocked and not status.known
|
||||
status.refresh()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert status.known and not status.blocked
|
||||
outcome[0] = OSError('resource directory unavailable')
|
||||
status.refresh()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert status.blocked and isinstance(status.error, OSError)
|
||||
outcome[0] = ()
|
||||
status.refresh()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert not status.blocked and status.error is None
|
||||
finally:
|
||||
status.close()
|
||||
|
||||
|
||||
def test_operation_completion_coalesces_recheck_and_ignores_the_stale_clear_snapshot(qtbot):
|
||||
started, release = Event(), Event()
|
||||
calls, states = [], []
|
||||
def read():
|
||||
calls.append(1)
|
||||
if len(calls) == 1:
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return ()
|
||||
return ({'state': 'blocked'},)
|
||||
status = ResourceStatus(read)
|
||||
status.changed.connect(lambda: states.append(status.blocked))
|
||||
try:
|
||||
status.refresh()
|
||||
qtbot.waitUntil(started.is_set)
|
||||
for _ in range(10):
|
||||
status.refresh()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert len(calls) == 2
|
||||
assert status.records == ({'state': 'blocked'},)
|
||||
assert states == [True], 'a pre-operation snapshot must not briefly unlock CAD actions'
|
||||
finally:
|
||||
release.set()
|
||||
status.close()
|
||||
|
||||
|
||||
def test_polling_does_not_restart_a_slow_resource_read(qtbot):
|
||||
started, release = Event(), Event()
|
||||
calls = []
|
||||
def read():
|
||||
calls.append(1)
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return ()
|
||||
status = ResourceStatus(read)
|
||||
try:
|
||||
status.refresh()
|
||||
qtbot.waitUntil(started.is_set)
|
||||
for _ in range(10):
|
||||
status._poll()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert status.known and not status.blocked
|
||||
assert len(calls) == 1
|
||||
finally:
|
||||
release.set()
|
||||
status.close()
|
||||
|
||||
|
||||
def test_close_cancels_polling_and_drops_late_resource_results(qtbot):
|
||||
started, release = Event(), Event()
|
||||
changes = []
|
||||
def read():
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
return ()
|
||||
status = ResourceStatus(read)
|
||||
status.changed.connect(lambda: changes.append(True))
|
||||
try:
|
||||
status.refresh()
|
||||
qtbot.waitUntil(started.is_set)
|
||||
status.close()
|
||||
assert not status._timer.isActive()
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not status.busy)
|
||||
assert status.blocked and changes == []
|
||||
finally:
|
||||
release.set()
|
||||
status.close()
|
||||
@@ -9,6 +9,21 @@ import pytest
|
||||
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch, run_monitored_process
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def started_worker_watch(monkeypatch):
|
||||
"""Test phase timeouts after real child startup, with a bounded startup grace."""
|
||||
stages = set()
|
||||
action = ProgressWatch.action
|
||||
def after_start(watch, now):
|
||||
if not watch.sequence and now - watch.started < 5:
|
||||
return None
|
||||
if watch.sequence:
|
||||
stages.add(watch.stage)
|
||||
return action(watch, now)
|
||||
monkeypatch.setattr(ProgressWatch, 'action', after_start)
|
||||
return stages
|
||||
|
||||
|
||||
def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
|
||||
watch = ProgressWatch('token', 'job', 10, 0)
|
||||
assert watch.accept(b'DX_PROGRESS\ttoken\tjob\t1\tsave_and_close\t0\t1\t0\n', 0)
|
||||
@@ -20,7 +35,7 @@ def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
|
||||
assert watch.snapshot(now=201)['waiting_for_safe_completion'] is False
|
||||
|
||||
|
||||
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path):
|
||||
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path, started_worker_watch):
|
||||
script = tmp_path / 'save.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
@@ -32,10 +47,11 @@ time.sleep(1.5)
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
result = run_monitored_process(command, .3)
|
||||
assert result.returncode == 0
|
||||
assert 'save_and_close' in started_worker_watch
|
||||
assert (tmp_path / 'saved.txt').read_text() == 'saved and independently verified'
|
||||
|
||||
|
||||
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path):
|
||||
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path, started_worker_watch):
|
||||
script = tmp_path / 'read.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
@@ -46,9 +62,10 @@ time.sleep(1.5)
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
with pytest.raises(subprocess.TimeoutExpired):
|
||||
run_monitored_process(command, .3, cooperative_abort=True)
|
||||
assert 'native_snapshot_read' in started_worker_watch
|
||||
|
||||
|
||||
def test_explicit_force_stops_unsafe_worker_with_protection(tmp_path):
|
||||
def test_explicit_force_stops_unsafe_worker_with_protection(tmp_path, monkeypatch):
|
||||
script = tmp_path / 'save.py'
|
||||
script.write_text('''import sys,time,pathlib
|
||||
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
|
||||
@@ -59,22 +76,20 @@ time.sleep(30)
|
||||
(root/'unexpected_completed').touch()
|
||||
''', encoding='utf-8')
|
||||
force = Event()
|
||||
def request():
|
||||
for _ in range(200):
|
||||
if (tmp_path / 'started').exists():
|
||||
force.set()
|
||||
return
|
||||
Event().wait(.01)
|
||||
requester = Thread(target=request)
|
||||
requester.start()
|
||||
accept = ProgressWatch.accept
|
||||
def force_after_unsafe_progress(watch, line, now):
|
||||
accepted = accept(watch, line, now)
|
||||
if accepted and watch.stage == 'save_and_close' and not watch.safe_stop:
|
||||
force.set()
|
||||
return accepted
|
||||
monkeypatch.setattr(ProgressWatch, 'accept', force_after_unsafe_progress)
|
||||
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
|
||||
try:
|
||||
with pytest.raises(Exception, match='forced'):
|
||||
run_monitored_process(command, .3, force_event=force)
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
assert not (tmp_path / 'unexpected_completed').exists()
|
||||
finally:
|
||||
requester.join(3)
|
||||
# This checks force at an accepted unsafe boundary, not startup speed.
|
||||
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
|
||||
with pytest.raises(WorkerMonitorError, match='forced'):
|
||||
run_monitored_process(command, 5, force_event=force)
|
||||
assert (tmp_path / 'uncertain.flag').exists()
|
||||
assert not (tmp_path / 'unexpected_completed').exists()
|
||||
|
||||
|
||||
def test_abnormal_cad_shutdown_is_not_hidden_by_physical_release(tmp_path):
|
||||
@@ -228,7 +243,14 @@ def test_failed_protection_fsync_is_retried_before_force_is_allowed(tmp_path, mo
|
||||
Event().wait(.01)
|
||||
assert control.control_error
|
||||
control.request_force()
|
||||
thread.join(.25)
|
||||
# Initial progress publication can still be doing filesystem I/O.
|
||||
# Observe the rejected force request instead of assuming it reaches
|
||||
# the retry within a fixed quarter-second scheduling window.
|
||||
for _ in range(300):
|
||||
if control.control_error:
|
||||
break
|
||||
Event().wait(.01)
|
||||
assert control.control_error
|
||||
assert thread.is_alive(), 'a file left by failed fsync must not authorize force'
|
||||
assert len(attempts) >= 2
|
||||
monkeypatch.setattr(module.os, 'fsync', original)
|
||||
|
||||
@@ -21,3 +21,47 @@ def test_pending_cleanup_cannot_expose_bom_preview():
|
||||
error=resource_pending_error('inspect_bom_batch',report,OSError('held desktop'))
|
||||
assert error.completed_result.preview is None
|
||||
assert error.bom_report.preview is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize('business_succeeded', [True, False])
|
||||
def test_abnormal_shutdown_retains_bom_rows_without_an_executable_preview(tmp_path, business_succeeded):
|
||||
from dx_productivity.trial_task_center.batch_resources import write_record
|
||||
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
|
||||
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview
|
||||
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
|
||||
from dx_productivity.trial_task_center.bom_import_state import BomImportMachine
|
||||
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.supervisor_protocol import encode, encode_error
|
||||
|
||||
report = BomImportReport((BomRowResult(4, 'board.prj', 'Board', 'failed', 'R99 missing'),), (),
|
||||
BomBatchPreview('task', (), ()) if business_succeeded else None)
|
||||
primary = TaskCenterError('inventory_cleanup', 'inventory reader failed')
|
||||
primary.bom_report = report
|
||||
journal = {'operation': 'inspect_bom_batch', 'batch_id': 'a' * 32, 'state': 'blocked'}
|
||||
write_record(tmp_path / 'batch-resources' / journal['batch_id'] / 'session.json', {
|
||||
'version': 1, 'session_id': journal['batch_id'], 'kind': 'bom_import', 'state': 'released',
|
||||
'generation': 1, 'desktop': 'dx-' + 'b' * 32, 'processes': [], 'cad_pid': None,
|
||||
'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
|
||||
'cad_shutdown': {'clean': False, 'orderly_shutdown': False}})
|
||||
response = {'business_succeeded': business_succeeded, 'status': 'error',
|
||||
'error': encode_error(TaskCenterError('batch_resources_pending', 'Quit failed'))}
|
||||
if business_succeeded:
|
||||
response['result'] = encode(report)
|
||||
else:
|
||||
response['operation_error'] = encode_error(primary)
|
||||
machine = BomImportMachine()
|
||||
attempt = machine.start()
|
||||
with pytest.raises(TaskCenterError) as caught:
|
||||
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
|
||||
failure = caught.value
|
||||
assert failure.code == 'application_shutdown_failed'
|
||||
machine.finish(attempt, error=failure)
|
||||
assert machine.state.report is not None, 'shutdown errors must preserve Excel row diagnostics'
|
||||
assert machine.state.report.rows[0].excel_row == 4
|
||||
assert machine.state.report.rows[0].reason == 'R99 missing'
|
||||
assert machine.state.report.preview is None
|
||||
if business_succeeded:
|
||||
assert failure.completed_result.preview is None
|
||||
else:
|
||||
assert failure.primary_error.code == 'inventory_cleanup'
|
||||
@@ -265,6 +265,33 @@ def test_dialog_discards_choices_when_project_binding_changes_before_delivery(qt
|
||||
assert '工程' in dialog.cell_status.text()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reader_fails', [False, True])
|
||||
def test_destroyed_mapping_dialog_ignores_pending_cell_reader(qtbot, reader_fails):
|
||||
from PySide6.QtCore import QCoreApplication, QEvent, QThreadPool
|
||||
from shiboken6 import isValid
|
||||
|
||||
release, started = Event(), Event()
|
||||
def load(_part):
|
||||
started.set()
|
||||
assert release.wait(5)
|
||||
if reader_fails:
|
||||
raise OSError('late library failure')
|
||||
return ('CellA',)
|
||||
dialog = _MappingDialog(None, 'OLD', 'NEW', cell_loader=load)
|
||||
dialog.cell_load_button.click()
|
||||
try:
|
||||
qtbot.waitUntil(started.is_set)
|
||||
dialog.deleteLater()
|
||||
QCoreApplication.sendPostedEvents(dialog, QEvent.Type.DeferredDelete)
|
||||
assert not isValid(dialog)
|
||||
finally:
|
||||
release.set()
|
||||
with qtbot.captureExceptions() as exceptions:
|
||||
assert QThreadPool.globalInstance().waitForDone(5000)
|
||||
QCoreApplication.processEvents()
|
||||
assert not exceptions, 'completed readers must not access destroyed dialog widgets'
|
||||
|
||||
|
||||
def test_update_rejects_non_text_cell_instead_of_clearing(batch):
|
||||
app, store, tasks = batch
|
||||
rule = app.add_rule(tasks[0].task_id, 'OLD', 'NEW', target_cell='Existing')
|
||||
|
||||
@@ -20,13 +20,14 @@ def test_pending_batch_resources_block_new_work_and_cleanup_does_not_replace(win
|
||||
pending.clear()
|
||||
return ()
|
||||
monkeypatch.setattr(window.service, 'cleanup_batch_resources', cleanup)
|
||||
window._update_gates()
|
||||
window._resource_status.refresh()
|
||||
qtbot.waitUntil(lambda: not window._resource_status.busy)
|
||||
assert not window.run_panel.quick_run_button.isEnabled()
|
||||
assert not window.plan_panel.collect_button.isEnabled()
|
||||
assert not window.plan_panel.import_bom_button.isEnabled()
|
||||
assert window.run_panel.cleanup_resources_button.isEnabled()
|
||||
window.run_panel.cleanup_resources_button.click()
|
||||
qtbot.waitUntil(lambda: not window._workers)
|
||||
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
|
||||
assert calls == ['cleanup']
|
||||
assert not window.run_panel.cleanup_resources_button.isEnabled()
|
||||
assert '已释放' in window.run_panel.operator_band.text()
|
||||
|
||||
@@ -40,6 +40,35 @@ def loaded(qtbot, window, task):
|
||||
and window._context.task.task_id == task.task_id, timeout=3000)
|
||||
|
||||
|
||||
def test_resource_scan_never_runs_in_gate_refresh_and_keeps_event_loop_responsive(browser, qtbot, monkeypatch):
|
||||
window, service, (task, _) = browser
|
||||
window.open_task(task.task_id)
|
||||
loaded(qtbot, window, task)
|
||||
entered, release = Event(), Event()
|
||||
gui_thread = get_ident()
|
||||
def slow_resources():
|
||||
assert get_ident() != gui_thread, 'resource files must not be read on the GUI thread'
|
||||
entered.set()
|
||||
assert release.wait(5)
|
||||
return ({'state': 'blocked'},)
|
||||
monkeypatch.setattr(service, 'pending_batch_resources', slow_resources)
|
||||
try:
|
||||
window._update_gates()
|
||||
window._resource_status.refresh()
|
||||
qtbot.waitUntil(entered.is_set)
|
||||
tick = []
|
||||
QTimer.singleShot(0, lambda: tick.append(True))
|
||||
window.task_list.search.setText('board')
|
||||
window._update_gates()
|
||||
qtbot.waitUntil(lambda: bool(tick))
|
||||
assert not release.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
qtbot.waitUntil(lambda: not window._resource_status.busy)
|
||||
assert window.run_panel.cleanup_resources_button.isEnabled()
|
||||
assert not window.run_panel.quick_run_button.isEnabled()
|
||||
|
||||
|
||||
def test_slow_task_read_is_background_and_stale_result_cannot_change_selection(browser, qtbot, monkeypatch):
|
||||
window, service, (a, b) = browser
|
||||
real = service.task_context
|
||||
|
||||
Reference in new issue
Block a user