Core regression / Python core, intervention UI and release configuration (push) Successful in 5m2s
Core regression / JavaScript syntax (push) Successful in 7s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 5m32s
Core regression / JavaScript syntax (pull_request) Successful in 8s
245 lines
14 KiB
Python
245 lines
14 KiB
Python
"""Run issue #33 D8 through real service/SQLite queues with an injected CAD runner."""
|
|
from argparse import ArgumentParser
|
|
from collections import Counter
|
|
import csv
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
from uuid import uuid4
|
|
|
|
from dx_productivity.trial_task_center import supervisor_protocol
|
|
from dx_productivity.trial_task_center.batch_resources import _process_gone, process_identity, write_record
|
|
from dx_productivity.trial_task_center.inventory import HEADER
|
|
from dx_productivity.trial_task_center.logging_setup import configure_logging
|
|
from dx_productivity.trial_task_center.quick_run import QuickRunPreparer, _decode_vbs_field
|
|
from dx_productivity.trial_task_center.service import TaskCenterService
|
|
from dx_productivity.trial_task_center.stop_control import StopControl
|
|
from dx_productivity.trial_task_center.store import TaskStore
|
|
from dx_productivity.trial_task_center.target_plan import TargetPlanRow
|
|
from dx_productivity.trial_task_center.task_queue import _plan_hash, execute_task_queue
|
|
|
|
|
|
class SimulatedRuntime:
|
|
cad = desktop = None
|
|
stop_event = None
|
|
|
|
def __init__(self, root, release):
|
|
self.root = root
|
|
self.release = release
|
|
self.session_id = uuid4().hex
|
|
|
|
def bind_logs(self, *_):
|
|
pass
|
|
|
|
def release_failed_project(self, *args):
|
|
return self.release(*args)
|
|
|
|
|
|
def run(root, projects, *, expect_baseline, resume_short=False):
|
|
resource_failure = projects == 100
|
|
data = root / 'data'
|
|
source = root / 'projects'
|
|
shared = source / 'shared-db'
|
|
prior, blocked, dependent = (10, 11, 12) if resource_failure else (0, 0, 0)
|
|
if not resume_short:
|
|
root.mkdir(parents=True)
|
|
shared.mkdir(parents=True)
|
|
(shared / 'icdb.dat').write_bytes(b'simulated shared design source')
|
|
for ordinal in range(1, projects + 1):
|
|
path = source / f'board-{ordinal:03}' / 'board.prj'
|
|
path.parent.mkdir()
|
|
databank = shared if ordinal in (blocked, dependent) else 'database'
|
|
path.write_text(f'KEY FrontEndSnapshot "DxD"\nKEY iCDBDir "{databank}"\n', encoding='utf-8')
|
|
data.mkdir()
|
|
|
|
stop = StopControl()
|
|
calls = []
|
|
release_checks = []
|
|
supervisor_calls = []
|
|
pre_cleanup = None
|
|
live_writer = None
|
|
identity = None
|
|
|
|
def worker(command, _timeout):
|
|
evidence = Path(command[3])
|
|
command_path = evidence / 'current-command.tsv'
|
|
if not command_path.exists():
|
|
command_path = evidence / 'command.tsv'
|
|
with command_path.open(encoding='utf-8-sig') as stream:
|
|
item = next(csv.DictReader(stream, delimiter='\t'))
|
|
path = Path(item['project_path'])
|
|
ordinal = int(path.parent.name.split('-')[-1])
|
|
if (evidence / 'sheet-discovery.request').exists():
|
|
(evidence / 'sheets.tsv').write_text(f'project_path\tschematic_name\tsheet_number\n{path}\tMAIN\t1\n')
|
|
(evidence / 'inventory.tsv').write_text(f'project_path\tschematic_name\tsheet_number\told_part\n{path}\tMAIN\t1\tOLD\n')
|
|
(evidence / 'components.tsv').write_text('\t'.join(HEADER) + f'\n{path}\tMAIN\t1\tuid\tR1\tOLD\t10K\n')
|
|
return subprocess.CompletedProcess(command, 0, '', '')
|
|
job = command[-1]
|
|
assert item['job_id'] == job
|
|
assert _decode_vbs_field(item['target_selectors']) == 'uid\x1fR1\x1f10K'
|
|
assert all(call['project'] != ordinal and call['job_id'] != job for call in calls)
|
|
state = 'batch_saved_unverified' if ordinal in (prior, blocked) else 'saved_ok'
|
|
calls.append({'project': ordinal, 'job_id': job, 'result': state})
|
|
message = ('Native replacement and parameter readback passed on current sheet. Replacements: '
|
|
'R1 OLD -> NEW Display verified: attributes=2. Saved, reopened for readback, and closed.')
|
|
if state != 'saved_ok':
|
|
message = 'Injected lookup timeout after an earlier possible CAD write.'
|
|
with (evidence / 'status.tsv').open('a', encoding='utf-8') as stream:
|
|
stream.write(f'{job}\tawaiting_native_replace\t\tcaptured\n')
|
|
stream.write(f'{job}\t{state}\tbatch_closed\t{message}\n')
|
|
if not resource_failure and ordinal == 3:
|
|
stop.set()
|
|
return subprocess.CompletedProcess(command, 0, '', '')
|
|
|
|
store = None
|
|
|
|
def open_service():
|
|
nonlocal store
|
|
store = TaskStore(data / 'task-center.db')
|
|
service = TaskCenterService(store, configure_logging(data), quick_run_preparer=QuickRunPreparer(
|
|
data, process_runner=worker, cscript_resolver=lambda: Path('simulated-cscript'),
|
|
sheet_discoverer=lambda _: (('MAIN', '1'),)))
|
|
service._supervised = True
|
|
|
|
def supervise(operation, arguments, *, stop_event):
|
|
nonlocal pre_cleanup
|
|
assert operation == 'execute_task_queue'
|
|
runtime = SimulatedRuntime(data, release)
|
|
supervisor_calls.append(dict(batch_id=runtime.session_id, queue_id=arguments.get('queue_id'),
|
|
resource_batch_id=arguments.get('resource_batch_id')))
|
|
result = execute_task_queue(service, stop_event=stop_event, runtime=runtime, **arguments)
|
|
if resource_failure and live_writer is not None and live_writer.poll() is None:
|
|
assert result.paused and result.current_task_id == ids[blocked - 1]
|
|
assert [entry['project'] for entry in calls] == list(range(1, blocked + 1))
|
|
assert not _process_gone(identity)
|
|
pre_cleanup = Counter(row.state for row in result.entries)
|
|
batch_id = runtime.session_id
|
|
attempt_id = uuid4().hex
|
|
directory = data / 'batch-resources' / batch_id
|
|
common = dict(version=supervisor_protocol.VERSION, batch_id=batch_id, attempt_id=attempt_id)
|
|
write_record(directory / 'request.json', dict(common, operation=operation,
|
|
root=str(data), arguments=supervisor_protocol.encode(arguments)))
|
|
request_digest = hashlib.sha256((directory / 'request.json').read_bytes()).hexdigest()
|
|
write_record(directory / 'result.json', dict(common, sequence=1, generation=1, type='result',
|
|
payload=dict(business_succeeded=True, result=supervisor_protocol.encode(result))))
|
|
journal = dict(common, operation=operation, task_ids=list(ids), state='finished',
|
|
process=identity, parent_process=identity, request_sha256=request_digest)
|
|
assert supervisor_protocol.valid_journal(journal, batch_id)
|
|
write_record(directory / 'supervisor.json', journal)
|
|
service._last_supervisor_batch_id = batch_id
|
|
from dx_productivity.trial_task_center import task_queue
|
|
admitted = getattr(task_queue, 'resource_pause_admitted', None)
|
|
if admitted is not None:
|
|
assert not admitted(data, batch_id, ids, hashes, result)
|
|
live_writer.terminate()
|
|
live_writer.wait(timeout=10)
|
|
assert _process_gone(identity)
|
|
return result
|
|
|
|
def release(error, evidence):
|
|
nonlocal live_writer, identity
|
|
ordinal = calls[-1]['project']
|
|
release_checks.append(ordinal)
|
|
if resource_failure and ordinal == blocked and live_writer is None:
|
|
live_writer = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(300)'],
|
|
creationflags=subprocess.CREATE_NO_WINDOW)
|
|
identity = process_identity(live_writer)
|
|
return live_writer is None or live_writer.poll() is not None
|
|
|
|
service._supervise = supervise
|
|
return service
|
|
|
|
service = open_service()
|
|
try:
|
|
if resume_short:
|
|
recorded = json.loads((root / 'pause.json').read_text(encoding='utf-8'))
|
|
ids = tuple(recorded['checkpoint']['task_ids'])
|
|
hashes = recorded['checkpoint']['plan_hashes']
|
|
calls.extend(recorded['calls'])
|
|
result = execute_task_queue(service, ids, stop_event=stop,
|
|
queue_id=recorded['queue_id'], expected_plan_hashes=hashes)
|
|
assert result.queue_id == recorded['queue_id']
|
|
final = json.loads((data / 'task-queues' / (result.queue_id + '.json')).read_text(encoding='utf-8'))
|
|
assert final['task_ids'] == list(ids) and final['plan_hashes'] == hashes
|
|
assert final['phase'] == 'finished' and not result.paused
|
|
assert Counter(row.state for row in result.entries) == {'completed': projects}
|
|
assert [call['project'] for call in calls] == list(range(1, projects + 1))
|
|
assert recorded['paused_in_pid'] != os.getpid()
|
|
return dict(projects=projects, first_return=recorded['first_return'],
|
|
final={'completed': projects}, queue_id=result.queue_id, calls=calls,
|
|
paused_in_pid=recorded['paused_in_pid'], resumed_in_pid=os.getpid())
|
|
tasks = service.create_project_tasks(source)
|
|
ids = tuple(task.task_id for task in tasks)
|
|
assert len(ids) == projects
|
|
assert [service.projects(task_id)[0].path.parent.name for task_id in ids] == [
|
|
f'board-{number:03}' for number in range(1, projects + 1)]
|
|
service.add_rule(ids[0], 'OLD', 'NEW')
|
|
for task_id in ids:
|
|
targets = service.collect_target_inventory(task_id, runtime=SimulatedRuntime(data, lambda *_: True))
|
|
service.replace_target_plan(task_id, [TargetPlanRow(targets[0].target, enabled=True, new_part_number='NEW')])
|
|
hashes = {task_id: _plan_hash(service.for_project_task(task_id), task_id) for task_id in ids}
|
|
first = execute_task_queue(service, ids, stop_event=stop, expected_plan_hashes=hashes,
|
|
checkpoint_id=uuid4().hex)
|
|
path = data / 'task-queues' / (first.queue_id + '.json')
|
|
checkpoint = json.loads(path.read_text(encoding='utf-8'))
|
|
initial = Counter(row.state for row in first.entries)
|
|
print(f'{projects} projects first return {dict(initial)}', flush=True)
|
|
if resource_failure:
|
|
assert pre_cleanup == {'completed': 9, 'blocked': 2, 'pending': projects - 11}
|
|
if expect_baseline:
|
|
assert first.paused and initial == pre_cleanup
|
|
return dict(projects=projects, first_return=initial, before_release=pre_cleanup,
|
|
queue_id=first.queue_id, writer_pid=identity['pid'],
|
|
writer_gone=_process_gone(identity), calls=calls, supervisor_calls=supervisor_calls)
|
|
assert not first.paused and initial == {'completed': 97, 'blocked': 3}
|
|
assert len(supervisor_calls) == 2
|
|
assert supervisor_calls[-1]['queue_id'] == first.queue_id
|
|
assert supervisor_calls[-1]['resource_batch_id'] == supervisor_calls[0]['batch_id']
|
|
else:
|
|
assert first.paused and [entry['project'] for entry in calls] == [1, 2, 3]
|
|
write_record(root / 'pause.json', dict(queue_id=first.queue_id, checkpoint=checkpoint,
|
|
calls=calls, first_return=initial, paused_in_pid=os.getpid()))
|
|
store.close()
|
|
subprocess.run([sys.executable, __file__, '--projects', str(projects), '--output', str(root),
|
|
'--resume-short'], check=True, creationflags=subprocess.CREATE_NO_WINDOW)
|
|
return json.loads((root / 'report.json').read_text(encoding='utf-8'))
|
|
|
|
store.close()
|
|
service = open_service()
|
|
stop = StopControl()
|
|
result = execute_task_queue(service, ids, stop_event=stop, queue_id=first.queue_id, expected_plan_hashes=hashes)
|
|
final = json.loads(path.read_text(encoding='utf-8'))
|
|
assert final['task_ids'] == checkpoint['task_ids']
|
|
assert final['plan_hashes'] == checkpoint['plan_hashes']
|
|
assert final['phase'] == 'finished' and not result.paused
|
|
if resource_failure:
|
|
assert final['dependency_tasks'] == {ids[dependent - 1]: ids[blocked - 1]}
|
|
assert [entry.state for entry in result.entries[prior - 1:dependent]] == ['blocked'] * 3
|
|
assert [call['project'] for call in calls] == [ordinal for ordinal in range(1, projects + 1) if ordinal != dependent]
|
|
assert execute_task_queue(service, ids, stop_event=stop, queue_id=result.queue_id) == result
|
|
return dict(projects=projects, first_return=initial, before_release=pre_cleanup,
|
|
final=Counter(row.state for row in result.entries), supervisor_calls=supervisor_calls,
|
|
queue_id=result.queue_id, shared_source_blocked=dependent or None,
|
|
writer_pid=(identity or {}).get('pid'), release_checks=release_checks, calls=calls)
|
|
finally:
|
|
if live_writer is not None and live_writer.poll() is None:
|
|
live_writer.terminate()
|
|
live_writer.wait(timeout=10)
|
|
store.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
parser = ArgumentParser(description=__doc__)
|
|
parser.add_argument('--output', type=Path, required=True)
|
|
parser.add_argument('--projects', type=int, choices=(8, 100), required=True)
|
|
parser.add_argument('--expect-baseline', action='store_true')
|
|
parser.add_argument('--resume-short', action='store_true', help='Internal pause handoff to a new Python process')
|
|
args = parser.parse_args()
|
|
result = run(args.output.resolve(), args.projects, expect_baseline=args.expect_baseline,
|
|
resume_short=args.resume_short)
|
|
(args.output / 'report.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
|
|
print({key: result.get(key) for key in ('projects', 'first_return', 'final', 'queue_id')}, flush=True)
|