fix: scope release proofs and bind PCB opening consent

This commit is contained in:
阿白叔 committed 2026-11-12 16:02:53 +08:00
1 parent 42d0cebc54
commit 466f400514
33 files changed
+1358 -61

No files matched your search

+4 -3
View File
@@ -142,7 +142,7 @@ def _align_library(project, pcb, library):
ensure_project_central_library(path, library)
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None):
def recover_from_backup(request, source, *, progress=None, verifier=None, idle_check=None, version_prompt=None):
"""Validate in copies before changing Work; preserve all recovery evidence."""
import pythoncom, win32con, win32event
from .network_path import absolute_preserving_drive
@@ -241,7 +241,8 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
preflight(validation)
emit('validate_source', '正在副本中打开备份工程并执行原生校验…')
release_confirmed = False
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available)
choice_options = {'version_prompt': version_prompt} if version_prompt is not None else {}
source_result = verifier(validation, progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = source_result.safe_to_continue
record['source_validation'] = asdict(source_result)
if (source_result.status != 'PASS' or source_result.library_flag != 'GREEN'
@@ -275,7 +276,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
release_confirmed = False
final = verifier(replace(request, lmc_file=library, evidence_dir=root/'target-verify',
auto_repair=False, native_lm_verify=False, interactive_input=False),
progress=progress, flag_reader=read_library_flag_if_available)
progress=progress, flag_reader=read_library_flag_if_available, **choice_options)
release_confirmed = final.safe_to_continue
if final.status == 'PASS' and (final.library_flag != 'GREEN' or not final.safe_to_continue):
final = replace(final, status='FAIL', stderr='目标工程恢复后的 Ready 状态未确认。')
+8
View File
@@ -236,6 +236,14 @@ class DialogActionExecutor:
def perform(self, snapshot: WindowSnapshot, action: dict) -> ActionResult:
channels = tuple(action.get("channels", ()))
action_name = action.get("action")
if action_name == 'user_confirmed_pcb_open':
try:
from .pcb_open_consent import validate_action_window
if channels != ('win32_button_click',):
raise ValueError('PCB_OPEN_ACTION_CHANNEL_CHANGED')
validate_action_window(snapshot, action)
except Exception as error:
return ActionResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error))
if action_name == 'user_selected_pcb_version':
try:
from .pcb_restore_prompt import validate_action_window
+40 -2
View File
@@ -84,6 +84,19 @@ def has_retained_library(library):
def recheck_previous_release(library, evidence_dir, *, block_name=None, required=False, progress=None):
"""Historical records trigger fresh proof, never process termination or repair."""
if not required:
with _guard:
owner = _owners.get(LibraryLock(library).key)
marker = blocker_path(library)
record = checkpoint_record(marker)
if (owner and owner['thread'] == threading.get_ident() and owner['depth'] > 0
and not owner['retained'] and not marker.with_suffix('.pending').exists()
and record and record['lease_id'] == owner['lease_id']
and record['pid'] == os.getpid() and record['status'] == 'OPERATION_IN_PROGRESS'
and record.get('block_name') == owner.get('block_name')
and owner.get('block_name') in (None, block_name)
and 'export_analysis' not in record):
return None # Nested Verify belongs to this live transaction, not a past crash.
if not (required or has_blocker(library) or has_retained_library(library)):
return None
def notify(stage, **details):
@@ -362,6 +375,23 @@ def _owner_matches_scope(item, library, roots):
return False if candidates else None
def _owner_is_blocking(item, library, roots):
"""Unknown external clients need resource proof, not a global exit rule."""
scope = _owner_matches_scope(item, library, roots)
if scope is not None:
return scope
command = str(item.get('command') or '').casefold()
flags = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker')
if any(flag in command for flag in flags):
return True # An unreadable in-flight request is not proof of another library.
from .failed_session import _command_args
try:
return any(Path(arg).name.casefold() in ('close_failed_block.vbs', 'save_verified_block.vbs')
for arg in _command_args(command)[1:])
except (OSError, ValueError):
return False
def _enter_maintenance(lease):
"""Transfer only a valid known lease, after project admission under lock."""
import win32con, win32event, win32file
@@ -466,14 +496,21 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
shared_root = Path(library).resolve().parent/'SymbolLibs'
if allow_unknown_checkpoint and scope_root is not None:
raise LibraryBusy('未知检查点必须执行完整库释放证明。')
observed = []
def check_owners():
owners = []
observed.clear()
from .session_record import active_write_records
if active_write_records(library):
raise LibraryBusy('本库原生调用或助手尚未确认返回,请等待当前操作结束。')
for item in query_owners(names):
if item['pid'] == os.getpid():
continue
if not allow_unknown_checkpoint:
roots = (scope_root, shared_root) if scope_root is not None else (Path(library).parent,)
if _owner_matches_scope(item, library, roots) is False:
if not _owner_is_blocking(item, library, roots):
if _owner_matches_scope(item, library, roots) is None:
observed.append(item)
continue
automation = item['name'].casefold() in ('python.exe', 'pythonw.exe', 'cbbrefreshverify.exe')
command = item['command'].casefold()
@@ -513,7 +550,8 @@ def _prove_library_released(library, block_name=None, *, allow_unknown_checkpoin
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
owners = check_owners()
yield {'native_owners': owners, 'addresses': addresses, 'export_copies': export_copies,
yield {'native_owners': owners, 'observed_owners': list(observed),
'addresses': addresses, 'export_copies': export_copies,
'unknown_checkpoint_recovery': allow_unknown_checkpoint,
'exclusive_files': [str(path) for path in native]}
finally:
+18 -4
View File
@@ -169,7 +169,7 @@ def _may_have_mutated(record):
or any(not isinstance(item, dict) or item.get('stage') not in prewrite for item in history))
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None):
def run_management(request, *, adapter=None, verifier=None, idle_check=None, progress=None, stop=None, version_prompt=None):
from .verify_runner import VerifyRequest, run_verify
from .backup_recovery import _idle_check
import win32con, win32event
@@ -402,8 +402,10 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
# Adapter catalog cannot return until its exact native owner exits.
checkpoint('verify')
owner_safe = False
options = {'version_prompt': version_prompt} if version_prompt is not None else {}
verified = verifier(VerifyRequest(library, request.name, root/'verify',
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root), progress=progress, stop=stop)
mapped_drive=request.mapped_drive, mapped_remote_root=request.mapped_remote_root),
progress=progress, stop=stop, **options)
owner_safe = verified.safe_to_continue
checkpoint('verified', verification=asdict(verified))
good = verified.status == 'PASS' and verified.library_flag == 'GREEN' and owner_safe
@@ -427,7 +429,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
uninitialize_com(initialized)
def run_management_batch(requests, *, stop=None, progress=None, **kwargs):
def run_management_batch(requests, *, stop=None, progress=None, item_executor=None, **kwargs):
results = []
retained_libraries = set()
for request in requests:
@@ -442,7 +444,19 @@ def run_management_batch(requests, *, stop=None, progress=None, **kwargs):
if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail})
continue
result = run_management(request, progress=progress, stop=stop, **kwargs)
def action():
result = run_management(request, progress=progress, stop=stop, **kwargs)
if not result.safe_to_continue:
from .operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.library, request.name, result)
return result
from .operation_queue import QueueCancelled
try:
result = item_executor(request, action) if item_executor is not None else action()
except QueueCancelled as error:
results.append(ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', 'CANCELLED', True, str(error)))
break
results.append(result)
if progress:
progress({'stage': result.status, 'block': result.name, 'detail': result.detail,
@@ -285,9 +285,54 @@ def _database_released(project_root):
return True
def _process_birth(value):
from datetime import datetime, timezone, timedelta
if not value:
return None
if isinstance(value, datetime):
return value.astimezone(timezone.utc)
if re.fullmatch(r'\d{14}\.\d{6}[+-]\d{3}', value):
zone = timezone(timedelta(minutes=int(value[21:])))
return datetime.strptime(value[:21], '%Y%m%d%H%M%S.%f').replace(tzinfo=zone).astimezone(timezone.utc)
try:
parsed = datetime.fromisoformat(value)
if parsed.tzinfo is not None:
return parsed.astimezone(timezone.utc)
except ValueError:
pass
return value
def _export_descendants(snapshot, tracked, existing):
"""A historical parent PID is not evidence of current parentage."""
from datetime import datetime
rows = {row['pid']: row for row in snapshot}
def matches(row):
birth = _process_birth(row.get('created'))
return tracked[row['pid']] is None or birth is None or tracked[row['pid']] == birth
changed = True
while changed:
changed = False
for row in snapshot:
if row['pid'] in tracked or row['parent'] not in tracked:
continue
birth = _process_birth(row.get('created'))
if (row['pid'], birth) in existing:
continue
parent = rows.get(row['parent'])
parent_birth = tracked[row['parent']]
if parent is not None and not matches(parent):
continue
if isinstance(birth, datetime) and isinstance(parent_birth, datetime) and birth < parent_birth:
continue
tracked[row['pid']] = birth
changed = True
return [row for row in snapshot if row['pid'] in tracked and matches(row)]
def _run_exports(project, root, mentor_home, timeout_seconds):
"""Observe exact exporter/descendant handles; never kill a database owner."""
import win32api, win32con, win32event, pywintypes
import win32api, win32con, win32event, win32process, pywintypes
root = Path(root)
try:
_write_json(root/'export-launch.json', {'started': False})
@@ -338,16 +383,17 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
creationflags=subprocess.CREATE_NO_WINDOW)
record['native_started'] = True
record['pid'] = process.pid
descendants = {process.pid}
handle = getattr(process, '_handle', None)
birth = _process_birth(win32process.GetProcessTimes(handle)['CreationTime']) if handle is not None else None
descendants = {process.pid: birth}
existing = {(p['pid'], _process_birth(p.get('created'))) for p in before}
if birth is not None:
record['root_created'] = birth.isoformat()
_write_json(root/(kind+'-process.json'), record)
while time.monotonic() < deadline:
snapshot = _process_snapshot()
changed = True
while changed:
previous = len(descendants)
descendants.update(p['pid'] for p in snapshot if p['parent'] in descendants)
changed = len(descendants) != previous
owners = [p for p in snapshot if p['pid'] in descendants or (
owned = {p['pid'] for p in _export_descendants(snapshot, descendants, existing)}
owners = [p for p in snapshot if p['pid'] in owned or (
p['name'].casefold() in _OWNER_NAMES and _native_scope_match(
p.get('command', ''), roots=(project.parent,)) is True)]
for owner in owners:
@@ -359,10 +405,10 @@ def _run_exports(project, root, mentor_home, timeout_seconds):
# owners until a fresh snapshot proves it absent.
record.setdefault('process_observation_errors', {})[str(owner['pid'])] = {
'winerror': error.winerror, 'detail': str(error)}
record['observed_pids'] = sorted(descendants | handles.keys())
identities.update({owner['pid']:
{key: owner.get(key, '') for key in ('pid', 'created', 'executable')}
for owner in owners})
record['observed_pids'] = sorted(descendants.keys() | handles.keys())
for owner in owners:
identities.setdefault(owner['pid'],
{key: owner.get(key, '') for key in ('pid', 'created', 'executable')})
record['process_identities'] = list(identities.values())
if (process.poll() is not None and not owners
and all(win32event.WaitForSingleObject(h, 0) == win32con.WAIT_OBJECT_0 for h in handles.values())):
+28 -2
View File
@@ -7,6 +7,19 @@ from uuid import uuid4
from .management import _write_json
def _preexisting_export_pids(record):
from datetime import datetime
from .native_engineering_identity import _process_birth
identities = record.get('process_identities', [])
root = next((p for p in identities if p.get('pid') == record.get('pid')), {})
birth = _process_birth(record.get('root_created') or root.get('created'))
if not isinstance(birth, datetime):
return set()
return {p['pid'] for p in identities if p.get('pid') != record.get('pid')
and isinstance(_process_birth(p.get('created')), datetime)
and _process_birth(p['created']) < birth}
def assert_retained_exports_idle(library=None):
import win32con, win32event
from .native_engineering_identity import _retained_exports
@@ -17,8 +30,18 @@ def assert_retained_exports_idle(library=None):
if (library is not None and scope.get('library')
and Path(scope['library']).resolve() != Path(library).resolve()):
continue
if process.poll() is None or any(win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
for handle in handles.values()):
excluded = set()
if scope.get('analysis_root') and getattr(process, 'pid', None):
try:
for path in Path(scope['analysis_root']).glob('*-process.json'):
record = json.loads(path.read_text('utf-8'))
if record.get('pid') == process.pid:
excluded.update(_preexisting_export_pids(record))
except (OSError, ValueError, KeyError, TypeError):
excluded.clear()
if process.poll() is None or any(pid not in excluded
and win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
for pid, handle in handles.items()):
raise LibraryBusy('Native identity exporter or descendant has not released.')
@@ -119,7 +142,10 @@ def prove_export_copies_released(library, *, allow_unknown_checkpoint=False, uns
if any(not isinstance(pid, int) or pid <= 0 for pid in pids):
raise ValueError('Invalid export process identity.')
identities = {p['pid']: p for p in process.get('process_identities', [])}
excluded = _preexisting_export_pids(process)
def original_alive(pid):
if pid in excluded:
return False
recorded = identities.get(pid, {})
current = next((p for p in snapshot if p['pid'] == pid), None)
if recorded.get('created') and current and current.get('created'):
@@ -2,6 +2,52 @@
from collections.abc import Sequence
def recheck_failed_release(library, block, result):
"""Refresh resource facts after a late exit; keep the original business failure."""
if result.safe_to_continue or not result.evidence_path:
return result
from pathlib import Path
from dataclasses import replace
import json
from .session_record import read_session_record, inspect_session_record
from .library_lock import release_retained_library
evidence = Path(result.evidence_path)
try:
session = Path(getattr(result, 'session_record_path', None) or evidence.with_name('session.json'))
if session.is_file():
record = read_session_record(session, evidence_root=evidence.parent)
if record.get('block') != block or Path(record.get('library', '')).resolve() != Path(library).resolve():
return result
if inspect_session_record(session, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result
else:
record = json.loads(evidence.read_text('utf-8'))
if (record.get('name') != block or record.get('operation') not in ('add', 'update', 'remove')
or Path(record.get('library', '')).resolve() != Path(library).resolve()):
return result
bound = []
for phase in ('before', 'remove', 'after-remove', 'add', 'after-add'):
candidate = evidence.parent/phase/'session.json'
if candidate.is_file():
owned = read_session_record(candidate, evidence_root=evidence.parent)
if Path(owned.get('library', '')).resolve() != Path(library).resolve():
return result
if inspect_session_record(candidate, evidence_root=evidence.parent).get('status') == 'ACTIVE':
return result
bound.append(candidate)
if not bound:
return result # A generic timeout without a bound owner is not an exit fact.
proof = release_retained_library(library, evidence.parent/'late-release', block_name=block)
if proof.get('status') != 'RELEASE_CONFIRMED' or Path(proof.get('library', '')).resolve() != Path(library).resolve():
return result
evidence.with_name('late-release-result.json').write_text(json.dumps(dict(
business_status=result.status, safe_to_continue=True, release_proof=proof),
ensure_ascii=False, default=str, indent=2), 'utf-8')
return replace(result, safe_to_continue=True, release_proof=proof)
except Exception:
return result
def classify_save_state(markers: Sequence[str], *, helper_exited: bool | None,
native_released: bool | None, forced: bool = False) -> dict:
names = {line.strip().split('|', 1)[0] for line in markers}
+154
View File
@@ -0,0 +1,154 @@
"""Explicit user answers to the owned PCB's exact read/write question."""
from contextlib import contextmanager, ExitStack
from pathlib import Path
from threading import Lock
import time
from .post_repair_consent import exact_prompt
def _prompt_identity(snapshot):
# UIA adds chrome/reorders controls and omits Win32 caption accelerator marks.
return tuple(sorted((c.handle, c.control_id, c.class_name,
c.name.replace('&', '') if c.class_name == 'Button' else c.name)
for c in snapshot.controls if c.handle and c.handle != snapshot.hwnd))
class OpenChoice:
def __init__(self, block, library):
self.block, self.library = block, library
self.decision = None
self._lock = Lock()
def choose(self, decision):
if decision not in ('continue', 'skip', 'cancel'):
raise ValueError('无效的打开工程选择')
with self._lock:
if self.decision is None:
self.decision = decision
def validate_owner(job, target_pid, launcher_pid, worker_pid):
from .owner_probe import query_process_snapshot
from .session_record import process_identity
from .mentor_adapter import is_reusable_circuit_pcb
rows = {r['pid']: r for r in query_process_snapshot()}
target, launcher = rows.get(target_pid), rows.get(launcher_pid)
if (not target or not launcher or target['parent'] != launcher_pid or launcher['parent'] != worker_pid
or not str(job.get('desktop', '')).startswith('CbbVerify_')
or job.get('interactive_input') or job.get('native_lm_verify') or job.get('diagnostic_only')):
raise ValueError('PCB_OPEN_OWNER_UNCONFIRMED')
for row in (target, launcher):
if not is_reusable_circuit_pcb(row['executable'], row['command'], job['pcb']):
raise ValueError('PCB_OPEN_TARGET_CHANGED')
return {'target': process_identity(target_pid), 'launcher': process_identity(launcher_pid)}
@contextmanager
def resource_guard(job, allowed_pids):
import win32con, win32file
from .icdb_ownership import database_directories, unreleased_addresses
from .owner_probe import query_process_snapshot
from .library_lock import _owner_is_blocking
from .verify_runner import preflight, VerifyRequest
library = Path(job['lmc_file'])
project, pcb = preflight(VerifyRequest(library, job['block_name'], Path(job['root'])))
if project.resolve() != Path(job['project']).resolve() or pcb.resolve() != Path(job['pcb']).resolve():
raise ValueError('PCB_OPEN_PROJECT_CHANGED')
roots = (project.parent, library.parent/'SymbolLibs')
def check():
if unreleased_addresses(library, project, pcb):
raise ValueError('目标仍有数据库地址记录,暂不能确认读写打开。')
for row in query_process_snapshot():
if row['pid'] not in allowed_pids and _owner_is_blocking(row, library, roots):
raise ValueError(f'目标还有其他会话,PID={row["pid"]};未确认读写打开。')
check()
paths = [library, pcb.parent/'Layout/LayoutDB.lyt',
*(d/'icdb.dat' for d in database_directories(library, project, pcb) if (d/'icdb.dat').is_file())]
with ExitStack() as stack:
for path in dict.fromkeys(paths):
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
check()
yield
class OpenController:
def __init__(self, job):
self.job = job
self.choice = None
self.original = self.owner = None
self.sent = False
self.sent_at = 0.0
def handle(self, snapshot, snapshots, *, target_pid, launcher_pid, worker_pid, show, perform):
from .dialog_supervisor import DialogPollResult
from .management import _write_json
try:
if not exact_prompt(snapshot) or snapshot.pid != target_pid or len(snapshots) != 1:
raise ValueError('PCB_OPEN_PROMPT_CHANGED')
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
if self.choice is None:
self.owner, self.original = owner, snapshot
self.choice = OpenChoice(self.job['block_name'], self.job['lmc_file'])
show(self.choice)
if (owner != self.owner or snapshot.hwnd != self.original.hwnd
or _prompt_identity(snapshot) != _prompt_identity(self.original)):
raise ValueError('PCB_OPEN_IDENTITY_CHANGED')
if self.sent:
if time.monotonic()-self.sent_at < 2:
return DialogPollResult(observed_snapshots=tuple(snapshots))
raise ValueError('PCB_OPEN_ANSWER_NOT_COMPLETED')
if self.choice.decision is None:
return DialogPollResult(activity=True, observed_snapshots=tuple(snapshots))
control = 6 if self.choice.decision == 'continue' else 7
action = {'action': 'user_confirmed_pcb_open', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'],
'pid': target_pid, 'owner': owner, 'choice': self.choice.decision}
def send():
self.sent, self.sent_at = True, time.monotonic()
_write_json(Path(self.job['root'])/'pcb-open-user-choice.json', dict(
choice=self.choice.decision, project=self.job['project'], pcb=self.job['pcb'],
library=self.job['lmc_file'], owner=owner, snapshot=snapshot.to_record()))
return perform(snapshot, action, snapshot.phase)
if control == 6:
allowed = {target_pid, launcher_pid, worker_pid, self.job.get('supervisor_pid')}
with resource_guard(self.job, allowed):
result = send()
else:
result = send()
error = result.error_code
if not error and result.accepted_controls != (control,):
error = 'PCB_OPEN_ANSWER_FAILED'
if not error and control == 7:
error = 'PCB_OPEN_SKIPPED' if self.choice.decision == 'skip' else 'USER_CANCELLED'
return DialogPollResult(activity=True, action_sent=True, snapshot=snapshot,
error_code=error, detail=result.detail or ('用户跳过本项。' if control == 7 else ''),
accepted_controls=result.accepted_controls, channel=result.channel,
action=action['action'], observed_snapshots=tuple(snapshots))
except Exception as error:
return DialogPollResult(error_code='DATABASE_RECOVERY_REQUIRED', detail=str(error),
snapshot=snapshot, observed_snapshots=tuple(snapshots))
def validate_action_window(snapshot, action):
from dataclasses import replace
import win32gui, win32process
from .native_repair_ui import _current_desktop_name
from .dialog_models import ControlSnapshot
from .session_record import process_identity
if (not exact_prompt(snapshot) or action.get('target', {}).get('control_id') not in (6, 7)
or snapshot.pid != action.get('pid') or _current_desktop_name() != action.get('desktop')
or not str(action.get('desktop', '')).startswith('CbbVerify_')
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
or process_identity(snapshot.pid) != action.get('owner', {}).get('target')):
raise ValueError('PCB_OPEN_LIVE_OWNER_CHANGED')
children = []
win32gui.EnumChildWindows(snapshot.hwnd, lambda h, _: children.append(int(h)), None)
controls = tuple(ControlSnapshot(h, win32gui.GetDlgCtrlID(h) & 0xffff,
win32gui.GetClassName(h), win32gui.GetWindowText(h), enabled=bool(win32gui.IsWindowEnabled(h))) for h in children)
if not exact_prompt(replace(snapshot, controls=controls)) or any(
c.handle != next(x.handle for x in snapshot.controls if x.control_id == c.control_id)
for c in controls if c.class_name == 'Button'):
raise ValueError('PCB_OPEN_LIVE_PROMPT_CHANGED')
+23 -9
View File
@@ -37,10 +37,11 @@ def _choice(snapshot):
class RestoreController:
def __init__(self, job):
def __init__(self, job, *, user_open=False):
from .post_repair_consent import _validate_grant
self.job = job
self.grant = _validate_grant(job)
self.grant = None if user_open else _validate_grant(job)
self.owner = None
self.prompt = None
self.original = None
self.selection_sent = self.confirm_sent = self.failed = False
@@ -60,13 +61,20 @@ class RestoreController:
or snapshot.pid != self.original.pid
or _candidate_key(choice['candidates']) != _candidate_key(self.prompt.candidates)):
raise ValueError('PCB_VERSION_CANDIDATES_CHANGED')
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
or pre.get('worker_pid') != worker_pid or pre.get('supervisor_pid') != self.job['supervisor_pid']
or pre.get('addresses') != []
or not all(consent._same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
raise ValueError('PCB_VERSION_PRELAUNCH_PROOF_INVALID')
consent._validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
if self.grant is None:
from .pcb_open_consent import validate_owner
owner = validate_owner(self.job, target_pid, launcher_pid, worker_pid)
if self.owner is not None and owner != self.owner:
raise ValueError('PCB_VERSION_OWNER_CHANGED')
self.owner = owner
else:
pre = json.loads((Path(self.job['root'])/'post-repair-prelaunch.json').read_text(encoding='utf-8'))
if (pre.get('nonce') != self.grant['nonce'] or pre.get('desktop') != self.job['desktop']
or pre.get('worker_pid') != worker_pid or pre.get('supervisor_pid') != self.job['supervisor_pid']
or pre.get('addresses') != []
or not all(consent._same(pre[key], self.grant[key]) for key in ('project', 'pcb', 'library'))):
raise ValueError('PCB_VERSION_PRELAUNCH_PROOF_INVALID')
consent._validate_current_processes(self.job, pre, target_pid, launcher_pid, worker_pid, companion_pids)
if self.prompt is None:
self.original = snapshot
self.prompt = RestoreChoice(self.job['block_name'], self.job['lmc_file'], choice['candidates'])
@@ -91,6 +99,8 @@ class RestoreController:
action = {'action': 'user_selected_pcb_version', 'channels': ['win32_button_click'],
'target': {'control_id': control}, 'desktop': self.job['desktop'], 'pid': target_pid,
'choice': selected['kind'], 'candidates': list(self.prompt.candidates)}
if self.owner is not None:
action['owner'] = self.owner
self.selection_sent = True
self.confirm_sent = confirming
self.sent_at = time.monotonic()
@@ -119,6 +129,10 @@ def validate_action_window(snapshot, action):
import win32gui, win32process
from .native_repair_ui import _current_desktop_name
from .dialog_models import ControlSnapshot
if action.get('owner') is not None:
from .session_record import process_identity
if process_identity(snapshot.pid) != action['owner']['target']:
raise ValueError('PCB_VERSION_LIVE_PROCESS_CHANGED')
if (not str(action.get('desktop', '')).startswith('CbbVerify_')
or _current_desktop_name() != action.get('desktop') or snapshot.pid != action.get('pid')
or win32process.GetWindowThreadProcessId(snapshot.hwnd)[1] != snapshot.pid
+12 -2
View File
@@ -447,7 +447,7 @@ def inspect_residual_sessions(library, *, block_names=()):
try:
item.update(_process_identity(row))
target, detail = close_target(row['name'], windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else (
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
None, '归属未确认,仅作观察;将检查当前库实际占用。')
item.update(can_close=target is not None, detail=detail)
except Exception as identity_error:
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{identity_error}')
@@ -616,6 +616,11 @@ def _session_evidence(row):
return value
def release_targets_complete(rows):
return all(row.get('release_status') == 'RELEASED' or (
row.get('scope_confirmed') is False and row.get('release_status') == 'OBSERVED') for row in rows)
def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False):
library = Path(plan['library']).resolve()
root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12])
@@ -666,6 +671,11 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
outcome = {'release_status': 'RELEASED', 'detail': '已退出'}
if stop is not None and stop.is_set():
outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'}
elif row.get('scope_confirmed') is False:
from .library_lock import _owner_is_blocking
outcome = ({'release_status': 'WAITING', 'detail': '当前归属已变化,请重新检查确认;未关闭'}
if current is not None and _owner_is_blocking(current, library, roots) else
{'release_status': 'OBSERVED', 'detail': '仅观察,未关闭;由目标资源检查确认是否影响当前库'})
elif current is not None:
from .library_lock import _owner_matches_scope
scoped = _owner_matches_scope(current, library, roots) is True
@@ -702,7 +712,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
cancel_prompt=(_cancel_question(row['name'], windows, incomplete=error)
if row.get('force_user_confirmed') is True else None),
native_activity=native_activity(row['name'], windows, incomplete=error))
if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()):
if release_targets_complete(result['sessions']) and not (stop and stop.is_set()):
result['proof'] = _finish_library_release(library, root/'library-proof')
proof = result['proof']
if (proof.get('status') != 'RELEASE_CONFIRMED'
+6 -5
View File
@@ -449,13 +449,13 @@ def active_write_records(library):
for path in paths:
try:
session, state, processes = _session(path, path.parent)
if state.get('phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED'):
result.append({**session, 'phase': state['phase']})
else:
if processes:
from .residual_sessions import _process_handle, _handle_identity, _force_ownership
import win32con, win32event
for identity in processes:
if identity.get('role') not in ('worker', 'helper'):
if identity.get('role') == 'supervisor' or (
state.get('phase') not in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED')
and identity.get('role') not in ('worker', 'helper')):
continue
try:
with _process_handle(identity['pid']) as handle:
@@ -465,7 +465,8 @@ def active_write_records(library):
if any(actual[k] != identity[k] for k in IDENTITY_KEYS if k != 'pid'):
continue
# A retained caller may be inside Close after the last journal write failed.
result.append({**session, 'phase': 'UNCONFIRMED'})
result.append({**session, 'phase': state['phase'] if state.get('phase') in (
'NATIVE_CALL', 'CLOSING', 'UNCONFIRMED') else 'UNCONFIRMED'})
break
except Exception as error:
if getattr(error, 'winerror', None) != 87:
@@ -12,6 +12,7 @@ from .backup_notice import MANUAL_BACKUP_NOTICE
class RecoverySignals(QObject):
progress = Signal(object)
choice = Signal(object)
class BackupRecoveryDialog(QDialog):
@@ -31,6 +32,8 @@ class BackupRecoveryDialog(QDialog):
self.pool.setMaxThreadCount(1)
self.signals = RecoverySignals(self)
self.signals.progress.connect(self._progress)
if parent is not None and hasattr(parent, '_show_version_choice'):
self.signals.choice.connect(parent._show_version_choice)
self.block_combo = QComboBox()
self.block_combo.addItems(list(names))
self.source_edit = QLineEdit()
@@ -96,7 +99,8 @@ class BackupRecoveryDialog(QDialog):
self.status_label.setText('正在准备恢复…')
self.started.emit(name)
def execute():
action = lambda: recoverer(request, source, progress=self.signals.progress.emit)
options = {'version_prompt': self.signals.choice.emit} if self.recoverer is None else {}
action = lambda: recoverer(request, source, progress=self.signals.progress.emit, **options)
if self.native_queue is None: return action()
from ..operation_queue import QueueCancelled
def restore():
+5 -1
View File
@@ -73,7 +73,11 @@ class IcdbCheckTask(QObject):
if request.block_name in self.invalidated:
return VerifyResult('SKIPPED', stderr='目标已有后续管理操作,请重新检查。')
self.event.emit({'stage': 'icdb_check_start', 'block': request.block_name})
return self.verifier(request)
result = self.verifier(request)
if not result.safe_to_continue:
from ..operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result
return self.queue.run(execute, stop=self.stop,
wait_state=lambda: (self.paused, library_wait_reason(request.lmc_file)),
ready=lambda: not self.paused and library_available(request.lmc_file),
+16 -7
View File
@@ -832,10 +832,10 @@ class MainWindow(QWidget):
path = QFileDialog.getOpenFileName(self, '选择中心库', '', 'LMC (*.lmc)')[0]
if path: self.lmc_edit.setText(path); self.load_library()
def _start(self, action, callback):
def _start(self, action, callback, *, queued=True):
self.stop.clear()
self.busy = True; self._update()
self.worker = ServiceWorker(self._queued_action(action))
self.worker = ServiceWorker(self._queued_action(action) if queued else action)
self.worker.signals.succeeded.connect(callback)
self.worker.signals.failed.connect(self._failed)
self.worker.signals.finished.connect(self._finished)
@@ -1370,6 +1370,7 @@ class MainWindow(QWidget):
self.signals.event.emit({'block': req.block_name, 'stage': 'icdb_check_start'})
return verify(req)
results = run_batch(requests, verifier=verifier, stop=self.stop,
item_executor=lambda req, action: self._queued_action(action)(),
progress=lambda name, result: self.signals.event.emit({'block': name, 'stage': result.status,
'error_category': result.error_category, 'evidence': str(result.evidence_path or ''),
'detail': result.stderr or result.stdout}))
@@ -1383,9 +1384,9 @@ class MainWindow(QWidget):
self.signals.event.emit({'stage': 'report_failed', 'detail': str(error)})
affected = [req.block_name for req, result in zip(requests, results) if result.status != 'SKIPPED']
safe = all(result.safe_to_continue for result in results)
refresh = self._read_affected_records(affected) if safe else None
refresh = self._queued_action(lambda: self._read_affected_records(affected))() if safe and not self.stop.is_set() else None
return results, report, affected, refresh
self._start(action, self._batch_done)
self._start(action, self._batch_done, queued=False)
def _read_affected_records(self, names):
"""Worker-only read; never derive library state from action outcomes."""
@@ -1655,9 +1656,17 @@ class MainWindow(QWidget):
if not self.busy or self.stop.is_set():
choice.choose('cancel')
return
self.version_dialog = PcbRestoreDialog(choice, self)
self.status_label.setText(f'{choice.block}:等待选择 PCB 恢复版本。')
self.icdb_phase.setText(f'{choice.block} · 等待选择 PCB 恢复版本')
from ..pcb_open_consent import OpenChoice
from .pcb_open_dialog import PcbOpenDialog
parent = self
backup = getattr(self, 'backup_dialog', None)
if backup is not None and backup.isVisible(): parent = backup
management = getattr(self, 'management_dialog', None)
if management is not None and management.isVisible(): parent = management
self.version_dialog = (PcbOpenDialog if isinstance(choice, OpenChoice) else PcbRestoreDialog)(choice, parent)
detail = '等待读写打开确认' if isinstance(choice, OpenChoice) else '等待选择 PCB 恢复版本'
self.status_label.setText(f'{choice.block}:{detail}。')
self.icdb_phase.setText(f'{choice.block} · {detail}')
self.version_dialog.show()
def request_stop(self):
@@ -33,6 +33,7 @@ STAGE_LABELS = {
class ManagementSignals(QObject):
progress = Signal(object)
choice = Signal(object)
class ManagementDialog(QDialog):
@@ -60,6 +61,8 @@ class ManagementDialog(QDialog):
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(1)
self.signals = ManagementSignals(self)
self.signals.progress.connect(self._progress)
if parent is not None and hasattr(parent, '_show_version_choice'):
self.signals.choice.connect(parent._show_version_choice)
self.setWindowTitle({'add': '新增 CBB', 'update': '同名更新 CBB', 'remove': '移除 CBB'}[self.operation])
self.resize(850, 450)
self.table = QTableWidget(0, 4)
@@ -178,6 +181,17 @@ class ManagementDialog(QDialog):
from ..operation_queue import QueueCancelled
from ..session_record import library_available, library_wait_reason
try:
if self.runner is run_management_batch:
def item(request, action):
return self.native_queue.run(action, stop=self.stop,
ready=lambda: library_available(request.library),
wait_state=lambda: library_wait_reason(request.library),
waiting=lambda: self.signals.progress.emit({'stage': 'waiting_native_slot',
'retained': not library_available(request.library),
'detail': library_wait_reason(request.library) or '已排队,等待当前原生操作结束'}))
return self.runner(requests, adapter=self.adapter, stop=self.stop,
progress=self.signals.progress.emit, item_executor=item,
version_prompt=self.signals.choice.emit)
return self.native_queue.run(action, stop=self.stop, waiting=lambda: self.signals.progress.emit(
{'stage': 'waiting_native_slot',
'retained': not library_available(self.template.library),
@@ -0,0 +1,21 @@
from PySide6.QtWidgets import QMessageBox
class PcbOpenDialog(QMessageBox):
def __init__(self, choice, parent=None):
super().__init__(parent)
self.choice = choice
self.setWindowTitle('确认打开 PCB 工程')
self.setIcon(QMessageBox.Question)
self.setText(f'CBB:{choice.block}\n中心库:{choice.library}\n\n'
'PCB 提示上次可能未正常关闭,或工程仍被其他用户打开。\n'
'请确认没有其他用户打开此工程,再选择继续以读写权限打开。')
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
'skip' if b is self.skip_button else 'cancel'))
self.finished.connect(lambda _: choice.choose('cancel'))
@@ -7,7 +7,7 @@ from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, QPushB
QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox)
from .workers import ServiceWorker
from ..residual_sessions import force_block_reason
from ..residual_sessions import force_block_reason, release_targets_complete
class ResidualReleaseDialog(QDialog):
@@ -95,6 +95,7 @@ class ResidualReleaseDialog(QDialog):
allowed = session.get('consent_allowed')
permission = '允许' if allowed is True else '未允许' if allowed is False else '待确认'
outcome = {'RELEASED': '已释放', 'WAITING': '未释放', 'IDENTITY_CHANGED': '身份已变化',
'OBSERVED': '仅观察,未关闭',
'CANCELLED': '已停止', 'REQUESTING': '执行中', 'NOT_STARTED': '尚未执行'}.get(
session.get('release_status'), '待执行')
for column, value in enumerate((session.get('project', ''), session['name'],
@@ -162,7 +163,7 @@ class ResidualReleaseDialog(QDialog):
# Both paths were canonicalized by the worker; GUI comparison must not touch SMB.
if (proof.get('status') != 'RELEASE_CONFIRMED'
or Path(proof.get('library', '')).absolute() != self.library.absolute()
or any(r.get('release_status') != 'RELEASED' for r in result['sessions'])):
or not release_targets_complete(result['sessions'])):
return False
self.plan = None
self.runtime_label.clear()
@@ -174,7 +175,7 @@ class ResidualReleaseDialog(QDialog):
proof = result.get('proof', {})
if (self.release_finalizer is not None and proof.get('status') == 'RELEASE_CONFIRMED'
and Path(proof.get('library', '')).absolute() == self.library.absolute()
and all(row.get('release_status') == 'RELEASED' for row in result['sessions'])):
and release_targets_complete(result['sessions'])):
self.release_finalizer(proof)
return {**result, 'proof': {**proof, 'mapping_cleanup_complete': True}}
return result
@@ -203,7 +204,7 @@ class ResidualReleaseDialog(QDialog):
self.library = Path(plan['library'])
self.plan = plan
self._rows(plan['sessions'])
text = ('确认后逐项正常关闭下列会话;有未保存更改时,可选择保存或保留。'
text = ('确认后正常关闭已确认属于当前库的会话,并复查库占用;其他会话仅作观察。'
if plan['sessions'] else '未发现活跃会话。')
records = plan.get('previous_records', [])
if records:
@@ -248,7 +249,8 @@ class ResidualReleaseDialog(QDialog):
def done(result):
self.plan = {**plan, 'sessions': result['sessions']}
self._rows(result['sessions'])
count = sum(row['release_status'] == 'RELEASED' for row in result['sessions'])
count = sum(row['release_status'] == 'RELEASED' and row.get('scope_confirmed') is not False
for row in result['sessions'])
if self._accept_release_proof(result):
self.message.setText(f'已释放 {count} 个会话,旧占用记录已解除。'
+ ('\n记录保存失败:'+result['evidence_error'] if result.get('evidence_error') else ''))
+27 -6
View File
@@ -940,6 +940,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
last_activity_key = None
phase = DialogPhase.PCB_STARTING
restore_controller = None
open_controller = None
dialog_agent = None
latest_snapshots = ()
if dialog_supervisor_factory is None:
@@ -1038,6 +1039,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
dialog_result = dialog_supervisor.poll()
else:
dialog_result = dialog_supervisor.poll()
if (version_prompt is not None and consent is None and dialog_agent is not None
and not request.diagnostic_only and not request.native_lm_verify
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None):
from .pcb_open_consent import OpenController, exact_prompt
if exact_prompt(dialog_result.snapshot):
if open_controller is None:
open_controller = OpenController(job)
dialog_result = open_controller.handle(dialog_result.snapshot, dialog_result.observed_snapshots,
target_pid=target_pid, launcher_pid=launcher_pid, worker_pid=process.pid,
show=version_prompt, perform=dialog_supervisor.backend.perform)
if (consent is not None and dialog_agent is not None
and dialog_result.error_code == 'DATABASE_RECOVERY_REQUIRED'
and dialog_result.snapshot is not None and exact_prompt(dialog_result.snapshot)):
@@ -1050,11 +1062,11 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
from .dialog_rules import archive_version_choice
choice_path = archive_version_choice(dialog_result.snapshot, root)
dialog_result = replace(dialog_result, detail=dialog_result.detail + f'\n版本候选与原生窗口证据:{choice_path}')
if (version_prompt is not None and consent is not None and dialog_agent is not None
if (version_prompt is not None and not request.diagnostic_only and dialog_agent is not None
and dialog_result.snapshot.hwnd in {int(h) for h in process.desktop.EnumDesktopWindows()}):
from .pcb_restore_prompt import RestoreController
if restore_controller is None:
restore_controller = RestoreController(job)
restore_controller = RestoreController(job, user_open=consent is None)
dialog_result = restore_controller.handle(dialog_result.snapshot,
dialog_result.observed_snapshots, target_pid=target_pid, launcher_pid=launcher_pid,
worker_pid=process.pid, companion_pids=tuple(process.companion_pids),
@@ -1089,7 +1101,8 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
# recovery checks for remaining native database clients.
_stop_worker(process, timeout=40)
return finish(VerifyResult(
'FAIL',
'CANCELLED' if dialog_result.error_code == 'USER_CANCELLED' else
'SKIPPED' if dialog_result.error_code == 'PCB_OPEN_SKIPPED' else 'FAIL',
stderr=f'{dialog_result.error_code}: {dialog_result.detail}',
error_stage=phase.value,
safe_to_continue=False,
@@ -1291,7 +1304,7 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
return finish(result)
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None):
def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=None, item_executor=None):
"""Run serially and stop when database/session safety is unconfirmed."""
if max_workers != 1:
raise ValueError('Only serial Verify is supported for the shared Library Manager session')
@@ -1308,10 +1321,18 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
result = VerifyResult('SKIPPED', stderr='同库原生会话尚未释放,未启动新的写入')
else:
try:
result = verifier(request)
def execute():
result = verifier(request)
if not result.safe_to_continue:
from .operation_lifecycle import recheck_failed_release
result = recheck_failed_release(request.lmc_file, request.block_name, result)
return result
result = item_executor(request, execute) if item_executor is not None else execute()
except Exception as error:
from .operation_queue import QueueCancelled
# An unexpected exception cannot establish database safety.
result = VerifyResult('FAIL', stderr=str(error), safe_to_continue=False)
result = VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled))
results.append(result)
# Never start another writer after an unconfirmed native shutdown.
if not result.safe_to_continue: