fix: separate skipped writes and file proof from native release

This commit is contained in:
阿白叔 committed 2026-11-16 09:53:29 +08:00
1 parent fee4a67ff1
commit fa5590468d
10 files changed
+296 -63

No files matched your search

+24 -18
View File
@@ -36,34 +36,39 @@ def _idle_check(library, project, pcb, *, confirmation=None, evidence=None, bloc
directories = database_directories(library, project, pcb)
scope = (Path(project).parent, *directories)
def owners():
unknown=[]
names=('ExpeditionPCB.exe','LibraryManager.exe','viewdraw.exe','iCDBProjectBackup.exe','ReuseBlockImporter.exe')
unknown = []
names = ('ExpeditionPCB.exe', 'LibraryManager.exe', 'viewdraw.exe',
'iCDBProjectBackup.exe', 'ReuseBlockImporter.exe')
for row in query_owners(names):
match=_native_scope_match(row['command'],roots=scope,files=(library,project,pcb))
match = _native_scope_match(row['command'], roots=scope, files=(library, project, pcb))
if match is True:
raise ValueError(f'TARGET_NATIVE_OWNER_ACTIVE: 目标工程或共享库有原生会话,PID={row["pid"]}')
if match is None:unknown.append(row)
if match is None:
unknown.append(row)
return unknown
def resources():
addresses=unreleased_addresses(library,project,pcb)
addresses = unreleased_addresses(library, project, pcb)
if addresses:
raise ValueError(f'TARGET_DATABASE_ADDRESS_UNCONFIRMED: 地址记录需原生确认;未据此判定正在占用:{addresses}')
with ExitStack() as stack:
paths=[Path(library),Path(pcb).parent/'Layout/LayoutDB.lyt',
*(directory/'icdb.dat' for directory in directories)]
paths = [Path(library), Path(pcb).parent/'Layout/LayoutDB.lyt',
*(directory/'icdb.dat' for directory in directories)]
for path in dict.fromkeys(paths):
if path.is_file():
handle=win32file.CreateFile(str(path),win32con.GENERIC_READ,0,None,
win32con.OPEN_EXISTING,0,None)
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, 0, None)
stack.callback(handle.Close)
unknown=owners()
unknown = owners()
resources() # Never hold exclusive probe handles while waiting for a user.
if unknown:
if confirmation is None:
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 原生程序的工程归属未知,写入前需要确认。')
confirmation.confirm(library,unknown,evidence=evidence,block=block)
unknown=owners()
if unknown and (confirmation is None or not confirmation.confirmed(library,unknown)):
if not unknown:
return
if confirmation is None:
from .write_admission import WriteAdmissionDeclined
raise WriteAdmissionDeclined('skip',
'TARGET_NATIVE_OWNER_UNCONFIRMED: 原生程序的工程归属未知,未执行;写入前需要确认。')
confirmation.confirm(library, unknown, evidence=evidence, block=block)
unknown = owners()
if unknown and not confirmation.confirmed(library, unknown):
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 占用确认后出现新的未知进程,请重新检查。')
resources()
@@ -302,8 +307,9 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
return save(final)
except Exception as error:
from .write_admission import WriteAdmissionDeclined
if isinstance(error,WriteAdmissionDeclined) and error.decision=='cancel' and not installed:
return save(VerifyResult('CANCELLED',stderr=str(error),safe_to_continue=release_confirmed))
if isinstance(error, WriteAdmissionDeclined) and not installed:
status = 'CANCELLED' if error.decision == 'cancel' else 'SKIPPED'
return save(VerifyResult(status, stderr=str(error), safe_to_continue=release_confirmed))
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
safe_to_continue=release_confirmed))
finally:
@@ -252,6 +252,7 @@ def capture_registration_identity(source, evidence_root, *, expected_library):
_write_json(root/'identity.json', {'identity': identity, 'safe_to_continue': True})
return IdentityOutcome(identity, True, 'Engineering files and project references checked; no native export.', root)
except Exception as error:
# No native session was acquired; the caller retains its own release proof.
return IdentityOutcome(None, True, str(error), root)
+1 -1
View File
@@ -405,7 +405,7 @@ class NativeManagementAdapter:
return NativeOutcome(True, owner_safe, 'Aligned target did not reopen with the exact catalog identity.',
identity_matches=False, evidence_path=evidence)
proof = capture_registration_identity(target, evidence/'registered-identity', expected_library=request.library)
owner_safe = proof.safe_to_continue
# File-only content evidence cannot change the catalog owner's exit proof.
expected, registered = prepared['expected_identity'], proof.identity
# Native Add rewrites PRJ metadata and runtime history. Registration
# identity uses the top block and Layout; other file diffs are evidence.
+2 -1
View File
@@ -116,7 +116,8 @@ class OpenController:
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
with resource_guard(self.job, allowed):
pass
# Mentor must acquire these files itself when it receives Yes.
# Deliberate TOCTOU tradeoff: release probes before Yes so Mentor
# can acquire the files without a sharing violation; recheck identity.
if validate_owner(self.job, target_pid, launcher_pid, worker_pid) != owner:
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
result = send()
@@ -134,6 +134,9 @@ class BackupRecoveryDialog(QDialog):
def _result(self, name, result):
if result.status == 'PASS':
message = '恢复完成,工程打开与校验通过。'
elif result.status in ('SKIPPED', 'CANCELLED'):
label = '恢复已跳过' if result.status == 'SKIPPED' else '恢复已取消'
message = f'{label}:{result.stderr or result.stdout or result.status}'
else:
message = f'恢复未通过:{result.stderr or result.stdout or result.status}'
if result.evidence_path:
@@ -2,21 +2,22 @@ from PySide6.QtWidgets import QMessageBox
class WriteOwnerDialog(QMessageBox):
def __init__(self,choice,parent=None):
def __init__(self, choice, parent=None):
super().__init__(parent)
self.choice=choice
self.choice = choice
self.setWindowTitle('确认中心库未被占用')
self.setIcon(QMessageBox.Question)
owners='\n'.join(f'{row["name"]} · PID {row["pid"]}' for row in choice.owners)
owners = '\n'.join(f'{row["name"]} · PID {row["pid"]}' for row in choice.owners)
self.setText(f'中心库:{choice.library}\n当前 CBB:{choice.block}\n\n'
f'无法确认下列程序是否打开了此库:\n{owners}\n\n'
'请确认这些程序在本批次完成前都不使用此库,再继续。')
self.setDetailedText('\n'.join(f'PID {row["pid"]}:{row["image"]}' for row in choice.owners))
self.continue_button=self.addButton('已确认未使用此库,继续',QMessageBox.ActionRole)
self.skip_button=self.addButton('跳过本项',QMessageBox.ActionRole)
self.cancel_button=self.addButton('取消本批次',QMessageBox.RejectRole)
self.setDefaultButton(self.cancel_button);self.setEscapeButton(self.cancel_button)
self.continue_button = self.addButton('已确认未使用此库,继续', QMessageBox.ActionRole)
self.skip_button = self.addButton('跳过本项', QMessageBox.ActionRole)
self.cancel_button = self.addButton('取消本批次', QMessageBox.RejectRole)
self.setDefaultButton(self.cancel_button)
self.setEscapeButton(self.cancel_button)
self.setModal(True)
self.buttonClicked.connect(lambda b:choice.choose('continue' if b is self.continue_button else
self.buttonClicked.connect(lambda b: choice.choose('continue' if b is self.continue_button else
'skip' if b is self.skip_button else 'cancel'))
self.finished.connect(lambda _:choice.choose('cancel'))
self.finished.connect(lambda _: choice.choose('cancel'))
+41 -33
View File
@@ -10,60 +10,68 @@ from .session_record import process_identity
class WriteOwnerChoice(OpenChoice):
def __init__(self, block, library, owners):
super().__init__(block, library)
self.owners=tuple(dict(row) for row in owners)
self.owners = tuple(dict(row) for row in owners)
class WriteAdmissionDeclined(ValueError):
def __init__(self, decision):
self.decision=decision
super().__init__('已取消本批次,未提交后续写入。' if decision=='cancel' else '用户跳过本项,未确认未知程序与目标库无关。')
def __init__(self, decision, detail=None):
self.decision = decision
super().__init__(detail or ('已取消本批次,未提交后续写入。' if decision == 'cancel' else
'用户跳过本项,未确认未知程序与目标库无关。'))
class WriteAdmission:
def __init__(self, *, prompt=None, stop=None):
self.prompt,self.stop=prompt,stop
self._grants={}
self.prompt, self.stop = prompt, stop
self._grants = {}
def _identities(self, owners):
rows=[]
rows = []
for row in owners:
try:identity=process_identity(row['pid'])
try:
identity = process_identity(row['pid'])
except Exception as error:
if getattr(error,'winerror',None)==87:continue
if getattr(error, 'winerror', None) == 87:
continue
raise
if Path(identity['image']).name.casefold()!=row['name'].casefold():
if Path(identity['image']).name.casefold() != row['name'].casefold():
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: PID 已被其他程序复用,请重新检查。')
if row.get('executable') and Path(row['executable']).resolve()!=Path(identity['image']).resolve():
if row.get('executable') and Path(row['executable']).resolve() != Path(identity['image']).resolve():
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 原生程序身份已变化,请重新检查。')
rows.append({**identity,'name':row['name']})
return tuple(sorted((row['pid'],row['created_handle'],row['image'],row['owner_sid'],row['session_id'])
for row in rows)),rows
rows.append({**identity, 'name': row['name']})
return tuple(sorted((row['pid'], row['created_handle'], row['image'], row['owner_sid'], row['session_id'])
for row in rows)), rows
def confirmed(self, library, owners):
key=str(Path(library).resolve()).casefold()
identities,_=self._identities(owners)
return set(identities).issubset(self._grants.get(key,set()))
key = str(Path(library).resolve()).casefold()
identities, _ = self._identities(owners)
return set(identities).issubset(self._grants.get(key, set()))
def confirm(self, library, owners, *, evidence, block):
key=str(Path(library).resolve()).casefold()
identities,rows=self._identities(owners)
if set(identities).issubset(self._grants.get(key,set())):return
key = str(Path(library).resolve()).casefold()
identities, rows = self._identities(owners)
if set(identities).issubset(self._grants.get(key, set())):
return
if self.prompt is None:
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 无法确认原生程序是否使用目标库,请通过界面核对后选择。')
choice=WriteOwnerChoice(block,str(Path(library)),rows)
raise WriteAdmissionDeclined('skip',
'TARGET_NATIVE_OWNER_UNCONFIRMED: 无法确认原生程序是否使用目标库,未执行;请通过界面核对后选择。')
choice = WriteOwnerChoice(block, str(Path(library)), rows)
self.prompt(choice)
while choice.decision is None and not (self.stop is not None and self.stop.is_set()):time.sleep(.05)
decision=choice.decision or 'cancel'
if decision!='continue':
if decision=='cancel' and self.stop is not None:self.stop.set()
while choice.decision is None and not (self.stop is not None and self.stop.is_set()):
time.sleep(.05)
decision = choice.decision or 'cancel'
if decision != 'continue':
if decision == 'cancel' and self.stop is not None:
self.stop.set()
raise WriteAdmissionDeclined(decision)
current,_=self._identities(owners)
current, _ = self._identities(owners)
if not set(current).issubset(identities):
raise ValueError('TARGET_NATIVE_OWNER_UNCONFIRMED: 确认期间进程身份已变化,请重新检查。')
from .management import _write_json
root=Path(evidence);root.mkdir(parents=True,exist_ok=True)
_write_json(root/('write-owner-consent-'+uuid4().hex+'.json'),dict(
intent='user_confirmed_unknown_clients_do_not_use_target_library',library=str(Path(library).resolve()),
block=block,scope='current_batch_library',owners=rows,choice='continue',
proves_native_ownership=False,requires_fresh_resource_checks=True))
self._grants.setdefault(key,set()).update(current)
root = Path(evidence)
root.mkdir(parents=True, exist_ok=True)
_write_json(root/('write-owner-consent-'+uuid4().hex+'.json'), dict(
intent='user_confirmed_unknown_clients_do_not_use_target_library', library=str(Path(library).resolve()),
block=block, scope='current_batch_library', owners=rows, choice='continue',
proves_native_ownership=False, requires_fresh_resource_checks=True))
self._grants.setdefault(key, set()).update(current)