Merge branch 'codex/review-residual-release' into codex/runtime-lifecycle-safety

This commit is contained in:
阿白叔 committed 2026-11-09 14:10:38 +08:00
commit d0a5ce5d17
20 files changed
+454 -72

No files matched your search

+21 -2
View File
@@ -84,11 +84,30 @@ def test_scan_reuses_checkpoint_and_queries_only_missing(tmp_path):
encoding="utf-8",
)
bridge = FakeBridge()
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint)
records = BatchStatusSession(bridge).scan(["A", "B"], lmc, checkpoint, resume=True)
assert bridge.requests == ["B"]
assert {record.block_name for record in records} == {"A", "B"}
def test_default_scan_refreshes_cached_ready_after_payload_change(tmp_path):
lmc = tmp_path/'library.lmc'; lmc.write_bytes(b'library')
checkpoint = tmp_path/'scan.jsonl'
BatchStatusSession(FakeBridge()).scan(['A'], lmc, checkpoint)
# The lightweight fingerprint cannot prove payload status is unchanged.
fingerprint = fingerprint_library(lmc)
(tmp_path/'payload.pcb').write_bytes(b'native edit without LMC change')
assert fingerprint_library(lmc) == fingerprint
class PendingBridge(FakeBridge):
def query(self, *args, **kwargs):
self.requests.append(args[1])
return BridgeResult('PENDING', 'fake')
bridge = PendingBridge()
records = BatchStatusSession(bridge).scan(['A'], lmc, checkpoint)
assert [record.status for record in records] == ['PENDING']
assert bridge.requests == ['A']
assert len(checkpoint.read_text('utf-8').splitlines()) == 1
def test_timeout_isolated_and_later_item_continues(tmp_path):
lmc = tmp_path / "mentor_lib.lmc"
lmc.write_bytes(b"library")
@@ -180,7 +199,7 @@ def test_retry_rechecks_failed_scan_without_library_changes(tmp_path):
first = BatchStatusSession(FakeBridge(timeout_name='A')).scan(['A', 'B'], lmc, checkpoint)
assert first[0].status == 'TIMEOUT'
bridge = FakeBridge()
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint)
second = BatchStatusSession(bridge).scan(['A', 'B'], lmc, checkpoint, resume=True)
assert bridge.requests == ['A']
assert second[0].status == 'READY'
+1 -1
View File
@@ -82,5 +82,5 @@ def test_fingerprint_change_does_not_reuse_checkpoint(tmp_path):
from cbb_refresh_verify.status_bridge import BridgeResult
return BridgeResult("PENDING", "fake")
bridge = Bridge()
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint)
BatchStatusSession(bridge).scan(["A"], lmc, checkpoint, resume=True)
assert bridge.requests == ["A"]
+1 -1
View File
@@ -291,7 +291,7 @@ def test_status_cache_does_not_reuse_a_different_block_type(tmp_path):
return BridgeResult('READY', 'test')
session = BatchStatusSession(Bridge())
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='RULP')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other')
session.scan(['Block'], library, tmp_path/'scan.jsonl', block_type='Other', resume=True)
assert calls == ['RULP', 'Other']
-18
View File
@@ -2,7 +2,6 @@ import pytest
from cbb_refresh_verify.pcb_bridge import (
PcbBridgeError,
execution_outcome,
require_document_identity,
wait_for_target_document,
)
@@ -74,23 +73,6 @@ def test_bridge_stops_if_pcb_exits_before_com_is_ready(tmp_path):
assert raised.value.error_code == 'PCB_EXITED_BEFORE_COM'
def test_fatal_dialog_overrides_successful_save_markers():
result = execution_outcome(
save_complete=True,
pcb_exited=True,
fatal_error='SAVE_REUSABLE_BLOCK_FAILED: Error saving the Reusable Block',
)
assert result['status'] == 'FAIL'
assert result['error_code'] == 'SAVE_REUSABLE_BLOCK_FAILED'
def test_success_requires_save_and_pcb_exit():
assert execution_outcome(save_complete=True, pcb_exited=True)['status'] == 'PASS'
assert execution_outcome(save_complete=False, pcb_exited=True)['status'] == 'FAIL'
assert execution_outcome(save_complete=True, pcb_exited=False)['status'] == 'FAIL'
def test_connected_com_without_document_remains_startup_and_checks_native_failure(tmp_path):
errors = iter(('', 'ICDB_REPAIR_REQUIRED: original lost session'))
events = []
+166
View File
@@ -0,0 +1,166 @@
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from PySide6.QtCore import QCoreApplication, QEvent
from PySide6.QtWidgets import QMessageBox
from shiboken6 import isValid
from cbb_refresh_verify.verify_runner import VerifyResult
def flush_deletes():
QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete)
def test_repeated_batch_results_retire_previous_dialog(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._batch_done(([VerifyResult('FAIL')], tmp_path/'report.log'))
previous = window.summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'report2.log'))
flush_deletes()
assert not isValid(previous)
assert len(window.findChildren(QMessageBox)) == 1
current = window.summary
current.close()
flush_deletes()
assert not isValid(current)
window._update() # No retained reference to deleted result actions.
def test_repeated_icdb_results_preserve_latest_recovery_task(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from test_reimport_recovery import failed_repair
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: failed_repair(tmp_path/'result.json', safe=True))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
first_task, previous = window.icdb_task, window.icdb_summary
window._run(['Gamma'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
flush_deletes()
assert not isValid(previous)
assert not hasattr(first_task, 'summary')
assert len(window.findChildren(QMessageBox)) == 1
assert window.icdb_task.summary is window.icdb_summary
action = next(b for b in window.icdb_summary.buttons() if '副本' in b.text())
action.click()
assert [request.name for request in window.management_dialog.requests()] == ['Gamma']
window.management_dialog.reject()
window._invalidate_check_targets('test.lmc', ['Beta', 'Gamma'])
window._update()
def test_batch_replacement_preserves_independent_icdb_result(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch,
verifier=lambda _: VerifyResult('CHECKED'))
window._run(['Beta'], maintenance=True)
qtbot.waitUntil(lambda: not window._icdb_active())
icdb_summary = window.icdb_summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'first.log'))
old_batch = window.summary
window._batch_done(([VerifyResult('PASS')], tmp_path/'second.log'))
flush_deletes()
assert not isValid(old_batch)
assert isValid(icdb_summary) and icdb_summary.isVisible()
assert window.icdb_task.summary is icdb_summary
assert len(window.findChildren(QMessageBox)) == 2
def test_close_wait_notice_remains_visible_and_timer_stops_on_idle(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
entered, release = Event(), Event()
def close_lease():
entered.set()
release.wait(5)
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window.library_lease = SimpleNamespace(close=close_lease)
window.show()
try:
window.close()
qtbot.waitUntil(entered.is_set)
assert window.isVisible() and '等待' in window.windowTitle()
timer = window.close_wait_timer
assert timer.isActive() and timer.interval() == 120_000
timer.start(10)
qtbot.waitUntil(lambda: '仍在等待' in window.windowTitle())
assert '仍在等待' in window.status_label.text()
window.close()
assert window.isVisible()
finally:
release.set()
qtbot.waitUntil(lambda: not window.isVisible())
assert not timer.isActive()
@pytest.fixture
def batch_cli(tmp_path, monkeypatch):
import cbb_refresh_verify.application as application
import cbb_refresh_verify.library_reader as reader
import cbb_refresh_verify.network_path as network
import cbb_refresh_verify.verify_runner as runner
from cbb_refresh_verify.models import CbbRecord, LibraryReadResult
log, requested, retained = [], [], []
def record(message, *args, **kwargs):
log.append(message % args if args else message)
logger = SimpleNamespace(info=record, warning=record, exception=record, handlers=())
monkeypatch.setattr(application, 'configure', lambda *_: SimpleNamespace(root=tmp_path, logger=logger))
class Lease:
display_path = Path(r'\\server\share\library')
mentor_path = tmp_path/'lib.lmc'
drive, remote_root, created = 'Z:', r'\\server\share', True
def __enter__(self): return self
def __exit__(self, *_): pass
def retain_for_recovery(self): retained.append(self.drive)
monkeypatch.setattr(network.LibraryPathLease, 'acquire', lambda _: Lease())
monkeypatch.setattr(network, 'select_library_file', lambda path: path)
monkeypatch.setattr(reader, 'read_library_fast', lambda *a, **kw: LibraryReadResult((
CbbRecord('Ready', 'LP', status='READY'), CbbRecord('One', 'LP'),
CbbRecord('Two', 'LP'), CbbRecord('Three', 'LP'))))
def run(requests):
requested.extend(request.block_name for request in requests)
return [VerifyResult('PASS') for _ in requests]
monkeypatch.setattr(runner, 'run_batch', run)
monkeypatch.setattr(runner, 'write_batch_report', lambda *a: tmp_path/'batch.log')
return application, runner, log, requested, retained
@pytest.mark.parametrize('extra, expected, counts', [
([], ['One', 'Two', 'Three'], (3, 3, 0)),
(['--limit', '2'], ['One', 'Two'], (2, 3, 1)),
(['--block', 'Three', '--block', 'One', '--limit', '1'], ['Three'], (1, 2, 1)),
])
def test_batch_cli_limit_is_optional_and_reports_selection(batch_cli, extra, expected, counts):
app, _, log, requested, _ = batch_cli
assert app.main(['--batch-lmc', 'lib.lmc', *extra]) == 0
assert requested == expected
assert any(all(f'{key}={value}' in line for key, value in zip(
('selected', 'total', 'remaining'), counts)) for line in log)
@pytest.mark.parametrize('value', ['0', '-1', 'no'])
def test_batch_cli_rejects_nonpositive_limit(batch_cli, value):
app, _, _, requested, _ = batch_cli
with pytest.raises(SystemExit) as error:
app.main(['--batch-lmc', 'lib.lmc', '--limit', value])
assert error.value.code == 2 and not requested
@pytest.mark.parametrize('raised', [False, True])
def test_retained_mapping_logs_context_and_confirmed_release_guidance(batch_cli, monkeypatch, raised):
app, runner, log, _, retained = batch_cli
def run(_):
if raised: raise RuntimeError('native writer status unknown')
return [VerifyResult('FAIL', safe_to_continue=False)]
monkeypatch.setattr(runner, 'run_batch', run)
assert app.main(['--batch-lmc', 'lib.lmc', '--block', 'One']) == (1 if raised else 2)
assert retained == ['Z:']
notice = next(line for line in log if 'batch_drive_retained' in line)
assert 'Z:' in notice and r'\\server\share' in notice
assert '释放残留会话' in notice and '确认' in notice
assert 'net use' not in notice.lower()
@@ -23,3 +23,18 @@ def test_confirmed_scope_and_execution_divergence_are_visible(qtbot, tmp_path, m
assert dialog.table.item(1, 7).text() == '未释放'
assert '原生操作进行中' in dialog.table.item(1, 3).text()
assert '确认允许 2' in dialog.message.text() and '未释放 1' in dialog.message.text()
def test_retiring_batch_summary_forgets_enabled_release_actions(qtbot, tmp_path):
from cbb_refresh_verify.ui.main_window import MainWindow
from cbb_refresh_verify.verify_runner import VerifyResult
from test_review345_ui_cli import flush_deletes
window = MainWindow(data_root=tmp_path)
qtbot.addWidget(window)
window._batch_done(([VerifyResult('FAIL', safe_to_continue=False)], None))
assert window._residual_release_action is not None
window.summary.close(); flush_deletes()
window._update()
assert window._residual_release_action is None
window._resume_batch = dict(library=tmp_path/'lib.lmc', released=True)
window._release_dialog_finished()
+14
View File
@@ -87,6 +87,20 @@ def test_management_records_scoped_changes_without_hashing_unrelated_cbb(setup,
assert 'SymbolLibs/shared/icdb.dat' in report['modified']
assert 'ReusableBlocksLP/Block/Work/Block.prj' in report['modified']
assert result.change_report == report
assert report['rule_version'] == 1
assert report['scope'] == {'kind': 'library', 'block_name': 'Block',
'library_name': request.library.name}
from cbb_refresh_verify import scoped_manifest as manifests
assert report['excluded_categories'] == sorted(manifests._NONPRIMARY_DIRECTORIES)
assert report['excluded_suffixes'] == sorted(manifests._NONPRIMARY_SUFFIXES)
runtime = report['runtime_exclusions']
assert runtime['native_directory_names'] == ['dbcheck', 'dbrestore', 'log']
assert runtime['file_names'] == ['saddress.adr']
assert runtime['file_name_prefixes'] == ['~$']
assert runtime['relative_directories'] == ['projectbackup/backups']
assert runtime['directory_prefixes'] == ['work.before-restore-']
assert 'selected CBB Work/Cert root or its PCB child' in runtime['directory_name_positions']
assert 'SymbolLibs/<partition>/cdbsvr' in runtime['native_directory_positions']
def test_failed_mutation_still_records_changes_and_release_fact(setup):
@@ -29,3 +29,17 @@ def test_report_failure_is_visible_without_inventing_native_failure(qtbot, setup
assert '历史会话已释放' in dialog.output.toPlainText()
dialog._progress({'stage':'previous_release_check','block':request.name})
assert '正在复核历史占用' in dialog.status_label.text()
def test_recorded_counts_identify_compared_engineering_file_scope(qtbot, setup):
from cbb_refresh_verify.management import ManagementResult
from cbb_refresh_verify.ui.management_dialog import ManagementDialog
request, _, _ = setup
dialog = ManagementDialog([request]); qtbot.addWidget(dialog)
result = ManagementResult(request.operation, request.library, request.name, request.partition,
None, False, 'complete', 'REMOVED', True, 'removed',
change_report={'status': 'RECORDED', 'added': ['a'], 'deleted': [], 'modified': ['b']})
dialog._result([result])
text = dialog.output.toPlainText()
assert '已比对的工程文件' in text
assert '新增 1' in text and '删除 0' in text and '修改 1' in text
+31 -6
View File
@@ -118,17 +118,42 @@ def test_corrupted_destination_bytes_are_rejected_and_evidence_is_preserved(tmp_
assert (destination/relative).exists()
def test_unlocked_primary_copy_reads_source_twice_and_target_once(tmp_path, monkeypatch):
from collections import Counter
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj', b'engineering' * 100000)
reads = Counter()
original_open = Path.open
def opened(path, mode='r', *args, **kwargs):
if mode == 'rb':
reads[path] += 1
return original_open(path, mode, *args, **kwargs)
monkeypatch.setattr(Path, 'open', opened)
hashes = Counter()
original_hash = recovery._hash
def hashed(path):
hashes[path] += 1
return original_hash(path)
monkeypatch.setattr(recovery, '_hash', hashed)
manifest = recovery._copy_verified(source, destination)
assert hashes[primary] == 1 # Only the final source rehash is a separate pass.
assert hashes[destination/'A.prj'] == 1
assert reads[primary] == 2 # Copy/hash stream, then final source content proof.
assert reads[destination/'A.prj'] == 1
assert manifest['files']['A.prj']['sha256'] == hashlib.sha256(primary.read_bytes()).hexdigest()
def test_source_byte_changes_with_preserved_metadata_are_rejected(tmp_path, monkeypatch):
source, destination = tmp_path/'source', tmp_path/'destination'
primary = put(source, 'A.prj')
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_change_source(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
metadata = primary.stat()
primary.write_bytes(b'X' * metadata.st_size)
os.utime(primary, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_change_source)
monkeypatch.setattr(shutil, 'copystat', copy_then_change_source)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert (destination/'A.prj').read_bytes() == b'engineering'
@@ -140,7 +165,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
put(source, 'A.prj')
runtime = put(source, 'logs/session.log')
destination = tmp_path/'destination'
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_mutate(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
if Path(src).name == 'A.prj':
@@ -151,7 +176,7 @@ def test_complete_tree_metadata_must_stay_stable_during_copy(tmp_path, monkeypat
else:
put(source, 'logs/added.log')
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_mutate)
monkeypatch.setattr(shutil, 'copystat', copy_then_mutate)
with pytest.raises(OSError):
recovery._copy_verified(source, destination)
assert destination.exists()
@@ -277,7 +302,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
scope = ManifestScope.library(block, 'target.lmc')
source, destination = tmp_path/'source', tmp_path/'destination'
put(source, relative)
real_copy = shutil.copy2
real_copy = shutil.copystat
def copy_then_corrupt(src, dst, *args, **kwargs):
result = real_copy(src, dst, *args, **kwargs)
corrupt = Path(src) if side == 'source' else Path(dst)
@@ -285,7 +310,7 @@ def test_colliding_engineering_names_cannot_bypass_primary_copy_byte_checks(tmp_
corrupt.write_bytes(b'X' * metadata.st_size)
os.utime(corrupt, ns=(metadata.st_atime_ns, metadata.st_mtime_ns))
return result
monkeypatch.setattr(shutil, 'copy2', copy_then_corrupt)
monkeypatch.setattr(shutil, 'copystat', copy_then_corrupt)
with pytest.raises(OSError):
recovery._copy_verified(source, destination, scope=scope)
assert (destination/relative).exists()