Compare commits

..
Author SHA1 Message Date
阿白叔 4fb715507e fix: recheck private desktop release with writer exit proof
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
Core regression / Python core, intervention UI and release configuration (pull_request) Waiting to run
Core regression / JavaScript syntax (pull_request) Waiting to run
2026-11-25 10:35:39 +08:00
abaishu0730 c114db9f31 Merge pull request 'fix: DxDataBook 写入前加载、超时证据与有限重试(#33 D6)' (#37) from codex/issue33-d6 into main
Core regression / Python core, intervention UI and release configuration (push) Waiting to run
Core regression / JavaScript syntax (push) Waiting to run
2026-11-25 10:12:30 +08:00
abaishu0730 8ccc9716de Merge pull request 'fix: 同一数据目录只启动一个主窗口(#33 D1)' (#35) from codex/issue33-d1 into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m28s
Core regression / JavaScript syntax (push) Successful in 8s
2026-11-25 09:57:58 +08:00
abaishu0730 29b40a5370 Merge pull request 'fix: 工程路径错误给出可执行提示(#33 D2)' (#34) from codex/issue33-d2 into main
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m20s
Core regression / JavaScript syntax (push) Successful in 7s
2026-11-25 09:57:37 +08:00
阿白叔 315d2e85b3 fix: limit the desktop app to one instance per data root
Core regression / Python core, intervention UI and release configuration (push) Successful in 5m36s
Core regression / JavaScript syntax (push) Successful in 9s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m30s
Core regression / JavaScript syntax (pull_request) Successful in 11s
2026-11-25 09:50:12 +08:00
阿白叔 d954b527f5 fix: report actionable project path errors
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m25s
Core regression / JavaScript syntax (push) Successful in 8s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m7s
Core regression / JavaScript syntax (pull_request) Successful in 7s
2026-11-25 09:49:54 +08:00
27 changed files with 1017 additions and 60 deletions

No files matched your search

@@ -0,0 +1,37 @@
# Issue 33 D2 · 工程路径错误提示验收
工程读取和任务创建的路径检查直接调用 `lstat()`。目录不存在或扫描后工程移走时,文件系统异常进入统一兜底,现场报告仅能看到“发生未处理异常”。目录存在且能读取属性时,`scandir()` 仍可能因缺少列目录权限失败。
修复在路径检查和读取处分类处理这些预期错误。读取对话框和创建任务的错误提示均显示完整路径、分类代码、处理建议和可关联日志的 `DXT` 编号。预期错误写入一条应用日志。未知异常保留 traceback。
## Windows 11 实测
使用 Qt 按钮启动读取、真实文件系统与任务库。第五例在成功扫描两个候选工程后重命名其中一个文件,从实际服务入口创建选定任务并检查主窗口所用的错误格式和任务数据库。
| 输入 | 基线 `46deb9c` | 修复后代码 | 修复后错误编号 |
| --- | --- | --- | --- |
| 不存在的目录 | 通用兜底 | `path_missing` | `DXT-20261125-3EE8F667` |
| 普通文件作为目录 | 英文非目录文案 | `path_not_directory` | `DXT-20261125-92876D74` |
| 路径中途遇到普通文件 | 通用兜底 | `path_not_directory` | `DXT-20261125-0C615FE8` |
| ACL 拒绝列目录 | 通用兜底 | `path_denied` | `DXT-20261125-ED64EEA9` |
| 工程在扫描后被移走 | 通用兜底 | `path_missing` | `DXT-20261125-CA48D2FF` |
ACL 测试对临时目录中的当前用户拒绝 `FILE_LIST_DIRECTORY`,两个版本的文件系统操作均触发原生 `WinError 5`。创建任务失败后库中仍有 0 条任务。五个路径输入的通用兜底率从 4/5 降到 0/5。额外注入的 `RuntimeError` 对照组仍触发一次 `unhandled_exception`,并保留 traceback。
## 复跑
在仓库根目录运行。使用未占用的临时目录保存测试日志。
```powershell
$env:PYTHONUTF8 = '1'
python -m pytest -q -s tests/v1_1/test_project_path_errors.py tests/v1_1/test_scan_responsiveness.py tests/v1_1/test_project_long_paths.py tests/v1_1/test_path_access.py tests/trial_task_center/test_logging_setup.py --basetemp build/issue33-d2
```
实测 35 项通过。以下命令按错误记录统计扫描和创建任务的通用兜底率。路径用例与故障对照分别统计时,从相应测试目录读取日志。
```powershell
$rows = Get-ChildItem build/issue33-d2 -Recurse -Filter application.log |
Select-String 'error_id=\S+ operation=(scan_project_directory|create_project_tasks) (code=\S+ )?message='
$generic = $rows | Where-Object { $_.Line -match 'code=unhandled_exception |message=发生未处理异常$' }
'{0}/{1}' -f @($generic).Count, @($rows).Count
```
@@ -0,0 +1,14 @@
# Issue #33 D7 · 已保存工程的资源收尾验证
Audio_D2128 历史副本的 `RV05` 换料已保存并通过独立网表核验。Quit 助手退出码为 0,CAD 根进程 15 秒内未退出。执行自有 Job 强退后,Job 活动进程数降到 0,两条后代进程的退出句柄已核验,根进程句柄在随后 5 秒内仍未发出信号。批次保留了根进程的创建时间和强退记录,桌面还未进入关闭阶段。首次失败后,运行时缺少自动复核这一迟到的退出结果的路径。
运行时在已请求强退的收尾失败后等待 0.5、1、2 秒,最多复核三次原有进程树。进程树仍活跃时保留原句柄与阻塞,确认退出时再收尾该代桌面。Windows 进程已收到强退请求后只等待原句柄。已保存工程的任务状态和独立网表回执继续作为业务证据。
历史记录通过 PID 和创建时间确认写进程退出,还要求自有清理记录或绑定到该代 CAD 的空 Job 证明。桌面存在性通过枚举核验。同名受管理桌面经槽位互斥锁检查,新的活动租约在观察期间保持运行。资源记录和业务保护独立持久化。启动和批次收尾的自动观察耗尽后保留已有保护,下一次资源清理可重新取证。
## Windows 证据
- 用原始受阻历史数据的独立副本运行资源清理。槽位锁内确认桌面已经消失,六个已绑定进程均退出,批次由 `blocked` 更新为 `released`。比较前后 SHA-256,任务状态、保存回读、独立网表、关闭检查点和原有 `uncertain.flag` 保持逐字节一致。 [历史副本记录](evidence/2026-11-25-issue33-d7/historical.json)
- 用真实 Win32 私有桌面和独立 Job 验证晚退出。故障注入使 CAD 收尾在子进程实际退出前返回异常,之后自动等待并证明原进程退出,随后退还同一租约。原异常和注入的强退诊断均保留。外部持有者场景确认外部进程存活,桌面先保持隔离,外部持有者退出后复核到物理释放。 [晚退出](evidence/2026-11-25-issue33-d7/delayed-owned-exit.json) [外部持有](evidence/2026-11-25-issue33-d7/external-reference.json)
- 真实 Mentor 7.9.5 空闲会话运行正常退出。Quit 助手和 CAD 根进程的退出码均为 0,约 4.375 秒完成关停,桌面释放后资源待处理数为 0。 [正常退出](evidence/2026-11-25-issue33-d7/mentor-idle.json)
- 新建的 Audio_D2128 真实 Mentor 对照在本机完成 BOM 位号核验,执行时停在 `open_project` 276 秒,到 `open_sheet` 安全检查点才返回。工程仍打开,任务保持保护。本轮未在该副本复现保存后的 Mentor 退出,保存侧证据来自上述真实历史数据。
@@ -0,0 +1,17 @@
# Issue #33 D1 同数据目录单实例
`application.main` 原先直接配置日志、打开 `task-center.db` 并执行启动恢复。现场 `data_lock` 日志有两次同根 `application_start`,两实例均成功读取任务列表。现有执行租约只在执行操作中生效。
GUI 现在先取得 `.gui-instance.lock` 的内核文件锁,再打开日志和数据库。第二次启动经 Qt 本地套接字请求激活现有窗口,该窗口写入 `instance_conflict` 并在状态栏提示。锁保持到 SQLite 和后台读线程关闭,进程强制结束时由操作系统回收。启动参数中的工作进程和 CLI 在 GUI 文件锁之前分流。
## Windows 复测
```powershell
$env:QT_QPA_PLATFORM = 'offscreen'
python -m pytest -q tests/v1_1/test_single_instance.py
```
- 四个真实 GUI 子进程并发打开同一目录,其中两个使用大写路径。日志有一次 `application_start`、一次启动恢复和三次 `instance_conflict`,三个转发进程均返回 0。
- 另一个数据目录的窗口与持锁窗口同时存活。同根 `--native-helper` 执行自身参数校验并返回 2,冲突计数仍为三次。
- 强制结束持锁进程后,同根 `--smoke-test` 成功启动并正常关闭,预先写入的任务 ID 仍在 SQLite。另一数据目录的进程继续运行。
- 修改前运行同一并发场景时,三个竞争进程没有退出,测试失败。测试使用 Qt offscreen,验证激活请求已处理。Windows 桌面前台切换和实际 CAD 写入需通过交互式验收复核。
@@ -0,0 +1,74 @@
{
"state": "released",
"generation": 1,
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"release_proof": {
"session_id": "61c734f3d79d42579ca635bbdb996673",
"generation": 1,
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"desktop_handle_closed": true,
"desktop_released": true,
"processes_exited": true,
"processes": [
{
"pid": 11236,
"creation_time": "2026-11-25 02:26:52.007000+00:00"
}
],
"observed_at": 1795573613.951475,
"method": "owned_cleanup"
},
"release_rechecks": [
{
"attempt": 1,
"delay_seconds": 0.5
},
{
"attempt": 2,
"delay_seconds": 1
}
],
"event_timeline": [
{
"phase": "releasing",
"desktop_disappeared": null,
"release_rechecks": []
},
{
"phase": "blocked",
"desktop_disappeared": null,
"release_rechecks": []
},
{
"phase": "releasing",
"desktop_disappeared": null,
"release_rechecks": [
{
"attempt": 1,
"delay_seconds": 0.5
},
{
"attempt": 2,
"delay_seconds": 1
}
]
},
{
"phase": "released",
"desktop_disappeared": true,
"release_rechecks": [
{
"attempt": 1,
"delay_seconds": 0.5
},
{
"attempt": 2,
"delay_seconds": 1
}
]
}
],
"shutdown": {
"forced_termination": true
}
}
@@ -0,0 +1,36 @@
{
"state": "released",
"generation": 1,
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"release_proof": {
"generation": 1,
"desktop_released": true,
"processes_exited": true,
"processes": [],
"method": "restart_observation"
},
"release_rechecks": [],
"event_timeline": [
{
"phase": "releasing",
"desktop_disappeared": null,
"release_rechecks": []
},
{
"phase": "isolated",
"desktop_disappeared": false,
"release_rechecks": []
},
{
"phase": "releasing",
"desktop_disappeared": false,
"release_rechecks": []
},
{
"phase": "released",
"desktop_disappeared": true,
"release_rechecks": []
}
],
"shutdown": null
}
@@ -0,0 +1,88 @@
{
"original_state": "blocked",
"confirmed_state": "released",
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"desktop_absent_under_slot_mutex": true,
"owned_root_observations": [
{
"pid": 62180,
"creation_time": "2026-11-25 02:02:37.882000+00:00",
"gone": true
},
{
"pid": 59508,
"creation_time": "2026-11-25 02:02:38.250000+00:00",
"gone": true
},
{
"pid": 58980,
"creation_time": "2026-11-25 02:03:40.779000+00:00",
"gone": true
},
{
"pid": 60628,
"creation_time": "2026-11-25 02:03:43.660000+00:00",
"gone": true
},
{
"pid": 23736,
"creation_time": "2026-11-25 02:05:22.446000+00:00",
"gone": true
},
{
"pid": 54872,
"creation_time": "2026-11-25 02:05:44.928000+00:00",
"gone": true
}
],
"original_shutdown": {
"orderly_shutdown": false,
"forced_termination": true,
"forced_root_termination": true,
"forced_descendant_pids": [
5216,
51620
],
"quit_helper_exit_code": 0
},
"release_proof": {
"generation": 1,
"desktop_released": true,
"processes_exited": true,
"processes": [
{
"pid": 62180,
"creation_time": "2026-11-25 02:02:37.882000+00:00"
},
{
"pid": 59508,
"creation_time": "2026-11-25 02:02:38.250000+00:00"
},
{
"pid": 58980,
"creation_time": "2026-11-25 02:03:40.779000+00:00"
},
{
"pid": 60628,
"creation_time": "2026-11-25 02:03:43.660000+00:00"
},
{
"pid": 23736,
"creation_time": "2026-11-25 02:05:22.446000+00:00"
},
{
"pid": 54872,
"creation_time": "2026-11-25 02:05:44.928000+00:00"
}
],
"method": "restart_observation"
},
"preserved_sha256": {
"batch-resources/588db35caf664589a499f02800559ff0/generation-1/uncertain.flag": "4a131c344827d0bbe9667dc5534af3d52e472737ec1d1c1c44a792c1ac66f360",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/quick-run/status.tsv": "2afdeacd43812445f616f89da425efe6adf565ff75052e7f587e332b70066338",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/execution-proof/saved-netlist-6f55dbc86cc94adeb3561dfedd30e44a/export/verification.json": "3579e55e5987f9aababe167801c127f4404511f96cc0334de663fc449990b955",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/netlist-checks/2af39a6d4d6143afa3352b8cbe4e4180/verification.json": "f0ed2209fa9de4c97a01da3079da1097e8ab2dc091631c625440a299e23728e3",
"tasks/d5810026-3117-4b2e-9eca-c16b22396dc3/quick-run/project-checkpoint.json": "04d6b04e85b23671b2ce92dd2adc64d673b8c3209813a148214a7322bf0e7e4a"
},
"project_descriptor_sha256_unchanged": true
}
@@ -0,0 +1,36 @@
{
"state": "released",
"desktop": "dx-7f3f2f5227fc2de985373cc53acedcd9",
"shutdown": {
"state": "session_closed",
"clean": true,
"cad_exit_code": 0,
"quit_helper_exit_code": 0,
"cleanup_errors": [],
"shutdown_seconds": 4.375,
"orderly_shutdown": true,
"diagnostic_errors": [],
"forced_termination": false,
"forced_root_termination": false,
"forced_descendant_pids": [],
"termination_reason": null,
"dialog_supervision": {
"evidence_path": "G:\\dx33\\acceptance\\d7-mentor-idle\\batch-resources\\765ec10f41134b80b4d2d7a49ef01fe5\\generation-1\\cad-dialogs-408b2726a75547929b58a0f1fe3bcfbe.json",
"dialogs_seen": 2,
"blocked": false,
"blocking_titles": [],
"current_dialogs": [],
"error": "",
"monitor_error": ""
},
"release_state": "released",
"project_close_policy": "saved_only"
},
"release_results": {
"mentor_released": true,
"desktop_released": true
},
"release_rechecks": [],
"error": null,
"pending": 0
}
@@ -9,12 +9,13 @@ import platform
import sys
from typing import Sequence
from PySide6.QtCore import QTimer, QThreadPool
from PySide6.QtCore import QTimer, QThreadPool, Qt
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QApplication
from dx_productivity.trial_task_center.logging_setup import LoggingContext, configure_logging, install_exception_hooks
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.single_instance import InstanceUnavailable, gui_instance, listen_for_activation
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.version import VERSION
@@ -161,10 +162,28 @@ def main(argv: Sequence[str] | None = None) -> int:
from dx_productivity.trial_task_center.sceneos_cli import run
return run(data_root)
try:
with gui_instance(data_root) as endpoint:
if endpoint is None:
return 0
return _run_gui(argv, arguments, data_root, endpoint)
except (OSError, InstanceUnavailable) as error:
message = f'无法打开 DxPartReplace。\n{data_root}\n{error}'
if sys.stderr is not None:
print(message, file=sys.stderr)
if os.name == 'nt' and bool(getattr(sys, 'frozen', False)):
import ctypes
ctypes.windll.user32.MessageBoxW(None, message, 'DxPartReplace', 0x30)
return 1
def _run_gui(argv, arguments, data_root, endpoint):
logging_context = configure_logging(data_root)
install_exception_hooks(logging_context)
store: TaskStore | None = None
window = None
activation_server = None
try:
database_path = data_root / "task-center.db"
_log_startup(logging_context, data_root, database_path)
@@ -177,6 +196,16 @@ def main(argv: Sequence[str] | None = None) -> int:
configure_application_identity(qt_application)
window = _load_window()(service)
window.show()
def activate():
logging_context.logger.info('instance_conflict data_root=%s', data_root)
window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized)
window.show()
window.raise_()
window.activateWindow()
window.statusBar().showMessage('此数据目录已在使用,已切换到现有窗口。', 6000)
activation_server = listen_for_activation(endpoint, activate)
if arguments.smoke_test:
QTimer.singleShot(0, lambda: (window.close(), qt_application.quit()))
exit_code = qt_application.exec()
@@ -187,6 +216,8 @@ def main(argv: Sequence[str] | None = None) -> int:
logging_context.report_exception("startup", error)
return 1
finally:
if activation_server is not None:
activation_server.close()
if store is not None:
# The window invalidates queued UI results on close. Finish the
# remaining read before releasing the shared SQLite connection.
@@ -37,11 +37,13 @@ def write_release_event(root, path, record, phase, *, context=None, reason='batc
'desktop_disappeared': disappeared, 'cad_exit_code': cad.get('cad_exit_code'),
'quit_helper_exit_code': cad.get('quit_helper_exit_code'),
'cad_shutdown': cad, 'shutdown_warning': record.get('shutdown_warning'),
'retries': record.get('retries', {}), 'cleanup': cleanup, 'error': str(error)}
'retries': record.get('retries', {}), 'release_rechecks': record.get('release_rechecks', []),
'cleanup': cleanup, 'error': str(error)}
title = {'started': '开始释放后台资源', 'succeeded': '后台资源释放成功',
'failed': '后台资源释放失败,资源释放待处理',
'isolated': '后台写入进程已退出,残留桌面已隔离(未确认释放)'}[phase]
purpose = {'batch_end': '批次结束', 'rebuild': '安全重建', 'manual_retry': '重新清理',
'automatic_recheck': '自动复核释放',
'restart_recheck': '重启后重新检查'}.get(reason, reason)
cad_text = f"CAD PID={details['cad_pid']}" if details['cad_pid'] else (
'CAD 未启动' if record.get('cad_start_requested') is False else
@@ -15,6 +15,27 @@ from .path_access import canonical_path, internal_path, retry_sharing_violation
# Recovery retains owned native handles after failed cleanup. This registry is
# never an implicit execution context and never contains COM application objects.
LIVE_RESOURCES = {}
RESOURCE_RELEASE_BACKOFF_SECONDS = (0.5, 1, 2)
def _observe_release(observe, record):
"""Check once immediately, then at most three times after backoff."""
record['release_rechecks'] = []
for attempt, delay in enumerate((0, *RESOURCE_RELEASE_BACKOFF_SECONDS)):
if delay:
time.sleep(delay)
try:
confirmed = observe()
except (OSError, TaskCenterError) as error:
confirmed, detail = False, str(error)
else:
detail = ''
if attempt:
record['release_rechecks'].append({'attempt': attempt, 'delay_seconds': delay,
'confirmed': confirmed, 'error': detail})
if confirmed:
return True
return False
class BatchResourceCleanupError(TaskCenterError):
@@ -237,6 +258,31 @@ def _process_gone(identity):
handle.Close()
def _historical_writer_trees_closed(record, path):
cleanup = record.get('cleanup') or {}
if cleanup.get('owned_cleanup_complete') is True:
return True
if not record.get('processes'):
return record.get('cad_pid') is None and record.get('cad_start_requested') is not True
if not record.get('cad_process') or record['processes'] != [record['cad_process']]:
return False # Older Job snapshots only bind the CAD root's process creation time.
# Older blocked records can miss the latest desktop cleanup while already
# retaining a complete per-CAD Job accounting record.
marker = path.parent / f"generation-{record['generation']}" / 'private-desktop.json'
native = json.loads(internal_path(marker).read_text(encoding='utf-8'))
if ((native.get('token'), native.get('guid'), native.get('desktop'), native.get('cad_process'))
!= (record.get('cad_token'), record.get('cad_guid'), record.get('desktop'), record.get('cad_process'))
or not record.get('cad_token') or not record.get('cad_guid') or not record.get('cad_process')):
return False
observations = (native.get('desktop_cleanup') or {}).get('processes', ())
return sum(observation.get('pid') == record['cad_pid']
and observation.get('job_membership_verified') is True
and observation.get('job_active_processes') == 0
and observation.get('job_handle_closed') is True
and observation.get('unconfirmed_descendant_handles') == 0
for observation in observations) == 1
def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False):
from .isolated_desktop import _Win32Api
from .batch_release_log import write_release_event
@@ -269,6 +315,8 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
continue
live = LIVE_RESOURCES.get(str(path))
if live is not None:
if live.record.get('state') != 'blocked':
continue # An active generation has not asked for release.
try:
live.close(reason='manual_retry' if retry_failed else 'resource_recheck')
except Exception:
@@ -305,30 +353,47 @@ def cleanup_pending_resources(root, *, logging_context=None, retry_failed=False)
if not all(_process_gone(item) for item in identities):
log('failed', '记录中的进程仍未确认退出')
continue
if not _historical_writer_trees_closed(record, path):
log('failed', '缺少历史写入进程树退出证明')
continue
desktop = record.get('desktop')
if (record.get('cleanup') or {}).get('desktop_lease'):
# A return belongs to this past lease, even while the same name
# is now serving another batch. Never open or stop its new owner.
proof = isolation_proof(record)
from .desktop_slot import managed_desktop_disappeared
if not managed_desktop_disappeared(record['cleanup']['desktop_lease']):
receipt = record['cleanup']['desktop_lease']
absent = _observe_release(lambda: managed_desktop_disappeared(receipt), record)
if not absent:
record.pop('record_path', None)
record.update(state='isolated', blocking=False, isolation_proof=proof)
write_record(path, record)
log('isolated')
continue
elif desktop:
try:
_Win32Api().confirm_desktop_released(desktop)
except Exception as error:
from .desktop_slot import observe_current_desktop_name
api = None
def observe():
nonlocal api
managed = observe_current_desktop_name(desktop) if os.name == 'nt' else None
if managed is not None:
return managed
if api is None:
api = _Win32Api()
api.confirm_desktop_released(desktop)
return True
if not _observe_release(observe, record):
# A residual desktop name is only a warning after owned
# handle closure and independently revalidated writer exit.
proof = isolation_proof(record)
record.pop('record_path', None)
warning = '桌面仍在或同名桌面正在使用,未取得桌面消失证明'
record.update(state='isolated', blocking=False, isolation_proof=proof,
isolation_warning=str(error))
isolation_warning=warning)
write_record(path, record)
log('isolated', str(error))
log('isolated', warning)
continue
# After restart only confirm disappearance. Never attach to COM,
# close a project, or terminate a PID whose handles we no longer own.
@@ -12,7 +12,7 @@ from uuid import UUID, uuid4
from .batch_resources import (BatchResourceCleanupError, LIVE_RESOURCES, cleanup_pending_resources,
guard_pending_resources, pending_resources, process_identity, project_checkpoint_released, write_record,
isolation_proof)
isolation_proof, RESOURCE_RELEASE_BACKOFF_SECONDS)
from .errors import TaskCenterError
from .path_access import canonical_path, internal_path, legacy_path
from .isolated_desktop import PrivateDesktop, ProcessNotStartedError
@@ -222,6 +222,7 @@ class BatchCadRuntime:
blocking=True, isolation_proof=None,
stopping_reason='', wait_reason='', primary_error=None,
cad_process=None, cad_token=None, cad_shutdown=None, cad_start_requested=False, cleanup=None,
release_rechecks=[],
release_state={'mentor': 'not_started', 'desktop': 'pending'})
self.generation = generation
self.desktop = desktop
@@ -950,10 +951,41 @@ class BatchCadRuntime:
if not self._release_lock.acquire(blocking=False):
raise BatchResourceCleanupError('资源释放正在进行,请等待当前释放结果。')
try:
return self._close_once(rebuilding=rebuilding, reason=reason)
try:
return self._close_once(rebuilding=rebuilding, reason=reason)
except BatchResourceCleanupError as initial:
shutdown = self.record.get('cad_shutdown') or {}
if (reason in {'resource_recheck', 'automatic_recheck'}
or not shutdown.get('forced_termination')
or self.record['state'] not in {'blocked', 'released'}):
raise
self.record['shutdown_warning'] = str(initial)
for attempt, delay in enumerate(RESOURCE_RELEASE_BACKOFF_SECONDS, start=1):
time.sleep(delay)
self.record.setdefault('release_rechecks', []).append({'attempt': attempt, 'delay_seconds': delay})
try:
self._close_once(rebuilding=rebuilding, reason='automatic_recheck')
except BatchResourceCleanupError:
continue
self._save()
if self._completed_project_after_shutdown():
return
break
self._save()
raise
finally:
self._release_lock.release()
def _completed_project_after_shutdown(self):
shutdown = self.record.get('cad_shutdown') or {}
proof = self.record.get('release_proof') or {}
return (self.result is not None and getattr(self, '_cad_close_error', None) is None
and self._active_evidence is not None and not self._active_attempts
and shutdown.get('project_close_policy') == 'saved_only'
and proof.get('method') == 'owned_cleanup'
and not internal_path(self._active_evidence / 'uncertain.flag').exists()
and project_checkpoint_released(self._active_evidence))
def _close_once(self, *, rebuilding=False, reason=None):
if self.desktop is None and not self.generation:
return # A cache-only batch never acquired resources.
@@ -967,7 +999,7 @@ class BatchCadRuntime:
for event in cleanup.get('desktop_handle_history', ()))):
raise BatchResourceCleanupError(str(self._close_failure),
completed_result=self.result, cleanup_error=self._close_failure)
if (reason == 'resource_recheck'
if (reason in {'resource_recheck', 'automatic_recheck'}
and self.record.get('release_results', {}).get('desktop_released') is not True
and cleanup.get('desktop_handle_closed') is True
and not getattr(self.desktop, '_processes', getattr(self.desktop, 'processes', ()))
@@ -1124,6 +1156,10 @@ class BatchCadRuntime:
'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid'],
'cleanup': self.record['cleanup'], 'released_at': released_at}
releases = [*self.record.get('generation_releases', ()), release]
shutdown = self.record.get('cad_shutdown') or {}
if shutdown.get('forced_termination') and (release['cleanup'] or {}).get('owned_cleanup_complete') is True:
proof = isolation_proof(self.record)
self.record['release_proof'] = dict(proof, desktop_released=True, method='owned_cleanup')
self._save(state='released', blocking=False, released_at=released_at, processes=[], generation_releases=releases,
wait_reason='')
LIVE_RESOURCES.pop(str(self.path), None)
@@ -219,7 +219,7 @@ def run(request_path):
def phase(value, message):
emit('phase', encode((value, str(message))))
if operation == 'cleanup_batch_resources':
result = service.cleanup_batch_resources()
result = service.cleanup_batch_resources(automatic=arguments.get('automatic') is True)
response.update(status='ok', business_succeeded=True, result=encode(result))
else:
with runtime:
@@ -135,6 +135,14 @@ def managed_desktop_disappeared(receipt):
backend.unlock(mutex)
def observe_current_desktop_name(name):
"""Observe a historical name in this logon without opening a desktop handle."""
slot = DesktopSlot()
if slot.name != name:
return None
return managed_desktop_disappeared({'scope': slot.scope, 'name': slot.name})
class DesktopSlot:
def __init__(self, *, root=None, context=None, backend=None):
self.context = _context() if context is None else context
@@ -27,3 +27,7 @@ class TaskCenterError(ValueError):
def _new_error_id() -> str:
date = datetime.now(timezone.utc).strftime("%Y%m%d")
return f"DXT-{date}-{secrets.token_hex(4).upper()}"
class ProjectPathError(TaskCenterError):
"""An expected filesystem failure while reading or selecting projects."""
@@ -258,7 +258,9 @@ def _stop_and_wait(process):
running = process.poll() is None
except Exception as error:
errors.append(error)
if running:
termination_requested = (isinstance(process, _Win32Process)
and process.cleanup_record.get('forced_root_termination'))
if running and not termination_requested:
try:
if isinstance(process, _Win32Process):
process.terminate(reason='root_process_active')
@@ -17,7 +17,7 @@ import time
import traceback
from typing import Any, Mapping
from .errors import TaskCenterError
from .errors import ProjectPathError, TaskCenterError
from .path_access import internal_path
from .retention import rotate_text_log
@@ -62,15 +62,18 @@ class LoggingContext:
reported = error
else:
reported = TaskCenterError("unhandled_exception", "发生未处理异常")
detail = "".join(
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
)
message = reported.message
if not isinstance(error, ProjectPathError):
detail = "".join(
traceback.format_exception(type(error), error, traceback_object or error.__traceback__)
)
message += "\n" + detail.rstrip()
self.logger.error(
"error_id=%s operation=%s message=%s\n%s",
"error_id=%s operation=%s code=%s message=%s",
reported.error_id,
operation,
reported.message,
detail.rstrip(),
reported.code,
message,
)
_flush_handlers(self.logger)
return reported
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Callable
from contextlib import contextmanager
from threading import Event
import os
@@ -10,20 +11,44 @@ from pathlib import Path
import stat
from uuid import uuid4
from .errors import TaskCenterError
from .errors import ProjectPathError, TaskCenterError
from .path_access import canonical_path, internal_path, strip_extended_prefix
from .models import TaskRecord, TaskStatus
from .scanner import _is_schematic_project, _reject_reparse
from .store import TaskStore
@contextmanager
def _path_errors(path: Path):
try:
yield
except FileNotFoundError as error:
raise ProjectPathError(
"path_missing", f"找不到路径「{path}」。请确认目录或工程是否已移动或删除,然后重新选择并读取。"
) from error
except PermissionError as error:
raise ProjectPathError(
"path_denied", f"无法读取路径「{path}」。请检查当前用户的读取权限,然后重试。"
) from error
except NotADirectoryError as error:
raise _not_directory(path) from error
def _not_directory(path: Path) -> ProjectPathError:
return ProjectPathError(
"path_not_directory", f"路径「{path}」中有一项不是目录。请选择工程目录后重试。"
)
def _validated_root(root: Path, excluded_roots: tuple[Path, ...]) -> tuple[Path, tuple[Path, ...]]:
root = Path(os.path.abspath(strip_extended_prefix(root)))
for ancestor in (*reversed(root.parents), root):
_reject_reparse(internal_path(ancestor).lstat(), ancestor)
root = canonical_path(root, strict=True)
if not internal_path(root).is_dir():
raise TaskCenterError("discovery_root", "project root is not a directory")
with _path_errors(root):
for ancestor in (*reversed(root.parents), root):
details = internal_path(ancestor).lstat()
_reject_reparse(details, ancestor)
if not stat.S_ISDIR(details.st_mode):
raise _not_directory(root)
root = canonical_path(root, strict=True)
excluded = tuple(canonical_path(path) for path in excluded_roots)
if any(root.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("discovery_root", "project root is inside an excluded directory")
@@ -50,12 +75,13 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
while pending:
check_cancelled()
directory = pending.pop()
_reject_reparse(internal_path(directory).lstat(), directory)
children = []
with os.scandir(internal_path(directory)) as entries:
for entry in entries:
check_cancelled()
children.append(entry)
with _path_errors(directory):
_reject_reparse(internal_path(directory).lstat(), directory)
with os.scandir(internal_path(directory)) as entries:
for entry in entries:
check_cancelled()
children.append(entry)
projects: list[Path] = []
folders: list[Path] = []
for entry in sorted(children, key=lambda item: item.name.casefold()):
@@ -63,12 +89,13 @@ def scan_project_directory(root: Path, *, excluded_roots: tuple[Path, ...] = (),
path = Path(strip_extended_prefix(entry.path))
if any(path.is_relative_to(blocked) for blocked in excluded):
continue
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, path)
if stat.S_ISDIR(details.st_mode):
folders.append(path)
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
projects.append(canonical_path(path, strict=True))
with _path_errors(path):
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, path)
if stat.S_ISDIR(details.st_mode):
folders.append(path)
elif stat.S_ISREG(details.st_mode) and path.suffix.casefold() == ".prj" and _is_schematic_project(path):
projects.append(canonical_path(path, strict=True))
found.extend(projects)
visited += 1
if on_progress is not None:
@@ -84,35 +111,41 @@ def _validate_selected(root: Path, selected_paths: tuple[Path, ...], excluded: t
ancestor_projects: dict[Path, bool] = {}
for candidate in selected_paths:
path = Path(os.path.abspath(strip_extended_prefix(candidate)))
if not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
if path == root or not path.is_relative_to(root) or any(path.is_relative_to(blocked) for blocked in excluded):
raise TaskCenterError("project_selection", "selected project is outside discovery results")
relative = path.relative_to(root)
cursor = root
for part in relative.parts:
cursor /= part
_reject_reparse(internal_path(cursor).lstat(), cursor)
if not internal_path(path).is_file() or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
raise TaskCenterError("project_selection", "selected file is not a schematic project")
with _path_errors(path):
for part in relative.parts:
cursor /= part
details = internal_path(cursor).lstat()
_reject_reparse(details, cursor)
if cursor != path and not stat.S_ISDIR(details.st_mode):
raise _not_directory(path)
if not stat.S_ISREG(details.st_mode) or path.suffix.casefold() != ".prj" or not _is_schematic_project(path):
raise TaskCenterError("project_selection", "selected file is not a schematic project")
# A project in any ancestor directory stops discovery below that directory.
directory = path.parent
while directory != root:
directory = directory.parent
if directory not in ancestor_projects:
has_project = False
with os.scandir(internal_path(directory)) as entries:
with _path_errors(directory), os.scandir(internal_path(directory)) as entries:
for entry in entries:
sibling = Path(strip_extended_prefix(entry.path))
if sibling.suffix.casefold() != ".prj" or any(sibling.is_relative_to(b) for b in excluded):
continue
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, sibling)
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
has_project = True
break
with _path_errors(sibling):
details = entry.stat(follow_symlinks=False)
_reject_reparse(details, sibling)
if stat.S_ISREG(details.st_mode) and _is_schematic_project(sibling):
has_project = True
break
ancestor_projects[directory] = has_project
if ancestor_projects[directory]:
raise TaskCenterError("project_selection", "selected project is hidden by an ancestor project")
selected.add(canonical_path(path, strict=True))
with _path_errors(path):
selected.add(canonical_path(path, strict=True))
return tuple(sorted(selected, key=lambda path: str(path).casefold()))
@@ -1078,10 +1078,10 @@ class TaskCenterService:
return self._operation('force_pending_owned_resources', None,
lambda: force_pending_owned_resources(self._logging.root, confirmed=confirmed))
def cleanup_batch_resources(self):
def cleanup_batch_resources(self, *, automatic=False):
"""Retry owned-resource release without opening or changing any project."""
if self._supervised:
result = self._supervise('cleanup_batch_resources', {})
self._supervise('cleanup_batch_resources', {'automatic': True} if automatic else {})
from .batch_supervisor import reconcile_supervisors
reconcile_supervisors(self._logging.root)
return self.pending_batch_resources()
@@ -1090,7 +1090,7 @@ class TaskCenterService:
assert_task_queue_idle(self._logging.root)
with _quick_run_lease(self._logging.root):
return self._operation('cleanup_batch_resources', None,
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging, retry_failed=True))
lambda: cleanup_pending_resources(self._logging.root, logging_context=self._logging, retry_failed=not automatic))
def inspect_bom_batch(self, task_id: str, path: Path, *, stop_event=None, on_progress=None, on_phase=None, runtime=None):
if runtime is None and self._supervised:
@@ -0,0 +1,86 @@
"""Hold a data-root lock while the GUI owns its database and layout."""
from contextlib import contextmanager
import errno
import os
import time
from PySide6.QtNetwork import QLocalServer, QLocalSocket
from .path_access import internal_path
from .task_queue import _os_lock
class InstanceUnavailable(RuntimeError):
pass
@contextmanager
def gui_instance(data_root):
root = internal_path(data_root)
root.mkdir(parents=True, exist_ok=True)
# OS locks release on process death. Keep the file so every contender locks the same inode.
with (root / '.gui-instance.lock').open('a+b') as handle:
identity = os.fstat(handle.fileno())
endpoint = f'DxPartReplace-{identity.st_dev:x}-{identity.st_ino:x}'
deadline = time.monotonic() + 30
while True:
try:
_os_lock(handle, True)
break
except OSError as error:
if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK):
raise
if _activate(endpoint):
yield None
return
if time.monotonic() >= deadline:
raise InstanceUnavailable('此数据目录已在使用,现有窗口暂未响应。')
time.sleep(.05)
yield endpoint
def _activate(endpoint):
socket = QLocalSocket()
socket.connectToServer(endpoint)
if not socket.waitForConnected(100):
return False
if os.name == 'nt':
import ctypes
from ctypes import wintypes
pid = wintypes.DWORD()
get_pipe_pid = ctypes.windll.kernel32.GetNamedPipeServerProcessId
get_pipe_pid.argtypes = (wintypes.HANDLE, ctypes.POINTER(wintypes.DWORD))
if get_pipe_pid(int(socket.socketDescriptor()), ctypes.byref(pid)):
ctypes.windll.user32.AllowSetForegroundWindow(pid.value)
socket.write(b'activate\n')
socket.flush()
return (socket.bytesAvailable() > 0 or socket.waitForReadyRead(1000)) and socket.readAll() == b'1'
def listen_for_activation(endpoint, activate):
server = QLocalServer()
server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption)
if os.name != 'nt':
QLocalServer.removeServer(endpoint) # The lock owner can remove a crashed owner's socket.
if not server.listen(endpoint):
raise RuntimeError(server.errorString())
def accept():
while server.hasPendingConnections():
socket = server.nextPendingConnection()
def respond(socket=socket):
if socket.canReadLine() and socket.readLine() == b'activate\n':
activate()
socket.write(b'1')
socket.flush()
socket.disconnectFromServer()
socket.disconnected.connect(socket.deleteLater)
socket.readyRead.connect(respond)
respond()
server.newConnection.connect(accept)
return server
@@ -1032,11 +1032,13 @@ class TrialTaskCenterWindow(MaterialMainWindow):
self._close_pending = False
self._set_operator_message(self.run_panel.operator_band.text() + '\n' + details, 'warning')
def _cleanup_batch_resources(self):
if not self.run_panel.cleanup_resources_button.isEnabled():
def _cleanup_batch_resources(self, *, automatic=False):
if not automatic and not self.run_panel.cleanup_resources_button.isEnabled():
return
state = getattr(self.service, '_supervisor_dialog_state', None) or {}
if (state.get('supervision') or {}).get('blocked'):
if automatic:
return
from .cad_dialog_operations import show_cad_dialogs
show_cad_dialogs(self)
self._update_gates()
@@ -1077,7 +1079,7 @@ class TrialTaskCenterWindow(MaterialMainWindow):
else:
self._dsh_blockers.clear('resource-release')
self._update_gates()
if pending and not any(row.get('force_available', True) for row in pending):
if automatic or pending and not any(row.get('force_available', True) for row in pending):
return
if pending and QMessageBox.question(self, '强制结束自有残留进程',
'安全释放尚未完成。是否强制结束本程序仍持有且能证明归属的残留进程?\n\n'
@@ -1087,7 +1089,8 @@ class TrialTaskCenterWindow(MaterialMainWindow):
force_confirmed = True
# A modal question can deliver finished before returning Yes.
start_force_if_ready()
self._run_async(self.service.cleanup_batch_resources, done,
cleanup = (lambda: self.service.cleanup_batch_resources(automatic=True)) if automatic else self.service.cleanup_batch_resources
self._run_async(cleanup, done,
self.run_panel.cleanup_resources_button, operation_area='resources', on_finished=after_cleanup)
def _startup_resource_recheck(self):
@@ -1096,9 +1099,9 @@ class TrialTaskCenterWindow(MaterialMainWindow):
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._resource_status.blocked:
if self._resource_status.records:
self._update_gates()
self._cleanup_batch_resources() # Resource-only; never resumes a queue.
self._cleanup_batch_resources(automatic=True)
def _export_diagnostics(self):
from pathlib import Path
@@ -3,6 +3,8 @@ from datetime import datetime
import json
import re
from ..errors import ProjectPathError
ERROR_TEXT = {
"dsh_startup": "DSH助手启动失败,请检查发布包中的运行时和 Node.js。",
'user_forced_stop': '操作已强制中断,结果待核验。',
@@ -57,6 +59,8 @@ ERROR_TEXT = {
def format_operation_error(error):
if isinstance(error, ProjectPathError):
return f'{error.message}\n错误代码:{error.code} · 错误编号:{error.error_id}'
title = ERROR_TEXT.get(error.code, '操作未完成')
report = getattr(error, 'bom_report', None)
if report is not None:
@@ -19,6 +19,8 @@ from .workers import ServiceWorker
from .operation_state import OperationPhase
from .command_menu import CommandMenu
from .icons import icon
from .messages import format_operation_error
from ..errors import ProjectPathError
from ..bom_import_state import BomImportMachine, BomImportPhase, BomImportState
from ..bom_pending import retained_bom_rows
@@ -44,6 +46,9 @@ class DirectoryTaskDialog(QDialog):
self.scan = QPushButton('读取工程', objectName='readTaskProjects')
self.projects = QListWidget(objectName='taskProjectCandidates')
self.summary = QLabel('先读取工程,再勾选需要创建任务的项目。')
self.summary.setWordWrap(True)
self.summary.setTextFormat(Qt.TextFormat.PlainText)
self.summary.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
self.buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setText('创建任务')
self.buttons.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
@@ -137,7 +142,10 @@ class DirectoryTaskDialog(QDialog):
if self._closed:
return
self._scanned_root = None
self.summary.setText(getattr(error, 'message', str(error)))
if isinstance(error, ProjectPathError):
self.summary.setText(format_operation_error(error))
else:
self.summary.setText(getattr(error, 'message', str(error)))
def _finished(self):
self._worker = None
+39
View File
@@ -4,6 +4,8 @@ import os
from pathlib import Path
import subprocess
import sys
from threading import Timer
from types import SimpleNamespace
import pytest
@@ -14,6 +16,43 @@ from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, build_
from dx_productivity.trial_task_center.logging_setup import configure_logging
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop object lifetime')
def test_a_late_owned_job_exit_releases_the_live_lease_without_second_quit(tmp_path):
runtime = BatchCadRuntime(tmp_path, 'execution')
desktop = runtime._ensure_desktop()
exit_file = tmp_path / 'exit'
process = desktop.start_process((sys.executable, '-u', '-c',
'import pathlib,sys,time; marker=pathlib.Path(sys.argv[1]); print("ready",flush=True); '
'exec("while not marker.exists(): time.sleep(.02)")', str(exit_file)),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
runtime._track(process)
quit_attempts = []
signal = Timer(.8, exit_file.touch)
def interrupted_quit(*args):
quit_attempts.append(process.pid)
signal.start()
raise OSError('injected delayed root exit')
try:
assert process.stdout.readline() == b'ready\r\n'
runtime.cad = SimpleNamespace(cad=process, record={'forced_termination': True}, __exit__=interrupted_quit)
with pytest.raises(BatchResourceCleanupError, match='injected delayed root exit'):
runtime.close()
assert len(quit_attempts) == 1
assert runtime.record['state'] == 'released'
assert runtime.record['release_proof']['method'] == 'owned_cleanup'
assert runtime.record['release_proof']['processes_exited'] is True
assert desktop.cleanup_record['desktop_lease']['returned'] is True
assert runtime.record['cad_shutdown']['forced_termination'] is True
assert len(runtime.record['release_rechecks']) in {2, 3}
guard_pending_resources(tmp_path)
finally:
exit_file.touch()
signal.cancel()
desktop.close()
@pytest.mark.skipif(os.name != 'nt', reason='Windows desktop object lifetime')
def test_external_reference_preserves_completed_result_until_resource_only_cleanup(tmp_path):
before = current_desktop_name()
+134
View File
@@ -0,0 +1,134 @@
from contextlib import closing
import os
from pathlib import Path
import pytest
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QDialogButtonBox
from dx_productivity.trial_task_center import project_tasks
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.ui.messages import format_operation_error
from dx_productivity.trial_task_center.ui.project_plan import DirectoryTaskDialog
@pytest.fixture
def service(tmp_path):
log = configure_logging(tmp_path / 'data')
with closing(TaskStore(tmp_path / 'tasks.db')) as store:
yield TaskCenterService(store, log), store, log.application_log_path
def deny_directory_listing(folder, request):
if os.name != 'nt':
pytest.skip('requires a Windows filesystem ACL')
import ntsecuritycon
import win32api
import win32con
import win32security
flag = win32security.DACL_SECURITY_INFORMATION
path = str(folder)
original = win32security.GetFileSecurity(path, flag)
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
try:
sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
finally:
token.Close()
dacl = win32security.ACL()
dacl.AddAccessDeniedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_LIST_DIRECTORY, sid)
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, ntsecuritycon.FILE_ALL_ACCESS, sid)
descriptor = win32security.SECURITY_DESCRIPTOR()
descriptor.SetSecurityDescriptorDacl(True, dacl, False)
request.addfinalizer(lambda: win32security.SetFileSecurity(path, flag, original))
win32security.SetFileSecurity(path, flag, descriptor)
with pytest.raises(PermissionError) as failure, os.scandir(folder):
pytest.fail('directory ACL did not deny enumeration')
assert failure.value.winerror == 5
print('Windows ACL produced WinError 5')
def assert_operator_error(text, path, code, advice):
print(text)
assert str(path) in text
assert code in text and 'DXT-' in text
assert advice in text
assert 'Traceback' not in text
assert '发生未处理异常' not in text
@pytest.mark.parametrize(('case', 'code', 'advice'), [
('missing', 'path_missing', '移动或删除'),
('file', 'path_not_directory', '请选择工程目录'),
('file_parent', 'path_not_directory', '请选择工程目录'),
('denied', 'path_denied', '读取权限'),
])
def test_directory_dialog_shows_actionable_path_error(qtbot, tmp_path, request, service, case, code, advice):
api, store, log = service
folder = tmp_path / case
requested = folder
if case in {'file', 'file_parent'}:
folder.touch()
if case == 'file_parent':
requested = folder / 'subfolder'
if case == 'denied':
folder.mkdir()
deny_directory_listing(folder, request)
dialog = DirectoryTaskDialog(api)
qtbot.addWidget(dialog)
dialog.directory.setText(str(requested))
dialog.show()
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
qtbot.waitUntil(lambda: dialog._worker is None, timeout=5000)
assert dialog.directory.isEnabled()
assert not dialog.buttons.button(QDialogButtonBox.StandardButton.Ok).isEnabled()
assert_operator_error(dialog.summary.text(), requested, code, advice)
assert store.list_tasks() == ()
contents = log.read_text(encoding='utf-8')
assert f'operation=scan_project_directory code={code}' in contents
assert 'Traceback' not in contents
def test_moved_project_fails_after_scan_without_creating_partial_tasks(qtbot, tmp_path, service):
api, store, log = service
root = tmp_path / 'projects'
root.mkdir()
for name in ('one.prj', 'two.prj'):
(root / name).write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
dialog = DirectoryTaskDialog(api)
qtbot.addWidget(dialog)
dialog.directory.setText(str(root))
dialog.show()
qtbot.mouseClick(dialog.scan, Qt.MouseButton.LeftButton)
create = dialog.buttons.button(QDialogButtonBox.StandardButton.Ok)
qtbot.waitUntil(create.isEnabled, timeout=5000)
moved = root / 'two.prj'
moved.rename(root / 'relocated.prj')
qtbot.mouseClick(create, Qt.MouseButton.LeftButton)
with pytest.raises(TaskCenterError) as failure:
api.create_project_tasks(dialog.values()[0], selected_paths=dialog.values()[1])
assert_operator_error(format_operation_error(failure.value), moved, 'path_missing', '移动或删除')
assert store.list_tasks() == ()
contents = log.read_text(encoding='utf-8')
assert 'operation=create_project_tasks code=path_missing' in contents
assert 'Traceback' not in contents
def test_unexpected_scan_fault_remains_traceable_in_application_log(tmp_path, monkeypatch, service):
api, _, log = service
def fail(*args, **kwargs):
raise RuntimeError('injected non-filesystem failure')
monkeypatch.setattr(project_tasks, '_validated_root', fail)
with pytest.raises(TaskCenterError) as failure:
api.scan_project_directory(tmp_path)
assert failure.value.code == 'unhandled_exception'
contents = log.read_text(encoding='utf-8')
assert 'operation=scan_project_directory code=unhandled_exception' in contents
assert 'Traceback' in contents and failure.value.error_id in contents
+96
View File
@@ -10,6 +10,102 @@ from dx_productivity.trial_task_center.batch_resources import LIVE_RESOURCES, cl
from dx_productivity.trial_task_center.errors import TaskCenterError
@pytest.mark.parametrize('exits_after_retry', [True, False])
def test_batch_close_rechecks_owned_exit_three_times_without_repeating_quit(tmp_path, monkeypatch, exits_after_retry):
from dx_productivity.trial_task_center import batch_runtime
calls, delays = [], []
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
process = SimpleNamespace(returncode=None, poll=lambda: process.returncode)
def close_mentor(*args):
calls.append('quit')
raise OSError('root exit still pending after forced job stop')
def advance(seconds):
delays.append(seconds)
if exits_after_retry and len(delays) == 2:
process.returncode = 1
monkeypatch.setattr(batch_runtime.time, 'sleep', advance)
runtime.cad = SimpleNamespace(cad=process, record={'forced_termination': True}, __exit__=close_mentor)
runtime.result = 'saved and independently verified'
try:
with pytest.raises(TaskCenterError, match='root exit still pending'):
runtime.close()
if exits_after_retry:
assert runtime.record['state'] == 'released'
assert runtime.record['cad_shutdown']['forced_termination'] is True
assert delays == [0.5, 1]
else:
assert runtime.record['state'] == 'blocked'
assert not runtime.desktop.released
assert delays == [0.5, 1, 2]
assert calls == ['quit']
assert runtime.result == 'saved and independently verified'
finally:
LIVE_RESOURCES.pop(str(runtime.path), None)
def test_restart_rechecks_physical_disappearance_without_replaying_owned_actions(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources, isolated_desktop
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
LIVE_RESOURCES.pop(str(runtime.path), None)
runtime._save(state='blocked')
observed, delays = [], []
work = tmp_path / 'uncertain.flag'
work.write_bytes(b'original business protection')
def confirm(name):
observed.append(name)
if len(observed) < 3:
raise OSError('desktop still exists')
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=confirm))
monkeypatch.setattr(batch_resources.time, 'sleep', delays.append)
assert cleanup_pending_resources(tmp_path) == ()
assert observed == [runtime.desktop.name] * 3
assert delays == [0.5, 1]
assert work.read_bytes() == b'original business protection'
def test_resource_only_observation_never_closes_a_ready_live_owner(tmp_path):
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
try:
assert cleanup_pending_resources(tmp_path)[0]['state'] == 'ready'
assert not runtime.desktop.released
finally:
runtime.close()
def test_missing_historical_job_exit_blocks_even_when_the_desktop_is_gone(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources, isolated_desktop
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
LIVE_RESOURCES.pop(str(runtime.path), None)
identity = {'pid': 1400, 'creation_time': 'exact'}
runtime._save(state='blocked', cad_pid=1400, cad_process=identity, processes=[identity])
monkeypatch.setattr(batch_resources, '_process_gone', lambda _: True)
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: pytest.fail('insufficient Job proof'))
assert cleanup_pending_resources(tmp_path)[0]['state'] == 'blocked'
def test_supervised_cleanup_carries_automatic_mode_to_worker(tmp_path):
from dx_productivity.trial_task_center.service import TaskCenterService
service = TaskCenterService.__new__(TaskCenterService)
service._supervised = True
service._logging = SimpleNamespace(root=tmp_path)
calls = []
service._supervise = lambda operation, arguments: calls.append((operation, arguments))
service.pending_batch_resources = lambda: ()
assert service.cleanup_batch_resources(automatic=True) == ()
assert calls == [('cleanup_batch_resources', {'automatic': True})]
def test_closed_desktop_rechecks_only_observe_until_external_reference_disappears(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
from dx_productivity.trial_task_center import isolated_desktop, batch_resources
@@ -7,6 +7,23 @@ import pytest
from test_ui_remediation import window
def test_startup_rechecks_isolation_without_using_the_manual_button(window, qtbot, monkeypatch):
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
pending = ({'state': 'isolated', 'blocking': False},)
monkeypatch.setattr(window.service, 'pending_batch_resources', lambda: pending)
modes = []
monkeypatch.setattr(window.service, 'cleanup_batch_resources',
lambda *, automatic=False: (modes.append(automatic) or ()))
monkeypatch.setattr(QMessageBox, 'question', lambda *args, **kwargs: pytest.fail('automatic force prompt'))
window._resource_status.records = pending
window._resource_status.known = True
window._update_gates()
assert not window.run_panel.cleanup_resources_button.isEnabled()
window._startup_resource_recheck()
qtbot.waitUntil(lambda: len(modes) == 1 and not window._workers)
assert modes == [True]
@pytest.mark.parametrize('finish_order', ['normal', 'after_confirmation', 'during_confirmation'])
@pytest.mark.parametrize('confirmed', [False, True])
def test_confirmed_force_runs_after_cleanup_worker_finishes(window, qtbot, monkeypatch, finish_order, confirmed):
+84
View File
@@ -0,0 +1,84 @@
from __future__ import annotations
import os
from pathlib import Path
import subprocess
import sys
import time
from dx_productivity.trial_task_center.store import TaskStore
_SOURCE = Path(__file__).resolve().parents[2] / 'src'
_APP = 'dx_productivity.trial_task_center.application'
def _wait_for(predicate, description):
deadline = time.monotonic() + 90
while time.monotonic() < deadline:
if predicate():
return
time.sleep(.05)
raise AssertionError(description)
def test_concurrent_gui_launches_activate_one_owner_and_recover_after_kill(tmp_path):
root = tmp_path / 'Shared Root'
independent = tmp_path / 'Independent Root'
root.mkdir()
store = TaskStore(root / 'task-center.db')
try:
task = store.create_task('Existing task')
finally:
store.close()
processes = []
env = os.environ | {'PYTHONPATH': str(_SOURCE), 'QT_QPA_PLATFORM': 'offscreen'}
def launch(path, *arguments):
process = subprocess.Popen(
[sys.executable, '-m', _APP, '--data-root', str(path), *arguments],
env=env,
)
processes.append(process)
return process
def log(path):
logfile = path / 'logs/application.log'
return logfile.read_text(encoding='utf-8') if logfile.exists() else ''
try:
alias = root.with_name(root.name.upper()) if os.name == 'nt' else root
contenders = [launch(root), launch(alias), launch(root), launch(alias)]
_wait_for(lambda: sum(p.poll() is not None for p in contenders) >= 3,
'Three concurrent launches should exit after handing off to one GUI')
owners = [p for p in contenders if p.poll() is None]
assert len(owners) == 1
assert [p.returncode for p in contenders if p not in owners] == [0, 0, 0]
_wait_for(lambda: log(root).count('instance_conflict') == 3,
'The GUI should handle and log all three activation requests')
assert log(root).count('application_start ') == 1
other = launch(independent)
_wait_for(lambda: 'application_start ' in log(independent), 'Different root should start independently')
assert other.poll() is None and owners[0].poll() is None
helper = launch(root, '--native-helper')
assert helper.wait(timeout=60) == 2 # The helper validates its own required snapshot.
assert log(root).count('instance_conflict') == 3
owners[0].kill()
owners[0].wait(timeout=10)
assert launch(root, '--smoke-test').wait(timeout=60) == 0
assert log(root).count('application_start ') == 2
assert log(root).count('application_clean_shutdown') == 1
assert other.poll() is None
store = TaskStore(root / 'task-center.db')
try:
assert [record.task_id for record in store.list_tasks()] == [task.task_id]
finally:
store.close()
finally:
for process in processes:
if process.poll() is None:
process.kill()
process.wait(timeout=10)