diff --git a/docs/superpowers/plans/2026-10-30-lifecycle-optimization.md b/docs/superpowers/plans/2026-10-30-lifecycle-optimization.md new file mode 100644 index 0000000..d9e5931 --- /dev/null +++ b/docs/superpowers/plans/2026-10-30-lifecycle-optimization.md @@ -0,0 +1,85 @@ +# Lifecycle Optimization Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Make CAD save, close, exit, and resource-release outcomes explicit and recoverable across normal, failed, cancelled, and forced-stop paths. + +**Architecture:** Keep business completion and infrastructure cleanup as separate outcomes. Extend the existing resource journal and runtime result objects with phase evidence, give owned helper processes a bounded natural-exit window, and preserve cleanup failures instead of converting them into a successful-looking result. + +**Tech Stack:** Python 3.12, PySide6, pywin32, pytest, existing `BatchCadRuntime`, `IsolatedCadSession`, supervisor protocol, and VBS worker evidence files. + +**Spec:** Approved in chat on 2026-10-30 as Phase 1 of the project optimization. + +## Global Constraints + +- Preserve the existing no-replay protection for uncertain project mutations. +- Never terminate an unowned process or clear evidence that cannot be verified. +- Keep normal successful replacement behavior and public service method signatures compatible. +- Every production change must have a regression test that fails before the change. + +--- + +### Task 1: Model and persist separate save/close evidence + +**Files:** +- Modify: `src/dx_productivity/trial_task_center/batch_runtime.py` +- Modify: `src/dx_productivity/trial_task_center/isolated_cad.py` +- Modify: `src/dx_productivity/trial_task_center/batch_resources.py` +- Test: `tests/v1_1/test_batch_runtime.py` +- Test: `tests/v1_1/test_isolated_cad.py` + +**Interfaces:** +- Consumes existing CAD shutdown records and project checkpoints. +- Produces journal fields for save requested, save returned, readback verified, project closed, and cleanup outcome. + +- [ ] **Step 1: Write failing tests** for a close failure after a save request and for a cleanup record that reports business completion with infrastructure failure. +- [ ] **Step 2: Run the focused tests** and verify they fail because the current record has no separate save evidence and the completed result hides cleanup failure. +- [ ] **Step 3: Add the smallest evidence fields** with backward-compatible defaults and preserve the existing uncertain/recovery guard. +- [ ] **Step 4: Run the focused tests** and verify both pass. +- [ ] **Step 5: Run the related supervisor and recovery tests** before moving to the next task. + +### Task 2: Allow owned helper processes a bounded natural exit window + +**Files:** +- Modify: `src/dx_productivity/trial_task_center/isolated_desktop.py` +- Test: `tests/v1_1/test_isolated_desktop.py` +- Test: `tests/v1_1/test_batch_runtime_windows.py` + +**Interfaces:** +- Consumes owned process identities and existing Win32 job cleanup records. +- Produces cleanup records that distinguish naturally exited descendants from forced termination. + +- [ ] **Step 1: Write a failing test** where the root CAD process has exited and an owned helper exits shortly afterward; assert no forced termination is requested. +- [ ] **Step 2: Run the test** and verify the current implementation calls the force cleanup immediately. +- [ ] **Step 3: Add a bounded wait** only for identities whose owned root has already exited; retain force cleanup after the deadline. +- [ ] **Step 4: Run the focused Windows tests** and verify the cleanup record includes the wait and final state. +- [ ] **Step 5: Run the resource release test group**. + +### Task 3: Separate diagnostic journal failures from the CAD Quit protocol + +**Files:** +- Modify: `src/dx_productivity/trial_task_center/isolated_cad.py` +- Modify: `src/dx_productivity/trial_task_center/batch_release_log.py` +- Test: `tests/v1_1/test_isolated_cad.py` +- Test: `tests/v1_1/test_batch_runtime.py` + +**Interfaces:** +- Consumes the existing owned CAD identity and project-close state. +- Produces an explicit diagnostic-write warning while still attempting a valid Quit sequence. + +- [ ] **Step 1: Write a failing test** that injects a closing-record write failure and asserts Quit is still attempted when project state is safe. +- [ ] **Step 2: Run the test** and verify Quit is currently skipped. +- [ ] **Step 3: Isolate diagnostic persistence errors** from the normal Quit decision and record both outcomes. +- [ ] **Step 4: Run the focused tests** and verify both normal and failed-record paths. +- [ ] **Step 5: Run all lifecycle and supervisor tests**. + +### Task 4: Verify the phase and document field validation + +**Files:** +- Modify: `docs/testing/2026-10-26-application-lifecycle-investigation.md` +- Create: `docs/testing/2026-10-30-phase1-lifecycle-optimization.md` + +- [ ] **Step 1: Run the complete test suite** and capture the count and warnings. +- [ ] **Step 2: Run `python -m compileall -q src` and `git diff --check`.** +- [ ] **Step 3: Record the exact scenarios covered and the remaining real DxDesigner field checks.** +- [ ] **Step 4: Review the final diff for accidental changes outside Phase 1.** diff --git a/docs/testing/2026-10-30-phase1-lifecycle-optimization.md b/docs/testing/2026-10-30-phase1-lifecycle-optimization.md new file mode 100644 index 0000000..0507870 --- /dev/null +++ b/docs/testing/2026-10-30-phase1-lifecycle-optimization.md @@ -0,0 +1,26 @@ +# Phase 1:生命周期优化验证 + +日期:2026-10-30(北京时间) +分支:`codex/project-optimization` + +## 本轮修复 + +批次执行发生一次可重试的预写失败时,运行时会先释放旧代资源,再重建 CAD 会话。此前如果旧代 CAD 的 `__exit__` 抛出异常,`BatchCadRuntime._close_resources(rebuilding=True)` 只写入 `shutdown_warning`,没有把异常加入资源错误集合,随后可能继续创建下一代桌面和 CAD。 + +现在该异常同时保留在诊断字段和资源错误集合中,批次状态保持 `blocked`,不会继续重建。外层上下文再次退出时也不会立即重复 close 并把 blocked 改写为 released。已有 `manual_retry` 清理入口仍可在资源状态修复后重新尝试释放。 + +上一轮的安全停止证据重试修复仍在本分支中:保护记录 fsync 失败后采用短轮询,强制结束前必须成功写入保护证据。 + +## 回归证据 + +- 新增 `test_rebuild_does_not_hide_cad_shutdown_failure`,先验证旧行为会吞掉 CAD 收尾异常,再验证修复后保持 blocked。 +- `tests/v1_1/test_batch_runtime.py`、`test_batch_runtime_windows.py`、`test_batch_supervisor.py`、`test_supervisor_result.py`:53 passed。 +- `test_isolated_cad.py`、`test_isolated_desktop.py`、`test_safe_user_stop.py`、`test_failed_native_recovery_guard.py`:93 passed。 +- `python -m compileall -q src`:通过。 +- `git diff --check`:通过。 + +## 当前边界 + +当前代码已经包含辅助进程自然退出宽限,以及诊断记录失败时仍尝试身份校验后的 CAD Quit。本轮没有重复修改这些路径,也没有声称真实 DxDesigner 现场桌面持有者问题已经闭环。 + +仍需在工程副本和实际 CAD 环境验证:CAD 收尾异常后的人工清理、跨重启资源复核、保存中断后的恢复入口,以及冻结包中的同一行为。 diff --git a/src/dx_productivity/trial_task_center/batch_runtime.py b/src/dx_productivity/trial_task_center/batch_runtime.py index 953cfc2..5080c3f 100644 --- a/src/dx_productivity/trial_task_center/batch_runtime.py +++ b/src/dx_productivity/trial_task_center/batch_runtime.py @@ -101,6 +101,8 @@ class BatchCadRuntime: self._project_attempts = {} self._logging = None self._active_evidence = None + self._close_failure = None + self._close_failure_rebuild = False def bind_logs(self, context, task_ids): """Keep every participating task's final release outcome visible.""" @@ -381,13 +383,22 @@ class BatchCadRuntime: if self.record['state'] == 'released': return reason = reason or ('rebuild' if rebuilding else 'batch_end') + if self._close_failure is not None and self._close_failure_rebuild and reason != 'manual_retry': + raise BatchResourceCleanupError(str(self._close_failure), completed_result=self.result, + cleanup_error=self._close_failure) + if reason == 'manual_retry': + self._close_failure = None started = time.monotonic() self._release_log('started', reason=reason) try: self._close_resources(rebuilding=rebuilding) except Exception as error: + self._close_failure = error + self._close_failure_rebuild = rebuilding self._release_log('failed', reason=reason, elapsed=time.monotonic() - started, error=error) raise + self._close_failure = None + self._close_failure_rebuild = False self._release_log('succeeded', reason=reason, elapsed=time.monotonic() - started) def _close_resources(self, *, rebuilding=False): @@ -404,8 +415,10 @@ class BatchCadRuntime: except Exception as error: if rebuilding: self.record['shutdown_warning'] = str(error) - else: - errors.append(str(error)) + # A rebuild must not proceed while the previous CAD owner has + # an unconfirmed shutdown. Keep the warning for diagnostics, + # but retain the failure in the resource gate as well. + errors.append(str(error)) finally: cad_record = getattr(cad, 'record', {}) cad_record = cad_record if isinstance(cad_record, dict) else {} diff --git a/src/dx_productivity/trial_task_center/stop_control.py b/src/dx_productivity/trial_task_center/stop_control.py index 7f016b9..ff99a46 100644 --- a/src/dx_productivity/trial_task_center/stop_control.py +++ b/src/dx_productivity/trial_task_center/stop_control.py @@ -68,7 +68,11 @@ 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: - if control.force_event.wait(.1): + # 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): try: protect() except OSError as failure: diff --git a/tests/v1_1/test_batch_runtime.py b/tests/v1_1/test_batch_runtime.py index 20d1361..b0dca62 100644 --- a/tests/v1_1/test_batch_runtime.py +++ b/tests/v1_1/test_batch_runtime.py @@ -193,6 +193,29 @@ def test_prewrite_failure_releases_old_desktop_and_retries_only_once(tmp_path, m and release['released_at'] > 0 for release in releases) +def test_rebuild_does_not_hide_cad_shutdown_failure(tmp_path): + from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime + from dx_productivity.trial_task_center.errors import TaskCenterError + + class FailingCad(Cad): + def __exit__(self, *_exc): + self.closed = True + self.desktop.close() + raise OSError('CAD quit confirmation failed') + + runtime = BatchCadRuntime(tmp_path / 'data', 'execution', + desktop_factory=Desktop, cad_factory=FailingCad) + runtime.__enter__() + runtime._ensure_desktop() + runtime._ensure_cad() + with pytest.raises(TaskCenterError, match='CAD quit confirmation failed'): + runtime.close(rebuilding=True) + with pytest.raises(TaskCenterError, match='CAD quit confirmation failed'): + runtime.__exit__(None, None, None) + record = json.loads(runtime.path.read_text()) + assert record['state'] == 'blocked' + + def test_possible_mutation_prevents_automatic_replay(tmp_path, monkeypatch): from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError command, _ = command_for(tmp_path)