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

+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'] == []