fix: close batch execution and recovery lifecycle

This commit is contained in:
阿白叔 committed 2026-11-17 16:56:29 +08:00
1 parent b19afc6a53
commit d9cf6a07e9
91 files changed
+5779 -454

No files matched your search

@@ -1,18 +1,14 @@
import importlib.util
import inspect
from pathlib import Path
import subprocess
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import call, patch
ROOT = Path(__file__).resolve().parents[2]
RUNTIME = ROOT / "integration" / "dxdesigner795"
SPEC = importlib.util.spec_from_file_location(
"native", ROOT / "src" / "dx_productivity" / "trial_task_center" / "native_helper.py"
)
native = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(native)
from dx_productivity.trial_task_center import native_helper as native
FAKES = r"""
Class TestPoint
@@ -107,7 +103,7 @@ End Sub
class NativeTests(unittest.TestCase):
def test_native_command_does_not_use_physical_mouse_fallback(self):
source = inspect.getsource(native.run_native)
source = inspect.getsource(inspect.unwrap(native.run_native))
self.assertIn("replacement_command_from_resources(executable)", source)
self.assertNotIn("win32api.SetCursorPos", source)
@@ -115,20 +111,24 @@ class NativeTests(unittest.TestCase):
self.assertNotIn("win32gui.SetCursorPos(screen_point)", source)
def test_snapshot_batch_is_reselected_before_the_strict_selection_gate(self):
app = object()
api = object()
metadata = ["M"]
first = type("Component", (), {"UID": "wanted"})()
other = type("Component", (), {"UID": "other"})()
first = SimpleNamespace(UID='wanted', Refdes='R1', Selected=False)
other = SimpleNamespace(UID='other', Refdes='R2', Selected=True)
first._oleobj_, other._oleobj_ = first, other
app = SimpleNamespace(ActiveView=SimpleNamespace(Query=lambda kind, scope:
[component for component in (first, other) if component.Selected]))
api = SimpleNamespace(IVdComp=lambda value:value)
records = [["C", "wanted"]]
with patch.object(native, "check_context", side_effect=([first, other], [first, other])) as check:
with patch.object(native, "selection") as select:
with patch.object(native, "check_context", return_value=[first, other]) as check:
with patch.object(native, "selection", side_effect=lambda component, selected:setattr(component,'Selected',selected)) as select, \
patch.object(native, "check_active_context"):
result = native.select_snapshot_batch(app, api, metadata, records)
self.assertEqual(result, [first, other])
self.assertEqual(check.call_args_list[0], call(app, api, metadata, records, require_selection=False))
self.assertEqual(check.call_args_list[1], call(app, api, metadata, records))
self.assertEqual(select.call_args_list, [call(first, True), call(other, False)])
self.assertTrue(first.Selected)
self.assertFalse(other.Selected)
def test_snapshot_escape_format(self):
self.assertEqual(native.decode("a%0009b%000Ac%0025"), "a\tb\nc%")
@@ -73,10 +73,11 @@ Class SessionApp
End Function
End Class
Class SessionDocuments
Public Owner, OpenCount, SheetCount
Public Owner, OpenCount, SheetCount, DocumentCount
Private Sub Class_Initialize()
OpenCount = 0
SheetCount = 1
DocumentCount = 1
End Sub
Public Function GetAvailableSchematics()
Dim Names
@@ -94,13 +95,14 @@ Class SessionDocuments
End Function
Public Function Open(ByVal Schematic, ByVal Sheet)
OpenCount = OpenCount + 1
DocumentCount = 1
Set Owner.ActiveView = Owner
Set Open = Me
End Function
Public Sub Activate()
End Sub
Public Property Get Count
Count = 1
Count = DocumentCount
End Property
Public Function Item(ByVal Index)
If Index <> 1 Then Err.Raise 51000,"Test","bad document index"
@@ -108,6 +110,7 @@ Class SessionDocuments
End Function
Public Sub Close(ByVal SaveChanges, ByVal FileName)
If SaveChanges Then Owner.SaveCount = Owner.SaveCount + 1
DocumentCount = DocumentCount - 1
Set Owner.ActiveView = Nothing
End Sub
End Class
@@ -141,6 +144,9 @@ def run_session(tmp_path, body):
target.touch()
setup = f'''
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
Set QP_SessionItems=CreateObject("Scripting.Dictionary")
Set QP_SessionSheets=CreateObject("Scripting.Dictionary")
Set QP_SessionDocuments=CreateObject("Scripting.Dictionary")
QP_Root = "{tmp_path}"
Dim Target, Attached
Target = "{target}"
+21 -6
View File
@@ -90,6 +90,7 @@ Class ValueApp
End Function
Public Sub Close(ByVal SaveChanges,ByVal FileName)
CloseCount=CloseCount+1
DocumentCount=DocumentCount-1
If SaveChanges Then
SaveCalled=True
SaveCount=SaveCount+1
@@ -149,6 +150,9 @@ End Function
SETUP = r'''
Dim Comp, Pin, Attr, Ignored, Command, Snapshot, SnapshotPath, Failure, Saved
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Set QP_SessionItems=CreateObject("Scripting.Dictionary")
Set QP_SessionSheets=CreateObject("Scripting.Dictionary")
Set QP_SessionDocuments=CreateObject("Scripting.Dictionary")
QP_Root="__ROOT__"
QP_CurrentJobId="value-job"
Set QP_App=New ValueApp
@@ -220,7 +224,7 @@ Require QP_App.UndoCount=0,"recovery undid prior CAD work"
''')
@pytest.mark.parametrize('change', ['Comp.UID="imposter"', 'Comp.Refdes="R99"'])
@pytest.mark.parametrize('change', ['Comp.Refdes="R99"'])
def test_restore_rejects_changed_component_identity_before_any_write(tmp_path, change):
run_vbs(tmp_path, 'part_number', '''
On Error Resume Next
@@ -233,6 +237,16 @@ Require QP_App.TransactionCount=0,"identity failure must precede CAD writes"
''', after=change)
def test_restore_accepts_uid_churn_without_changing_reference_or_replaying_replace(tmp_path):
run_vbs(tmp_path, 'part_number', '''
QPRestoreAfterOperatorReplace Command,SnapshotPath
Require QP_App.TransactionCount=1,"restoration did not use exactly one transaction"
Require Comp.Refdes="R1","reference identity changed"
Require Comp.FindAttribute("Value").InstanceValue="NEW","Value policy was not verified"
Require QP_App.UndoCount=0,"UID churn replayed or undid the native replacement"
''', after='Comp.UID="changed-native-uid"')
def _batch_readback_fixture(routines, *, fault=''):
# Exercise real restore/finish/guards, replacing only the external open and
# command transport with an in-memory CAD-shaped application.
@@ -242,6 +256,7 @@ End Function''', routines)
routines = re.sub(r'(?ms)^Sub QPEnsureProject\([^\n]*\n.*?^End Sub', '''Sub QPEnsureProject(ByRef App, ByVal TargetPath)
App.ProjectPath=TargetPath
App.CloseCount=0
App.DocumentCount=1
QP_OwnedProject=True
QP_OwnedProjectPath=TargetPath
''' + ('Set Attr=Other.FindAttribute("Value"): Attr.Value="DRIFT"' if fault == 'after_reopen' else '') + '''
@@ -258,7 +273,7 @@ def test_save_then_project_close_refusal_retains_save_boundary(tmp_path):
Dim FullChecks
FullChecks=0
Command.Add "project_path",QPProjectPath()
QP_BatchMode=True: QP_SessionMode=True
QP_BatchMode=True: QP_SessionMode=False
QP_SessionToken=String(32,"b")
QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
@@ -274,7 +289,7 @@ QP_App.RefuseClose=False
QPDiscardFailedBatchProject CloseError
Require Len(CloseError)>0,"uncertain save must not discard the open project"
Require Len(QPProjectPath())>0,"failed saved project was silently discarded"
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"failure published success"
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"status.tsv")),"failure published success"
''', routines_transform=_batch_readback_fixture)
@@ -284,7 +299,7 @@ def test_owned_batch_checks_full_state_at_save_and_disk_boundaries(tmp_path, fau
Dim FullChecks
FullChecks=0
Command.Add "project_path",QPProjectPath()
QP_BatchMode=True: QP_SessionMode=True
QP_BatchMode=True: QP_SessionMode=False
QP_SessionToken=String(32,"b")
QP_OwnedProject=True: QP_OwnedProjectPath=QPProjectPath()
QPRestoreAfterOperatorReplace Command,SnapshotPath
@@ -298,10 +313,10 @@ On Error GoTo 0
Require Failure=0,"valid batch failed"
Require FullChecks=2,"expected one full check before save and one after reopen"
Require QP_App.SaveCalled,"valid batch did not save"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"saved_ok")>0,"no verified result"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"saved_ok")>0,"no verified result"
''' if not fault else '''
Require Failure<>0,"unselected drift passed the commit guard"
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"project-session-result.tsv")),"failure published a completion"
Require Not QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"status.tsv")),"failure published a completion"
Require QP_App.SaveCalled=''' + ('True' if fault == 'after_reopen' else 'False') + ''',"wrong save boundary"
Require QP_BatchSaveCommitted=''' + ('True' if fault == 'after_reopen' else 'False') + ''',"saved uncertainty marker is wrong"
'''), after='''
+17 -13
View File
@@ -104,11 +104,11 @@ def test_no_match_is_recorded_as_information_not_warning(tmp_path):
assert executed[0]['details']['state'] == 'no_match'
def test_discovery_inventory_completes_definite_misses_without_reopening_projects(tmp_path):
def test_discovery_inventory_records_missing_targets_without_reopening_projects(tmp_path):
service, task, calls = setup_queue(tmp_path, ('no_match', 'no_match'))
preparer = service._quick_run_preparer
preparer._sheet_discoverer = None
preparer._discover_project_sheets = lambda _project, _parts: _ProjectDiscovery(
preparer._discover_project_sheets = lambda _project, _parts, **_options: _ProjectDiscovery(
(('Main', '1'),),
{('Main', '1'): frozenset()},
)
@@ -116,16 +116,17 @@ def test_discovery_inventory_completes_definite_misses_without_reopening_project
result = run_queue(service, task)
assert result.progress.queue_complete
assert result.progress.no_match_items == 2
assert result.progress.failed_items == 2
assert result.progress.no_match_items == 0
assert calls == []
assert all(project.summary == 'quick_run_result:0:1:saved' for project in service.projects(task.task_id))
assert all(project.summary.startswith('quick_run_result:0:0:failed') for project in service.projects(task.task_id))
events = [
json.loads(line)
for line in (tmp_path / 'data/tasks' / task.task_id / 'events.jsonl').read_text(encoding='utf-8').splitlines()
]
prefiltered = [event for event in events if event['operation'] == 'quick_run_inventory_prefiltered']
assert len(prefiltered) == 1
assert prefiltered[0]['details']['prefiltered_items'] == 2
assert not any(event['operation'] == 'quick_run_executed' for event in events)
status = (tmp_path / 'data/quick-run/status.tsv').read_text(encoding='utf-8')
assert status.count('\tbatch_skipped\tinventory_empty\t') == 2
def test_discovery_inventory_executes_present_sources_and_skips_only_absent_sources(tmp_path):
@@ -133,9 +134,11 @@ def test_discovery_inventory_executes_present_sources_and_skips_only_absent_sour
service.add_rule(task.task_id, 'ABSENT', 'OTHER')
preparer = service._quick_run_preparer
preparer._sheet_discoverer = None
preparer._discover_project_sheets = lambda _project, _parts: _ProjectDiscovery(
from dx_productivity.trial_task_center.target_plan import ComponentTarget
preparer._discover_project_sheets = lambda _project, _parts, **_options: _ProjectDiscovery(
(('Main', '1'),),
{('Main', '1'): frozenset({'old'})},
(ComponentTarget(_project, 'Main', '1', 'u1', 'R1', 'OLD', '10K'),),
)
def worker(command, timeout):
del timeout
@@ -152,7 +155,8 @@ def test_discovery_inventory_executes_present_sources_and_skips_only_absent_sour
assert result.progress.queue_complete
assert result.progress.saved_items == 1
assert result.progress.no_match_items == 1
assert result.progress.no_match_items == 0
assert result.progress.failed_items == 1
assert len(calls) == 1
@@ -496,7 +500,7 @@ def test_real_failure_isolated_from_later_project(tmp_path):
assert projects[0].status is ProjectStatus.COMPLETED
assert projects[1].status is ProjectStatus.FAILED
assert projects[2].status is ProjectStatus.COMPLETED
assert service.get_task(task.task_id).status is TaskStatus.RUNNING
assert service.get_task(task.task_id).status is TaskStatus.FAILED
assert service.quick_run_phase(task.task_id) == 'retry'
@@ -512,7 +516,7 @@ def test_batch_failure_marks_project_failed_and_continues_to_next_project(tmp_pa
assert projects[0].status is ProjectStatus.FAILED
assert projects[0].summary == 'quick_run_result:0:0:failed|Main:1 result'
assert projects[1].status is ProjectStatus.COMPLETED
assert service.get_task(task.task_id).status is TaskStatus.RUNNING
assert service.get_task(task.task_id).status is TaskStatus.FAILED
assert service.quick_run_phase(task.task_id) == 'retry'
@@ -555,7 +559,7 @@ def test_missing_project_is_skipped_and_other_projects_continue(tmp_path):
assert final_projects[0].status is ProjectStatus.FAILED
assert '工程文件不存在,已跳过' in final_projects[0].summary
assert final_projects[1].status is ProjectStatus.COMPLETED
assert service.get_task(task.task_id).status is TaskStatus.RUNNING
assert service.get_task(task.task_id).status is TaskStatus.FAILED
def test_batch_failure_continues_with_next_rule_in_same_project(tmp_path):
@@ -602,7 +606,7 @@ def test_batch_failure_continues_with_next_rule_in_same_project(tmp_path):
assert result.progress.saved_items == 1
assert result.progress.failed_items == 1
assert service.projects(task.task_id)[0].status is ProjectStatus.FAILED
assert service.get_task(task.task_id).status is TaskStatus.RUNNING
assert service.get_task(task.task_id).status is TaskStatus.FAILED
assert service.quick_run_phase(task.task_id) == 'retry'
status_text = (data / 'quick-run/status.tsv').read_text(encoding='utf-8')
assert 'batch_skipped' not in status_text
+63
View File
@@ -0,0 +1,63 @@
"""Task categories follow committed receipts before the whole batch releases."""
from threading import Event
from PySide6.QtCore import Qt
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
def visible_ids(panel):
return [panel.list.item(index).data(Qt.ItemDataRole.UserRole) for index in range(panel.list.count())]
def test_completed_task_moves_category_while_next_task_is_still_executing(ui, qtbot, monkeypatch):
window=ui.window
first,second=ui.tasks
waiting,release=Event(),Event()
execute=TaskCenterService.execute_quick_run_queue
def hold_second(service, task_id, **options):
if task_id==second.task_id:
waiting.set()
assert release.wait(10), 'test did not release its controlled second task'
return execute(service, task_id, **options)
monkeypatch.setattr(TaskCenterService,'execute_quick_run_queue',hold_second)
window._quick_run_confirmer=lambda *_args:True
try:
window._execute_project_tasks()
qtbot.waitUntil(waiting.is_set, timeout=5000)
assert ui.store.get_task(first.task_id).status is TaskStatus.COMPLETED
ui.open(second)
window.task_list.filter.setCurrentIndex(window.task_list.filter.findData('completed'))
qtbot.waitUntil(lambda:visible_ids(window.task_list)==[first.task_id], timeout=3000)
assert window._workers and window._batch_stop is not None
assert window._task_id==second.task_id
assert ui.store.get_task(second.task_id).status is not TaskStatus.COMPLETED
assert len(ui.calls)==1
finally:
release.set()
ui.settle()
assert len(ui.calls)==2
assert set(visible_ids(window.task_list))=={first.task_id,second.task_id}
def test_resource_error_after_business_completion_refreshes_categories(ui):
window=ui.window
first=ui.tasks[0]
window._begin_run(first.task_id)
window._quick_run_timer.stop() # The final error path must refresh even without a timer tick.
window.task_list.filter.setCurrentIndex(window.task_list.filter.findData('completed'))
def execute_then_fail_release():
progress=ui.service.quick_run_progress(first.task_id)
expected=(str(progress.next_project_path),progress.next_old_part_number,
progress.next_new_part_number,'preserve')
ui.service.execute_quick_run_queue(first.task_id,expected_item=expected,
stop_event=window._batch_stop)
raise BatchResourceCleanupError('controlled desktop release failure after task completion')
window._run_async(execute_then_fail_release,lambda _:None,expected_task_id=first.task_id)
ui.settle()
assert ui.store.get_task(first.task_id).status is TaskStatus.COMPLETED
assert visible_ids(window.task_list)==[first.task_id]
assert window._batch_stop is None
assert len(ui.calls)==1
assert 'controlled desktop release failure' in window.run_panel.operator_band.text()
+39 -2
View File
@@ -28,10 +28,14 @@ def visible_ids(panel):
@pytest.mark.parametrize(('category','expected'),[
('all',['draft','ready','running','paused','completed','failed']),
('unfinished',['draft','ready','running','paused','failed']),
('all',['draft','ready','running','paused','completed','failed','blocked']),
('unfinished',['draft','ready','running','paused','failed','blocked']),
('pending',['draft','ready']),
('running',['running']),
('paused',['paused']),
('completed',['completed']),
('failed',['failed']),
('blocked',['blocked']),
])
def test_visible_status_category_filters_task_list(navigation,category,expected):
panel,tasks,opened=navigation
@@ -89,3 +93,36 @@ def test_recycle_bin_ignores_active_status_category(ui):
assert panel.filter.isEnabled()
assert panel.filter.currentData()=='completed'
assert visible_ids(panel)==[]
def test_retryable_failure_is_in_failed_category_and_never_displayed_as_running(navigation):
panel,tasks,opened=navigation
failed = replace(tasks[2], summary='current-sheet quick-run queue completed with retryable failures')
panel.populate(tuple(failed if task.task_id == failed.task_id else task for task in tasks))
panel.filter.setCurrentIndex(panel.filter.findData('failed'))
assert visible_ids(panel)==['running','failed']
assert panel.list.item(0).text().splitlines()[-1]=='失败'
panel.filter.setCurrentIndex(panel.filter.findData('running'))
assert visible_ids(panel)==[]
assert failed.status is TaskStatus.RUNNING # Display classification does not authorize a retry.
def test_status_refresh_preserves_multiple_selected_tasks(navigation):
panel,tasks,opened=navigation
panel.select_all_tasks()
updated=tuple(replace(task,status=TaskStatus.COMPLETED) if task.task_id=='ready' else task for task in tasks)
panel.populate(updated,selected_task_id='ready')
assert {item.data(Qt.ItemDataRole.UserRole) for item in panel.list.selectedItems()} == {
task.task_id for task in tasks}
def test_status_refresh_does_not_reselect_a_current_item_the_user_deselected(navigation):
panel,tasks,opened=navigation
panel.select_all_tasks()
panel.list.currentItem().setSelected(False)
before={item.data(Qt.ItemDataRole.UserRole) for item in panel.list.selectedItems()}
assert 'ready' not in before
updated=tuple(replace(task,status=TaskStatus.COMPLETED) if task.task_id=='ready' else task for task in tasks)
panel.populate(updated,selected_task_id='ready')
assert {item.data(Qt.ItemDataRole.UserRole) for item in panel.list.selectedItems()}==before
assert panel.current_task_id()=='ready'
+7 -1
View File
@@ -25,8 +25,12 @@ def run_vbs(tmp_path, names, body, prelude=''):
names = tuple(names)
support = tuple(name for name in ('QPReadOptionalAttributeValue', 'QPRequiredAttributeValue',
'QPReadableAttributeValue', 'QPEffectiveAttributeValue',
'QPComponentIdentityKey', 'QPComparableState', 'QPEncode', 'QPDecode')
'QPComponentIdentityKey', 'QPComponentUnitKey', 'QPBindSheetReferences',
'QPBindSnapshotReference', 'QPBindSnapshotFullState', 'QPCommandTargetKey',
'QPComparableState', 'QPEncode', 'QPDecode')
if name not in {n.lstrip('?') for n in names})
if not re.search(r'(?mi)^Dim [^\n]*\bQP_ReferenceAliases\b', prelude + '\n' + body):
prelude += '\nDim QP_ReferenceAliases\n'
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,
@@ -112,6 +116,8 @@ End Sub
Function QPUntouchedFullState(ByRef component)
QPUntouchedFullState = component
End Function
Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total)
End Sub
''')
assert output=='stable semantic state'
+10 -13
View File
@@ -1,4 +1,4 @@
"""An external Windows reference blocks a batch without replaying its results."""
"""An external Windows reference is isolated after owned writers exit."""
import json
import os
from pathlib import Path
@@ -21,26 +21,23 @@ def test_external_reference_preserves_completed_result_until_resource_only_clean
runtime.bind_logs(configure_logging(tmp_path), ('windows-resource-test',))
external = None
try:
with pytest.raises(BatchResourceCleanupError) as caught:
with runtime:
with runtime.native_scope(tmp_path / 'completed-operation') as scope:
with runtime:
with runtime.native_scope(tmp_path / 'completed-operation') as scope:
# The test owns this independent actor, outside runtime's
# process/job list. The runtime must leave it alive.
external = _Win32Api().create_process((sys.executable, '-u', '-c',
external = _Win32Api().create_process((sys.executable, '-u', '-c',
'import win32service,time,sys; '
'd=win32service.OpenDesktop(sys.argv[1],0,False,0x10000000); '
'd.SetThreadDesktop();print("ready",flush=True);time.sleep(30)', scope.name),
build_startup_info(scope.name).lpDesktop, None, None,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
assert external.stdout.readline() == b'ready\r\n'
runtime.result = 'already saved and independently verified'
assert caught.value.completed_result == runtime.result
assert external.stdout.readline() == b'ready\r\n'
runtime.result = 'already saved and independently verified'
assert external.poll() is None
assert json.loads(runtime.path.read_text())['state'] == 'blocked'
assert json.loads(runtime.path.read_text())['state'] == 'isolated'
log = runtime.path.with_name('resource-release.log').read_text(encoding='utf-8')
assert '资源释放失败' in log and '桌面消失:未确认' in log
with pytest.raises(BatchResourceCleanupError):
guard_pending_resources(tmp_path)
assert 'isolated' in log
guard_pending_resources(tmp_path)
assert not list(Path(tmp_path).rglob('uncertain.flag'))
assert current_desktop_name() == before
finally:
@@ -52,7 +49,7 @@ def test_external_reference_preserves_completed_result_until_resource_only_clean
assert runtime.generation == 1
rows = [json.loads(line) for line in (tmp_path / 'tasks/windows-resource-test/events.jsonl')
.read_text(encoding='utf-8').splitlines()]
assert [row['operation'] for row in rows] == ['resource_release_started', 'resource_release_failed',
assert [row['operation'] for row in rows] == ['resource_release_started', 'resource_release_isolated',
'resource_release_started', 'resource_release_succeeded']
assert rows[-1]['details']['desktop_disappeared'] is True
guard_pending_resources(tmp_path)
+13
View File
@@ -419,3 +419,16 @@ def test_retained_scope_honors_optional_selectors_and_disabled_overrides(batch,
retained = retained_bom_rows((request,), rows)
assert len(retained) == 1 and retained[0].target.uid == retained_uid
assert retained[0] is next(row for row in rows if row.target.uid == retained_uid)
def test_unique_pending_reference_does_not_retain_old_row_due_to_stale_uid(batch):
from dx_productivity.trial_task_center.bom_pending import PendingBomRequest, retained_bom_rows
from dx_productivity.trial_task_center.bom_plan import BomRecord
from dx_productivity.trial_task_center.target_plan import TargetPlanRow
service, store, tasks, targets, calls = batch
first, second = targets[tasks[0].task_id]
rows = (TargetPlanRow(first, True, 'KEEP-1'), TargetPlanRow(second, True, 'KEEP-2'))
record = BomRecord(str(first.project_path), 'OLD', 'NEW', (first.refdes,),
first.schematic_name, first.sheet_number, 'stale-uid', False, '', True)
request = PendingBomRequest(record, 'source.xlsx', 8, 'hash')
assert retained_bom_rows((request,), rows) == (rows[1],)
+20
View File
@@ -20,6 +20,26 @@ def setup_store(tmp_path):
return store, task, targets
def test_unique_scoped_reference_ignores_stale_bom_uid(tmp_path):
from dx_productivity.trial_task_center.bom_plan import BomMatcher, BomRecord
from dx_productivity.trial_task_center.target_plan import TargetPlanRow
target = ComponentTarget(tmp_path / 'board.prj', 'MAIN', '1', 'current', 'R1', 'OLD', '10nF')
matcher = BomMatcher((TargetPlanRow(target),))
record = BomRecord('', 'OLD', 'NEW', ('R1',), 'MAIN', '1', 'stale', True, '', True)
matched = matcher.match_record(record)
assert len(matched) == 1 and next(iter(matched.values())).target is target
def test_uid_can_only_disambiguate_multiple_reference_candidates(tmp_path):
from dx_productivity.trial_task_center.bom_plan import BomMatcher, BomRecord
from dx_productivity.trial_task_center.target_plan import TargetPlanRow
first = ComponentTarget(tmp_path / 'board.prj', 'MAIN', '1', 'u1', 'R1', 'OLD', '10nF')
second = ComponentTarget(tmp_path / 'board.prj', 'MAIN', '2', 'u2', 'R1', 'OLD', '10nF')
matcher = BomMatcher((TargetPlanRow(first), TargetPlanRow(second)))
record = BomRecord('', 'OLD', 'NEW', ('R1',), '', '', 'u2', True, '', True)
assert next(iter(matcher.match_record(record).values())).target is second
def test_already_target_does_not_accept_duplicate_nc_from_leading_marker(tmp_path):
from dx_productivity.trial_task_center.bom_plan import BomMatcher, BomRecord
from dx_productivity.trial_task_center.target_plan import TargetPlanRow
+163
View File
@@ -0,0 +1,163 @@
import json
import os
import zipfile
import pytest
from dx_productivity.trial_task_center import diagnostics_bundle as bundle
from dx_productivity.trial_task_center.execution_feedback import read_feedback
from dx_productivity.trial_task_center.ui.execution_feedback import format_feedback
def write(root, name, text):
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding='utf-8')
return path
def test_bundle_exports_execution_closure_and_inventory_evidence(tmp_path):
names = {
'tasks/t/quick-run/worker-progress.json': '{"stage":"save_and_close"}',
'tasks/t/quick-run/quick-part-replace.log': 'native returned token=private-token',
'tasks/t/quick-run/project-commit-' + 'a' * 32 + '.tsv': 'saved_ok\tjob1',
'tasks/t/quick-run/project-pause-' + 'a' * 32 + '.tsv': 'paused\tjob2',
'tasks/t/quick-run/post-state-job1.tsv': 'R1\tNEW',
'tasks/t/quick-run/value-readback-job1.json': '{"verified":true}',
'execution-proof/proof1/project-commit-' + 'a' * 32 + '.tsv': 'saved_ok\tjob1',
'execution-proof/proof1/completion.json': '{"verified":true}',
'tasks/t/quick-run-history/native-inventory-a/native-inventory.json': '{"state":"ready"}',
'tasks/t/quick-run-history/native-inventory-a/output/scope.txt': 'R1\tUID1',
'tasks/t/quick-run-history/native-inventory-a/output/effective.txt': 'R1\tNEW',
'tasks/t/netlist-checks/run1/verification.json': '{"verified":true}',
'tasks/t/netlist-checks/run1/after-export/netlist.json': '{"complete":true}',
}
for name, text in names.items():
write(tmp_path, name, text)
write(tmp_path, 'tasks/t/netlist-checks/run1/before/project.prj', 'private project')
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert set(names).issubset(archive.namelist())
assert 'private-token' not in archive.read('tasks/t/quick-run/quick-part-replace.log').decode()
assert all(not name.endswith('.prj') for name in archive.namelist())
def test_bundle_tails_active_logs_and_keeps_latest_evidence_under_budget(tmp_path, monkeypatch):
monkeypatch.setattr(bundle, 'MAX_FILE_BYTES', 160)
monkeypatch.setattr(bundle, 'MAX_FILES', 2)
for index in range(4):
path = write(tmp_path, f'tasks/{index}/quick-run/worker-progress.json', json.dumps({'stage': str(index)}))
os.utime(path, (100 + index, 100 + index))
log = write(tmp_path, 'tasks/latest/quick-run/quick-part-replace.log',
'old heartbeat\n' * 100 + 'last failure token=secret-value\n')
os.utime(log, (500, 500))
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
text = archive.read('tasks/latest/quick-run/quick-part-replace.log').decode()
assert 'last failure' in text and 'secret-value' not in text
assert 'tasks/3/quick-run/worker-progress.json' in archive.namelist()
manifest = json.loads(archive.read('manifest.json'))
assert manifest['truncated'][0]['mode'] == 'tail'
@pytest.mark.parametrize('record,reason,wait', [
({'stage': 'native_replace', 'stop_requested': True}, 'inactivity', 'native_call'),
({'stage': 'save_and_close', 'stopping_reason': 'user_pause'}, 'user_pause', 'save'),
({'stage': 'verify_saved_project'}, '', 'readback'),
({'stage': 'private_shutdown', 'stopping_reason': 'failure_cleanup', 'wait_reason': 'mentor_exit'},
'failure_cleanup', 'mentor_exit'),
({'stage': 'awaiting_reconciliation', 'primary_error': 'native failed'}, '', 'reconciliation'),
])
def test_feedback_classifies_stop_and_actual_wait_without_generic_save(tmp_path, record, reason, wait):
write(tmp_path, 'quick-run/worker-progress.json', json.dumps(record))
value = read_feedback('t', 1, 1, 'running', tmp_path, 0)
assert value.stopping_reason == reason
assert value.wait_reason == wait
text = format_feedback(value, 'board', 4, True)
if wait != 'save':
assert '保存' not in text
if record.get('primary_error'):
assert record['primary_error'] in text
def test_operation_events_preserve_last_success_and_incomplete_call(tmp_path):
from dx_productivity.trial_task_center.operation_diagnostics import record_operation
assert record_operation(tmp_path / 'quick-run', 'item', 'return', item_id='job1')
assert record_operation(tmp_path / 'quick-run', 'save', 'enter', item_id='job2')
assert record_operation(tmp_path / 'quick-run', 'mentor_exit', 'enter')
assert record_operation(tmp_path / 'quick-run', 'mentor_exit', 'error', error='cleanup failed')
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
summary = json.loads(archive.read('closure-summary.json'))['operations']['quick-run']
assert summary['last_successful_item'] == 'job1'
assert summary['incomplete_operations'][0]['operation'] == 'save'
assert summary['errors'][0]['error'] == 'cleanup failed'
def test_stop_control_keeps_failure_reason_and_first_error(tmp_path):
from dx_productivity.trial_task_center.stop_control import StopControl, wait_for_resolution, MentorReleaseRequired
control = StopControl()
with pytest.raises(MentorReleaseRequired):
wait_for_resolution(control, tmp_path, 'native failed', release_on_failure=True)
assert control.stopping_reason == 'failure_cleanup'
assert control.primary_error == 'native failed'
control.request_failure_cleanup(tmp_path, 'later cleanup failure')
assert control.primary_error == 'native failed'
record = json.loads((tmp_path / 'worker-progress.json').read_text())
assert record['primary_error'] == 'native failed'
assert record['wait_reason'] == 'reconciliation'
def test_closing_desktop_overrides_old_save_wait(tmp_path):
write(tmp_path, 'quick-run/worker-progress.json', json.dumps({
'stage': 'save_and_close', 'wait_reason': 'save', 'stopping_reason': 'failure_cleanup'}))
write(tmp_path, 'quick-run/private-desktop.json', '{"state":"closing"}')
value = read_feedback('t', 1, 1, 'running', tmp_path, 0)
assert value.wait_reason == 'desktop_release'
assert '保存' not in format_feedback(value, 'board', 4, True)
def test_bundle_keeps_complete_event_tail_and_latest_successful_status(tmp_path):
write(tmp_path, 'quick-run/operation-events.jsonl',
'{"operation":"save","event":"enter","item_id":"job2"}\n{"broken":')
write(tmp_path, 'quick-run/status.tsv',
'job1\tsaved_ok\tsession_verified\tdone\njob2\tpending_save\tsession_staged\tstaged\n')
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
summary = json.loads(archive.read('closure-summary.json'))
assert summary['items']['quick-run']['last_successful_item'] == 'job1'
assert summary['items']['quick-run']['latest_item'] == {'job_id': 'job2', 'state': 'pending_save'}
assert summary['operations']['quick-run']['incomplete_operations'][0]['operation'] == 'save'
manifest = json.loads(archive.read('manifest.json'))
assert any(row['reason'] == 'invalid_jsonl_lines' for row in manifest['omissions'])
def test_bundle_keeps_valid_call_when_other_event_has_invalid_shape(tmp_path):
write(tmp_path, 'quick-run/operation-events.jsonl',
'{"operation":[],"event":"enter","item_id":{}}\n'
'{"operation":"save","event":"enter","item_id":"job1"}\n')
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
summary = json.loads(archive.read('closure-summary.json'))
assert summary['operations']['quick-run']['incomplete_operations'][0]['operation'] == 'save'
def test_bundle_reads_native_ascii_report_using_local_windows_encoding(tmp_path):
name = 'quick-run-history/native-inventory-a/output/scope.txt'
path = write(tmp_path, name, '')
path.write_bytes('R1 中文说明'.encode('mbcs' if os.name == 'nt' else 'cp1252', errors='replace'))
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
assert name in archive.namelist()
assert 'R1 ' in archive.read(name).decode('utf-8')
def test_redaction_growth_does_not_discard_latest_failure_tail(tmp_path, monkeypatch):
monkeypatch.setattr(bundle, 'MAX_FILE_BYTES', 128)
name = 'quick-run/quick-part-replace.log'
write(tmp_path, name, 'token=x\n' * 100 + 'native failed token=y\n')
output = bundle.export_diagnostic_bundle(tmp_path, tmp_path / 'support.zip')
with zipfile.ZipFile(output) as archive:
text = archive.read(name).decode()
assert 'native failed' in text
assert len(archive.read(name)) <= 128
+161
View File
@@ -0,0 +1,161 @@
import json
from pathlib import Path
import subprocess
import sys
import pytest
from dx_productivity.trial_task_center import batch_resources, batch_worker, operation_diagnostics
from dx_productivity.trial_task_center.project_session import ProjectSessionWorker
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
from test_project_session import toy_worker
def events(root):
path = root / 'operation-events.jsonl'
return [json.loads(line) for line in path.read_text(encoding='utf-8').splitlines()] if path.exists() else []
def test_native_step_and_commit_enter_events_precede_real_worker_dispatch(tmp_path):
command = toy_worker(tmp_path)
script = Path(command[2])
source = script.read_text(encoding='utf-8').replace('job=initial; sequence=0', '''job=initial; sequence=0
events=[json.loads(line) for line in (root/'operation-events.jsonl').read_text().splitlines()]
assert any(e['operation']=='native_step' and e['event']=='enter' and e['item_id']==job for e in events)''')
source = source.replace("if job=='close':break", '''if job=='close':
events=[json.loads(line) for line in (root/'operation-events.jsonl').read_text().splitlines()]
assert any(e['operation']=='close_project' and e['event']=='enter' for e in events)
break''')
script.write_text(source, encoding='utf-8')
worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path)
try:
assert worker.run_step(command, 3).returncode == 0
assert [(e['operation'], e['event']) for e in events(tmp_path)] == [('native_step', 'enter'), ('native_step', 'return')]
assert not (tmp_path / 'closed.txt').exists()
finally:
worker.close()
assert [(e['operation'], e['event']) for e in events(tmp_path)] == [
('native_step', 'enter'), ('native_step', 'return'), ('close_project', 'enter'), ('close_project', 'return')]
assert not any(e['operation'] in {'item', 'readback'} for e in events(tmp_path))
@pytest.mark.parametrize('diagnostic_failure', [False, True])
def test_native_failure_keeps_primary_error_even_when_diagnostics_fail(tmp_path, monkeypatch, diagnostic_failure):
command = toy_worker(tmp_path)
script = Path(command[2])
script.write_text(script.read_text(encoding='utf-8').replace('saved_ok', 'invalid_checkpoint'), encoding='utf-8')
if diagnostic_failure:
monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure')))
worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path)
try:
with pytest.raises(WorkerMonitorError, match='invalid checkpoint'):
worker.run_step(command, 3)
finally:
worker.close()
if not diagnostic_failure:
records = [row for row in events(tmp_path) if row['operation'] == 'native_step']
assert [row['event'] for row in records] == ['enter', 'error']
assert 'invalid checkpoint' in records[-1]['error']
def test_diagnostic_failure_does_not_block_worker_success_or_native_close(tmp_path, monkeypatch):
monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure')))
worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path)
try:
assert worker.run_step(toy_worker(tmp_path), 3).returncode == 0
finally:
worker.close()
assert (tmp_path / 'closed.txt').exists()
def test_native_close_failure_logs_error_and_never_a_successful_close(tmp_path):
command = toy_worker(tmp_path)
script = Path(command[2])
script.write_text(script.read_text(encoding='utf-8') + '\nsys.exit(7)\n', encoding='utf-8')
worker = ProjectSessionWorker(tmp_path / 'board.prj', tmp_path)
assert worker.run_step(command, 3).returncode == 0
with pytest.raises(WorkerMonitorError, match='did not close cleanly'):
worker.close()
closing = [row for row in events(tmp_path) if row['operation'] == 'close_project']
assert [row['event'] for row in closing] == ['enter', 'error']
worker.close()
assert [row for row in events(tmp_path) if row['operation'] == 'close_project'] == closing
def test_result_persistence_enter_is_durable_before_actual_result_write(tmp_path, monkeypatch):
original = batch_resources.write_record
def observe(path, value):
assert [(e['operation'], e['event']) for e in events(tmp_path)] == [('result_persistence', 'enter')]
assert not path.exists()
original(path, value)
monkeypatch.setattr(batch_resources, 'write_record', observe)
result = {'attempt_id': 'attempt', 'payload': {'status': 'ok'}}
batch_worker._persist_result(tmp_path, result)
assert json.loads((tmp_path / 'result.json').read_text(encoding='utf-8')) == result
assert [(e['operation'], e['event']) for e in events(tmp_path)] == [('result_persistence', 'enter'), ('result_persistence', 'return')]
@pytest.mark.parametrize('diagnostic_failure', [False, True])
def test_result_write_failure_remains_original_exception_and_never_logs_success(tmp_path, monkeypatch, diagnostic_failure):
failure = OSError('result storage failed')
monkeypatch.setattr(batch_resources, 'write_record', lambda *args: (_ for _ in ()).throw(failure))
if diagnostic_failure:
monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure')))
with pytest.raises(OSError) as caught:
batch_worker._persist_result(tmp_path, {'attempt_id': 'attempt'})
assert caught.value is failure
assert not (tmp_path / 'result.json').exists()
if not diagnostic_failure:
assert [e['event'] for e in events(tmp_path)] == ['enter', 'error']
assert events(tmp_path)[-1]['error'] == 'result storage failed'
def test_diagnostic_failure_does_not_block_actual_result_persistence(tmp_path, monkeypatch):
monkeypatch.setattr(operation_diagnostics, 'record_operation', lambda *args, **kwargs: (_ for _ in ()).throw(OSError('diagnostic disk failure')))
batch_worker._persist_result(tmp_path, {'attempt_id': 'attempt', 'payload': 'completed'})
assert json.loads((tmp_path / 'result.json').read_text(encoding='utf-8'))['payload'] == 'completed'
def test_real_supervisor_result_write_uses_structured_persistence_boundary(tmp_path):
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
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'
directory = next((tmp_path / 'batch-resources').iterdir())
assert [row['event'] for row in events(directory) if row['operation'] == 'result_persistence'] == ['enter', 'return']
assert (directory / 'result.json').exists()
finally:
store.close()
def test_result_write_process_crash_leaves_durable_incomplete_boundary(tmp_path):
source = Path(__file__).resolve().parents[2] / 'src'
script = '''import os,sys
from pathlib import Path
sys.path.insert(0,sys.argv[1])
from dx_productivity.trial_task_center import batch_resources,batch_worker
batch_resources.write_record=lambda *args: os._exit(23)
batch_worker._persist_result(Path(sys.argv[2]),{'attempt_id':'attempt'})
'''
result = subprocess.run((sys.executable, '-c', script, str(source), str(tmp_path)), capture_output=True, timeout=10)
assert result.returncode == 23, result.stderr
summary = operation_diagnostics.summarize_operations(events(tmp_path))
assert [(e['operation'], e['item_id']) for e in summary['incomplete_operations']] == [('result_persistence', 'attempt')]
assert not (tmp_path / 'result.json').exists()
def test_incomplete_actual_operation_can_be_reported_before_return(tmp_path):
with operation_diagnostics.operation_span(tmp_path, 'native_step', item_id='job'):
summary = operation_diagnostics.summarize_operations(events(tmp_path))
assert [(e['operation'], e['item_id']) for e in summary['incomplete_operations']] == [('native_step', 'job')]
assert summary['last_successful_item'] is None
assert operation_diagnostics.summarize_operations(events(tmp_path))['incomplete_operations'] == []
def test_diagnostic_serialization_failure_is_nonblocking(tmp_path):
assert operation_diagnostics.record_operation(tmp_path, 'native_step', 'enter', item_id=object()) is False
@@ -116,17 +116,28 @@ def test_manual_failure_cannot_be_completed_by_native_progress(failed_native):
service.quick_run_progress(task_id)
def test_uncertain_batch_failed_blocks_next_project_in_task_queue(failed_native, tmp_path):
def test_uncertain_batch_failed_isolated_before_next_project_in_task_queue(failed_native, tmp_path, monkeypatch):
from threading import Event
from dx_productivity.trial_task_center.task_queue import execute_task_queue
service, store, task_id, _, _ = failed_native
other = store.create_task('next must not run')
other = store.create_task('independent next project')
path = tmp_path / 'next.prj'
path.touch()
project = store.sync_projects(other.task_id, tmp_path, (path,))[0]
store.set_project_selected(project.project_id, True)
store.bind_project_task(other.task_id, project.project_id, 'batch', 1)
result = execute_task_queue(service, (task_id, other.task_id), stop_event=Event())
assert result.paused
assert [entry.state for entry in result.entries] == ['blocked', 'pending']
from test_project_isolation_queue import ReleasedRuntime
from dx_productivity.trial_task_center.quick_run_protocol import QuickRunProgress
calls = []
child = service.for_project_task(other.task_id)
monkeypatch.setattr(child, 'quick_run_progress', lambda _: calls.append(other.task_id) or QuickRunProgress(
0, 0, None, None, None, (path,), True))
monkeypatch.setattr(child, 'has_interrupted_quick_run', lambda _: False)
child._quick_run_preparer.reconcile_terminal_receipts = lambda _: None
original_child = service.for_project_task
monkeypatch.setattr(service, 'for_project_task', lambda identifier: child if identifier == other.task_id else original_child(identifier))
result = execute_task_queue(service, (task_id, other.task_id), stop_event=Event(), runtime=ReleasedRuntime(service._logging.root))
assert not result.paused
assert [entry.state for entry in result.entries] == ['blocked', 'completed']
assert calls == [other.task_id]
assert not (service.for_project_task(other.task_id)._quick_run_preparer.data_root / 'quick-run').exists()
+5
View File
@@ -42,6 +42,11 @@ def test_inventory_rejects_changed_or_removed_baseline_atomically(batch, change)
incoming.append(incoming[0])
else:
incoming[0] = replace(incoming[0], **{change: 'CHANGED'})
if change == 'uid':
rows = store.record_target_inventory(task.task_id, incoming)
assert len(rows) == 3
assert {row.target.key: row for row in rows}[before[0].target.key] == before[0]
return
with pytest.raises(TaskCenterError):
store.record_target_inventory(task.task_id, incoming)
assert store.list_target_plan(task.task_id) == before
@@ -0,0 +1,230 @@
from pathlib import Path
from types import SimpleNamespace
import pytest
from test_failed_native_recovery_guard import failed_native
from dx_productivity.trial_task_center import batch_resources, batch_runtime
from dx_productivity.trial_task_center.stop_control import StopControl, ProjectStopControl
def test_project_force_observes_user_force_without_leaking_failure_to_parent(tmp_path):
from dx_productivity.trial_task_center.workspace_execution import _ProjectControl
parent = StopControl()
local = _ProjectControl(parent)
local.request_failure_cleanup(tmp_path, 'A failure')
assert local.force_event.is_set()
assert not parent.force_event.is_set() and not parent.is_set()
successor = _ProjectControl(parent)
assert not successor.force_event.is_set() and not successor.is_set()
parent.request_force()
assert successor.is_set() and successor.force_event.wait(.01)
@pytest.mark.parametrize('residual', [False, True])
def test_failed_project_retires_proven_exit_despite_shutdown_error(tmp_path, residual):
from test_batch_runtime import Desktop
class OwnedDesktop(Desktop):
def close(self):
self.cleanup_record = {'desktop_handle_closed': True, 'owned_cleanup_complete': True,
'desktop_confirmation': {'released': not residual}, 'errors': []}
if residual: raise OSError('foreign desktop reference')
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', ProjectStopControl(StopControl()), desktop_factory=OwnedDesktop)
runtime._ensure_desktop()
def cad_exit(*args): raise OSError('shutdown diagnostics failed after exit')
runtime.cad = SimpleNamespace(cad=SimpleNamespace(poll=lambda: 0), record={}, __exit__=cad_exit)
original = RuntimeError('original failed project')
assert runtime.release_failed_project(original, tmp_path / 'failed')
assert batch_resources.blocking_resources(tmp_path) == ()
assert runtime.record['state'] == ('isolated' if residual else 'released')
assert runtime.record['release_results']['desktop_released'] is (not residual)
assert runtime.desktop is None and 'shutdown diagnostics failed' in original.shutdown_warning
assert (tmp_path / 'failed' / 'uncertain.flag').exists()
def test_runtime_cleanup_events_record_real_boundaries_and_preserve_error(tmp_path):
import json
from test_batch_runtime import Desktop
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
def cad_exit(*args): raise OSError('actual exit error')
runtime.cad = SimpleNamespace(cad=SimpleNamespace(poll=lambda: 0), record={}, __exit__=cad_exit)
with pytest.raises(batch_resources.BatchResourceCleanupError, match='actual exit error'):
runtime.close()
rows = [json.loads(line) for line in (runtime.path.parent / 'operation-events.jsonl').read_text().splitlines()]
assert [(row['operation'], row['event']) for row in rows] == [
('mentor_exit', 'enter'), ('mentor_exit', 'error'), ('desktop_release', 'enter'), ('desktop_release', 'return')]
def test_workspace_accepts_writer_exit_warning_and_blocks_shared_source_follower(tmp_path, monkeypatch):
from test_workspace_execution import service_for
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
from dx_productivity.trial_task_center.errors import TaskCenterError
failure = TaskCenterError('quick_run_uncertain', 'A business outcome unknown')
failure.resources_released = False
failure.owned_writers_exited = True
service, calls = service_for(tmp_path, monkeypatch, {'A': failure, 'B': 'completed'})
result = execute_workspace_projects(service, ('A', 'B'), stop_event=StopControl())
assert not result.paused and result.entries[1].state == 'completed'
calls.clear()
for name in ('A', 'B'):
path = tmp_path / name / 'board.prj'
path.parent.mkdir(exist_ok=True)
path.write_text('KEY iCDBDir "../shared"\n')
result = execute_workspace_projects(service, ('A', 'B'), stop_event=StopControl())
assert not result.paused and [row.state for row in result.entries] == ['blocked', 'blocked']
assert [call[1]['task_ids'][0] for call in calls] == ['A']
def test_blocked_progress_read_does_not_promote_or_throw(failed_native):
from dx_productivity.trial_task_center.models import TaskStatus
service, store, task_id, handoff, _ = failed_native
store.set_task_status(task_id, TaskStatus.BLOCKED, summary='requires reconciliation')
service.quick_run_progress(task_id)
assert store.get_task(task_id).status is TaskStatus.BLOCKED
def test_public_recovery_tries_verified_project_commit_before_cad(failed_native, monkeypatch):
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.quick_run_protocol import QuickRunStepResult
from dx_productivity.trial_task_center.service import TaskCenterService
service, store, task_id, handoff, _ = failed_native
store.set_task_status(task_id, TaskStatus.BLOCKED, summary='project commit publication failed')
child = service.for_project_task(task_id)
result = QuickRunStepResult(handoff.script_path, handoff.command_path, handoff.status_path,
handoff.log_path, 'saved_ok', 'verified durable project commit')
calls = []
monkeypatch.setattr(child._quick_run_preparer, 'recover_project_commit',
lambda identifier, *, confirmed: calls.append((identifier, confirmed)) or result, raising=False)
monkeypatch.setattr(service, '_synchronize_quick_run_progress', lambda identifier: calls.append(('sync', identifier)))
monkeypatch.setattr(TaskCenterService, '_owned_cad_operation', lambda *args, **options: pytest.fail('project commit recovery acquired CAD'))
assert service.recover_quick_run(task_id, confirmed=True) is result
assert calls == [(task_id, True), ('sync', task_id)]
assert store.get_task(task_id).status is TaskStatus.READY
@pytest.mark.parametrize('publication_failure', [None, 'sql', 'marker'])
@pytest.mark.parametrize('queue_directory', ['task-queues', 'workspace-queues'])
def test_dependency_recovery_needs_confirmation_clear_source_and_never_opens_cad(tmp_path, monkeypatch, publication_failure, queue_directory):
import json
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.task_queue import _plan_hash
from dx_productivity.trial_task_center.errors import TaskCenterError
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
tasks = []
for name in ('A', 'B'):
task = store.create_task(name)
path = tmp_path / name / 'board.prj'
path.parent.mkdir()
path.write_text(' key iCDBDir "../shared"\n')
project = store.sync_projects(task.task_id, path.parent, (path,))[0]
store.set_project_selected(project.project_id, True)
store.bind_project_task(task.task_id, project.project_id, 'group', len(tasks))
store.add_rule(task.task_id, 'OLD', 'NEW')
tasks.append((task.task_id, path))
for task_id, _ in tasks:
store.set_task_status(task_id, TaskStatus.BLOCKED, summary='dependency')
dependency, follower = tasks
child = service.for_project_task(follower[0])
marker = service._logging.root / 'dependency-blocks' / (follower[0] + '.json')
marker.parent.mkdir()
marker.write_text(json.dumps({'version': 1, 'task_id': follower[0], 'dependency_task_id': dependency[0],
'project_path': str(follower[1].resolve()).casefold(), 'sources': [str((tmp_path / 'shared/icdb.dat').resolve()).casefold()],
'plan_hash': _plan_hash(child, follower[0]), 'queue_id': 'a'*32, 'state': 'blocked', 'undispatched': True}))
queue_path = service._logging.root / queue_directory / ('a'*32 + '.json')
queue_path.parent.mkdir()
queue_path.write_text(json.dumps({'plan_hashes': {follower[0]: _plan_hash(child, follower[0])},
'dependency_tasks': {follower[0]: dependency[0]}, 'entries': {follower[0]: {'state': 'blocked'}}}))
monkeypatch.setattr(TaskCenterService, '_owned_cad_operation', lambda *args, **kw: pytest.fail('dependency recovery opened CAD'))
with pytest.raises(TaskCenterError, match='quick_run_dependency'):
service.recover_quick_run(follower[0], confirmed=False)
with pytest.raises(TaskCenterError, match='quick_run_dependency'):
service.recover_quick_run(follower[0], confirmed=True)
store.set_task_status(dependency[0], TaskStatus.READY, summary='verified recovery fixture')
if publication_failure:
from dx_productivity.trial_task_center import batch_resources
original_write, original_status = batch_resources.write_record, store.set_task_status
failed = []
def write(path, record):
if publication_failure == 'marker' and Path(path) == marker and record.get('state') == 'readmitted' and not failed:
failed.append(True)
raise OSError('readmission marker publication failed')
return original_write(path, record)
def set_status(identifier, state, **options):
if publication_failure == 'sql' and identifier == follower[0] and state is TaskStatus.READY and not failed:
failed.append(True)
raise OSError('SQL readmission failed')
return original_status(identifier, state, **options)
monkeypatch.setattr(batch_resources, 'write_record', write)
monkeypatch.setattr(store, 'set_task_status', set_status)
with pytest.raises(TaskCenterError): service.recover_quick_run(follower[0], confirmed=True)
assert json.loads(marker.read_text())['state'] == 'readmission_prepared'
assert store.get_task(follower[0]).status is (TaskStatus.READY if publication_failure == 'marker' else TaskStatus.BLOCKED)
result = service.recover_quick_run(follower[0], confirmed=True)
assert result.state == 'pending' and store.get_task(follower[0]).status is TaskStatus.READY
assert json.loads(marker.read_text())['state'] == 'readmitted'
assert service.recover_quick_run(follower[0], confirmed=True).state == 'pending'
# A restart sees the same marker/SQL result; it does not need a snapshot.
second_service = TaskCenterService(store, configure_logging(tmp_path / 'data'))
assert second_service.recover_quick_run(follower[0], confirmed=True).state == 'pending'
# The original isolated task stays skipped while its undispatched follower
# can re-enter the same frozen queue after explicit readmission.
from dx_productivity.trial_task_center import task_queue
original_sources = set(json.loads(marker.read_text())['sources'])
queue = {'version': 1, 'task_ids': [dependency[0], follower[0]],
'plan_hashes': {key: _plan_hash(service.for_project_task(key), key) for key, _ in tasks},
'phase': 'finished', 'entries': {dependency[0]: {'state': 'blocked', 'message': 'original uncertain'},
follower[0]: {'state': 'blocked', 'message': 'dependency'}},
'dependency_tasks': {follower[0]: dependency[0]},
'isolated_tasks': {dependency[0]: 'original uncertain', follower[0]: 'dependency'},
'isolated_sources': {source: dependency[0] for source in original_sources}}
queue_path.write_text(json.dumps(queue))
calls = []
from test_project_isolation_queue import ReleasedRuntime
original_child = service.for_project_task
def selected_child(identifier):
selected = original_child(identifier)
if identifier == follower[0]:
selected.has_interrupted_quick_run = lambda _: False
selected._quick_run_preparer.reconcile_terminal_receipts = lambda _: None
from dx_productivity.trial_task_center.quick_run_protocol import QuickRunProgress
selected.quick_run_progress = lambda _: calls.append(identifier) or QuickRunProgress(0, 0, None, None, None, (follower[1],), True)
return selected
monkeypatch.setattr(service, 'for_project_task', selected_child)
def run_queue():
if queue_directory == 'task-queues':
return task_queue.execute_task_queue(service, tuple(key for key, _ in tasks), stop_event=StopControl(),
queue_id='a'*32, runtime=ReleasedRuntime(service._logging.root))
from dx_productivity.trial_task_center.workspace_execution import execute_workspace_projects
return execute_workspace_projects(service, tuple(key for key, _ in tasks), stop_event=StopControl(), queue_id='a'*32)
if queue_directory == 'workspace-queues':
for index, (identifier, _) in enumerate(tasks):
queue['entries'][identifier].update(released=True, problems_done=True, checkpoint_id=str(index+1)*32)
queue_path.write_text(json.dumps(queue))
def supervise(operation, arguments, **controls):
identifier = arguments['task_ids'][0]
calls.append(identifier)
return task_queue.TaskQueueResult(arguments['checkpoint_id'] or arguments['queue_id'],
(task_queue.TaskQueueEntry(identifier, 'completed'),), False)
monkeypatch.setattr(service, '_supervise', supervise)
resumed = run_queue()
assert [row.state for row in resumed.entries] == ['blocked', 'completed'] and calls == [follower[0]]
calls.clear()
run_queue()
assert not calls
attempted_row = {'task_id': follower[0], 'job_id': 'actually-dispatched', 'project_path': str(follower[1]),
'old_part': 'OLD', 'new_part': 'NEW', 'schematic_name': 'MAIN', 'sheet_number': '1'}
child._quick_run_preparer.journal.bind(follower[0], [attempted_row], {})
child._quick_run_preparer.journal.claim(follower[0], attempted_row)
from dx_productivity.trial_task_center import recovery
def native_recovery(*args, **options):
raise TaskCenterError('native_recovery_reached', 'validate the actual follower attempt')
monkeypatch.setattr(recovery, 'recover', native_recovery)
monkeypatch.setattr(TaskCenterService, '_owned_cad_operation', lambda self, name, action, *args, **options: action(SimpleNamespace()))
with pytest.raises(TaskCenterError, match='native_recovery_reached'):
service.recover_quick_run(follower[0], confirmed=True)
store.close()
+5 -2
View File
@@ -17,10 +17,13 @@ def test_explicit_no_button_closes_owned_unknown_popup_and_releases(tmp_path):
process = desktop.start_process((sys.executable, '-c', code), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
guard = CadDialogGuard(desktop, process, tmp_path / 'cad-dialogs.json', 'manual-native-sample')
deadline = time.monotonic() + 10
while not guard.summary()['blocked'] and time.monotonic() < deadline:
dialogs = []
while time.monotonic() < deadline:
guard.poll('manual_sample')
dialogs = guard.summary()['current_dialogs']
if len(dialogs) == 1 and any(button['id'] == 7 for button in dialogs[0]['buttons']):
break
time.sleep(.03)
dialogs = guard.summary()['current_dialogs']
assert len(dialogs) == 1 and process.poll() is None
dialog = dialogs[0]
button = next(button for button in dialog['buttons'] if button['id'] == 7)
+3 -3
View File
@@ -10,7 +10,7 @@ import pytest
@pytest.mark.parametrize('behavior, steps, changed, states', [
('success', 24, 24, ['completed', 'completed', 'completed']),
('failure_continue', 24, 23, ['failed', 'completed', 'completed']),
('uncertain_stop', 1, 0, ['blocked', 'pending', 'pending']),
('uncertain_stop', 17, 16, ['blocked', 'completed', 'completed']),
('pause_resume', 24, 24, ['completed', 'completed', 'completed']),
])
def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tmp_path, behavior, steps, changed, states):
@@ -24,14 +24,14 @@ def test_multiple_projects_preserve_task_order_scope_results_and_measurements(tm
assert report['executed_steps'] == steps
assert report['changed_components'] == changed
assert report['unselected_components_preserved'] == 12
assert report['result']['paused'] == (behavior == 'uncertain_stop')
assert report['result']['paused'] is False
assert [entry['state'] for entry in report['result']['entries']] == states
calls = report['calls']
assert len(calls) == steps
assert all(len(call['refdes']) == 1 for call in calls)
assert len({(call['project'], call['sheet'], call['refdes'][0]) for call in calls}) == steps
assert sum(call['state'] == 'saved_ok' for call in calls) == changed
assert [call['project'] for call in calls] == (['board-000'] if behavior == 'uncertain_stop' else
assert [call['project'] for call in calls] == (['board-000'] + ['board-001'] * 8 + ['board-002'] * 8 if behavior == 'uncertain_stop' else
['board-000'] * 8 + ['board-001'] * 8 + ['board-002'] * 8)
assert calls[0]['state'] == {'failure_continue': 'batch_failed', 'uncertain_stop': 'batch_saved_unverified'}.get(behavior, 'saved_ok')
with sqlite3.connect(output / 'tasks.db') as connection:
+51 -12
View File
@@ -16,7 +16,7 @@ def effective_report(tmp_path, *, part='NEW', value='0R/NC', path='', duplicate=
@pytest.mark.parametrize('repeated_uid', [False, True])
def test_hierarchical_project_can_select_only_globally_unique_root_target(tmp_path, repeated_uid):
def test_hierarchical_project_selects_unambiguous_root_and_child_references(tmp_path, repeated_uid):
hierarchy = report(tmp_path)
text = hierarchy.read_text().replace('Block disconnected \tRoot', 'Block child ')
text = text.replace('Block board \tRoot\n', 'Block board \tRoot\n'
@@ -31,17 +31,13 @@ def test_hierarchical_project_can_select_only_globally_unique_root_target(tmp_pa
text = text.replace('$28I200', '$27I100')
hierarchy.write_text(hierarchy.read_text().replace('$28I200', '$27I100'))
flat.write_text(text)
if repeated_uid:
with pytest.raises(protocol.NativeInventoryUnsupported, match='唯一'):
protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('NEW',),
expected_root='board', effective_report_path=flat)
else:
result = protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('NEW',),
expected_root='board', effective_report_path=flat)
assert [(row.uid, row.refdes) for row in result.components] == [('$27I100', 'R1')]
with pytest.raises(protocol.NativeInventoryUnsupported):
protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('CHILD',),
expected_root='board', effective_report_path=flat)
result = protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('NEW',),
expected_root='board', effective_report_path=flat)
assert [(row.uid, row.refdes, row.schematic_name, row.sheet_number) for row in result.components] == [
('@REFDES|R1' if repeated_uid else '$27I100', 'R1', 'board', 'MAIN')]
child = protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('CHILD',),
expected_root='board', effective_report_path=flat)
assert [(row.refdes, row.schematic_name, row.sheet_number) for row in child.components] == [('R2', 'child', 'AUX')]
def test_inventory_uses_effective_instance_part_and_value_before_filtering(tmp_path):
@@ -129,6 +125,11 @@ def test_filtered_or_ambiguous_ascii_report_requires_com_fallback(tmp_path, chan
old, new = substitutions[change]
text = text.replace(old, new)
path.write_text(text)
if change == 'bad_uid':
result = protocol.read_ascii_discovery(tmp_path / 'source.prj', path, ('OLD',),
effective_report_path=effective_report(tmp_path, part='OLD', value='10K/NC'))
assert {row.refdes for row in result.components} == {'R1', 'R2'}
return
with pytest.raises(protocol.NativeInventoryUnsupported):
protocol.read_ascii_discovery(tmp_path / 'source.prj', path, ('OLD',),
effective_report_path=effective_report(tmp_path, part='OLD', value='10K/NC'))
@@ -179,3 +180,41 @@ def test_unrequested_reference_override_does_not_block_certified_target_inventor
with pytest.raises(protocol.NativeInventoryUnsupported, match='位号与属性不一致'):
protocol.read_ascii_discovery(tmp_path / 'board.prj', report(tmp_path), ('OLD',),
effective_report_path=flat)
@pytest.mark.parametrize('uid', ['VCC', '$29I300', '$27I100'])
@pytest.mark.parametrize('part', ['NEW', 'UNREQUESTED'])
def test_explicit_non_pcb_symbols_are_not_replacement_identities(tmp_path, uid, part):
hierarchy, flat = report(tmp_path), effective_report(tmp_path)
# Electrical annotations may carry library properties and reuse names/UIDs.
props = '\tSymbol name power.1 type Primitive\n\tProp Part Number ' + part + '\n'
hierarchy.write_text(hierarchy.read_text() + (' Symbol ' + uid + '\tpage AUX\n' + props) * 2)
flat.write_text(flat.read_text() + (' Symbol ' + uid + '\tref des \tpage \n\tPath \n' + props) * 2)
result = protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('NEW',),
effective_report_path=flat)
assert [(row.uid, row.refdes) for row in result.components] == [('$27I100', 'R1')]
@pytest.mark.parametrize('mode', ['hierarchy', 'effective'])
@pytest.mark.parametrize('damage', ['uid', 'ref', 'classification'])
def test_non_pcb_filter_keeps_real_component_identity_checks(tmp_path, mode, damage):
hierarchy, flat = report(tmp_path), effective_report(tmp_path)
flat.write_text(flat.read_text().replace('\tPath \n',
'\tPath \n\tSymbol name res.1 type Primitive Frozen ForwardPCB\n'))
path = hierarchy if mode == 'hierarchy' else flat
text = path.read_text()
if damage == 'uid':
text = text.replace('$27I100', 'MISSING_UID')
elif damage == 'ref':
text = text.replace('\tProp Ref Designator R1\n', '')
else:
text = text.replace('res.1 type Primitive Frozen ForwardPCB', 'power.1 type Primitive', 1)
path.write_text(text)
if damage == 'uid':
result = protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('NEW',),
effective_report_path=flat)
assert [(row.uid,row.refdes) for row in result.components] == [('@REFDES|R1','R1')]
return
with pytest.raises(protocol.NativeInventoryUnsupported):
protocol.read_ascii_discovery(tmp_path / 'board.prj', hierarchy, ('NEW',),
effective_report_path=flat)
+3 -3
View File
@@ -23,9 +23,9 @@ def test_normal_replacement_requires_the_selected_library_identity(change):
native.replacement_matches([current], RECORDS, 'NEW', True, library_row=LIBRARY)
def test_recovery_never_substitutes_a_different_uid_with_the_same_refdes():
with pytest.raises(ValueError, match='identity|UID'):
native.existing_replacement_uids([component(uid='$2I999')], RECORDS, 'NEW', {'library_row': LIBRARY})
def test_recovery_reassociates_uid_changes_by_the_same_unique_refdes():
assert native.existing_replacement_uids([component(uid='$2I999')], RECORDS, 'NEW',
{'library_row': LIBRARY}) == ['$2I100']
def test_recovery_treats_part_label_case_as_significant():
+6 -4
View File
@@ -170,7 +170,7 @@ def test_resume_reuses_intact_before_export_but_rebuilds_changed_output(tmp_path
result = {'status': 'success', 'complete': True, 'capture': saved,
'outputs': {'effective': str(output)},
'runs': [{'command': [sys.executable], 'tool_sha256': native_netlist._hash(Path(sys.executable))}],
'graph': {'components': {'u1': {'attributes': {'Part Number': part, 'Value': 'V'}}},
'graph': {'components': {'u1': {'refdes': 'R1', 'attributes': {'Part Number': part, 'Value': 'V'}}},
'nets': [{'name': 'GND', 'endpoints': [['u1', '1']]}]}}
write_record(directory / 'netlist.json', result)
return result
@@ -232,7 +232,7 @@ def test_graph_match_does_not_claim_failed_execution_verified(tmp_path, monkeypa
destination.mkdir(parents=True)
return {'project': str(source), 'root': str(destination)}
graph = {'components': {'u': {'attributes': {'Part Number': 'NEW', 'Value': 'V'}}},
graph = {'components': {'u': {'refdes': 'R1', 'attributes': {'Part Number': 'NEW', 'Value': 'V'}}},
'nets': [{'name': 'N', 'endpoints': [['u', '1']]}]}
monkeypatch.setattr(native_netlist, 'capture_project', capture)
monkeypatch.setattr(native_netlist, 'export_netlist', lambda *a, **k: {'status': 'success', 'complete': True, 'graph': graph})
@@ -253,7 +253,8 @@ def test_expected_library_identity_comes_from_intact_bound_native_receipt(proof_
receipt = {'native_state': 'saved_ok', 'proof': proof}
library = library_from_receipt(command, receipt)
assert library == {'uid': {'attributes': {'Part Number': 'NEW', 'Part Name': 'name', 'Part Label': 'label'},
'target_symbol': 'sym', 'slot_count': 1}}
'target_symbol': 'sym', 'slot_count': 1, 'refdes': 'R1',
'schematic_name': 'MAIN', 'sheet_number': '1'}}
native = next(Path(item['path']) for item in proof['files'] if item['path'].endswith('.native.json'))
native.write_text('{}', encoding='utf-8')
with pytest.raises(ValueError, match='证据'):
@@ -339,7 +340,8 @@ def test_rule_netlist_accepts_bound_component_expansion_and_rejects_foreign_scop
_rule_rows(child, 'task', plan, before)
else:
rows, scopes = _rule_rows(child, 'task', plan, before)
assert rows[0]['target'] == {'uid': 'uid', 'old_value': 'ORIGINAL'}
assert rows[0]['target'] == {'uid': 'uid', 'refdes': 'R1', 'old_value': 'ORIGINAL',
'schematic_name': 'MAIN', 'sheet_number': '1'}
assert rows[0]['new_part_number'] == 'NEW'
assert scopes[0]['source_uids'] == ['uid']
finally:
+12 -9
View File
@@ -13,7 +13,8 @@ from dx_productivity.trial_task_center.target_plan import ComponentTarget, Targe
from dx_productivity.trial_task_center.task_queue import execute_task_queue
def test_hundred_uid_batch_keeps_93_verified_items_and_stops_at_unknown_write(tmp_path):
def test_hundred_uid_batch_keeps_93_verified_items_and_isolates_unknown_writes(tmp_path):
from test_project_isolation_queue import ReleasedRuntime
calls = []
outcomes = {}
def worker(command, timeout):
@@ -58,20 +59,22 @@ def test_hundred_uid_batch_keeps_93_verified_items_and_stops_at_unknown_write(tm
# the production queue, receipts, backups, issue pass and runtime cleanup.
def supervise(operation, arguments, *, stop_event):
assert operation == 'execute_task_queue'
return execute_task_queue(engine, stop_event=stop_event, **arguments)
runtime = ReleasedRuntime(data)
runtime.desktop = None
return execute_task_queue(engine, stop_event=stop_event, runtime=runtime, **arguments)
gui._supervise = supervise
ids = tuple(task.task_id for task in tasks)
try:
result = execute_task_queue(gui, ids, stop_event=Event())
assert result.paused
assert [entry.state for entry in result.entries] == ['failed', 'completed', 'blocked', 'pending']
assert len(calls) == 99 and set(Counter(calls).values()) == {1}
assert (tasks[3].task_id, 'u1') not in calls
assert not result.paused
assert [entry.state for entry in result.entries] == ['failed', 'completed', 'blocked', 'blocked']
assert len(calls) == 100 and set(Counter(calls).values()) == {1}
assert (tasks[3].task_id, 'u1') in calls
records = dict(store._connection.execute('SELECT state,count(*) FROM execution_operations GROUP BY state'))
assert records == {'verified': 93, 'failed': 5, 'uncertain': 1}
assert records == {'verified': 93, 'failed': 5, 'uncertain': 2}
resumed = execute_task_queue(gui, ids, stop_event=Event(), queue_id=result.queue_id)
assert resumed.paused and resumed.entries[2].state == 'blocked'
assert len(calls) == 99
assert not resumed.paused and resumed.entries[2].state == 'blocked'
assert len(calls) == 100
finally:
store.close()
reopened = TaskStore(database)
+7 -3
View File
@@ -88,9 +88,13 @@ def test_uncertain_component_never_runs_same_project_remainder(component_case):
service, _, tasks, calls, outcomes = component_case
task_id = tasks[0].task_id
outcomes[(task_id, ('R1',))] = 'batch_saved_unverified'
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert result.paused
assert calls == [(task_id, ('R1',))]
ids = tuple(task.task_id for task in tasks)
result = execute_task_queue(service, ids, stop_event=Event())
assert not result.paused and [entry.state for entry in result.entries] == ['blocked', 'completed']
assert calls == [(task_id, ('R1',)), (ids[1], ('R1',)), (ids[1], ('R2',))]
assert service.has_interrupted_quick_run(task_id)
execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id)
assert len(calls) == 3
def test_problem_retry_budget_survives_rebinding_and_is_shared(component_case):
+88
View File
@@ -2,6 +2,94 @@ import pytest
import test_accuracy_vbs_guards as guards
@pytest.mark.parametrize('fault', ['', 'snapshot', 'identity', 'transaction', 'native',
'save_requested', 'save_committed', 'close'])
def test_safe_pause_cannot_interrupt_verified_failure_cleanup(tmp_path, fault):
output = guards.run_vbs(tmp_path, ['QPProgress', 'QPDiscardFailedBatchProject',
'QPCloseBatchProject', 'QPReadUtf8'], '''
Dim Failure,Stream,PausedBefore,PausedAfter
Set QP_App=New FakeApp
Set Stream=QP_Fso.CreateTextFile(QP_Fso.BuildPath(QP_Root,"monitor-token.stop"),True)
Stream.Write "token":Stream.Close
On Error Resume Next
QPProgress "query_components",0,1
PausedBefore=(Err.Source="QuickPartReplace.SafeStop"):Err.Clear
QPDiscardFailedBatchProject Failure
If Err.Number<>0 Then WScript.Quit 8
QPProgress "query_components",0,1
PausedAfter=(Err.Source="QuickPartReplace.SafeStop"):Err.Clear
WScript.Echo "result:" & CStr(PausedBefore) & ":" & CStr(QP_App.Closed) & ":" & _
CStr(Len(Failure)>0) & ":" & CStr(PausedAfter)
''', prelude='''
Option Explicit
Dim QP_Fso,QP_Root,QP_App,QP_CurrentJobId,QP_AttemptToken,QP_ProgressSequence
Dim QP_NativeMutationPossible,QP_RestoreTransactionOpen,QP_NativeCallActive,QP_ExpectedJobId
Dim QP_BatchMode,QP_SessionMode,QP_MonitorJobId,QP_SessionToken,QP_OwnedProject,QP_OwnedProjectPath
Dim QP_BatchSaveRequested,QP_BatchSaveCommitted,QP_SessionExternalChange,QP_FailureCleanupActive
Dim QP_SessionItems,QP_SessionDocuments
Set QP_SessionItems=CreateObject("Scripting.Dictionary")
Set QP_SessionDocuments=CreateObject("Scripting.Dictionary")
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
QP_Root="''' + str(tmp_path) + '''":QP_AttemptToken="token":QP_ProgressSequence=0
QP_BatchMode=True:QP_OwnedProject=True:QP_OwnedProjectPath="board.prj"
QP_NativeMutationPossible=''' + str(fault == 'native') + '''
QP_BatchSaveRequested=''' + str(fault == 'save_requested') + '''
QP_BatchSaveCommitted=''' + str(fault == 'save_committed') + '''
Class FakeApp
Public Closed,Path
Private Documents
Private Sub Class_Initialize()
Closed=False:Path="board.prj"
Set Documents=CreateObject("Scripting.Dictionary")
Documents.Add 1,New FakeDocument
End Sub
Function SchematicSheetDocuments()
Set SchematicSheetDocuments=Documents
End Function
Sub RemoveDocument()
Documents.Remove 1
End Sub
Sub CloseProject()
Closed=True:Path=""
End Sub
Function GetProjectData()
Set GetProjectData=Me
End Function
Function GetProjectFilePath()
GetProjectFilePath=Path
End Function
End Class
Class FakeDocument
Sub Close(ByVal Save,ByVal Name)
If Save Then Err.Raise 1235,"Test","unexpected save"
If "''' + fault + '''"="close" Then Err.Raise 1236,"FakeCOM","close failed"
QP_App.RemoveDocument
End Sub
End Class
Sub QPVerifyFailedOriginalSnapshot()
If "''' + fault + '''"="snapshot" Then Err.Raise 1234,"Snapshot","source changed"
If "''' + fault + '''"="identity" Then QP_App.Path="other.prj"
If "''' + fault + '''"="transaction" Then QP_RestoreTransactionOpen=True
QPProgress "verify_untouched",1,1
End Sub
Function QPCanonicalPath(ByVal Path)
QPCanonicalPath=LCase(Path)
End Function
Function QPProjectPath()
QPProjectPath=QP_App.Path
End Function
Sub QPInvalidatePinIndex()
End Sub
Sub QPInvalidateComponentIndex()
End Sub
Sub QPLog(ByVal Root,ByVal Level,ByVal Message)
End Sub
''')
paused_before = fault != 'native'
paused_after = fault not in {'native', 'transaction'}
assert output.splitlines()[-1] == f'result:{paused_before}:{not fault}:{bool(fault)}:{paused_after}'
@pytest.mark.parametrize('snapshot_changed', [False, True])
def test_failed_project_closes_only_after_unchanged_snapshot_is_certified(tmp_path, snapshot_changed):
output = guards.run_vbs(tmp_path, ['QPDiscardFailedBatchProject'], '''
@@ -0,0 +1,171 @@
from contextlib import contextmanager
from pathlib import Path
import subprocess
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _encode_vbs_field
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
@pytest.mark.parametrize('pause_after_first', [False, True])
def test_real_batch_preparer_and_journal_commit_staged_prefix_only_after_native_close(tmp_path, pause_after_first, monkeypatch):
monkeypatch.setattr('dx_productivity.trial_task_center.scanner._is_schematic_project', lambda path: True)
project = tmp_path / 'projects' / 'board.prj'
project.parent.mkdir(); project.write_text('disposable project')
root = tmp_path / 'data' / 'quick-run'
stop = Event()
preparer = QuickRunPreparer(tmp_path / 'data', process_runner=lambda *args: None,
cscript_resolver=lambda: Path('cscript.exe'), sheet_discoverer=lambda project: (('Main', '1'),))
service = TaskCenterService(TaskStore(tmp_path / 'tasks.db'), configure_logging(tmp_path / 'data'), quick_run_preparer=preparer)
task = service.create_task('staged project')
service.scan_projects(task.task_id, project.parent)
for row in service.projects(task.task_id):service.set_project_selected(row.project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW')
service.add_rule(task.task_id, 'OTHER', 'NEW')
class NativeBoundary:
enabled = True
worker = None
on_commit = None
jobs = []
closes = 0
def prepare(self, project):pass
def run_step(self, project, command, timeout):
self.worker = SimpleNamespace(token='a' * 32, root=root)
job = command[-1]
if self.jobs:
states = [row[0] for row in service._store._connection.execute('SELECT state FROM execution_operations')]
assert states.count('pending_save') == 1
assert 'verified' not in states
assert self.closes == 0
self.jobs.append(job)
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
stream.write(f'{job}\tpending_save\tsession_staged_no_match\tverified in memory\n')
if pause_after_first:stop.set()
return subprocess.CompletedProcess(command, 0, '', '')
def close(self):
if self.worker is None:return
self.closes += 1
marker = f'{self.worker.token}\t{project}\tproject_verified\n'
for job in self.jobs:
state = '\t'.join(_encode_vbs_field(str(value)) for value in
(job, project, 'Main', '1', 'S\tfull_sheet_v1\r\nunchanged'))
(root / f'post-state-{job}.tsv').write_text(
'job_id\tproject_path\tschematic_name\tsheet_number\tsemantic_state\n' + state + '\n', encoding='utf-8')
marker += f'{job}\tno_match\n'
(root / f'project-commit-{self.worker.token}.tsv').write_text(marker, encoding='utf-8')
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
for job in self.jobs:stream.write(f'{job}\tno_match\tproject_committed\tclosed and read back\n')
if self.on_commit:self.on_commit(self.worker)
self.worker = None
boundary = NativeBoundary()
@contextmanager
def retained_scope(**kwargs):
try:yield boundary
finally:boundary.close()
preparer.project_session_scope = retained_scope
progress = service.quick_run_progress(task.task_id)
result = service.execute_quick_run_queue(task.task_id,
expected_item=(str(project), progress.next_old_part_number, progress.next_new_part_number, 'preserve'), stop_event=stop)
assert boundary.closes == 1
assert len(boundary.jobs) == (1 if pause_after_first else 2)
assert result.progress.completed_items == len(boundary.jobs)
assert result.progress.saved_items == 0
assert result.progress.no_match_items == len(boundary.jobs)
assert result.paused is pause_after_first
assert result.progress.queue_complete is (not pause_after_first)
assert service._store._connection.execute('SELECT state FROM execution_project_commits').fetchone()[0] == 'verified'
states = [row[0] for row in service._store._connection.execute('SELECT state FROM execution_operations')]
assert states.count('no_match') == len(boundary.jobs)
if pause_after_first:assert states.count('pending') == 1
service._store.close()
def test_runtime_prewrite_pause_commits_prefix_and_retires_only_current_claim(tmp_path, monkeypatch):
from test_batch_runtime import worker_runtime, Cad
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.stop_control import StopControl
monkeypatch.setattr('dx_productivity.trial_task_center.scanner._is_schematic_project', lambda path: True)
project = tmp_path / 'projects' / 'board.prj'
project.parent.mkdir(); project.write_text('disposable project')
root = tmp_path / 'data' / 'quick-run'
stop = StopControl()
preparer = QuickRunPreparer(tmp_path / 'data', process_runner=lambda *args: None,
cscript_resolver=lambda: Path('cscript.exe'), sheet_discoverer=lambda project: (('Main', '1'),))
service = TaskCenterService(TaskStore(tmp_path / 'tasks.db'), configure_logging(tmp_path / 'data'), quick_run_preparer=preparer)
task = service.create_task('prewrite pause')
service.scan_projects(task.task_id, project.parent)
for row in service.projects(task.task_id):service.set_project_selected(row.project_id, True)
service.add_rule(task.task_id, 'OLD', 'NEW'); service.add_rule(task.task_id, 'OTHER', 'NEW')
token = 'a' * 32
current = {}
def native_monitor(command, *args, **kwargs):
stop.set()
prefix, paused = current['jobs']
fields = (prefix, str(project), 'Main', '1', 'S\tfull_sheet_v1\r\nverified final state')
(root / f'post-state-{prefix}.tsv').write_text(
'job_id\tproject_path\tschematic_name\tsheet_number\tsemantic_state\n' +
'\t'.join(_encode_vbs_field(value) for value in fields) + '\n', encoding='utf-8')
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_verified\n{prefix}\tno_match\n', encoding='utf-8')
(root / f'project-pause-{token}.tsv').write_text(f'{token}\t{project}\t{paused}\tprewrite_closed', encoding='utf-8')
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
stream.write(f'{prefix}\tno_match\tproject_committed\tprefix closed\n')
stream.write(f'{paused}\tawaiting_native_replace\t\tsnapshot before pause\n')
result = subprocess.CompletedProcess(command, 75, '', '')
result.prewrite_pause = dict(session_token=token, monitor_token='b' * 32, job_id=paused,
project_path=str(project), sequence=7, worker_tree_exited=True)
return result
runtime = worker_runtime(tmp_path, monkeypatch, native_monitor)
runtime.cad_factory = lambda *args, stop_control=None, **options: Cad(*args, **options)
runtime.stop_event = stop
class RetainedNative:
enabled = True
worker = SimpleNamespace(token=token, root=root)
on_commit = None
def prepare(self, project):pass
def run_step(self, project, command, timeout):
current.setdefault('jobs', []).append(command[-1])
(root / 'project-session.request').write_text(f'{token}\t{project}\t{command[-1]}', encoding='utf-8')
if len(current['jobs']) == 1:
current['initial_command'] = command
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
stream.write(f'{command[-1]}\tpending_save\tsession_staged_no_match\tstaged\n')
return subprocess.CompletedProcess(command, 0, '', '')
return runtime.run_worker(current['initial_command'], timeout)
def close(self):
if self.on_commit:self.on_commit(self.worker)
self.worker = None
boundary = RetainedNative()
@contextmanager
def retained_scope(**kwargs):
try:yield boundary
finally:boundary.close()
preparer.project_session_scope = retained_scope
progress = service.quick_run_progress(task.task_id)
with runtime, pytest.raises(TaskCenterError) as raised:
service.execute_quick_run_queue(task.task_id, expected_item=(str(project), progress.next_old_part_number,
progress.next_new_part_number, 'preserve'), stop_event=stop, runtime=runtime)
assert raised.value.code == 'operation_cancelled'
assert not (root / 'uncertain.flag').exists()
assert not (root / 'current-command.tsv').exists()
states = [row[0] for row in service._store._connection.execute('SELECT state FROM execution_operations ORDER BY rowid')]
assert states == ['no_match', 'pending']
record = service._store._connection.execute("SELECT * FROM execution_operations WHERE state='pending'").fetchone()
assert record['generation'] == 0
assert preparer.journal.certified_startup_pause(task.task_id, record)
assert service.quick_run_progress(task.task_id).completed_items == 1
assert not preparer.has_interrupted(task.task_id)
service._store.close()
+108
View File
@@ -0,0 +1,108 @@
import hashlib
import json
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.execution_journal import ExecutionJournal, create_execution_schema
from dx_productivity.trial_task_center.history_store import HistoryRepository, create_history_schema
from dx_productivity.trial_task_center.store import TaskStore
@pytest.fixture
def staged_case(tmp_path):
store = TaskStore(tmp_path / 'tasks.db')
with store.transaction():
create_execution_schema(store._connection)
create_history_schema(store._connection)
task = store.create_task('project commit')
journal = ExecutionJournal(store)
rows = [dict(task_id=task.task_id, job_id=f'job{index}', project_path=str(tmp_path / 'board.prj'),
schematic_name='MAIN', sheet_number='1', old_part='OLD', new_part='NEW',
target_scope='targets', target_selectors=f'uid{index}\x1fR{index}\x1f10K') for index in (1, 2)]
journal.bind(task.task_id, rows, {})
evidence = tmp_path / 'readback'; evidence.write_text('persisted sheet state')
proof = {'files': [{'path': str(evidence), 'sha256': hashlib.sha256(evidence.read_bytes()).hexdigest()}],
'baseline': dict(project_path=rows[0]['project_path'], schematic_name='MAIN', sheet_number='1', state='persisted sheet state')}
yield store, journal, task.task_id, rows, proof
store.close()
def test_staged_prefix_is_not_saved_and_cannot_replay_after_rebind(staged_case, tmp_path):
store, journal, task, rows, proof = staged_case
attempt = journal.claim(task, rows[0])
journal.stage_project_result(attempt, rows[0], session_token='a' * 32, root=tmp_path, proof=proof)
record = store._connection.execute('SELECT state FROM execution_operations WHERE attempt_id=?', (attempt.attempt_id,)).fetchone()
assert record['state'] == 'pending_save'
assert HistoryRepository(store).page().rows == ()
with pytest.raises(TaskCenterError, match='quick_run_uncertain'):
journal.bind(task, rows, {rows[0]['job_id']: ('saved_ok', 'session_verified', 'uncommitted')})
assert journal.needs_reconciliation(task)
assert journal.unresolved_jobs(task, rows) == ('job1',)
# The active retained owner can stage another independent operation.
assert journal.claim(task, rows[1]).generation == 1
def test_project_commit_is_atomic_idempotent_and_preserves_operation_ids(staged_case, tmp_path, monkeypatch):
store, journal, task, rows, proof = staged_case
attempts = [journal.claim(task, row) for row in rows]
for attempt, row in zip(attempts, rows):
journal.stage_project_result(attempt, row, session_token='a' * 32, root=tmp_path, proof=proof)
commit_proof = dict(proof, session_token='a' * 32, project_path=rows[0]['project_path'], jobs=['job1', 'job2'])
original = HistoryRepository.append
calls = []
def fail_second(self, **values):
calls.append(values)
if len(calls) == 2:
raise OSError('disk full')
return original(self, **values)
monkeypatch.setattr(HistoryRepository, 'append', fail_second)
with pytest.raises(OSError):
journal.commit_project_results(task, 'a' * 32, {'job1': proof, 'job2': proof}, commit_proof)
assert [r[0] for r in store._connection.execute('SELECT state FROM execution_operations')] == ['pending_save', 'pending_save']
assert HistoryRepository(store).page().rows == ()
monkeypatch.setattr(HistoryRepository, 'append', original)
journal.commit_project_results(task, 'a' * 32, {'job1': proof, 'job2': proof}, commit_proof)
journal.commit_project_results(task, 'a' * 32, {'job1': proof, 'job2': proof}, commit_proof)
assert len(HistoryRepository(store).page().rows) == 2
records = store._connection.execute('SELECT state,attempt_id,generation FROM execution_operations').fetchall()
assert [r['state'] for r in records] == ['verified', 'verified']
assert [r['attempt_id'] for r in records] == [a.attempt_id for a in attempts]
assert journal.bind(task, rows, {})['job1'][0] == 'saved_ok'
def test_partial_pause_commits_only_staged_prefix_and_rejects_incomplete_readback(staged_case, tmp_path):
store, journal, task, rows, proof = staged_case
attempt = journal.claim(task, rows[0])
journal.stage_project_result(attempt, rows[0], session_token='a' * 32, root=tmp_path, proof=proof)
with pytest.raises(TaskCenterError):
journal.commit_project_results(task, 'a' * 32, {}, dict(proof, jobs=[]))
commit = dict(proof, session_token='a' * 32, project_path=rows[0]['project_path'], jobs=['job1'])
journal.commit_project_results(task, 'a' * 32, {'job1': proof}, commit)
assert journal.claim(task, rows[1]).generation == 1
record = store._connection.execute('SELECT state FROM execution_project_commits').fetchone()
assert record['state'] == 'verified'
def test_crash_reconciliation_commits_native_marker_without_replaying_any_worker(staged_case, tmp_path):
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _encode_vbs_field
store, journal, task, rows, proof = staged_case
attempt = journal.claim(task, rows[0])
journal.stage_project_result(attempt, rows[0], session_token='a' * 32, root=tmp_path, proof=proof)
def forbidden_worker(*args):
pytest.fail('recovery replayed native replacement')
preparer = QuickRunPreparer(tmp_path, process_runner=forbidden_worker)
preparer.journal = journal
with pytest.raises(TaskCenterError):preparer._commit_staged_project(task)
assert store._connection.execute('SELECT state FROM execution_operations WHERE attempt_id=?', (attempt.attempt_id,)).fetchone()[0] == 'pending_save'
job = rows[0]['job_id']
fields = (job, rows[0]['project_path'], 'MAIN', '1', 'S\tfull_sheet_v1\r\nfinal persisted state')
(tmp_path / f'post-state-{job}.tsv').write_text(
'job_id\tproject_path\tschematic_name\tsheet_number\tsemantic_state\n' +
'\t'.join(_encode_vbs_field(value) for value in fields) + '\n', encoding='utf-8')
(tmp_path / ('project-commit-' + 'a' * 32 + '.tsv')).write_text(
'a' * 32 + '\t' + rows[0]['project_path'] + '\tproject_verified\n' + job + '\tno_match\n', encoding='utf-8')
preparer._commit_staged_project(task)
preparer._commit_staged_project(task)
assert store._connection.execute('SELECT state FROM execution_operations WHERE attempt_id=?', (attempt.attempt_id,)).fetchone()[0] == 'no_match'
assert len(HistoryRepository(store).page().rows) == 1
@@ -0,0 +1,27 @@
from pathlib import Path
from types import SimpleNamespace
from dx_productivity.trial_task_center.quick_run import QuickRunProgress, _advance_batch_session, _correlated_status_change
def test_staging_advances_live_cursor_without_counting_saved_or_completed_items(tmp_path):
project = str(tmp_path / 'board.prj')
commands = (('task', 'one', project, 'OLD', 'NEW'), ('task', 'two', project, 'OTHER', 'NEW'))
progress = QuickRunProgress(0, 2, Path(project), 'OLD', 'NEW', (), False)
session = SimpleNamespace(commands=commands, next_index=0, latest={}, progress=progress, sheets=None)
_advance_batch_session(session, ('one', 'pending_save', 'session_staged', 'staged'))
assert session.next_index == 1
assert session.progress.completed_items == 0
assert session.progress.saved_items == 0
assert session.progress.completed_project_paths == ()
assert session.progress.next_old_part_number == 'OTHER'
assert not session.progress.queue_complete
def test_native_staged_and_resumed_pause_statuses_correlate_to_current_operation():
command = ('task', 'one', 'board.prj', 'OLD', 'NEW')
waiting = ('one', 'awaiting_native_replace', '', 'snapshot')
staged = ('one', 'pending_save', 'session_staged', 'verified in memory')
assert _correlated_status_change((), (waiting, staged), (command,), expected_command=command) == staged
paused = ('one', 'pending', 'prewrite_paused', 'not replaced')
assert _correlated_status_change((paused,), (paused, waiting, staged), (command,), expected_command=command) == staged
+29
View File
@@ -0,0 +1,29 @@
import json
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.execution_proof import capture_project_commit, proof_intact
def test_commit_manifest_binds_ordered_prefix_project_and_immutable_copy(tmp_path):
root = tmp_path / 'worker'; root.mkdir()
project = tmp_path / 'board.prj'
token = 'a' * 32
commit = dict(session_token=token, project_path=str(project.resolve()).casefold(), jobs_json=json.dumps(['one', 'two']))
marker = root / f'project-commit-{token}.tsv'
marker.write_text(f'{token}\t{project}\tproject_verified\none\tsaved_ok\ntwo\tno_match\n', encoding='utf-8')
proof = capture_project_commit(tmp_path, root, commit)
assert proof['jobs'] == ['one', 'two']
assert proof['outcomes'] == {'one': 'saved_ok', 'two': 'no_match'}
marker.write_text('crashed next session', encoding='utf-8')
assert proof_intact(proof)
@pytest.mark.parametrize('tail', ['one\tsaved_ok\n', 'two\tsaved_ok\none\tsaved_ok\n', 'one\tpending_save\ntwo\tsaved_ok\n'])
def test_commit_manifest_rejects_partial_or_unverified_prefix(tmp_path, tail):
project = tmp_path / 'board.prj'; token = 'a' * 32
commit = dict(session_token=token, project_path=str(project.resolve()).casefold(), jobs_json=json.dumps(['one', 'two']))
(tmp_path / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_verified\n' + tail, encoding='utf-8')
with pytest.raises(TaskCenterError):
capture_project_commit(tmp_path, tmp_path, commit)
@@ -0,0 +1,216 @@
import json
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.history_store import HistoryRepository
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.models import TaskStatus
from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _encode_vbs_field as enc, _write_uncertain_flag, _run_process
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
@pytest.fixture
def public_commit_case(tmp_path, monkeypatch, request):
monkeypatch.setattr('dx_productivity.trial_task_center.scanner._is_schematic_project', lambda _: True)
project = tmp_path / 'project' / 'board.prj'
project.parent.mkdir(); project.write_text('saved both replacements')
data = tmp_path / 'data'
preparer = QuickRunPreparer(data, process_runner=lambda *args: pytest.fail('native replacement/recovery replayed'),
cscript_resolver=lambda: Path('cscript.exe'), sheet_discoverer=lambda _: (('MAIN', '1'),))
store = TaskStore(tmp_path / 'tasks.db')
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=preparer)
task = service.create_task('saved engineering project')
service.scan_projects(task.task_id, project.parent)
for row in service.projects(task.task_id):service.set_project_selected(row.project_id, True)
service.add_rule(task.task_id, 'OLD1', 'NEW1'); service.add_rule(task.task_id, 'OLD2', 'NEW2')
root = data / 'quick-run'
handoff = preparer.prepare(task.task_id, service.projects(task.task_id), service.rules(task.task_id),
sheet_targets={str(project.resolve()).casefold(): (('MAIN', '1'),)})
rows = list(preparer._bind_journal_handoff(task.task_id, handoff).values())
preparer._process_runner = _run_process
attempts = []
for index, row in enumerate(rows, 1):
job = row['job_id']; uid = f'original{index}'; ref = f'R{index}'
snapshot = root / f'snapshot-{job}.tsv'
snapshot.write_text('\t'.join(map(enc, ['M', str(project), row['old_part'], row['new_part'], 'MAIN:1', 'preserve', '', '1'])) + '\n' +
f'C\t{uid}\t{ref}\t{index*100}\t0\t0\t1\tNO_PINS\nA\t{uid}\tValue\t1K\t1K\t0\t0\t0\t0\t1\t0\t1\n', encoding='utf-8')
metadata, components = read_snapshot(snapshot)
report = {'ok': True, 'stage': 'native_replace_verified',
'transaction': transaction_binding(snapshot, metadata, components, ['lib', row['new_part'], 'symbol', '', 'name', 'label'], 'symbol'),
'batch_attempt': dict(task_id=task.task_id, job_id=job, project_path=str(project), session_id='b'*32, attempt_id='c'*32, generation=1)}
Path(str(snapshot) + '.native.json').write_text(json.dumps(report), encoding='utf-8')
(root / f'post-state-{job}.tsv').write_text('job_id\tproject_path\tschematic_name\tsheet_number\tsemantic_state\n' +
'\t'.join(map(enc, [job, str(project), 'MAIN', '1', 'S\tfull_sheet_v1\r\nR1=NEW1\r\nR2=NEW2\r\n'])) + '\n', encoding='utf-8')
raw = [['V','2',task.task_id,job,'saved_ok',str(project),'MAIN','1',row['old_part'],row['new_part'],
'preserve','','1','','',snapshot.read_bytes().decode('utf-8')], ['C',uid,ref,row['new_part'],'1K','1','']]
(root / f'value-readback-{job}.tsv').write_text('\n'.join('\t'.join(map(enc, fields)) for fields in raw) + '\n', encoding='utf-8')
attempt = preparer.journal.claim(task.task_id, row); attempts.append(attempt)
proof = preparer.result_proof(root, row, ('pending_save', 'session_staged', 'staged'))
preparer.journal.stage_project_result(attempt, row, session_token='a'*32, root=root, proof=proof)
(root / ('project-commit-' + 'a'*32 + '.tsv')).write_text('a'*32 + '\t' + str(project) + '\tproject_verified\n' +
''.join(row['job_id'] + '\tsaved_ok\n' for row in rows), encoding='utf-8')
# Production native status append failed/truncated after the durable marker.
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:stream.write(rows[0]['job_id'] + '\tpending_save\tsession_staged\tstaged\n')
if getattr(request, 'param', None) != 'checkpoint':
original = HistoryRepository.append
def disk_full(*args, **kwargs):raise OSError('history disk full')
monkeypatch.setattr(HistoryRepository, 'append', disk_full)
with pytest.raises(OSError, match='history disk full'):
preparer._commit_staged_project(task.task_id, session_token='a'*32, bind_source=True)
monkeypatch.setattr(HistoryRepository, 'append', original)
_write_uncertain_flag(root / 'uncertain.flag', 'receipt_commit_failed')
store.set_task_status(task.task_id, TaskStatus.BLOCKED, summary='saved project receipt commit failed')
monkeypatch.setattr(TaskCenterService, '_owned_cad_operation', lambda *args, **kwargs: (_ for _ in ()).throw(
TaskCenterError('native_recovery_required', 'ordinary recovery path requires a separately verified native boundary')))
yield service, store, task.task_id, preparer, project, rows, attempts
store.close()
def test_deleted_task_cannot_recover_bound_project_commit(public_commit_case):
service, store, task, preparer, _, _, _ = public_commit_case
flag = preparer.data_root / 'quick-run' / 'uncertain.flag'
protection = flag.read_bytes()
store.set_task_status(task, TaskStatus.DELETED, summary='deleted by operator')
with pytest.raises(TaskCenterError) as caught:
service.recover_quick_run(task, confirmed=True)
assert caught.value.code == 'quick_run_recovery'
assert caught.value.message == '请先恢复已删除的任务记录,再核验其中断步骤。'
assert flag.read_bytes() == protection
assert store.get_task(task).status is TaskStatus.DELETED
assert [row[0] for row in store._connection.execute('SELECT state FROM execution_operations')] == ['pending_save', 'pending_save']
def test_public_confirmed_project_commit_recovery_is_atomic_without_native_replay(public_commit_case):
service, store, task, preparer, project, rows, attempts = public_commit_case
root = preparer.data_root / 'quick-run'
assert [r[0] for r in store._connection.execute('SELECT state FROM execution_operations')] == ['pending_save', 'pending_save']
with pytest.raises(TaskCenterError):service.recover_quick_run(task, confirmed=False)
assert store.get_task(task).status is TaskStatus.BLOCKED
result = service.recover_quick_run(task, confirmed=True)
assert result.state == 'saved_ok' and result.progress.saved_items == 2
assert store.get_task(task).status is TaskStatus.COMPLETED
assert not (root / 'uncertain.flag').exists()
actual = store._connection.execute('SELECT state,attempt_id,generation FROM execution_operations ORDER BY rowid').fetchall()
assert [r['state'] for r in actual] == ['verified', 'verified']
assert [(r['attempt_id'], r['generation']) for r in actual] == [(a.attempt_id, a.generation) for a in attempts]
assert len([r for r in HistoryRepository(store).page().rows if r['operation'] == '器件替换']) == 2
assert service.recover_quick_run(task, confirmed=True).state == 'saved_ok'
@pytest.mark.parametrize('damage', ['manifest', 'source', 'later_attempt', 'later_job', 'unrelated_reason', 'native_report'])
def test_public_recovery_refuses_unproven_or_later_write_uncertainty(public_commit_case, damage):
service, store, task, preparer, project, rows, _ = public_commit_case
root = preparer.data_root / 'quick-run'
if damage == 'manifest':(root / ('project-commit-' + 'a'*32 + '.tsv')).write_text('partial')
elif damage == 'source':project.write_text('external or later native modification')
elif damage == 'later_attempt':
store._connection.execute("UPDATE execution_operations SET generation=generation+1 WHERE operation_key=(SELECT operation_key FROM execution_operations LIMIT 1)")
elif damage == 'later_job':
record = dict(store._connection.execute('SELECT * FROM execution_operations LIMIT 1').fetchone())
command = json.loads(record['command_json']); command['old_part'] = 'LATER'
store._connection.execute('''INSERT INTO execution_operations(task_id,round_id,operation_key,command_json,state,attempt_id,generation)
VALUES (?,?,?,?, 'prepared',?,1)''', (task, record['round_id'], 'later-operation', json.dumps(command), 'd'*32))
elif damage == 'native_report':(root / f'snapshot-{rows[0]["job_id"]}.tsv.native.json').write_text('{}')
else:_write_uncertain_flag(root / 'uncertain.flag', 'native_failure_after_snapshot')
with pytest.raises((TaskCenterError, AssertionError)):service.recover_quick_run(task, confirmed=True)
assert (root / 'uncertain.flag').exists()
assert store.get_task(task).status is TaskStatus.BLOCKED
def test_public_recovery_after_real_store_and_preparer_restart(public_commit_case):
service, store, task, preparer, project, rows, attempts = public_commit_case
path, data = store.path, preparer.data_root
store.close()
reopened = TaskStore(path)
try:
worker = QuickRunPreparer(data, process_runner=_run_process)
resumed = TaskCenterService(reopened, configure_logging(data), quick_run_preparer=worker)
result = resumed.recover_quick_run(task, confirmed=True)
assert result.progress.saved_items == 2 and reopened.get_task(task).status is TaskStatus.COMPLETED
finally:reopened.close()
@pytest.mark.parametrize('public_commit_case', ['checkpoint'], indirect=True)
@pytest.mark.parametrize('damage', [None, 'missing_checkpoint', 'missing_owner', 'native_attempt', 'readback', 'supervisor', 'foreign_supervisor'])
def test_public_recovery_uses_runtime_checkpoint_when_sql_callback_never_binds(public_commit_case, damage):
from types import SimpleNamespace
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
from test_batch_runtime import Desktop
service, store, task, preparer, project, rows, attempts = public_commit_case
root = preparer.data_root / 'quick-run'
assert preparer.journal.project_commit_records(task)[0]['proof_json'] is None
Desktop.fail_release = False
runtime = BatchCadRuntime(preparer.data_root, 'execution', desktop_factory=Desktop, session_id='b'*32)
runtime._ensure_desktop()
runtime.cad = SimpleNamespace(checkpoint=lambda _: None)
runtime.record['active_job'] = rows[0]['job_id']
runtime._current_attempts = [(root / (row['job_id'] + '.json'), row) for row in rows]
(root / 'project-session.request').write_text('a'*32 + '\t' + str(project) + '\t' + rows[0]['job_id'])
runtime._checkpoint(root, project, 'c'*32)
runtime.desktop.close()
runtime.record['cleanup'] = runtime.desktop.cleanup_record
runtime.desktop = runtime.cad = None
runtime._record_release()
checkpoint_path = root / 'project-checkpoint.json'
if damage == 'missing_checkpoint':checkpoint_path.unlink()
elif damage == 'missing_owner':runtime.path.unlink()
elif damage == 'native_attempt':
checkpoint = json.loads(checkpoint_path.read_text())
checkpoint['project_commit_source']['native_attempt']['attempt_id'] = 'e'*32
checkpoint_path.write_text(json.dumps(checkpoint))
elif damage == 'readback':(root / ('value-readback-' + rows[0]['job_id'] + '.tsv')).write_text('changed')
elif damage in {'supervisor', 'foreign_supervisor'}:
from dx_productivity.trial_task_center.batch_resources import write_record
from dx_productivity.trial_task_center.batch_supervisor import _mark_interrupted
(root / 'uncertain.flag').unlink()
_mark_interrupted(preparer.data_root, {'batch_id': runtime.session_id, 'operation': 'execute_task_queue',
'task_ids': [task], 'uncertainty_roots': {task: str(preparer.data_root)}},
'parent crashed after native checkpoint before SQL callback')
if damage == 'foreign_supervisor':
supervisor_path = runtime.path.parent / 'supervisor.json'
supervisor = json.loads(supervisor_path.read_text()); supervisor['protected_task_ids'] = ['foreign-task']
write_record(supervisor_path, supervisor)
# The SQL callback was never entered; a new process consumes the native certificate.
reopened = TaskStore(store.path)
try:
worker = QuickRunPreparer(preparer.data_root, process_runner=_run_process)
resumed = TaskCenterService(reopened, configure_logging(preparer.data_root), quick_run_preparer=worker)
if damage in {None, 'supervisor'}:
assert resumed.recover_quick_run(task, confirmed=True).progress.saved_items == 2
assert reopened.get_task(task).status is TaskStatus.COMPLETED
else:
with pytest.raises(TaskCenterError):resumed.recover_quick_run(task, confirmed=True)
assert (root / 'uncertain.flag').is_file()
assert reopened.get_task(task).status is TaskStatus.BLOCKED
finally:reopened.close()
@pytest.mark.parametrize('failure', ['status', 'flag', 'sql_status'])
def test_public_recovery_retries_publication_after_sql_commit_without_duplicate_history(public_commit_case, monkeypatch, failure):
from dx_productivity.trial_task_center import quick_run
service, store, task, preparer, project, rows, attempts = public_commit_case
root = preparer.data_root / 'quick-run'
original_status, original_replace = quick_run._write_status_details, Path.replace
count = []
def status(*args, **kwargs):
if failure == 'status' and not count:count.append(1); raise OSError('status publication failed')
return original_status(*args, **kwargs)
def replace(path, target):
if failure == 'flag' and path.name == 'uncertain.flag' and not count:count.append(1); raise OSError('flag retirement failed')
return original_replace(path, target)
monkeypatch.setattr(quick_run, '_write_status_details', status); monkeypatch.setattr(Path, 'replace', replace)
original_task_status = store.set_task_status
def task_status(task_id, state, **kwargs):
if failure == 'sql_status' and state is TaskStatus.READY and not count:
count.append(1); raise OSError('task status publication failed')
return original_task_status(task_id, state, **kwargs)
monkeypatch.setattr(store, 'set_task_status', task_status)
with pytest.raises((TaskCenterError, OSError)):service.recover_quick_run(task, confirmed=True)
assert (root / 'uncertain.flag').exists() is (failure != 'sql_status')
reopened = TaskCenterService(store, configure_logging(service._logging.root), quick_run_preparer=preparer)
assert reopened.recover_quick_run(task, confirmed=True).state == 'saved_ok'
assert len([r for r in HistoryRepository(store).page().rows if r['operation'] == '器件替换']) == 2
@@ -0,0 +1,37 @@
import json
from pathlib import Path
import subprocess
import pytest
from dx_productivity.trial_task_center.execution_proof import validate_project_commit_source
@pytest.mark.parametrize('resume_later_job', [False, True])
def test_native_closed_checkpoint_binds_project_marker_and_saved_source(tmp_path, monkeypatch, resume_later_job):
from test_batch_runtime import command_for, worker_runtime
command, project = command_for(tmp_path)
root = Path(command[3])
if resume_later_job:
with (root / 'command.tsv').open('a') as stream:
stream.write(f'task\tnext\t{project}\told\tnew\n')
command = (*command[:-1], 'next')
job = command[-1]
token = 'a' * 32
(root / 'project-session.request').write_text(f'{token}\t{project}\t{job}')
marker = root / ('project-commit-' + token + '.tsv')
def monitor(*args, **kwargs):
marker.write_text(f'{token}\t{project}\tproject_verified\n{job}\tno_match\n')
(root / ('post-state-' + job + '.tsv')).write_text('native final semantic state')
return subprocess.CompletedProcess(command, 0, '', '')
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
with runtime:
runtime.run_worker(command, 5)
checkpoint = json.loads((root / 'project-checkpoint.json').read_text(encoding='utf-8'))
proof = checkpoint['project_commit_source']
assert proof['session_token'] == token and proof['jobs'] == [job]
assert set(proof['readback_files']) == {'post-state-' + job + '.tsv'}
assert proof['native_attempt'] == {'session_id': runtime.session_id, 'generation': runtime.generation,
'attempt_id': runtime.record['active_attempt']}
assert validate_project_commit_source(proof, root)
marker.write_text('changed')
assert not validate_project_commit_source(proof, root)
+44
View File
@@ -0,0 +1,44 @@
from pathlib import Path
import json
from types import SimpleNamespace
from dx_productivity.trial_task_center.project_session import ProjectSessionScope
from test_project_session import toy_worker
def test_staged_worker_stays_open_until_project_commit_and_callback_runs_once(tmp_path):
command = toy_worker(tmp_path)
script = Path(command[2])
script.write_text(script.read_text(encoding='utf-8').replace('saved_ok', 'pending_save').replace('session_verified', 'session_staged'), encoding='utf-8')
commits = []
with ProjectSessionScope(None, enabled=True) as scope:
result = scope.run_step(tmp_path / 'board.prj', command, 3)
assert result.returncode == 0
assert not (tmp_path / 'closed.txt').exists()
scope.on_commit = lambda worker: commits.append(worker.token)
assert scope.run_step(tmp_path / 'board.prj', (*command[:-1], 'job2'), 3).returncode == 0
assert (tmp_path / 'project-session.request').read_text(encoding='utf-8').split('\t')[2] == 'job2'
scope.close()
assert (tmp_path / 'closed.txt').exists()
scope.close()
assert len(commits) == 1
def test_project_close_extends_wait_while_native_commit_keeps_reporting_progress(tmp_path, monkeypatch):
from dx_productivity.trial_task_center import project_session
elapsed = [0.0]
class FinishingCommit:
def is_set(self):return elapsed[0] >= 12
def wait(self, timeout):
elapsed[0] += .1
(tmp_path / 'worker-progress.json').write_text(json.dumps({'sequence': int(elapsed[0]), 'native_progress_frames': 0}))
return self.is_set()
monkeypatch.setattr(project_session, 'time', SimpleNamespace(monotonic=lambda: elapsed[0], sleep=lambda seconds: None))
worker = project_session.ProjectSessionWorker(tmp_path / 'board.prj', tmp_path)
worker._thread = object()
worker._timeout = 1
worker._done = FinishingCommit()
worker._result = SimpleNamespace(returncode=0)
worker.close()
assert elapsed[0] >= 12
assert not worker._abort.is_set()
+27
View File
@@ -0,0 +1,27 @@
import hashlib
import pytest
from test_value_readback import case
from dx_productivity.trial_task_center.value_readback import capture_value_readback, load_value_readback
from dx_productivity.trial_task_center.quick_run_protocol import _encode_vbs_field
@pytest.mark.parametrize('damage',['','foreign_project','changed_marker','wrong_state'])
def test_committed_prefix_readback_is_bound_to_manifest_not_last_status(tmp_path,damage):
row,_=case(tmp_path)
token='a'*32
marker=tmp_path/f'project-commit-{token}.tsv'
marker.write_text(f'{token}\t{_encode_vbs_field(row["project_path"])}\tproject_verified\njob\tsaved_ok\nnext\tno_match\n')
proof={'session_token':token,'project_path':row['project_path'],'jobs':['job','next'],
'outcomes':{'job':'saved_ok','next':'no_match'},
'files':[{'path':str(marker),'sha256':hashlib.sha256(marker.read_bytes()).hexdigest()}]}
with (tmp_path/'status.tsv').open('a') as stream:
stream.write('next\tno_match\tproject_committed\tverified\n')
if damage=='foreign_project':proof['project_path']=str(tmp_path/'other.prj')
elif damage=='changed_marker':marker.write_text('changed')
elif damage=='wrong_state':proof['outcomes']['job']='no_match'
result=capture_value_readback(tmp_path,row,('saved_ok','project_committed','verified'),project_commit=proof)
assert result['value_readback_status']==('rejected' if damage else 'verified')
if not damage:
assert load_value_readback(tmp_path,row,('saved_ok','project_committed','verified'))==result
+403
View File
@@ -0,0 +1,403 @@
from pathlib import Path
import re
import subprocess
import pytest
SOURCE = Path(__file__).resolve().parents[2] / 'integration/dxdesigner795/QuickPartReplace.vbs'
def procedure(name):
source = SOURCE.read_text(encoding='utf-8-sig')
match = re.search(rf'(?ms)^Sub {name}\(.*?^End Sub', source)
assert match, f'missing production procedure {name}'
return match.group()
def run_script(tmp_path, script):
path = tmp_path / 'production-extract.vbs'
path.write_text(script, encoding='ascii')
return subprocess.run((r'C:\Windows\SysWOW64\cscript.exe', '//nologo', str(path)),
capture_output=True, text=True, timeout=10)
def test_production_batch_finish_stages_session_item_before_per_step_save(tmp_path):
result = run_script(tmp_path, '''QP_SessionMode = True
QP_BatchState = "restored_ok"
QPFinishBatchItem
Sub QPStageSessionItem()
WScript.Echo "pending_save"
End Sub
''' + procedure('QPFinishBatchItem'))
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == 'pending_save'
def test_production_baseline_wrapper_preserves_safe_pause_source(tmp_path):
result = run_script(tmp_path, '''On Error Resume Next
QPVerifyExpectedBaselines "board"
WScript.Echo Err.Source
Sub QPCheckExpectedBaselines(ByVal TargetPath)
Err.Raise vbObjectError + 860, "QuickPartReplace.SafeStop", "paused"
End Sub
''' + procedure('QPVerifyExpectedBaselines'))
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == 'QuickPartReplace.SafeStop'
def test_production_project_commit_closes_empty_owned_project_without_save(tmp_path):
result = run_script(tmp_path, '''Set QP_SessionItems = CreateObject("Scripting.Dictionary")
QP_SessionProject = "board.prj"
QPCommitSessionProject
Sub QPCloseBatchProject(ByVal Target, ByVal SaveChanges)
WScript.Echo Target & ":" & CStr(SaveChanges)
End Sub
''' + procedure('QPCommitSessionProject'))
assert result.returncode == 0, result.stderr
assert result.stdout.strip() == 'board.prj:False'
def test_production_pause_acknowledges_only_after_original_proof_and_prefix_close(tmp_path):
script = '''Set QP_Fso = CreateObject("Scripting.FileSystemObject")
Set QP_SessionItems = CreateObject("Scripting.Dictionary")
QP_CurrentJobId = "current"
QP_ExpectedJobId = "current"
QP_MonitorJobId = "initial"
QP_OwnedProject = True
QP_Root = "."
QP_SessionToken = String(32, "a")
QP_SessionProject = "board.prj"
QP_AttemptToken = "monitor"
QP_ProgressSequence = 3
QPAcknowledgePrewritePause
WScript.Echo "unsafe-no-ack"
Sub QPVerifyFailedOriginalSnapshot()
WScript.Echo "original-verified"
End Sub
Function QPReadCommand(ByVal Path)
Set QPReadCommand = CreateObject("Scripting.Dictionary")
End Function
Sub QPWriteVerifiedState(ByRef Command)
WScript.Echo "unchanged-semantic-state"
End Sub
Sub QPCommitSessionProject()
WScript.Echo "prefix-committed-and-closed"
QP_OwnedProject = False
End Sub
Sub QPWriteUtf8(ByVal Path, ByVal Data)
WScript.Echo "durable-pause-marker"
End Sub
Function QPEncode(ByVal Value)
QPEncode = Value
End Function
'''
result = run_script(tmp_path, script + procedure('QPAcknowledgePrewritePause'))
assert result.returncode == 75
assert result.stdout.splitlines()[:4] == ['original-verified', 'unchanged-semantic-state',
'prefix-committed-and-closed', 'durable-pause-marker']
assert result.stdout.splitlines()[4] == 'DX_PREWRITE_PAUSED\tmonitor\tinitial\t' + 'a' * 32 + '\tcurrent\t3'
unsafe = run_script(tmp_path, script.replace('QPAcknowledgePrewritePause\n',
'QP_NativeMutationPossible = True\nQPAcknowledgePrewritePause\n', 1) + procedure('QPAcknowledgePrewritePause'))
assert unsafe.returncode == 0
assert unsafe.stdout.strip() == 'unsafe-no-ack'
def test_production_commit_saves_each_sheet_once_and_reopens_project_once(tmp_path):
# COM is the test boundary; all project commit/close sequencing comes from VBS.
script = '''On Error Resume Next
Set QP_Fso = CreateObject("Scripting.FileSystemObject")
QP_Root = "."
QP_SessionMode = True
QP_SessionProject = "board.prj"
QP_OwnedProjectPath = "board.prj"
QP_OwnedProject = True
QP_ProjectOpen = True
QP_DocCount = 2
QP_Saves = 0
QP_Closes = 0
QP_Opens = 0
QP_Reads = 0
QP_TargetSchematic = ""
QP_TargetSheet = ""
QP_CurrentJobId = ""
QP_SessionToken = String(32, "a")
Set QP_App = New FakeApp
Set QP_SessionItems = CreateObject("Scripting.Dictionary")
Set QP_SessionSheets = CreateObject("Scripting.Dictionary")
Set QP_SessionDocuments = CreateObject("Scripting.Dictionary")
QP_SessionDocuments.Add "A", True
QP_SessionDocuments.Add "B", True
QP_SessionSheets.Add "A:1", "finalA"
QP_SessionSheets.Add "B:1", "finalB"
For I = 1 To 3
Set Entry = CreateObject("Scripting.Dictionary")
Set Command = CreateObject("Scripting.Dictionary")
Command.Add "job_id", "job" & I
Set Records = CreateObject("Scripting.Dictionary")
Set Components = CreateObject("Scripting.Dictionary")
Records.Add "components", Components
Entry.Add "command", Command
Entry.Add "snapshot_path", "snapshot-job" & I
Set Values = CreateObject("Scripting.Dictionary")
Entry.Add "value_states", Values
Entry.Add "schematic", "A"
If I = 3 Then Entry("schematic") = "B"
Entry.Add "sheet", "1"
Entry.Add "final_state", "restored_ok"
QP_SessionItems.Add "job" & I, Entry
Next
QPCommitSessionProject
If Err.Number <> 0 Then
WScript.StdErr.WriteLine Err.Source & ":" & Err.Description
WScript.Quit 1
End If
WScript.Echo "counts=" & QP_Saves & "," & QP_Closes & "," & QP_Opens & "," & QP_Reads
Class FakeDocument
Sub Close(ByVal SaveChanges, ByVal Ignored)
If SaveChanges Then QP_Saves = QP_Saves + 1
QP_DocCount = QP_DocCount - 1
End Sub
End Class
Class FakeDocuments
Property Get Count
Count = QP_DocCount
End Property
Function Item(ByVal Index)
Set Item = New FakeDocument
End Function
End Class
Class FakeProjectData
Function GetProjectFilePath()
GetProjectFilePath = ""
If QP_ProjectOpen Then GetProjectFilePath = "board.prj"
End Function
End Class
Class FakeApp
Function SchematicSheetDocuments()
Set SchematicSheetDocuments = New FakeDocuments
End Function
Function GetProjectData()
Set GetProjectData = New FakeProjectData
End Function
Sub CloseProject()
QP_Closes = QP_Closes + 1
QP_ProjectOpen = False
End Sub
End Class
Sub QPEnsureProject(ByRef App, ByVal Project)
If Not QP_ProjectOpen Then
QP_ProjectOpen = True
QP_Opens = QP_Opens + 1
QP_DocCount = 2
QP_OwnedProject = True
QP_OwnedProjectPath = Project
QP_SessionDocuments.Add "A", True
QP_SessionDocuments.Add "B", True
End If
End Sub
Function QPSheetKey(ByVal Schematic, ByVal Sheet)
QPSheetKey = Schematic & ":" & Sheet
End Function
Function QPCurrentSemanticState()
QP_Reads = QP_Reads + 1
QPCurrentSemanticState = "final" & QP_TargetSchematic
End Function
Sub QPRequireExpectedState(ByVal Expected, ByVal Actual)
If Expected <> Actual Then Err.Raise 1, "Readback", "changed sheet"
End Sub
Function QPProjectPath()
QPProjectPath = "board.prj"
End Function
Function QPCanonicalPath(ByVal Value)
QPCanonicalPath = Value
End Function
Sub QPProgress(ByVal Stage, ByVal Done, ByVal Total)
End Sub
Sub QPLog(ByVal Root, ByVal Level, ByVal Message)
End Sub
Sub QPInvalidatePinIndex()
End Sub
Sub QPInvalidateComponentIndex()
End Sub
Sub QPWriteSemanticState(ByRef Command, ByVal SemanticState)
End Sub
Function QPReadSnapshot(ByVal Path)
Set Result = CreateObject("Scripting.Dictionary")
Set Parts = CreateObject("Scripting.Dictionary")
Result.Add "components", Parts
Set QPReadSnapshot = Result
End Function
Sub QPVerifyRestoredPlans(ByRef Command, ByRef Records, ByRef Plans, ByRef Values)
End Sub
Sub QPWriteValueReadback(ByRef Command, ByRef Records, ByRef Plans, ByVal State)
End Sub
Function QPEncode(ByVal Value)
QPEncode = Value
End Function
Sub QPWriteUtf8(ByVal Path, ByVal Data)
WScript.Echo "marker"
End Sub
Sub QPWriteStatus(ByVal Root, ByVal Job, ByVal State, ByVal Code, ByVal Message)
WScript.Echo Job & ":" & State
End Sub
'''
result = run_script(tmp_path, script + procedure('QPCommitSessionProject') + '\n' + procedure('QPCloseBatchProject'))
assert result.returncode == 0, result.stderr
assert result.stdout.splitlines() == ['marker', 'job1:saved_ok', 'job2:saved_ok', 'job3:saved_ok', 'counts=2,2,1,4']
# A failed reopened sheet readback must not publish the commit marker/status.
changed = script.replace('QPCurrentSemanticState = "final" & QP_TargetSchematic',
'QPCurrentSemanticState = "final" & QP_TargetSchematic\n If QP_Opens > 0 Then QPCurrentSemanticState = "changed"')
failed = run_script(tmp_path, changed + procedure('QPCommitSessionProject') + '\n' + procedure('QPCloseBatchProject'))
assert failed.returncode == 1
assert 'Readback:changed sheet' in failed.stderr
assert 'marker' not in failed.stdout
assert 'saved_ok' not in failed.stdout
@pytest.mark.parametrize('state', ['restored_ok', 'no_match'])
def test_stage_rereads_real_current_command_before_publishing_pending_save(tmp_path, state):
import test_accuracy_vbs_guards as guards
header='task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\n'
(tmp_path/'command.tsv').write_text(header+'task\tother\tboard.prj\tOLD\tNEW\tpreserve\n')
(tmp_path/'current-command.tsv').write_text(header+'task\tjob\tboard.prj\tOLD\tNEW\tpreserve\n')
(tmp_path/'current-state.tsv').write_text('job_id\tstate\tcode\tmessage\njob\tawaiting_native_replace\t\tdispatched\n')
names=['QPStageSessionItem','QPReadCommand','QPActiveCommandPath','QPReadProjectRuleStates',
'QPReadState','QPIsNextRuleState','QPReadUtf8','QPWriteUtf8','QPWriteStatus','QPAppendAscii','QPSheetKey']
output=guards.run_vbs(tmp_path,names,'''
QP_Root="'''+str(tmp_path)+'''"
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Set QP_App=New FakeApp
Set QP_SessionItems=CreateObject("Scripting.Dictionary")
Set QP_SessionSheets=CreateObject("Scripting.Dictionary")
QP_ExpectedJobId="job":QP_CurrentJobId="job":QP_BatchMode=True
QP_BatchState="'''+state+'''":QP_SessionToken=String(32,"a")
QPStageSessionItem
WScript.Echo QP_SessionItems("job")("command")("job_id")
WScript.Echo QP_SessionItems("job")("final_state")
WScript.Echo CStr(InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"pending_save")>0)
WScript.Echo QP_BatchState
''',prelude='''
Dim QP_Root,QP_Fso,QP_App,QP_SessionItems,QP_SessionSheets,QP_ExpectedJobId,QP_CurrentJobId
Dim QP_BatchMode,QP_BatchState,QP_SessionToken
Class FakeApp
Property Get ActiveView()
Set ActiveView=Me
End Property
Function GetName(ByVal Ignored)
GetName="MAIN"
End Function
Property Get Block()
Set Block=Me
End Property
Property Get SheetNum()
SheetNum="1"
End Property
End Class
Function QPProjectPath()
QPProjectPath="board.prj"
End Function
Function QPCanonicalPath(ByVal Value)
QPCanonicalPath=Value
End Function
Function QPValueMode(ByRef Command)
QPValueMode=Command("value_mode")
End Function
Function QPReadSnapshot(ByVal Path)
Dim R,C:Set R=CreateObject("Scripting.Dictionary"):Set C=CreateObject("Scripting.Dictionary")
R.Add "components",C:Set QPReadSnapshot=R
End Function
Function QPJobSnapshotPath(ByVal Job)
QPJobSnapshotPath="unused-snapshot"
End Function
Sub QPRequireCommandSnapshot(ByRef Command,ByVal Path)
End Sub
Sub QPVerifyUntouched(ByRef Records)
End Sub
Function QPCurrentSemanticState()
QPCurrentSemanticState="verified-memory"
End Function
''')
assert output.splitlines()==['job',state,'True',state]
assert (tmp_path/'project-session-result.tsv').read_text(encoding='utf-8-sig').split('\t')[2]=='pending_save'
@pytest.mark.parametrize('continuation', ['close','next'])
def test_pause_during_staged_checkpoint_finishes_prefix_or_pauses_next_prewrite(tmp_path, continuation):
import test_accuracy_vbs_guards as guards
token='a'*32
(tmp_path/'monitor-monitor.stop').write_text('monitor')
(tmp_path/'project-session-next.tsv').write_text(token+'\t'+continuation)
(tmp_path/'batch.request').write_text('next')
output=guards.run_vbs(tmp_path,['QPSessionNext','QPRequireSessionCheckpoint','QPProgress','QPReadUtf8','QPSheetKey'],'''
QP_Root="'''+str(tmp_path)+'''"
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Set QP_App=New App
Set QP_SessionItems=CreateObject("Scripting.Dictionary"):QP_SessionItems.Add "previous",True
Set QP_SessionDocuments=CreateObject("Scripting.Dictionary"):QP_SessionDocuments.Add "MAIN:1",True
Set QP_SessionSheets=CreateObject("Scripting.Dictionary"):QP_SessionSheets.Add QPSheetKey("MAIN","1"),"original"
QP_SessionMode=True:QP_SessionWaiting=True:QP_SessionToken="'''+token+'''"
QP_SessionProject="board":QP_OwnedProject=True:QP_OwnedProjectPath="board"
QP_CheckpointSchematic="MAIN":QP_CheckpointSheet="1"
QP_ExpectedJobId="previous":QP_CurrentJobId="previous":QP_MonitorJobId="initial"
QP_AttemptToken="monitor":QP_ProgressSequence=0
QPSessionNext
If QP_SessionMode Then
On Error Resume Next
QPProgress "before_native",0,1
WScript.Echo "next_prewrite_stop=" & CStr(Err.Source="QuickPartReplace.SafeStop")
End If
''',prelude='''
Dim QP_Root,QP_Fso,QP_App,QP_SessionItems,QP_SessionDocuments,QP_SessionSheets
Dim QP_SessionMode,QP_SessionWaiting,QP_SessionToken,QP_SessionProject,QP_OwnedProject,QP_OwnedProjectPath
Dim QP_CheckpointSchematic,QP_CheckpointSheet,QP_ExpectedJobId,QP_CurrentJobId,QP_MonitorJobId
Dim QP_AttemptToken,QP_ProgressSequence
Class App
Function SchematicSheetDocuments()
Set SchematicSheetDocuments=Me
End Function
Property Get Count()
Count=1
End Property
Property Get ActiveView()
Set ActiveView=Me
End Property
Function GetName(ByVal Flags)
GetName="MAIN"
End Function
Property Get Block()
Set Block=Me
End Property
Property Get SheetNum()
SheetNum="1"
End Property
End Class
Function QPProjectPath()
QPProjectPath="board"
End Function
Function QPCanonicalPath(ByVal Value)
QPCanonicalPath=Value
End Function
Function QPReadContinuation(ByVal Path)
QPReadContinuation=QPReadUtf8(Path)
End Function
Function QPCurrentSemanticState()
QPProgress "capture_semantic_state",1,104
QPCurrentSemanticState="original"
End Function
Sub QPRequireExpectedState(ByVal Expected,ByVal Actual)
If Expected<>Actual Then Err.Raise 1,"checkpoint","changed"
End Sub
Sub QPCommitSessionProject()
WScript.Echo "prefix_commit"
End Sub
Function QPConfirmedProjectPath()
QPConfirmedProjectPath="board"
End Function
Sub QPEnsureProject(ByRef App,ByVal Path)
End Sub
''')
lines=output.splitlines()
semantic=[line for line in lines if '\tcapture_semantic_state\t' in line]
assert len(semantic)==1 and semantic[0].split('\t')[-2:]==['0','previous']
assert ('prefix_commit' in lines) if continuation=='close' else ('next_prewrite_stop=True' in lines)
@@ -0,0 +1,65 @@
from pathlib import Path
from threading import Event
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.task_queue import execute_task_queue
from test_task_queue import Service
class ReleasedRuntime:
def __init__(self,root,released=True):
self.root=root
self.stop_event=None
self.cad=None
self.released=released
self.release_calls=[]
def bind_logs(self,*args):
pass
def release_failed_project(self,error,evidence_root):
self.release_calls.append(error.code)
return self.released
@pytest.mark.parametrize('released',[False,True])
def test_uncertain_project_only_holds_independent_tasks_until_writers_exit(tmp_path,released):
service=Service(tmp_path,{'A':TaskCenterError('quick_run_uncertain','unknown saved result')})
runtime=ReleasedRuntime(tmp_path,released)
result=execute_task_queue(service,('A','B'),stop_event=Event(),runtime=runtime)
assert result.entries[0].state=='blocked'
assert result.paused is (not released)
assert service.calls==([('start','A'),('start','B'),('end','B')] if released else [('start','A')])
assert runtime.release_calls==['quick_run_uncertain']
def test_local_failure_cleanup_does_not_become_user_batch_pause(tmp_path):
from dx_productivity.trial_task_center.stop_control import ProjectStopControl,StopControl
parent=StopControl()
local=ProjectStopControl(parent)
local.request_failure_cleanup(tmp_path,'injected project failure')
assert local.is_set() and local.force_event.is_set()
assert not parent.is_set() and not parent.force_event.is_set()
next_project=ProjectStopControl(parent)
assert not next_project.is_set()
next_project.set()
assert parent.is_set()
def test_resolution_failure_release_keeps_the_parent_user_intent_unset(tmp_path):
from dx_productivity.trial_task_center.stop_control import ProjectStopControl,StopControl,wait_for_resolution
parent=StopControl()
local=ProjectStopControl(parent)
wait_for_resolution(local,tmp_path,'injected failure',resolved=lambda:True,release_on_failure=True)
assert local.is_set() and not parent.is_set()
def test_isolated_project_is_not_replayed_on_queue_resume(tmp_path):
service=Service(tmp_path,{'A':TaskCenterError('quick_run_uncertain','unknown')})
runtime=ReleasedRuntime(tmp_path)
first=execute_task_queue(service,('A','B'),stop_event=Event(),runtime=runtime)
before=list(service.calls)
resumed=execute_task_queue(service,('A','B'),stop_event=Event(),runtime=runtime,queue_id=first.queue_id)
assert service.calls==before
assert resumed.entries[0].state=='blocked'
+7 -3
View File
@@ -50,9 +50,13 @@ def test_changed_project_after_controlled_failure_blocks_remaining_uid(component
project = service.projects(task_id)[0].path
outcomes[(task_id, ('R1',))] = 'batch_failed'
outcomes['after_call'] = lambda count: project.write_text('unexpected source mutation') if count == 1 else None
result = execute_task_queue(service, (task_id,), stop_event=Event())
assert result.paused
assert calls == [(task_id, ('R1',))]
ids = tuple(task.task_id for task in tasks)
result = execute_task_queue(service, ids, stop_event=Event())
assert not result.paused and [entry.state for entry in result.entries] == ['blocked', 'completed']
assert calls == [(task_id, ('R1',)), (ids[1], ('R1',)), (ids[1], ('R2',))]
assert service.has_interrupted_quick_run(task_id)
execute_task_queue(service, ids, stop_event=Event(), queue_id=result.queue_id)
assert len(calls) == 3
def test_tampered_failure_health_denies_resume(component_case):
+550
View File
@@ -0,0 +1,550 @@
"""Reference designators remain usable when native UID metadata is broken."""
from copy import deepcopy
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import native_inventory_protocol as inventory, native_netlist
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow, compile_target_rules
from test_native_ascii_inventory import report, effective_report
@pytest.mark.parametrize('damage', ['invalid', 'duplicate', 'changed_between_reports'])
def test_inventory_joins_real_parts_by_refdes_when_uid_is_unusable(tmp_path, damage):
hier,flat=report(tmp_path),effective_report(tmp_path,part='OLD')
if damage=='invalid':
hier.write_text(hier.read_text().replace('$27I100','broken'))
flat.write_text(flat.read_text().replace('$27I100','broken'))
elif damage=='duplicate':
hier.write_text(hier.read_text().replace('$28I200','$27I100'))
flat.write_text(flat.read_text().replace('$28I200','$27I100'))
else:
flat.write_text(flat.read_text().replace('$27I100','$99I999'))
result=inventory.read_ascii_discovery(tmp_path/'board.prj',hier,('OLD',),effective_report_path=flat)
assert {(row.refdes,row.old_part_number,row.sheet_number) for row in result.components}=={
('R1','OLD','MAIN'),('R2','OLD','AUX')}
assert len({row.key for row in result.components})==2
def test_plan_target_identity_is_refdes_based_without_rewriting_legacy_uid(tmp_path):
old=ComponentTarget(tmp_path/'board.prj','MAIN','1','legacy-u1','R1','OLD','1K')
new=ComponentTarget(tmp_path/'board.prj','MAIN','1','changed-u1','R1','OLD','1K')
assert old.key==new.key
assert old.uid=='legacy-u1'
with pytest.raises(Exception,match='more than once|重复'):
compile_target_rules((TargetPlanRow(old,True,'NEW'),TargetPlanRow(new,True,'NEW')))
def test_blank_uid_can_be_represented_by_a_reference_target(tmp_path):
target=ComponentTarget(tmp_path/'board.prj','MAIN','1','','R1','OLD','1K')
assert target.uid=='@REFDES|R1'
def graph(uid):
return {'status':'success','complete':True,'graph':{
'components':{uid:{'refdes':'R1','attributes':{'Part Number':'OLD'},
'symbol':'res.1 type Primitive ForwardPCB',
'pins':{'p1':{'number':'1','nets':['GND']}}}},
'nets':[{'name':'GND','endpoints':[[uid,'p1']]}]}}
def test_uid_change_alone_does_not_change_netlist_acceptance():
before,after=graph('$1I1'),graph('$2I2')
result=native_netlist.compare_netlists(before,after)
assert result['status']=='verified',result
assert '$1I1' in before['graph']['components'] # comparisons do not mutate evidence
def test_reference_mapping_does_not_hide_real_pin_net_changes():
before,after=graph('$1I1'),graph('$2I2')
after['graph']['components']['$2I2']['pins']['p1']['nets']=['VCC']
after['graph']['nets']=[{'name':'VCC','endpoints':[['$2I2','p1']]}]
result=native_netlist.compare_netlists(before,after)
assert result['status']=='different'
def test_native_readback_can_reassociate_changed_uid_by_unique_refdes(monkeypatch):
from dx_productivity.trial_task_center import native_helper
components=[SimpleNamespace(UID='new-uid',Refdes='R1')]
values={'Part Number':'NEW','Part Name':'LIB:NEW','Part Label':'LABEL'}
monkeypatch.setattr(native_helper,'attribute_value',lambda component,name,**options:values.get(name,''))
records=[['C','old-uid','R1','0','0','0','1','']]
assert native_helper.replacement_matches(components,records,'NEW',True,
library_row=['','NEW','','','LIB:NEW','LABEL'])==['old-uid']
def test_native_snapshot_scope_binds_legacy_keys_by_reference_and_resets(tmp_path):
from dx_productivity.trial_task_center import native_helper
snapshot=tmp_path/'snapshot.tsv'
snapshot.write_text('M\tjob\tproject.prj\tOLD\tNEW\tMAIN:1\n'
'C\tlegacy\tR1\t0\t0\t0\t1\t\n')
component=SimpleNamespace(UID='changed',Refdes='R1')
with native_helper.snapshot_identity_scope(snapshot):
assert native_helper._component_uid(component)=='legacy'
assert native_helper._component_uid(component)=='changed'
def test_complete_ascii_graph_does_not_require_numeric_uid(tmp_path):
from test_native_cli_netlist import ascii_report
ascii_path,keyin=tmp_path/'flat.txt',tmp_path/'design.kyn'
ascii_path.write_text(ascii_report().replace('$1I1','broken-uid'))
keyin.write_text('%net\n%page=board\n\\N1\\ \\R1\\-\\1\\\n%Part\n\\OLD\\ \\R1\\\n')
result=native_netlist.read_graph(ascii_path,keyin)
assert {row['refdes'] for row in result['components'].values()}=={'R1'}
def test_vbs_selector_can_resolve_a_changed_uid_by_reference(tmp_path):
import test_accuracy_vbs_guards as guards
output=guards.run_vbs(tmp_path,['QPComponentIdentityKey'],'''
Dim Comp
Set Comp=New FakeComponent
Set QP_ReferenceAliases=CreateObject("Scripting.Dictionary")
QP_ReferenceAliases.Add "main:1|r1","legacy-id"
WScript.Echo QPComponentIdentityKey(Comp)
''',prelude='''
Dim QP_ReferenceAliases
Class FakeComponent
Public UID,Refdes
Private Sub Class_Initialize()
UID="changed-id":Refdes="R1"
End Sub
End Class
Function QPSheetIdentity()
QPSheetIdentity="MAIN:1"
End Function
''')
assert output=='legacy-id'
def test_netlist_plan_can_bind_reference_selector_to_original_graph_uid():
from dx_productivity.trial_task_center.netlist_verification import _reference_plan
plan={'rows':[{'enabled':True,'target':{'uid':'@REFDES|R1','refdes':'R1',
'schematic_name':'MAIN','sheet_number':'1','old_value':'1K'},'new_part_number':'NEW'}]}
rebound,library=_reference_plan(plan,graph('$1I1'),{'@REFDES|R1':{
'refdes':'R1','schematic_name':'MAIN','sheet_number':'1','attributes':{'Part Number':'NEW'}}})
assert rebound['rows'][0]['target']['uid']=='$1I1'
assert '$1I1' in library
assert plan['rows'][0]['target']['uid']=='@REFDES|R1'
def test_reused_uid_cannot_override_a_known_reference_mismatch():
from dx_productivity.trial_task_center.netlist_verification import _reference_plan
plan={'rows':[{'enabled':True,'target':{'uid':'$1I1','refdes':'R2','old_value':'1K'},'new_part_number':'NEW'}]}
with pytest.raises(ValueError,match='位号'):
_reference_plan(plan,graph('$1I1'),{})
def test_vbs_unselected_duplicate_uids_get_distinct_reference_keys(tmp_path):
import test_accuracy_vbs_guards as guards
output=guards.run_vbs(tmp_path,['QPComponentIdentityKey','QPBindSheetReferences'],'''
Dim Rows,A,B
Set Rows=CreateObject("Scripting.Dictionary")
Set A=New FakeComponent:A.UID="duplicate":A.Refdes="R2"
Set B=New FakeComponent:B.UID="duplicate":B.Refdes="R3"
Rows.Add A,True:Rows.Add B,True
QPBindSheetReferences Rows
WScript.Echo QPComponentIdentityKey(A)
WScript.Echo QPComponentIdentityKey(B)
''',prelude='''
Dim QP_ReferenceAliases
Class FakeComponent
Public UID,Refdes
End Class
Function QPSheetIdentity()
QPSheetIdentity="MAIN:1"
End Function
''')
assert output.splitlines()==['@REFDES|R2','@REFDES|R3']
def test_inventory_disambiguates_same_reference_by_sheet(tmp_path):
hier, flat = report(tmp_path), effective_report(tmp_path, part='OLD')
hier.write_text(hier.read_text().replace('Ref Designator R2', 'Ref Designator R1'))
flat.write_text(flat.read_text().replace('ref des R1\tpage ', 'ref des R1\tpage MAIN')
.replace('ref des R2\tpage ', 'ref des R1\tpage AUX')
.replace('Ref Designator R2', 'Ref Designator R1'))
result = inventory.read_ascii_discovery(tmp_path/'board.prj', hier, ('OLD',), effective_report_path=flat)
assert {(row.refdes, row.sheet_number) for row in result.components} == {('R1','MAIN'),('R1','AUX')}
def test_inventory_groups_legal_slots_as_one_physical_target(tmp_path):
hier, flat = report(tmp_path), effective_report(tmp_path, part='OLD')
text = hier.read_text()
first = text[text.index(' Symbol $27I100'):text.index(' Symbol IN_PORT')]
hier.write_text(text.replace(' Symbol IN_PORT', first.replace('$27I100','$27I101').replace('res.1','res.2')+' Symbol IN_PORT'))
text = flat.read_text().replace('\tPath \n', '\tPath \n\tSymbol name res.1 type Primitive ForwardPCB\n')
first = text[text.index(' Symbol $27I100'):text.index(' Symbol $28I200')]
flat.write_text(text+first.replace('$27I100','$27I101').replace('res.1','res.2'))
result = inventory.read_ascii_discovery(tmp_path/'board.prj', hier, ('OLD',), effective_report_path=flat)
assert [(row.refdes,row.sheet_number) for row in result.components] == [('R1','MAIN'),('R2','AUX')]
@pytest.mark.parametrize('uid', ['broken', '$27I100'])
def test_hierarchical_inventory_joins_child_by_reference_despite_uid_damage(tmp_path, uid):
hier, flat = report(tmp_path), effective_report(tmp_path, part='OLD')
text = hier.read_text().replace('Block disconnected \tRoot', 'Block child ')
text = text.replace('Block board \tRoot\n', 'Block board \tRoot\n'
'\tChild child.1\tinstance name $9I2\tview unrecognized\n Symbol $9I2\tpage MAIN\n')
hier.write_text(text.replace('$28I200',uid))
flat.write_text(flat.read_text().replace('$28I200',uid).replace(
'ref des R2\tpage \n\tPath \n', 'ref des R2\tpage AUX\n\tPath $9I2\n')
.replace('Prop Ref Designator R2','Prop Ref Designator 2R2')
+' Symbol IN_PORT\tref des \tpage \n\tPath \n\tSymbol name input.1 type \n')
result = inventory.read_ascii_discovery(tmp_path/'board.prj', hier, ('OLD',), expected_root='board', effective_report_path=flat)
assert {(row.refdes,row.schematic_name,row.sheet_number) for row in result.components} == {('R1','board','MAIN'),('2R2','child','AUX')}
def test_hierarchy_graph_coverage_uses_reference_when_raw_uid_repeats(tmp_path):
from test_native_cli_netlist import ascii_report
text = ascii_report()
text = text.replace('\t\tPath root\n', '\t\tPath root\n\t\tConn $1I1 pin B page \n\t\tPath root\n')
second = text[text.index(' Symbol '):].replace('ref des R1','ref des R2').replace('Ref Designator R1','Ref Designator R2').replace('Pin A','Pin B').replace('num 1','num 2')
flat, kyn, hier = tmp_path/'flat.txt',tmp_path/'g.kyn',tmp_path/'hier.txt'
flat.write_text(text+second)
kyn.write_text('%net\n\\N1\\ \\R1\\-\\1\\ \\R2\\-\\2\\\n%Part\n\\OLD\\ \\R1\\ \\R2\\\n')
header = ascii_report().split('Config ')[0].replace('FLAT BLOCKS','HIER BLOCKS')
hier.write_text(header+'Block board \tRoot\n Symbol $1I1\tpage 1\n\tProp Ref Designator R1\n'
+' Symbol $1I1\tpage 1\n\tProp Ref Designator R2\n')
parsed = native_netlist.read_graph(flat,kyn,hierarchy_path=hier,root_block='board')
assert {row['source_uid'] for row in parsed['components'].values()} == {'$1I1'}
assert {row['refdes'] for row in parsed['components'].values()} == {'R1','R2'}
def test_reference_graph_distinguishes_same_ref_on_different_sheets():
before = graph('a')
before['graph']['components']['a'].update(source_page='1',symbol='res.1 type Primitive ForwardPCB')
second = deepcopy(before['graph']['components']['a'])
second['source_page'] = '2'
before['graph']['components']['b'] = second
before['graph']['nets'][0]['endpoints'].append(['b','p1'])
after = deepcopy(before)
after['graph']['components']['new-a'] = after['graph']['components'].pop('a')
after['graph']['components']['new-b'] = after['graph']['components'].pop('b')
after['graph']['nets'][0]['endpoints'] = [['new-a','p1'],['new-b','p1']]
assert native_netlist.compare_netlists(before,after)['verified']
assert native_netlist.reference_targets(after['graph'],'R1',sheet='2') == ('new-b',)
def test_declared_reference_changes_expand_to_all_legal_symbol_units():
before = graph('a')
before['graph']['components']['a']['symbol'] = 'old.1 type Primitive ForwardPCB'
second = deepcopy(before['graph']['components']['a'])
second['symbol'] = 'old.2 type Primitive ForwardPCB'
second['pins']['p1']['number'] = '2'
before['graph']['components']['b'] = second
before['graph']['nets'][0]['endpoints'].append(['b','p1'])
after = deepcopy(before)
for row in after['graph']['components'].values():
row['attributes']['Part Number'] = 'NEW'
result = native_netlist.compare_netlists(before,after,expected_changes={'@REFDES|R1':{'Part Number':'NEW'}})
assert result['verified'],result
after['graph']['components']['b']['attributes']['Part Number'] = 'WRONG'
assert not native_netlist.compare_netlists(before,after,expected_changes={'@REFDES|R1':{'Part Number':'NEW'}})['verified']
def test_native_inventory_and_reciprocal_graph_accept_missing_uid(tmp_path):
from test_native_cli_netlist import ascii_report
hier, flat = report(tmp_path), effective_report(tmp_path, part='OLD')
hier.write_text(hier.read_text().replace('$27I100',''))
flat.write_text(flat.read_text().replace('$27I100',''))
result = inventory.read_ascii_discovery(tmp_path/'board.prj',hier,('OLD',),effective_report_path=flat)
assert {row.refdes for row in result.components} == {'R1','R2'}
graph_path, keyin = tmp_path/'graph.txt',tmp_path/'graph.kyn'
graph_path.write_text(ascii_report().replace('$1I1',''))
keyin.write_text('%net\n\\N1\\ \\R1\\-\\1\\\n%Part\n\\OLD\\ \\R1\\\n')
parsed = native_netlist.read_graph(graph_path,keyin)
assert [row['source_uid'] for row in parsed['components'].values()] == ['']
@pytest.mark.parametrize('damage', ['missing_value', 'missing_reference'])
def test_hierarchical_inventory_keeps_required_observation_checks(tmp_path, damage):
hier, flat = report(tmp_path), effective_report(tmp_path, part='OLD')
text = hier.read_text().replace('Block disconnected \tRoot', 'Block child ')
text = text.replace('Block board \tRoot\n', 'Block board \tRoot\n'
'\tChild child.1\tinstance name $9I2\tview unrecognized\n Symbol $9I2\tpage MAIN\n')
hier.write_text(text.replace('\tProp Ref Designator R2\n','') if damage == 'missing_reference' else text)
text = flat.read_text()
if damage == 'missing_value':
text = text.replace('\tProp Value 20K\n','')
flat.write_text(text.replace('ref des R2\tpage \n\tPath \n',
'ref des R2\tpage \n\tPath $9I2\n')
+' Symbol IN_PORT\tref des \tpage \n\tPath \n\tSymbol name input.1 type \n')
with pytest.raises(inventory.NativeInventoryUnsupported):
inventory.read_ascii_discovery(tmp_path/'board.prj',hier,('OLD',),expected_root='board',effective_report_path=flat)
def test_six_heterogeneous_units_with_shared_slot_number_compare_by_physical_pins():
from pathlib import Path
fixtures = Path(__file__).parent/'fixtures/native-complex'
parsed = native_netlist.read_graph(fixtures/'six-physical-gates.txt',fixtures/'six-physical-gates.kyn')
result = {'status':'success','complete':True,'graph':parsed}
assert native_netlist.compare_netlists(result,result)['verified']
@pytest.mark.parametrize('field,actual,wanted', [('source_page','2','1'),('source_schematic','OTHER','MAIN')])
def test_reused_uid_cannot_override_known_scope_mismatch(field,actual,wanted):
from dx_productivity.trial_task_center.netlist_verification import _reference_plan
before=graph('$1I1');before['graph']['components']['$1I1'][field]=actual
target={'uid':'$1I1','refdes':'R1', 'sheet_number' if field=='source_page' else 'schematic_name':wanted}
with pytest.raises(ValueError):
_reference_plan({'rows':[{'enabled':True,'target':target}]},before,{})
def test_snapshot_scope_disambiguates_unselected_raw_uid_collisions(tmp_path):
from dx_productivity.trial_task_center import native_helper as helper
path=tmp_path/'snapshot.tsv'
path.write_text('C\tselected\tR1\t0\t0\t0\t1\t\nU\tduplicate\tR2\tOTHER\tx\tn\tl\nU\tduplicate\tR3\tOTHER\tx\tn\tl\n')
with helper.snapshot_identity_scope(path):
identities=[helper._component_uid(SimpleNamespace(UID='duplicate',Refdes=ref)) for ref in ('R2','R3')]
assert identities==['@REFDES|R2','@REFDES|R3']
def unit(uid,x,part='NEW'):
attributes={'Part Number':part,'Part Name':'LIB:NEW','Part Label':'LABEL','Value':'1K'}
component=SimpleNamespace(UID=uid,Refdes='U1',Orientation=0,Scale=1,
GetLocation=lambda:SimpleNamespace(X=x,Y=0),
FindAttribute=lambda name:SimpleNamespace(Value=attributes[name],InstanceValue='') if name in attributes else None)
component._oleobj_=component
return component
def test_multiunit_readback_keeps_original_unit_keys_after_uid_churn(tmp_path):
from dx_productivity.trial_task_center import native_helper as helper
path=tmp_path/'snapshot.tsv'
path.write_text('C\told1\tU1\t0\t0\t0\t1\t\nC\told2\tU1\t100\t0\t0\t1\t\n')
records=[['C','old1','U1','0','0','0','1',''],['C','old2','U1','100','0','0','1','']]
with helper.snapshot_identity_scope(path):
current=[unit('new2',100),unit('new1',0)]
assert [helper._component_uid(component) for component in current]==['old2','old1']
assert helper.replacement_matches(current,records,'NEW',True,library_row=['','NEW','','','LIB:NEW','LABEL'])==['old1','old2']
assert helper.replacement_matches([unit('new1',0),unit('new2',100,'WRONG')],records,'NEW',True) is None
with pytest.raises(ValueError):
helper.replacement_matches([unit('new1',0),unit('new2',0)],records,'NEW',True)
def test_vbs_unit_aliases_survive_uid_changes_and_keep_physical_selector(tmp_path):
import test_accuracy_vbs_guards as guards
output=guards.run_vbs(tmp_path,['QPCommandTargetKey'],'''
Dim Rows,A,B,Selectors
Set Rows=CreateObject("Scripting.Dictionary")
Set A=New FakeComponent:A.UID="old1":A.X=0
Set B=New FakeComponent:B.UID="old2":B.X=100
Rows.Add A,True:Rows.Add B,True
QPBindSheetReferences Rows
A.UID="changed1":B.UID="changed2"
Set Selectors=CreateObject("Scripting.Dictionary")
Selectors.Add "@REFDES|U1",Array("U1","1K")
WScript.Echo QPComponentIdentityKey(A)
WScript.Echo QPComponentIdentityKey(B)
WScript.Echo QPCommandTargetKey(B,Selectors)
''',prelude='''
Class FakePoint
Public X,Y
End Class
Class FakeComponent
Public UID,X,Refdes,Orientation,Scale
Private Sub Class_Initialize()
Refdes="U1":Orientation=0:Scale=1
End Sub
Public Function GetLocation()
Dim P:Set P=New FakePoint:P.X=X:P.Y=0:Set GetLocation=P
End Function
End Class
Function QPSheetIdentity()
QPSheetIdentity="MAIN:1"
End Function
''')
assert output.splitlines()==['old1','old2','@REFDES|U1']
def test_multiunit_value_evidence_covers_physical_selector_without_dropping_units(tmp_path):
from test_value_readback import case
from dx_productivity.trial_task_center.value_readback import capture_value_readback
from dx_productivity.trial_task_center.quick_run_protocol import _encode_vbs_field as enc
row, raw=case(tmp_path)
row['target_selectors']='@REFDES|U1\x1fU1\x1f10nF'
snapshot='C\tu1\tU1\t0\t0\t0\t1\tNO_PINS\r\nC\tu2\tU1\t100\t0\t0\t1\tNO_PINS\r\n'
(tmp_path/'snapshot-job.tsv').write_bytes(snapshot.encode())
header=['V','2','task','job','saved_ok',row['project_path'],'MAIN','1','OLD','NEW','custom','10nF','1','CELL',row['target_selectors'],snapshot]
records=[header,['C','u1','U1','NEW','10nF','1','CELL'],['C','u2','U1','NEW','10nF','1','CELL']]
raw.write_text('\n'.join('\t'.join(map(enc,record)) for record in records)+'\n',encoding='utf8')
result=capture_value_readback(tmp_path,row,('saved_ok','batch_closed','verified'))
assert result['value_readback_status']=='verified',result
assert {item['uid'] for item in result['value_readback']}=={'u1','u2'}
raw.write_text('\n'.join('\t'.join(map(enc,record)) for record in records[:-1])+'\n',encoding='utf8')
assert capture_value_readback(tmp_path,row,('saved_ok','batch_closed','verified'))['value_readback_status']=='rejected'
def test_real_vbs_capture_records_all_units_of_one_physical_selector(tmp_path):
import test_accuracy_vbs_guards as guards
names=guards.UNTOUCHED_ROUTINES+['QPCaptureAndSelect','QPSnapshotComponent','QPCommandTargets',
'QPBooleanText','QPLogField','QPTargetCell','QPRequireUniqueAttributeNames','QPAttributeObservations']
path=tmp_path/'units.tsv'
output=guards.run_vbs(tmp_path,names,'''
Dim A,B,Attr,Pin,Command,Records,Comp
Set QP_App=New FakeApp
Set A=New FullComponent:A.UID="u1":A.Refdes="U1":A.X=0
Set B=New FullComponent:B.UID="u2":B.Refdes="U1":B.X=100
For Each Comp In Array(A,B)
Set Attr=New FullAttribute:Attr.Name="Part Number":Attr.Value="OLD":Attr.InstanceValue="OLD"
Comp.Attributes.Add Attr,True
Set Attr=New FullAttribute:Attr.Name="Value":Attr.Value="1K":Attr.InstanceValue="1K"
Comp.Attributes.Add Attr,True
QP_App.ActiveView.Components.Add Comp,True
Set Pin=New FakePin:Set Pin.Component=Comp:Pin.Number="1":Pin.X=Comp.X:Pin.Y=0
Set Pin.Connection=Nothing:QP_App.ActiveView.Pins.Add Pin,True
Next
Set Command=CreateObject("Scripting.Dictionary")
Command.Add "job_id","test":Command.Add "old_part_number","OLD":Command.Add "new_part_number","NEW"
Command.Add "schematic_name","MAIN":Command.Add "sheet_number","1"
Command.Add "target_scope","targets":Command.Add "target_selectors",QPEncode("@REFDES|U1" & Chr(31) & "U1" & Chr(31) & "1K")
QPCaptureAndSelect Command,"'''+str(path)+'''"
Set Records=QPReadSnapshot("'''+str(path)+'''")
WScript.Echo Records("components").Count
WScript.Echo CapturedState
''',prelude=guards.LOG_STUB+guards.FULL_FAKE+'''
Dim CapturedState
Sub QPBuildComponentIndex(ByRef Components)
End Sub
Function QPValueMode(ByRef Command)
QPValueMode="preserve"
End Function
Function QPCustomValue(ByRef Command)
QPCustomValue=""
End Function
Function QPSyncNc(ByRef Command)
QPSyncNc=False
End Function
Sub QPWriteStatus(ByVal Root,ByVal Job,ByVal State,ByVal Code,ByVal Message)
CapturedState=State
End Sub
''')
assert output.splitlines()==['2','awaiting_native_replace']
def test_fresh_vbs_recovery_restores_interleaved_unselected_unit_aliases(tmp_path):
import test_accuracy_vbs_guards as guards
from dx_productivity.trial_task_center.quick_run_protocol import _encode_vbs_field as enc
path=tmp_path/'recovery.tsv'
text='M\tC:\\board.prj\tOLD\tNEW\tMAIN:1\r\nC\tselected\tR1\t0\t0\t0\t1\t\r\nA\tselected\tValue\t1\t1\t0\t0\t0\t0\t10\t0\t1\r\n'
for uid,x in [('unit1','0'),('unit2','100')]:
state=f'C\t{uid}\tU1\t{x}\t0\t0\t1\tNO_PINS\r\n'
text+=f'U\t{uid}\tU1\tOTHER\tv\tn\tl\r\nG\t{uid}\t{enc(state)}\r\n'
path.write_bytes(text.encode())
output=guards.run_vbs(tmp_path,['QPReadSnapshot','QPReadUtf8'],'''
Dim QP_Fso,Records,A,B
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Set Records=QPReadSnapshot("'''+str(path)+'''")
Set A=New Unit:A.X=0:Set B=New Unit:B.X=100
WScript.Echo QPComponentIdentityKey(A)
WScript.Echo QPComponentIdentityKey(B)
''',prelude='''
Class Point
Public X,Y
End Class
Class Unit
Public X
Public Property Get UID()
UID="changed"
End Property
Public Property Get Refdes()
Refdes="U1"
End Property
Public Function GetLocation()
Dim P:Set P=New Point:P.X=X:P.Y=0:Set GetLocation=P
End Function
Public Property Get Orientation()
Orientation=0
End Property
Public Property Get Scale()
Scale=1
End Property
End Class
Function QPSheetIdentity()
QPSheetIdentity="MAIN:1"
End Function
''')
assert output.splitlines()==['unit1','unit2']
def test_all_match_pre_submit_rejects_reused_uid_with_changed_ref(monkeypatch):
from dx_productivity.trial_task_center import native_helper as helper
component=unit('original',0,'OLD');component.Refdes='R2'
app=SimpleNamespace(ActiveView=SimpleNamespace(Query=lambda *args:[component]))
monkeypatch.setattr(helper,'check_active_context',lambda *args:None)
with pytest.raises(ValueError,match='reference|Reference'):
helper.check_context(app,SimpleNamespace(IVdComp=lambda value:value),
['M','board','OLD','NEW','MAIN:1','preserve'],[['C','original','R1','0','0','0','1','']],require_selection=False)
def test_vbs_snapshot_does_not_alias_distinct_blank_reference_annotations(tmp_path):
import test_accuracy_vbs_guards as guards
from dx_productivity.trial_task_center.quick_run_protocol import _encode_vbs_field as enc
path=tmp_path/'annotations.tsv'
text='M\tC:\\board.prj\tOLD\tNEW\tMAIN:1\r\nC\tselected\tR1\t0\t0\t0\t1\t\r\nA\tselected\tValue\t1\t1\t0\t0\t0\t0\t10\t0\t1\r\n'
for uid in ('annotation1','annotation2'):
state=f'C\t{uid}\t\t0\t0\t0\t1\tNO_PINS\r\n'
text+=f'U\t{uid}\t\t\t\t\t\r\nG\t{uid}\t{enc(state)}\r\n'
path.write_bytes(text.encode())
output=guards.run_vbs(tmp_path,['QPReadSnapshot','QPReadUtf8'],'''
Dim QP_Fso,Records,A,B
Set QP_Fso=CreateObject("Scripting.FileSystemObject")
Set Records=QPReadSnapshot("'''+str(path)+'''")
Set A=New Annotation:A.UID="annotation1"
Set B=New Annotation:B.UID="annotation2"
WScript.Echo QPComponentIdentityKey(A)
WScript.Echo QPComponentIdentityKey(B)
WScript.Echo CStr(QP_ReferenceAliases.Exists("main:1|"))
''',prelude='''
Class Annotation
Public UID,Refdes
End Class
Function QPSheetIdentity()
QPSheetIdentity="MAIN:1"
End Function
''')
assert output.splitlines()==['annotation1','annotation2','False']
def test_semantic_capture_reports_each_completed_component_without_changing_baseline(tmp_path):
import test_accuracy_vbs_guards as guards
output=guards.run_vbs(tmp_path,['QPCurrentSemanticState','QPSortSnapshotLines'],'''
Dim QP_App,State
Set QP_App=New App
State=QPCurrentSemanticState()
WScript.Echo Replace(State,vbCrLf,";")
''',prelude='''
Const VDM_COMP=128
Const VD_ALL=0
Class App
Property Get ActiveView()
Set ActiveView=Me
End Property
Function Query(ByVal Kind,ByVal Scope)
Dim Rows:Set Rows=CreateObject("Scripting.Dictionary")
Rows.Add "C3",True:Rows.Add "C1",True:Rows.Add "C2",True
Set Query=Rows
End Function
End Class
Sub QPInvalidatePinIndex()
End Sub
Sub QPInvalidateComponentIndex()
End Sub
Function QPUntouchedFullState(ByVal Comp)
QPUntouchedFullState=Comp & vbCrLf
End Function
Sub QPProgress(ByVal Stage,ByVal Done,ByVal Total)
WScript.Echo Stage & ":" & Done & "/" & Total
End Sub
''')
assert output.splitlines()[:3]==['capture_semantic_state:1/3','capture_semantic_state:2/3','capture_semantic_state:3/3']
assert output.splitlines()[3]=='S\tfull_sheet_v1;C1;C2;C3;'
def test_semantic_component_progress_refreshes_business_watchdog():
from dx_productivity.trial_task_center.worker_monitor import ProgressWatch
watch=ProgressWatch('token','job',150,0)
for sequence,now in enumerate((100,200,300,400),1):
assert watch.accept(f'DX_PROGRESS\ttoken\tjob\t{sequence}\tcapture_semantic_state\t{sequence}\t104\t0\n'.encode(),now)
assert watch.action(now+100) is None
assert not watch.stop_requested
+9 -6
View File
@@ -10,8 +10,10 @@ from dx_productivity.trial_task_center.batch_resources import LIVE_RESOURCES, cl
from dx_productivity.trial_task_center.errors import TaskCenterError
def test_closed_desktop_rechecks_only_observe_until_external_reference_disappears(tmp_path):
def test_closed_desktop_rechecks_only_observe_until_external_reference_disappears(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.isolated_desktop import PrivateDesktop
from dx_productivity.trial_task_center import isolated_desktop, batch_resources
import json
calls = []
class Api:
present = True
@@ -21,6 +23,7 @@ def test_closed_desktop_rechecks_only_observe_until_external_reference_disappear
if self.present:
raise OSError('external reference remains')
api = Api()
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: api)
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
runtime._ensure_desktop()
desktop = PrivateDesktop(runtime.record['desktop'], enabled=True, api=api)
@@ -28,19 +31,19 @@ def test_closed_desktop_rechecks_only_observe_until_external_reference_disappear
runtime.desktop = desktop
runtime.result = 'saved result'
try:
with pytest.raises(TaskCenterError):
runtime.close()
original_error = runtime.record['error']
runtime.close()
assert runtime.record['state'] == 'isolated'
for _ in range(3):
assert cleanup_pending_resources(tmp_path)
assert not batch_resources.blocking_resources(tmp_path)
assert calls.count('close') == 1
api.present = False
assert cleanup_pending_resources(tmp_path) == ()
assert calls.count('close') == 1
assert all(call == 'close' or call == ('observe', desktop.name) for call in calls)
assert runtime.result == 'saved result'
assert runtime.record['error'] == original_error
assert runtime.record['cleanup']['desktop_confirmation']['released'] is True
final = json.loads(runtime.path.read_text(encoding='utf-8'))
assert final['state'] == 'released' and final['release_proof']['desktop_released'] is True
finally:
LIVE_RESOURCES.pop(str(runtime.path), None)
+162
View File
@@ -0,0 +1,162 @@
import json
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center import batch_resources, batch_runtime, isolated_desktop
def runtime_with_residual(tmp_path, monkeypatch):
calls = []
class Desktop:
def __init__(self, name, **options):
self.name = name
self._processes = []
self.cleanup_record = None
def __enter__(self): return self
def close(self):
calls.append('close')
self.cleanup_record = {'desktop_handle_closed': True,
'owned_cleanup_complete': True,
'desktop_confirmation': {'released': False}, 'errors': ['foreign reference']}
raise OSError('foreign reference')
def release_desktop(self):
calls.append('observe')
raise OSError('foreign reference')
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execute_task_queue', desktop_factory=Desktop)
runtime.__enter__()
runtime._ensure_desktop()
runtime.result = {'completed': True}
return runtime, calls
def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch):
runtime, calls = runtime_with_residual(tmp_path, monkeypatch)
runtime.close()
assert runtime.record['state'] == 'isolated'
assert runtime.record['blocking'] is False
assert runtime.record['release_results']['desktop_released'] is False
assert batch_resources.blocking_resources(tmp_path) == ()
assert batch_resources.pending_resources(tmp_path)[0]['state'] == 'isolated'
with pytest.raises(batch_resources.BatchResourceCleanupError):
runtime._ensure_desktop()
runtime.close()
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(
confirm_desktop_released=lambda name: (_ for _ in ()).throw(OSError('foreign reference'))))
batch_resources.cleanup_pending_resources(tmp_path)
assert calls == ['close']
with batch_runtime.BatchCadRuntime(tmp_path, 'next') as admitted:
assert admitted.generation == 0
assert runtime.result == {'completed': True}
def test_isolation_proof_is_revalidated_after_restart_and_does_not_trust_label(tmp_path, monkeypatch):
runtime, _ = runtime_with_residual(tmp_path, monkeypatch)
identity = {'pid': 1234, 'creation_time': 'exact'}
runtime.record['writer_identities'] = [identity]
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: True)
runtime.close()
proof = runtime.record['isolation_proof']
assert proof['processes'] == [identity]
assert proof['session_id'] == runtime.session_id and proof['generation'] == 1
assert batch_resources.blocking_resources(tmp_path) == ()
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: False)
assert batch_resources.blocking_resources(tmp_path)
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
assert batch_resources.cleanup_pending_resources(tmp_path)
assert batch_resources.blocking_resources(tmp_path)
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: True)
record = json.loads(runtime.path.read_text(encoding='utf-8'))
record['isolation_proof']['generation'] = 99
batch_resources.write_record(runtime.path, record)
assert batch_resources.blocking_resources(tmp_path)
def test_active_or_unknown_writer_cannot_be_isolated(tmp_path, monkeypatch):
runtime, _ = runtime_with_residual(tmp_path, monkeypatch)
runtime.record['writer_identities'] = [{'pid': 1234, 'creation_time': 'exact'}]
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: False)
with pytest.raises(batch_resources.BatchResourceCleanupError): runtime.close()
assert batch_resources.blocking_resources(tmp_path)
runtime.record['writer_identities'][0]['creation_time'] = None
monkeypatch.setattr(batch_resources, '_process_gone', lambda item: True)
with pytest.raises(batch_resources.BatchResourceCleanupError): runtime.close(reason='manual_retry')
assert batch_resources.blocking_resources(tmp_path)
def test_isolation_log_never_claims_resources_released(tmp_path):
from dx_productivity.trial_task_center.batch_release_log import write_release_event
from dx_productivity.trial_task_center.logging_setup import configure_logging
context = configure_logging(tmp_path)
path = tmp_path / 'batch-resources' / ('a' * 32) / 'session.json'
record = {'session_id': 'a' * 32, 'generation': 1, 'state': 'isolated', 'kind': 'execution'}
assert write_release_event(tmp_path, path, record, 'isolated', context=context) == []
text = path.parent.joinpath('resource-release.log').read_text(encoding='utf-8')
assert 'isolated' in text
def test_passive_disappearance_confirmation_updates_both_release_state_and_result(tmp_path, monkeypatch):
runtime, calls = runtime_with_residual(tmp_path, monkeypatch)
runtime.close()
monkeypatch.setattr(isolated_desktop, '_Win32Api', lambda: SimpleNamespace(confirm_desktop_released=lambda _: None))
assert batch_resources.cleanup_pending_resources(tmp_path) == ()
final = json.loads(runtime.path.read_text(encoding='utf-8'))
assert final['release_results']['desktop_released'] is True
assert final['release_state']['desktop'] == 'released'
assert calls == ['close']
def test_supervisor_preserves_success_and_business_failure_with_nonfatal_desktop_warning(tmp_path, monkeypatch):
from dx_productivity.trial_task_center.batch_supervisor import _finish_response
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.supervisor_protocol import encode, encode_error
from dx_productivity.trial_task_center.errors import TaskCenterError
runtime, _ = runtime_with_residual(tmp_path, monkeypatch)
runtime.close()
warnings = batch_resources.pending_resources(tmp_path)
monkeypatch.setattr(batch_resources, 'cleanup_pending_resources', lambda *args, **kwargs: warnings)
journal = {'operation': 'probe', 'batch_id': runtime.session_id}
result = {'verified': True}
response = {'business_succeeded': True, 'status': 'ok', 'result': encode(result)}
assert _finish_response(tmp_path, journal, response, configure_logging(tmp_path)) == result
assert journal['state'] == 'finished'
assert journal['resource_recheck']['desktop_released'] is False
response = {'business_succeeded': False, 'status': 'error',
'error': encode_error(TaskCenterError('replacement_uncertain', 'requires verification'))}
with pytest.raises(TaskCenterError) as caught:
_finish_response(tmp_path, journal, response, configure_logging(tmp_path))
assert caught.value.code == 'replacement_uncertain'
assert caught.value.resources_released is False and caught.value.owned_writers_exited is True
def test_resource_status_displays_isolation_warning_without_blocking(qtbot):
from dx_productivity.trial_task_center.ui.resource_status import ResourceStatus
warning = {'state': 'isolated', 'blocking': False, 'desktop_released': False}
status = ResourceStatus(lambda: (warning,))
try:
status.refresh()
qtbot.waitUntil(lambda: not status.busy)
assert status.records == (warning,) and not status.blocked
status._received((warning, {'state': 'blocked'}))
assert status.blocked
finally:
status.close()
def test_failed_project_initiates_owned_cleanup_before_certifying_exit(tmp_path):
from test_batch_runtime import Desktop
from dx_productivity.trial_task_center.stop_control import StopControl
control = StopControl()
runtime = batch_runtime.BatchCadRuntime(tmp_path, 'execution', control, desktop_factory=Desktop)
runtime._ensure_desktop()
process = SimpleNamespace(returncode=None, poll=lambda: process.returncode)
def close(*args):
assert (tmp_path / 'failed' / 'uncertain.flag').exists()
assert control.cleanup_mode == 'mentor_release_required'
assert runtime.record['wait_reason'] == 'mentor_exit'
process.returncode = 0
runtime.cad = SimpleNamespace(cad=process, __exit__=close, record={})
assert runtime.release_failed_project(RuntimeError('source read failed'), tmp_path / 'failed')
assert runtime.desktop is None and runtime.cad is None
proof = json.loads((tmp_path / 'failed' / 'project-resource-release.json').read_text())
assert proof['writers_exited'] is True and proof['business_uncertainty_preserved'] is True
@@ -0,0 +1,104 @@
from pathlib import Path
import subprocess
import os
import sys
from threading import Event
import pytest
from dx_productivity.trial_task_center import batch_attempt
from dx_productivity.trial_task_center.stop_control import StopControl
from dx_productivity.trial_task_center.worker_monitor import WorkerMonitorError
@pytest.mark.parametrize('damage', [None, 'current_mutated', 'marker_missing', 'uncovered_prefix', 'source_unexplained', 'checkpoint'])
def test_prewrite_pause_certifies_only_current_job_and_hash_binds_committed_prefix(tmp_path, monkeypatch, damage):
from test_batch_runtime import command_for, worker_runtime, Cad
command, project = command_for(tmp_path)
root = Path(command[3])
text = (root / 'command.tsv').read_text()
(root / 'command.tsv').write_text(text + f'task\tnext\t{project}\told\tnew\n')
request = root / 'project-session.request'
request.write_text(f'{"a"*32}\t{project}\tjob')
def monitor(*args, **kwargs):
runtime.stop_event.set()
request.write_text(f'{"a"*32}\t{project}\tnext')
paths = {expected['job_id']: (path, expected) for path, expected in runtime._current_attempts}
path, expected = paths['job']
batch_attempt._publish(path, dict(expected, state='mutation_possible'))
if damage == 'current_mutated':
path, expected = paths['next']
batch_attempt._publish(path, dict(expected, state='mutation_possible'))
project.write_text('saved prefix')
if damage != 'marker_missing':
(root / ('project-pause-' + 'a'*32 + '.tsv')).write_text(f'{"a"*32}\t{project}\tnext\tprewrite_closed')
if damage != 'source_unexplained':
(root / ('project-commit-' + 'a'*32 + '.tsv')).write_text(
f'{"a"*32}\t{project}\tproject_verified\n' + ('foreign' if damage == 'uncovered_prefix' else 'job') + '\tsaved_ok\n')
for name in ('post-state-job.tsv', 'snapshot-job.tsv', 'snapshot-job.tsv.native.json', 'value-readback-job.tsv'):
(root / name).write_text('bound native prefix evidence')
if damage == 'checkpoint':
runtime.cad.checkpoint = lambda *args: (_ for _ in ()).throw(WorkerMonitorError('project still open'))
result = subprocess.CompletedProcess(command, 75, '', '')
result.prewrite_pause = {'session_token': 'a'*32, 'monitor_token': 'b'*32,
'job_id': 'next', 'project_path': str(project), 'sequence': 7, 'worker_tree_exited': True}
return result
runtime = worker_runtime(tmp_path, monkeypatch, monitor)
runtime.cad_factory = lambda *args, stop_control=None, **options: Cad(*args, **options)
runtime.stop_event = StopControl()
# Invalid certificates must fail promptly; no fake writer needs a live resolution wait.
monkeypatch.setattr(runtime, '_retain_uncertain', lambda *args: None)
with runtime:
if damage:
with pytest.raises(WorkerMonitorError): runtime.run_worker(command, 5)
else:
result = runtime.run_worker(command, 5)
proof = result.prewrite_pause
assert proof['phase'] == 'before_native_dispatch' and proof['job_id'] == 'next'
assert len(proof['batch_attempts']) == 1
assert proof['batch_attempts'][0]['expected']['job_id'] == 'next'
assert proof['committed_prefix'] == {'job': 'saved_ok'}
assert proof['native_dispatch_not_started'] and proof['project_closed']
assert proof['files']
@pytest.mark.skipif(os.name != 'nt', reason='Actual owned Windows protocol actor')
@pytest.mark.parametrize('damage', [None, 'token', 'session', 'job', 'sequence', 'marker', 'no_abort'])
def test_monitor_prewrite_pause_correlates_current_job_after_prior_unsafe_prefix(tmp_path, damage):
from dx_productivity.trial_task_center.worker_monitor import run_monitored_process
from dx_productivity.trial_task_center.isolated_desktop import _Win32Api
project = tmp_path / 'board.prj'
project.write_text('fixture')
(tmp_path / 'project-session.request').write_text(f'{"a"*32}\t{project}\tjob')
script = tmp_path / 'actor.py'
script.write_text('''import pathlib,sys,time
root=pathlib.Path(sys.argv[1]);job=sys.argv[4];token=sys.argv[5]
damage=''' + repr(damage) + '''
while not (root/f'monitor-{token}.ready').exists():time.sleep(.002)
if damage!='no_abort':
while not (root/f'monitor-{token}.stop').exists():time.sleep(.002)
request=root/'project-session.request'
fields=request.read_text().split('\\t');fields[2]='next';request.write_text('\\t'.join(fields))
print(f'DX_PROGRESS\\t{token}\\t{job}\\t1\\tnative_replace\\t0\\t1\\t0\\tjob',flush=True)
print(f'DX_PROGRESS\\t{token}\\t{job}\\t2\\tverify_saved_project\\t1\\t1\\t0\\tjob',flush=True)
if damage!='marker':(root/('project-pause-'+fields[0]+'.tsv')).write_text('\\t'.join([fields[0],fields[1],'next','prewrite_closed']))
print('\\t'.join(['DX_PREWRITE_PAUSED','bad' if damage=='token' else token,job,
'c'*32 if damage=='session' else fields[0],'bad' if damage=='job' else 'next',
'99' if damage=='sequence' else '2']),flush=True)
sys.exit(75)
''', encoding='utf-8')
stop, api = Event(), _Win32Api()
if damage != 'no_abort': stop.set()
command = (sys.executable, '-u', str(script), str(tmp_path), sys.executable, '', 'job')
try:
if damage:
with pytest.raises(WorkerMonitorError):
run_monitored_process(command, 5, abort_event=stop,
process_factory=lambda launch, **options: api.create_process(launch, None, tmp_path, None, **options))
else:
result = run_monitored_process(command, 5, abort_event=stop,
process_factory=lambda launch, **options: api.create_process(launch, None, tmp_path, None, **options))
assert result.prewrite_pause['job_id'] == 'next'
assert result.prewrite_pause['worker_tree_exited'] is True
finally:
api.close_pending()
+3 -3
View File
@@ -54,7 +54,7 @@ def test_restart_with_incomplete_handoff_never_replays_worker(resume_case,damage
assert context.interrupted
assert context.has_evidence
outcome=execute_task_queue(restarted,(task.task_id,),stop_event=Event())
assert outcome.paused and outcome.entries[0].state=='blocked'
assert not outcome.paused and outcome.entries[0].state=='blocked'
assert len(calls)==2
@@ -84,7 +84,7 @@ def test_receipts_block_rollback_to_an_empty_status_even_without_sidecars(resume
restarted=reopen()
assert restarted.task_context(task.task_id).interrupted
result=execute_task_queue(restarted,(task.task_id,),stop_event=Event())
assert result.paused and len(calls)==2
assert not result.paused and result.entries[0].state=='blocked' and len(calls)==2
def test_missing_entire_handoff_cannot_erase_database_receipts(resume_case):
@@ -93,4 +93,4 @@ def test_missing_entire_handoff_cannot_erase_database_receipts(resume_case):
restarted=reopen()
assert restarted.task_context(task.task_id).interrupted
result=execute_task_queue(restarted,(task.task_id,),stop_event=Event())
assert result.paused and len(calls)==2
assert not result.paused and result.entries[0].state=='blocked' and len(calls)==2
+2 -1
View File
@@ -89,7 +89,8 @@ def test_timeout_without_complete_proof_stays_uncertain(component_case, unsafe):
raise error
preparer._process_runner = worker
result = execute_task_queue(service, (task_id,), stop_event=stop)
assert result.paused
assert result.paused is (unsafe == 'cancelled')
assert result.entries[0].state == 'blocked'
assert calls == []
assert service.reserve_problem_retry(task_id) == ()
assert preparer.has_interrupted(task_id)
+7 -7
View File
@@ -70,11 +70,11 @@ def test_changed_confirmed_plan_is_rejected_before_any_executor(tmp_path):
assert not service.calls
def test_preflight_named_error_after_dispatch_needs_receipt_before_continuing(tmp_path):
def test_dispatched_error_isolates_the_project_after_its_owned_resources_exit(tmp_path):
service = Service(tmp_path, {'A': TaskCenterError('quick_run_preflight', 'target absent')})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
assert result.paused and result.entries[0].state == 'blocked'
assert service.calls == [('start', 'A')]
assert not result.paused and result.entries[0].state == 'blocked'
assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')]
def test_actual_read_phase_failure_allows_next_project(tmp_path):
@@ -93,12 +93,12 @@ def test_actual_read_phase_failure_allows_next_project(tmp_path):
assert service.calls == [('start', 'B'), ('end', 'B')]
def test_uncertain_result_blocks_next_task(tmp_path):
def test_uncertain_result_is_quarantined_without_replaying_before_next_independent_task(tmp_path):
service = Service(tmp_path, {'A': TaskCenterError('quick_run_uncertain', 'unknown')})
result = execute_task_queue(service, ('A', 'B'), stop_event=Event())
assert result.paused
assert not result.paused
assert result.entries[0].state == 'blocked'
assert service.calls == [('start', 'A')]
assert service.calls == [('start', 'A'), ('start', 'B'), ('end', 'B')]
def test_pause_finishes_current_item_and_does_not_start_next_task(tmp_path):
@@ -122,7 +122,7 @@ def test_pause_between_problem_tasks_preserves_resumable_batch(tmp_path, monkeyp
assert result.paused and result.current_task_id in {'A', 'B'}
assert [entry.state for entry in result.entries] == ['failed', 'completed']
import json
checkpoint = json.loads((tmp_path / 'task-queues' / (result.queue_id + '.json')).read_text())
checkpoint = json.loads((tmp_path / 'task-queues' / (result.queue_id + '.json')).read_text(encoding='utf-8'))
assert checkpoint['phase'] == 'problems'
+114
View File
@@ -0,0 +1,114 @@
"""Resource recheck failures must publish a terminal result after writers exit."""
import json
import os
from pathlib import Path
import subprocess
import sys
import textwrap
from types import SimpleNamespace
from uuid import uuid4
import pytest
from dx_productivity.trial_task_center import batch_worker, isolated_cad, stop_control, worker_monitor
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
from dx_productivity.trial_task_center.supervisor_protocol import encode
@pytest.mark.parametrize('owner', ['exited', 'runtime', 'cad', 'worker'])
def test_resource_error_is_returnable_only_after_all_write_owners_exit(tmp_path, monkeypatch, owner):
failure = BatchResourceCleanupError('desktop object still exists')
def close(**options):
raise failure
runtime = SimpleNamespace(read_only=False, root=tmp_path, path=tmp_path / 'session.json',
record={'state': 'blocked'}, desktop=object(), cad=None,
owned_processes_exited=lambda: owner != 'runtime', close=close)
monkeypatch.setattr(isolated_cad, 'RETAINED_CAD_SESSIONS', {
'fixture': SimpleNamespace(root=tmp_path, _owned_processes=lambda: [
SimpleNamespace(tree_exited=lambda: owner != 'cad')])})
monkeypatch.setattr(worker_monitor, 'RETAINED_WORKERS', {
'fixture': {'root': tmp_path, 'process': object(), 'owned': object()}})
monkeypatch.setattr(worker_monitor, '_worker_tree_exited', lambda *args: owner != 'worker')
monkeypatch.setattr(worker_monitor, 'cleanup_retained_workers', lambda *args, **kwargs: None)
# Simulate a failed release attempt; it must not count as proof of exit.
monkeypatch.setattr(stop_control, 'wait_for_resolution', lambda *args, **kwargs: None)
if owner == 'exited':
assert batch_worker._wait_for_owned_writes(runtime, stop_control.StopControl()) is failure
else:
with pytest.raises(BatchResourceCleanupError) as caught:
batch_worker._wait_for_owned_writes(runtime, stop_control.StopControl())
assert caught.value is failure
@pytest.mark.parametrize('business_failed', [False, True])
@pytest.mark.parametrize('initial_cleanup_failed', [False, True])
def test_real_worker_exits_with_durable_result_when_desktop_recheck_fails(tmp_path, business_failed,
initial_cleanup_failed):
batch_id, attempt_id = uuid4().hex, uuid4().hex
directory = tmp_path / 'batch-resources' / batch_id
directory.mkdir(parents=True)
request = directory / 'request.json'
request.write_text(json.dumps({'version': 1, 'batch_id': batch_id, 'attempt_id': attempt_id,
'root': str(tmp_path), 'database': str(tmp_path / 'tasks.db'), 'operation': 'execute_task_queue',
'arguments': encode({}), 'task_ids': []}), encoding='utf-8')
launcher = textwrap.dedent('''
import sys
from pathlib import Path
from types import SimpleNamespace
from dx_productivity.trial_task_center import batch_runtime, batch_worker, read_recovery, task_queue
from dx_productivity.trial_task_center.batch_resources import BatchResourceCleanupError
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.errors import TaskCenterError
batch_worker._admit_request = lambda *args: {}
read_recovery.check_owner_loss = lambda *args, **kwargs: False
class FailingDesktop(batch_runtime.BatchCadRuntime):
def __enter__(self):
self.desktop = SimpleNamespace(_processes=[], cleanup_record={
'desktop_handle_closed': True, 'desktop_confirmation': {'released': False}})
self.record.update(state='blocked', error='desktop object still exists')
return self
def __exit__(self, *args):
if sys.argv[3] == 'True':
raise BatchResourceCleanupError('initial desktop release failed')
def close(self, **kwargs):
raise BatchResourceCleanupError('desktop recheck still failed')
batch_runtime.BatchCadRuntime = FailingDesktop
def execute(*args, **kwargs):
if sys.argv[2] == 'True':
raise TaskCenterError('fixture', 'business failed')
return task_queue.TaskQueueResult('fixture', (
task_queue.TaskQueueEntry('saved', 'completed'),
task_queue.TaskQueueEntry('untouched', 'pending')), paused=True)
task_queue.execute_task_queue = execute
close_store = TaskStore.close
def close(self):
close_store(self)
(Path(sys.argv[1]).parent / 'store-closed').touch()
TaskStore.close = close
raise SystemExit(batch_worker.run(Path(sys.argv[1])))
''')
result = subprocess.run([sys.executable, '-X', 'utf8', '-c', launcher, str(request),
str(business_failed), str(initial_cleanup_failed)],
capture_output=True, text=True, encoding='utf-8', timeout=20,
env=dict(os.environ, PYTHONPATH=str(Path(batch_worker.__file__).resolve().parents[2])))
assert result.returncode == 0, result.stderr
final = json.loads((directory / 'result.json').read_text(encoding='utf-8'))
body = final['payload']
assert final['batch_id'] == batch_id and final['attempt_id'] == attempt_id
assert body['status'] == 'error' and body['business_succeeded'] is (not business_failed)
assert (directory / 'store-closed').is_file()
assert json.loads(result.stdout.splitlines()[-1]) == final
assert 'desktop recheck still failed' in (directory / 'supervisor.log').read_text(encoding='utf-8')
expected_error = ('initial desktop release failed' if initial_cleanup_failed else
'business failed' if business_failed else 'desktop recheck still failed')
assert body['error']['message'] == expected_error
if business_failed:
assert body['operation_error']['message'] == 'business failed'
else:
saved = json.loads((directory / 'business-result.json').read_text(encoding='utf-8'))
assert body['result'] == saved['payload']['result']
from dx_productivity.trial_task_center.supervisor_result import validated_outcome
queue = validated_outcome('execute_task_queue', body)[0]
assert queue.paused is True
assert [(entry.task_id, entry.state) for entry in queue.entries] == [
('saved', 'completed'), ('untouched', 'pending')]