merge: preserve main safety fixes in acrylic workspace

This commit is contained in:
阿白叔 committed 2026-10-31 14:07:20 +08:00
commit a41c6cf928
56 files changed
+2734 -169

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):
@@ -26,7 +26,7 @@ def test_quick_part_replace_is_an_ascii_current_sheet_automatic_contract() -> No
"Comp.Orientation",
"Comp.Scale",
"QP_App.ActiveView.Query(VDM_COMPPIN, VD_ALL)",
"CmpPin.Component.UID",
"QPComponentIdentityKey(CmpPin.Component)",
"Set Connection = CmpPin.Connection",
"Set Net = Connection.Net",
"Net.UID",
@@ -47,6 +47,8 @@ def test_quick_part_replace_is_an_ascii_current_sheet_automatic_contract() -> No
'AddAttribute("Value=" & LabelValue',
"QPNativeReplace Command, SnapshotPath",
'" --native-helper --snapshot "',
'QPLog QP_Root',
'QPAppendAscii',
):
assert required in text
@@ -117,7 +119,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
+22 -1
View File
@@ -14,7 +14,7 @@ FAKES = next(ast.literal_eval(statement.value) for statement in TREE.body
for target in statement.targets))
EXTRA = r'''
Class ValueComponent
Public UID, Refdes, Orientation, Scale, Attributes, AddCount
Public UID, Refdes, Orientation, Scale, Attributes, AddCount, Selected
Private Point
Private Sub Class_Initialize()
Set Point=New TestPoint
@@ -371,6 +371,27 @@ Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"
''', routines_transform=_batch_readback_fixture)
def test_missing_uid_capture_restore_save_and_reopen(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks, Captured
FullChecks=0
Command.Add "project_path",QPProjectPath()
Comp.FindAttribute("Part Number").Value="OLD"
QPCaptureAndSelect Command,SnapshotPath
Set Captured=QPReadSnapshot(SnapshotPath)
Require Captured.Item("components").Item("0")("uid")="@REFDES|R1","fallback lost in snapshot"
Require Captured.Item("untouched").Count=0,"target incorrectly captured as untouched"
Comp.FindAttribute("Part Number").Value="NEW"
QP_BatchMode=True:QP_SessionMode=False
QP_OwnedProject=True:QP_OwnedProjectPath=QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
QPFinishBatchItem
Require QP_App.SaveCount=1,"replacement was not saved exactly once"
Require Len(QP_App.ProjectPath)=0,"reopened project was not closed"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"missing saved readback proof"
''', before='Comp.UID=""', routines_transform=_batch_readback_fixture)
def test_non_session_no_match_closes_without_any_save(tmp_path):
run_vbs(tmp_path, 'part_number', '''
Dim FullChecks
+1 -1
View File
@@ -36,7 +36,7 @@ def ui(qtbot, tmp_path):
def settle():
qtbot.waitUntil(lambda:not window._workers and not window._task_query.busy
and not window._context_query.busy and not window._feedback_query.busy
and not window._log_presenter.query.busy,timeout=5000)
and not window._log_presenter.query.busy and not window._resource_status.busy,timeout=5000)
def open_task(task):
window.open_task(task.task_id)
qtbot.waitUntil(lambda:not window._context_query.busy and not window._loading,timeout=5000)
@@ -23,6 +23,20 @@ def test_current_task_executes_only_after_confirmation_and_no_match_is_completed
assert w.run_panel.new_round_button.isEnabled()
def test_batch_execute_button_tracks_remaining_tasks(ui):
w = ui.window
w._quick_run_confirmer = lambda *_args: True
w._prepare_quick_run()
ui.settle()
# A completed selection must still allow execution of its pending sibling.
assert w.task_list.queue_button.isEnabled()
w.task_list.queue_button.click()
ui.settle()
assert len(ui.calls) == 2
assert not w.task_list.queue_button.isEnabled(), 'a completed batch must not offer a no-op execution button'
assert w.run_panel.new_round_button.isEnabled()
@pytest.mark.parametrize('value',[False,True])
def test_changed_value_policy_stops_stale_confirmation_before_worker(ui,value):
w=ui.window;task=ui.tasks[0]
@@ -60,6 +74,17 @@ def test_regular_mutation_locks_navigation_until_completion(ui,qtbot):
ui.open(ui.tasks[1])
def test_execution_callback_failure_releases_run_controls(ui,qtbot):
w=ui.window
w._begin_run(ui.tasks[0].task_id)
w._run_async(lambda: 'result', lambda _result: (_ for _ in ()).throw(RuntimeError('render failed')),
expected_task_id=ui.tasks[0].task_id)
ui.settle()
assert w._batch_stop is None
assert not w.run_panel.busy_indicator.isVisible()
assert not w.run_panel.force_stop_button.isVisible()
def test_close_during_execution_requests_boundary_pause_and_waits(ui,qtbot):
w=ui.window;started,release=Event(),Event()
def work():
@@ -1,5 +1,6 @@
"""Readable logs and execution feedback on the current project-task interface."""
"""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()
+149 -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_unreadable_display_fields_retain_missing_state(tmp_path):
output = run_vbs(tmp_path, ['QPOptionalAttributeField', 'QPReadOptionalAttributeValue'], '''
Dim Attr
Set Attr = New BrokenOptionalAttribute
WScript.Echo "color=" & QPOptionalAttributeField(Attr, "color")
WScript.Echo "x=" & 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() == ['color=', 'x=']
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,70 @@ WScript.Echo Replace(Text,vbCrLf,"")
assert output.splitlines() == ['1', 'A\tu1\tValue\tSAME\tSAME\t0\t0\t1\t2\t3\t0\t1']
@pytest.mark.parametrize('field', ['Color', 'Font', 'Size', 'Orientation', 'Visible', 'location'])
def test_unreadable_style_blocks_snapshot_and_never_writes_default(tmp_path, field):
fake = FULL_FAKE
if field == 'location':
fake = fake.replace('Function GetLocation()\n Dim Point:',
'Function GetLocation()\n If FailRead Then Err.Raise 1234,"FakeCOM","unavailable"\n Dim Point:', 1)
record_field = 'x'
else:
fake = fake.replace('Color, Font, Size, Orientation, Visible',
', '.join(x for x in ['Color', 'Font', 'Size', 'Orientation', 'Visible'] if x != field), 1)
marker = ' Private Sub Class_Initialize\n Name = "Value"'
fake = fake.replace(marker, f''' Private Stored
Property Get {field}
If FailRead Then Err.Raise 1234,"FakeCOM","unavailable"
{field}=Stored
End Property
Property Let {field}(ByVal NewValue)
Stored=NewValue:Writes=Writes+1
End Property
Private Sub Class_Initialize
Name = "Value"''', 1)
record_field = field.lower()
output = run_vbs(tmp_path, ['QPSnapshotAttribute', 'QPOptionalAttributeField', 'QPEncode',
'QPRestoreDisplay'], f'''
Dim Attr,Text,Failure,Record,Key,FailRead,Writes
FailRead=False
Set Attr=New FullAttribute
Writes=0:FailRead=True
On Error Resume Next
Text=QPSnapshotAttribute("u1",Attr)
Failure=Err.Number:Err.Clear
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
FailRead=False
Set Record=CreateObject("Scripting.Dictionary")
For Each Key In Array("x","y","color","font","size","orientation","visible")
Record.Add Key,"1"
Next
Record("{record_field}")=""
On Error Resume Next
QPRestoreDisplay Attr,Record,"R1"
Failure=Err.Number:Err.Clear
On Error GoTo 0
WScript.Echo CStr(Failure<>0)
WScript.Echo Writes
''', LOG_STUB + fake + '''
Sub QPVerifyDisplay(ByRef Attr,ByRef Record,ByVal Refdes)
End Sub
''')
assert output.splitlines() == ['True', 'True', '0']
@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
+63
View File
@@ -165,6 +165,46 @@ def test_two_projects_reuse_cad_and_produce_distinct_close_checkpoints(tmp_path,
assert Cad.created[0].closed and Desktop.created[0].released
def test_completed_project_does_not_hold_resolution_wait_for_next_project_failure(tmp_path, monkeypatch):
import subprocess
command, _ = command_for(tmp_path)
next_command, _ = command_for(tmp_path, 'next')
runtime = worker_runtime(tmp_path, monkeypatch, lambda command, *a, **k:
subprocess.CompletedProcess(command, 0, '', ''))
with runtime:
runtime.run_worker(command, 5)
assert runtime._active_attempts == []
def fail_prepare(*args, **kwargs):
raise OSError('next project backup failed')
monkeypatch.setattr(runtime, '_prepare_attempts', fail_prepare)
with pytest.raises(OSError, match='next project backup failed'):
runtime.run_worker(next_command, 5)
assert not getattr(runtime.stop_event, 'waiting_for_resolution', False)
assert not (Path(command[3]) / 'quick-run' / 'uncertain.flag').exists()
def test_current_task_and_attempt_are_durable_before_worker_launch(tmp_path, monkeypatch):
import subprocess
one, _ = command_for(tmp_path)
two, _ = command_for(tmp_path, 'next')
next_root = Path(two[3])
command_path = next_root / 'command.tsv'
command_path.write_text(command_path.read_text().replace('task\tjob\t', 'task2\tjob2\t'), encoding='utf-8')
calls = []
def monitor(command, *args, **kwargs):
calls.append(command)
record = json.loads(runtime.path.read_text(encoding='utf-8'))
expected_task = 'task' if len(calls) == 1 else 'task2'
assert record.get('active_task') == expected_task
assert record.get('active_attempt')
return subprocess.CompletedProcess(command, 0, '', '')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
two = (*two[:-1], 'job2')
with runtime:
runtime.run_worker(one, 5)
runtime.run_worker(two, 5)
@pytest.mark.parametrize('second_fails', [False, True])
def test_prewrite_failure_releases_old_desktop_and_retries_only_once(tmp_path, monkeypatch, second_fails):
import subprocess
@@ -193,6 +233,29 @@ def test_prewrite_failure_releases_old_desktop_and_retries_only_once(tmp_path, m
and release['released_at'] > 0 for release in releases)
def test_rebuild_does_not_hide_cad_shutdown_failure(tmp_path):
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from dx_productivity.trial_task_center.errors import TaskCenterError
class FailingCad(Cad):
def __exit__(self, *_exc):
self.closed = True
self.desktop.close()
raise OSError('CAD quit confirmation failed')
runtime = BatchCadRuntime(tmp_path / 'data', 'execution',
desktop_factory=Desktop, cad_factory=FailingCad)
runtime.__enter__()
runtime._ensure_desktop()
runtime._ensure_cad()
with pytest.raises(TaskCenterError, match='CAD quit confirmation failed'):
runtime.close(rebuilding=True)
with pytest.raises(TaskCenterError, match='CAD quit confirmation failed'):
runtime.__exit__(None, None, None)
record = json.loads(runtime.path.read_text())
assert record['state'] == 'blocked'
def test_possible_mutation_prevents_automatic_replay(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
command, _ = command_for(tmp_path)
+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']
@@ -1,4 +1,5 @@
from collections import Counter
from pathlib import Path
from types import SimpleNamespace
import pytest
@@ -43,6 +44,55 @@ def test_native_readback_checks_each_unselected_attribute_once(tmp_path, target_
assert other.reads == {'Part Number': 1, 'Value': 1, 'Part Name': 1, 'Part Label': 1}
@pytest.mark.parametrize('others,changed', [(0, False), (2, False), (2, True)])
def test_legacy_readback_checks_every_unselected_component(tmp_path, others, changed):
target = Component('u1', 'R1', **{'Part Number': 'NEW', 'Part Name': 'TARGET'})
components, baseline = [target], {}
for index in range(others):
uid, refdes = f'u{index + 2}', f'R{index + 2}'
baseline[uid] = (refdes, 'OLD', 'V0', 'NAME', 'LABEL')
components.append(Component(uid, refdes, **{'Part Number': 'OLD',
'Value': 'CHANGED' if changed and index == 0 else 'V0',
'Part Name': 'NAME', 'Part Label': 'LABEL'}))
def verify():
return native.verify_replacement_readback(tmp_path / 'snapshot.tsv', components,
['M', 'project', 'OLD', 'NEW', 'sheet', 'preserve'], [['C', 'u1', 'R1']],
{c.UID for c in components}, baseline, False, None, ['u1'])
if changed:
with pytest.raises(ValueError, match='unselected component'):
verify()
else:
assert verify() == ['u1']
@pytest.mark.parametrize('count', [1, 2])
def test_missing_uid_matches_flow_into_pin_promotion(monkeypatch, count):
components = [Component('', f'R{i+1}', **{'Part Number': 'NEW', 'Part Name': 'TARGET'})
for i in range(count)]
records = [['C', f'@REFDES|R{i+1}', f'R{i+1}'] for i in range(count)]
matches = native.replacement_matches(components, records, 'NEW', False)
assert matches == [row[1] for row in records]
pins = [SimpleNamespace(Component=c, Number='1') for c in components]
for pin in pins:
pin._oleobj_ = pin
app = SimpleNamespace(ActiveView=SimpleNamespace(
Block=SimpleNamespace(PromoteSymbolNumbers=lambda *args: None),
Query=lambda *args: pins))
monkeypatch.setattr(native, 'components_on_sheet', lambda *args: components)
monkeypatch.setattr(native, 'selection', lambda *args: None)
promoted = native.promote_pin_numbers(app, SimpleNamespace(IVdCmpPin=lambda p: p), matches)
assert [pin['uid'] for pin in promoted] == matches
def test_missing_uid_fallback_survives_complete_readback():
target = Component('', 'R1', **{'Part Number': 'NEW', 'Part Name': 'TARGET', 'Part Label': 'LABEL'})
snapshot = Path('fallback-readback.tsv')
metadata = ['M', 'project', 'OLD', 'NEW', 'sheet', 'part_label', '', '1']
assert native.verify_replacement_readback(snapshot, [target], metadata,
[['C', '@REFDES|R1', 'R1']], {'@REFDES|R1'}, {}, True,
['lib', 'NEW', 'symbol', 'gate', 'TARGET', 'LABEL'], ['@REFDES|R1']) == ['@REFDES|R1']
def test_preselection_context_does_not_query_an_unused_selection(monkeypatch):
target = Component('u1', 'R1', **{'Part Number': 'OLD', 'Value': 'V0'})
target._oleobj_ = target
@@ -66,3 +116,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')
+103
View File
@@ -0,0 +1,103 @@
"""Resource snapshots stay conservative during slow, failed and repeated reads."""
import os
os.environ.setdefault('QT_QPA_PLATFORM', 'offscreen')
from threading import Event
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
def test_resource_read_failure_blocks_until_a_successful_recheck(qtbot):
outcome = [()]
def read():
if isinstance(outcome[0], Exception):
raise outcome[0]
return outcome[0]
status = ResourceStatus(read)
try:
assert status.blocked and not status.known
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.known and not status.blocked
outcome[0] = OSError('resource directory unavailable')
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.blocked and isinstance(status.error, OSError)
outcome[0] = ()
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert not status.blocked and status.error is None
finally:
status.close()
def test_operation_completion_coalesces_recheck_and_ignores_the_stale_clear_snapshot(qtbot):
started, release = Event(), Event()
calls, states = [], []
def read():
calls.append(1)
if len(calls) == 1:
started.set()
assert release.wait(5)
return ()
return ({'state': 'blocked'},)
status = ResourceStatus(read)
status.changed.connect(lambda: states.append(status.blocked))
try:
status.refresh()
qtbot.waitUntil(started.is_set)
for _ in range(10):
status.refresh()
release.set()
qtbot.waitUntil(lambda: not status.busy)
assert len(calls) == 2
assert status.records == ({'state': 'blocked'},)
assert states == [True], 'a pre-operation snapshot must not briefly unlock CAD actions'
finally:
release.set()
status.close()
def test_polling_does_not_restart_a_slow_resource_read(qtbot):
started, release = Event(), Event()
calls = []
def read():
calls.append(1)
started.set()
assert release.wait(5)
return ()
status = ResourceStatus(read)
try:
status.refresh()
qtbot.waitUntil(started.is_set)
for _ in range(10):
status._poll()
release.set()
qtbot.waitUntil(lambda: not status.busy)
assert status.known and not status.blocked
assert len(calls) == 1
finally:
release.set()
status.close()
def test_close_cancels_polling_and_drops_late_resource_results(qtbot):
started, release = Event(), Event()
changes = []
def read():
started.set()
assert release.wait(5)
return ()
status = ResourceStatus(read)
status.changed.connect(lambda: changes.append(True))
try:
status.refresh()
qtbot.waitUntil(started.is_set)
status.close()
assert not status._timer.isActive()
release.set()
qtbot.waitUntil(lambda: not status.busy)
assert status.blocked and changes == []
finally:
release.set()
status.close()
+109 -22
View File
@@ -9,6 +9,21 @@ import pytest
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch, run_monitored_process
@pytest.fixture
def started_worker_watch(monkeypatch):
"""Test phase timeouts after real child startup, with a bounded startup grace."""
stages = set()
action = ProgressWatch.action
def after_start(watch, now):
if not watch.sequence and now - watch.started < 5:
return None
if watch.sequence:
stages.add(watch.stage)
return action(watch, now)
monkeypatch.setattr(ProgressWatch, 'action', after_start)
return stages
def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
watch = ProgressWatch('token', 'job', 10, 0)
assert watch.accept(b'DX_PROGRESS\ttoken\tjob\t1\tsave_and_close\t0\t1\t0\n', 0)
@@ -20,7 +35,7 @@ def test_unsafe_save_timeout_waits_for_completion_and_recovers_on_progress():
assert watch.snapshot(now=201)['waiting_for_safe_completion'] is False
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path):
def test_real_slow_save_is_not_killed_by_inactivity(tmp_path, started_worker_watch):
script = tmp_path / 'save.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
@@ -32,10 +47,11 @@ time.sleep(1.5)
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
result = run_monitored_process(command, .3)
assert result.returncode == 0
assert 'save_and_close' in started_worker_watch
assert (tmp_path / 'saved.txt').read_text() == 'saved and independently verified'
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path):
def test_readonly_native_wait_keeps_bounded_cancellation_without_force_ui(tmp_path, started_worker_watch):
script = tmp_path / 'read.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
@@ -46,9 +62,10 @@ time.sleep(1.5)
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
with pytest.raises(subprocess.TimeoutExpired):
run_monitored_process(command, .3, cooperative_abort=True)
assert 'native_snapshot_read' in started_worker_watch
def test_explicit_force_stops_unsafe_worker_with_protection(tmp_path):
def test_explicit_force_stops_unsafe_worker_with_protection(tmp_path, monkeypatch):
script = tmp_path / 'save.py'
script.write_text('''import sys,time,pathlib
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
@@ -59,22 +76,20 @@ time.sleep(30)
(root/'unexpected_completed').touch()
''', encoding='utf-8')
force = Event()
def request():
for _ in range(200):
if (tmp_path / 'started').exists():
force.set()
return
Event().wait(.01)
requester = Thread(target=request)
requester.start()
accept = ProgressWatch.accept
def force_after_unsafe_progress(watch, line, now):
accepted = accept(watch, line, now)
if accepted and watch.stage == 'save_and_close' and not watch.safe_stop:
force.set()
return accepted
monkeypatch.setattr(ProgressWatch, 'accept', force_after_unsafe_progress)
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
try:
with pytest.raises(Exception, match='forced'):
run_monitored_process(command, .3, force_event=force)
assert (tmp_path / 'uncertain.flag').exists()
assert not (tmp_path / 'unexpected_completed').exists()
finally:
requester.join(3)
# This checks force at an accepted unsafe boundary, not startup speed.
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
with pytest.raises(WorkerMonitorError, match='forced'):
run_monitored_process(command, 5, force_event=force)
assert (tmp_path / 'uncertain.flag').exists()
assert not (tmp_path / 'unexpected_completed').exists()
def test_abnormal_cad_shutdown_is_not_hidden_by_physical_release(tmp_path):
@@ -110,6 +125,43 @@ 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'),
poll=lambda: 0 if calls else None)
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_retry_terminates_again_if_process_is_still_alive(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'), poll=lambda: None)
journal = {'operation': 'execute_task_queue', 'batch_id': 'a' * 32, 'attempt_id': 'b' * 32,
'task_ids': ['task'], 'state': 'running', 'force_state': 'termination_requested'}
_force_owned_supervisor(tmp_path, journal, process)
assert calls == ['terminate']
def test_empty_interruption_marker_is_repaired_before_force(tmp_path):
from dx_productivity.trial_task_center.stop_control import protect_interruption
marker = tmp_path / 'uncertain.flag'
marker.touch()
protect_interruption(tmp_path, 'reason=interrupted')
assert marker.read_text(encoding='utf-8') == 'reason=interrupted'
def test_force_already_performed_remains_forced_when_exit_diagnostics_fail(tmp_path):
@@ -228,7 +280,14 @@ def test_failed_protection_fsync_is_retried_before_force_is_allowed(tmp_path, mo
Event().wait(.01)
assert control.control_error
control.request_force()
thread.join(.25)
# Initial progress publication can still be doing filesystem I/O.
# Observe the rejected force request instead of assuming it reaches
# the retry within a fixed quarter-second scheduling window.
for _ in range(300):
if control.control_error:
break
Event().wait(.01)
assert control.control_error
assert thread.is_alive(), 'a file left by failed fsync must not authorize force'
assert len(attempts) >= 2
monkeypatch.setattr(module.os, 'fsync', original)
@@ -241,8 +300,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
@@ -288,6 +350,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():
@@ -326,13 +409,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
+74
View File
@@ -1,6 +1,36 @@
import pytest
@pytest.mark.parametrize('content', ['{bad', '[]', '{"cad_shutdown": 5}',
'{"cad_shutdown": {"cleanup_errors": [1]}}'])
def test_corrupt_shutdown_evidence_keeps_result_and_blocks(tmp_path, monkeypatch, content):
from dx_productivity.trial_task_center import batch_resources
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode
journal = {'operation': 'probe', 'batch_id': 'a' * 32}
root = tmp_path / 'batch-resources' / journal['batch_id']
root.mkdir(parents=True)
(root / 'session.json').write_text(content, encoding='utf-8')
monkeypatch.setattr(batch_resources, 'cleanup_pending_resources', lambda *args, **kwargs: ())
response = {'business_succeeded': True, 'status': 'ok', 'result': encode({'verified': True})}
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert caught.value.code == 'application_shutdown_failed'
assert caught.value.completed_result == {'verified': True}
assert journal['state'] == 'blocked'
def test_failed_progress_publish_emits_warning(tmp_path, monkeypatch, caplog):
from dx_productivity.trial_task_center import worker_monitor
def fail(*args):
raise OSError('disk full')
monkeypatch.setattr(worker_monitor, '_atomic_text', fail)
worker_monitor._publish_progress(tmp_path / 'progress.json', {'stage': 'awaiting_reconciliation'})
assert 'worker_progress_publish_failed' in caplog.text
@pytest.mark.parametrize('body', [None, {}, {'status':'ok','business_succeeded':'yes','result':'bad'},
{'status':'ok','business_succeeded':True,'result':'wrong type'}])
def test_invalid_result_cannot_finish_resource_gate(tmp_path, body):
@@ -21,3 +51,47 @@ def test_pending_cleanup_cannot_expose_bom_preview():
error=resource_pending_error('inspect_bom_batch',report,OSError('held desktop'))
assert error.completed_result.preview is None
assert error.bom_report.preview is None
@pytest.mark.parametrize('business_succeeded', [True, False])
def test_abnormal_shutdown_retains_bom_rows_without_an_executable_preview(tmp_path, business_succeeded):
from dx_productivity.trial_task_center.batch_resources import write_record
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.bom_batch import BomBatchPreview
from dx_productivity.trial_task_center.bom_import_report import BomImportReport, BomRowResult
from dx_productivity.trial_task_center.bom_import_state import BomImportMachine
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
report = BomImportReport((BomRowResult(4, 'board.prj', 'Board', 'failed', 'R99 missing'),), (),
BomBatchPreview('task', (), ()) if business_succeeded else None)
primary = TaskCenterError('inventory_cleanup', 'inventory reader failed')
primary.bom_report = report
journal = {'operation': 'inspect_bom_batch', 'batch_id': 'a' * 32, 'state': 'blocked'}
write_record(tmp_path / 'batch-resources' / journal['batch_id'] / 'session.json', {
'version': 1, 'session_id': journal['batch_id'], 'kind': 'bom_import', 'state': 'released',
'generation': 1, 'desktop': 'dx-' + 'b' * 32, 'processes': [], 'cad_pid': None,
'cad_guid': None, 'checkpoints': {}, 'retries': {}, 'timings': [],
'cad_shutdown': {'clean': False, 'orderly_shutdown': False}})
response = {'business_succeeded': business_succeeded, 'status': 'error',
'error': encode_error(TaskCenterError('batch_resources_pending', 'Quit failed'))}
if business_succeeded:
response['result'] = encode(report)
else:
response['operation_error'] = encode_error(primary)
machine = BomImportMachine()
attempt = machine.start()
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
failure = caught.value
assert failure.code == 'application_shutdown_failed'
machine.finish(attempt, error=failure)
assert machine.state.report is not None, 'shutdown errors must preserve Excel row diagnostics'
assert machine.state.report.rows[0].excel_row == 4
assert machine.state.report.rows[0].reason == 'R99 missing'
assert machine.state.report.preview is None
if business_succeeded:
assert failure.completed_result.preview is None
else:
assert failure.primary_error.code == 'inventory_cleanup'
+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())
+27
View File
@@ -265,6 +265,33 @@ def test_dialog_discards_choices_when_project_binding_changes_before_delivery(qt
assert '工程' in dialog.cell_status.text()
@pytest.mark.parametrize('reader_fails', [False, True])
def test_destroyed_mapping_dialog_ignores_pending_cell_reader(qtbot, reader_fails):
from PySide6.QtCore import QCoreApplication, QEvent, QThreadPool
from shiboken6 import isValid
release, started = Event(), Event()
def load(_part):
started.set()
assert release.wait(5)
if reader_fails:
raise OSError('late library failure')
return ('CellA',)
dialog = _MappingDialog(None, 'OLD', 'NEW', cell_loader=load)
dialog.cell_load_button.click()
try:
qtbot.waitUntil(started.is_set)
dialog.deleteLater()
QCoreApplication.sendPostedEvents(dialog, QEvent.Type.DeferredDelete)
assert not isValid(dialog)
finally:
release.set()
with qtbot.captureExceptions() as exceptions:
assert QThreadPool.globalInstance().waitForDone(5000)
QCoreApplication.processEvents()
assert not exceptions, 'completed readers must not access destroyed dialog widgets'
def test_update_rejects_non_text_cell_instead_of_clearing(batch):
app, store, tasks = batch
rule = app.add_rule(tasks[0].task_id, 'OLD', 'NEW', target_cell='Existing')
+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'
+3 -2
View File
@@ -20,13 +20,14 @@ def test_pending_batch_resources_block_new_work_and_cleanup_does_not_replace(win
pending.clear()
return ()
monkeypatch.setattr(window.service, 'cleanup_batch_resources', cleanup)
window._update_gates()
window._resource_status.refresh()
qtbot.waitUntil(lambda: not window._resource_status.busy)
assert not window.run_panel.quick_run_button.isEnabled()
assert not window.plan_panel.collect_button.isEnabled()
assert not window.plan_panel.import_bom_button.isEnabled()
assert window.run_panel.cleanup_resources_button.isEnabled()
window.run_panel.cleanup_resources_button.click()
qtbot.waitUntil(lambda: not window._workers)
qtbot.waitUntil(lambda: not window._workers and not window._resource_status.busy)
assert calls == ['cleanup']
assert not window.run_panel.cleanup_resources_button.isEnabled()
assert '已释放' in window.run_panel.operator_band.text()
+29
View File
@@ -40,6 +40,35 @@ def loaded(qtbot, window, task):
and window._context.task.task_id == task.task_id, timeout=3000)
def test_resource_scan_never_runs_in_gate_refresh_and_keeps_event_loop_responsive(browser, qtbot, monkeypatch):
window, service, (task, _) = browser
window.open_task(task.task_id)
loaded(qtbot, window, task)
entered, release = Event(), Event()
gui_thread = get_ident()
def slow_resources():
assert get_ident() != gui_thread, 'resource files must not be read on the GUI thread'
entered.set()
assert release.wait(5)
return ({'state': 'blocked'},)
monkeypatch.setattr(service, 'pending_batch_resources', slow_resources)
try:
window._update_gates()
window._resource_status.refresh()
qtbot.waitUntil(entered.is_set)
tick = []
QTimer.singleShot(0, lambda: tick.append(True))
window.task_list.search.setText('board')
window._update_gates()
qtbot.waitUntil(lambda: bool(tick))
assert not release.is_set()
finally:
release.set()
qtbot.waitUntil(lambda: not window._resource_status.busy)
assert window.run_panel.cleanup_resources_button.isEnabled()
assert not window.run_panel.quick_run_button.isEnabled()
def test_slow_task_read_is_background_and_stale_result_cannot_change_selection(browser, qtbot, monkeypatch):
window, service, (a, b) = browser
real = service.task_context