feat-ui-operation-history-and-durable-execution
Core regression / Python core and release configuration (push) Successful in 17s
Core regression / JavaScript syntax (push) Successful in 3s
Core regression / Python core and release configuration (pull_request) Successful in 16s
Core regression / JavaScript syntax (pull_request) Successful in 3s

This commit is contained in:
阿白叔 committed 2026-11-03 17:54:17 +08:00
1 parent 4874c7e95a
commit cf90ced825
44 files changed
+3165 -92

No files matched your search

@@ -173,6 +173,7 @@ def test_batch_no_match_commits_only_after_owned_project_close(tmp_path):
run_session(tmp_path, '''
Set QP_App=FakeApp
FakeApp.ProjectPath=Target
Set FakeApp.ActiveView=FakeApp
QP_CurrentJobId="batch-job": QP_ExpectedJobId="batch-job"
QPWriteUtf8 QP_Fso.BuildPath(QP_Root,"command.tsv"),"task_id" & vbTab & "job_id" & vbTab & "project_path" & vbTab & "old_part" & vbTab & "new_part" & vbTab & "value_mode" & vbCrLf & "task" & vbTab & "batch-job" & vbTab & Target & vbTab & "OLD" & vbTab & "NEW" & vbTab & "preserve" & vbCrLf
QP_BatchMode=True: QP_OwnedProject=True: QP_OwnedProjectPath=Target
@@ -182,6 +183,7 @@ Require QPReadState(QP_Fso.BuildPath(QP_Root,"status.tsv"),QP_CurrentJobId)="no_
QPFinishBatchItem
Require FakeApp.CloseCount=1,"project not closed exactly once"
Require FakeApp.SaveCount=0,"no-match must close without saving"
Require QP_Fso.FileExists(QP_Fso.BuildPath(QP_Root,"post-state-batch-job.tsv")),"missing semantic readback proof"
Require InStr(QPReadUtf8(QP_Fso.BuildPath(QP_Root,"status.tsv")),"batch_closed")>0,"no completion proof"
''')
+42 -1
View File
@@ -272,7 +272,7 @@ def test_failed_commit_restores_status_and_lock(interrupted, monkeypatch):
@pytest.mark.parametrize('initial', ['ready', 'paused', 'failed'])
def test_service_recovery_updates_queue_and_database(interrupted, initial):
def test_service_recovery_updates_queue_and_database(interrupted, initial, monkeypatch):
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.service import TaskCenterService
@@ -295,12 +295,53 @@ def test_service_recovery_updates_queue_and_database(interrupted, initial):
elif initial == 'failed':
store.set_task_status(task.task_id, TaskStatus.FAILED)
interrupted.preparer._process_runner = worker_result(interrupted)
def no_reimport(*args,**kwargs):
raise AssertionError('verified recovery must commit its proof directly, not reimport old active files')
monkeypatch.setattr(interrupted.preparer,'result_proof',no_reimport)
result = service.recover_quick_run(task.task_id, confirmed=True)
assert result.state == 'restored_ok'
assert store.get_task(task.task_id).status is TaskStatus.COMPLETED
assert service.quick_run_progress(task.task_id).queue_complete
assert not service.has_interrupted_quick_run(task.task_id)
@pytest.mark.parametrize('state', ['restored_ok', 'retry_ready'])
@pytest.mark.parametrize('fault', ['receipt','after_binding'])
def test_verified_recovery_replays_receipt_commit_without_a_second_worker(interrupted, monkeypatch, state, fault):
from dx_productivity.trial_task_center.execution_journal import ExecutionJournal
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(interrupted.root/'tasks.db')
try:
service=TaskCenterService(store,configure_logging(interrupted.root),quick_run_preparer=interrupted.preparer)
task=service.create_task('Crash during recovery commit')
service.set_copy_part_number_to_value(task.task_id,True)
project=service.scan_projects(task.task_id,interrupted.projects[0].path.parent)[0]
service.set_project_selected(project.project_id,True)
service.add_rule(task.task_id,'OLD','NEW',target_cell='CELL')
path=interrupted.handoff.command_path
path.write_text(path.read_text().replace('task\t',task.task_id+'\t'),encoding='utf8')
calls=[]
native=worker_result(interrupted,state)
def worker(*args,**kwargs):calls.append(1);return native(*args,**kwargs)
interrupted.preparer._process_runner=worker
original=ExecutionJournal.reconcile_recovery
original_unlink=Path.unlink
def crash(*args,**kwargs):raise OSError('controlled database write failure')
def crash_after_binding(path,*args,**kwargs):
if path.name=='recovery-commit.json':raise OSError('controlled crash after file/database binding')
return original_unlink(path,*args,**kwargs)
if fault=='receipt':monkeypatch.setattr(ExecutionJournal,'reconcile_recovery',crash)
else:monkeypatch.setattr(Path,'unlink',crash_after_binding)
with pytest.raises(Exception):service.recover_quick_run(task.task_id,confirmed=True)
monkeypatch.setattr(ExecutionJournal,'reconcile_recovery',original)
monkeypatch.setattr(Path,'unlink',original_unlink)
result=service.recover_quick_run(task.task_id,confirmed=True)
assert result.state==state and len(calls)==1
assert not service.has_interrupted_quick_run(task.task_id)
finally:store.close()
@pytest.mark.parametrize('fault',['source_changed','choice_removed','proof_missing'])
def test_cell_catalog_drift_blocks_recovery_before_worker(interrupted,fault):
calls=[]
+1 -1
View File
@@ -382,7 +382,7 @@ def test_v1_database_migrates_to_attempt_metadata_schema(tmp_path: Path) -> None
assert migrated.get_task(task.task_id).name == "Trial"
with sqlite3.connect(database) as connection:
assert connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == "7"
assert connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == "8"
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'attempts'").fetchone()
assert connection.execute("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'external_requests'").fetchone()
@@ -99,7 +99,7 @@ def test_migrations_preserve_target_plan(tmp_path: Path, version: int):
store.close()
migrated = TaskStore(path)
assert migrated.read_task_bundle(task.task_id).targets == original
assert migrated._connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == '7'
assert migrated._connection.execute("SELECT value FROM metadata WHERE key = 'schema_version'").fetchone()[0] == '8'
def test_failed_migration_rolls_back_version_and_schema(tmp_path: Path, monkeypatch):
@@ -0,0 +1,46 @@
from PySide6.QtCore import Qt
from dx_productivity.trial_task_center.history_store import HistoryRepository
def test_history_navigation_search_and_return_preserve_current_task(ui,qtbot,monkeypatch):
window=ui.window;task_id=window._task_id
def no_dsh(_self):raise AssertionError('History must not launch DSH')
monkeypatch.setattr(type(window),'_create_dsh_view',no_dsh)
HistoryRepository(ui.store).append(task_id=task_id,task_name='Board-A',project_path='C:/CBB/A.prj',
operation='器件替换',state='verified',summary='HISTORY-PROBE R1 OLD → NEW',details={'refdes':'R1','old_part':'OLD','new_part':'NEW'})
qtbot.mouseClick(window.history_navigation,Qt.MouseButton.LeftButton)
panel=window.history_panel
qtbot.waitUntil(lambda:not panel._query.busy)
assert window.content_stack.currentWidget() is panel
assert window.history_action.isChecked() and not window.dsh_action.isChecked()
assert panel.table.rowCount()>=1
# Initial saved-plan history may also contain R1; isolate this known result.
panel.search.setText('HISTORY-PROBE')
qtbot.waitUntil(lambda:not panel._search_timer.isActive() and not panel._query.busy)
assert panel.table.rowCount()==1
panel.table.selectRow(0)
assert 'OLD' in panel.details.toPlainText() and 'NEW' in panel.details.toPlainText()
qtbot.mouseClick(window.task_center_navigation,Qt.MouseButton.LeftButton)
assert window.content_stack.currentIndex()==0 and window._task_id==task_id
assert window.task_center_action.isChecked() and not window.history_action.isChecked()
def test_history_service_records_real_configuration_changes_and_ignores_reads(ui):
task=ui.tasks[0]
before=ui.service.operation_history_page().total
for _ in range(3):ui.service.tasks();ui.service.task_context(task.task_id)
assert ui.service.operation_history_page().total==before
ui.service.update_task(task.task_id,name='History Test Board',note='changed note')
page=ui.service.operation_history_page(query='History Test Board')
assert page.rows and 'changed note' in str(page.rows[0]['details'])
def test_history_clear_is_disabled_while_execution_is_active(ui,qtbot):
window=ui.window
window.history_action.trigger()
qtbot.waitUntil(lambda:not window.history_panel._query.busy)
window._begin_run(ui.tasks[0].task_id)
window._update_gates()
try:assert not window.history_panel.clear_button.isEnabled()
finally:window._finish_run();window._update_gates()
+167
View File
@@ -0,0 +1,167 @@
from types import SimpleNamespace
import pytest
from PySide6.QtWidgets import QMessageBox
from dx_productivity.trial_task_center.history_store import HistoryRepository, create_history_schema
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.ui.operation_history import OperationHistoryPage
@pytest.fixture
def history_page(qtbot,tmp_path):
store=TaskStore(tmp_path/'tasks.db')
with store.transaction():create_history_schema(store._connection)
repository=HistoryRepository(store)
calls=[]
class Service:
def operation_history_page(self,**values):
calls.append(values)
return repository.page(**values)
def operation_history_clear_snapshot(self):return repository.clear_snapshot()
def clear_operation_history(self,cutoff_id):return repository.clear(cutoff_id)
service=Service()
page=OperationHistoryPage(service)
qtbot.addWidget(page)
page.resize(980,600);page.show()
def append(**values):
base=dict(task_id='task',task_name='电源 CBB',project_path='F:/Board/board.prj',
operation='quick_run_executed',state='verified',summary='R101 OLD → NEW',
details={'refdes':'R101','old_part_number':'OLD','new_part_number':'NEW'})
base.update(values)
return repository.append(**base)
def settle():
qtbot.waitUntil(lambda:not page._query.busy and not page._clear_query.busy and page._worker is None,timeout=5000)
yield SimpleNamespace(page=page,append=append,repository=repository,service=service,calls=calls,settle=settle)
page.shutdown();settle();page.close();store.close()
def test_history_page_loads_on_navigation_and_shows_recorded_changes(history_page,qtbot):
fixture=history_page
fixture.append()
assert not fixture.calls
fixture.page.set_active(True);fixture.settle()
assert fixture.page.table.rowCount()==1
fixture.page.table.selectRow(0)
assert 'R101' in fixture.page.details.toPlainText()
assert 'OLD' in fixture.page.details.toPlainText()
assert 'NEW' in fixture.page.details.toPlainText()
assert not fixture.page.empty_hint.isVisible()
assert fixture.page.clear_button.isEnabled()
def test_search_and_state_filter_use_current_query(history_page,qtbot):
fixture=history_page
fixture.append()
fixture.append(task_name='失败板',state='failed',summary='U2 缺少目标',details={'refdes':'U2'})
fixture.page.set_active(True);fixture.settle()
fixture.page.search.setText('U2')
qtbot.wait(250);fixture.settle()
assert fixture.page.table.rowCount()==1
assert fixture.page.table.item(0,1).text()=='失败板'
fixture.page.state_filter.setCurrentIndex(fixture.page.state_filter.findData('verified'))
fixture.settle()
assert fixture.page.table.rowCount()==0
assert fixture.page.empty_hint.isVisible()
assert '没有' in fixture.page.empty_hint.text()
@pytest.mark.parametrize('accepted',[True,False])
def test_clear_binds_confirmation_cutoff_and_keeps_later_history(history_page,monkeypatch,accepted):
fixture=history_page
old=fixture.append(source_key='old')
fixture.page.set_active(True);fixture.settle()
seen=[]
def choose(parent,title,text,buttons,default):
seen.append((text,default))
fixture.append(summary='确认期间新增',source_key='new')
return QMessageBox.StandardButton.Yes if accepted else QMessageBox.StandardButton.No
monkeypatch.setattr(QMessageBox,'question',choose)
fixture.page.clear_button.click();fixture.settle()
assert seen and '1' in seen[0][0]
assert seen[0][1]==QMessageBox.StandardButton.No
records=fixture.repository.page().rows
assert len(records)==(1 if accepted else 2)
assert records[0]['summary']=='确认期间新增'
if accepted:assert all(row['event_id']!=old for row in records)
def test_active_execution_disables_clear_without_blocking_search(history_page):
fixture=history_page
fixture.append();fixture.page.set_active(True);fixture.settle()
fixture.page.set_mutations_enabled(False)
assert not fixture.page.clear_button.isEnabled()
assert fixture.page.search.isEnabled()
fixture.page.set_mutations_enabled(True)
assert fixture.page.clear_button.isEnabled()
def test_read_failure_keeps_existing_results_and_refresh_can_retry(history_page,monkeypatch):
fixture=history_page
fixture.append();fixture.page.set_active(True);fixture.settle()
real=fixture.service.operation_history_page
def fail(**_):raise OSError('controlled read failure')
monkeypatch.setattr(fixture.service,'operation_history_page',fail)
fixture.page.refresh_button.click();fixture.settle()
assert fixture.page.table.rowCount()==1
assert '读取失败' in fixture.page.status.text()
monkeypatch.setattr(fixture.service,'operation_history_page',real)
fixture.page.refresh_button.click();fixture.settle()
assert fixture.page.table.rowCount()==1
assert '读取失败' not in fixture.page.status.text()
def test_clear_failure_keeps_history_visible(history_page,monkeypatch):
fixture=history_page
fixture.append();fixture.page.set_active(True);fixture.settle()
monkeypatch.setattr(QMessageBox,'question',lambda *args:QMessageBox.StandardButton.Yes)
def fail(_):raise OSError('controlled commit failure')
monkeypatch.setattr(fixture.service,'clear_operation_history',fail)
fixture.page.clear_button.click();fixture.settle()
assert fixture.page.table.rowCount()==1
assert fixture.repository.page().total==1
assert '清空失败' in fixture.page.status.text()
def test_shutdown_does_not_publish_late_results(history_page):
fixture=history_page
fixture.append();fixture.page.set_active(True)
fixture.page.shutdown();fixture.settle()
assert fixture.page.table.rowCount()==0
def test_older_page_survives_navigation_without_loading_unbounded_rows(history_page):
fixture=history_page
for index in range(103):fixture.append(summary=f'操作 {index}')
fixture.page.set_active(True);fixture.settle()
assert fixture.page.table.rowCount()==100
fixture.page.older_button.click();fixture.settle()
assert fixture.page.table.rowCount()==3
assert fixture.page.table.item(0,4).text()=='操作 2'
fixture.page.set_active(False)
fixture.page.set_active(True);fixture.settle()
assert fixture.page.table.rowCount()==3
assert not fixture.page.older_button.isEnabled()
fixture.page.refresh_button.click();fixture.settle()
assert fixture.page.table.rowCount()==100
def test_execution_start_during_confirmation_cancels_clear(history_page,monkeypatch):
fixture=history_page
fixture.append();fixture.page.set_active(True);fixture.settle()
def choose(*args):
fixture.page.set_mutations_enabled(False)
return QMessageBox.StandardButton.Yes
monkeypatch.setattr(QMessageBox,'question',choose)
fixture.page.clear_button.click();fixture.settle()
assert fixture.repository.page().total==1
assert fixture.page._worker is None
def test_clear_all_stays_available_when_current_filter_matches_nothing(history_page,qtbot):
fixture=history_page
fixture.append();fixture.page.set_active(True);fixture.settle()
fixture.page.search.setText('not-found')
qtbot.wait(250);fixture.settle()
assert fixture.page.table.rowCount()==0
assert fixture.page.clear_button.isEnabled()
+71
View File
@@ -41,6 +41,77 @@ End Sub
'''
def test_resume_semantic_guard_rejects_external_sheet_changes(tmp_path):
output=run_vbs(tmp_path,['QPRequireExpectedState'],'''
On Error Resume Next
QPRequireExpectedState "S" & vbTab & "full_sheet_v1" & vbCrLf & "R1=NEW", _
"S" & vbTab & "full_sheet_v1" & vbCrLf & "R1=OLD"
If Err.Number = 0 Then WScript.Quit 8
Err.Clear
QPRequireExpectedState "same-state", "same-state"
If Err.Number <> 0 Then WScript.Quit 9
WScript.Echo "blocked external change"
''')
assert output=='blocked external change'
def test_baseline_read_failure_is_always_an_uncertain_result(tmp_path):
output=run_vbs(tmp_path,['QPVerifyExpectedBaselines'],'''
On Error Resume Next
QPVerifyExpectedBaselines "board.prj"
If Err.Number <> vbObjectError + 879 Or Err.Source <> "QuickPartReplace.Baseline" Then WScript.Quit 8
WScript.Echo "requires reconciliation"
''',prelude='''
Sub QPCheckExpectedBaselines(ByVal TargetPath)
Err.Raise vbObjectError + 871, "QuickPartReplace.Batch", "recorded sheet was removed"
End Sub
''')
assert output=='requires reconciliation'
def test_resume_semantic_state_ignores_component_enumeration_order(tmp_path):
output=run_vbs(tmp_path,['QPCurrentSemanticState','QPSortSnapshotLines'],'''
Dim first, second
Set QP_App = New FakeApp
QP_App.Reverse = False
first = QPCurrentSemanticState()
QP_App.Reverse = True
second = QPCurrentSemanticState()
If first <> second Or InStr(first, "R1=NEW") = 0 Then WScript.Quit 8
WScript.Echo "stable semantic state"
''',prelude='''
Const VDM_COMP = 128
Const VD_ALL = 0
Dim QP_App
Class FakeApp
Public Reverse
Public Property Get ActiveView()
Set ActiveView = Me
End Property
Public Function Query(kind, scope)
Dim rows
Set rows = CreateObject("Scripting.Dictionary")
If Reverse Then
rows.Add "R2=OLD" & vbCrLf, True
rows.Add "R1=NEW" & vbCrLf, True
Else
rows.Add "R1=NEW" & vbCrLf, True
rows.Add "R2=OLD" & vbCrLf, True
End If
Set Query = rows
End Function
End Class
Sub QPInvalidatePinIndex()
End Sub
Sub QPInvalidateComponentIndex()
End Sub
Function QPUntouchedFullState(ByRef component)
QPUntouchedFullState = component
End Function
''')
assert output=='stable semantic state'
def test_attribute_com_failure_propagates_instead_of_missing(tmp_path):
output = run_vbs(tmp_path, ['QPFindCurrentAttribute'], '''
Dim Comp, Attr
+139
View File
@@ -0,0 +1,139 @@
from copy import deepcopy
from pathlib import Path
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 journal_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('Test Board')
journal=ExecutionJournal(store)
row={'task_id':task.task_id,'job_id':'first-job','project_path':str(tmp_path/'board.prj'),
'schematic_name':'MAIN','sheet_number':'1','old_part':'OLD','new_part':'NEW',
'target_scope':'targets','target_selectors':'uid1\x1fR1\x1f10K','value_mode':'preserve','sync_nc':'1'}
yield store,journal,task,row
store.close()
def test_receipt_survives_rebinding_new_job_and_history_clear(journal_case):
store,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
attempt=journal.claim(task.task_id,row)
journal.finish(attempt,'saved_ok','batch_closed','R1 OLD -> NEW')
history=HistoryRepository(store)
snapshot=history.clear_snapshot();history.clear(snapshot.cutoff_id)
changed=dict(row,job_id='regenerated-job')
saved=journal.bind(task.task_id,[changed],{})
assert saved['regenerated-job'][0]=='saved_ok'
with pytest.raises(TaskCenterError,match='quick_run_complete'):journal.claim(task.task_id,changed)
assert history.page().rows==()
def test_unfinished_attempt_cannot_be_claimed_again(journal_case):
_,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
journal.claim(task.task_id,row)
with pytest.raises(TaskCenterError,match='quick_run_uncertain'):journal.claim(task.task_id,row)
def test_late_attempt_cannot_override_committed_receipt(journal_case):
_,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
attempt=journal.claim(task.task_id,row)
journal.finish(attempt,'saved_ok','batch_closed','verified')
with pytest.raises(TaskCenterError):journal.finish(attempt,'batch_failed','batch_closed','late failure')
assert journal.bind(task.task_id,[row],{})[row['job_id']][0]=='saved_ok'
def test_successful_targets_cannot_be_regrouped_or_revised(journal_case):
_,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
journal.finish(journal.claim(task.task_id,row),'saved_ok','batch_closed','verified')
revised=dict(row,new_part='NEW2',target_selectors='uid1\x1fR1\x1f10K\x1euid2\x1fR2\x1f10K')
journal.authorize_retry(task.task_id)
with pytest.raises(TaskCenterError):journal.bind(task.task_id,[revised],{})
def test_retry_never_unlocks_success_and_only_releases_safe_failure(journal_case):
_,journal,task,row=journal_case
second=dict(row,job_id='second',sheet_number='2',target_selectors='uid2\x1fR2\x1f10K')
journal.bind(task.task_id,[row,second],{})
journal.finish(journal.claim(task.task_id,row),'saved_ok','batch_closed','saved')
journal.finish(journal.claim(task.task_id,second),'batch_failed','batch_closed','preflight failed')
with pytest.raises(TaskCenterError,match='quick_run_retry_required'):journal.claim(task.task_id,second)
journal.authorize_retry(task.task_id)
journal.bind(task.task_id,[row,second],{})
with pytest.raises(TaskCenterError,match='quick_run_complete'):journal.claim(task.task_id,row)
retry=journal.claim(task.task_id,second)
assert retry.generation==2
def test_new_round_is_the_only_way_to_repeat_success(journal_case):
_,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
journal.finish(journal.claim(task.task_id,row),'saved_ok','batch_closed','saved')
journal.start_round(task.task_id,'new-explicit-round')
journal.bind(task.task_id,[row],{})
assert journal.claim(task.task_id,row).generation==1
def test_receipt_and_history_commit_roll_back_together(journal_case,monkeypatch):
store,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
attempt=journal.claim(task.task_id,row)
def fail(*args,**kwargs):raise OSError('history storage failure')
monkeypatch.setattr(HistoryRepository,'append',fail)
with pytest.raises(OSError):journal.finish(attempt,'saved_ok','batch_closed','saved')
assert HistoryRepository(store).page().rows==()
with pytest.raises(TaskCenterError,match='quick_run_uncertain'):journal.claim(task.task_id,row)
@pytest.mark.parametrize('result',['restored_ok','retry_ready'])
def test_explicit_native_recovery_can_resolve_an_uncertain_receipt(journal_case,result):
_,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
journal.finish(journal.claim(task.task_id,row),'batch_saved_unverified','batch_closed','unverified')
journal.reconcile_recovery(task.task_id,row,result,'recovery_saved_verified','verified recovery')
if result=='restored_ok':
with pytest.raises(TaskCenterError,match='quick_run_complete'):journal.claim(task.task_id,row)
else:
assert journal.claim(task.task_id,dict(row,job_id='new-recovery-job')).generation==3
def test_explicit_failed_scope_revision_does_not_prevent_a_later_new_round(journal_case):
_,journal,task,row=journal_case
journal.bind(task.task_id,[row],{})
journal.finish(journal.claim(task.task_id,row),'batch_failed','batch_closed','safe failure')
revised=dict(row,new_part='FIXED')
journal.authorize_retry(task.task_id)
journal.bind(task.task_id,[revised],{})
journal.finish(journal.claim(task.task_id,revised),'saved_ok','batch_closed','saved')
journal.start_round(task.task_id,'confirmed-next-round')
assert not journal.has_plan(task.task_id)
def test_latest_verified_semantic_state_advances_atomically_and_proof_damage_blocks(journal_case,tmp_path):
import hashlib
_,journal,task,row=journal_case
second=dict(row,job_id='second',old_part='OTHER',target_selectors='uid2\x1fR2\x1f1K')
journal.bind(task.task_id,[row,second],{})
evidence=tmp_path/'proof';evidence.write_text('immutable proof')
proof={'files':[{'path':str(evidence),'sha256':hashlib.sha256(evidence.read_bytes()).hexdigest()}],
'baseline':dict(project_path=row['project_path'],schematic_name='MAIN',sheet_number='1',state='first verified state')}
journal.finish(journal.claim(task.task_id,row),'saved_ok','batch_closed','saved',proof=proof)
assert journal.expected_baselines(task.task_id,row['project_path'])[0]['state']=='first verified state'
proof=deepcopy(proof);proof['baseline']['state']='second verified state'
journal.finish(journal.claim(task.task_id,second),'saved_ok','batch_closed','saved',proof=proof)
assert journal.expected_baselines(task.task_id,row['project_path'])[0]['state']=='second verified state'
assert 'proof' not in HistoryRepository(journal.store).page().rows[0]['details']
evidence.unlink()
assert journal.conflicts(task.task_id,[row,second],{r['job_id']:('saved_ok','batch_closed','saved') for r in (row,second)})
with pytest.raises(TaskCenterError):journal.expected_baselines(task.task_id,row['project_path'])
+76
View File
@@ -0,0 +1,76 @@
import json
from pathlib import Path
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.native_helper import read_snapshot, transaction_binding
from dx_productivity.trial_task_center.quick_run import _encode_vbs_field
@pytest.fixture
def proof_case(tmp_path):
project=tmp_path/'board.prj';project.touch()
root=tmp_path/'data'/'quick-run';root.mkdir(parents=True)
row=dict(task_id='task',job_id='job',project_path=str(project),schematic_name='MAIN',sheet_number='1',
old_part='OLD',new_part='NEW',value_mode='preserve',target_scope='all')
snapshot=root/'snapshot-job.tsv'
snapshot.write_text(f'M\t{project}\tOLD\tNEW\tMAIN:1\tpreserve\nC\tuid\tR1\t0\t0\t0\t1\tpins\n',encoding='utf8')
meta,components=read_snapshot(snapshot)
report={'ok':True,'stage':'native_replace_verified','transaction':transaction_binding(
snapshot,meta,components,['lib','NEW','sym','','name','label'],'sym'),
'batch_attempt':dict(task_id='task',job_id='job',project_path=str(project),
session_id='a'*32,attempt_id='b'*32,generation=1)}
Path(str(snapshot)+'.native.json').write_text(json.dumps(report),encoding='utf8')
(root/'post-state-job.tsv').write_text('job_id\tproject_path\tschematic_name\tsheet_number\tsemantic_state\n'+
'\t'.join(_encode_vbs_field(row[key]) for key in ('job_id','project_path','schematic_name','sheet_number'))+
'\t'+_encode_vbs_field('S\tfull_sheet_v1\r\nR1=NEW\r\n')+'\n',encoding='utf8')
return tmp_path/'data',root,row
def test_receipt_proof_binds_native_snapshot_attempt_and_semantic_state(proof_case):
from dx_productivity.trial_task_center.execution_proof import capture_result, proof_intact
data,root,row=proof_case
proof=capture_result(data,root,row,('saved_ok','batch_closed','verified'),strict=True)
assert proof['baseline']['state']=='S\tfull_sheet_v1\r\nR1=NEW\r\n'
assert proof['native_attempt']['attempt_id']=='b'*32
assert proof_intact(proof)
# Active handoff can be archived without breaking committed proof identity.
root.rename(root.with_name('archived'))
assert proof_intact(proof)
Path(proof['files'][0]['path']).write_text('changed',encoding='utf8')
assert not proof_intact(proof)
@pytest.mark.parametrize('damage',['missing_report','foreign_attempt','snapshot_changed','missing_baseline'])
def test_unbound_result_cannot_be_imported_as_a_completion_receipt(proof_case,damage):
from dx_productivity.trial_task_center.execution_proof import capture_result
data,root,row=proof_case
report=root/'snapshot-job.tsv.native.json'
if damage=='missing_report':report.unlink()
elif damage=='foreign_attempt':
record=json.loads(report.read_text());record['batch_attempt']['job_id']='other';report.write_text(json.dumps(record))
elif damage=='snapshot_changed':
with (root/'snapshot-job.tsv').open('a') as stream:stream.write('changed\n')
else:(root/'post-state-job.tsv').unlink()
with pytest.raises(TaskCenterError,match='quick_run_uncertain'):
capture_result(data,root,row,('saved_ok','batch_closed','verified'),strict=True)
def test_proof_changed_during_binding_is_never_committed(proof_case,monkeypatch):
from dx_productivity.trial_task_center.execution_proof import capture_result
from dx_productivity.trial_task_center import native_helper
data,root,row=proof_case
original=native_helper.require_resumable_transaction
def changed(snapshot,*args):
result=original(snapshot,*args)
with Path(snapshot).open('a') as stream:stream.write('changed after validation\n')
return result
monkeypatch.setattr(native_helper,'require_resumable_transaction',changed)
with pytest.raises(TaskCenterError):capture_result(data,root,row,('saved_ok','batch_closed','verified'),strict=True)
def test_success_without_save_close_code_is_not_a_verified_native_receipt(proof_case):
from dx_productivity.trial_task_center.execution_proof import capture_result
data,root,row=proof_case
with pytest.raises(TaskCenterError):capture_result(data,root,row,('saved_ok','','unverified close'),strict=True)
@@ -0,0 +1,31 @@
from threading import Event, Thread
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
def test_history_facade_initialization_does_not_invert_store_and_cache_locks(tmp_path,monkeypatch):
from dx_productivity.trial_task_center import history_recording
project=tmp_path/'projects'/'Board'/'board.prj'
project.parent.mkdir(parents=True);project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
store=TaskStore(tmp_path/'tasks.db')
try:
service=TaskCenterService(store,configure_logging(tmp_path/'data'))
task=service.create_project_tasks(tmp_path/'projects')[0]
entered=Event();errors=[]
original=history_recording.initialize_history_import
def initialize(store):entered.set();original(store)
monkeypatch.setattr(history_recording,'initialize_history_import',initialize)
def read():
try:service._facade_for_task_record(task)
except BaseException as error:errors.append(error)
with store._lock:
thread=Thread(target=read,daemon=True);thread.start()
assert entered.wait(2)
acquired=service._facade_lock.acquire(timeout=.2)
if acquired:service._facade_lock.release()
thread.join(3)
assert acquired,'A DB owner reading the facade would deadlock with facade initialization waiting on DB'
assert not thread.is_alive() and not errors
finally:store.close()
+181
View File
@@ -0,0 +1,181 @@
from datetime import datetime, timedelta, timezone
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.history_store import HistoryRepository, create_history_schema
from dx_productivity.trial_task_center.history_recording import (
ensure_legacy_history, initialize_history_import, record_operation)
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
@pytest.fixture
def recording(tmp_path):
store=TaskStore(tmp_path/'tasks.db')
with store.transaction():create_history_schema(store._connection)
service=SimpleNamespace(_store=store,_logging=SimpleNamespace(root=tmp_path/'data'))
yield service,HistoryRepository(store)
store.close()
def test_task_creation_and_metadata_changes_are_recorded_with_actual_differences(recording):
service,history=recording
task=record_operation(service,'create_task',None,lambda:service._store.create_task('原名称','原备注'))
record_operation(service,'update_task',task.task_id,
lambda:service._store.update_task(task.task_id,name='新名称',note='新备注'))
rows=history.page().rows
assert len(rows)==2 and rows[0]['task_name']=='新名称'
change=next(change for change in rows[0]['details']['changes'] if change['table']=='tasks')
assert change['before']=={'name':'原名称','note':'原备注'}
assert change['after']=={'name':'新名称','note':'新备注'}
assert '原名称' in rows[0]['summary'] and '新名称' in rows[0]['summary']
def test_rule_mutation_without_task_id_records_only_final_values(recording):
service,history=recording
task=service._store.create_task('规则任务')
rule=service._store.add_rule(task.task_id,'OLD','NEW')
def update():
service._store.update_rule(rule.rule_id,old_part_number='OLD',new_part_number='TEMP',enabled=False)
return service._store.update_rule(rule.rule_id,old_part_number='OLD',new_part_number='FINAL',enabled=True)
record_operation(service,'update_rule',None,update)
row=history.page().rows[0]
assert row['task_id']==task.task_id
changes=[change for change in row['details']['changes'] if change['table']=='rules']
assert len(changes)==1
assert changes[0]['before']=={'new_part_number':'NEW'}
assert changes[0]['after']=={'new_part_number':'FINAL'}
assert history.page(query='TEMP').total==0
def test_no_change_and_read_only_actions_do_not_manufacture_history(recording):
service,history=recording
task=service._store.create_task('相同值')
record_operation(service,'update_task',task.task_id,
lambda:service._store.update_task(task.task_id,name=task.name,note=task.note))
assert record_operation(service,'list_tasks',None,lambda:service._store.list_tasks())
assert history.page().total==0
def test_history_failure_rolls_back_mutation_and_cleans_temporary_capture(recording,monkeypatch):
service,history=recording
task=service._store.create_task('原任务')
def fail(*args,**kwargs):raise OSError('history commit failed')
with monkeypatch.context() as patch:
patch.setattr(HistoryRepository,'append',fail)
with pytest.raises(OSError):
record_operation(service,'update_task',task.task_id,
lambda:service._store.update_task(task.task_id,name='不应提交',note=''))
assert service._store.get_task(task.task_id).name=='原任务'
record_operation(service,'update_task',task.task_id,
lambda:service._store.update_task(task.task_id,name='可以提交',note=''))
assert history.page().total==1
def test_deletion_preserves_task_name_and_real_removed_rows(recording):
service,history=recording
task=service._store.create_task('待删除任务')
service._store.add_rule(task.task_id,'OLD','NEW')
service._store.soft_delete_task(task.task_id)
record_operation(service,'purge_task',task.task_id,lambda:service._store.purge_task(task.task_id))
row=history.page().rows[0]
assert row['task_name']=='待删除任务'
assert any(change['table']=='rules' and change['after'] is None for change in row['details']['changes'])
def test_large_target_plan_records_exact_changed_rows_in_bounded_chunks(recording,tmp_path):
service,history=recording
task=service._store.create_task('大量位号')
project=tmp_path/'board.prj';project.write_text('sample')
rows=tuple(TargetPlanRow(ComponentTarget(project,'MAIN','1',f'uid-{i}',f'R{i}','OLD','10K'),True,'NEW')
for i in range(230))
# The capture concerns the real target table writes; store's public guards
# are covered separately. Use its persisted row shape in this fixture.
def save():
for row in rows:
t=row.target
service._store._connection.execute('''INSERT INTO target_plan
(task_id,project_path,schematic_name,sheet_number,uid,refdes,old_part_number,old_value,enabled,new_part_number)
VALUES (?,?,?,?,?,?,?,?,?,?)''',
(task.task_id,str(project),t.schematic_name,t.sheet_number,t.uid,t.refdes,t.old_part_number,t.old_value,1,'NEW'))
return rows
record_operation(service,'save_plan_drafts',None,save)
page=history.page()
assert len(page.rows)==3
changes=[change for event in page.rows for change in event['details']['changes'] if change['table']=='target_plan']
assert len(changes)==230
assert all(len(event['details']['changes'])<=100 for event in page.rows)
assert history.page(query='R229').total==1
def legacy(service,task,*,name='events.jsonl',timestamp=None,state='saved_ok',operation='quick_run_executed',message='R1 OLD → NEW',details=None):
path=service._logging.root/'tasks'/task.task_id/name
path.parent.mkdir(parents=True,exist_ok=True)
payload={'task_id':task.task_id,'sequence':1,'timestamp_utc':timestamp or
(datetime.now(timezone.utc)-timedelta(days=1)).isoformat(),
'operation':operation,'message':message,'details':dict(state=state,**(details or {}))}
path.write_text(json.dumps(payload,ensure_ascii=False)+'\n',encoding='utf8')
return path
@pytest.mark.parametrize(('state','expected'),[
('saved_ok','verified'),('no_match','no_match'),('batch_failed','failed'),
('hard_failure','failed'),('batch_saved_unverified','uncertain'),('restored_ok','restored'),
('awaiting_native_replace','uncertain')])
def test_legacy_native_states_are_imported_without_inventing_success(recording,state,expected):
service,history=recording
task=service._store.create_task('旧任务')
source=legacy(service,task,state=state)
original=source.read_bytes()
initialize_history_import(service._store)
ensure_legacy_history(service)
rows=history.page().rows
assert len(rows)==1 and rows[0]['state']==expected
assert rows[0]['timestamp_utc']<datetime.now(timezone.utc).isoformat()
assert source.read_bytes()==original
def test_import_cutoff_and_completion_survive_clear_and_repeated_initialization(recording):
service,history=recording
task=service._store.create_task('旧任务')
legacy(service,task,name='events.jsonl.1')
initialize_history_import(service._store)
legacy(service,task,timestamp=(datetime.now(timezone.utc)+timedelta(seconds=2)).isoformat(),message='新回执对应事件')
initialize_history_import(service._store)
ensure_legacy_history(service)
assert history.page().total==1
history.clear(history.clear_snapshot().cutoff_id)
initialize_history_import(service._store)
ensure_legacy_history(service)
assert history.page().total==0
def test_cancelled_or_failed_import_does_not_mark_migration_complete(recording):
service,history=recording
task=service._store.create_task('待迁移')
source=legacy(service,task)
initialize_history_import(service._store)
class Cancel:
def checkpoint(self):raise RuntimeError('cancelled')
with pytest.raises(RuntimeError,match='cancelled'):ensure_legacy_history(service,Cancel())
source.write_text('{"truncated":\n',encoding='utf8')
with pytest.raises(TaskCenterError):ensure_legacy_history(service)
legacy(service,task)
ensure_legacy_history(service)
assert history.page().total==1
def test_import_excludes_new_or_unrelated_diagnostics_and_credentials(recording):
service,history=recording
task=service._store.create_task('旧任务')
legacy(service,task,details={'api_key':'must-not-import','refdes':'R10'})
legacy(service,task,name='events.jsonl.1',operation='dx_dsh_response',message='must-not-import')
initialize_history_import(service._store)
ensure_legacy_history(service)
assert history.page().total==1
assert history.page(query='must-not-import').total==0
assert history.page(query='R10').total==1
+137
View File
@@ -0,0 +1,137 @@
import pytest
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.history_store import HistoryRepository, create_history_schema
@pytest.fixture
def history(tmp_path):
store=TaskStore(tmp_path/'tasks.db')
with store.transaction():
create_history_schema(store._connection)
yield HistoryRepository(store),store
store.close()
def event(repository, **changes):
values=dict(task_id='task-1',task_name='电源 CBB',project_path='F:/Board/board.prj',
operation='quick_run_executed',state='verified',summary='R101 OLD-1 → NEW-1',
details={'refdes':'R101','old_part_number':'OLD-1','new_part_number':'NEW-1'})
values.update(changes)
return repository.append(**values)
@pytest.mark.parametrize('query',['电源','cbb','f:/board','R101','old-1','NEW-1'])
def test_history_searches_unicode_identity_and_recorded_changes(history,query):
repository,_=history
identifier=event(repository)
event(repository,task_name='无关任务',project_path='F:/Other.prj',summary='未命中',details={},state='no_match')
page=repository.page(query=query)
assert page.total==1
assert [row['event_id'] for row in page.rows]==[identifier]
assert page.rows[0]['details']['refdes']=='R101'
def test_search_treats_wildcards_as_literal_text(history):
repository,_=history
literal=event(repository,summary='100%_done')
event(repository,summary='100xxxAdone',details={})
assert [row['event_id'] for row in repository.page(query='100%_').rows]==[literal]
def test_keyset_paging_and_state_filter_have_no_duplicates(history):
repository,_=history
identifiers=[event(repository,state='failed' if index%2 else 'verified') for index in range(7)]
first=repository.page(state='verified',limit=2)
assert first.total==4
assert [row['event_id'] for row in first.rows]==[identifiers[6],identifiers[4]]
second=repository.page(state='verified',limit=2,before_id=first.next_cursor)
assert [row['event_id'] for row in second.rows]==[identifiers[2],identifiers[0]]
assert second.next_cursor is None
def test_clear_uses_confirmation_cutoff_and_preserves_new_events_and_other_tables(history):
repository,store=history
with store.transaction():
store._connection.execute('CREATE TABLE completion_probe (value TEXT)')
store._connection.execute("INSERT INTO completion_probe VALUES ('complete')")
old=event(repository,source_key='native:event:1')
snapshot=repository.clear_snapshot()
assert snapshot.cutoff_id==old and snapshot.count==1
newer=event(repository,summary='确认期间完成的新操作',source_key='native:event:2')
assert repository.clear(snapshot.cutoff_id)==1
assert [row['event_id'] for row in repository.page().rows]==[newer]
assert store._connection.execute('SELECT value FROM completion_probe').fetchone()[0]=='complete'
assert event(repository,source_key='native:event:1')==old
assert [row['event_id'] for row in repository.page().rows]==[newer]
def test_clear_survives_reopen_without_reusing_ids_or_reimporting(history):
repository,store=history
old=event(repository,source_key='legacy:task-1:1')
repository.clear(repository.clear_snapshot().cutoff_id)
second=TaskStore(store.path)
try:
with second.transaction():create_history_schema(second._connection)
other=HistoryRepository(second)
assert other.page().rows==()
assert event(other,source_key='legacy:task-1:1')==old
assert other.page().rows==()
assert event(other,source_key='new')>old
finally:second.close()
def test_history_and_receipt_transaction_roll_back_together(history):
repository,store=history
with pytest.raises(RuntimeError):
with store.transaction():
event(repository,source_key='rolled-back')
raise RuntimeError('receipt commit failed')
assert repository.page().rows==()
assert event(repository,source_key='rolled-back')>0
def test_empty_state_and_invalid_paging_are_explicit(history):
repository,_=history
assert repository.clear_snapshot().count==0
assert repository.page().total==0 and repository.page().next_cursor is None
for values in ({'limit':0},{'limit':501},{'before_id':-1}):
with pytest.raises(ValueError):repository.page(**values)
def test_legacy_import_preserves_event_time_in_normalized_utc(history):
repository,_=history
identifier=event(repository,timestamp_utc='2026-11-01T08:02:03+08:00',source_key='old-timestamp')
row=repository.page().rows[0]
assert row['event_id']==identifier
assert row['timestamp_utc']=='2026-11-01T00:02:03.000000Z'
@pytest.mark.parametrize('value',['2026-11-01T08:00:00','not-a-time',14])
def test_import_rejects_invalid_or_ambiguous_event_time(history,value):
repository,_=history
with pytest.raises(ValueError):event(repository,timestamp_utc=value)
assert repository.page().total==0
def test_late_legacy_import_keeps_chronological_keyset_order(history):
repository,_=history
newest=event(repository,timestamp_utc='2026-11-03T12:00:00Z',summary='新操作')
oldest=event(repository,timestamp_utc='2026-10-30T12:00:00Z',summary='旧导入')
middle=event(repository,timestamp_utc='2026-11-01T12:00:00Z',summary='较旧操作')
tied=event(repository,timestamp_utc='2026-11-01T12:00:00Z',summary='同时间操作')
first=repository.page(limit=2)
assert [row['event_id'] for row in first.rows]==[newest,tied]
second=repository.page(limit=2,before_id=first.next_cursor)
assert [row['event_id'] for row in second.rows]==[middle,oldest]
assert second.next_cursor is None
def test_cleared_page_cursor_requires_explicit_refresh(history):
repository,_=history
for index in range(3):event(repository)
first=repository.page(limit=1)
repository.clear(repository.clear_snapshot().cutoff_id)
event(repository)
with pytest.raises(ValueError,match='cursor'):
repository.page(before_id=first.next_cursor)
+96
View File
@@ -0,0 +1,96 @@
from pathlib import Path
import subprocess
from threading import Event
import pytest
from dx_productivity.trial_task_center.errors import TaskCenterError
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.task_queue import execute_task_queue
@pytest.fixture
def resume_case(tmp_path):
project=tmp_path/'projects'/'Board'/'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
calls=[];stop=Event()
def worker(command,timeout):
job=command[-1];calls.append(job)
with (Path(command[3])/'status.tsv').open('a',encoding='utf8') as stream:
stream.write(f'{job}\tawaiting_native_replace\t\tSimulated capture\n')
stream.write(f'{job}\tsaved_ok\tbatch_closed\tSimulated verified result\n')
if len(calls)==2:stop.set()
return subprocess.CompletedProcess(command,0,'','')
stores=[]
def reopen():
store=TaskStore(tmp_path/'tasks.db');stores.append(store)
return TaskCenterService(store,configure_logging(tmp_path/'data'),
quick_run_preparer=QuickRunPreparer(tmp_path/'data',process_runner=worker,
cscript_resolver=lambda:Path('simulated-cscript'),
sheet_discoverer=lambda _: (('MAIN','1'),('MAIN','2'))))
service=reopen()
task=service.create_project_tasks(tmp_path/'projects')[0]
service.add_rule(task.task_id,'OLD1','NEW1');service.add_rule(task.task_id,'OLD2','NEW2')
result=execute_task_queue(service,(task.task_id,),stop_event=stop)
assert result.paused and len(calls)==2
root=service.for_project_task(task.task_id)._quick_run_preparer.data_root/'quick-run'
yield service,task,result,root,calls,reopen
for store in stores:store.close()
@pytest.mark.parametrize('damage',['missing_status','missing_command','empty_status','truncated_status','truncated_command'])
def test_restart_with_incomplete_handoff_never_replays_worker(resume_case,damage):
service,task,result,root,calls,reopen=resume_case
path=root/('command.tsv' if 'command' in damage else 'status.tsv')
if damage.startswith('missing'):path.unlink()
elif damage=='empty_status':path.write_text('job_id\tstate\tcode\tmessage\n',encoding='utf8')
else:path.write_text(path.read_text(encoding='utf8')[:-12],encoding='utf8')
restarted=reopen()
context=restarted.task_context(task.task_id)
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 len(calls)==2
def test_ordinary_restart_only_dispatches_remaining_items(resume_case):
service,task,result,root,calls,reopen=resume_case
restarted=reopen()
context=restarted.task_context(task.task_id)
assert not context.interrupted and context.progress.completed_items==2
result=execute_task_queue(restarted,(task.task_id,),stop_event=Event())
assert not result.paused and result.entries[0].state=='completed'
assert len(calls)==4 and len(set(calls))==4
def test_direct_prepare_cannot_overwrite_incomplete_handoff(resume_case):
service,task,result,root,calls,reopen=resume_case
(root/'status.tsv').unlink()
command=(root/'command.tsv').read_bytes()
with pytest.raises(TaskCenterError):service.prepare_quick_run(task.task_id)
assert (root/'command.tsv').read_bytes()==command
assert len(calls)==2
def test_receipts_block_rollback_to_an_empty_status_even_without_sidecars(resume_case):
service,task,result,root,calls,reopen=resume_case
(root/'status.tsv').write_text('job_id\tstate\tcode\tmessage\n',encoding='utf8')
(root/'current-command.tsv').unlink(missing_ok=True)
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
def test_missing_entire_handoff_cannot_erase_database_receipts(resume_case):
service,task,result,root,calls,reopen=resume_case
root.rename(root.with_name('preserved-probe-handoff'))
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
@@ -0,0 +1,126 @@
"""Dispatch-count regressions for interruptions in retry/receipt publication."""
import csv
from dataclasses import replace
from pathlib import Path
import subprocess
from threading import Event
import pytest
from dx_productivity.trial_task_center.execution_journal import ExecutionJournal
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.quick_run_protocol import ProjectDiscovery
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
from dx_productivity.trial_task_center.task_queue import execute_task_queue
@pytest.fixture
def partial_case(tmp_path, monkeypatch):
project = tmp_path/'projects'/'Board'/'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'uid{i}', f'R{i}', f'OLD{i}', '')
for i in (1, 2))
calls = []
def discover(self, path, parts, **kwargs):
rows = tuple(replace(row, old_part_number='NEW1') if row.uid=='uid1' and calls else row
for row in targets)
return ProjectDiscovery((('MAIN','1'),), {('MAIN','1'):frozenset(r.old_part_number.casefold() for r in rows)}, rows)
monkeypatch.setattr(QuickRunPreparer, 'discover_project', discover)
def worker(command, timeout):
root = Path(command[3])
with (root/'current-command.tsv').open(encoding='utf-8-sig') as stream:
row = next(csv.DictReader(stream, delimiter='\t'))
calls.append(row)
state = 'batch_failed' if len(calls)==2 else 'saved_ok'
with (root/'status.tsv').open('a', encoding='utf8') as stream:
if state=='saved_ok':stream.write(f'{command[-1]}\tawaiting_native_replace\t\tcaptured\n')
stream.write(f'{command[-1]}\t{state}\tbatch_closed\tControlled result\n')
return subprocess.CompletedProcess(command, 0, '', '')
store = TaskStore(tmp_path/'tasks.db')
service = TaskCenterService(store, configure_logging(tmp_path/'data'), quick_run_preparer=QuickRunPreparer(
tmp_path/'data', process_runner=worker, cscript_resolver=lambda:Path('simulated')))
task = service.create_project_tasks(tmp_path/'projects')[0]
store.record_target_inventory(task.task_id, targets)
service.replace_target_plan(task.task_id, tuple(TargetPlanRow(row, True, f'NEW{i}')
for i,row in enumerate(targets,1)))
outcome = execute_task_queue(service, (task.task_id,), stop_event=Event())
assert outcome.entries[0].state=='failed' and len(calls)==2
yield service, task, calls
store.close()
def test_exact_target_retry_preserves_completed_targets(partial_case):
service, task, calls = partial_case
service.prepare_failed_quick_run(task.task_id)
result = execute_task_queue(service, (task.task_id,), stop_event=Event())
assert not result.paused and result.entries[0].state=='completed'
assert [row['old_part'] for row in calls]==['OLD1','OLD2','OLD2']
def test_retry_backup_failure_can_resume_preparation_without_dispatch(partial_case, monkeypatch):
service, task, calls = partial_case
from dx_productivity.trial_task_center import batch_backup
original = batch_backup.inherit_backup_for_retry
def fail(*args): raise OSError('controlled backup publication failure')
monkeypatch.setattr(batch_backup, 'inherit_backup_for_retry', fail)
with pytest.raises(Exception): service.prepare_failed_quick_run(task.task_id)
assert len(calls)==2
assert not service.task_context(task.task_id).interrupted
monkeypatch.setattr(batch_backup, 'inherit_backup_for_retry', original)
service.prepare_failed_quick_run(task.task_id)
result = execute_task_queue(service, (task.task_id,), stop_event=Event())
assert result.entries[0].state=='completed' and len(calls)==3
def test_final_success_before_receipt_commit_reconciles_without_dispatch(tmp_path, monkeypatch):
project=tmp_path/'projects'/'Board'/'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
calls=[]
def worker(command,timeout):
calls.append(command[-1])
with (Path(command[3])/'status.tsv').open('a',encoding='utf8') as stream:
stream.write(f'{command[-1]}\tawaiting_native_replace\t\tcaptured\n')
stream.write(f'{command[-1]}\tsaved_ok\tbatch_closed\tControlled result\n')
return subprocess.CompletedProcess(command,0,'','')
store=TaskStore(tmp_path/'tasks.db')
try:
service=TaskCenterService(store,configure_logging(tmp_path/'data'),quick_run_preparer=QuickRunPreparer(
tmp_path/'data',process_runner=worker,cscript_resolver=lambda:Path('simulated'),
sheet_discoverer=lambda _:(('MAIN','1'),)))
task=service.create_project_tasks(tmp_path/'projects')[0]
service.add_rule(task.task_id,'OLD','NEW')
original=ExecutionJournal.finish
def crash(*args,**kwargs):raise KeyboardInterrupt('controlled process exit')
monkeypatch.setattr(ExecutionJournal,'finish',crash)
with pytest.raises(KeyboardInterrupt):execute_task_queue(service,(task.task_id,),stop_event=Event())
monkeypatch.setattr(ExecutionJournal,'finish',original)
result=execute_task_queue(service,(task.task_id,),stop_event=Event())
assert result.entries[0].state=='completed' and len(calls)==1
receipt=store._connection.execute('SELECT state,receipt_json FROM execution_operations').fetchone()
assert receipt['state']=='verified' and receipt['receipt_json']
service.start_new_round(task.task_id)
finally:store.close()
def test_retry_publication_crash_restores_original_handoff_on_restart(partial_case):
import json
service,task,calls=partial_case
preparer=service.for_project_task(task.task_id)._quick_run_preparer
root=preparer.data_root/'quick-run'
original=(root/'command.tsv').read_bytes()
token='c'*32
archive=preparer.data_root/'quick-run-history'/('obsolete-retry-'+token)
archive.parent.mkdir(exist_ok=True)
(preparer.data_root/'retry-preparation.json').write_text(json.dumps({'task_id':task.task_id,'transition_id':token}))
root.rename(archive)
root.mkdir()
(root/'command.tsv').write_text('partially published retry')
TaskCenterService(service._store,service._logging,quick_run_preparer=service._quick_run_preparer)
assert (root/'command.tsv').read_bytes()==original
assert not (preparer.data_root/'retry-preparation.json').exists()
assert len(calls)==2
+54
View File
@@ -0,0 +1,54 @@
import csv
from pathlib import Path
import subprocess
from threading import Event
import pytest
from dx_productivity.trial_task_center.logging_setup import configure_logging
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer
from dx_productivity.trial_task_center.service import TaskCenterService
from dx_productivity.trial_task_center.store import TaskStore
from dx_productivity.trial_task_center.task_queue import execute_task_queue
@pytest.mark.parametrize('failure',['batch_failed','attach_failed'])
def test_safe_cbb_failure_holds_remaining_items_and_continues_next_engineering_task(tmp_path,failure):
for name in ('A','B'):
project=tmp_path/'projects'/name/'board.prj'
project.parent.mkdir(parents=True)
project.write_text('KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "database"\n')
calls=[]
def worker(command,timeout):
directory=Path(command[3])
with (directory/'current-command.tsv').open(encoding='utf-8-sig') as stream:
row=next(csv.DictReader(stream,delimiter='\t'))
calls.append(row)
if len(calls)==2 and failure=='attach_failed':
return subprocess.CompletedProcess(command,2,'','Controlled pre-mutation attachment failure')
state='batch_failed' if len(calls)==2 else 'saved_ok'
with (directory/'status.tsv').open('a',encoding='utf8') as stream:
if state=='saved_ok':stream.write(f'{command[-1]}\tawaiting_native_replace\t\tcaptured\n')
stream.write(f'{command[-1]}\t{state}\tbatch_closed\tControlled result, no CAD\n')
return subprocess.CompletedProcess(command,0,'','')
store=TaskStore(tmp_path/'tasks.db')
try:
service=TaskCenterService(store,configure_logging(tmp_path/'data'),quick_run_preparer=QuickRunPreparer(
tmp_path/'data',process_runner=worker,cscript_resolver=lambda:Path('simulated-cscript'),
sheet_discoverer=lambda _:(('MAIN','1'),('MAIN','2'))))
tasks=service.create_project_tasks(tmp_path/'projects')
service.add_rule(tasks[0].task_id,'OLD1','NEW1');service.add_rule(tasks[0].task_id,'OLD2','NEW2')
ids=tuple(task.task_id for task in tasks)
result=execute_task_queue(service,ids,stop_event=Event())
assert not result.paused
assert [entry.state for entry in result.entries]==['failed','completed']
assert [row['task_id'] for row in calls]==[ids[0]]*2+[ids[1]]*4
assert service.task_context(ids[0]).phase=='retry'
execute_task_queue(service,ids,stop_event=Event())
assert len(calls)==6,'ordinary continue must not repeat a safe failure or prior success'
service.prepare_failed_quick_run(ids[0])
retried=execute_task_queue(service,(ids[0],),stop_event=Event())
assert not retried.paused, retried
assert len(calls)==9,'explicit retry runs the failed item and held items, preserving the successful item'
assert sum(row['task_id']==ids[0] and row['sheet_number']=='1' and row['old_part']=='OLD1' for row in calls)==1
finally:
store.close()
+1 -1
View File
@@ -42,7 +42,7 @@ def test_recycle_bin_has_independent_toggle(qtbot):
view = TaskList(lambda _: None)
qtbot.addWidget(view)
assert view.recycle_button.isCheckable()
assert view.filter.isHidden()
assert not view.filter.isHidden() # Status categories are now a visible, independent filter.
def test_creating_tasks_from_recycle_bin_returns_to_active_list(window, qtbot):