fix(runtime): block identity replay and retain generation release proof

This commit is contained in:
阿白叔 committed 2026-10-21 15:45:09 +08:00
1 parent 486ea05ad5
commit a8358d90d7
4 files changed
+169 -21

No files matched your search

@@ -213,7 +213,7 @@ class BatchCadRuntime:
def run_worker(self, command, timeout, *, abort_event=None, cooperative_abort=False):
from .discovery_cache import project_fingerprint
from .isolated_cad import PrivateCadStartupError
from .isolated_cad import PrivateCadStartupError, is_identity_conflict
from .worker_monitor import run_monitored_process
root = Path(command[3]).resolve()
self._ensure_desktop(abort_event)
@@ -254,7 +254,7 @@ class BatchCadRuntime:
status_after = status.read_bytes() if status.exists() else None
# Runtime database changes require separate identity evidence. Until
# available for a failed read, use the stricter full fingerprint.
safe = (before is not None and before == after
safe = (not is_identity_conflict(failure) and before is not None and before == after
and status_before == status_after and self._can_retry(project, expected)
and not (root / 'recovery.request').exists()
and not (abort_event is not None and abort_event.is_set())
@@ -334,5 +334,10 @@ class BatchCadRuntime:
if errors:
self._save(state='blocked', error='; '.join(errors))
raise BatchResourceCleanupError('; '.join(errors), completed_result=self.result)
self._save(state='released', released_at=time.time(), processes=[])
released_at = time.time()
release = {'generation': self.generation, 'desktop': self.record['desktop'],
'cad_pid': self.record['cad_pid'], 'cad_guid': self.record['cad_guid'],
'cleanup': self.record['cleanup'], 'released_at': released_at}
releases = [*self.record.get('generation_releases', ()), release]
self._save(state='released', released_at=released_at, processes=[], generation_releases=releases)
LIVE_RESOURCES.pop(str(self.path), None)
@@ -18,6 +18,34 @@ class PrivateCadStartupError(WorkerMonitorError):
"""The owned desktop was released before any project worker was launched."""
class CadIdentityConflict(WorkerMonitorError, ValueError):
"""An invalid CAD ownership certificate can never authorize automatic replay."""
class PrivateCadIdentityError(PrivateCadStartupError, CadIdentityConflict):
"""Startup ownership failed, and its local resources were released."""
PRIVATE_CAD_IDENTITY_EXIT_CODE = 4
def is_identity_conflict(error):
"""Keep the no-retry decision when cleanup or evidence I/O wraps the cause."""
pending, seen = [error], set()
while pending:
item = pending.pop()
if item is None or id(item) in seen:
continue
seen.add(id(item))
# The legacy VBS launcher transports these ownership failures as exit
# 2 plus text. Treat only its explicit identity diagnostics as conflicts.
if (isinstance(item, CadIdentityConflict) or any(message in str(item).casefold()
for message in ('incomplete private cad identity', 'private cad guid mismatch'))):
return True
pending.extend((item.__cause__, item.__context__))
return False
def _helper_command(action, evidence, pid):
if getattr(sys, 'frozen', False):
return (sys.executable, '--private-cad-action', action, '--private-cad-evidence', str(evidence),
@@ -111,13 +139,19 @@ class IsolatedCadSession:
time.sleep(0.05)
code = probe.poll()
if code:
raise WorkerMonitorError('private CAD startup identity failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
raise failure_type('private CAD startup failed: ' + probe.stderr.read().decode('utf-8', errors='replace'))
finally:
probe.close()
result = json.loads(bootstrap.read_text(encoding='utf-8'))
self.binding = CadBinding(**result)
if (self.binding.pid, self.binding.desktop, self.binding.token) != (self.cad.pid, self.desktop.name, self.token):
raise WorkerMonitorError('private CAD bootstrap returned a foreign identity')
try:
result = json.loads(bootstrap.read_text(encoding='utf-8'))
binding = CadBinding(**result)
if (type(binding.pid) is not int or not isinstance(binding.guid, str) or not binding.guid
or (binding.pid, binding.desktop, binding.token) != (self.cad.pid, self.desktop.name, self.token)):
raise ValueError('private CAD bootstrap returned a foreign identity')
except (OSError, ValueError, TypeError) as failure:
raise CadIdentityConflict('private CAD bootstrap identity evidence is invalid: ' + str(failure)) from failure
self.binding = binding
self._record(state='ready', guid=self.binding.guid, startup_seconds=time.monotonic() - self.started)
return self
except Exception as error:
@@ -127,6 +161,8 @@ class IsolatedCadSession:
self._uncertain('startup cleanup failed: ' + str(failure))
raise WorkerMonitorError('private CAD startup cleanup requires reconciliation: ' + str(failure)) from error
self._record(state='released', clean=False, startup_error=str(error))
if is_identity_conflict(error):
raise PrivateCadIdentityError(str(error)) from error
raise PrivateCadStartupError(str(error)) from error
def _check_abort(self):
@@ -153,13 +189,20 @@ class IsolatedCadSession:
process = self.start_worker(_helper_command('checkpoint', evidence, self.cad.pid),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
if process.wait(timeout=20):
raise WorkerMonitorError('project close checkpoint failed: ' +
code = process.wait(timeout=20)
if code:
failure_type = CadIdentityConflict if code == PRIVATE_CAD_IDENTITY_EXIT_CODE else WorkerMonitorError
raise failure_type('project close checkpoint failed: ' +
process.stderr.read().decode('utf-8', errors='replace'))
result = json.loads(evidence.read_text(encoding='utf-8'))
if (result.get('binding') != asdict(self.binding) or result.get('project_path') != ''
or result.get('project_closed') is not True or self.cad.poll() is not None):
raise WorkerMonitorError('project close checkpoint identity mismatch')
try:
result = json.loads(evidence.read_text(encoding='utf-8'))
if (not isinstance(result, dict) or result.get('binding') != asdict(self.binding)
or result.get('project_path') != '' or result.get('project_closed') is not True):
raise ValueError('project close checkpoint identity mismatch')
except (OSError, ValueError, TypeError) as failure:
raise CadIdentityConflict('project close checkpoint identity evidence is invalid: ' + str(failure)) from failure
if self.cad.poll() is not None:
raise WorkerMonitorError('owned CAD exited during project checkpoint')
finally:
process.close()
return result
@@ -228,6 +271,8 @@ def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abor
with IsolatedCadSession(Path(command[3]), abort_event=abort_event) as session:
return run_monitored_process(command, timeout, abort_event=abort_event, process_factory=session.start_worker,
**({'cooperative_abort': True} if cooperative_abort else {}))
except CadIdentityConflict:
raise
except PrivateCadStartupError as error:
# The existing handoff recognizes exit=2 with unchanged status as a
# retryable pre-mutation startup failure, without an uncertainty lock.
@@ -235,6 +280,14 @@ def run_isolated_process(command, timeout, *, abort_event=None, cooperative_abor
def native_action(action, evidence, expected_pid):
try:
return _run_native_action(action, evidence, expected_pid)
except CadIdentityConflict as error:
print(str(error), file=sys.stderr)
return PRIVATE_CAD_IDENTITY_EXIT_CODE
def _run_native_action(action, evidence, expected_pid):
"""Runs in a child created with lpDesktop, never in a Python thread switch."""
if action != 'probe':
return _native_action(action, evidence, expected_pid)
@@ -260,10 +313,10 @@ def _native_action(action, evidence, expected_pid):
desktop = os.environ.get('DXPART_DESKTOP', '')
token = os.environ.get('DXPART_SESSION_TOKEN', '')
if not desktop.startswith('dx-') or current_desktop_name() != desktop:
raise ValueError('CAD bootstrap is not on the requested private desktop')
raise CadIdentityConflict('CAD bootstrap is not on the requested private desktop')
expected_pid = int(expected_pid)
if expected_pid <= 0 or str(expected_pid) != os.environ.get('DXPART_CAD_PID'):
raise ValueError('invalid CAD bootstrap PID')
raise CadIdentityConflict('invalid CAD bootstrap PID')
deadline = time.monotonic() + 60
while True:
try:
@@ -282,15 +335,24 @@ def _native_action(action, evidence, expected_pid):
# ROT is scoped to this desktop. Certify the freshly launched instance
# here; every subsequent VBS/helper attachment checks its GUID.
binding = CadBinding(desktop, expected_pid, str(app.Guid()), token)
verify_application(app, binding, require_view=False)
try:
verify_application(app, binding, require_view=False)
except ValueError as error:
raise CadIdentityConflict(str(error)) from error
Path(evidence).write_text(json.dumps(asdict(binding)), encoding='utf-8')
elif action in {'quit', 'checkpoint'}:
binding = CadBinding.from_environment()
try:
binding = CadBinding.from_environment()
if binding is None:
raise ValueError('missing private CAD identity')
verify_application(app, binding, require_view=False)
opened_project = project_file_path(app)
except ValueError as error:
raise CadIdentityConflict(str(error)) from error
# ActiveViewHandle can retain a destroyed/reused HWND after closing
# the last project. The private ROT/GUID binds this empty instance.
verify_application(app, binding, require_view=False)
if project_file_path(app):
raise ValueError('owned CAD still has a project open; no implicit save or discard')
if opened_project:
raise CadIdentityConflict('owned CAD still has a project open; no implicit save or discard')
if action == 'quit':
app.Quit()
else:
+68
View File
@@ -185,6 +185,12 @@ def test_prewrite_failure_releases_old_desktop_and_retries_only_once(tmp_path, m
runtime.run_worker(command, 5)
assert len(calls) == len(Desktop.created) == len(Cad.created) == 2
assert runtime.generation == 2
releases = json.loads(runtime.path.read_text())['generation_releases']
assert [release['generation'] for release in releases] == [1, 2]
assert [release['desktop'] for release in releases] == [desktop.name for desktop in Desktop.created]
assert all(release['cad_pid'] == 500 and release['cad_guid'] == 'owned'
and release['cleanup']['desktop_confirmation']['released'] is True
and release['released_at'] > 0 for release in releases)
def test_possible_mutation_prevents_automatic_replay(tmp_path, monkeypatch):
@@ -375,6 +381,8 @@ def test_release_publication_failure_can_be_reconciled_without_replaying(tmp_pat
monkeypatch.setattr(batch_runtime, 'write_record', real_write)
assert batch_runtime.cleanup_pending_resources(tmp_path) == ()
assert len(Desktop.created) == 1
releases = json.loads(runtime.path.read_text())['generation_releases']
assert len(releases) == 1 and releases[0]['generation'] == 1
@pytest.mark.parametrize('record', [
@@ -430,3 +438,63 @@ def test_restart_reconciles_only_confirmed_disappearance_without_replacement(tmp
present[0] = False
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
assert len(Desktop.created) == 1
@pytest.mark.parametrize('conflict', [
'bootstrap_binding', 'bootstrap_json', 'bootstrap_schema', 'helper_identity',
'checkpoint_binding', 'checkpoint_json', 'worker_identity',
])
def test_identity_conflict_never_rebuilds_or_launches_another_worker(tmp_path, monkeypatch, conflict):
import io
import subprocess
from dx_productivity.trial_task_center import isolated_cad, worker_monitor
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
command, _ = command_for(tmp_path)
workers = []
class IdentityDesktop(Desktop):
def start_process(self, launch, **options):
process = super().start_process(launch, **options)
process.stderr = io.BytesIO(b'CAD COM GUID does not match its owned session')
process.wait = lambda timeout: process.returncode
if launch[0] == 'cad.exe':
self.cad = process
process.returncode = None
return process
action, evidence, pid = launch
binding = {'desktop': self.name, 'pid': pid, 'guid': 'owned',
'token': options['env']['DXPART_SESSION_TOKEN']}
if action == 'probe':
if conflict == 'helper_identity':
process.returncode = 4 # Private helper identity-conflict exit.
return process
if conflict == 'bootstrap_binding':
binding['pid'] = pid + 1
if conflict == 'bootstrap_schema':
binding.pop('token')
Path(evidence).write_text('{' if conflict == 'bootstrap_json' else json.dumps(binding))
elif action == 'checkpoint':
closing = Path(evidence).name.startswith('cad-closed-')
if closing and conflict == 'checkpoint_binding':
binding['guid'] = 'foreign'
record = {'binding': binding, 'project_path': '', 'project_closed': True}
Path(evidence).write_text('{' if closing and conflict == 'checkpoint_json' else json.dumps(record))
elif action == 'quit':
self.cad.returncode = 0
return process
monkeypatch.setattr(isolated_cad, '_designer_executable', lambda: 'cad.exe')
monkeypatch.setattr(isolated_cad, '_helper_command', lambda *args: args)
def monitor(*args, **kwargs):
workers.append(1)
if conflict == 'worker_identity':
return subprocess.CompletedProcess(command, 2, '', 'private CAD GUID mismatch; no project was changed')
return subprocess.CompletedProcess(command, 0, '', '')
monkeypatch.setattr(worker_monitor, 'run_monitored_process', monitor)
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=IdentityDesktop)
with runtime, pytest.raises(worker_monitor.WorkerMonitorError):
runtime.run_worker(command, 5)
assert len(Desktop.created) == 1
assert len(workers) == (1 if conflict.startswith('checkpoint') or conflict == 'worker_identity' else 0)
assert runtime.generation == 1 and not runtime.record['retries']
assert Desktop.created[0].released
+13
View File
@@ -314,6 +314,19 @@ def test_released_startup_failure_returns_retryable_pre_mutation_code(monkeypatc
assert not (tmp_path / 'uncertain.flag').exists()
def test_released_startup_identity_conflict_is_not_a_retryable_exit(monkeypatch, tmp_path):
class FailedIdentity:
def __init__(self, *args, **kwargs):
pass
def __enter__(self):
raise runtime.PrivateCadIdentityError('bootstrap returned a foreign identity')
def __exit__(self, *args):
pytest.fail('failed identity must not enter execution')
monkeypatch.setattr(runtime, 'IsolatedCadSession', FailedIdentity)
with pytest.raises(runtime.CadIdentityConflict):
runtime.run_isolated_process(('cscript.exe', '//nologo', 'helper.vbs', str(tmp_path)), 1)
@pytest.mark.parametrize('failure', ['quit', 'cad_exit', 'unexpected_exit'])
def test_uncertain_cleanup_is_durable_before_forced_owned_release(monkeypatch, tmp_path, failure):
events, cad = fake_desktop(monkeypatch, tmp_path,