Merge branch 'codex/review-residual-release' into codex/runtime-lifecycle-safety

# Conflicts:
#	src/cbb_refresh_verify/residual_sessions.py
This commit is contained in:
阿白叔 committed 2026-11-09 10:41:24 +08:00
commit b1c36e3ca6
8 files changed
+466 -51

No files matched your search

@@ -0,0 +1,7 @@
# PR #10 comment 309
Release proof now records the requested CBB, effective BLOCK/LIBRARY proof scope, identities/statuses of archived checkpoints and retained owners, and `reconciled_foreign_blockers`. For example, a BlockA operation which safely reconciles BlockB's historical checkpoint explicitly lists BlockB and the full-library proof. `data_recovery_confirmed` remains false. No extra gate, automatic backup or native action was added.
Three regressions first failed on missing evidence fields. After the fix, 94 backend/lease/release regressions passed; compileall and git diff --check passed. The tests use real temporary file/lease handles with the process-query boundary replaced; no production library was opened. Full regression is run again at the integrated chain tip. Real Mentor/shared-network acceptance and a rebuilt package remain outstanding.
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/10#issuecomment-309
@@ -0,0 +1,21 @@
# PR #12 comment 313
## Behavior
Window inspection takes a Windows thread snapshot for the requested processes, finds the desktops assigned to those threads, and opens only those desktops. Failures are recorded per affected PID outside the real window list. Unrelated inaccessible desktops no longer disable healthy rows. Preview, cooperative close, forced close, native Cancel and save-prompt responses all use the same per-PID incomplete-read fact during their fresh action-time observation.
Unknown or active native writes still prohibit forced termination. The review's suggested blanket force override for unreadable windows is not implemented: exact identity and private-desktop ownership do not establish that Save/Repair has returned. A failed read names that session and can be retried, while other sessions remain actionable.
Disk evidence retains window identity and a UTF-8 output excerpt of at most 4,096 bytes, original output length and SHA-256. It omits child-control trees and duplicated native-activity output. The complete preview remains in memory for the existing details action.
Native Cancel carries the preview's `block_names` and checks the same Work + SymbolLibs scope before the exact-process/control checks. It no longer silently widens a scoped preview to the full library.
## Verification
The initial five regressions failed against the old implementation. After the fix, 116 residual/backend/UI/background-queue regressions passed; compileall and git diff --check passed. This includes a real controlled Windows window on a private CbbManagement desktop, read from another process, with clean fixture exit and no Mentor/native database actions.
The real fixture caught a platform limitation missed by API doubles: EnumThreadWindows silently omits windows on another desktop. The final implementation maps threads to desktop names and uses OpenDesktop/EnumDesktopWindows for only those mapped desktops. GetThreadDesktop's borrowed handle is never closed; owned OpenDesktop handles and the thread snapshot are closed.
Independent review and the full integrated-chain run are recorded at the final PR #13 tip. Older deep-review comments #297-#300 remain outside this explicitly selected scope. No candidate was rebuilt; real Mentor, Windows 10 and shared/network release scenarios remain unverified.
Review: https://git.simgreek.com/Skyworth_Digital_Hardware/cbb-refresh-verify-795/pulls/12#issuecomment-313
@@ -0,0 +1,25 @@
# Latest reviews for PR #10/#11/#12
Scope: user selected only the 2026-11-09 comments #309/#310/#313. Earlier deep-review backlog stays out of scope. Preserve ICDB automatic Repair OFF, serial writes, current icon and independent-library admission. No merge to main, issue closure or release.
## PR #10
- [ ] Reproduce BlockA releasing historical BlockB checkpoints and retained owners without naming BlockB in proof.
- [ ] Record requested block, actual proof scope, checkpoint identities and foreign names in existing release proof. Preserve original checkpoint bytes and data_recovery_confirmed=False; no new blocking gate.
- [ ] Run backend/lease regressions, compile/diff checks, commit on codex/review-native-backend.
## PR #11/#12
- [ ] Forward-merge backend into UI, then UI into residual branch; no history rewriting.
- [ ] Test one unreadable process/thread not affecting another, without fabricated modal windows; cover preview and action-time rechecks.
- [ ] Enumerate only target-process threads/windows, store incomplete-read metadata per PID. Keep unknown/active writers protected rather than adding a blind force override.
- [ ] Persist window identities and at most a 4 KiB output excerpt, preserve full preview in memory, stop duplicating activity output.
- [ ] Carry exact preview block scope into native Cancel and recheck identity/scope before clicking.
- [ ] Run residual/UI regressions, compile/diff checks, commit on residual branch.
## Chain tip
- [ ] Merge residual fixes into PR #13, preserving ca39fb3 and icon.
- [ ] Address #11's line-ending note once at the tip: application.py to LF; pin it and main_window.py in EditorConfig. Preserve all other file endings and the global * -text rule.
- [ ] Independent review, integrated full suite, compile/diff checks, validation records and fast-forward pushes to existing PR branches.
- [ ] Update PR descriptions with precise results and no new package/native acceptance. Leave #3 as historical umbrella, without merging or closing it.
+13
View File
@@ -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')
+173 -48
View File
@@ -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]
+4 -3
View File
@@ -334,11 +334,12 @@ def test_partial_desktop_enumeration_never_offers_normal_close(monkeypatch):
def failed(*_): raise OSError('desktop disappeared')
monkeypatch.setattr(win32gui, 'EnumWindows', failed)
monkeypatch.setattr(win32service, 'GetProcessWindowStation', lambda: SimpleNamespace(EnumDesktops=lambda: []))
windows = _process_windows({10})[10]
assert any(w['class'] == 'UNCONFIRMED' for w in windows)
snapshot = _process_windows({10})
windows = snapshot[10]
assert snapshot.incomplete[10]
windows.append({'hwnd': 100, 'class': 'Afx:main', 'title': 'Design - Expedition PCB',
'children': [], 'enabled': True})
assert close_target('ExpeditionPCB.exe', windows)[0] is None
assert close_target('ExpeditionPCB.exe', windows, incomplete=snapshot.incomplete[10])[0] is None
@pytest.mark.parametrize('choice', [6, 7, 2])
+171
View File
@@ -0,0 +1,171 @@
from contextlib import nullcontext
import json
import sys
import time
from pathlib import Path
from types import SimpleNamespace
from uuid import uuid4
import pytest
from cbb_refresh_verify import residual_sessions as sessions
from test_residual_sessions import row, OWNERSHIP
def window():
return dict(hwnd=100, title='Design - Expedition PCB', desktop='Default',
**{'class': 'Afx:main'}, enabled=True, children=[], documents=[])
class PartialWindows(dict):
incomplete = {10: 'target thread inaccessible'}
def test_thread_read_failure_does_not_poison_another_process(monkeypatch):
import win32gui, win32process, win32service
def global_failure(*args):
raise OSError('an unrelated desktop is inaccessible')
monkeypatch.setattr(win32gui, 'EnumWindows', global_failure)
monkeypatch.setattr(win32service, 'GetProcessWindowStation',
lambda: SimpleNamespace(EnumDesktops=lambda: ['Default', 'CbbManagement_Unrelated']))
monkeypatch.setattr(sessions, '_process_threads', lambda _: {10: [100], 20: [200]}, raising=False)
monkeypatch.setattr(sessions, '_thread_desktop_name',
lambda tid: 'Default' if tid == 100 else 'CbbManagement_Broken', raising=False)
def open_desktop(name, *args):
if name == 'CbbManagement_Broken':
raise PermissionError('only process 20 is unreadable')
assert name == 'Default', 'an unrelated desktop must not be inspected'
return SimpleNamespace(EnumDesktopWindows=lambda: [1000], CloseDesktop=lambda: None)
monkeypatch.setattr(win32service, 'OpenDesktop', open_desktop)
monkeypatch.setattr(win32process, 'GetWindowThreadProcessId', lambda _: (100, 10))
monkeypatch.setattr(win32gui, 'IsWindowVisible', lambda _: True)
monkeypatch.setattr(win32gui, 'EnumChildWindows', lambda *args: None)
monkeypatch.setattr(win32gui, 'GetWindowText', lambda _: 'Design - Expedition PCB')
monkeypatch.setattr(win32gui, 'GetClassName', lambda _: 'Afx:main')
monkeypatch.setattr(win32gui, 'IsWindowEnabled', lambda _: True)
monkeypatch.setattr(win32gui, 'GetWindowRect', lambda _: (0, 0, 100, 100))
result = sessions._process_windows({10, 20})
assert [w['hwnd'] for w in result[10]] == [1000]
assert 10 not in result.incomplete and 'unreadable' in result.incomplete[20]
assert result[20] == [], 'a read error must not be represented as a native modal window'
assert sessions.close_target('ExpeditionPCB.exe', result[10])[0]
def test_preview_exposes_only_target_process_incomplete_state(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/{pid}.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
monkeypatch.setattr(sessions, '_process_identity', lambda r: dict(created_handle='creation',
image=r['executable'], **OWNERSHIP))
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()], 20: [window()]}))
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert affected['windows_incomplete'] and not affected['can_close'] and not affected['force_allowed']
assert affected['native_activity']['status'] == 'UNCONFIRMED'
assert '读取' in affected['detail'] and '弹窗' not in affected['detail']
assert healthy['can_close'] and healthy['force_allowed']
def test_action_rechecks_incomplete_read_before_force_termination(monkeypatch):
import win32api, win32con, win32event
process = dict(row(10, 'C:/library/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True, **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_handle', lambda *a, **kw: nullcontext(123))
monkeypatch.setattr(sessions, '_handle_identity', lambda _: {k: process[k] for k in ('created_handle', 'image')})
monkeypatch.setattr(sessions, '_force_ownership', lambda *args: dict(OWNERSHIP))
monkeypatch.setattr(win32event, 'WaitForSingleObject', lambda *args: win32con.WAIT_TIMEOUT)
monkeypatch.setattr(sessions, '_process_windows', lambda _: PartialWindows({10: [window()]}))
monkeypatch.setattr(win32api, 'TerminateProcess', lambda *args: pytest.fail('unreadable target was ended'))
result = sessions._force_close(process)
assert result['release_status'] == 'WAITING' and result['native_activity']['status'] == 'UNCONFIRMED'
def test_identity_read_failure_keeps_the_other_preview_row_available(tmp_path, monkeypatch):
library = tmp_path/'lib.lmc'; library.touch()
processes = [row(pid, tmp_path/f'ReusableBlocksLP/{pid}/Work/A.prj', name='ExpeditionPCB.exe')
for pid in (10, 20)]
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: processes)
def identity(process):
if process['pid'] == 10:
raise PermissionError('token inaccessible')
return dict(created_handle='creation', image=process['executable'], **OWNERSHIP)
monkeypatch.setattr(sessions, '_process_identity', identity)
monkeypatch.setattr(sessions, '_process_windows', lambda _: {pid: [window()] for pid in (10, 20)})
affected, healthy = sessions.inspect_residual_sessions(library)['sessions']
assert not affected['force_allowed'] and 'token inaccessible' in affected['detail']
assert healthy['force_allowed'] and healthy['can_close']
def test_native_cancel_retains_exact_preview_scope(tmp_path, monkeypatch):
from cbb_refresh_verify import library_lock
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj'),
scope_confirmed=True, block_names=['A'], cancel_prompt={'hwnd': 100})
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
expected = (library.parent/'ReusableBlocksLP/A/Work', library.parent/'SymbolLibs')
def scoped(actual, selected_library, roots):
assert roots == expected, 'Cancel widened the scope from its preview'
return True
monkeypatch.setattr(library_lock, '_owner_matches_scope', scoped)
monkeypatch.setattr(sessions, '_request_native_cancel', lambda *a, **kw:
dict(release_status='WAITING', detail='cancel requested'))
result = sessions.request_native_cancel(process, library, tmp_path/'evidence')
assert result['sessions'][0]['detail'] == 'cancel requested'
def test_persisted_release_evidence_is_bounded_without_changing_preview(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'; library.parent.mkdir(); library.touch()
output = '原生输出' * 100000
observed = dict(window(), output=output, children=[dict(text=output, **{'class': 'RichEdit'})])
process = dict(row(10, library.parent/'ReusableBlocksLP/A/Work/A.prj', name='ExpeditionPCB.exe'),
created_handle='creation', image='C:/Mentor/ExpeditionPCB.exe', scope_confirmed=True,
windows=[observed], native_activity={'status': 'IDLE', 'output': output}, **OWNERSHIP)
monkeypatch.setattr(sessions, 'query_process_snapshot', lambda: [process])
monkeypatch.setattr(sessions, '_process_windows', lambda _: {})
monkeypatch.setattr(sessions, '_force_close', lambda *a, **kw: dict(release_status='RELEASED', detail='ended'))
monkeypatch.setattr(sessions, '_finish_library_release', lambda *args:
dict(status='RELEASE_CONFIRMED', library=str(library)))
result = sessions.release_residual_sessions(dict(library=str(library), sessions=[process]),
tmp_path/'evidence', force=True)
assert result['status'] == 'RELEASE_CONFIRMED'
for path in (Path(result['evidence_path']), Path(result['consent_path'])):
assert path.stat().st_size < 20000
saved = json.loads(path.read_text('utf-8'))['sessions'][0]
assert 'output' not in saved['native_activity']
assert 'children' not in saved['windows'][0] and 'output' not in saved['windows'][0]
assert len(saved['windows'][0]['output_excerpt'].encode('utf-8')) <= 4096
assert saved['windows'][0]['output_truncated'] is True
assert process['windows'][0]['output'] == output
def test_real_private_desktop_is_read_through_its_process_threads(tmp_path):
from cbb_refresh_verify.desktop_worker import DesktopWorker
ready, stop = tmp_path/'ready.json', tmp_path/'stop'
script = tmp_path/'window.py'
name = 'CbbManagement_Review_'+uuid4().hex[:10]
script.write_text('import json,time,win32api,win32con,win32gui\nfrom pathlib import Path\n'
'wc=win32gui.WNDCLASS()\nwc.hInstance=win32api.GetModuleHandle(None)\n'
'wc.lpszClassName="CbbReviewWindow"\nwc.lpfnWndProc=win32gui.DefWindowProc\n'
'atom=win32gui.RegisterClass(wc)\n'
'hwnd=win32gui.CreateWindow(atom,"Controlled review fixture",'
'win32con.WS_OVERLAPPEDWINDOW|win32con.WS_VISIBLE,0,0,300,200,0,0,wc.hInstance,None)\n'
f'Path({str(ready)!r}).write_text(json.dumps(dict(hwnd=hwnd)))\n'
f'while not Path({str(stop)!r}).exists():\n'
' win32gui.PumpWaitingMessages();time.sleep(.02)\n'
'win32gui.DestroyWindow(hwnd)\n', encoding='utf-8')
worker = DesktopWorker([sys.executable, str(script)], name)
try:
deadline = time.monotonic()+8
while not ready.exists() and worker.poll() is None and time.monotonic()<deadline:
time.sleep(.02)
assert ready.exists()
hwnd = json.loads(ready.read_text())['hwnd']
snapshot = sessions._process_windows({worker.pid})
assert worker.pid not in snapshot.incomplete, snapshot.incomplete
target = next(w for w in snapshot[worker.pid] if w['hwnd'] == hwnd)
assert target['desktop'] == name and target['title'] == 'Controlled review fixture'
finally:
stop.touch()
worker.wait(5)
worker.close()
@@ -0,0 +1,52 @@
import json
from pathlib import Path
import pytest
from cbb_refresh_verify import library_lock as locks
@pytest.mark.parametrize('retained_owner', [False, True])
def test_releasing_another_blocks_checkpoint_names_its_owner(tmp_path, monkeypatch, retained_owner):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
lease = None
if retained_owner:
with locks.LibraryLock(library, block_name='BlockB', safe_to_release=lambda: False) as lease:
pass
else:
locks._persist_blocker(library, lease_id='b'*32, block_name='BlockB')
before = locks.blocker_path(library).read_bytes()
try:
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['requested_block_name'] == 'BlockA'
assert proof['proof_scope'] == 'LIBRARY'
assert proof['reconciled_foreign_blockers'] == ['BlockB']
assert proof['data_recovery_confirmed'] is False
checkpoint = next(r for r in proof['reconciled_checkpoints'] if r['kind'] == 'checkpoint')
assert checkpoint['block_name'] == 'BlockB' and checkpoint['status'] == 'OWNER_RELEASE_UNCONFIRMED'
assert checkpoint['lease_id']
proof_path = Path(proof['evidence_path'])
assert json.loads(proof_path.read_text('utf-8'))['reconciled_foreign_blockers'] == ['BlockB']
assert (proof_path.parent/'blocker-before-0.json').read_bytes() == before
assert not locks.blocker_path(library).exists()
if retained_owner:
assert any(r['kind'] == 'retained_owner' and r['block_name'] == 'BlockB'
for r in proof['reconciled_checkpoints'])
finally:
if lease:
with locks._guard:
owner = locks._owners.pop(lease.key, None)
if owner:
owner['handle'].Close()
def test_matching_checkpoint_uses_block_scope_without_foreign_targets(tmp_path, monkeypatch):
library = tmp_path/'library/lib.lmc'
library.parent.mkdir(); library.touch()
monkeypatch.setattr('cbb_refresh_verify.owner_probe.query_owners', lambda *_: [])
locks._persist_blocker(library, lease_id='a'*32, block_name='BlockA')
proof = locks.release_retained_library(library, tmp_path/'evidence', block_name='BlockA')
assert proof['proof_scope'] == 'BLOCK' and proof['proof_block_name'] == 'BlockA'
assert proof['reconciled_foreign_blockers'] == []