fix: preserve handoff cleanup and ICDB cancellation bindings

This commit is contained in:
阿白叔 committed 2026-11-18 09:05:22 +08:00
1 parent b4737b5102
commit fa1f662e1d
6 files changed
+169 -10

No files matched your search

@@ -0,0 +1,38 @@
# PR 16 small review follow-up
Refs #15. Follow-up to review comment 446 on `b4737b5`; this does not authorize
merging, release publication or issue closure.
- Verify now propagates a registered `TaskHandoff` instead of recording it as a
close error and continuing a second native cleanup. It preserves the cancelled
or failed result as evidence before returning cleanup ownership to the observer.
- Repair runs local worker cleanup even when observer registration or handoff
raises. A live native worker retains its existing observer-owned handles;
`DesktopWorker.close()` does not terminate it or claim resources are released.
- Starting an ICDB check binds the fallback Stop signal to the task's actual
context. The normal global Stop and per-task cancellation policies are unchanged.
- Native Versions/Repair errors now explain that the main PRJ must contain exactly
one nonempty `iCDBDir` using a project-local relative path. Absolute paths,
including absolute paths inside Work, and multiple entries remain unsupported.
No PRJ is rewritten and no native tool is launched for rejected input.
The previously approved three-second defaults remain: submitted execution
continues; unknown ownership/read-write confirmation skips; version selection
uses the last manual save; exit saves; force termination defaults to cancellation.
This follow-up does not add or change those product decisions.
## Validation
The unchanged targeted baseline passed 31 tests. New behavior regressions first
recorded four failures and four passes; after the fixes all eight passed.
Related Verify, Repair, native-entry, observer, ICDB/UI and shutdown regressions
passed **363 tests in 157.24 seconds**, exit code 0.
Compilation and whitespace checks also passed. Independent scoped review found
zero Critical, Important or Minor issues in the follow-up fixes.
These are source tests with real task contexts and Qt controls; native process
boundaries are replaced where the tests require them. This follow-up does not
claim a new full-suite run, rebuilt frozen package, or actual Mentor acceptance.
The earlier 2,418-test full run and B14 package still belong to source `c1e2596`.
Original field inconsistency, the retained-phase native replay, Windows 10 and
production SMB acceptance remain outstanding as documented in the main matrix.
+1 -1
View File
@@ -61,7 +61,7 @@ def native_backup_target(request, *, mode='versions', target_database=None):
values = re.findall(r'^KEY iCDBDir "([^"\r\n]+)"\s*$', _project_text(config), re.M)
if len(values) != 1 or not values[0] or PureWindowsPath(values[0]).root or PureWindowsPath(values[0]).drive:
if config == project or target_database is None:
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 未唯一绑定')
raise ValueError('NATIVE_TARGET_UNCONFIRMED: 主 PRJ 的 iCDBDir 必须唯一且为工程内相对路径,不支持绝对路径或多条记录')
continue
database = (config.parent/values[0]).resolve()
if not database.is_relative_to(project.parent.resolve()):
+10 -8
View File
@@ -336,11 +336,13 @@ def _supervise_repair(command, desktop, cancel, root, timeout_seconds, progress,
worker.request_stop()
raise
finally:
if entered:
native.__exit__(None, None, None)
if worker.poll() is None and getattr(worker, 'session_record_path', None):
from .session_record import handoff_session
from .operation_queue import hold_native_handoff
handoff_session(worker.session_record_path, evidence_root=root, process=worker)
hold_native_handoff(worker, worker.session_record_path)
worker.close()
try:
if entered:
native.__exit__(None, None, None)
if worker.poll() is None and getattr(worker, 'session_record_path', None):
from .session_record import handoff_session
from .operation_queue import hold_native_handoff
handoff_session(worker.session_record_path, evidence_root=root, process=worker)
hold_native_handoff(worker, worker.session_record_path)
finally:
worker.close()
+1
View File
@@ -1111,6 +1111,7 @@ class MainWindow(QWidget):
self._current_job = previous_job
self._jobs.pop(job.context.operation_id, None)
job.context = task.context
self.stop = task.stop
self._jobs[job.context.operation_id] = job
task.ui_job = job
task.revision = self._view_revision
+7 -1
View File
@@ -1010,7 +1010,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .desktop_worker import DesktopWorker
from .dialog_supervisor import AgentDialogBackend, DialogSupervisor, Win32DialogBackend
from .dialog_models import DialogPhase
from .operation_queue import check_active, native_channel
from .operation_queue import TaskHandoff, check_active, native_channel
check_active()
worker_launch_attempted = False
native = native_channel()
@@ -1322,6 +1322,12 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
'detail': '已转后台观察,可查看状态'})
from .operation_queue import hold_native_handoff
hold_native_handoff(process, process.session_record_path)
except TaskHandoff as error:
handoff_result = _handoff_verify_result(error)
if handoff_result.evidence_path:
_write_optional_evidence(handoff_result.evidence_path,
{'block_name': request.block_name, **asdict(handoff_result)})
raise
except Exception as error:
close_errors.append(str(error))
if 'process' in locals():
+112
View File
@@ -0,0 +1,112 @@
"""PR 16: handoff must preserve control flow, resource cleanup and cancellation."""
import json
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
def test_verify_handoff_skips_duplicate_native_cleanup_and_keeps_result(tmp_path, monkeypatch):
from cbb_refresh_verify import operation_queue, verify_runner
from test_cancelled_session_handoff import worker_fixture
handoff = operation_queue.hold_native_handoff
state, _, run = worker_fixture(tmp_path, monkeypatch)
monkeypatch.setattr(operation_queue, 'hold_native_handoff', handoff)
late_cleanup = []
monkeypatch.setattr(verify_runner, '_cleanup_session_processes',
lambda *a, **kw: late_cleanup.append(True) or {'safe_to_continue': False})
completed = Event()
original = verify_runner._run_verify_task
def execute(*args, **kwargs):
try:
return original(*args, **kwargs)
finally:
completed.set()
monkeypatch.setattr(verify_runner, '_run_verify_task', execute)
result = run(True)
assert completed.wait(3)
assert result.status == 'CANCELLED' and not result.safe_to_continue
assert state['observers'] and not state['closed']
assert not late_cleanup, 'The registered observer owns native cleanup after handoff'
saved = json.loads(state['path'].with_name('result.json').read_text(encoding='utf-8'))
assert saved['status'] == 'CANCELLED' and saved['safe_to_continue'] is False
@pytest.mark.parametrize('registration_error', [False, True])
def test_repair_handoff_always_closes_local_worker_resources(tmp_path, monkeypatch, registration_error):
from cbb_refresh_verify import desktop_worker, native_repair, session_record
from cbb_refresh_verify.operation_queue import BatchTaskContext, TaskHandoff
events = []
class Worker:
pid = 700
session_record_path = tmp_path/'session.json'
def __init__(self, *args): pass
def bind_cancellation(self, path): pass
def bind_session(self, job): pass
def poll(self): return None
def request_stop(self): events.append('stop')
def close(self): events.append('close')
monkeypatch.setattr(desktop_worker, 'DesktopWorker', Worker)
ticks = iter((0, 100))
monkeypatch.setattr(native_repair, 'time', SimpleNamespace(monotonic=lambda: next(ticks)))
def observe(*args, **kwargs):
events.append('observe')
if registration_error:
raise OSError('observer registration failed')
monkeypatch.setattr(session_record, 'handoff_session', observe)
context = BatchTaskContext(str(tmp_path/'library.lmc'))
completed = Event()
def execute():
try:
return native_repair._supervise_repair([], 'CbbRepair_test', tmp_path/'cancel',
tmp_path, 1, None, None, {'start_gate': str(tmp_path/'start')})
finally:
completed.set()
with pytest.raises(OSError if registration_error else TaskHandoff):
context.run(execute)
assert completed.wait(3)
assert events == ['stop', 'observe', 'close']
def test_icdb_fallback_stop_cancels_the_active_task_context(qtbot, tmp_path, monkeypatch):
from cbb_refresh_verify.verify_runner import VerifyResult
from test_ui_filters import load_window
entered, release = Event(), Event()
def verify(request):
entered.set()
assert release.wait(3)
return VerifyResult('CANCELLED')
window = load_window(qtbot, tmp_path, monkeypatch, verifier=verify)
window._start_icdb_check(['Beta'])
try:
qtbot.waitUntil(entered.is_set)
window.stop.set()
assert window.icdb_task.stop.is_set(), 'Fallback Stop must cancel the running ICDB task'
finally:
window.icdb_task.cancel()
release.set()
qtbot.waitUntil(lambda: not window.icdb_task.active)
@pytest.mark.parametrize('mode', ['versions', 'repair'])
@pytest.mark.parametrize('config', [
'KEY iCDBDir "C:\\outside\\database"\n',
'KEY iCDBDir "database"\nKEY iCDBDir "other"\n',
])
def test_ambiguous_or_absolute_database_stops_before_native_launch(tmp_path, monkeypatch, mode, config):
from cbb_refresh_verify import native_backup
from test_native_backup import project_fixture
request, project = project_fixture(tmp_path)
project.write_text(config, encoding='utf-8')
monkeypatch.setattr(native_backup, 'native_backup_executable',
lambda *_: pytest.fail('Invalid database binding reached native preparation'))
with pytest.raises(ValueError, match='NATIVE_TARGET_UNCONFIRMED'):
native_backup.launch_native_backup(request, mode=mode)
assert not request.evidence_dir.exists()