fix: finish owned idle sessions before proving resource release

This commit was merged in pull request #18.
This commit is contained in:
阿白叔 committed 2026-11-19 11:14:49 +08:00
1 parent 3bde847ff7
commit 55cdf2b082
10 files changed
+632 -8

No files matched your search

+8 -2
View File
@@ -41,6 +41,7 @@ def hold_release_files(library, roots=None, *, timeout_seconds=10, stop=None):
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')
error.blocked_resources = record.get('blocked_resources', [])
raise error
# Duplicate the already-open handles before acknowledging the probe.
# Its exit can never create a gap in the parent's commit protection.
@@ -108,6 +109,7 @@ def file_probe_main(job):
job = Path(job)
request = json.loads(job.read_text('utf-8'))
result = {'token': request['token'], 'status': 'UNCONFIRMED'}
opening = None
try:
def checked_path(value):
path = Path(value).absolute()
@@ -127,15 +129,18 @@ def file_probe_main(job):
with ExitStack() as stack:
handles = []
for path in snapshot['exclusive_files']:
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
handles.append(int(handle))
for path in snapshot['binding_files']:
opening = path
handle = win32file.CreateFile(path, win32con.GENERIC_READ, win32con.FILE_SHARE_READ,
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
stack.callback(handle.Close)
handles.append(int(handle))
opening = None
if _snapshot(library, roots) != snapshot:
raise ValueError('占用检查期间资源集合变化')
pending = job.with_name('result.pending')
@@ -145,7 +150,8 @@ def file_probe_main(job):
return 0
except Exception as error:
pending = job.with_name('result.pending')
pending.write_text(json.dumps({**result, 'error': str(error),
'winerror': getattr(error, 'winerror', None)}), 'utf-8')
blocked = [opening] if opening and getattr(error, 'winerror', None) in (32,33) else []
pending.write_text(json.dumps({**result, 'error': (opening+': ' if opening else '')+str(error),
'winerror': getattr(error, 'winerror', None), 'blocked_resources': blocked}), 'utf-8')
pending.replace(job.with_name('result.json'))
return 1
+2
View File
@@ -559,6 +559,7 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
except OSError as error:
blocked = LibraryBusy(str(error))
blocked.winerror = getattr(error, 'winerror', None)
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
raise blocked from error
note_metadata_progress()
if files['addresses']:
@@ -576,6 +577,7 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
except OSError as error:
blocked = LibraryBusy(str(error))
blocked.winerror = getattr(error, 'winerror', None)
blocked.blocked_resources = getattr(error, 'blocked_resources', [])
raise blocked from error
if any(current[key] != files[key] for key in (
'exclusive_files', 'addresses', 'signatures', 'inspection_targets')):
+17 -3
View File
@@ -28,7 +28,10 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
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
from .residual_sessions import finish_owned_idle_session
finish_owned_idle_session(session, stop=stop)
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')
@@ -42,7 +45,10 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
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
from .residual_sessions import finish_owned_idle_session
finish_owned_idle_session(candidate, stop=stop)
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.
@@ -60,7 +66,15 @@ def recheck_failed_release(library, block, result, *, stop=None, timeout_seconds
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:
except Exception as error:
try:
evidence.with_name('late-release-attempt.json').write_text(json.dumps(dict(
business_status=result.status, safe_to_continue=False,
status='IN_USE' if getattr(error,'winerror',None) in (32,33) else 'UNCONFIRMED',
library=str(library), block=block, detail=str(error),
blocked_resources=getattr(error,'blocked_resources',[])),ensure_ascii=False,indent=2),'utf-8')
except OSError:
pass
return result
+112
View File
@@ -818,6 +818,118 @@ def resume_cancelled_startup(path, *, stop=None):
return False
def finish_owned_idle_session(path, *, stop=None):
"""One normal close for a registered, settled, empty client; never a server."""
from contextlib import ExitStack
import stat
import pywintypes, win32con, win32event
from .session_record import _session, active_write_records, write_session_record
from .operation_queue import check_active, native_phase
path = Path(path)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired or stop is not None and stop.is_set(): return False
session, state, identities = _session(path, path.parent)
if 'owned_idle_cleanup' in session: return False
def read(name):
item = path.with_name(name)
if item.lstat().st_file_attributes & stat.FILE_ATTRIBUTE_REPARSE_POINT:
raise ValueError('OWNED_CLEANUP_REPARSE_POINT')
with item.open('rb') as stream: data = stream.read(1024*1024+1)
if len(data) > 1024*1024: raise ValueError('OWNED_CLEANUP_RECORD_TOO_LARGE')
return json.loads(data)
job, result = read('request.json'), read('result.json')
if not isinstance(job, dict) or not isinstance(result, dict): return False
if (any(job.get(k) != session.get(k) for k in ('operation_id','operation','library','desktop','block'))
or Path(job.get('session_record_path','')).resolve() != path.resolve()
or result.get('safe_to_continue') is not False): return False
operation, desktop = job['operation'], job['desktop']
if operation == 'verify':
facts = result.get('write_outcome') or {}
failed_open = (result.get('error_stage') == 'PCB_STARTING'
and result.get('error_category') in ('MENTOR_DATABASE_LOAD_FAILED','ICDB_REPAIR_REQUIRED')
and not path.with_name('save.log').exists())
saved_closed = (isinstance(facts, dict) and facts.get('interrupted') is False
and all(facts.get(k) == v for k,v in (
('save_state','COMMITTED'),('close_state','CLOSED'),('helper_state','EXITED'))))
if (not desktop.startswith('CbbVerify_') or job.get('interactive_input') is not False
or result.get('status') not in ('FAIL','BLOCKED','TIMEOUT','CANCELLED')
or result.get('block_name') != job['block']
or Path(result.get('evidence_path','')).resolve() != path.with_name('result.json').resolve()
or Path(job.get('root','')).resolve() != path.parent.resolve()
or job.get('lmc_file') != job['library'] or not (failed_open or saved_closed)): return False
client_name = 'expeditionpcb.exe'
elif operation == 'catalog' and job.get('worker_role') == 'catalog_readonly' and desktop.startswith('CbbManagement_'):
client_name = 'librarymanager.exe'
else:
return False
workers = [p for p in identities if p.get('role') in ('worker','helper')]
clients = [p for p in identities if p.get('role') == 'native' and Path(p['image']).name.casefold() == client_name]
if not workers or len(clients) != 1: return False
if any(r.get('operation_id') != session['operation_id'] for r in active_write_records(session['library'])):
return False
with ExitStack() as held:
for worker in workers:
try:
handle = held.enter_context(_process_handle(worker['pid']))
if (win32event.WaitForSingleObject(handle, 0) != win32con.WAIT_OBJECT_0
and _handle_identity(handle) == {k:worker[k] for k in ('created_handle','image')}):
return False
except pywintypes.error as error:
if error.winerror != 87: raise
client = clients[0]
handle = held.enter_context(_process_handle(client['pid']))
def same_client():
owner = _force_ownership(handle, client['pid'])
return (win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_TIMEOUT
and owner.get('force_user_confirmed') is True
and _handle_identity(handle) == {k:client[k] for k in ('created_handle','image')}
and all(owner.get(k) == client[k] for k in ('owner_sid','session_id')))
def empty_target():
snapshot = _process_windows({client['pid']}, include_hidden_documents=True)
windows = snapshot.get(client['pid'], [])
if (any(w.get('desktop') != desktop or w.get('documents')
or any(c['class'].casefold().startswith('afx:') and c.get('visible') is False
for c in w.get('children',[])) for w in windows)):
return None
return close_target(client_name, windows, incomplete=_window_error(snapshot,client['pid']))[0]
if not same_client(): return False
target = empty_target()
if target is None or stop is not None and stop.is_set(): return False
check_active()
current, _, _ = _session(path, path.parent)
if current != session: return False
claim = dict(operation_id=session['operation_id'],pid=client['pid'],identity=client,
status='REQUESTED',hwnd=target['hwnd'],desktop=desktop)
write_session_record(path, {**session,'owned_idle_cleanup':claim})
# Re-read after durable I/O; never act on a window that gained a document.
latest, latest_state, latest_identities = _session(path, path.parent)
if (latest_state != state or latest_identities != identities
or latest.get('owned_idle_cleanup') != claim
or any(latest.get(k) != v for k,v in session.items() if k != 'recorded_at')
or not same_client() or empty_target() != target or read('request.json') != job
or read('result.json') != result or stop is not None and stop.is_set()): return False
with native_phase(read_only=True):
_post_window_message(target,target['hwnd'],client['pid'],win32con.WM_CLOSE)
deadline = time.monotonic()+3
while time.monotonic() < deadline:
if win32event.WaitForSingleObject(handle,100) == win32con.WAIT_OBJECT_0: break
if stop is not None and stop.is_set(): break
exited = win32event.WaitForSingleObject(handle,0) == win32con.WAIT_OBJECT_0
write_session_record(path.with_name('owned-idle-cleanup-result.json'),dict(
operation_id=session['operation_id'],library=session['library'],
status='CLIENT_EXITED' if exited else 'WAITING',claim=claim,
resource_release_confirmed=False))
return True # Client exit is still not independent resource release proof.
except (OSError,pywintypes.error,ValueError,KeyError,TypeError,RuntimeError):
return False
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
def _request_close(row, *, stop=None):
import win32con, win32event
with _process_handle(row['pid']) as handle:
+2 -2
View File
@@ -409,8 +409,8 @@ def observe_retained_session(path, *, evidence_root, stop=None, progress=None, p
pass
if result['status'] == 'ACTIVE' and not observation_only and not stop.is_set():
try:
from .residual_sessions import resume_cancelled_startup
if resume_cancelled_startup(path, stop=stop):
from .residual_sessions import resume_cancelled_startup, finish_owned_idle_session
if resume_cancelled_startup(path, stop=stop) or finish_owned_idle_session(path, stop=stop):
# Cleanup is not release proof. Re-read all held identities
# and independently prove the resource release as usual.
result = _reconcile(Path(path), Path(evidence_root), handles, stack)
+1 -1
View File
@@ -657,7 +657,7 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
Path(request.evidence_dir)/'previous-release', block_name=request.block_name,
progress=progress, stop=stop)
check_active()
library_lock = LibraryLock(request.lmc_file, checkpoint=False,
library_lock = LibraryLock(request.lmc_file, checkpoint=False, block_name=request.block_name,
safe_to_release=clients_released)
library_lock.__enter__()
check_active()