fix: handle shared database proof and stale generated cell libraries

This commit is contained in:
阿白叔 committed 2026-11-23 18:33:41 +08:00
1 parent 4fb978ee21
commit 8e0f78979a
8 files changed
+378 -5

No files matched your search

+5
View File
@@ -77,10 +77,15 @@ def _snapshot(library, roots):
raise ValueError('目标库身份缺失')
addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr')
targets, signatures = [], {}
from .icdb_ownership import shared_symbol_database
shared = shared_symbol_database(library)
for address in addresses:
data = address.read_bytes()
signatures[str(address)] = hashlib.sha256(data).hexdigest()
database = address.parent.parent
if address == shared/'cdbsvr/sAddress.adr' and shared/'icdb.dat' in native:
targets.append({'scope': 'shared_symbols', 'database': str(shared), 'address': str(address)})
continue
matches = []
for project in database.parent.glob('*.prj'):
if project not in entries or project.stat().st_size > 1024*1024:
+9 -2
View File
@@ -8,18 +8,22 @@ def session_resource_scope(job):
project, pcb = job.get('project'), job.get('pcb')
projects = [str(Path(project))] if project else []
databases = [str(Path(p).parent/'database') for p in (project, pcb) if p]
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
shared = shared_symbol_database(library)
return {'scope_state': 'DECLARED' if project else 'RECHECK_REQUIRED',
'library': str(library), 'operation_id': job.get('operation_id'),
'block_name': job.get('block'), 'projects': projects,
'databases': list(dict.fromkeys(databases)), 'shared_dependencies': [str(shared)]}
def shared_symbol_database(library):
return Path(library).parent/'SymbolLibs/__ReusableBlocksSymb'
def database_directories(lmc_file, project, pcb):
return tuple(dict.fromkeys((
Path(project).parent/'database',
Path(pcb).parent/'database',
Path(lmc_file).parent/'SymbolLibs/__ReusableBlocksSymb',
shared_symbol_database(lmc_file),
)))
@@ -37,6 +41,9 @@ def inspect_release_addresses(snapshot, *, stop=None):
from .library_lock import LibraryBusy
results = []
for item in snapshot['inspection_targets']:
if item.get('scope') == 'shared_symbols':
raise LibraryBusy('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'
+ item['address'])
target = RepairTarget(Path(item['project']), Path(item['database']))
root = Path(tempfile.mkdtemp(prefix='cbb-release-inspection-'))
result = run_native_repair(target, root, inspection_only=True, stop=stop)
@@ -0,0 +1,171 @@
"""Preserve one generated PCB Cell Library after a bound integration failure."""
from contextlib import contextmanager, ExitStack
import hashlib
import json
import os
from pathlib import Path
import re
import stat
def _cache_paths(pcb):
cache = Path(pcb).parent/'Work/Layout_Temp'
return cache, cache/'JobPrefsDB.jpf'
def _cache_identity(cache):
metadata = cache.lstat()
if not stat.S_ISDIR(metadata.st_mode) or metadata.st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError('本地 Cell Library 不是普通目录')
if cache.resolve(strict=True) != cache:
raise ValueError('本地 Cell Library 路径含链接')
return {'device': metadata.st_dev, 'file_id': metadata.st_ino,
'created_ns': metadata.st_ctime_ns}
def _digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def capture_binding_change(job, config, emit):
"""Keep the exact changed pcb.prj and the pre-launch generated directory identity."""
from .management import _write_json
cache, preferences = _cache_paths(job['pcb'])
if not preferences.is_file():
return
try:
record = {key: str(job[key]) for key in ('operation_id', 'project', 'pcb', 'lmc_file', 'block_name')}
record.update(config=str(config), config_sha256=_digest(config), original_cache=_cache_identity(cache))
_write_json(Path(job['root'])/'local-cell-library-binding.json', record)
except (OSError, ValueError, KeyError) as error:
emit(stage='local_cell_library_binding_unavailable', detail=str(error))
def _explicit_cache_error(text, preferences):
native = str(text).replace('/', '\\').casefold()
path = str(preferences).replace('/', '\\').casefold()
return ('could not load job preferences db' in native and 'unable to create local cell library' in native
and re.search(re.escape(path) + r'(?![\w.\\/])', native) is not None)
@contextmanager
def _hold_primary_files(proof, cache, required):
"""Keep the proven databases protected while moving the generated directory."""
import win32con
import win32file
paths = {Path(p) for p in proof['exclusive_files'] if not Path(p).is_relative_to(cache)}
if not required <= paths:
raise ValueError('缺少主要工程文件占用证明')
with ExitStack() as stack:
for path in sorted(paths):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
for name, digest in proof['signatures'].items():
path = Path(name)
if not path.is_relative_to(cache):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, win32con.FILE_SHARE_READ, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
if _digest(path) != digest:
raise ValueError('会话地址或工程绑定已变化')
yield
def preserve_failed_cache(request, result, *, stop=None):
"""After clean exit, preserve generated files and return one retry's receipt."""
if not result.safe_to_continue or not result.evidence_path or (stop is not None and stop.is_set()):
return None
import pywintypes
from .backup_recovery import _project_text
from .library_lock import _prove_library_released
from .management import _write_json
from .mentor_adapter import _CENTRAL_LIBRARY_KEY
from .operation_queue import QueueCancelled, check_active, local_commit
from .scoped_manifest import scan_tree
from .verify_runner import preflight
root = Path(result.evidence_path).parent
receipt_path = root/'local-cell-library-retry.json'
binding_path = root/'local-cell-library-binding.json'
if not binding_path.is_file() or receipt_path.exists():
return None
try:
job = json.loads((root/'request.json').read_text(encoding='utf-8'))
binding = json.loads(binding_path.read_text(encoding='utf-8'))
project, pcb = preflight(request)
if (binding.get('operation_id') != job.get('operation_id') or not job.get('operation_id')
or binding.get('block_name') != request.block_name
or any(not binding.get(key) or Path(binding[key]).resolve() != Path(path).resolve()
for key, path in [('lmc_file', request.lmc_file), ('project', project), ('pcb', pcb)])):
return None
cache, preferences = _cache_paths(pcb)
config = pcb.with_name('pcb.prj')
if not _explicit_cache_error(result.stderr, preferences):
return None
events = [json.loads(line) for line in (root/'events.jsonl').read_text(encoding='utf-8').splitlines()]
stages = {event.get('stage') for event in events}
identity_bound = any(event.get('stage') == 'identity_verified'
and Path(event.get('project') or '.').resolve() == project.resolve()
and Path(event.get('document') or '.').name.casefold() == pcb.name.casefold()
for event in events)
if (not identity_bound
or not any(event.get('stage') == 'central_library_path' and event.get('status') == 'UPDATED'
and Path(event.get('path') or '.').resolve() == config.resolve()
and Path(event.get('target') or '.').resolve() == Path(request.lmc_file).resolve()
for event in events)
or stages.intersection({'save_start', 'save_helper', 'save_progress', 'saved_and_closed'})
or (root/'save.log').exists()
or not any(event.get('stage') == 'integration_error'
and _explicit_cache_error(event.get('detail'), preferences) for event in events)):
return None
def validate_binding():
if (config.resolve(strict=True) != config or config != Path(binding['config'])
or _digest(config) != binding['config_sha256'] or _cache_identity(cache) != binding['original_cache']):
raise ValueError('PCB 项目绑定或生成目录身份已变化')
references = _CENTRAL_LIBRARY_KEY.findall(_project_text(config))
if not references or any((config.parent/target).resolve() != Path(request.lmc_file).resolve()
for _, target, _ in references):
raise ValueError('PCB 项目未绑定当前中心库')
members = scan_tree(cache, check=check_active)
if not all(path in members and stat.S_ISREG(members[path].st_mode)
for path in (preferences, cache/'CellDB.cel')):
raise ValueError('未确认 Mentor 生成的本地 Cell Library 文件')
validate_binding()
with _prove_library_released(request.lmc_file, block_name=request.block_name, stop=stop) as proof:
if proof.get('data_recovery_required') is True or proof.get('blocked_resources'):
raise ValueError('数据库资源仍待确认')
# Windows cannot rename this directory while an exclusive handle to
# its generated LayoutDB is held. The current library lease stays held.
validate_binding()
preserved = project.parent.parent/('Layout_Temp.before-rebuild-' + root.name)
if os.path.lexists(preserved):
return None
receipt = {'kind': 'LOCAL_CELL_LIBRARY_RETRY', 'status': 'PRESERVE_REQUESTED',
'original_operation_id': binding['operation_id'],
'initial_evidence': str(result.evidence_path), 'cache': str(cache),
'preserved_name': preserved.name, 'preserved_path': str(preserved)}
_write_json(receipt_path, receipt)
required = {Path(request.lmc_file).resolve(), (pcb.parent/'Layout/LayoutDB.lyt').resolve()}
with _hold_primary_files(proof, cache, required), local_commit():
if stop is not None and stop.is_set():
return None
validate_binding()
cache.rename(preserved)
receipt['status'] = 'PRESERVED'
_write_json(receipt_path, receipt)
return receipt
except QueueCancelled:
raise
except (OSError, ValueError, KeyError, TypeError, RuntimeError, pywintypes.error) as error:
try:
_write_json(root/'local-cell-library-retry-unavailable.json', {
'initial_evidence': str(result.evidence_path), 'detail': str(error)})
except OSError:
pass
return None
+4 -1
View File
@@ -709,8 +709,11 @@ def execute_job(job, emit):
else:
from .maintenance_entry import maintenance_project_files
for index, config in enumerate(maintenance_project_files(job['project'], job['pcb'])):
ensure_project_central_library(config, job['lmc_file'],
changed = ensure_project_central_library(config, job['lmc_file'],
evidence_dir=Path(root)/'diagnostics'/f'project-{index}', emit=emit)
if changed and prewrite_eligible and config == Path(job['pcb']).with_name('pcb.prj'):
from .local_cell_library import capture_binding_change
capture_binding_change(job, config, emit)
if prewrite_eligible:
from .diagnostic_open import snapshot_diagnostic_logs
from .session_record import process_identity
+18 -1
View File
@@ -52,6 +52,7 @@ def validate_owner(job, target_pid, launcher_pid, worker_pid):
def resource_guard(job, allowed_pids, *, require_complete_proof=False):
import hashlib
from .file_probe import hold_release_files
from .icdb_ownership import shared_symbol_database
from .maintenance_entry import maintenance_project_files
from .native_repair import RepairTarget, run_native_repair
from .native_occupancy import confirmed_inspection
@@ -99,7 +100,7 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
if not database.is_relative_to(project.parent.resolve()):
raise ValueError(f'PCB_OPEN_DATABASE_UNCONFIRMED: iCDBDir 越出工程:{database}')
required_files.add(database/'icdb.dat')
shared = library.parent/'SymbolLibs/__ReusableBlocksSymb'
shared = shared_symbol_database(library)
if shared.exists():
required_files.add((shared/'icdb.dat').resolve())
missing = required_files - {Path(path).resolve() for path in files['exclusive_files']}
@@ -109,6 +110,22 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
if files['addresses']:
targets = files['inspection_targets']
for item in targets:
if item.get('scope') == 'shared_symbols':
address = Path(item['address'])
shared = shared_symbol_database(library).resolve()
if (Path(item['database']).resolve() != shared
or address.resolve() != shared/'cdbsvr/sAddress.adr'
or str(address) not in files['binding_files']
or shared/'icdb.dat' not in {Path(p).resolve() for p in files['exclusive_files']}):
raise ValueError(f'SHARED_ICDB_BINDING_UNCONFIRMED: {address}')
_write_json(Path(job['root'])/'pcb-open-resource-denied.json', {
'status': 'SHARED_ICDB_INSPECTION_UNAVAILABLE',
'operation_id': job.get('operation_id'), 'library': str(library),
'database': str(shared), 'address': str(address),
'address_sha256': files['signatures'][str(address)],
'exclusive_file_observed': True,
})
raise ValueError('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'+str(address))
if Path(item['project']).resolve() not in {p.resolve() for p in configs}:
raise ValueError(f"PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置:{item['database']}")
stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
+27 -1
View File
@@ -673,8 +673,34 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
local_retry = None
if (library_lock is not None and result.error_category == 'MENTOR_LOCAL_CELL_LIBRARY'
and not request.diagnostic_only and not request.auto_repair and not request.native_lm_verify
and not request.interactive_input and request.post_repair_proof is None):
from .local_cell_library import preserve_failed_cache
release_confirmed = result.safe_to_continue
local_retry = preserve_failed_cache(request, result, stop=stop)
if local_retry is not None:
initial_seconds = result.timings_seconds.get('total', 0.0)
original_evidence = result.evidence_path
_notify_progress(progress, {'stage': 'local_cell_library_retry', 'block': request.block_name,
'detail': '已保留旧本地 Cell Library,重新打开一次让 Mentor 重建。'})
check_active()
release_confirmed = False
result = _run_verify_serialized(request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
local_retry.update(status='REBUILT_AND_VERIFIED' if result.status == 'PASS' else 'REVERIFY_FAILED',
retry_evidence=str(result.evidence_path or ''))
_write_optional_evidence(original_evidence.with_name('local-cell-library-retry.json'), local_retry)
retry_seconds = result.timings_seconds.get('total', 0.0)
result = replace(result, recovery_attempts=(*result.recovery_attempts, local_retry),
timings_seconds={**result.timings_seconds, 'initial_verify': initial_seconds,
'local_cell_library_retry': retry_seconds, 'total': initial_seconds + retry_seconds})
if result.evidence_path:
_write_optional_evidence(result.evidence_path, {'block_name': request.block_name, **asdict(result)})
facts = result.write_outcome or {}
if (not request.diagnostic_only and not request.auto_repair and request.post_repair_proof is None
if (local_retry is None and not request.diagnostic_only and not request.auto_repair and request.post_repair_proof is None
and result.status == 'FAIL' and result.safe_to_continue and result.evidence_path
and result.library_flag == 'NOT_GREEN' and result.error_stage == 'library_flag'
and result.error_category == 'MENTOR_VERIFY_NOT_COMMITTED'