fix: preserve batch receipts and resource recovery after review
Core regression / Python core, intervention UI and release configuration (push) Successful in 18m39s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 11m51s
Core regression / JavaScript syntax (pull_request) Successful in 7s
Core regression / Python core, intervention UI and release configuration (push) Successful in 18m39s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 11m51s
Core regression / JavaScript syntax (pull_request) Successful in 7s
This commit is contained in:
1 parent
e63a82b695
commit
4a438e027b
25 files changed
+748
-138
No files matched your search
@@ -57,6 +57,36 @@ def test_cache_only_batch_does_not_create_desktop_or_cad(tmp_path):
|
||||
assert not Desktop.created
|
||||
|
||||
|
||||
@pytest.mark.parametrize('failure', ['factory', 'first_write'])
|
||||
def test_desktop_startup_before_acquisition_does_not_block_later_batches(tmp_path, monkeypatch, failure):
|
||||
from dx_productivity.trial_task_center import batch_runtime
|
||||
|
||||
def fail_startup(*args, **options):
|
||||
raise OSError('desktop startup unavailable')
|
||||
|
||||
runtime = batch_runtime.BatchCadRuntime(
|
||||
tmp_path, 'execution', desktop_factory=fail_startup if failure == 'factory' else Desktop)
|
||||
if failure == 'first_write':
|
||||
write_record = batch_runtime.write_record
|
||||
|
||||
def fail_first_write(path, record):
|
||||
if record['state'] == 'starting':
|
||||
fail_startup()
|
||||
write_record(path, record)
|
||||
|
||||
monkeypatch.setattr(batch_runtime, 'write_record', fail_first_write)
|
||||
|
||||
with pytest.raises(OSError, match='desktop startup unavailable'):
|
||||
with runtime:
|
||||
with runtime.native_scope(tmp_path / 'startup'):
|
||||
pytest.fail('startup must fail before the desktop is acquired')
|
||||
|
||||
assert not Desktop.created
|
||||
assert batch_runtime.pending_resources(tmp_path) == ()
|
||||
with batch_runtime.BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop):
|
||||
pass
|
||||
|
||||
|
||||
def test_batch_forwards_business_failure_to_owned_cad_close(tmp_path):
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
runtime = BatchCadRuntime(tmp_path, 'execution', desktop_factory=Desktop)
|
||||
@@ -182,6 +212,28 @@ def command_for(tmp_path, name='one'):
|
||||
return ('cscript', '//nologo', 'worker.vbs', str(root), 'python', 'job'), project
|
||||
|
||||
|
||||
def test_unlaunched_worker_retry_leaves_no_ownership_record(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import batch_runtime, worker_monitor
|
||||
|
||||
def fail_startup(*args, **options):
|
||||
raise OSError('desktop factory unavailable')
|
||||
|
||||
def unexpected_worker(*args, **options):
|
||||
pytest.fail('no worker may launch after the desktop factory fails')
|
||||
|
||||
monkeypatch.setattr(worker_monitor, 'run_monitored_process', unexpected_worker)
|
||||
command, _ = command_for(tmp_path)
|
||||
runtime = batch_runtime.BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=fail_startup)
|
||||
with pytest.raises(OSError, match='desktop factory unavailable'):
|
||||
with runtime:
|
||||
runtime.run_worker(command, 5)
|
||||
|
||||
assert runtime.record['retries']
|
||||
assert batch_runtime.pending_resources(runtime.root) == ()
|
||||
with batch_runtime.BatchCadRuntime(runtime.root, 'execution', desktop_factory=Desktop):
|
||||
pass
|
||||
|
||||
|
||||
def worker_runtime(tmp_path, monkeypatch, monitor):
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
from dx_productivity.trial_task_center import worker_monitor
|
||||
|
||||
@@ -21,3 +21,24 @@ def test_slot_can_be_returned_by_the_worker_monitor_thread():
|
||||
assert not thread.is_alive() and not errors
|
||||
again = backend.lock(name)
|
||||
backend.unlock(again)
|
||||
|
||||
|
||||
@pytest.mark.skipif(os.name != 'nt', reason='Windows mutex thread ownership')
|
||||
def test_release_error_closes_mutex_handle_and_allows_its_next_owner(monkeypatch):
|
||||
import win32event
|
||||
from dx_productivity.trial_task_center.desktop_slot import _Windows
|
||||
|
||||
def fail_release(handle):
|
||||
raise OSError('ReleaseMutex failed')
|
||||
|
||||
backend = _Windows()
|
||||
name = 'Local\\DxPartReplace-Release-Error-Test-' + uuid4().hex
|
||||
mutex = backend.lock(name)
|
||||
with monkeypatch.context() as patch:
|
||||
patch.setattr(win32event, 'ReleaseMutex', fail_release)
|
||||
with pytest.raises(OSError, match='ReleaseMutex failed'):
|
||||
backend.unlock(mutex)
|
||||
|
||||
assert not int(mutex[0])
|
||||
next_mutex = backend.lock(name)
|
||||
backend.unlock(next_mutex)
|
||||
@@ -105,7 +105,8 @@ def test_public_recovery_tries_verified_project_commit_before_cad(failed_native,
|
||||
|
||||
@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):
|
||||
@pytest.mark.parametrize('previous_round', [False, True])
|
||||
def test_dependency_recovery_needs_confirmation_clear_source_and_never_opens_cad(tmp_path, monkeypatch, publication_failure, queue_directory, previous_round):
|
||||
import json
|
||||
from dx_productivity.trial_task_center.service import TaskCenterService
|
||||
from dx_productivity.trial_task_center.store import TaskStore
|
||||
@@ -130,6 +131,13 @@ def test_dependency_recovery_needs_confirmation_clear_source_and_never_opens_cad
|
||||
store.set_task_status(task_id, TaskStatus.BLOCKED, summary='dependency')
|
||||
dependency, follower = tasks
|
||||
child = service.for_project_task(follower[0])
|
||||
if previous_round:
|
||||
with store.transaction():
|
||||
store._connection.execute('INSERT INTO execution_rounds(task_id, round_id) VALUES (?, ?)',
|
||||
(follower[0], 'current-round'))
|
||||
store._connection.execute('''INSERT INTO execution_operations
|
||||
(task_id, round_id, operation_key, command_json, state, attempt_id, generation)
|
||||
VALUES (?, 'old-round', 'old-operation', '{}', 'verified', 'old-attempt', 1)''', (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],
|
||||
|
||||
@@ -68,18 +68,76 @@ def test_runtime_publishes_actual_managed_name_before_starting_a_worker(tmp_path
|
||||
runtime.close()
|
||||
|
||||
|
||||
def test_catalog_accepts_intact_return_without_claiming_desktop_disappearance(tmp_path):
|
||||
@pytest.mark.parametrize('confirmation', [{'released': False}, None])
|
||||
def test_catalog_accepts_intact_return_without_claiming_desktop_disappearance(tmp_path, confirmation):
|
||||
from dx_productivity.trial_task_center.cell_catalog import _require_cleanup
|
||||
backend = Backend(); current = slot(tmp_path, backend).acquire()
|
||||
receipt = current.release(desktop_disappeared=False)
|
||||
cleanup = dict(desktop=current.name, desktop_handle_closed=True, owned_cleanup_complete=True, errors=[],
|
||||
desktop_confirmation={'released': False}, desktop_lease=receipt,
|
||||
desktop_confirmation=confirmation, desktop_lease=receipt,
|
||||
processes=[dict(errors=[], job_active_processes=0, process_handle_closed=True, job_handle_closed=True)])
|
||||
_require_cleanup(cleanup)
|
||||
cleanup['desktop_lease'] = dict(receipt, lease_id='forged')
|
||||
with pytest.raises(TaskCenterError): _require_cleanup(cleanup)
|
||||
|
||||
|
||||
def test_mutex_release_error_preserves_the_durably_returned_lease(tmp_path):
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
|
||||
class ReleaseErrorBackend(Backend):
|
||||
def unlock(self, handle):
|
||||
super().unlock(handle)
|
||||
raise OSError('mutex release failed')
|
||||
|
||||
backend = ReleaseErrorBackend()
|
||||
api = Api(backend)
|
||||
|
||||
def factory(name, **options):
|
||||
return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend))
|
||||
|
||||
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
|
||||
with runtime:
|
||||
with runtime.native_scope(tmp_path / 'operation'):
|
||||
pass
|
||||
|
||||
record = batch_resources.pending_resources(runtime.root)[0]
|
||||
assert record['state'] == 'isolated' and record['blocking'] is False
|
||||
assert record['cleanup']['desktop_lease']['returned'] is True
|
||||
assert 'mutex release failed' in record['isolation_warning']
|
||||
|
||||
next_owner = slot(tmp_path / 'slot', backend).acquire()
|
||||
with pytest.raises(OSError, match='mutex release failed'):
|
||||
next_owner.release(desktop_disappeared=False)
|
||||
assert next_owner.handle is None
|
||||
|
||||
|
||||
def test_failed_lease_return_stays_blocking_until_the_slot_can_be_returned(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
from dx_productivity.trial_task_center.batch_runtime import BatchCadRuntime
|
||||
|
||||
backend = Backend()
|
||||
api = Api(backend)
|
||||
|
||||
def factory(name, **options):
|
||||
return PrivateDesktop(name, **options, api=api, slot=slot(tmp_path / 'slot', backend))
|
||||
|
||||
def fail_return(*args):
|
||||
raise OSError('desktop observation unavailable')
|
||||
|
||||
runtime = BatchCadRuntime(tmp_path / 'data', 'execution', desktop_factory=factory)
|
||||
with pytest.raises(TaskCenterError, match='desktop observation unavailable'):
|
||||
with runtime:
|
||||
with runtime.native_scope(tmp_path / 'operation'):
|
||||
monkeypatch.setattr(backend, 'desktop_exists', fail_return)
|
||||
|
||||
assert backend.locked and batch_resources.blocking_resources(runtime.root)
|
||||
monkeypatch.undo()
|
||||
batch_resources.cleanup_pending_resources(runtime.root, retry_failed=True)
|
||||
assert not backend.locked
|
||||
assert batch_resources.blocking_resources(runtime.root) == ()
|
||||
|
||||
|
||||
def test_failed_owned_handle_cleanup_keeps_slot_until_cleanup_succeeds(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import batch_resources
|
||||
backend = Backend(); api = Api(backend)
|
||||
|
||||
@@ -230,6 +230,7 @@ def test_hierarchy_expansion_repeated_blocks_requires_every_instance(tmp_path):
|
||||
path.write_text(text)
|
||||
graph = {'components': {uid: {} for uid in ('$9I2/$1I1', '$9I3/$1I1')}}
|
||||
native_netlist._check_hierarchy_graph(path, graph, 'board')
|
||||
assert graph['source_sheets'] == [['board', '1'], ['child', '1']]
|
||||
graph['components'].pop('$9I3/$1I1')
|
||||
with pytest.raises(ValueError, match='coverage'):
|
||||
native_netlist._check_hierarchy_graph(path, graph, 'board')
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from threading import Event
|
||||
@@ -10,6 +11,8 @@ 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
|
||||
from test_nonblocking_items import component_case
|
||||
from test_saved_netlist_verification import saved_case
|
||||
|
||||
|
||||
@pytest.mark.parametrize('pause_after_first', [False, True])
|
||||
@@ -169,3 +172,212 @@ def test_runtime_prewrite_pause_commits_prefix_and_retires_only_current_claim(tm
|
||||
assert service.quick_run_progress(task.task_id).completed_items == 1
|
||||
assert not preparer.has_interrupted(task.task_id)
|
||||
service._store.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize('saved_case', ['execute'], indirect=True)
|
||||
@pytest.mark.parametrize('failure', [None, 'publication', 'marker_locked'])
|
||||
def test_saved_prewrite_pause_preserves_verified_prefix_and_retired_claim(
|
||||
saved_case, tmp_path, monkeypatch, failure):
|
||||
from dx_productivity.trial_task_center import quick_run
|
||||
from dx_productivity.trial_task_center.batch_attempt import _publish
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
from dx_productivity.trial_task_center.quick_run import _file_identity, _read_status_details
|
||||
from dx_productivity.trial_task_center.stop_control import StopControl
|
||||
from test_batch_runtime import Cad, worker_runtime
|
||||
|
||||
service, store, task, preparer, project, rows, control = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
prefix, paused = [row['job_id'] for row in rows]
|
||||
token = 'a' * 32
|
||||
stop = StopControl()
|
||||
(root / f'project-commit-{token}.tsv').unlink()
|
||||
monkeypatch.setattr('dx_productivity.trial_task_center.cell_catalog.preflight_command_target', lambda *args: None)
|
||||
marker_locked = failure == 'marker_locked'
|
||||
if marker_locked:
|
||||
unlink = Path.unlink
|
||||
|
||||
def lock_marker(path, *args, **kwargs):
|
||||
if marker_locked and path.name == 'current-command.tsv':
|
||||
raise PermissionError('current-command.tsv is locked')
|
||||
return unlink(path, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(Path, 'unlink', lock_marker)
|
||||
if failure == 'publication':
|
||||
append = quick_run._append_status_details
|
||||
|
||||
def fail_prefix_publication(path, statuses):
|
||||
if any(state == 'saved_ok' for _, state, _, _ in statuses):
|
||||
raise OSError('status append interrupted after SQL commit')
|
||||
return append(path, statuses)
|
||||
|
||||
monkeypatch.setattr(quick_run, '_append_status_details', fail_prefix_publication)
|
||||
|
||||
def native_monitor(command, *args, **kwargs):
|
||||
stop.set()
|
||||
path, expected = runtime._current_attempts[0]
|
||||
_publish(path, dict(expected, state='mutation_possible'))
|
||||
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\n{prefix}\tpending_save\n')
|
||||
(root / f'project-pause-{token}.tsv').write_text(f'{token}\t{project}\t{paused}\tprewrite_closed')
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{paused}\tawaiting_native_replace\t\tsnapshot before pause\n')
|
||||
result = subprocess.CompletedProcess(command, 75, '', '')
|
||||
result.prewrite_pause = dict(session_token=token, job_id=paused, project_path=str(project),
|
||||
sequence=7, worker_tree_exited=True)
|
||||
return result
|
||||
|
||||
runtime = worker_runtime(tmp_path, monkeypatch, native_monitor)
|
||||
runtime.stop_event = stop
|
||||
runtime.cad_factory = lambda *args, stop_control=None, **options: Cad(*args, **options)
|
||||
runtime_attempt = 'c' * 32
|
||||
from dx_productivity.trial_task_center import batch_runtime
|
||||
monkeypatch.setattr(batch_runtime, 'uuid4', lambda: SimpleNamespace(hex=runtime_attempt))
|
||||
report_path = root / f'snapshot-{prefix}.tsv.native.json'
|
||||
report = json.loads(report_path.read_text())
|
||||
report['batch_attempt'].update(session_id=runtime.session_id, attempt_id=runtime_attempt)
|
||||
report_path.write_text(json.dumps(report))
|
||||
|
||||
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):
|
||||
(root / 'project-session.request').write_text(f'{token}\t{project}\t{command[-1]}')
|
||||
if command[-1] == prefix:
|
||||
self.initial_command = command
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{prefix}\tpending_save\tsession_staged\tapplied\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
return runtime.run_worker(self.initial_command, timeout)
|
||||
|
||||
def close(self):
|
||||
if self.on_commit:
|
||||
self.on_commit(self.worker)
|
||||
self.worker = None
|
||||
|
||||
identity = _file_identity((root / 'status.tsv').stat())
|
||||
boundary = RetainedNative()
|
||||
def execute():
|
||||
return preparer.execute_step(task, service.projects(task), service.rules(task), batch_mode=True,
|
||||
batch_session=control['session'], project_session=boundary, stop_event=stop, runtime=runtime)
|
||||
with runtime:
|
||||
assert execute().state == 'pending_save'
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
execute()
|
||||
if raised.value.code == 'operation_cancelled':
|
||||
boundary.close()
|
||||
assert _file_identity((root / 'status.tsv').stat()) == identity
|
||||
if marker_locked:
|
||||
assert (root / 'current-command.tsv').is_file()
|
||||
marker_locked = False
|
||||
assert not service.has_interrupted_quick_run(task)
|
||||
assert not (root / 'current-command.tsv').exists()
|
||||
record = store._connection.execute("SELECT * FROM execution_operations WHERE state='pending'").fetchone()
|
||||
assert preparer.journal.certified_startup_pause(task, record)
|
||||
proof = json.loads(preparer.journal.project_commit_records(task)[0]['proof_json'])
|
||||
assert proof['operation_attempts'] == preparer.journal.project_commit_attempts(task, token)
|
||||
assert proof['native_attempt']['attempt_id'] == runtime_attempt
|
||||
if failure == 'publication':
|
||||
assert raised.value.code == 'quick_run_uncertain'
|
||||
assert service.has_interrupted_quick_run(task)
|
||||
assert 'project_commit_unverified' in (root / 'uncertain.flag').read_text()
|
||||
# Older project proofs can recover from the independently bound per-job receipt.
|
||||
del proof['operation_attempts']
|
||||
store._connection.execute('UPDATE execution_project_commits SET proof_json=?', (json.dumps(proof),))
|
||||
assert service.recover_quick_run(task, confirmed=True).progress.saved_items == 1
|
||||
else:
|
||||
assert raised.value.code == 'operation_cancelled', raised.value.__cause__
|
||||
assert {job: (state, code) for job, state, code, _ in _read_status_details(root / 'status.tsv')} == {
|
||||
prefix: ('saved_ok', 'project_committed'), paused: ('pending', 'prewrite_paused')}
|
||||
assert not (root / 'uncertain.flag').exists()
|
||||
assert service.quick_run_progress(task).saved_items == 1
|
||||
assert not service.has_interrupted_quick_run(task)
|
||||
assert len(control['calls']) == 3
|
||||
|
||||
|
||||
def test_component_failure_closes_retained_prefix_with_commit_callback(component_case, monkeypatch):
|
||||
from dx_productivity.trial_task_center.project_session import ProjectSessionScope
|
||||
from dx_productivity.trial_task_center.target_plan import ComponentTarget, TargetPlanRow
|
||||
|
||||
service, store, tasks, calls, outcomes = component_case
|
||||
task = tasks[0].task_id
|
||||
child = service.for_project_task(task)
|
||||
preparer = child._quick_run_preparer
|
||||
project = child.projects(task)[0].path
|
||||
database = project.parent / 'database'
|
||||
database.mkdir()
|
||||
(database / 'icdb.dat').write_bytes(b'database')
|
||||
root = preparer.data_root / 'quick-run'
|
||||
targets = tuple(ComponentTarget(project, 'MAIN', '1', f'u{i}', f'R{i}', 'OLD', '10K') for i in (1, 2, 3))
|
||||
store.record_target_inventory(task, targets)
|
||||
store.replace_target_plan(task, tuple(TargetPlanRow(target, True, 'NEW') for target in targets))
|
||||
dispatched = []
|
||||
|
||||
class RetainedWorker:
|
||||
def __init__(self, project, root, **kwargs):
|
||||
self.project, self.root = project, root
|
||||
self.token = ('a' if not dispatched else 'b') * 32
|
||||
self._done = Event()
|
||||
self._abort = Event()
|
||||
self.staged = []
|
||||
|
||||
def run_step(self, command, timeout):
|
||||
job = command[-1]
|
||||
dispatched.append(job)
|
||||
if len(dispatched) == 2:
|
||||
outcomes[(task, ('R2',))] = 'batch_failed'
|
||||
return preparer._process_runner(command, timeout)
|
||||
if len(dispatched) == 3:
|
||||
assert preparer.journal.project_commit_records(task)[0]['state'] == 'verified'
|
||||
self.staged.append(job)
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
stream.write(f'{job}\tpending_save\tsession_staged_no_match\tstaged\n')
|
||||
return subprocess.CompletedProcess(command, 0, '', '')
|
||||
|
||||
def close(self):
|
||||
if self._done.is_set():
|
||||
return
|
||||
marker = f'{self.token}\t{project}\tproject_verified\n'
|
||||
for job in self.staged:
|
||||
fields = (job, str(project), 'MAIN', '1', 'S\tfull_sheet_v1\r\nverified final state')
|
||||
(root / 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')
|
||||
marker += f'{job}\tno_match\n'
|
||||
(root / f'project-commit-{self.token}.tsv').write_text(marker, encoding='utf-8')
|
||||
with (root / 'status.tsv').open('a', encoding='utf-8') as stream:
|
||||
for job in self.staged:
|
||||
stream.write(f'{job}\tno_match\tproject_committed\tclosed\n')
|
||||
self._done.set()
|
||||
|
||||
monkeypatch.setattr('dx_productivity.trial_task_center.project_session.ProjectSessionWorker', RetainedWorker)
|
||||
preparer.project_session_scope = lambda **kwargs: ProjectSessionScope(preparer._process_runner, enabled=True)
|
||||
progress = child.quick_run_progress(task)
|
||||
result = child.execute_quick_run_queue(task, expected_item=(str(project), progress.next_old_part_number,
|
||||
progress.next_new_part_number, 'preserve'), stop_event=Event())
|
||||
assert len(dispatched) == 3
|
||||
assert result.progress.queue_complete
|
||||
assert (result.progress.no_match_items, result.progress.failed_items) == (2, 1)
|
||||
assert [row[0] for row in store._connection.execute('SELECT state FROM execution_operations ORDER BY rowid')] == [
|
||||
'no_match', 'failed', 'no_match']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('error_type', [ValueError, OSError])
|
||||
def test_reconciliation_marks_verification_errors_uncertain(saved_case, monkeypatch, error_type):
|
||||
from dx_productivity.trial_task_center.errors import TaskCenterError
|
||||
|
||||
_, _, task, preparer, _, _, _ = saved_case
|
||||
failure = error_type('saved database verification failed')
|
||||
|
||||
def fail(*args):
|
||||
raise failure
|
||||
|
||||
monkeypatch.setattr(preparer, '_commit_staged_project', fail)
|
||||
with pytest.raises(TaskCenterError) as raised:
|
||||
preparer.reconcile_terminal_receipts(task)
|
||||
assert raised.value.code == 'quick_run_uncertain'
|
||||
assert raised.value.__cause__ is failure
|
||||
assert (preparer.data_root / 'quick-run/uncertain.flag').read_text().startswith(
|
||||
'reason=uncommitted_receipt_requires_verification;')
|
||||
@@ -84,7 +84,9 @@ def test_partial_pause_commits_only_staged_prefix_and_rejects_incomplete_readbac
|
||||
assert record['state'] == 'verified'
|
||||
|
||||
|
||||
def test_crash_reconciliation_commits_native_marker_without_replaying_any_worker(staged_case, tmp_path):
|
||||
@pytest.mark.parametrize('persist_legacy_marker', [False, True])
|
||||
def test_crash_reconciliation_commits_native_marker_without_replaying_any_worker(staged_case, tmp_path, persist_legacy_marker):
|
||||
from dx_productivity.trial_task_center.execution_proof import capture_project_commit
|
||||
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])
|
||||
@@ -102,7 +104,13 @@ def test_crash_reconciliation_commits_native_marker_without_replaying_any_worker
|
||||
'\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')
|
||||
if persist_legacy_marker:
|
||||
commit = journal.pending_project_commits(task)[0]
|
||||
marker_proof = capture_project_commit(tmp_path, tmp_path, commit)
|
||||
journal.bind_project_commit_proof(task, commit['session_token'], marker_proof)
|
||||
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
|
||||
commit_proof = json.loads(journal.project_commit_records(task)[0]['proof_json'])
|
||||
assert commit_proof['operation_attempts'] == {job: [attempt.operation_key, attempt.attempt_id, attempt.generation]}
|
||||
@@ -134,6 +134,27 @@ def test_reused_uid_cannot_override_a_known_reference_mismatch():
|
||||
_reference_plan(plan,graph('$1I1'),{})
|
||||
|
||||
|
||||
def test_multiunit_reference_plan_keeps_each_saved_value_with_its_source_unit():
|
||||
from dx_productivity.trial_task_center.netlist_verification import NetlistVerification, _reference_plan
|
||||
before = graph('$1I1')
|
||||
components = before['graph']['components']
|
||||
components['rebound-unit-2'] = deepcopy(components['$1I1'])
|
||||
components['rebound-unit-2'].update(source_uid='$1I2', symbol='res.2 type Primitive ForwardPCB')
|
||||
components['rebound-unit-2']['pins']['p1']['number'] = '2'
|
||||
before['graph']['nets'][0]['endpoints'].append(['rebound-unit-2', 'p1'])
|
||||
target = dict(uid='@REFDES|R1', refdes='R1', old_value='')
|
||||
plan = {'copy_value': False, 'rows': [dict(enabled=True, target=target,
|
||||
new_part_number='NEW', custom_value_enabled=False, sync_nc=False)]}
|
||||
library = {uid: dict(refdes='R1', attributes={'Part Number': 'NEW'}, preserved_value=value)
|
||||
for uid, value in [('$1I1', '10K'), ('$1I2', '20K')]}
|
||||
after = deepcopy(before)
|
||||
for uid, value in [('$1I1', '10K'), ('rebound-unit-2', '20K')]:
|
||||
after['graph']['components'][uid]['attributes'] = {'Part Number': 'NEW', 'Value': value}
|
||||
rows, rebound = _reference_plan(plan, before, library)
|
||||
expected = NetlistVerification._expected(rows, after, rebound)
|
||||
assert native_netlist.compare_netlists(before, after, expected_changes=expected)['verified'] is True
|
||||
|
||||
|
||||
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'],'''
|
||||
|
||||
@@ -6,7 +6,7 @@ import pytest
|
||||
from dx_productivity.trial_task_center import batch_resources, batch_runtime, isolated_desktop
|
||||
|
||||
|
||||
def runtime_with_residual(tmp_path, monkeypatch):
|
||||
def runtime_with_residual(tmp_path, monkeypatch, *, confirmation=False):
|
||||
calls = []
|
||||
class Desktop:
|
||||
def __init__(self, name, **options):
|
||||
@@ -18,7 +18,8 @@ def runtime_with_residual(tmp_path, monkeypatch):
|
||||
calls.append('close')
|
||||
self.cleanup_record = {'desktop_handle_closed': True,
|
||||
'owned_cleanup_complete': True,
|
||||
'desktop_confirmation': {'released': False}, 'errors': ['foreign reference']}
|
||||
'desktop_confirmation': None if confirmation is None else {'released': confirmation},
|
||||
'errors': ['foreign reference']}
|
||||
raise OSError('foreign reference')
|
||||
def release_desktop(self):
|
||||
calls.append('observe')
|
||||
@@ -30,8 +31,9 @@ def runtime_with_residual(tmp_path, monkeypatch):
|
||||
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)
|
||||
@pytest.mark.parametrize('confirmation', [False, None])
|
||||
def test_residual_desktop_is_warning_admits_fresh_batch_and_never_repeats_close(tmp_path, monkeypatch, confirmation):
|
||||
runtime, calls = runtime_with_residual(tmp_path, monkeypatch, confirmation=confirmation)
|
||||
runtime.close()
|
||||
assert runtime.record['state'] == 'isolated'
|
||||
assert runtime.record['blocking'] is False
|
||||
|
||||
@@ -102,6 +102,8 @@ def saved_case(tmp_path, monkeypatch, request):
|
||||
else:
|
||||
text = ';; V4.1.0\n%net\n%page=MAIN\n\\N1\\ \\R1\\-\\1\\ \\R2\\-\\1\\\n%Part\n\\NEW1\\ \\R1\\\n\\NEW2\\ \\R2\\\n'
|
||||
path = next(arg[5:] for arg in command if arg.startswith('-out='))
|
||||
if control['damage'] == 'wrong_page':
|
||||
text = text.replace('page 1', 'page 2').replace('page 1', 'page 2')
|
||||
Path(path).write_text(text)
|
||||
if control['damage']=='source':(project.parent/'database/icdb.dat').write_bytes(b'changed during export')
|
||||
return type('Process',(),{'poll':lambda self:0})()
|
||||
@@ -244,6 +246,79 @@ def test_saved_prefix_mixed_applied_and_no_match_commits_after_one_export(saved_
|
||||
assert len(control['calls'])==3
|
||||
|
||||
|
||||
@pytest.mark.parametrize(('ref', 'damage', 'error'), [
|
||||
(None, 'wrong_page', 'coverage'), ('R2', 'wrong_page', 'coverage'), ('R3', None, 'coverage'),
|
||||
('R2', 'part', 'Part Number'), ('R2', None, None), (None, None, None),
|
||||
(None, 'unscoped', 'coverage'),
|
||||
])
|
||||
def test_saved_no_match_requires_exported_sheet_and_every_selected_part(saved_case, ref, damage, error):
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import verify_saved_project
|
||||
_, _, _, preparer, project, rows, control = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
token = 'a' * 32
|
||||
row = rows[1].copy()
|
||||
job = row['job_id']
|
||||
if ref is not None:
|
||||
row.update(target_scope='targets', target_selectors=f'@REFDES|{ref}\x1f{ref}\x1f10K')
|
||||
if damage == 'unscoped':
|
||||
row['sheet_number'] = ''
|
||||
control['damage'] = damage
|
||||
(root / f'project-commit-{token}.tsv').write_text(f'{token}\t{project}\tproject_saved\n{job}\tno_match\n')
|
||||
proof = capture_project_commit(preparer.data_root, root, dict(session_token=token,
|
||||
project_path=str(project.resolve()).casefold(), jobs_json=json.dumps([job])))
|
||||
proof = bind_project_commit_source(dict(proof, readback_files={}), preparer.data_root, root, project)
|
||||
if error:
|
||||
with pytest.raises(ValueError, match=error):
|
||||
verify_saved_project(preparer.data_root, root, proof, [row])
|
||||
else:
|
||||
verified = verify_saved_project(preparer.data_root, root, proof, [row])
|
||||
assert verified['outcomes'] == {job: 'no_match'}
|
||||
assert verified['saved_netlist']['status'] == 'verified'
|
||||
assert len(control['calls']) == (0 if damage == 'unscoped' else 3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('readbacks', [None, {}, {'unrelated.tsv': 'value'}])
|
||||
def test_saved_applied_write_requires_bound_writer_files_before_export(saved_case, readbacks):
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import verify_saved_project
|
||||
_, _, _, preparer, project, rows, control = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
proof = capture_project_commit(preparer.data_root, root, dict(session_token='a' * 32,
|
||||
project_path=str(project.resolve()).casefold(), jobs_json=json.dumps([row['job_id'] for row in rows])))
|
||||
if readbacks is not None:
|
||||
proof['readback_files'] = readbacks
|
||||
proof = bind_project_commit_source(proof, preparer.data_root, root, project)
|
||||
with pytest.raises(ValueError, match='writer evidence'):
|
||||
verify_saved_project(preparer.data_root, root, proof, rows)
|
||||
assert control['calls'] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize('damage', ['pointer', 'marker', 'verification', 'manifest', 'output'])
|
||||
def test_same_source_saved_export_integrity_failure_is_visible(saved_case, damage):
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import load_saved_export
|
||||
_, _, task, preparer, project, _, _ = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
preparer._commit_staged_project(task, bind_source=True)
|
||||
pointer = root / 'saved-netlist-export.json'
|
||||
record = json.loads(pointer.read_text(encoding='utf-8'))
|
||||
paths = {'pointer': pointer, 'marker': root / f'project-commit-{record["context"]["session_token"]}.tsv',
|
||||
'verification': Path(record['verification_path']), 'manifest': Path(record['export_path']),
|
||||
'output': Path(record['result']['outputs']['hier'])}
|
||||
paths[damage].write_text('corrupt', encoding='utf-8')
|
||||
with pytest.raises(ValueError, match='saved native export'):
|
||||
load_saved_export(root, project)
|
||||
|
||||
|
||||
def test_later_source_is_a_saved_export_cache_miss(saved_case):
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import load_saved_export
|
||||
_, _, task, preparer, project, _, _ = saved_case
|
||||
root = preparer.data_root / 'quick-run'
|
||||
preparer._commit_staged_project(task, bind_source=True)
|
||||
(project.parent / 'database/icdb.dat').write_bytes(b'later source revision')
|
||||
assert load_saved_export(root, project) is None
|
||||
|
||||
|
||||
def test_scoped_multiunit_preserve_checks_each_declared_library_default():
|
||||
from dx_productivity.trial_task_center.saved_netlist_verification import _observations
|
||||
row = dict(task_id='task',job_id='job',project_path='board.prj',old_part='OLD',new_part='NEW',schematic_name='MAIN',sheet_number='1')
|
||||
|
||||
@@ -230,6 +230,21 @@ def test_bad_optional_progress_does_not_block_saved_source_binding(tmp_path, pro
|
||||
assert bind_project_commit_source({}, root.parent, root, project)['saved_sources']
|
||||
|
||||
|
||||
def test_status_file_sharing_conflict_does_not_recycle_mentor(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source, batch_resources
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
project, database, root = inputs(tmp_path)
|
||||
write_record = batch_resources.write_record
|
||||
def write(path, record):
|
||||
if path.name == 'saved-source-status.json':
|
||||
raise locked()
|
||||
return write_record(path, record)
|
||||
monkeypatch.setattr(batch_resources, 'write_record', write)
|
||||
monkeypatch.setattr(saved_source, 'LOCK_WAIT_SECONDS', 0)
|
||||
assert bind_project_commit_source({}, root.parent, root, project,
|
||||
release_mentor=lambda _: pytest.fail('diagnostic file lock recycled Mentor'))['saved_sources']
|
||||
|
||||
|
||||
def test_pause_after_release_notice_never_starts_cad_recycling(tmp_path, monkeypatch):
|
||||
from dx_productivity.trial_task_center import saved_source, batch_resources
|
||||
from dx_productivity.trial_task_center.execution_proof import bind_project_commit_source
|
||||
|
||||
Reference in new issue
Block a user