fix: preflight short batch attempts and preserve cleanup causes

This commit is contained in:
阿白叔 committed 2026-10-23 15:11:16 +08:00
1 parent b21960cda1
commit 7d5ea814ec
11 files changed
+332 -94

No files matched your search

+36
View File
@@ -161,3 +161,39 @@ def test_native_failure_does_not_reuse_previous_attempt_transaction(prepared, tm
assert report['stage'] == 'preflight' and 'transaction' not in report
assert report['batch_attempt']['job_id'] == 'job-a'
assert attempts.read_attempt(path)['state'] == 'prepared'
def test_attempt_write_handles_long_unicode_evidence_and_keeps_canonical_identity(tmp_path, monkeypatch):
from pathlib import Path
directory = tmp_path / ('long-' + 'x' * 110) / ('more-' + 'y' * 80)
path = directory / 'attempt.json'
real_mkdir = Path.mkdir
def strict_mkdir(target, *args, **kwargs):
if len(str(target)) >= 260 and not str(target).startswith(chr(92) * 2 + '?'):
raise OSError('legacy MAX_PATH')
return real_mkdir(target, *args, **kwargs)
monkeypatch.setattr(Path, 'mkdir', strict_mkdir)
project = tmp_path / 'board.prj'
record = attempts.prepare_attempt(path, session_id='session', generation=1,
task_id='task', job_id='job', project_path=project)
assert record['project_path'] == os.path.normcase(str(project.resolve()))
assert attempts.can_retry_attempt(path, record)
assert not str(record['project_path']).startswith(chr(92) * 2 + '?')
def test_publication_retries_sharing_violation_only_and_keeps_original_record(tmp_path, monkeypatch):
path = tmp_path / 'attempt.json'
first = attempts.prepare_attempt(path, session_id='session', generation=1,
task_id='task', job_id='job', project_path=tmp_path / 'board.prj')
calls = []
def fail(source, target):
calls.append((source, target))
error = PermissionError('sharing violation')
error.winerror = 32
raise error
monkeypatch.setattr(os, 'replace', fail)
with pytest.raises(PermissionError):
attempts.prepare_attempt(path, session_id='session', generation=2,
task_id='task', job_id='job', project_path=tmp_path / 'board.prj')
assert len(calls) == 3
assert attempts.read_attempt(path) == first
assert list(tmp_path.iterdir()) == [path]
+47 -2
View File
@@ -199,7 +199,7 @@ def test_possible_mutation_prevents_automatic_replay(tmp_path, monkeypatch):
calls = []
def monitor(*args, **kwargs):
calls.append(1)
path = next((Path(command[3]) / 'batch-attempts').rglob('job.json'))
path = next((runtime.path.parent / 'attempts').rglob('job.json'))
record = json.loads(path.read_text())
record['state'] = 'mutation_possible'
path.write_text(json.dumps(record))
@@ -228,7 +228,7 @@ def test_previous_checkpoint_invalidated_before_new_worker(tmp_path, monkeypatch
raise WorkerMonitorError('cannot certify empty project')
runtime.cad.checkpoint = fail_checkpoint
# No retry after evidence has been marked as possibly modified.
path = next((Path(command[3]) / 'batch-attempts').rglob('job.json'))
path = next((runtime.path.parent / 'attempts').rglob('job.json'))
record = json.loads(path.read_text())
record['state'] = 'mutation_possible'
path.write_text(json.dumps(record))
@@ -247,6 +247,9 @@ def test_attempt_publication_failure_never_launches_worker(tmp_path, monkeypatch
with runtime, pytest.raises(OSError):
runtime.run_worker(command, 5)
assert not Cad.created
assert not Desktop.created
from dx_productivity.trial_task_center.batch_resources import pending_resources
assert pending_resources(runtime.root) == ()
def test_boundary_pause_does_not_abort_current_cad_startup(tmp_path, monkeypatch):
@@ -498,3 +501,45 @@ def test_identity_conflict_never_rebuilds_or_launches_another_worker(tmp_path, m
assert len(workers) == (1 if conflict.startswith('checkpoint') or conflict == 'worker_identity' else 0)
assert runtime.generation == 1 and not runtime.record['retries']
assert Desktop.created[0].released
def test_request_session_identity_is_uuid_bound(tmp_path):
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
session = '12345678-1234-5678-1234-567812345678'
runtime = BatchCadRuntime(tmp_path, 'bom_import', session_id=session)
assert runtime.session_id == session.replace('-', '')
with pytest.raises(ValueError):
BatchCadRuntime(tmp_path, 'bom_import', session_id='../escape')
def test_cleanup_preserves_primary_bom_error_and_report(tmp_path):
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
primary = TaskCenterError('bom_inspection', 'read failed')
primary.bom_report = object()
Desktop.fail_release = True
with pytest.raises(TaskCenterError) as caught:
with BatchCadRuntime(tmp_path, 'bom_import', desktop_factory=Desktop) as runtime:
with runtime.native_scope(tmp_path / 'operation'):
pass
raise primary
error = caught.value
assert error.primary_error is primary
assert error.cleanup_error is not None
assert error.bom_report is primary.bom_report
assert 'BOM' in error.message and '已核验任务结果保留' not in error.message
assert runtime.record['primary_error']['code'] == primary.code
assert runtime.record['cleanup_error']
Desktop.fail_release = False
from dx_productivity.trial_task_center.batch_resources import cleanup_pending_resources
cleanup_pending_resources(tmp_path)
def test_attempts_live_under_short_session_root(tmp_path, monkeypatch):
import subprocess
command, _ = command_for(tmp_path)
runtime = worker_runtime(tmp_path, monkeypatch, lambda command, *a, **k:
subprocess.CompletedProcess(command, 0, '', ''))
with runtime:
runtime.run_worker(command, 5)
assert list((runtime.path.parent / 'attempts').rglob('job.json'))
assert not (Path(command[3]) / 'batch-attempts').exists()
@@ -231,6 +231,8 @@ def test_native_cleanup_failure_blocks_fallback_and_keeps_recovery_evidence(tmp_
with pytest.raises(TaskCenterError) as caught:
reader.read(project, ('OLD',), stop_event=stop)
assert caught.value.code == 'inventory_cleanup'
assert caught.value.primary_error.code == 'operation_cancelled'
assert isinstance(caught.value.cleanup_error, OSError)
assert released == [True] and list((tmp_path / 'evidence').rglob('uncertain.flag'))
assert list((tmp_path / 'temporary').iterdir())
+70
View File
@@ -0,0 +1,70 @@
import pytest
def test_windows_extended_paths_keep_canonical_identity():
from dx_productivity.trial_task_center.path_access import windows_extended_path, strip_extended_prefix
slash = chr(92)
local = 'C:' + slash + ('nested' + slash) * 45 + 'file.json'
assert windows_extended_path(local) == slash * 2 + '?' + slash + local
assert strip_extended_prefix(windows_extended_path(local)) == local
unc = slash * 2 + 'server' + slash + 'share' + slash + 'file.json'
assert windows_extended_path(unc) == slash * 2 + '?' + slash + 'UNC' + unc[1:]
assert strip_extended_prefix(windows_extended_path(unc)) == unc
def test_sharing_retry_is_bounded_and_does_not_retry_permission_denied():
from dx_productivity.trial_task_center.path_access import retry_sharing_violation
calls = []
def operation():
calls.append(1)
error = PermissionError('sharing violation')
error.winerror = 32
raise error
with pytest.raises(PermissionError):
retry_sharing_violation(operation, sleep=lambda delay: None)
assert len(calls) == 3
calls.clear()
def denied():
calls.append(1)
raise PermissionError('access denied')
with pytest.raises(PermissionError):
retry_sharing_violation(denied, sleep=lambda delay: None)
assert len(calls) == 1
def test_discovery_uses_extended_filesystem_access_before_legacy_launch(tmp_path, monkeypatch):
import os
import subprocess
from pathlib import Path
from dx_productivity.trial_task_center.project_discovery import discover_project, DiscoveryRuntime
if os.name != 'nt':
pytest.skip('Windows filesystem boundary')
data = tmp_path / ('nested-' + 'a' * 90) / ('more-' + 'b' * 70)
project = tmp_path / 'board.prj'
project.write_text('project')
script = tmp_path / 'worker.vbs'
script.write_text('script')
real_mkdir = Path.mkdir
def strict_mkdir(path, *args, **kwargs):
if len(str(path)) >= 260 and not str(path).startswith(chr(92) * 2 + '?'):
raise OSError('legacy MAX_PATH filesystem access')
return real_mkdir(path, *args, **kwargs)
monkeypatch.setattr(Path, 'mkdir', strict_mkdir)
reached = []
def launch(*args):
reached.append(1)
raise subprocess.SubprocessError('stop at launch')
runtime = DiscoveryRuntime(launch, lambda: Path('cscript'), lambda s, r: (str(s), str(r)),
lambda: (), str, lambda *a: (), lambda *a: {}, 5)
with pytest.raises(Exception):
discover_project(project, ('OLD',), data_root=data, script_source=script, runtime=runtime)
assert reached, 'long-path filesystem preparation failed before worker boundary'
def test_native_short_path_never_passes_extended_prefix_to_wsh(tmp_path):
import os
from dx_productivity.trial_task_center.legacy_paths import _short_path
if os.name != 'nt':
pytest.skip('Windows short-path boundary')
result = _short_path(tmp_path)
if result is None:
pytest.skip('filesystem does not provide short paths')
assert not result.startswith(chr(92) * 2 + '?')