fix: reuse managed desktop across batches with isolated leases

This commit is contained in:
阿白叔 committed 2026-11-18 10:38:11 +08:00
1 parent d08a940afe
commit cdbc92fab8
15 files changed
+999 -26

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
import json
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
CONTEXT = {'sid': 'S-1-5-21-123', 'logon': 'S-1-5-5-2-1234', 'station': 'WinSta0'}
class Backend:
def __init__(self):
self.locked = False
self.exists = False
self.alive = set()
self.jobs = set()
self.owner = {'pid': 100, 'creation_time': 'owner-100'}
def lock(self, name):
if self.locked:
raise TaskCenterError('desktop_slot_busy', 'slot busy')
self.locked = True
return name
def unlock(self, handle): self.locked = False
def desktop_exists(self, name): return self.exists
def process_gone(self, identity): return identity['pid'] not in self.alive
def job_empty(self, name): return name not in self.jobs
def current_process(self): return dict(self.owner)
def slot(tmp_path, backend, **options):
from dx_productivity.trial_task_center.desktop_slot import DesktopSlot
return DesktopSlot(root=tmp_path, context=CONTEXT, backend=backend, **options)
def test_sequential_leases_reuse_name_but_never_reuse_attempt_identity(tmp_path):
backend = Backend()
first = slot(tmp_path, backend).acquire()
name = first.name
backend.exists = True # External reference keeps the object after our close.
receipt = first.release(desktop_disappeared=False)
second = slot(tmp_path, backend).acquire()
assert second.name == name
assert second.lease_id != first.lease_id
assert receipt['desktop_disappeared'] is False and receipt['returned'] is True
second.release(desktop_disappeared=False)
def test_competing_owner_cannot_create_another_slot(tmp_path):
backend = Backend()
first = slot(tmp_path, backend).acquire()
with pytest.raises(TaskCenterError): slot(tmp_path, backend).acquire()
first.release(desktop_disappeared=True)
assert slot(tmp_path, backend).acquire().name == first.name
@pytest.mark.parametrize('damage', ['owner_alive', 'job_alive', 'launch_pending', 'unknown_desktop', 'bad_record'])
def test_restart_admission_does_not_override_unresolved_writer(tmp_path, damage):
backend = Backend()
first = slot(tmp_path, backend).acquire()
job = first.prepare_launch()
first.launched(job, {'pid': 200, 'creation_time': 'worker-200'})
backend.locked = False # Simulated abandoned mutex after owner loss.
backend.exists = True
if damage == 'owner_alive': backend.alive.add(100)
elif damage == 'job_alive': backend.jobs.add(job)
elif damage == 'launch_pending':
record = json.loads(first.path.read_text())
record['launches'][0]['state'] = 'launching'
first.path.write_text(json.dumps(record))
elif damage == 'unknown_desktop': first.path.unlink()
else: first.path.write_text('{broken')
with pytest.raises(TaskCenterError): slot(tmp_path, backend).acquire()
assert not backend.locked
def test_restart_reclaims_dead_owner_only_after_named_job_is_empty(tmp_path):
backend = Backend()
first = slot(tmp_path, backend).acquire()
job = first.prepare_launch()
first.launched(job, {'pid': 200, 'creation_time': 'worker-200'})
backend.locked = False
backend.exists = True
second = slot(tmp_path, backend).acquire()
assert second.name == first.name
second.release(desktop_disappeared=False)
def test_slot_cannot_be_returned_while_owned_job_is_alive(tmp_path):
backend = Backend()
current = slot(tmp_path, backend).acquire()
job = current.prepare_launch()
current.launched(job, {'pid': 200, 'creation_time': 'worker-200'})
backend.jobs.add(job)
with pytest.raises(TaskCenterError): current.release(desktop_disappeared=False)
assert backend.locked
backend.jobs.clear()
assert current.release(desktop_disappeared=False)['returned'] is True
def test_old_release_is_idempotent_and_cannot_change_new_lease(tmp_path):
from dx_productivity.trial_task_center.desktop_slot import returned_lease_intact
backend = Backend()
first = slot(tmp_path, backend).acquire()
receipt = first.release(desktop_disappeared=False)
second = slot(tmp_path, backend).acquire()
before = second.path.read_bytes()
assert first.release(desktop_disappeared=True) == receipt
assert second.path.read_bytes() == before and backend.locked
assert returned_lease_intact(receipt, first.name)
data = json.loads(first.return_path.read_text()); data['lease_id'] = 'wrong'
first.return_path.write_text(json.dumps(data))
assert not returned_lease_intact(receipt, first.name)
second.release(desktop_disappeared=False)
def test_launch_intent_must_be_durable_before_a_process_can_start(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import desktop_slot
backend = Backend()
current = slot(tmp_path, backend).acquire()
def fail(*args): raise OSError('storage unavailable')
monkeypatch.setattr(desktop_slot, 'write_record', fail)
with pytest.raises(OSError): current.prepare_launch()
assert backend.locked
def test_user_and_logon_change_the_name_not_workspace_path(tmp_path):
from dx_productivity.trial_task_center.desktop_slot import DesktopSlot
backend = Backend()
a = slot(tmp_path / 'workspace-one', backend)
b = slot(tmp_path / 'workspace-two', backend)
c = DesktopSlot(root=tmp_path, context=dict(CONTEXT, logon='different-logon'), backend=backend)
assert a.name == b.name and a.name != c.name
def test_atomic_job_launch_recovers_publication_gap_only_after_job_exit(tmp_path):
backend = Backend()
first = slot(tmp_path, backend).acquire()
job = first.prepare_launch(atomic_job=True)
backend.locked = False
backend.jobs.add(job)
with pytest.raises(TaskCenterError): slot(tmp_path, backend).acquire()
backend.jobs.clear()
recovered = slot(tmp_path, backend).acquire()
recovered.release(desktop_disappeared=True)
+23
View File
@@ -0,0 +1,23 @@
import os
from threading import Thread
from uuid import uuid4
import pytest
@pytest.mark.skipif(os.name != 'nt', reason='Windows mutex thread ownership')
def test_slot_can_be_returned_by_the_worker_monitor_thread():
from dx_productivity.trial_task_center.desktop_slot import _Windows
backend = _Windows()
name = 'Local\\DxPartReplace-Thread-Return-Test-' + uuid4().hex
mutex = backend.lock(name)
errors = []
def release():
try: backend.unlock(mutex)
except Exception as error: errors.append(error)
thread = Thread(target=release)
thread.start(); thread.join(timeout=5)
if errors: backend.unlock(mutex)
assert not thread.is_alive() and not errors
again = backend.lock(name)
backend.unlock(again)
+160
View File
@@ -0,0 +1,160 @@
from types import SimpleNamespace
import pytest
from test_desktop_slot import Backend, slot
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
from dx_productivity.trial_task_center.errors import TaskCenterError
class Api:
def __init__(self, backend): self.backend = backend; self.launches = []
def create_desktop(self, name):
self.backend.exists = True
return SimpleNamespace(CloseDesktop=lambda: None)
def create_process(self, command, desktop, cwd, env, **options):
self.launches.append(options['job_name'])
return SimpleNamespace(pid=200, handle=None, poll=lambda: 0,
close=lambda: None, wait=lambda **options: 0, cleanup_record={})
def test_managed_desktop_returns_external_residue_and_old_close_cannot_touch_new_owner(tmp_path):
backend = Backend(); api = Api(backend)
first = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend))
first.__enter__(); first.close()
assert first.cleanup_record['desktop_confirmation']['released'] is False
assert first.cleanup_record['desktop_lease']['returned'] is True
second = PrivateDesktop('another-task', enabled=True, api=api, slot=slot(tmp_path, backend))
second.__enter__()
assert second.name == first.name
first.close()
assert backend.locked
second.close()
def test_managed_launch_uses_durable_named_job_and_keeps_failed_launch_unresolved(tmp_path):
backend = Backend(); api = Api(backend)
current = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend))
current.__enter__()
def failed(*args, **options):
assert current._slot.record['launches'][0]['job'] == options['job_name']
raise OSError('unknown create boundary')
api.create_process = failed
with pytest.raises(OSError): current.start_process(('worker',))
with pytest.raises(TaskCenterError): current.close()
assert backend.locked
def test_managed_launch_cleanup_allows_return_only_after_job_exit(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources
backend = Backend(); api = Api(backend)
current = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend))
monkeypatch.setattr(batch_resources, 'process_identity', lambda process: {'pid': process.pid, 'creation_time': 'worker-200'})
current.__enter__()
current.start_process(('worker',))
assert api.launches == [current._slot.record['launches'][0]['job']]
current.close()
assert not backend.locked
def test_runtime_publishes_actual_managed_name_before_starting_a_worker(tmp_path):
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
backend = Backend(); api = Api(backend)
def factory(requested, **options):
return PrivateDesktop(requested, **options, api=api, slot=slot(tmp_path / 'slot', backend))
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
desktop = runtime._ensure_desktop()
assert runtime.record['desktop'] == desktop.name
runtime.close()
def test_catalog_accepts_intact_return_without_claiming_desktop_disappearance(tmp_path):
from dx_productivity.trial_task_center.cell_catalog import _require_cleanup
backend = Backend(); current = slot(tmp_path, backend).acquire()
receipt = current.release(desktop_disappeared=False)
cleanup = dict(desktop=current.name, desktop_handle_closed=True, owned_cleanup_complete=True, errors=[],
desktop_confirmation={'released': False}, desktop_lease=receipt,
processes=[dict(errors=[], job_active_processes=0, process_handle_closed=True, job_handle_closed=True)])
_require_cleanup(cleanup)
cleanup['desktop_lease'] = dict(receipt, lease_id='forged')
with pytest.raises(TaskCenterError): _require_cleanup(cleanup)
def test_failed_owned_handle_cleanup_keeps_slot_until_cleanup_succeeds(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources
backend = Backend(); api = Api(backend)
current = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend))
monkeypatch.setattr(batch_resources, 'process_identity', lambda process: {'pid': process.pid, 'creation_time': 'worker-200'})
current.__enter__(); process = current.start_process(('worker',))
process.close = lambda: (_ for _ in ()).throw(OSError('Job handle not closed'))
with pytest.raises(TaskCenterError): current.close()
assert backend.locked
process.close = lambda: None
current.close()
assert not backend.locked
def test_resource_recheck_never_queries_a_reused_desktop_for_a_returned_lease(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources, isolated_desktop
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
backend = Backend(); api = Api(backend)
def factory(name, **options): return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend))
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
runtime._ensure_desktop(); runtime.close()
assert runtime.record['state'] == 'isolated'
next_owner = slot(tmp_path / 'slot', backend).acquire()
from dx_productivity.trial_task_center import desktop_slot
monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared', lambda receipt: False)
def forbidden(*args): pytest.fail('old batch queried the currently leased desktop')
monkeypatch.setattr(isolated_desktop, '_Win32Api', forbidden)
warnings = batch_resources.cleanup_pending_resources(runtime.root)
assert warnings and warnings[0]['blocking'] is False
next_owner.release(desktop_disappeared=False)
def test_failed_acquisition_cleanup_does_not_release_another_owner(tmp_path):
backend = Backend(); api = Api(backend)
first = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend))
first.__enter__()
second = PrivateDesktop('ignored', enabled=True, api=api, slot=slot(tmp_path, backend))
with pytest.raises(TaskCenterError): second.__enter__()
second.close()
assert backend.locked and second.cleanup_record['desktop_not_acquired'] is True
first.close()
def test_transient_return_proof_read_failure_can_be_rechecked_without_permanent_block(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import batch_resources, desktop_slot
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
backend = Backend(); api = Api(backend)
def factory(name, **options): return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend))
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
runtime._ensure_desktop(); runtime.close()
original = desktop_slot.returned_lease_intact
monkeypatch.setattr(desktop_slot, 'managed_desktop_disappeared', lambda receipt: False)
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', lambda *args: False)
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is True
monkeypatch.setattr(desktop_slot, 'returned_lease_intact', original)
assert batch_resources.cleanup_pending_resources(runtime.root)[0]['blocking'] is False
assert not batch_resources.blocking_resources(runtime.root)
def test_native_job_creation_failure_is_certified_before_process_creation():
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
api = _Win32Api.__new__(_Win32Api)
api.process = SimpleNamespace(STARTUPINFO=SimpleNamespace)
api.con = SimpleNamespace(CREATE_NO_WINDOW=1, CREATE_SUSPENDED=2)
def denied(*args): raise OSError('temporary Job allocation failure')
api.job = SimpleNamespace(CreateJobObject=denied)
with pytest.raises(OSError) as caught:
api.create_process(('worker',), 'winsta0\\probe', None, None)
assert caught.value.desktop_launch_cleanup_proven is True
def test_unsupported_platform_can_construct_evidence_without_win32_identity(monkeypatch):
from dx_productivity.trial_task_center import desktop_slot, isolated_desktop
monkeypatch.setattr(isolated_desktop, 'os', SimpleNamespace(name='posix'))
def forbidden(): pytest.fail('non-Windows evidence construction queried a Windows logon')
monkeypatch.setattr(desktop_slot, '_context', forbidden)
desktop = PrivateDesktop('dx-evidence', enabled=True, managed=True)
assert desktop.name == 'dx-evidence' and desktop._slot is None