fix: harden supervised replacement and missing uid handling

This commit is contained in:
阿白叔 committed 2026-10-30 16:33:10 +08:00
1 parent 656f43e2ff
commit 131b6dbbb3
30 files changed
+1655 -92

No files matched your search

@@ -180,7 +180,7 @@ class NativeTests(unittest.TestCase):
component = type("Component", (), {"UID": "uid", "Refdes": "R1"})()
records = [["C", "uid", "R1"]]
def value(_component, name):
def value(_component, name, *, required=False, fallback=""):
return {"Part Number": "NEW", "Part Name": "RES", "Part Label": ""}[name]
with patch.object(native, "attribute_value", side_effect=value):
@@ -117,7 +117,7 @@ def test_quick_part_replace_prioritizes_recovery_and_preflights_before_writes()
assert '"hard_failure"' in text
assert "multiple awaiting_native_replace rules" in text
assert text.index("QPRestorePreflight") < text.index("Comp.Refdes =")
assert "Cannot capture " in text
assert "optional_display_field_unavailable field=" in text
assert "QPOptionalAttributeField" in text
assert "value_style_defaulted" in text
assert 'QP_App.ExecuteCommand("undo")' in text
+19
View File
@@ -1,5 +1,6 @@
"""UI log and feedback coverage, collectable alongside the service feedback tests."""
import json
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.ui.messages import (
_aligned_log_line, _format_task_log_lines, _nc_sync_log_lines,
@@ -54,6 +55,24 @@ def test_preflight_error_keeps_reason_and_stable_id_in_operator_feedback(ui):
assert error.error_id in ui.window._log_presenter.log_text
@pytest.mark.parametrize('kind', ['missing', 'invalid', 'forced', 'resources'])
def test_supervisor_failure_feedback_keeps_support_id_and_recovery_instruction(ui, kind):
from dx_productivity.trial_task_center.supervisor_evidence import MissingSupervisorResult, InvalidSupervisorResult
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
errors = {
'missing': MissingSupervisorResult(exit_code=79, stderr_tail='worker failed'),
'invalid': InvalidSupervisorResult(exit_code=0),
'forced': TaskCenterError('user_forced_stop', '已强制结束,请先核验恢复。'),
'resources': BatchResourceCleanupError('资源确认失败,请重新清理资源。'),
}
error = errors[kind]
ui.window._show_error(error)
text = ui.window.run_panel.operator_band.text()
assert error.error_id in text
assert error.message in text
assert error.error_id in ui.window._log_presenter.log_text
def test_running_feedback_names_owner_and_keeps_navigation_available(ui,qtbot):
from threading import Event
release,started=Event(),Event()
+97 -1
View File
@@ -22,7 +22,11 @@ def routine(name):
def run_vbs(tmp_path, names, body, prelude=''):
script = tmp_path / 'guard.vbs'
script.write_text(prelude + '\n' + '\n'.join(routine(name) for name in names) + '\n' + body,
names = tuple(names)
support = tuple(name for name in ('QPReadOptionalAttributeValue', 'QPRequiredAttributeValue',
'QPReadableAttributeValue', 'QPEffectiveAttributeValue',
'QPComponentIdentityKey') if name not in names)
script.write_text(prelude + '\n' + '\n'.join(routine(name) for name in names + support) + '\n' + body,
encoding='ascii')
result = subprocess.run(['cscript.exe', '//nologo', str(script)], capture_output=True,
text=True, timeout=15)
@@ -69,6 +73,41 @@ End Class
''') == 'True'
@pytest.mark.parametrize(('uid', 'refdes', 'expected'), [
('', 'R1', '@REFDES|R1'),
('u1', 'R1', 'u1'),
])
def test_missing_component_uid_uses_stable_refdes_fallback(tmp_path, uid, refdes, expected):
output = run_vbs(tmp_path, ['QPComponentIdentityKey'], f'''
Dim Comp
Set Comp = New IdentityComponent
Comp.UID = "{uid}": Comp.Refdes = "{refdes}"
On Error Resume Next
WScript.Echo QPComponentIdentityKey(Comp)
''', LOG_STUB + f'''
Class IdentityComponent
Public UID, Refdes
End Class
''')
assert output == expected
def test_missing_component_refdes_still_fails_fast(tmp_path):
output = run_vbs(tmp_path, ['QPComponentIdentityKey'], '''
Dim Comp
Set Comp = New IdentityComponent
Comp.UID = "": Comp.Refdes = ""
On Error Resume Next
WScript.Echo QPComponentIdentityKey(Comp)
WScript.Echo Err.Number
''', LOG_STUB + '''
Class IdentityComponent
Public UID, Refdes
End Class
''')
assert output.splitlines()[-1] != '0'
def test_instance_value_com_failure_cannot_fallback_to_base_value(tmp_path):
assert run_vbs(tmp_path, ['QPEffectiveAttributeValue'], '''
Dim Attr, Value
@@ -89,6 +128,51 @@ End Class
''') == '1234'
def test_optional_attribute_fields_degrade_to_safe_defaults(tmp_path):
output = run_vbs(tmp_path, ['QPOptionalAttributeField', 'QPReadOptionalAttributeValue'], '''
Dim Attr
Set Attr = New BrokenOptionalAttribute
WScript.Echo QPOptionalAttributeField(Attr, "color")
WScript.Echo QPOptionalAttributeField(Attr, "location_x")
WScript.Echo QPReadOptionalAttributeValue(Attr)
''', LOG_STUB + '''
Class BrokenOptionalAttribute
Public Name
Private Sub Class_Initialize
Name = "Value"
End Sub
Public Property Get Color
Err.Raise 1234, "FakeCOM", "color unavailable"
End Property
Public Function GetLocation()
Err.Raise 1235, "FakeCOM", "location unavailable"
End Function
Public Property Get InstanceValue
Err.Raise 1236, "FakeCOM", "instance unavailable"
End Property
Public Property Get Value
Err.Raise 1237, "FakeCOM", "value unavailable"
End Property
End Class
''')
assert output.splitlines() == ['0', '0']
def test_optional_component_label_read_failure_is_not_identity_failure(tmp_path):
output = run_vbs(tmp_path, ['QPEffectiveComponentAttribute', 'QPFindCurrentAttribute', 'QPLogField'], '''
Dim Comp
Set Comp = New BrokenComponent
WScript.Echo QPEffectiveComponentAttribute(Comp, "Part Label")
''', LOG_STUB + '''
Class BrokenComponent
Function FindAttribute(ByVal Name)
Err.Raise 1234, "FakeCOM", "optional label unavailable"
End Function
End Class
''')
assert output == ''
CONNECTION_ROUTINES = ['QPConnectionsMatch', 'QPConnectionLineValid', 'QPConnectionCoordinate',
'QPConnectionNumber', 'QPConnectionNetIdentity', 'QPConnectionsMatchOffset']
@@ -331,6 +415,18 @@ WScript.Echo Replace(Text,vbCrLf,"")
assert output.splitlines() == ['1', 'A\tu1\tValue\tSAME\tSAME\t0\t0\t1\t2\t3\t0\t1']
@pytest.mark.parametrize('instance', ['', 'OVERRIDE'])
def test_snapshot_preserves_base_value_separately_from_instance_override(tmp_path, instance):
output = run_vbs(tmp_path, ['QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPEncode'], f'''
Dim Attr, Text
Set Attr=New FullAttribute
Attr.Value="BASE":Attr.InstanceValue="{instance}"
Text=QPSnapshotAttribute("u1",Attr)
WScript.Echo Replace(Text,vbCrLf,"")
''', LOG_STUB + FULL_FAKE)
assert output.split('\t')[3:5] == ['BASE', instance]
def test_unselected_identity_comes_from_the_same_complete_attribute_read(tmp_path):
output = run_vbs(tmp_path, UNTOUCHED_ROUTINES, '''
Dim Comp, Attr, Text, Lines, Names, Values, Item
+108 -1
View File
@@ -17,6 +17,16 @@ def test_supervisor_runs_in_other_process_and_releases_gate(tmp_path):
assert result['pid'] != os.getpid()
assert result['resource_state'] == 'not_acquired'
assert_supervisor_idle(tmp_path)
directory = next((tmp_path / 'batch-resources').iterdir())
from dx_productivity.trial_task_center.supervisor_evidence import LifecycleEvidence
stages = [row['event'] for row in LifecycleEvidence(directory).events()]
assert stages == ['supervisor_starting', 'worker_started', 'business_started',
'business_finished', 'resources_releasing', 'worker_closing',
'result_committed', 'supervisor_exit']
process = json.loads((directory / 'process.json').read_text(encoding='utf-8'))
assert process['exit_code'] == 0
assert process['cleanup']['job_active_processes'] == 0
assert process['cleanup']['job_membership_verified'] is True
finally:
store.close()
@@ -29,6 +39,102 @@ def test_mutation_guard_refuses_owned_launch_gate(tmp_path):
assert_supervisor_idle(tmp_path)
def test_diagnostic_write_failure_does_not_erase_committed_business_result(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import supervisor_evidence
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
def denied(*args, **kwargs):
raise PermissionError('diagnostic write denied')
monkeypatch.setattr(supervisor_evidence, 'write_process_evidence', denied)
store = TaskStore(tmp_path / 'tasks.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
result = run_supervised(service, 'probe', {})
assert result['resource_state'] == 'not_acquired'
assert list((tmp_path / 'batch-resources').glob('*/result.json'))
finally:
store.close()
def test_launch_failure_keeps_original_cause_and_blocks_attempt(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.errors import TaskCenterError
def failed(*args, **kwargs):
raise OSError('native launch denied')
monkeypatch.setattr(_Win32Api, 'create_process', failed)
store = TaskStore(tmp_path / 'tasks.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
with pytest.raises(TaskCenterError) as caught:
run_supervised(service, 'probe', {})
assert caught.value.code == 'worker_start_failed'
assert 'native launch denied' in str(caught.value.primary_error)
finally:
store.close()
def test_corrupt_committed_result_is_not_accepted_as_success(tmp_path, monkeypatch):
import sys
from dx_productivity.trial_task_center import batch_supervisor
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.supervisor_evidence import InvalidSupervisorResult
monkeypatch.setattr(batch_supervisor, '_command', lambda request: (
sys.executable, '-c', "import pathlib,sys; pathlib.Path(sys.argv[1]).with_name('result.json').write_text('{')", str(request)))
store = TaskStore(tmp_path / 'tasks.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
with pytest.raises(InvalidSupervisorResult) as caught:
batch_supervisor.run_supervised(service, 'probe', {})
assert caught.value.exit_code == 0
journal = json.loads(next((tmp_path / 'batch-resources').glob('*/supervisor.json')).read_text(encoding='utf-8'))
assert journal['state'] == 'blocked'
finally:
store.close()
@pytest.mark.parametrize('protection_failure', [False, True])
def test_crash_captures_stderr_without_newline_and_keeps_exit_code(tmp_path, monkeypatch, protection_failure):
import sys
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
from dx_productivity.trial_task_center import batch_supervisor
from dx_productivity.trial_task_center.supervisor_evidence import MissingSupervisorResult
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.errors import TaskCenterError
monkeypatch.setattr(batch_supervisor, '_command', lambda request: (
sys.executable, '-c', "import os,sys; sys.stderr.write('x'*100000+'crash detail'); sys.stderr.flush(); os._exit(79)"))
store = TaskStore(tmp_path / 'tasks.db')
try:
service = TaskCenterService(store, configure_logging(tmp_path))
task = store.create_task('never opened in CAD')
if protection_failure:
def denied(*args, **kwargs):
raise PermissionError('protection denied')
monkeypatch.setattr(batch_supervisor, '_mark_interrupted', denied)
with pytest.raises(TaskCenterError) as caught:
run_supervised(service, 'execute_quick_run', {'task_id': task.task_id})
error = caught.value.primary_error if protection_failure else caught.value
if protection_failure:
assert caught.value.code == 'interruption_protection_failed'
assert isinstance(error, MissingSupervisorResult)
assert error.exit_code == 79
assert error.stderr_tail.endswith('crash detail')
assert len(error.stderr_tail.encode('utf-8')) <= 65536
journal = json.loads(next((tmp_path / 'batch-resources').glob('*/supervisor.json')).read_text(encoding='utf-8'))
assert journal['state'] == 'blocked'
finally:
store.close()
def test_supervisor_deep_root_uses_compatible_process_working_directory(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.batch_supervisor import run_supervised
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
@@ -259,7 +365,8 @@ def test_real_supervisor_process_crash_reconciles_without_replaying_mock_busines
else:
with pytest.raises(TaskCenterError) as caught:
supervisor.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id})
assert caught.value.code == 'supervisor_interrupted'
assert caught.value.code == 'worker_result_missing'
assert caught.value.exit_code == 73
executions = witness.read_text().splitlines()
assert len(executions) == 1 and int(executions[0]) not in {os.getpid(), previous['pid']}
marker = evidence / 'quick-run/uncertain.flag'
+92
View File
@@ -68,6 +68,87 @@ def test_startup_info_always_targets_private_desktop():
assert info.lpDesktop == 'winsta0\\dx-private-test'
@pytest.mark.skipif(os.name != 'nt', reason='native Windows process identity')
def test_redirected_process_pid_matches_owned_handle():
import win32process
api = _Win32Api()
process = api.create_process((sys.executable, '-c', 'import time; time.sleep(1)'),
None, None, None, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
assert process.pid == win32process.GetProcessId(process.handle)
finally:
process.close()
api.close_pending()
@pytest.mark.skipif(os.name != 'nt', reason='native Windows venv launcher')
def test_python_worker_identity_and_environment_match_native_process():
api = _Win32Api()
script = 'import os,sys,json,win32api; print(json.dumps([os.getpid(),sys.prefix]),flush=True)'
process = api.create_process((sys.executable, '-c', script), None, None, None,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
import json
pid, prefix = json.loads(process.stdout.readline())
assert pid == process.pid
assert prefix == sys.prefix
assert process.wait(timeout=5) == 0
finally:
process.close()
api.close_pending()
@pytest.mark.skipif(os.name != 'nt', reason='native Windows launch environment')
@pytest.mark.parametrize('flags', [(), ('-E',), ('-I',)])
@pytest.mark.parametrize('redirected', [False, True])
def test_python_launch_preserves_venv_in_isolated_modes_and_unicode_cwd(tmp_path, flags, redirected):
import json
working = tmp_path / '中文工作目录 with spaces'
working.mkdir()
witness = working / 'identity.json'
script = ('import json,os,sys,win32api; from pathlib import Path; '
'Path(sys.argv[1]).write_text(json.dumps([os.getpid(),sys.prefix,os.getcwd()]),encoding="utf-8")')
environment = dict(os.environ)
environment['COMPATIBILITY_SENTINEL'] = 'retained'
original = dict(environment)
api = _Win32Api()
kwargs = {'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE} if redirected else {}
process = api.create_process((sys.executable, *flags, '-c', script, str(witness)),
None, working, environment, **kwargs)
try:
assert process.wait(timeout=15) == 0
pid, prefix, cwd = json.loads(witness.read_text(encoding='utf-8'))
assert pid == process.pid
assert prefix == sys.prefix
assert Path(cwd) == working
assert environment == original # child-only venv setup must not alter caller environment
finally:
process.close()
api.close_pending()
@pytest.mark.parametrize('frozen,current_python', [(True, True), (False, False)])
def test_frozen_and_foreign_executables_never_use_current_venv_launcher(monkeypatch, frozen, current_python):
from dx_productivity.trial_task_center import isolated_desktop as module
api, _, _, *_ = native_api()
command = (sys.executable if current_python else r'C:\other-runtime\python.exe', '--batch-worker', 'request.json')
observed = []
create = api.process.CreateProcess
def record(*args):
observed.append(args)
return create(*args)
api.process.CreateProcess = record
monkeypatch.setattr(module.sys, 'frozen', frozen, raising=False)
environment = {'SystemRoot': os.environ['SystemRoot'], 'PYTHONHOME': 'unrelated'}
process = api.create_process(command, None, None, environment)
try:
assert observed[0][0] == command[0]
assert observed[0][6] == environment
assert '__PYVENV_LAUNCHER__' not in environment
finally:
process.close()
def test_desktop_records_native_handle_before_close_and_failed_retry():
class Desktop:
fail = True
@@ -190,6 +271,7 @@ def native_api(*, assign_error=False):
{'BasicLimitInformation': {'LimitFlags': 0}} if kind == 9 else {'ActiveProcesses': int(state['running'])}),
SetInformationJobObject=lambda *_args: events.append(('limits',)),
AssignProcessToJobObject=assign, TerminateJobObject=terminate,
IsProcessInJob=lambda *args: True,
JobObjectExtendedLimitInformation=9, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE=0x2000,
JobObjectBasicAccountingInformation=1,
)
@@ -203,6 +285,16 @@ def test_process_is_suspended_until_job_assignment():
assert process.pid == 42
assert ('create', 0x8000004) in events
assert events.index(('assign',)) < events.index(('resume',))
assert process.cleanup_record['job_membership_verified'] is True
def test_unverified_job_membership_never_resumes_child():
api, events, state, *_ = native_api()
api.job.IsProcessInJob = lambda *args: False
with pytest.raises(TaskCenterError, match='membership'):
api.create_process(('python.exe',), None, None, None)
assert ('resume',) not in events
assert state['running'] is False
def test_failed_job_assignment_terminates_and_reaps_owned_process():
+135
View File
@@ -0,0 +1,135 @@
"""Exercise the inventory entry point, rather than only its identity helper."""
import pytest
from test_accuracy_vbs_guards import run_vbs
@pytest.mark.parametrize('broken_value', [False, True])
@pytest.mark.parametrize(('uid', 'refdes', 'duplicate', 'expected'), [
('', 'R1', False, 'OK'),
('u1', 'R1', False, 'OK'),
('', '', False, 'BLOCKED'),
('u1', '', False, 'BLOCKED'),
('', 'R1', True, 'BLOCKED'),
('u1', 'R1', True, 'BLOCKED'),
])
def test_inventory_accepts_missing_uid_only_with_unique_refdes(tmp_path, uid, refdes, duplicate, expected, broken_value):
(tmp_path / 'component-inventory.request').touch()
output = run_vbs(tmp_path, ['QPDiscoverInventory', 'QPFindCurrentAttribute',
'QPEffectiveComponentAttribute'], f'''
Dim Documents, Comp, Other, Failure
QP_Root="{tmp_path}"
BrokenValue={str(broken_value)}
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Set QP_App=New FakeApp
Set Documents=New FakeDocuments
Set Comp=New FakeComponent
Comp.UID="{uid}":Comp.Refdes="{refdes}"
QP_App.ActiveView.Components.Add Comp,True
If {str(duplicate)} Then
Set Other=New FakeComponent
Other.UID="other":Other.Refdes="{refdes.lower()}"
QP_App.ActiveView.Components.Add Other,True
End If
On Error Resume Next
QPDiscoverInventory Documents
Failure=Err.Number
On Error GoTo 0
If Failure<>0 Then
WScript.Echo "BLOCKED"
Else
WScript.Echo "OK"
WScript.Echo ExportedText
End If
''', '''
Dim QP_Root, QP_App, QP_Fso, QP_Stage, QP_FallbackIdentityUsed, BrokenValue, ExportedText
Const VDM_COMP=128
Const VD_ALL=0
Sub QPLog(ByVal Root,ByVal Level,ByVal Message)
End Sub
Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total)
End Sub
Function QPReadInventoryRequest()
Dim Requested
Set Requested=CreateObject("Scripting.Dictionary")
Requested.Add "old","OLD"
Set QPReadInventoryRequest=Requested
End Function
Function QPProjectPath()
QPProjectPath="project.prj"
End Function
Function QPSheetKey(ByVal Schematic,ByVal Sheet)
QPSheetKey=Schematic & ":" & Sheet
End Function
Function QPEncode(ByVal Value)
QPEncode=CStr(Value)
End Function
Sub QPWriteUtf8(ByVal FilePath,ByVal Text)
If Right(FilePath,14)="components.tsv" Then ExportedText=Text
End Sub
Class FakeApp
Public ActiveView
Private Sub Class_Initialize
Set ActiveView=New FakeView
End Sub
End Class
Class FakeView
Public Components,Block
Private Sub Class_Initialize
Set Components=CreateObject("Scripting.Dictionary")
Set Block=New FakeBlock
End Sub
Function Query(ByVal Kind,ByVal Scope)
Set Query=Components
End Function
Function GetName(ByVal Mode)
GetName="MAIN"
End Function
End Class
Class FakeBlock
Public SheetNum
Private Sub Class_Initialize
SheetNum="1"
End Sub
End Class
Class FakeDocuments
Function GetAvailableSchematics()
Set GetAvailableSchematics=CreateObject("Scripting.Dictionary")
GetAvailableSchematics.Add "MAIN",True
End Function
Function GetAvailableSheets(ByVal Schematic)
Set GetAvailableSheets=CreateObject("Scripting.Dictionary")
GetAvailableSheets.Add "1",True
End Function
Function Open(ByVal Schematic,ByVal Sheet)
Set Open=New FakeDocument
End Function
End Class
Class FakeDocument
Sub Activate()
End Sub
Sub Close(ByVal Save,ByVal Name)
End Sub
End Class
Class FakeComponent
Public UID,Refdes
Function FindAttribute(ByVal Name)
If Name="Value" And BrokenValue Then Err.Raise 1234,"FakeCOM","optional value unavailable"
If Name="Part Number" Then
Set FindAttribute=New FakeAttribute
Else
Set FindAttribute=Nothing
End If
End Function
End Class
Class FakeAttribute
Public Value,InstanceValue
Private Sub Class_Initialize
Value="OLD":InstanceValue=""
End Sub
End Class
''')
assert output.splitlines()[0] == expected
if expected == 'OK':
identity = uid or '@REFDES|' + refdes
assert output.splitlines()[-1].split('\t')[3:6] == [identity, refdes, 'OLD']
@@ -66,3 +66,12 @@ def test_preselection_context_does_not_query_an_unused_selection(monkeypatch):
assert view.selection_reads == 0
with pytest.raises(ValueError, match='Selected component set'):
native.check_context(app, api, metadata, records)
def test_optional_attribute_read_failure_degrades_but_required_identity_fails_fast():
class Broken:
def FindAttribute(self, name):
raise RuntimeError('COM attribute unavailable')
assert native.attribute_value(Broken(), 'Value') == ''
with pytest.raises(ValueError, match='required attribute'):
native.attribute_value(Broken(), 'Part Number', required=True)
+2
View File
@@ -10,6 +10,8 @@ from dx_productivity.trial_task_center import legacy_paths, native_helper
def long_project(tmp_path):
folder = tmp_path / ('design-' + 'x' * 78) / ('revision-' + 'y' * 78)
while len(str(folder / 'board.prj')) <= 260:
folder /= 'extra-' + 'z' * 40
folder.mkdir(parents=True)
project = folder / 'board.prj'
project.write_text('project')
+48 -3
View File
@@ -125,6 +125,23 @@ def test_force_cannot_terminate_before_interruption_evidence_is_durable(tmp_path
with pytest.raises(PermissionError):
module._force_owned_supervisor(tmp_path, journal, process)
assert calls == []
saved = json.loads((tmp_path / 'batch-resources' / ('a' * 32) / 'supervisor.json').read_text())
assert saved['stop_mode'] == 'forced'
assert saved['force_state'] == 'protection_failed'
assert saved['state'] == 'blocked'
def test_repeated_force_does_not_terminate_twice(tmp_path):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_supervisor import _force_owned_supervisor
calls = []
process = SimpleNamespace(terminate=lambda: calls.append('terminate'))
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
'task_ids': ['task'], 'state': 'running'}
_force_owned_supervisor(tmp_path, journal, process)
_force_owned_supervisor(tmp_path, journal, process)
assert calls == ['terminate']
assert journal['force_state'] == 'termination_requested'
def test_force_already_performed_remains_forced_when_exit_diagnostics_fail(tmp_path):
@@ -263,8 +280,11 @@ def test_failed_protection_fsync_is_retried_before_force_is_allowed(tmp_path, mo
thread.join(3)
@pytest.mark.parametrize('deny_first,transport_failure', [(False, False), (True, False), (False, True)])
def test_real_supervisor_force_preserves_protection_and_never_replays(tmp_path, monkeypatch, deny_first, transport_failure):
@pytest.mark.parametrize('deny_first,transport_failure,cleanup_failure,late_write_failure', [
(False, False, False, False), (True, False, False, False), (False, True, False, False),
(False, False, True, False), (False, False, False, True), (False, False, True, True)])
def test_real_supervisor_force_preserves_protection_and_never_replays(
tmp_path, monkeypatch, deny_first, transport_failure, cleanup_failure, late_write_failure):
import os
import textwrap
import time
@@ -310,6 +330,27 @@ def test_real_supervisor_force_preserves_protection_and_never_replays(tmp_path,
raise PermissionError('force evidence denied once')
return original_mark(*args)
monkeypatch.setattr(module, '_mark_interrupted', mark)
if late_write_failure:
from dx_productivity.trial_task_center import batch_resources
original_write = batch_resources.write_record
late_failures = []
def write(path, value):
if (Path(path).name == 'supervisor.json' and not late_failures
and value.get('force_state') in {'confirmed', 'confirmation_failed'}):
late_failures.append(True)
raise PermissionError('late confirmation write denied')
return original_write(path, value)
monkeypatch.setattr(batch_resources, 'write_record', write)
if cleanup_failure:
from dx_productivity.trial_task_center.isolated_desktop import _Win32Process
original_close = _Win32Process.close
failures = []
def close(process):
original_close(process)
if process.cleanup_record['forced_termination'] and not failures:
failures.append(True)
raise OSError('exit confirmation diagnostic failed')
monkeypatch.setattr(_Win32Process, 'close', close)
control = StopControl()
driver_errors, survived = [], []
def request():
@@ -348,13 +389,17 @@ def test_real_supervisor_force_preserves_protection_and_never_replays(tmp_path,
module.run_supervised(service, 'execute_quick_run', {'task_id': task.task_id}, stop_event=control,
on_progress=(lambda _: (_ for _ in ()).throw(RuntimeError('UI feedback failed'))) if transport_failure else None)
assert not driver_errors
assert caught.value.code == 'user_forced_stop'
assert caught.value.code == ('batch_resources_pending' if cleanup_failure or late_write_failure else 'user_forced_stop')
if cleanup_failure or late_write_failure:
assert caught.value.primary_error.code == 'user_forced_stop'
assert (evidence / 'uncertain.flag').exists()
marker = (evidence / 'uncertain.flag').read_bytes()
assert not (evidence / 'unexpected_completed').exists()
journals = [json.loads(p.read_text(encoding='utf-8')) for p in (tmp_path / 'batch-resources').glob('*/supervisor.json')]
forced = next(r for r in journals if r['operation'] == 'execute_quick_run')
assert forced['stop_mode'] == 'forced' and forced['business_uncertain'] is True
assert forced['force_state'] == ('termination_requested' if late_write_failure else
'confirmation_failed' if cleanup_failure else 'confirmed')
assert service.cleanup_batch_resources() == ()
assert (evidence / 'uncertain.flag').read_bytes() == marker
assert not (evidence / 'unexpected_completed').exists()
+107
View File
@@ -0,0 +1,107 @@
import json
import pytest
def test_lifecycle_evidence_appends_atomically_and_is_readable(tmp_path):
from dx_productivity.trial_task_center.supervisor_evidence import LifecycleEvidence
evidence = LifecycleEvidence(tmp_path / 'attempt')
evidence.append('started', pid=123)
evidence.append('result_committed', sequence=4)
rows = evidence.events()
assert [row['event'] for row in rows] == ['started', 'result_committed']
assert rows[0]['pid'] == 123
assert all((tmp_path / 'attempt' / name).exists() for name in ('lifecycle.jsonl',))
def test_missing_result_error_includes_process_and_stream_evidence(tmp_path):
from dx_productivity.trial_task_center.supervisor_evidence import (
MissingSupervisorResult,
write_process_evidence,
)
path = tmp_path / 'attempt'
write_process_evidence(path, exit_code=17, stdout='last progress', stderr='import failed')
error = MissingSupervisorResult.from_directory(path)
assert error.code == 'worker_result_missing'
assert error.exit_code == 17
assert error.stdout_tail == 'last progress'
assert error.stderr_tail == 'import failed'
assert 'import failed' in str(error)
def test_stream_tail_is_bounded(tmp_path):
from dx_productivity.trial_task_center.supervisor_evidence import write_process_evidence
write_process_evidence(tmp_path, exit_code=0, stdout='x' * 100, stderr='y' * 100, limit=8)
data = json.loads((tmp_path / 'process.json').read_text(encoding='utf-8'))
assert data['stdout_tail'] == 'x' * 8
assert data['stderr_tail'] == 'y' * 8
def test_invalid_result_has_distinct_code_and_preserves_exit_evidence(tmp_path):
from dx_productivity.trial_task_center.supervisor_evidence import InvalidSupervisorResult, write_process_evidence
write_process_evidence(tmp_path, exit_code=0, stderr='diagnostic')
error = InvalidSupervisorResult.from_directory(tmp_path)
assert error.code == 'worker_result_invalid'
assert error.exit_code == 0
assert error.stderr_tail == 'diagnostic'
def test_process_evidence_preserves_cleanup_and_last_protocol_message(tmp_path):
from dx_productivity.trial_task_center.supervisor_evidence import write_process_evidence
value = write_process_evidence(tmp_path, exit_code=0,
cleanup={'job_active_processes': 0}, last_message={'type': 'heartbeat', 'sequence': 3})
assert value['cleanup']['job_active_processes'] == 0
assert value['last_message']['sequence'] == 3
def test_stream_tail_bound_is_utf8_bytes(tmp_path):
from dx_productivity.trial_task_center.supervisor_evidence import write_process_evidence
data = write_process_evidence(tmp_path, exit_code=0, stdout='中' * 100, limit=8)
assert len(data['stdout_tail'].encode('utf-8')) <= 8
@pytest.mark.parametrize('value', [None, [], {'stdout_tail': None, 'stderr_tail': 3}])
def test_malformed_process_evidence_cannot_mask_missing_result(tmp_path, value):
from dx_productivity.trial_task_center.supervisor_evidence import MissingSupervisorResult
(tmp_path / 'process.json').write_text(json.dumps(value), encoding='utf-8')
error = MissingSupervisorResult.from_directory(tmp_path)
assert error.code == 'worker_result_missing'
def test_torn_lifecycle_keeps_complete_events(tmp_path):
from dx_productivity.trial_task_center.supervisor_evidence import LifecycleEvidence
evidence = LifecycleEvidence(tmp_path)
evidence.append('started')
with evidence.path.open('ab') as stream:
stream.write(b'{"event":')
assert [row['event'] for row in evidence.events()] == ['started']
def test_optional_lifecycle_reports_write_failure_without_disrupting_business(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.supervisor_evidence import LifecycleEvidence
evidence = LifecycleEvidence(tmp_path)
def denied(*args, **kwargs):
raise PermissionError('disk denied')
monkeypatch.setattr(evidence, 'append', denied)
assert 'disk denied' in evidence.try_append('result_committed')
def test_diagnostic_bundle_includes_redacted_attempt_evidence(tmp_path):
import zipfile
from dx_productivity.trial_task_center.diagnostics_bundle import export_diagnostic_bundle
from dx_productivity.trial_task_center.supervisor_evidence import LifecycleEvidence, write_process_evidence
directory = tmp_path / 'data' / 'batch-resources' / ('a' * 32)
LifecycleEvidence(directory).append('worker_started', pid=123)
write_process_evidence(directory, exit_code=7, stderr='password=secretValue')
bundle = export_diagnostic_bundle(tmp_path / 'data', tmp_path / 'diagnostic.zip')
with zipfile.ZipFile(bundle) as archive:
prefix = 'batch-resources/' + 'a' * 32 + '/'
assert prefix + 'lifecycle.jsonl' in archive.namelist()
process = archive.read(prefix + 'process.json').decode()
assert 'secretValue' not in process
assert 'REDACTED' in process
+1 -1
View File
@@ -175,7 +175,7 @@ def test_native_catalog_checks_cannot_cold_read_or_submit_on_miss(tmp_path, monk
monkeypatch.setattr(native_helper, 'check_active_context', lambda *args: None)
for name in ('components_on_sheet', 'select_snapshot_batch', 'check_context'):
monkeypatch.setattr(native_helper, name, lambda *args, **kwargs: components)
monkeypatch.setattr(native_helper, 'attribute_value', lambda *args: 'OLD')
monkeypatch.setattr(native_helper, 'attribute_value', lambda *args, **kwargs: 'OLD')
monkeypatch.setattr(native_helper, 'selection', lambda *args: None)
monkeypatch.setattr(native_helper, 'replacement_command_from_resources', lambda *args: 33977)
monkeypatch.setattr(native_helper, 'wait_for', lambda callback, *args, **kwargs: callback())
+60
View File
@@ -166,6 +166,66 @@ def test_native_context_rejects_missing_or_changed_target_without_no_match():
check_context(App(components), Api, metadata, [record])
def test_native_snapshot_rejects_empty_uid_snapshot_only_until_inventory_fallback(tmp_path):
from dx_productivity.trial_task_center.native_helper import read_snapshot
snapshot = tmp_path / 'snapshot.tsv'
snapshot.write_text(
'M\tC:/board.prj\tOLD\tNEW\tMAIN:1\tpreserve\t\t1\ttargets\t\x1fR1\x1fA\n'
'C\t\tR1\t0\t0\t0\t0\t\n', encoding='utf-8')
with pytest.raises(ValueError, match='UID'):
read_snapshot(snapshot)
def test_native_context_uses_refdes_fallback_for_empty_component_uid():
from dx_productivity.trial_task_center.native_helper import check_context
class Component:
UID = ''
Refdes = 'R1'
_oleobj_ = None
def FindAttribute(self, name):
value = 'OLD' if name == 'Part Number' else 'A'
return type('Attr', (), {'InstanceValue': value, 'Value': value})()
Component._oleobj_ = Component()
class View:
Block = type('Block', (), {'SheetNum': '1'})()
def GetName(self, index): return 'MAIN'
def Query(self, kind, selected): return [Component()]
class App:
ActiveView = View()
def GetProjectData(self):
return type('Project', (), {'GetProjectFilePath': lambda self: 'C:/board.prj'})()
class Api:
IVdComp = staticmethod(lambda value: value)
metadata = ['M', 'C:/board.prj', 'OLD', 'NEW', 'MAIN:1', 'preserve', '', '1', 'targets', 'x\x1fR1\x1fA']
metadata[9] = '@REFDES|R1\x1fR1\x1fA'
assert len(check_context(App(), Api(), metadata,
[['C', '@REFDES|R1', 'R1', '0', '0', '0', '0', '']], require_selection=False)) == 1
def test_native_context_rejects_duplicate_refdes_fallback():
from dx_productivity.trial_task_center.native_helper import check_context
class Component:
UID = ''
Refdes = 'R1'
_oleobj_ = None
def FindAttribute(self, name):
return type('Attr', (), {'InstanceValue': 'OLD', 'Value': 'OLD'})()
Component._oleobj_ = Component()
class View:
Block = type('Block', (), {'SheetNum': '1'})()
def GetName(self, index): return 'MAIN'
def Query(self, kind, selected): return [Component(), Component()]
class App:
ActiveView = View()
def GetProjectData(self):
return type('Project', (), {'GetProjectFilePath': lambda self: 'C:/board.prj'})()
class Api:
IVdComp = staticmethod(lambda value: value)
with pytest.raises(ValueError, match='Duplicate component UID'):
check_context(App(), Api(), ['M', 'C:/board.prj', 'OLD', 'NEW', 'MAIN:1'],
[['C', '@REFDES|R1', 'R1']])
def test_native_rejects_changed_unselected_component_since_snapshot(tmp_path):
class Component:
UID = 'u2'