Add real external desktop holder acceptance probe and evidence

This commit is contained in:
阿白叔 committed 2026-10-23 16:01:32 +08:00
1 parent ba5b13667b
commit 3c4e6e7e37
2 files changed
+169

No files matched your search

@@ -0,0 +1,27 @@
# Issue 3:外部 OpenDesktop 句柄实机验收
2026-10-23,在 Windows 本机运行 `python tools/probe_external_desktop_holder.py`,退出码为 0。探针使用真实 `BatchCadRuntime` / `PrivateDesktop`,只创建独立 Python 持有者,不启动 CAD,不打开工程,不执行替换。
真实证据保存在 `build/issue-3-external-holder/run-d0a0af0e6a154c65910fb5f29a645e61/evidence.json`,同时保留该目录下真实 `data/batch-resources/*/session.json`、`business-result.json` 和资源释放日志。每次运行创建全新的 `run-*` 目录,避免覆盖既有证据。
本次探针 PID 为 37744;桌面为 `dx-d346d3ab310f470c86ffd9d32ccbef4a`;独立持有者 PID 为 18136,使用 `OpenDesktop(..., DESKTOP_READOBJECTS)` 获得句柄 412。桌面所有者记录句柄 552 的创建与成功关闭,包含 PID 37744、原生线程 ID 22468。持有者仍在默认桌面,无测试窗口。
| 检查 | 实机结果 |
| --- | --- |
| 首次批次清理 | 自有桌面句柄关闭,但枚举仍发现桌面;等待 5 秒后 `blocked` |
| 残留窗口 | `remaining_windows=[]`,仍然阻断,没有据此推断资源已释放 |
| 持有者存活 | 首次失败与持有期间资源重试后,持有者均仍在运行 |
| 新批次门禁 | `BatchCadRuntime.__enter__` 抛出 `batch_resources_pending`;候选批次 generation=0,未创建桌面 |
| 持有中仅重试资源 | `cleanup_pending_resources` 再次确认阻断,没有启动 CAD 或业务操作 |
| 持有者自行释放 | 通过探针持有的 stdin 发送 `release`;持有者调用 `CloseDesktop`,正常退出码 0 |
| 释放后仅重试资源 | `cleanup_pending_resources` 返回空元组,session 状态为 `released`,桌面枚举确认消失 |
| 业务结果 | 合成的已核验 `business-result.json` 逐字节保持一致;内存业务结果亦保持一致 |
| CAD 与重放 | CAD 工厂调用次数 0;`cad_start_requested=false`、`cad_pid=null`、`processes=[]`;没有业务重放入口调用 |
| 输入桌面 | 前后一致,未切换输入桌面 |
| 释放后的准入 | 后续批次可通过准入检查,但探针不启动其桌面/CAD或业务 |
业务结果前后 SHA256 均为 `80507674ce6b5c1d11419bd6e7b2fdfea3c5a6697cb01d628abf232615e9dc7e`。本轮总耗时 10.609 秒,主要为两次有界的 5 秒释放确认。
诊断中的外部持有者仍为 `unknown`,未识别具体外部句柄持有 PID。上述 PID 18136 仅由探针自身创建进程返回值与辅助进程握手确认,不能视为产品诊断识别能力。空窗口列表也不能证明没有外部句柄持有者。
这轮覆盖的是资源门禁与资源清理 API 的真实 Windows 句柄路径。业务结果是独立合成验收夹具,不等同于真实 CAD 工程结果,也不替代打包 EXE 的交互验收。未修改 `src`。
+142
View File
@@ -0,0 +1,142 @@
"""Windows-only real external OpenDesktop reference acceptance (never starts CAD)."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
from uuid import uuid4
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from dx_productivity.trial_task_center.batch_resources import (
BatchResourceCleanupError, cleanup_pending_resources, pending_resources,
)
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.cad_identity import current_desktop_name
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
HOLDER = '''import json,os,sys,win32service
handle=win32service.OpenDesktop(sys.argv[1],0,False,1)
print(json.dumps({'state':'holding','pid':os.getpid(),'handle':int(handle)}),flush=True)
assert sys.stdin.readline().strip()=='release'
handle.CloseDesktop()
print(json.dumps({'state':'released','pid':os.getpid()}),flush=True)
'''
def probe(output):
if os.name != 'nt':
raise RuntimeError('Windows is required')
output = Path(output).resolve() / ('run-' + uuid4().hex)
root = output / 'data'
output.mkdir(parents=True)
started = time.monotonic()
before_desktop = current_desktop_name()
cad_requests = []
def forbidden_cad(*args, **kwargs):
cad_requests.append(True)
raise AssertionError('This resource-only probe must not create CAD')
runtime = BatchCadRuntime(root, 'external_holder_acceptance', cad_factory=forbidden_cad)
runtime.__enter__()
desktop = runtime._ensure_desktop()
result_path = runtime.path.parent / 'business-result.json'
original_result = {'kind': 'acceptance_fixture', 'status': 'verified',
'completed': True, 'saved_projects': 0, 'note': 'Synthetic result, no CAD/project operation'}
original_bytes = json.dumps(original_result, ensure_ascii=False, indent=2).encode('utf-8')
result_path.write_bytes(original_bytes)
runtime.result = original_result
digest = hashlib.sha256(original_bytes).hexdigest()
holder = None
report = {'version': 1, 'probe_pid': os.getpid(), 'desktop': desktop.name,
'result_sha256_before': digest, 'events': [], 'cad_requests': cad_requests,
'holder_identification': {'diagnostics_identified_external_handle_holder': False,
'external_handle_holders': 'unknown',
'fixture_pid_source': 'PID returned by subprocess.Popen and confirmed by fixture handshake; not inferred from diagnostics'}}
try:
holder = subprocess.Popen((sys.executable, '-u', '-c', HOLDER, desktop.name),
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding='utf-8', creationflags=subprocess.CREATE_NO_WINDOW)
handshake = json.loads(holder.stdout.readline())
assert handshake['pid'] == holder.pid and handshake['state'] == 'holding'
report['holder_fixture'] = handshake
try:
runtime.close()
raise AssertionError('cleanup incorrectly succeeded with external holder')
except BatchResourceCleanupError as failure:
assert failure.completed_result == original_result
report['events'].append({'phase': 'initial_cleanup', 'blocked': True,
'error': str(failure), 'holder_still_running': holder.poll() is None})
assert holder.poll() is None
blocked = pending_resources(root)
assert len(blocked) == 1 and blocked[0]['state'] == 'blocked'
assert blocked[0]['cleanup']['desktop_confirmation']['remaining_windows'] == []
assert blocked[0]['cleanup']['desktop_handle_closed']
report['blocked_resource_record'] = blocked[0]
candidate = BatchCadRuntime(root, 'must_be_blocked', cad_factory=forbidden_cad)
try:
candidate.__enter__()
raise AssertionError('new batch bypassed pending resource guard')
except BatchResourceCleanupError as failure:
report['events'].append({'phase': 'new_batch', 'blocked': True, 'error': str(failure)})
assert candidate.generation == 0 and candidate.desktop is None
pending = cleanup_pending_resources(root)
assert pending and pending[0]['state'] == 'blocked' and holder.poll() is None
report['events'].append({'phase': 'resource_only_retry_while_held',
'blocked': True, 'holder_still_running': True})
assert result_path.read_bytes() == original_bytes
holder.stdin.write('release\n')
holder.stdin.flush()
released = json.loads(holder.stdout.readline())
assert released['state'] == 'released' and released['pid'] == holder.pid
assert holder.wait(timeout=5) == 0
remaining = cleanup_pending_resources(root)
assert remaining == ()
final = json.loads(runtime.path.read_text(encoding='utf-8'))
assert final['state'] == 'released'
assert final['cad_pid'] is None and final['cad_start_requested'] is False
assert final['processes'] == [] and cad_requests == []
assert result_path.read_bytes() == original_bytes and runtime.result == original_result
assert current_desktop_name() == before_desktop
listed = _Win32Api().service.GetProcessWindowStation().EnumDesktops()
assert desktop.name.casefold() not in {name.casefold() for name in listed}
# Admission may be checked again, but no batch resources or business work
# are started by this independent acceptance probe.
with BatchCadRuntime(root, 'post_release_admission', cad_factory=forbidden_cad) as admitted:
assert admitted.generation == 0 and admitted.desktop is None
report.update(success=True, final_resource_record=final,
result_sha256_after=hashlib.sha256(result_path.read_bytes()).hexdigest(),
business_result_unchanged=True, cad_started=False, business_replayed=False,
desktop_released=True, input_desktop_unchanged=True,
elapsed_seconds=time.monotonic() - started)
report['events'].append({'phase': 'resource_only_retry_after_holder_release',
'released': True, 'business_result_unchanged': True})
except Exception as failure:
report.update(success=False, failure=repr(failure))
raise
finally:
if holder is not None:
if holder.poll() is None:
# Only this explicitly created helper may be stopped on probe failure.
holder.terminate()
holder.wait(timeout=5)
for stream in (holder.stdin, holder.stdout, holder.stderr):
if stream is not None:
stream.close()
try:
runtime.close(reason='probe_finally')
finally:
(output / 'evidence.json').write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding='utf-8')
return output / 'evidence.json'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, default=Path('build/issue-3-external-holder'))
args = parser.parse_args()
print(probe(args.output))