fix: narrow cross-item and cross-library blockers

This commit is contained in:
阿白叔 committed 2026-11-05 07:42:49 +08:00
1 parent 53118bae19
commit aea6192ef9
8 files changed
+178 -15

No files matched your search

@@ -0,0 +1,26 @@
# 阻塞范围收紧记录
本轮处理的是“一个 CBB 出问题后把整批和其他库一起停掉”的误阻塞。
## 已收紧
- 批次继续条件保持按实际释放证据判断。单项 FAIL、ICDB 检查发现问题或普通内容错误,只要本次原生/自动化客户端已经退出并返回 `safe_to_continue=true`,下一项继续;只有进程仍存活、退出状态无法确认或共享写入安全无法证明时才停止后续写操作。
- 管理失败状态现在绑定实际中心库。切换到另一个中心库会清除旧库的 `_management_unsafe`,不会把库 A 的失败带到库 B;释放检查完成回调也只清除同一库的状态。
- 显式维护的原生占用检查按目标 PRJ 命令行过滤无关 PCB/Library Manager。旧的零参数占用探针仍兼容,目标路径可用时不再被其他 CBB 阻塞。
- 释放证明支持目标 CBB 范围。提供目标名称时,只检查该 Work 工程的地址记录、主要数据库文件和命令行包含该工程的原生客户端;其他 CBB 的 `sAddress.adr` 不再阻塞当前恢复。无目标范围的全库释放检查继续保守处理。
- 释放接口新增参数保持旧调用兼容;旧插件或测试没有 `block_name` 参数时继续走全库证明路径。
- UI 比较中心库身份不再对不可达 UNC 路径调用会访问网络的 `Path.resolve()`。网络共享暂时不可达时保持可用状态和错误提示,不在界面刷新中抛异常。
## 仍然必须停止的情况
- 当前项的 PCB、Project Backup、保存助手、Importer 或管理工作进程仍在运行。
- 进程查询失败、原生窗口身份不明、退出状态缺失,或库锁/共享写入归属无法确认。
- 用户明确点击取消,当前批次停止后续项目。
这些停止条件保护共享数据库和原生写入现场;移除它们会把一个仍在写入的工程与下一个 CBB 并行运行,可能造成更大范围的数据损坏。
## 验证
新增回归覆盖单项已释放失败继续批次、切库清除管理阻塞、目标 CBB 过滤无关进程/地址、旧释放接口兼容和不可达 UNC 路径。最终全量回归 **1309 passed**,1 条既有 pywinauto STA 警告;`compileall` 与 `git diff --check` 通过。
本轮没有修改图标等其他工作区文件,也没有对现场中心库执行写入、Repair 或 Restore。
+16 -6
View File
@@ -315,7 +315,7 @@ def owned_snapshot(path):
@contextmanager
def _prove_library_released(library):
def _prove_library_released(library, block_name=None):
"""Hold all native database read handles during explicit lease release."""
import win32con, win32file
from .owner_probe import query_owners
@@ -333,11 +333,16 @@ def _prove_library_released(library):
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe', 'CleanWGLib.exe',
'cscript.exe', 'wscript.exe', 'python.exe', 'pythonw.exe',
'CbbRefreshVerify.exe', *sorted(_OWNER_NAMES))
scope_root = (Path(library).resolve().parent/'ReusableBlocksLP'/block_name/'Work').resolve() if block_name else None
def check_owners():
owners = []
for item in query_owners(names):
if item['pid'] == os.getpid():
continue
if scope_root is not None and item.get('command'):
command = str(item['command']).casefold().replace('/', '\\')
if str(scope_root).casefold().replace('/', '\\') not in command:
continue
automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
command = item['command'].casefold()
if not automation or not command or any(flag in command for flag in (
@@ -348,11 +353,14 @@ def _prove_library_released(library):
return owners
check_owners()
entries = scan_tree(Path(library).parent)
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr']
addresses = [str(path) for path in entries if path.name.casefold() == 'saddress.adr'
and (scope_root is None or path.resolve().is_relative_to(scope_root))]
if addresses:
raise LibraryBusy(f'库中仍有数据库地址记录,不能自动解除:{addresses}')
native = [path for path in entries if path.is_file()
and (path.suffix.casefold() == '.lmc' or path.name.casefold() in ('icdb.dat', 'layoutdb.lyt'))]
native = [path for path in entries if path.is_file() and (
path.suffix.casefold() == '.lmc'
or (path.name.casefold() in ('icdb.dat', 'layoutdb.lyt')
and (scope_root is None or path.resolve().is_relative_to(scope_root))))]
if Path(library).resolve() not in native:
raise LibraryBusy('目标库身份缺失,不能解除协调阻止。')
with ExitStack() as stack:
@@ -368,7 +376,7 @@ def _prove_library_released(library):
uninitialize_com(initialized)
def release_retained_library(library, evidence_dir):
def release_retained_library(library, evidence_dir, *, block_name=None):
"""Explicit user-requested release, after fresh owner/address/access proof.
The upload sidecar is never deleted. This acknowledges process release,
@@ -398,7 +406,9 @@ def release_retained_library(library, evidence_dir):
win32con.OPEN_ALWAYS, win32con.FILE_ATTRIBUTE_NORMAL, None)
except Exception as error:
raise LibraryBusy('其他进程仍持有库锁,不能解除。') from error
with _prove_library_released(library) as proof:
proof_context = (_prove_library_released(library, block_name=block_name)
if block_name else _prove_library_released(library))
with proof_context as proof:
marker = blocker_path(library)
checkpoints = (marker, marker.with_suffix('.pending'))
if any(path.exists() and checkpoint_record(path) is None for path in checkpoints):
+23 -4
View File
@@ -13,8 +13,9 @@ import stat
from uuid import uuid4
def assert_native_idle():
def assert_native_idle(target=None):
from .owner_probe import query_owners
from .failed_session import _command_args
from .native_management import _retained_workers
from .native_export_guard import assert_retained_exports_idle
from .native_engineering_identity import _OWNER_NAMES
@@ -33,10 +34,28 @@ def assert_native_idle():
if not automation or not command or any(flag in command for flag in (
'--verify-worker', '--repair-worker', '--management-worker')):
owners.append(item)
if target is not None:
expected = os.path.normcase(os.path.abspath(str(target.project)))
scoped = []
for item in owners:
command = str(item.get('command') or '')
if not command:
scoped.append(item)
elif expected in [os.path.normcase(os.path.abspath(arg)) for arg in _command_args(command)[1:]]:
scoped.append(item)
owners = scoped
if owners:
raise ValueError(f'MAINTENANCE_OWNER_ACTIVE: 请正常关闭原生程序/操作助手:{owners}')
def _assert_native_idle_for(target):
"""Keep test/third-party zero-argument idle probes compatible."""
import inspect
if not inspect.signature(assert_native_idle).parameters:
return assert_native_idle()
return assert_native_idle(target)
def address_snapshot(paths):
from .scoped_manifest import hash_file
return {str(path.resolve()): {'sha256': hash_file(path), 'size': path.stat().st_size,
@@ -173,7 +192,7 @@ def maintenance_target_guard(request, expected=None, *, stop=None):
for p in (pcb, *maintenance_project_files(project, pcb))}}
if expected is not None and context != expected:
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 目标或地址记录在检查后变化')
assert_native_idle()
_assert_native_idle_for(target)
check()
def native_files(snapshot):
return {path for path, info in snapshot.items() if stat.S_ISREG(info.st_mode) and (
@@ -185,7 +204,7 @@ def maintenance_target_guard(request, expected=None, *, stop=None):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
assert_native_idle()
_assert_native_idle_for(target)
current = maintenance_entries(request, check=check)
if native_files(current) != files:
raise ValueError('MAINTENANCE_SOURCE_CHANGED: 检查期间库文件集合发生变化')
@@ -411,7 +430,7 @@ def run_existing_address_maintenance(request, *, diagnosed_target, startup_resul
recovery = run_native_repair(target, native_root, mentor_bin=request.mentor_bin,
timeout_seconds=max(60, request.timeout_seconds), progress=native_event,
maintenance_context=context, stop=stop)
assert_native_idle()
_assert_native_idle_for(target)
recovery = {**recovery, 'native_status': recovery.get('status'), 'validation_passed': False}
recovery['release'] = repair_release_state(request, target, recovery)
safe = recovery['release'].get('safe_to_continue') is True
+6 -1
View File
@@ -50,7 +50,12 @@ def run_reimport_recovery(requests, *, previous_evidence, evidence_dir,
stage = 'release_check'
save(stage)
if progress: progress({'stage': stage, 'detail': '正在检查原生会话释放,尚未替换条目'})
proof = release_retained_library(library, root/'release')
import inspect
block_name = requests[0].name if len(requests) == 1 else None
if 'block_name' in inspect.signature(release_retained_library).parameters:
proof = release_retained_library(library, root/'release', block_name=block_name)
else:
proof = release_retained_library(library, root/'release')
if proof.get('status') != 'RELEASE_CONFIRMED':
raise ValueError('原生会话释放未确认,未开始导入。')
save('released', release=proof)
+40 -4
View File
@@ -12,6 +12,14 @@ from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
QTabBar, QStackedWidget, QSizePolicy)
from PySide6.QtWidgets import QStyle
def _path_key(value):
"""Compare local and unavailable UNC paths without touching the network."""
raw = str(value or '')
if not raw:
return ''
return os.path.normcase(os.path.normpath(os.path.abspath(raw)))
try:
from dx_productivity.trial_task_center.ui.workers import ServiceWorker
except ImportError:
@@ -66,6 +74,8 @@ class MainWindow(QWidget):
self.management_adapter = management_adapter or NativeManagementAdapter()
self.management_capabilities = self.management_adapter.capabilities()
self._management_unsafe = False
self._management_unsafe_library = None
self._management_operation_library = None
self._maintenance_recovery_view = False
self._reload_after_maintenance = False
self._reimport_offers = ()
@@ -319,8 +329,10 @@ class MainWindow(QWidget):
if reason:
reasons.append(reason)
self.management_capability_label.setText('\n'.join(dict.fromkeys(reasons)))
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
notice = ('上次管理操作尚未确认安全释放,请检查该操作的结果。'
if self._management_unsafe else '')
if (self._management_unsafe and self._management_unsafe_library is not None
and current_library == _path_key(self._management_unsafe_library)) else '')
self.library_notice.setText(notice)
self.library_notice.setVisible(bool(notice))
for widget in (self.lmc_edit, self.browse_button, self.load_button, self.cbb_table,
@@ -362,20 +374,36 @@ class MainWindow(QWidget):
if library.is_dir():
library = select_library_file(library)
def completed(result):
self._management_unsafe = False
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text().strip())
if current_library == _path_key(library):
self._management_unsafe = False
self._management_unsafe_library = None
session = self._native_backup_session
if session is not None and session.library == library and session.process.poll() is not None:
self._release_native_backup_session(session)
message = f'原生会话释放检查通过。请审查未完成任务后重新读取中心库。\n{result["evidence_path"]}'
self.status_label.setText(message); self.output.append(message)
self._start(lambda: release_retained_library(library, self.data_root/'release-checks'), completed)
block_name = None
if len(self._batch_requests) == 1:
block_name = self._batch_requests[0].block_name
elif len(self.selected_records()) == 1:
block_name = self.selected_records()[0].name
import inspect
if 'block_name' in inspect.signature(release_retained_library).parameters:
action = lambda: release_retained_library(library, self.data_root/'release-checks',
block_name=block_name)
else:
action = lambda: release_retained_library(library, self.data_root/'release-checks')
self._start(action, completed)
def _management_block_reason(self, operation):
if self.busy:
return '当前任务尚未结束,请等待后再执行库管理操作。'
if self._native_backup_same_library():
return '该库的版本与备份窗口仍在使用,关闭后可执行写入操作。'
if self._management_unsafe:
current_library = _path_key(self.mentor_lmc_path or self.lmc_edit.text()) if self.lmc_edit.text().strip() else None
if (self._management_unsafe and self._management_unsafe_library is not None
and current_library == _path_key(self._management_unsafe_library)):
return '上次管理操作的会话尚未安全释放,请先查看异常证据并执行释放检查。'
capability = self.management_capabilities[operation]
if not capability.supported:
@@ -411,6 +439,7 @@ class MainWindow(QWidget):
self._global_icdb_run = False
self.stop.clear()
self._management_is_recovery = bool(recovery_from)
self._management_operation_library = _path_key(requests[0].library) if requests else None
self.management_dialog = ManagementDialog(requests, self, adapter=self.management_adapter,
recovery_from=recovery_from)
self._management_results = []
@@ -444,6 +473,7 @@ class MainWindow(QWidget):
if (getattr(self, '_management_is_recovery', False) and results
and all(result.safe_to_continue for result in results)):
self._management_unsafe = False
self._management_unsafe_library = None
self._maintenance_recovery_view = False
restored = {result.name for result in results if result.status == 'UPLOADED_VERIFIED'}
self._reimport_offers = tuple(offer for offer in self._reimport_offers if offer[1].name not in restored)
@@ -455,6 +485,7 @@ class MainWindow(QWidget):
self.output.append('副本恢复校验通过,版本待核对。')
if any(not result.safe_to_continue for result in results):
self._management_unsafe = True
self._management_unsafe_library = self._management_operation_library
if self.library_lease:
self.library_lease.retain_for_recovery()
self.status_label.setText('管理操作需要人工确认恢复/释放;已停止写入,未再次读取原生目录。')
@@ -541,6 +572,11 @@ class MainWindow(QWidget):
if self.busy or not self.lmc_edit.text(): return
self._maintenance_recovery_view = False
self._global_icdb_run = False
if self._management_unsafe_library is not None:
requested_library = _path_key(self.lmc_edit.text())
if requested_library != _path_key(self._management_unsafe_library):
self._management_unsafe = False
self._management_unsafe_library = None
self.icdb_progress.hide(); self.icdb_phase.hide()
self._release_library_lease()
self.loaded_path = None; self.cbb_table.setRowCount(0); self._row_by_name = {}; self.ready_names = set()
+15
View File
@@ -41,6 +41,21 @@ def test_batch_continuation_follows_actual_release(tmp_path, monkeypatch, status
if owner: owner['handle'].Close()
def test_item_failure_with_confirmed_release_does_not_stop_unrelated_items(tmp_path):
from cbb_refresh_verify.verify_runner import VerifyRequest, VerifyResult
library = tmp_path/'library.lmc'; library.touch()
requests = [VerifyRequest(library, name, tmp_path/'evidence') for name in ('A', 'B')]
calls = []
def verify(request):
calls.append(request.block_name)
return VerifyResult('FAIL' if request.block_name == 'A' else 'PASS',
stderr='单项失败但会话已释放' if request.block_name == 'A' else '',
safe_to_continue=True)
results = runner.run_batch(requests, verifier=verify)
assert calls == ['A', 'B']
assert [result.status for result in results] == ['FAIL', 'PASS']
def test_stop_worker_escalates_only_after_cooperative_deadline():
calls = []
class Worker:
+41
View File
@@ -41,6 +41,47 @@ def test_catalog_checkpoint_does_not_disable_ordinary_verify(qtbot, tmp_path, mo
assert 'ICDB' in window.cbb_table.item(window._row_by_name['Beta'], 3).text()
def test_management_release_block_is_scoped_to_the_loaded_library(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
from cbb_refresh_verify.management import Capability
adapter = type('Adapter', (), {
'capabilities': lambda self: {name: Capability(True, 'available')
for name in ('add', 'update', 'remove')}})()
window = load_window(qtbot, tmp_path, monkeypatch, management_adapter=adapter)
window._management_unsafe = True
window._management_unsafe_library = (tmp_path/'library-a.lmc').resolve()
window.lmc_edit.setText(str(tmp_path/'library-b.lmc'))
window.loaded_path = str(tmp_path/'library-b.lmc')
window.mentor_lmc_path = Path(window.loaded_path)
window.select_visible_button.click()
window._update()
assert window.add_button.isEnabled()
assert '上次管理操作' not in window._management_block_reason('update')
def test_loading_a_different_library_clears_old_management_block(qtbot, tmp_path, monkeypatch):
from test_ui_filters import load_window
window = load_window(qtbot, tmp_path, monkeypatch)
old = (tmp_path/'library-a.lmc').resolve()
window._management_unsafe = True
window._management_unsafe_library = old
window.lmc_edit.setText(str(tmp_path/'library-b.lmc'))
window.load_library()
qtbot.waitUntil(lambda: not window.busy)
assert not window._management_unsafe
assert window._management_unsafe_library is None
def test_targeted_native_idle_ignores_unrelated_native_command(tmp_path, monkeypatch):
from cbb_refresh_verify import maintenance_entry as entry
from cbb_refresh_verify.native_repair import RepairTarget
project = tmp_path/'target.prj'; project.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda names: [
{'pid': 10, 'name': 'ExpeditionPCB.exe', 'command': 'ExpeditionPCB.exe other.pcb'},
])
entry.assert_native_idle(RepairTarget(project, tmp_path/'database'))
def test_maintenance_guard_does_not_scan_other_cbb_projects(case, monkeypatch):
from cbb_refresh_verify import maintenance_entry as entry
from cbb_refresh_verify import scoped_manifest as manifests
+11
View File
@@ -134,6 +134,17 @@ def test_release_proof_checks_addresses_and_exclusive_databases(tmp_path, monkey
assert proof['exclusive_files'] == [str(library)]
def test_scoped_release_ignores_another_cbb_address(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.owner_probe as probe
monkeypatch.setattr(probe, 'query_owners', lambda *_: [])
library = tmp_path/'lib.lmc'; library.touch()
other = tmp_path/'ReusableBlocksLP/Other/Work/database/cdbsvr/sAddress.adr'
other.parent.mkdir(parents=True); other.touch()
with locks._prove_library_released(library, block_name='Target') as proof:
assert proof['addresses'] == []
def test_release_probe_timeout_does_not_clear_retained_checkpoint(tmp_path, monkeypatch):
import cbb_refresh_verify.library_lock as locks
import cbb_refresh_verify.owner_probe as probe