Files
dxdesigner-part-replacement/tools/probe_external_desktop_holder.py
T

197 lines
11 KiB
Python

"""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, blocking_resources,
process_identity, write_record,
)
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.batch_worker import _wait_for_owned_writes
from dx_productivity.trial_task_center.cad_identity import current_desktop_name
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
from dx_productivity.trial_task_center.stop_control import StopControl
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
runtime.close()
report['events'].append({'phase': 'initial_cleanup', 'blocked': False,
'state': runtime.record['state'], 'holder_still_running': holder.poll() is None})
assert holder.poll() is None
blocked = pending_resources(root)
assert len(blocked) == 1 and blocked[0]['state'] == 'isolated' and not blocking_resources(root)
assert blocked[0]['blocking'] is False and blocked[0]['release_results']['desktop_released'] is False
assert blocked[0]['cleanup']['desktop_confirmation']['remaining_windows'] == []
assert blocked[0]['cleanup']['desktop_handle_closed']
report['isolated_resource_record'] = blocked[0]
# A synthetic persistent claim with an actual live owned helper proves
# that neither the isolated label nor a forged exit flag opens the gate.
active = subprocess.Popen((sys.executable, '-c', 'import sys;sys.stdin.readline()'),
stdin=subprocess.PIPE, creationflags=subprocess.CREATE_NO_WINDOW)
try:
active_identity = process_identity(active)
active_root = output / 'active-writer-data'
active_session = uuid4().hex
active_path = active_root / 'batch-resources' / active_session / 'session.json'
active_record = dict(blocked[0], session_id=active_session,
writer_identities=[active_identity], processes=[active_identity])
active_record.pop('record_path', None)
active_record['isolation_proof'] = dict(active_record['isolation_proof'],
session_id=active_session, processes=[active_identity])
write_record(active_path, active_record)
assert blocking_resources(active_root)
assert cleanup_pending_resources(active_root) and blocking_resources(active_root)
assert active.poll() is None
report['active_writer_gate'] = {'process': active_identity, 'blocked': True,
'record_fixture': 'synthetic isolated claim; real owned helper remains alive'}
finally:
active.stdin.write(b'release\n')
active.stdin.flush()
active.wait(timeout=5)
active.stdin.close()
assert not blocking_resources(active_root) # Exact recorded process has now exited.
candidate = BatchCadRuntime(root, 'fresh_batch', cad_factory=forbidden_cad)
with candidate:
fresh = candidate._ensure_desktop()
assert fresh.name == desktop.name
report['fresh_desktop'] = fresh.name
report['events'].append({'phase': 'new_batch', 'blocked': False, 'managed_desktop_reused': True})
restart_code = '''import json,sys
from pathlib import Path
sys.path.insert(0,sys.argv[2])
from dx_productivity.trial_task_center.batch_resources import cleanup_pending_resources,blocking_resources
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
root=Path(sys.argv[1])
rows=cleanup_pending_resources(root)
assert rows and all(row['state']=='isolated' and row['blocking'] is False for row in rows)
assert not blocking_resources(root)
with BatchCadRuntime(root,'restart_admission') as runtime:
desktop=runtime._ensure_desktop()
assert desktop.name == rows[0]['desktop']
print(json.dumps({'restart_isolation_validated':True,'fresh_desktop':desktop.name}))
'''
restarted = subprocess.run((sys.executable, '-c', restart_code, str(root),
str(Path(__file__).resolve().parents[1] / 'src')), capture_output=True, text=True,
encoding='utf-8', timeout=30, creationflags=subprocess.CREATE_NO_WINDOW)
assert restarted.returncode == 0, restarted.stderr
report['restart'] = json.loads(restarted.stdout.strip())
cleanup_error = _wait_for_owned_writes(runtime, StopControl())
assert cleanup_error is None
assert runtime.owned_processes_exited() and holder.poll() is None
assert runtime.record['state'] == 'isolated' and result_path.read_bytes() == original_bytes
report['events'].append({'phase': 'worker_exit_resource_recheck',
'error_returned': False, 'owned_writers_exited': True,
'holder_still_running': True, 'resource_state': runtime.record['state']})
pending = cleanup_pending_resources(root)
assert pending and pending[0]['state'] == 'isolated' and holder.poll() is None
assert not blocking_resources(root)
close_history = runtime.record['cleanup']['desktop_handle_history']
assert len([event for event in close_history if event['operation'] == 'close']) == 1
report['events'].append({'phase': 'resource_only_retry_while_held',
'blocked': False, 'holder_still_running': True, 'owned_desktop_handle_closed_once': 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))