Merge branch 'codex/review-residual-release' into codex/runtime-lifecycle-safety
# Conflicts: # src/cbb_refresh_verify/residual_sessions.py
This commit is contained in:
commit
b1c36e3ca6
8 files changed
+466
-51
No files matched your search
@@ -561,6 +561,16 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
records = [checkpoint_record(path) for path, data in before.items() if data is not None]
|
||||
scoped = (block_name if block_name and all(record and record.get('block_name') == block_name
|
||||
for record in records) and (owner is None or owner.get('block_name') == block_name) else None)
|
||||
reconciled = [{'kind': 'checkpoint', 'path': str(path), 'recognized': metadata is not None,
|
||||
**{key: (metadata or {}).get(key) for key in ('block_name', 'lease_id', 'pid', 'status', 'time')}}
|
||||
for path, data in before.items() if data is not None
|
||||
for metadata in (checkpoint_record(path),)]
|
||||
if owner:
|
||||
reconciled.append({'kind': 'retained_owner', 'path': str(lease.path),
|
||||
'block_name': owner.get('block_name'), 'lease_id': owner['lease_id'],
|
||||
'status': 'OWNER_RELEASE_UNCONFIRMED'})
|
||||
foreign = sorted({item['block_name'] for item in reconciled
|
||||
if block_name and item.get('block_name') and item['block_name'] != block_name})
|
||||
proof_context = (_prove_library_released(library, allow_unknown_checkpoint=True) if unknown else
|
||||
_prove_library_released(library, block_name=scoped)
|
||||
if scoped else _prove_library_released(library))
|
||||
@@ -572,6 +582,9 @@ def release_retained_library(library, evidence_dir, *, block_name=None):
|
||||
root = evidence/('release-' + uuid4().hex)
|
||||
root.mkdir(parents=True, exist_ok=False)
|
||||
record = {'library': str(library), 'status': 'RELEASE_CONFIRMED', **proof,
|
||||
'requested_block_name': block_name, 'proof_scope': 'BLOCK' if scoped else 'LIBRARY',
|
||||
'proof_block_name': scoped, 'reconciled_checkpoints': reconciled,
|
||||
'reconciled_foreign_blockers': foreign,
|
||||
'unknown_checkpoint_archived': unknown,
|
||||
'data_recovery_confirmed': False, 'evidence_path': str(root/'release.json')}
|
||||
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Preview and cooperatively close the exact native sessions a user confirms."""
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
@@ -41,8 +42,8 @@ def force_block_reason(row):
|
||||
return ''
|
||||
|
||||
|
||||
def native_activity(name, windows):
|
||||
if any(w['class'] == 'UNCONFIRMED' for w in windows):
|
||||
def native_activity(name, windows, *, incomplete=None):
|
||||
if incomplete or any(w['class'] == 'UNCONFIRMED' for w in windows):
|
||||
return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'}
|
||||
if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled'])
|
||||
or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows):
|
||||
@@ -114,16 +115,85 @@ def _force_ownership(handle, pid):
|
||||
and session == win32ts.ProcessIdToSessionId(os.getpid())}
|
||||
|
||||
|
||||
class _WindowSnapshot(dict):
|
||||
def __init__(self, pids):
|
||||
super().__init__((pid, []) for pid in pids)
|
||||
self.incomplete = {}
|
||||
|
||||
|
||||
def _process_threads(pids):
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
class ThreadEntry(ctypes.Structure):
|
||||
_fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('tid', wintypes.DWORD),
|
||||
('pid', wintypes.DWORD), ('base', wintypes.LONG), ('delta', wintypes.LONG),
|
||||
('flags', wintypes.DWORD)]
|
||||
kernel = ctypes.WinDLL('kernel32', use_last_error=True)
|
||||
kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
|
||||
kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE
|
||||
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
for name in ('Thread32First', 'Thread32Next'):
|
||||
function = getattr(kernel, name)
|
||||
function.argtypes = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)]
|
||||
function.restype = wintypes.BOOL
|
||||
snapshot = kernel.CreateToolhelp32Snapshot(4, 0) # TH32CS_SNAPTHREAD
|
||||
if snapshot == ctypes.c_void_p(-1).value:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
result = {pid: [] for pid in pids}
|
||||
try:
|
||||
entry = ThreadEntry(); entry.size = ctypes.sizeof(entry)
|
||||
more = kernel.Thread32First(snapshot, ctypes.byref(entry))
|
||||
while more:
|
||||
if entry.pid in result:
|
||||
result[entry.pid].append(int(entry.tid))
|
||||
entry.size = ctypes.sizeof(entry)
|
||||
more = kernel.Thread32Next(snapshot, ctypes.byref(entry))
|
||||
if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
finally:
|
||||
kernel.CloseHandle(snapshot)
|
||||
return result
|
||||
|
||||
|
||||
def _thread_desktop_name(tid):
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
user = ctypes.WinDLL('user32', use_last_error=True)
|
||||
user.GetThreadDesktop.argtypes = [wintypes.DWORD]
|
||||
user.GetThreadDesktop.restype = wintypes.HANDLE
|
||||
user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID,
|
||||
wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)]
|
||||
user.GetUserObjectInformationW.restype = wintypes.BOOL
|
||||
ctypes.set_last_error(0)
|
||||
desktop = user.GetThreadDesktop(tid)
|
||||
if not desktop:
|
||||
if error := ctypes.get_last_error():
|
||||
raise ctypes.WinError(error)
|
||||
return None # A non-GUI thread need not have an assigned desktop.
|
||||
# GetThreadDesktop returns a borrowed handle; never CloseDesktop it.
|
||||
name, needed = ctypes.create_unicode_buffer(512), wintypes.DWORD()
|
||||
if not user.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(needed)):
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
return name.value
|
||||
|
||||
|
||||
def _window_error(snapshot, pid):
|
||||
return getattr(snapshot, 'incomplete', {}).get(pid)
|
||||
|
||||
|
||||
def _process_windows(pids):
|
||||
if not pids: return {}
|
||||
result = _WindowSnapshot(pids)
|
||||
if not pids: return result
|
||||
import win32api, win32con, win32gui, win32process, win32service
|
||||
from .native_repair_ui import _native_output
|
||||
result = {pid: [] for pid in pids}
|
||||
observed = set()
|
||||
def capture(hwnd, _=None, *, desktop_name='Default'):
|
||||
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
|
||||
if pid not in result or hwnd in observed or not win32gui.IsWindowVisible(hwnd):
|
||||
def capture(hwnd, _, *, pid, desktop_name):
|
||||
if win32process.GetWindowThreadProcessId(hwnd)[1] != pid:
|
||||
raise ValueError('窗口所属进程已变化')
|
||||
if hwnd in observed or not win32gui.IsWindowVisible(hwnd):
|
||||
return
|
||||
if desktop_name is None:
|
||||
raise ValueError('窗口所属桌面无法读取')
|
||||
observed.add(hwnd)
|
||||
children, documents = [], []
|
||||
def child(handle, _):
|
||||
@@ -143,31 +213,46 @@ def _process_windows(pids):
|
||||
if any(c['class'].casefold().startswith('richedit') for c in children):
|
||||
window['output'] = _native_output([window])
|
||||
result[pid].append(window)
|
||||
win32api.SetLastError(0)
|
||||
def incomplete():
|
||||
for pid in result:
|
||||
result[pid].append({'hwnd': 0, 'title': '窗口状态读取不完整', 'class': 'UNCONFIRMED',
|
||||
'enabled': False, 'children': []})
|
||||
try:
|
||||
win32gui.EnumWindows(capture, None)
|
||||
except Exception:
|
||||
incomplete()
|
||||
try:
|
||||
desktops = win32service.GetProcessWindowStation().EnumDesktops()
|
||||
except Exception:
|
||||
incomplete()
|
||||
threads = _process_threads(pids)
|
||||
except Exception as error:
|
||||
result.incomplete = {pid: str(error)[:500] for pid in pids}
|
||||
return result
|
||||
for name in desktops:
|
||||
if name != 'Default' and not name.startswith(('CbbVerify_', 'CbbRepair_', 'CbbManagement_', 'CbbStatusRead_', 'CbbFlagRead_')):
|
||||
continue
|
||||
desktops = {}
|
||||
for pid in pids:
|
||||
if not threads.get(pid):
|
||||
result.incomplete[pid] = '进程线程已退出或暂时无法读取'
|
||||
for tid in threads.get(pid, ()):
|
||||
try:
|
||||
desktop = _thread_desktop_name(tid)
|
||||
if desktop:
|
||||
desktops.setdefault(desktop, set()).add(pid)
|
||||
except Exception as error:
|
||||
result.incomplete.setdefault(pid, str(error)[:500])
|
||||
if not any(pid in members for members in desktops.values()):
|
||||
result.incomplete.setdefault(pid, '窗口所属桌面暂时无法确认')
|
||||
# EnumThreadWindows silently omits windows on other desktops. Enumerate
|
||||
# only desktops actually assigned to the target processes' threads.
|
||||
for name, members in desktops.items():
|
||||
desktop = None
|
||||
try:
|
||||
desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS)
|
||||
for hwnd in desktop.EnumDesktopWindows(): capture(int(hwnd), desktop_name=name)
|
||||
except Exception:
|
||||
incomplete()
|
||||
win32api.SetLastError(0)
|
||||
for hwnd in desktop.EnumDesktopWindows():
|
||||
pid = None
|
||||
try:
|
||||
pid = win32process.GetWindowThreadProcessId(hwnd)[1]
|
||||
if pid in members:
|
||||
capture(hwnd, None, pid=pid, desktop_name=name)
|
||||
except Exception as error:
|
||||
for affected in (members if pid is None else {pid} & members):
|
||||
result.incomplete.setdefault(affected, str(error)[:500])
|
||||
except Exception as error:
|
||||
for pid in members:
|
||||
result.incomplete.setdefault(pid, str(error)[:500])
|
||||
finally:
|
||||
if desktop is not None: desktop.CloseDesktop()
|
||||
if desktop is not None:
|
||||
desktop.CloseDesktop()
|
||||
return result
|
||||
|
||||
|
||||
@@ -183,8 +268,10 @@ def _project_name(row, library):
|
||||
return '当前库关联会话'
|
||||
|
||||
|
||||
def close_target(name, windows):
|
||||
def close_target(name, windows, *, incomplete=None):
|
||||
"""No save/restore approval and no close against an unknown modal/window."""
|
||||
if incomplete:
|
||||
return None, '该会话窗口读取不完整,请重新检查:'+str(incomplete)
|
||||
main = [w for w in windows if w['class'].startswith('Afx:') and (
|
||||
name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup')
|
||||
or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager')
|
||||
@@ -214,7 +301,9 @@ def close_target(name, windows):
|
||||
return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭')
|
||||
|
||||
|
||||
def _save_question(windows):
|
||||
def _save_question(windows, *, incomplete=None):
|
||||
if incomplete:
|
||||
return None
|
||||
for window in windows:
|
||||
text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static')
|
||||
buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']}
|
||||
@@ -226,8 +315,9 @@ def _save_question(windows):
|
||||
return None
|
||||
|
||||
|
||||
def _cancel_question(name, windows):
|
||||
if name.casefold() != 'icdbprojectbackup.exe' or native_activity(name, windows)['status'] != 'ACTIVE':
|
||||
def _cancel_question(name, windows, *, incomplete=None):
|
||||
if (name.casefold() != 'icdbprojectbackup.exe'
|
||||
or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'):
|
||||
return None
|
||||
candidates = []
|
||||
for window in windows:
|
||||
@@ -275,20 +365,23 @@ def inspect_residual_sessions(library, *, block_names=()):
|
||||
item['library'] = str(library)
|
||||
if runtime_writes and row['scope_confirmed']:
|
||||
item['runtime_phase'] = runtime_writes[0]['phase']
|
||||
item['block_names'] = list(blocks)
|
||||
error = _window_error(windows, row['pid'])
|
||||
item.update(windows_incomplete=bool(error), window_read_error=error)
|
||||
try:
|
||||
item.update(_process_identity(row))
|
||||
target, detail = close_target(row['name'], windows.get(row['pid'], [])) if row['scope_confirmed'] else (
|
||||
target, detail = close_target(row['name'], windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else (
|
||||
None, '归属未确认,请在原生窗口确认工程并关闭后重新检查')
|
||||
item.update(can_close=target is not None, detail=detail)
|
||||
except Exception as error:
|
||||
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{error}')
|
||||
except Exception as identity_error:
|
||||
item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{identity_error}')
|
||||
item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认'
|
||||
item['prompt'] = _save_question(windows.get(row['pid'], [])) if row['scope_confirmed'] else None
|
||||
item['prompt'] = _save_question(windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else None
|
||||
observed = windows.get(row['pid'], [])
|
||||
item['windows'] = observed
|
||||
item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')})
|
||||
item['native_activity'] = native_activity(row['name'], observed)
|
||||
item['cancel_prompt'] = (_cancel_question(row['name'], observed)
|
||||
item['native_activity'] = native_activity(row['name'], observed, incomplete=error)
|
||||
item['cancel_prompt'] = (_cancel_question(row['name'], observed, incomplete=error)
|
||||
if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None)
|
||||
if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']:
|
||||
item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作'
|
||||
@@ -321,7 +414,10 @@ def _request_close(row, *, stop=None):
|
||||
identity = _handle_identity(handle)
|
||||
if identity != {key: row.get(key) for key in ('created_handle', 'image')}:
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'}
|
||||
windows = _process_windows({row['pid']}).get(row['pid'], [])
|
||||
snapshot = _process_windows({row['pid']})
|
||||
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
|
||||
if error:
|
||||
return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error}
|
||||
if row['name'].casefold() == 'expeditionpcb.exe':
|
||||
from .failed_session import _startup_snapshot, _cancel_target
|
||||
for window in windows:
|
||||
@@ -335,10 +431,13 @@ def _request_close(row, *, stop=None):
|
||||
return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
windows = _process_windows({row['pid']}).get(row['pid'], [])
|
||||
snapshot = _process_windows({row['pid']})
|
||||
windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid'])
|
||||
if error:
|
||||
break
|
||||
if close_target(row['name'], windows)[0] is not None: break
|
||||
break
|
||||
target, detail = close_target(row['name'], windows)
|
||||
target, detail = close_target(row['name'], windows, incomplete=error)
|
||||
if target is None: return {'release_status': 'WAITING', 'detail': detail}
|
||||
if stop is not None and stop.is_set():
|
||||
return {'release_status': 'CANCELLED', 'detail': '已停止释放'}
|
||||
@@ -373,7 +472,9 @@ def _force_close(row, *, stop=None):
|
||||
if (not ownership['force_user_confirmed'] or
|
||||
any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))):
|
||||
return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'}
|
||||
activity = native_activity(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
|
||||
snapshot = _process_windows({row['pid']})
|
||||
activity = native_activity(row['name'], snapshot.get(row['pid'], []),
|
||||
incomplete=_window_error(snapshot, row['pid']))
|
||||
if reason := force_block_reason({**row, 'native_activity': activity}):
|
||||
return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity}
|
||||
if stop is not None and stop.is_set():
|
||||
@@ -403,7 +504,9 @@ def _request_native_cancel(row, *, stop=None):
|
||||
owner = _force_ownership(handle, row['pid'])
|
||||
if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')):
|
||||
raise ValueError('取消目标用户/会话已变化')
|
||||
prompt = _cancel_question(row['name'], _process_windows({row['pid']}).get(row['pid'], []))
|
||||
snapshot = _process_windows({row['pid']})
|
||||
prompt = _cancel_question(row['name'], snapshot.get(row['pid'], []),
|
||||
incomplete=_window_error(snapshot, row['pid']))
|
||||
if not prompt or prompt != row.get('cancel_prompt'):
|
||||
raise ValueError('原生取消按钮已变化,请重新检查')
|
||||
button = prompt['button']
|
||||
@@ -417,10 +520,29 @@ def _request_native_cancel(row, *, stop=None):
|
||||
|
||||
def request_native_cancel(row, library, evidence_dir, *, stop=None):
|
||||
# Reuse serialized admission, consent and incremental evidence for cancellation.
|
||||
plan = {'library': str(library), 'sessions': [row]}
|
||||
plan = {'library': str(library), 'sessions': [row], 'block_names': row.get('block_names', [])}
|
||||
return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True)
|
||||
|
||||
|
||||
def _session_evidence(row):
|
||||
"""Keep the full preview in memory, but bound repeatedly written Output."""
|
||||
value = dict(row)
|
||||
if 'native_activity' in value:
|
||||
value['native_activity'] = {k: v for k, v in value['native_activity'].items() if k != 'output'}
|
||||
if 'windows' in value:
|
||||
value['windows'] = []
|
||||
for window in row['windows']:
|
||||
saved = {k: window[k] for k in ('hwnd', 'title', 'class', 'desktop', 'enabled') if k in window}
|
||||
output = window.get('output')
|
||||
if isinstance(output, str):
|
||||
data = output.encode('utf-8')
|
||||
saved.update(output_excerpt=data[:4096].decode('utf-8', errors='ignore'),
|
||||
output_bytes=len(data), output_sha256=hashlib.sha256(data).hexdigest(),
|
||||
output_truncated=len(data) > 4096)
|
||||
value['windows'].append(saved)
|
||||
return value
|
||||
|
||||
|
||||
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])
|
||||
@@ -436,7 +558,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
from .management import _write_json
|
||||
try:
|
||||
result['report_saved'] = True
|
||||
_write_json(root/'result.json', result)
|
||||
_write_json(root/'result.json', {**result, 'sessions': [_session_evidence(row) for row in result['sessions']]})
|
||||
return True
|
||||
except OSError as error:
|
||||
result.update(status='PARTIAL', report_saved=False, evidence_error=str(error))
|
||||
@@ -447,7 +569,7 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
consent_path = root/'consent.json'
|
||||
consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library),
|
||||
'time_ns': time.time_ns(), 'sessions': [
|
||||
{**row, 'force_allowed': not force_block_reason(row),
|
||||
{**_session_evidence(row), 'force_allowed': not force_block_reason(row),
|
||||
'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True,
|
||||
'force_block_reason': force_block_reason(row)} for row in plan['sessions']]}
|
||||
try:
|
||||
@@ -501,10 +623,12 @@ def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, ca
|
||||
row.update(release_status='RELEASED', detail='已退出')
|
||||
elif row['release_status'] == 'WAITING':
|
||||
windows = remaining_windows.get(row['pid'], [])
|
||||
row.update(prompt=_save_question(windows), windows=windows,
|
||||
cancel_prompt=(_cancel_question(row['name'], windows)
|
||||
error = _window_error(remaining_windows, row['pid'])
|
||||
row.update(prompt=_save_question(windows, incomplete=error), windows=windows,
|
||||
windows_incomplete=bool(error), window_read_error=error,
|
||||
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))
|
||||
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()):
|
||||
result['proof'] = _finish_library_release(library, root/'library-proof')
|
||||
proof = result['proof']
|
||||
@@ -569,7 +693,8 @@ def _answer_save_question(row, choice):
|
||||
with _process_handle(row['pid']) as handle:
|
||||
if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}:
|
||||
raise ValueError('进程已变化,请重新检查')
|
||||
prompt = _save_question(_process_windows({row['pid']}).get(row['pid'], []))
|
||||
snapshot = _process_windows({row['pid']})
|
||||
prompt = _save_question(snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid']))
|
||||
if not prompt or prompt != row.get('prompt'):
|
||||
raise ValueError('原生提示已变化,请重新检查')
|
||||
button = prompt['buttons'][choice]
|
||||
|
||||
Reference in new issue
Block a user