fix: reconcile native save release and resume affected CBB batches
This commit is contained in:
1 parent
443668aa4b
commit
c76b755f13
16 files changed
+655
-36
No files matched your search
@@ -101,7 +101,10 @@ def _native_scope_match(command, *, roots=(), files=()):
|
||||
|
||||
|
||||
def _project_text(path):
|
||||
data = path.read_bytes()
|
||||
return _decode_project_text(path.read_bytes())
|
||||
|
||||
|
||||
def _decode_project_text(data):
|
||||
if data.startswith((b'\xff\xfe', b'\xfe\xff')):
|
||||
return data.decode('utf-16')
|
||||
try:
|
||||
|
||||
@@ -299,6 +299,10 @@ def launch_save_helper(command, *, start_gate=None, identity_path=None, operatio
|
||||
return helper
|
||||
|
||||
|
||||
def supervisor_has_exited():
|
||||
return _supervisor_lost.is_set()
|
||||
|
||||
|
||||
def start_supervisor_watchdog(supervisor_pid, *, cancel_path=None, stop_clients=False,
|
||||
session_record_path=None, operation_id=None, supervisor_identity=None):
|
||||
"""Record stop intent; a watchdog cannot interrupt an in-flight COM call.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
from contextlib import contextmanager, ExitStack
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from pathlib import Path, PureWindowsPath
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
@@ -13,13 +13,14 @@ from uuid import uuid4
|
||||
|
||||
|
||||
@contextmanager
|
||||
def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
|
||||
def hold_release_files(library, roots=None, *, saved_project=None, timeout_seconds=10, stop=None):
|
||||
"""Only this pure probe may be terminated. stdin EOF releases its handles."""
|
||||
with tempfile.TemporaryDirectory(prefix='cbb-file-probe-') as folder:
|
||||
job = Path(folder)/'request.json'
|
||||
token = uuid4().hex
|
||||
job.write_text(json.dumps({'token': token, 'library': str(library),
|
||||
'roots': [str(p) for p in roots] if roots is not None else None}), 'utf-8')
|
||||
'roots': [str(p) for p in roots] if roots is not None else None,
|
||||
'saved_project': [str(p) for p in saved_project] if saved_project is not None else None}), 'utf-8')
|
||||
command = ([sys.executable] if getattr(sys, 'frozen', False) else
|
||||
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--file-probe', str(job)]
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL,
|
||||
@@ -27,17 +28,23 @@ def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
|
||||
try:
|
||||
deadline = time.monotonic()+max(.1, min(10, timeout_seconds))
|
||||
result_path = job.with_name('result.json')
|
||||
while not result_path.exists():
|
||||
while True:
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('FILE_PROBE_CANCELLED')
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError('FILE_PROBE_TIMEOUT: 文件占用检查超时,未证明释放')
|
||||
if process.poll() is not None:
|
||||
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据')
|
||||
try:
|
||||
record = json.loads(result_path.read_text('utf-8'))
|
||||
break
|
||||
except FileNotFoundError:
|
||||
if process.poll() is not None and not result_path.exists():
|
||||
raise OSError('FILE_PROBE_UNCONFIRMED: 文件探测未返回证据') from None
|
||||
except PermissionError:
|
||||
# Windows may temporarily share-lock a newly published receipt.
|
||||
pass
|
||||
time.sleep(.02)
|
||||
if stop is not None and stop.is_set():
|
||||
raise InterruptedError('FILE_PROBE_CANCELLED')
|
||||
record = json.loads(result_path.read_text('utf-8'))
|
||||
if record.get('token') != token or record.get('status') != 'HELD' or process.poll() is not None:
|
||||
error = OSError('FILE_PROBE_UNCONFIRMED: '+str(record.get('error', '探测身份或句柄失效')))
|
||||
error.winerror = record.get('winerror')
|
||||
@@ -65,6 +72,50 @@ def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
|
||||
process.wait(3)
|
||||
|
||||
|
||||
def _shared_server_shutdown(address, data, database, entries):
|
||||
"""Bind the retained advertisement to the exact native server shutdown."""
|
||||
lines = data.decode('ascii', errors='replace').splitlines()
|
||||
if len(lines) < 6 or lines[-1] != '.' or not re.fullmatch(r'(?:[0-9a-f]{4}-){11}[0-9a-f]{4}', lines[0], re.I):
|
||||
return None
|
||||
guid = lines[0]
|
||||
session = re.fullmatch(r'(\d{4}-\d{2}-\d{2}) \d{2}\.\d{2}\.\d{2}-([1-9]\d{0,9})', lines[-2])
|
||||
if session is None:
|
||||
return None
|
||||
log = address.parent/'log'/session[0]/(session[1].replace('-', '.')+'.txt')
|
||||
if (log not in entries or not stat.S_ISREG(entries[log].st_mode)
|
||||
or max(entries[database].st_mtime_ns, entries[address].st_mtime_ns) > entries[log].st_mtime_ns):
|
||||
return None
|
||||
with log.open('rb') as stream:
|
||||
raw = stream.read(2*1024*1024+1)
|
||||
if len(raw) > 2*1024*1024:
|
||||
return None
|
||||
|
||||
from .icdb_recovery import decode_log
|
||||
messages = re.findall(r'^\[[^\r\n]+\] \[[^\r\n]+\] \[\d+\] ([^\r\n]*)', decode_log(raw), re.M)
|
||||
if not messages or messages[-1] != 'S: STOP' or messages.count('S: STOP') != 1:
|
||||
return None
|
||||
close_prefix = f'Single file [{database}] closed with size ['.casefold()
|
||||
last_close = next((message for message in reversed(messages)
|
||||
if message.casefold().startswith(close_prefix)), '')
|
||||
if not last_close.casefold().startswith(close_prefix + f'{entries[database].st_size} ('):
|
||||
return None
|
||||
ordered = (
|
||||
lambda line: line.startswith('iCDB Server ver.'),
|
||||
lambda line: line.startswith('Machine [') and line.endswith(f' PID [{session[2]}]'),
|
||||
lambda line: line.casefold().startswith(f'S: Project path [{database.parent}] on file system ['.casefold()),
|
||||
lambda line: line == f'S: Server GUID [{guid}]',
|
||||
lambda line: line == 'S: Wrote data to server address file',
|
||||
lambda line: line == 'iCDB Server PI: Database closed',
|
||||
lambda line: line == last_close,
|
||||
lambda line: line.casefold() == f'AT: ERROR: Could not remove server address file [{address}]'.casefold(),
|
||||
)
|
||||
remaining = iter(messages[:-1])
|
||||
if not all(any(matches(message) for message in remaining) for matches in ordered):
|
||||
return None
|
||||
return {'server_guid': guid, 'server_pid': int(session[2]), 'database': str(database.parent),
|
||||
'log': str(log), 'log_sha256': hashlib.sha256(raw).hexdigest()}
|
||||
|
||||
|
||||
def _snapshot(library, roots):
|
||||
from .scoped_manifest import scan_tree
|
||||
entries = {library: library.lstat()}
|
||||
@@ -76,7 +127,7 @@ def _snapshot(library, roots):
|
||||
if library not in native:
|
||||
raise ValueError('目标库身份缺失')
|
||||
addresses = sorted(path for path in entries if path.name.casefold() == 'saddress.adr')
|
||||
targets, signatures = [], {}
|
||||
targets, signatures, shared_shutdowns = [], {}, {}
|
||||
from .icdb_ownership import shared_symbol_database
|
||||
shared = shared_symbol_database(library)
|
||||
for address in addresses:
|
||||
@@ -85,6 +136,10 @@ def _snapshot(library, roots):
|
||||
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)})
|
||||
with_shutdown = _shared_server_shutdown(address, data, shared/'icdb.dat', entries)
|
||||
if with_shutdown is not None:
|
||||
shared_shutdowns[str(address)] = with_shutdown
|
||||
signatures[with_shutdown['log']] = with_shutdown['log_sha256']
|
||||
continue
|
||||
matches = []
|
||||
for project in database.parent.glob('*.prj'):
|
||||
@@ -101,6 +156,7 @@ def _snapshot(library, roots):
|
||||
signatures[str(matches[0])] = hashlib.sha256(matches[0].read_bytes()).hexdigest()
|
||||
return {'exclusive_files': [str(p) for p in native], 'addresses': [str(p) for p in addresses],
|
||||
'inspection_targets': targets, 'signatures': signatures, 'binding_files': sorted(signatures),
|
||||
'shared_shutdowns': shared_shutdowns,
|
||||
'resource_scope': {'library': str(library), 'roots': [str(p) for p in roots],
|
||||
'projects': sorted(str(p) for p in entries if p.suffix.casefold() == '.prj'),
|
||||
'shared_dependencies': sorted(str(p.parent) for p in native
|
||||
@@ -108,6 +164,54 @@ def _snapshot(library, roots):
|
||||
'databases': sorted({str(p.parent) for p in native if p.name.casefold() == 'icdb.dat'})}}
|
||||
|
||||
|
||||
def _saved_project_snapshot(library, project, pcb, checked_path):
|
||||
from .backup_recovery import _decode_project_text
|
||||
from .icdb_ownership import database_directories
|
||||
|
||||
if (project.suffix.casefold() != '.prj' or not project.is_relative_to(library.parent)
|
||||
or pcb.suffix.casefold() != '.pcb' or not pcb.is_relative_to(project.parent)):
|
||||
raise ValueError('保存释放检查的工程范围不属于所选库')
|
||||
|
||||
candidates = {path/'icdb.dat': False for path in database_directories(library, project, pcb)}
|
||||
signatures = {}
|
||||
auxiliary = checked_path(pcb.parent/'pcb.prj')
|
||||
configs = (project, auxiliary) if auxiliary.exists() and auxiliary != project else (project,)
|
||||
for config in configs:
|
||||
if not config.is_file():
|
||||
raise ValueError(f'保存释放检查缺少工程配置:{config}')
|
||||
with config.open('rb') as stream:
|
||||
data = stream.read(1024*1024+1)
|
||||
if len(data) > 1024*1024:
|
||||
raise ValueError(f'工程配置过大:{config}')
|
||||
references = re.findall(r'^KEY[ \t]+iCDBDir\b[^\r\n]*', _decode_project_text(data), re.I | re.M)
|
||||
signatures[str(config)] = hashlib.sha256(data).hexdigest()
|
||||
if not references:
|
||||
continue
|
||||
reference = (re.fullmatch(r'KEY[ \t]+iCDBDir[ \t]+"([^"\r\n]+)"[ \t]*', references[0], re.I)
|
||||
if len(references) == 1 else None)
|
||||
if reference is None or PureWindowsPath(reference[1]).anchor:
|
||||
raise ValueError(f'工程 iCDBDir 必须唯一且为相对路径:{config}')
|
||||
target = checked_path(config.parent/reference[1]/'icdb.dat')
|
||||
if not target.is_relative_to(project.parent):
|
||||
raise ValueError(f'工程 iCDBDir 越出工程范围:{config}')
|
||||
candidates[target] = True
|
||||
|
||||
files = [str(library)]
|
||||
for candidate, required in candidates.items():
|
||||
path = checked_path(candidate)
|
||||
try:
|
||||
info = path.lstat()
|
||||
except FileNotFoundError:
|
||||
if required:
|
||||
raise ValueError(f'工程引用的数据库不存在:{path}') from None
|
||||
continue
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
raise ValueError(f'数据库路径不是普通文件:{path}')
|
||||
files.append(str(path))
|
||||
return {'exclusive_files': list(dict.fromkeys(files)), 'binding_files': list(signatures),
|
||||
'signatures': signatures}
|
||||
|
||||
|
||||
def file_probe_main(job):
|
||||
"""No native launch, writes, repair, address deletion or process termination."""
|
||||
import win32con, win32file
|
||||
@@ -130,7 +234,13 @@ def file_probe_main(job):
|
||||
roots = [checked_path(p) for p in request['roots']] if request['roots'] is not None else [library.parent]
|
||||
if library.suffix.casefold() != '.lmc' or any(not p.is_relative_to(library.parent) for p in roots):
|
||||
raise ValueError('文件探测范围不属于所选库')
|
||||
snapshot = _snapshot(library, roots)
|
||||
def read_snapshot():
|
||||
if request.get('saved_project') is None:
|
||||
return _snapshot(library, roots)
|
||||
project, pcb = (checked_path(path) for path in request['saved_project'])
|
||||
return _saved_project_snapshot(library, project, pcb, checked_path)
|
||||
|
||||
snapshot = read_snapshot()
|
||||
with ExitStack() as stack:
|
||||
handles = []
|
||||
for path in snapshot['exclusive_files']:
|
||||
@@ -146,7 +256,7 @@ def file_probe_main(job):
|
||||
stack.callback(handle.Close)
|
||||
handles.append(int(handle))
|
||||
opening = None
|
||||
if _snapshot(library, roots) != snapshot:
|
||||
if read_snapshot() != snapshot:
|
||||
raise ValueError('占用检查期间资源集合变化')
|
||||
pending = job.with_name('result.pending')
|
||||
pending.write_text(json.dumps({**result, **snapshot, 'status': 'HELD', 'handles': handles}), 'utf-8')
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Known native database owners touched by a CBB verification operation."""
|
||||
from pathlib import Path
|
||||
import time
|
||||
|
||||
|
||||
def session_resource_scope(job):
|
||||
@@ -33,6 +34,36 @@ def unreleased_addresses(lmc_file, project, pcb):
|
||||
if (path/'cdbsvr/sAddress.adr').exists()]
|
||||
|
||||
|
||||
def wait_for_saved_database_release(library, project, pcb, *, stop=None,
|
||||
report_pending=lambda **event: None, timeout_seconds=75):
|
||||
"""Check scoped files after PCB exits, outside the host native channel."""
|
||||
from .file_probe import hold_release_files
|
||||
from .operation_queue import note_metadata_progress
|
||||
|
||||
deadline = time.monotonic() + timeout_seconds
|
||||
reported = None
|
||||
while True:
|
||||
try:
|
||||
with hold_release_files(library, saved_project=(project, pcb), timeout_seconds=deadline-time.monotonic(),
|
||||
stop=stop) as proof:
|
||||
return {**proof, 'status': 'RELEASE_CONFIRMED', 'blocked_resources': []}
|
||||
except (OSError, ValueError) as error:
|
||||
winerror = getattr(error, 'winerror', None)
|
||||
blocked = getattr(error, 'blocked_resources', [])
|
||||
remaining = deadline - time.monotonic()
|
||||
if winerror not in (32, 33) or remaining <= 0:
|
||||
return {'status': 'IN_USE' if winerror in (32, 33) else 'UNCONFIRMED',
|
||||
'detail': str(error), 'winerror': winerror, 'blocked_resources': blocked}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'status': 'UNCONFIRMED', 'detail': '已取消释放检查',
|
||||
'blocked_resources': blocked}
|
||||
note_metadata_progress()
|
||||
if blocked != reported:
|
||||
report_pending(blocked_resources=blocked)
|
||||
reported = blocked
|
||||
time.sleep(min(1, remaining))
|
||||
|
||||
|
||||
def inspect_release_addresses(snapshot, *, stop=None):
|
||||
"""An address is a reason for native inspection, never an occupancy verdict."""
|
||||
import tempfile
|
||||
@@ -42,6 +73,8 @@ def inspect_release_addresses(snapshot, *, stop=None):
|
||||
results = []
|
||||
for item in snapshot['inspection_targets']:
|
||||
if item.get('scope') == 'shared_symbols':
|
||||
if item['address'] in snapshot.get('shared_shutdowns', {}):
|
||||
continue
|
||||
raise LibraryBusy('SHARED_ICDB_INSPECTION_UNAVAILABLE: 共享符号库地址需要原生核对:'
|
||||
+ item['address'])
|
||||
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||
|
||||
@@ -844,6 +844,8 @@ def execute_job(job, emit):
|
||||
cscript = Path(os.environ.get('WINDIR', r'C:\Windows'))/'SysWOW64'/'cscript.exe'
|
||||
from .desktop_worker import launch_save_helper
|
||||
helper_gate = root/'start-save.signal'
|
||||
from .residual_sessions import OrphanedVerifySavePrompt
|
||||
orphaned_prompt = OrphanedVerifySavePrompt(job, worker_pid, emit)
|
||||
with (root/'save.log').open('w', encoding='utf-8') as log:
|
||||
helper = launch_save_helper([str(cscript), '//nologo', str(script), job['project'],
|
||||
Path(job['pcb']).name, str(job.get('cancel_signal') or ''), str(helper_gate)],
|
||||
@@ -861,6 +863,7 @@ def execute_job(job, emit):
|
||||
last_markers = current
|
||||
from .runtime_timing import parse_save_progress
|
||||
emit(stage='save_progress', helper_exited=False, **parse_save_progress('\n'.join(current)))
|
||||
orphaned_prompt.poll(current)
|
||||
time.sleep(.2)
|
||||
code = helper.returncode
|
||||
save_log = (root/'save.log').read_bytes().decode('utf-8', errors='replace')
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Cooperative FIFO admission for this application's native operations."""
|
||||
from contextlib import contextmanager
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from dataclasses import dataclass, field
|
||||
import ntpath
|
||||
from threading import Condition, Event, RLock, Thread, local
|
||||
@@ -91,6 +91,8 @@ class _Call:
|
||||
shutdown_handoff: bool = False
|
||||
native_handoff: str = ''
|
||||
handoff_cancelled: bool = False
|
||||
queue_pause: object = None
|
||||
queued_for_slot: bool = False
|
||||
phase_started: float = field(default_factory=time.monotonic)
|
||||
result: object = None
|
||||
last_result: object = None
|
||||
@@ -110,6 +112,11 @@ def task_stop(fallback=None):
|
||||
return getattr(_local, 'call', None) or fallback
|
||||
|
||||
|
||||
def allow_other_libraries():
|
||||
call = getattr(_local, 'call', None)
|
||||
return call.queue_pause() if call is not None and call.queue_pause is not None else nullcontext()
|
||||
|
||||
|
||||
def check_active():
|
||||
call = getattr(_local, 'call', None)
|
||||
if call is not None and call.is_set():
|
||||
@@ -393,7 +400,8 @@ class BatchTaskContext:
|
||||
call.abandoned = True
|
||||
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
|
||||
elapsed = time.monotonic()-call.phase_started
|
||||
if not call.native_depth and not call.commit_depth and (call.abandoned or elapsed >= timeout_seconds):
|
||||
expired = not call.queued_for_slot and elapsed >= timeout_seconds
|
||||
if not call.native_depth and not call.commit_depth and (call.abandoned or expired):
|
||||
cancelled = call.is_set()
|
||||
call.abandoned = True
|
||||
raise TaskHandoff(self, cancelled=cancelled, result=call.last_result)
|
||||
@@ -402,6 +410,13 @@ class BatchTaskContext:
|
||||
return call.result
|
||||
|
||||
|
||||
@dataclass(eq=False)
|
||||
class _Ticket:
|
||||
roots: frozenset
|
||||
ready: bool = False
|
||||
paused: bool = False
|
||||
|
||||
|
||||
class NativeQueue:
|
||||
def __init__(self):
|
||||
self.condition = Condition()
|
||||
@@ -447,9 +462,62 @@ class NativeQueue:
|
||||
raise QueueUnavailable(path, retained_session_states(path), timed_out=True)
|
||||
return False
|
||||
return True
|
||||
ticket = [object(), False]
|
||||
roots = frozenset(ntpath.dirname(_path_key(path))
|
||||
for path in (context.library, *context.aliases)) if context is not None else frozenset()
|
||||
ticket = _Ticket(roots)
|
||||
acquired, notified = False, False
|
||||
previous_state = None
|
||||
|
||||
def first_ready():
|
||||
paused = [entry for entry in self.pending if entry.paused]
|
||||
return next((entry for entry in self.pending if entry.ready and not any(
|
||||
owner is not entry and (not entry.roots or owner.roots & entry.roots)
|
||||
for owner in paused)), None)
|
||||
|
||||
@contextmanager
|
||||
def pause():
|
||||
nonlocal acquired
|
||||
call = _local.call
|
||||
with self.condition:
|
||||
can_pause = acquired and not call.native_depth and not call.commit_depth
|
||||
if can_pause:
|
||||
ticket.ready, ticket.paused = False, True
|
||||
self.active = acquired = False
|
||||
self.condition.notify_all()
|
||||
if not can_pause:
|
||||
# Nested Verify may still be part of a management transaction.
|
||||
yield
|
||||
return
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
with _tasks_guard:
|
||||
call.queued_for_slot = True
|
||||
try:
|
||||
with self.condition:
|
||||
ticket.ready = True
|
||||
while ticket in self.pending and not self.closed and not call.is_set():
|
||||
if not self.active and first_ready() is ticket:
|
||||
self.active = acquired = True
|
||||
break
|
||||
self.condition.wait(.1)
|
||||
ticket.paused = ticket.ready = False
|
||||
self.condition.notify_all()
|
||||
if not acquired:
|
||||
raise QueueCancelled('已取消等待原生通道,未提交新的调用。')
|
||||
finally:
|
||||
with _tasks_guard:
|
||||
call.queued_for_slot = False
|
||||
call.phase_started = time.monotonic()
|
||||
|
||||
def run_admitted():
|
||||
call = _local.call
|
||||
previous_pause, call.queue_pause = call.queue_pause, pause
|
||||
try:
|
||||
return action()
|
||||
finally:
|
||||
call.queue_pause = previous_pause
|
||||
|
||||
with self.condition:
|
||||
if self.closed:
|
||||
raise QueueCancelled('队列已关闭,未启动新的操作。')
|
||||
@@ -466,15 +534,14 @@ class NativeQueue:
|
||||
if (self.closed or stop is not None and stop.is_set()
|
||||
or context is not None and (context.stop.is_set() or context.stop_after_current.is_set())):
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
ticket[1] = bool(available)
|
||||
first = next((entry for entry in self.pending if entry[1]), None)
|
||||
if not self.active and first is ticket:
|
||||
ticket.ready = bool(available)
|
||||
if not self.active and first_ready() is ticket:
|
||||
self.active = acquired = True
|
||||
else:
|
||||
self.condition.wait(.1)
|
||||
if acquired and not available_now():
|
||||
with self.condition:
|
||||
ticket[1] = self.active = acquired = False
|
||||
ticket.ready = self.active = acquired = False
|
||||
self.condition.notify_all()
|
||||
if not acquired and waiting is not None:
|
||||
try:
|
||||
@@ -487,7 +554,7 @@ class NativeQueue:
|
||||
if (stop is not None and stop.is_set()
|
||||
or context is not None and context.stop_after_current.is_set()):
|
||||
raise QueueCancelled('已取消排队,未启动原生操作。')
|
||||
return context.run(action, stop=stop, timeout_seconds=timeout_seconds) if context else action()
|
||||
return context.run(run_admitted, stop=stop, timeout_seconds=timeout_seconds) if context else action()
|
||||
finally:
|
||||
with self.condition:
|
||||
self.pending = [entry for entry in self.pending if entry is not ticket]
|
||||
|
||||
@@ -118,6 +118,8 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
|
||||
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}')
|
||||
if str(address) in files.get('shared_shutdowns', {}):
|
||||
continue
|
||||
_write_json(Path(job['root'])/'pcb-open-resource-denied.json', {
|
||||
'status': 'SHARED_ICDB_INSPECTION_UNAVAILABLE',
|
||||
'operation_id': job.get('operation_id'), 'library': str(library),
|
||||
@@ -130,6 +132,8 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
|
||||
raise ValueError(f"PCB_OPEN_DATABASE_UNCONFIRMED: 地址未绑定实际工程配置:{item['database']}")
|
||||
stack.close() # Native inspection must access the DB; repeat exact proof afterwards.
|
||||
for index, item in enumerate(targets):
|
||||
if item.get('scope') == 'shared_symbols':
|
||||
continue
|
||||
target = RepairTarget(Path(item['project']), Path(item['database']))
|
||||
evidence = Path(job['root'])/('open-inspection-'+str(index))
|
||||
result = run_native_repair(target, evidence, mentor_bin=job.get('mentor_bin'),
|
||||
@@ -157,7 +161,8 @@ def resource_guard(job, allowed_pids, *, require_complete_proof=False):
|
||||
'operation_id': job.get('operation_id'), 'library': str(library),
|
||||
'project': str(project), 'pcb': str(pcb), 'binding': original_binding,
|
||||
'exclusive_files': files['exclusive_files'], 'addresses': files['addresses'],
|
||||
'native_inspections': inspections, 'repair_confirmed': False})
|
||||
'native_inspections': inspections, 'shared_shutdowns': files.get('shared_shutdowns', {}),
|
||||
'repair_confirmed': False})
|
||||
yield
|
||||
|
||||
|
||||
|
||||
@@ -394,6 +394,78 @@ def _save_question(windows, *, incomplete=None):
|
||||
return None
|
||||
|
||||
|
||||
class OrphanedVerifySavePrompt:
|
||||
"""Continue the registered worker's already started Save after supervisor loss."""
|
||||
|
||||
def __init__(self, job, pcb_pid, emit, *, clock=time.monotonic):
|
||||
self.job = job
|
||||
self.pid = pcb_pid
|
||||
self.emit = emit
|
||||
self.clock = clock
|
||||
self.pending = None
|
||||
self.clicked = False
|
||||
|
||||
def poll(self, markers):
|
||||
from .desktop_worker import supervisor_has_exited
|
||||
if (self.clicked or 'SAVE_START' not in markers
|
||||
or any(marker == 'SAVE_OK' or marker.startswith(('SAVE_REJECTED', 'SAVE_RESULT_UNKNOWN'))
|
||||
for marker in markers)
|
||||
or not supervisor_has_exited()
|
||||
or self.job.get('interactive_input') is not False
|
||||
or not self.job.get('desktop', '').startswith('CbbVerify_')
|
||||
or not self.job.get('session_record_path')):
|
||||
return
|
||||
|
||||
from .session_record import IDENTITY_KEYS, process_identity, read_session_record
|
||||
import win32con
|
||||
|
||||
state_path = Path(self.job['session_record_path']).with_name('worker-state.json')
|
||||
try:
|
||||
state = read_session_record(state_path, evidence_root=state_path.parent)
|
||||
if (state['operation_id'] != self.job['operation_id']
|
||||
or state.get('phase') != 'NATIVE_CALL'):
|
||||
self.pending = None
|
||||
return
|
||||
identity = next((row for row in state['processes']
|
||||
if row['role'] == 'native' and row['pid'] == self.pid), None)
|
||||
actual = process_identity(self.pid) if identity is not None else None
|
||||
if actual is None or any(actual[key] != identity[key] for key in IDENTITY_KEYS):
|
||||
self.pending = None
|
||||
return
|
||||
windows = _process_windows({self.pid})
|
||||
matches = []
|
||||
for window in windows.get(self.pid, ()):
|
||||
if (window['desktop'] != self.job['desktop'] or window['class'] != '#32770'
|
||||
or window['title'] != 'Expedition PCB' or not window['enabled']):
|
||||
continue
|
||||
texts = [child['text'].strip().casefold() for child in window['children']
|
||||
if child['class'] == 'Static' and child['text'].strip()]
|
||||
buttons = [child for child in window['children'] if child['class'] == 'Button']
|
||||
if (texts == ['do you want to save the reusable block cell?']
|
||||
and sorted(item['id'] for item in buttons) == [6, 7]
|
||||
and all(item['enabled'] for item in buttons)):
|
||||
button = next(item['hwnd'] for item in buttons if item['id'] == 6)
|
||||
matches.append((window, button))
|
||||
if self.pid in windows.incomplete or len(matches) != 1:
|
||||
self.pending = None
|
||||
return
|
||||
window, button = matches[0]
|
||||
now = self.clock()
|
||||
signature = (window['hwnd'], button)
|
||||
if self.pending is None or self.pending[0] != signature:
|
||||
self.pending = (signature, now)
|
||||
return
|
||||
if now - self.pending[1] < 3:
|
||||
return
|
||||
_post_window_message(window, button, self.pid, win32con.BM_CLICK)
|
||||
self.clicked = True
|
||||
self.emit(stage='orphaned_save_confirmed', native_pid=self.pid, hwnd=window['hwnd'],
|
||||
rule_id='reusable-block-save', accepted_control=[6])
|
||||
except Exception:
|
||||
# Read errors must leave the already executing native write alone.
|
||||
self.pending = None
|
||||
|
||||
|
||||
def _cancel_question(name, windows, *, incomplete=None):
|
||||
if (name.casefold() != 'icdbprojectbackup.exe'
|
||||
or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'):
|
||||
|
||||
@@ -18,6 +18,7 @@ from PySide6.QtWidgets import (QWidget, QLineEdit, QPushButton, QFormLayout,
|
||||
QTableWidget, QTableWidgetItem, QHeaderView, QCheckBox, QVBoxLayout, QProgressBar, QComboBox,
|
||||
QTabBar, QStackedWidget, QSizePolicy, QDialog, QDialogButtonBox, QPlainTextEdit)
|
||||
from PySide6.QtWidgets import QStyle
|
||||
from shiboken6 import isValid
|
||||
|
||||
|
||||
def _path_key(value):
|
||||
@@ -134,7 +135,8 @@ class MainWindow(QWidget):
|
||||
self._diagnostic_evidence = {}
|
||||
self.pool = QThreadPool(self); self.pool.setMaxThreadCount(8)
|
||||
self.lifecycle_pool = QThreadPool(self); self.lifecycle_pool.setMaxThreadCount(1)
|
||||
self.lease_pool = QThreadPool(self); self.lease_pool.setMaxThreadCount(1)
|
||||
self.lease_pool = QThreadPool()
|
||||
self.lease_pool.setMaxThreadCount(1)
|
||||
self._lifecycle_workers = set()
|
||||
self._lifecycle_contexts = set()
|
||||
self._lease_pending = 0
|
||||
@@ -408,22 +410,24 @@ class MainWindow(QWidget):
|
||||
if signal == 'version_choice': value.choose('cancel')
|
||||
|
||||
def _finish_job(self, job):
|
||||
view_alive = isValid(self) and isValid(self.cbb_table)
|
||||
if job.keep_session:
|
||||
if self._job_current(job): self._finished()
|
||||
if view_alive and self._job_current(job): self._finished()
|
||||
return
|
||||
paused = getattr(job, 'paused_check', None)
|
||||
if paused is not None and paused.active and not paused.stop.is_set() and not self._closing:
|
||||
if view_alive and paused is not None and paused.active and not paused.stop.is_set() and not self._closing:
|
||||
paused.resume()
|
||||
job.active = False
|
||||
self._jobs.pop(job.context.operation_id, None)
|
||||
state = job.context.close(timeout_seconds=0)
|
||||
if job.lease is not None and job.lease is not self.library_lease:
|
||||
if job.lease is not None and (not view_alive or job.lease is not self.library_lease):
|
||||
if state['pending'] or id(job.lease) in self._shutdown_leases:
|
||||
self._retain_path_lease(job.lease)
|
||||
elif not any(other.lease is job.lease for other in self._jobs.values()):
|
||||
self._close_path_lease(job.lease)
|
||||
if self._job_current(job): self._finished()
|
||||
else: self._update()
|
||||
if view_alive:
|
||||
if self._job_current(job): self._finished()
|
||||
else: self._update()
|
||||
|
||||
def _release_library_lease(self):
|
||||
lease, self.library_lease = self.library_lease, None
|
||||
@@ -457,7 +461,10 @@ class MainWindow(QWidget):
|
||||
|
||||
def _lease_action(self, action, completed=None, failed=None, *, hold_busy=False,
|
||||
library=None, completed_always=False):
|
||||
# The serial pool orders retain before every subsequent close.
|
||||
# The serial pool outlives the view and orders retain before close.
|
||||
if not isValid(self) or not isValid(self.cbb_table):
|
||||
self.lease_pool.start(ServiceWorker(action))
|
||||
return
|
||||
owner = (self._view_revision, id(self._current_job))
|
||||
def current():
|
||||
from shiboken6 import isValid
|
||||
@@ -477,7 +484,10 @@ class MainWindow(QWidget):
|
||||
worker = ServiceWorker(lambda:context.run(action))
|
||||
self._lease_workers.add(worker)
|
||||
if completed is not None:
|
||||
worker.signals.succeeded.connect(lambda result:completed(result) if completed_always or current() else None)
|
||||
def ready(result):
|
||||
if isValid(self) and isValid(self.cbb_table) and (completed_always or current()):
|
||||
completed(result)
|
||||
worker.signals.succeeded.connect(ready)
|
||||
worker.signals.failed.connect(lambda error:(failed or self._display_error)(error) if current() else None)
|
||||
def finished():
|
||||
self._lease_workers.discard(worker)
|
||||
@@ -2082,7 +2092,7 @@ class MainWindow(QWidget):
|
||||
elif event.get('stage') == 'native_slot_acquired':
|
||||
self.status_label.setText(event.get('detail') or '正在执行当前任务…')
|
||||
self._update()
|
||||
if event.get('stage') in ('session_handoff', 'save_stop_requested'):
|
||||
if event.get('stage') in ('session_handoff', 'save_stop_requested', 'post_save_release_pending'):
|
||||
self.status_label.setText(event.get('detail', '当前状态无法确认'))
|
||||
if (event.get('stage') == 'session_observation' and event.get('status') == 'RELEASED'
|
||||
and event.get('release_proof')):
|
||||
@@ -2457,6 +2467,8 @@ class MainWindow(QWidget):
|
||||
self.status_label.setText('当前操作尚未结束,仍在等待安全关闭。')
|
||||
|
||||
def _close_when_idle(self):
|
||||
if not isValid(self):
|
||||
return
|
||||
owners = [self, *self.icdb_tasks, *self._dialogs]
|
||||
for name in ('management_dialog', 'backup_dialog', 'release_dialog'):
|
||||
owners.append(getattr(self, name, None))
|
||||
|
||||
@@ -1441,6 +1441,34 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
release_result = {**(release_result or {}), 'icdb_addresses': addresses}
|
||||
except OSError as error:
|
||||
close_errors.append(str(error))
|
||||
try:
|
||||
save_lines = (root/'save.log').read_text('utf-8', errors='replace').splitlines()
|
||||
except FileNotFoundError:
|
||||
save_lines = []
|
||||
except OSError as error:
|
||||
save_lines = []
|
||||
close_errors.append(str(error))
|
||||
if (worker_exited and automation_release.get('safe_to_continue') and not close_errors
|
||||
and release_result.get('safe_to_continue') and not request.diagnostic_only
|
||||
and {'SAVE_START', 'SAVE_OK', 'IS_SAVED', 'CLOSE_OK'}.issubset(save_lines)):
|
||||
from .icdb_ownership import wait_for_saved_database_release
|
||||
from .operation_queue import allow_other_libraries, task_stop
|
||||
timing.begin('database_release')
|
||||
try:
|
||||
with allow_other_libraries():
|
||||
database_release = wait_for_saved_database_release(
|
||||
request.lmc_file, project, pcb, stop=task_stop(stop),
|
||||
report_pending=lambda **event: _notify_progress(progress, {
|
||||
'stage': 'post_save_release_pending', 'block': request.block_name,
|
||||
'detail': '已保存,等待 iCDB 释放数据库', **event}))
|
||||
except Exception as error:
|
||||
database_release = {'status': 'UNCONFIRMED', 'detail': str(error),
|
||||
'blocked_resources': []}
|
||||
finally:
|
||||
timing.end('database_release')
|
||||
release_result = {**release_result, 'database_release': database_release,
|
||||
'blocked_resources': database_release['blocked_resources'],
|
||||
'safe_to_continue': database_release['status'] == 'RELEASE_CONFIRMED'}
|
||||
if close_errors:
|
||||
release_result = {**(release_result or {}), 'safe_to_continue': False,
|
||||
'close_errors': close_errors}
|
||||
@@ -1470,8 +1498,6 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
'close_errors': [*close_errors, str(error)]}
|
||||
try:
|
||||
from .operation_lifecycle import classify_save_state
|
||||
save_lines = ((root/'save.log').read_text('utf-8', errors='replace').splitlines()
|
||||
if (root/'save.log').is_file() else [])
|
||||
facts = classify_save_state(save_lines,
|
||||
helper_exited=(False if automation_release.get('remaining_pids') else
|
||||
True if worker_exited and automation_release.get('safe_to_continue') else None),
|
||||
@@ -1504,8 +1530,17 @@ def _run_verify(request, *, timing, progress=None, flag_reader=None, process_run
|
||||
pass
|
||||
if not release_result or not release_result.get('safe_to_continue'):
|
||||
if 'result' in locals():
|
||||
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status, safe_to_continue=False,
|
||||
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
|
||||
database_release = (release_result or {}).get('database_release')
|
||||
if database_release and database_release['status'] != 'RELEASE_CONFIRMED':
|
||||
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
|
||||
safe_to_continue=False, error_category='ICDB_RELEASE_PENDING', error_stage='release_check',
|
||||
release_proof=database_release,
|
||||
stderr=(result.stderr + '\nICDB_RELEASE_PENDING: 已保存,数据库释放未确认。'
|
||||
+ database_release['detail']).strip())
|
||||
else:
|
||||
result = replace(result, status='FAIL' if result.status == 'PASS' else result.status,
|
||||
safe_to_continue=False,
|
||||
stderr=(result.stderr + '\nPCB_RELEASE_UNCONFIRMED: 未确认原生会话退出').strip())
|
||||
recovery = {'desktop': job['desktop'], 'project': str(project),
|
||||
'pcb': str(pcb), 'release': release_result,
|
||||
'action': '停止批次;检查原生会话及数据库;不要删除锁文件或自动恢复。'}
|
||||
@@ -1583,6 +1618,15 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
if refreshed.safe_to_continue:
|
||||
results[index] = refreshed
|
||||
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
|
||||
cached_timeout = None
|
||||
if library_keys.intersection(timed_out_admissions):
|
||||
from .session_record import library_available
|
||||
for key in library_keys.intersection(timed_out_admissions):
|
||||
blocked_library, previous_result = timed_out_admissions[key]
|
||||
if not library_available(blocked_library, live_only=True):
|
||||
cached_timeout = previous_result
|
||||
break
|
||||
del timed_out_admissions[key]
|
||||
if (queue_stop or stop is not None and stop.is_set()
|
||||
or context is not None and context.stop.is_set()):
|
||||
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
|
||||
@@ -1590,8 +1634,8 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
previous, index = retained_libraries[next(iter(library_keys.intersection(retained_libraries)))]
|
||||
result = VerifyResult('SKIPPED', error_category='PREVIOUS_SESSION_UNRELEASED',
|
||||
error_stage='admission', stderr=f'前项 {getattr(previous, "block_name", previous)} 的同库会话尚未释放,当前项未启动。')
|
||||
elif library_keys.intersection(timed_out_admissions):
|
||||
result = timed_out_admissions[next(iter(library_keys.intersection(timed_out_admissions)))]
|
||||
elif cached_timeout is not None:
|
||||
result = cached_timeout
|
||||
else:
|
||||
try:
|
||||
def execute():
|
||||
@@ -1612,7 +1656,7 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
|
||||
VerifyResult('CANCELLED' if isinstance(error, QueueCancelled) else 'FAIL',
|
||||
stderr=str(error), safe_to_continue=isinstance(error, QueueCancelled)))
|
||||
if isinstance(error, QueueUnavailable) and error.timed_out:
|
||||
timed_out_admissions.update(dict.fromkeys(library_keys, result))
|
||||
timed_out_admissions.update(dict.fromkeys(library_keys, (error.library, result)))
|
||||
results.append(result)
|
||||
# Never start another writer after an unconfirmed native shutdown.
|
||||
if not result.safe_to_continue:
|
||||
|
||||
Reference in new issue
Block a user