feat(logs): retain resource release history in batch and task logs

This commit is contained in:
阿白叔 committed 2026-10-21 18:01:59 +08:00
1 parent faad50df80
commit 2a9398ab50
12 files changed
+365 -15

No files matched your search

+153
View File
@@ -0,0 +1,153 @@
"""Release diagnostics remain visible without changing cleanup decisions."""
import json
import pytest
from dx_productivity.trial_task_center import batch_resources, batch_runtime
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.ui.messages import _format_task_log_lines
from test_batch_runtime import Desktop
@pytest.fixture(autouse=True)
def reset_desktop():
Desktop.created = []
Desktop.fail_release = False
def events(root, task='one'):
return [json.loads(line) for line in (root / 'tasks' / task / 'events.jsonl')
.read_text(encoding='utf-8').splitlines()]
def runtime(root):
result = batch_runtime.BatchCadRuntime(root, 'task_queue', desktop_factory=Desktop)
result.bind_logs(configure_logging(root), ('one', 'two'))
return result
def test_batch_release_is_readable_and_visible_for_each_participating_task(tmp_path):
with runtime(tmp_path) as owner:
with owner.native_scope(tmp_path / 'native'):
pass
log = owner.path.with_name('resource-release.log').read_text(encoding='utf-8')
assert '开始释放' in log and '资源释放成功' in log
assert owner.session_id in log and owner.record['desktop'] in log
assert 'CAD 未启动' in log
for task in ('one', 'two'):
rows = events(tmp_path, task)
assert [row['operation'] for row in rows] == ['resource_release_started', 'resource_release_succeeded']
details = rows[-1]['details']
assert details['batch_id'] == owner.session_id and details['generation'] == 1
assert details['desktop_handle_closed'] is True and details['desktop_disappeared'] is True
assert details['elapsed_seconds'] >= 0 and details['record_path'] == str(owner.path)
assert '资源释放成功' in '\n'.join(_format_task_log_lines(tuple(json.dumps(row) for row in rows)))
assert '资源释放成功' in (tmp_path / 'logs/application.log').read_text(encoding='utf-8')
def test_failed_release_and_manual_retry_keep_both_results_without_replay(tmp_path):
Desktop.fail_release = True
owner = runtime(tmp_path)
with pytest.raises(batch_resources.BatchResourceCleanupError):
with owner:
with owner.native_scope(tmp_path / 'native'):
pass
owner.result = 'saved and verified'
failed = events(tmp_path)[-1]
assert failed['operation'] == 'resource_release_failed'
assert 'outside owner retains desktop' in failed['message']
assert failed['details']['desktop_disappeared'] is False
assert failed['details']['result'] == 'blocked'
Desktop.fail_release = False
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
rows = events(tmp_path)
assert [row['sequence'] for row in rows] == [1, 2, 3, 4]
assert rows[-1]['operation'] == 'resource_release_succeeded'
assert rows[-1]['details']['reason'] == 'manual_retry'
assert owner.result == 'saved and verified' and len(Desktop.created) == 1
def test_release_log_failure_does_not_skip_cleanup_or_falsify_its_result(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_release_log
def denied(*_args):
raise OSError('release log locked')
monkeypatch.setattr(batch_release_log, '_append_line', denied)
with runtime(tmp_path) as owner:
with owner.native_scope(tmp_path / 'native'):
pass
assert Desktop.created[0].released
assert owner.record['state'] == 'released' and not batch_resources.pending_resources(tmp_path)
persisted = json.loads(owner.path.read_text(encoding='utf-8'))
assert any('release log locked' in entry for entry in persisted['release_log_errors'])
assert events(tmp_path)[-1]['operation'] == 'resource_release_succeeded'
def test_restart_recheck_logs_original_batch_and_tasks(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import isolated_desktop
Desktop.fail_release = True
owner = runtime(tmp_path)
with pytest.raises(batch_resources.BatchResourceCleanupError):
with owner:
with owner.native_scope(tmp_path / 'native'):
pass
batch_resources.LIVE_RESOURCES.pop(str(owner.path))
class Api:
def confirm_desktop_released(self, name):
assert name == owner.record['desktop']
monkeypatch.setattr(isolated_desktop, '_Win32Api', Api)
assert batch_resources.cleanup_pending_resources(tmp_path, logging_context=configure_logging(tmp_path)) == ()
row = events(tmp_path)[-1]
assert row['operation'] == 'resource_release_succeeded'
assert row['details']['reason'] == 'restart_recheck'
assert row['details']['batch_id'] == owner.session_id
assert row['details']['desktop_disappeared'] is True
assert len(Desktop.created) == 1
def test_cached_batch_has_no_misleading_release_success(tmp_path):
with runtime(tmp_path) as owner:
pass
assert not owner.path.exists()
assert not owner.path.with_name('resource-release.log').exists()
assert not (tmp_path / 'tasks/one/events.jsonl').exists()
def test_cad_exit_and_cleanup_evidence_are_logged(tmp_path):
with runtime(tmp_path) as owner:
with owner.native_scope(tmp_path / 'native'):
pass
class Cad:
record = {'state': 'session_closed', 'clean': True,
'cad_exit_code': 0, 'quit_helper_exit_code': 0, 'shutdown_seconds': .01}
def __exit__(self, *_):
pass
owner.cad = Cad()
owner._save(cad_pid=123, cad_guid='owned')
event = events(tmp_path)[-1]
assert event['details']['cad_pid'] == 123
assert event['details']['cad_exit_code'] == event['details']['quit_helper_exit_code'] == 0
assert 'CAD 退出码=0' in event['message']
def test_release_logger_crash_cannot_hide_final_cleanup_failure(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_release_log
def crash(*_args, **_options):
raise OSError('diagnostic unavailable')
monkeypatch.setattr(batch_release_log, 'write_release_event', crash)
Desktop.fail_release = True
owner = runtime(tmp_path)
with pytest.raises(batch_resources.BatchResourceCleanupError):
with owner:
with owner.native_scope(tmp_path / 'native'):
pass
assert batch_resources.pending_resources(tmp_path)
Desktop.fail_release = False
batch_resources.LIVE_RESOURCES.pop(str(owner.path))
from dx_productivity.trial_task_center import isolated_desktop
class Api:
def confirm_desktop_released(self, _name):
pass
monkeypatch.setattr(isolated_desktop, '_Win32Api', Api)
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
record = json.loads(owner.path.read_text())
assert record['state'] == 'released' and record['release_log_errors']
@@ -27,6 +27,8 @@ def runtime_module(monkeypatch):
scopes.append(self)
def __enter__(self):
return self
def bind_logs(self, context, task_ids):
self.log_task_ids = tuple(task_ids)
def __exit__(self, *args):
self.closed = True
if self.fail_cleanup:
@@ -58,6 +60,7 @@ def test_task_queue_owns_one_runtime_and_passes_it_to_every_child(tmp_path, runt
assert [entry.state for entry in result.entries] == ['completed', 'completed']
assert len(scopes) == 1 and scopes[0].closed
assert seen == [scopes[0], scopes[0]]
assert scopes[0].log_task_ids == ('A', 'B')
def test_final_cleanup_failure_preserves_completed_tasks_and_resume_does_not_repeat(tmp_path, runtime_module):
+9
View File
@@ -11,12 +11,14 @@ from dx_productivity.trial_task_center.batch_runtime import (
BatchCadRuntime, BatchResourceCleanupError, cleanup_pending_resources, guard_pending_resources)
from dx_productivity.trial_task_center.cad_identity import current_desktop_name
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api, build_startup_info
from dx_productivity.trial_task_center.logging_setup import configure_logging
@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()
runtime = BatchCadRuntime(tmp_path, 'execution')
runtime.bind_logs(configure_logging(tmp_path), ('windows-resource-test',))
external = None
try:
with pytest.raises(BatchResourceCleanupError) as caught:
@@ -35,6 +37,8 @@ def test_external_reference_preserves_completed_result_until_resource_only_clean
assert caught.value.completed_result == runtime.result
assert external.poll() is None
assert json.loads(runtime.path.read_text())['state'] == 'blocked'
log = runtime.path.with_name('resource-release.log').read_text(encoding='utf-8')
assert '资源释放失败' in log and '桌面消失:未确认' in log
with pytest.raises(BatchResourceCleanupError):
guard_pending_resources(tmp_path)
assert not list(Path(tmp_path).rglob('uncertain.flag'))
@@ -46,4 +50,9 @@ def test_external_reference_preserves_completed_result_until_resource_only_clean
assert json.loads(runtime.path.read_text())['state'] == 'released'
assert runtime.result == 'already saved and independently verified'
assert runtime.generation == 1
rows = [json.loads(line) for line in (tmp_path / 'tasks/windows-resource-test/events.jsonl')
.read_text(encoding='utf-8').splitlines()]
assert [row['operation'] for row in rows] == ['resource_release_started', 'resource_release_failed',
'resource_release_started', 'resource_release_succeeded']
assert rows[-1]['details']['desktop_disappeared'] is True
guard_pending_resources(tmp_path)
+4 -1
View File
@@ -36,8 +36,10 @@ def test_reports_all_matching_errors_and_success_is_read_only(batch, tmp_path):
def test_bom_batch_passes_one_runtime_to_all_project_reads(batch, tmp_path, monkeypatch):
from types import SimpleNamespace
service, store, tasks, targets, calls = batch
runtime = object()
bound = []
runtime = SimpleNamespace(bind_logs=lambda context, task_ids: bound.append((context, task_ids)))
seen = []
for task in tasks:
preparer = service.for_project_task(task.task_id)._quick_run_preparer
@@ -50,6 +52,7 @@ def test_bom_batch_passes_one_runtime_to_all_project_reads(batch, tmp_path, monk
write_bom_template(tmp_path / 'shared.xlsx', records_for(tasks, targets)), runtime=runtime)
assert report.passed_projects == 2
assert seen == [runtime, runtime]
assert bound == [(service._logging, tuple(task.task_id for task in tasks))]
def test_duplicate_marks_both_rows_and_cross_row_chain_rejected(batch, tmp_path):