From 832ab5d5631b3576bf05f08ea8decc439f8be126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Wed, 21 Oct 2026 14:28:25 +0800 Subject: [PATCH] feat: persist batch attempt proof before CAD mutations --- .../dxdesigner795/QuickPartReplace.vbs | 38 ++++ .../trial_task_center/application.py | 10 +- .../trial_task_center/batch_attempt.py | 133 ++++++++++++++ .../trial_task_center/native_helper.py | 54 ++++++ tests/v1_1/test_batch_attempt.py | 163 ++++++++++++++++++ tests/v1_1/test_batch_attempt_vbs.py | 60 +++++++ 6 files changed, 457 insertions(+), 1 deletion(-) create mode 100644 src/dx_productivity/trial_task_center/batch_attempt.py create mode 100644 tests/v1_1/test_batch_attempt.py create mode 100644 tests/v1_1/test_batch_attempt_vbs.py diff --git a/integration/dxdesigner795/QuickPartReplace.vbs b/integration/dxdesigner795/QuickPartReplace.vbs index 061f085..7dd3e9d 100644 --- a/integration/dxdesigner795/QuickPartReplace.vbs +++ b/integration/dxdesigner795/QuickPartReplace.vbs @@ -930,6 +930,7 @@ Sub QPFinishBatchItem() Next End If If FinalState = "restored_ok" Then + QPMarkBatchMutation Command QPCloseBatchProject TargetPath, True QP_BatchSaveCommitted = True ElseIf Not QP_SessionMode Then @@ -975,6 +976,42 @@ Sub QPFinishBatchItem() QPProgress "finished", 1, 1 End Sub +Sub QPMarkBatchMutation(ByRef Command) + Dim Shell, Entry, Required, CommandLine, Key, Value, ExitCode + Set Shell = CreateObject("WScript.Shell") + Required = False + For Each Entry In Shell.Environment("Process") + If InStr(1, CStr(Entry), "DXPART_ATTEMPT_FILE=", vbTextCompare) = 1 Or _ + InStr(1, CStr(Entry), "DXPART_BATCH_SESSION_ID=", vbTextCompare) = 1 Or _ + InStr(1, CStr(Entry), "DXPART_BATCH_GENERATION=", vbTextCompare) = 1 Or _ + InStr(1, CStr(Entry), "DXPART_ATTEMPT_ID=", vbTextCompare) = 1 Then Required = True + Next + If Not Required Then Exit Sub + If Len(QP_HelperExecutable) = 0 Or Not QP_Fso.FileExists(QP_HelperExecutable) Then _ + Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", "mutation proof helper is unavailable" + CommandLine = Chr(34) & QP_HelperExecutable & Chr(34) + If Len(QP_HelperScript) > 0 Then + If Not QP_Fso.FileExists(QP_HelperScript) Then _ + Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", "mutation proof script is unavailable" + CommandLine = CommandLine & " " & Chr(34) & QP_HelperScript & Chr(34) + End If + CommandLine = CommandLine & " --mark-batch-attempt" + For Each Key In Array("job_id", "task_id", "project_path") + Value = CStr(Command(Key)) + If Len(Value) = 0 Or InStr(Value, Chr(34)) > 0 Or InStr(Value, vbCr) > 0 Or InStr(Value, vbLf) > 0 Then _ + Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", "invalid mutation proof identity" + Select Case Key + Case "job_id": CommandLine = CommandLine & " --attempt-job " + Case "task_id": CommandLine = CommandLine & " --attempt-task " + Case "project_path": CommandLine = CommandLine & " --attempt-project " + End Select + CommandLine = CommandLine & Chr(34) & Value & Chr(34) + Next + ExitCode = Shell.Run(CommandLine, 0, True) + If ExitCode <> 0 Then Err.Raise vbObjectError + 879, "QuickPartReplace.Attempt", _ + "durable mutation proof failed; no CAD write allowed" +End Sub + Sub QPAutomaticReplaceAndRestore(ByRef Command, ByVal SnapshotPath) Dim ErrorNumber, ErrorSource, ErrorDescription QPRequireCommandSnapshot Command, SnapshotPath @@ -1590,6 +1627,7 @@ Sub QPRestoreAfterOperatorReplace(ByRef Command, ByVal SnapshotPath) QPProgress "restore_preflight", Index + 1, Records.Item("components").Count Next QPProgress "before_restore_transaction", 0, Plans.Count + QPMarkBatchMutation Command QP_RestoreTransactionOpen = True QP_App.ActiveView.Block.StartUndoTransaction On Error Resume Next diff --git a/src/dx_productivity/trial_task_center/application.py b/src/dx_productivity/trial_task_center/application.py index 1685852..40b7b91 100644 --- a/src/dx_productivity/trial_task_center/application.py +++ b/src/dx_productivity/trial_task_center/application.py @@ -51,9 +51,13 @@ def _parse_arguments(argv: Sequence[str] | None) -> argparse.Namespace: parser.add_argument("--data-root", type=Path, help=argparse.SUPPRESS) parser.add_argument("--native-helper", action="store_true", help=argparse.SUPPRESS) parser.add_argument("--snapshot", type=Path, help=argparse.SUPPRESS) + parser.add_argument('--mark-batch-attempt', action='store_true', help=argparse.SUPPRESS) + parser.add_argument('--attempt-job', help=argparse.SUPPRESS) + parser.add_argument('--attempt-task', help=argparse.SUPPRESS) + parser.add_argument('--attempt-project', type=Path, help=argparse.SUPPRESS) parser.add_argument('--cell-catalog-worker', type=Path, help=argparse.SUPPRESS) parser.add_argument("--sceneos-cli", action="store_true", help=argparse.SUPPRESS) - parser.add_argument('--private-cad-action', choices=('probe', 'quit'), help=argparse.SUPPRESS) + parser.add_argument('--private-cad-action', choices=('probe', 'quit', 'checkpoint'), help=argparse.SUPPRESS) parser.add_argument('--private-cad-evidence', type=Path, help=argparse.SUPPRESS) parser.add_argument('--private-cad-pid', type=int, help=argparse.SUPPRESS) return parser.parse_args(list(argv) if argv is not None else None) @@ -116,6 +120,10 @@ def _flush(context: LoggingContext) -> None: def main(argv: Sequence[str] | None = None) -> int: """Run the Qt shell, returning a conventional process status code.""" arguments = _parse_arguments(argv) + if arguments.mark_batch_attempt: + from dx_productivity.trial_task_center.native_helper import run_attempt_marker + return run_attempt_marker(job_id=arguments.attempt_job, task_id=arguments.attempt_task, + project_path=arguments.attempt_project) if arguments.cell_catalog_worker is not None: from dx_productivity.trial_task_center.cell_catalog_worker import run return run(arguments.cell_catalog_worker) diff --git a/src/dx_productivity/trial_task_center/batch_attempt.py b/src/dx_productivity/trial_task_center/batch_attempt.py new file mode 100644 index 0000000..1be9ea1 --- /dev/null +++ b/src/dx_productivity/trial_task_center/batch_attempt.py @@ -0,0 +1,133 @@ +"""Durable write-ahead proof for one logical job in a private CAD attempt. + +A prepared record is evidence of no write only while its complete identity still +matches. Helpers never create records and must fail closed if publication fails. +""" +import json +import os +from pathlib import Path +import re +import tempfile +import time +from uuid import uuid4 + + +_IDENTITY = ('session_id', 'generation', 'attempt_id', 'task_id', 'job_id', 'project_path') + + +def _project(value): + return os.path.normcase(os.path.abspath(value)) + + +def _validate(record): + if not isinstance(record, dict) or record.get('schema_version') != 1: + raise ValueError('invalid batch attempt schema') + for key in ('session_id', 'task_id', 'job_id', 'project_path'): + value = record.get(key) + if not isinstance(value, str) or not value.strip() or any(ord(c) < 32 for c in value): + raise ValueError(f'invalid batch attempt {key}') + generation = record.get('generation') + if type(generation) is not int or generation < 1: + raise ValueError('invalid batch attempt generation') + if not isinstance(record.get('attempt_id'), str) or not re.fullmatch(r'[0-9a-f]{32}', record['attempt_id']): + raise ValueError('invalid batch attempt ID') + if record.get('state') not in {'prepared', 'mutation_possible'}: + raise ValueError('invalid batch attempt state') + return record + + +def _publish(path, record): + path = Path(path) + descriptor, temporary = tempfile.mkstemp(prefix=f'.{path.name}.', suffix='.tmp', dir=path.parent) + try: + with os.fdopen(descriptor, 'w', encoding='utf-8', newline='') as handle: + json.dump(record, handle, ensure_ascii=False, indent=2) + handle.flush() + os.fsync(handle.fileno()) + deadline = time.monotonic() + 1 + while True: + try: + os.replace(temporary, path) + break + except PermissionError: + if time.monotonic() >= deadline: + raise + time.sleep(.02) + # POSIX needs a directory sync for the atomic rename; Windows does not + # expose fsync on directories through the CRT. + if os.name != 'nt': + directory = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + Path(temporary).unlink(missing_ok=True) + + +def prepare_attempt(path, *, session_id, generation, task_id, job_id, project_path, attempt_id=None): + record = _validate(dict(schema_version=1, session_id=str(session_id), generation=generation, + task_id=str(task_id), job_id=str(job_id), project_path=_project(project_path), + attempt_id=uuid4().hex if attempt_id is None else attempt_id, state='prepared')) + Path(path).parent.mkdir(parents=True, exist_ok=True) + _publish(path, record) + return record + + +def read_attempt(path): + return _validate(json.loads(Path(path).read_text(encoding='utf-8'))) + + +def _bound_attempt(path=None, *, job_id=None, task_id=None, project_path=None): + if path is None and 'DXPART_ATTEMPT_FILE' not in os.environ: + if any(key in os.environ for key in ('DXPART_BATCH_SESSION_ID', 'DXPART_BATCH_GENERATION', 'DXPART_ATTEMPT_ID')): + raise ValueError('missing batch attempt file') + return None + raw_path = os.environ.get('DXPART_ATTEMPT_FILE') if path is None else os.fspath(path) + if not raw_path or not Path(raw_path).is_absolute(): + raise ValueError('invalid batch attempt file') + path = Path(raw_path) + job_id = str(job_id) if job_id is not None else os.environ.get('DXPART_JOB_ID') + task_id = str(task_id) if task_id is not None else os.environ.get('DXPART_TASK_ID') + if path.is_dir(): + if not job_id or not re.fullmatch(r'[A-Za-z0-9_-]+', job_id): + raise ValueError('missing or unsafe batch attempt job ID') + path = path / f'{job_id}.json' + record = read_attempt(path) + expected = {'session_id': os.environ.get('DXPART_BATCH_SESSION_ID'), + 'attempt_id': os.environ.get('DXPART_ATTEMPT_ID'), + 'generation': os.environ.get('DXPART_BATCH_GENERATION')} + if not all(expected.values()) or str(record['generation']) != expected.pop('generation'): + raise ValueError('missing or stale batch generation') + if any(record[key] != value for key, value in expected.items()): + raise ValueError('stale batch attempt identity') + if not job_id or not task_id or record['job_id'] != job_id or record['task_id'] != task_id: + raise ValueError('batch attempt task/job mismatch') + # Optional environment bindings remain authoritative even when the caller + # supplies explicit command fields. + for key, value in (('DXPART_JOB_ID', job_id), ('DXPART_TASK_ID', task_id)): + if key in os.environ and os.environ[key] != value: + raise ValueError('batch process task/job mismatch') + if project_path is not None and record['project_path'] != _project(project_path): + raise ValueError('batch attempt project mismatch') + return path, record + + +def mark_mutation_possible(path=None, *, job_id=None, task_id=None, project_path=None): + bound = _bound_attempt(path, job_id=job_id, task_id=task_id, project_path=project_path) + if bound is None: + return None + path, record = bound + if record['state'] != 'mutation_possible': + record = dict(record, state='mutation_possible') + _publish(path, record) + return record + + +def can_retry_attempt(path, expected): + try: + _validate(expected) + actual = read_attempt(path) + return actual['state'] == 'prepared' and all(actual[key] == expected[key] for key in _IDENTITY) + except (OSError, ValueError, TypeError, KeyError): + return False diff --git a/src/dx_productivity/trial_task_center/native_helper.py b/src/dx_productivity/trial_task_center/native_helper.py index 7350902..86e7fef 100644 --- a/src/dx_productivity/trial_task_center/native_helper.py +++ b/src/dx_productivity/trial_task_center/native_helper.py @@ -2,6 +2,7 @@ import argparse import faulthandler import ctypes +import csv import hashlib import json import os @@ -13,6 +14,48 @@ import time import traceback +def snapshot_attempt(snapshot): + """Bind batch evidence to the actual snapshot and its confirmed queue row.""" + from .batch_attempt import _bound_attempt + if 'DXPART_ATTEMPT_FILE' not in os.environ: + return _bound_attempt() + snapshot = Path(snapshot) + metadata, _ = read_snapshot(snapshot) + if not snapshot.name.startswith('snapshot-') or snapshot.suffix != '.tsv': + raise ValueError('batch snapshot has no job identity') + job_id = snapshot.stem[len('snapshot-'):] + with (snapshot.parent / 'command.tsv').open(encoding='utf-8-sig', newline='') as handle: + commands = [row for row in csv.DictReader(handle, delimiter='\t') if row.get('job_id') == job_id] + if len(commands) != 1: + raise ValueError('batch snapshot must match one confirmed command') + command = commands[0] + if os.path.normcase(os.path.abspath(command['project_path'])) != os.path.normcase(os.path.abspath(metadata[1])): + raise ValueError('batch command and snapshot projects differ') + return _bound_attempt(job_id=job_id, task_id=command['task_id'], project_path=metadata[1]) + + +def mark_snapshot_mutation(snapshot): + from .batch_attempt import mark_mutation_possible + bound = snapshot_attempt(snapshot) + if bound is None: + return None + path, record = bound + return mark_mutation_possible(path, job_id=record['job_id'], task_id=record['task_id'], + project_path=record['project_path']) + + +def run_attempt_marker(*, job_id, task_id, project_path): + from .batch_attempt import mark_mutation_possible + if not job_id or not task_id or not project_path: + return 2 + try: + mark_mutation_possible(job_id=job_id, task_id=task_id, project_path=project_path) + return 0 + except (OSError, ValueError, KeyError, TypeError) as error: + print(f'Batch mutation proof failed: {error}', file=sys.stderr) + return 1 + + def decode(value): characters = [] index = 0 @@ -542,6 +585,7 @@ def run_native(snapshot, report): slot_count = int(binding.get("slot_count", report.get("slot_count", 1))) if slot_count < 1: raise ValueError("Recorded replacement has no valid slots") + mark_snapshot_mutation(snapshot) report["promoted_pins"] = promote_pin_numbers(app, api, report["replaced_uids"], slot_count, lambda phase: _promotion_phase(snapshot, report, phase)) report["already_replaced"] = True @@ -706,6 +750,7 @@ def run_native(snapshot, report): cell_catalog=cell_proof) report["stage"] = "native_replace_started" save_report(snapshot, report) + mark_snapshot_mutation(snapshot) click(dlg_item(dialog, 1695)) replacement_poll_count = 0 @@ -820,6 +865,15 @@ def run(snapshot): watchdog.daemon = True watchdog.start() try: + bound = snapshot_attempt(snapshot) + if bound is not None: + _, current = bound + identity = {key: current[key] for key in + ('session_id', 'generation', 'attempt_id', 'task_id', 'job_id', 'project_path')} + if report.get('batch_attempt') != identity: + report.clear() + report.update(snapshot=str(snapshot), ok=False, stage='preflight') + report['batch_attempt'] = identity run_native(snapshot, report) report["ok"] = True return 0 diff --git a/tests/v1_1/test_batch_attempt.py b/tests/v1_1/test_batch_attempt.py new file mode 100644 index 0000000..a62c0fd --- /dev/null +++ b/tests/v1_1/test_batch_attempt.py @@ -0,0 +1,163 @@ +import json +import os + +import pytest + +from dx_productivity.trial_task_center import batch_attempt as attempts + + +@pytest.fixture +def prepared(tmp_path, monkeypatch): + path = tmp_path / 'job.json' + record = attempts.prepare_attempt(path, session_id='session-a', generation=1, + task_id='task-a', job_id='job-a', project_path=tmp_path / 'board.prj') + monkeypatch.setenv('DXPART_ATTEMPT_FILE', str(path)) + monkeypatch.setenv('DXPART_BATCH_SESSION_ID', 'session-a') + monkeypatch.setenv('DXPART_BATCH_GENERATION', '1') + monkeypatch.setenv('DXPART_ATTEMPT_ID', record['attempt_id']) + monkeypatch.setenv('DXPART_TASK_ID', 'task-a') + monkeypatch.setenv('DXPART_JOB_ID', 'job-a') + return path, record + + +def test_only_current_prepared_attempt_can_retry(prepared): + path, expected = prepared + assert attempts.can_retry_attempt(path, expected) + attempts.mark_mutation_possible(job_id='job-a') + assert attempts.read_attempt(path)['state'] == 'mutation_possible' + assert not attempts.can_retry_attempt(path, expected) + + +@pytest.mark.parametrize('field,value', [('session_id', 'old'), ('generation', 2), + ('attempt_id', '0' * 32), ('task_id', 'old'), ('job_id', 'old'), + ('project_path', 'other.prj')]) +def test_retry_rejects_stale_identity(prepared, field, value): + path, expected = prepared + assert not attempts.can_retry_attempt(path, dict(expected, **{field: value})) + + +@pytest.mark.parametrize('contents', [None, '{truncated', '{}', '[]']) +def test_unreadable_or_incomplete_proof_never_allows_retry(prepared, contents): + path, expected = prepared + if contents is None: + path.unlink() + else: + path.write_text(contents) + assert not attempts.can_retry_attempt(path, expected) + with pytest.raises((OSError, ValueError)): + attempts.mark_mutation_possible(job_id='job-a') + + +@pytest.mark.parametrize('name,value', [('DXPART_BATCH_SESSION_ID', 'old'), + ('DXPART_BATCH_GENERATION', '2'), ('DXPART_ATTEMPT_ID', '0' * 32), + ('DXPART_TASK_ID', 'old'), ('DXPART_JOB_ID', 'old')]) +def test_marker_blocks_stale_process_identity(prepared, monkeypatch, name, value): + path, _ = prepared + monkeypatch.setenv(name, value) + with pytest.raises(ValueError): + attempts.mark_mutation_possible(job_id='job-a') + assert attempts.read_attempt(path)['state'] == 'prepared' + + +def test_marker_fsync_failure_blocks_caller_without_publishing_mutation(prepared, monkeypatch): + path, _ = prepared + def fail(_): + raise OSError('durability failed') + monkeypatch.setattr(os, 'fsync', fail) + with pytest.raises(OSError, match='durability failed'): + attempts.mark_mutation_possible(job_id='job-a') + assert json.loads(path.read_text())['state'] == 'prepared' + + +def test_legacy_no_environment_remains_supported(monkeypatch): + for name in tuple(os.environ): + if name.startswith('DXPART_') and ('ATTEMPT' in name or 'BATCH_' in name): + monkeypatch.delenv(name) + assert attempts.mark_mutation_possible() is None + + +def test_blank_batch_path_is_not_legacy(monkeypatch): + monkeypatch.setenv('DXPART_ATTEMPT_FILE', '') + with pytest.raises(ValueError): + attempts.mark_mutation_possible() + + +def test_preparation_is_durable_before_return(tmp_path, monkeypatch): + fsynced = [] + real_fsync = os.fsync + def fsync(fd): + fsynced.append(True) + return real_fsync(fd) + monkeypatch.setattr(os, 'fsync', fsync) + path = tmp_path / 'attempt.json' + first = attempts.prepare_attempt(path, session_id='s', generation=1, + task_id='t', job_id='j', project_path=tmp_path / 'board.prj') + assert fsynced and attempts.read_attempt(path)['state'] == 'prepared' + second = attempts.prepare_attempt(tmp_path / 'second.json', session_id='s', generation=1, + task_id='t', job_id='j', project_path=tmp_path / 'board.prj') + assert first['attempt_id'] != second['attempt_id'] + + +def test_reused_worker_marks_each_logical_job(tmp_path, monkeypatch): + directory = tmp_path / 'attempt' + for job in ('job-a', 'job-b'): + attempts.prepare_attempt(directory / f'{job}.json', session_id='session-a', generation=1, + task_id='task-a', job_id=job, project_path=tmp_path / 'board.prj', attempt_id='a' * 32) + monkeypatch.setenv('DXPART_ATTEMPT_FILE', str(directory)) + monkeypatch.setenv('DXPART_BATCH_SESSION_ID', 'session-a') + monkeypatch.setenv('DXPART_BATCH_GENERATION', '1') + monkeypatch.setenv('DXPART_ATTEMPT_ID', 'a' * 32) + for job in ('job-a', 'job-b'): + attempts.mark_mutation_possible(job_id=job, task_id='task-a', project_path=tmp_path / 'board.prj') + assert attempts.read_attempt(directory / f'{job}.json')['state'] == 'mutation_possible' + + +def test_native_guard_binds_snapshot_to_command_and_current_attempt(prepared, tmp_path): + from dx_productivity.trial_task_center.native_helper import mark_snapshot_mutation + path, _ = prepared + snapshot = tmp_path / 'snapshot-job-a.tsv' + snapshot.write_text(f'M\t{tmp_path / "board.prj"}\tOLD\tNEW\tsheet:1\nC\tu1\tR1\t0\t0\t0\t0\t0\n') + (tmp_path / 'command.tsv').write_text('task_id\tjob_id\tproject_path\n' + f'task-a\tjob-a\t{tmp_path / "board.prj"}\n') + assert mark_snapshot_mutation(snapshot)['state'] == 'mutation_possible' + assert attempts.read_attempt(path)['state'] == 'mutation_possible' + + +def test_native_guard_rejects_other_project_before_marking(prepared, tmp_path): + from dx_productivity.trial_task_center.native_helper import mark_snapshot_mutation + path, _ = prepared + snapshot = tmp_path / 'snapshot-job-a.tsv' + snapshot.write_text(f'M\t{tmp_path / "other.prj"}\tOLD\tNEW\tsheet:1\nC\tu1\tR1\t0\t0\t0\t0\t0\n') + (tmp_path / 'command.tsv').write_text('task_id\tjob_id\tproject_path\n' + f'task-a\tjob-a\t{tmp_path / "board.prj"}\n') + with pytest.raises(ValueError): + mark_snapshot_mutation(snapshot) + assert attempts.read_attempt(path)['state'] == 'prepared' + + +def test_marker_cli_fails_closed_on_stale_job(prepared): + from dx_productivity.trial_task_center.application import main + path, record = prepared + assert main(['--mark-batch-attempt', '--attempt-job', 'other', '--attempt-task', 'task-a', + '--attempt-project', record['project_path']]) == 1 + assert attempts.read_attempt(path)['state'] == 'prepared' + + +def test_native_failure_does_not_reuse_previous_attempt_transaction(prepared, tmp_path, monkeypatch): + from dx_productivity.trial_task_center import native_helper as native + path, _ = prepared + snapshot = tmp_path / 'snapshot-job-a.tsv' + snapshot.write_text(f'M\t{tmp_path / "board.prj"}\tOLD\tNEW\tsheet:1\nC\tu1\tR1\t0\t0\t0\t0\t0\n') + (tmp_path / 'command.tsv').write_text('task_id\tjob_id\tproject_path\n' + f'task-a\tjob-a\t{tmp_path / "board.prj"}\n') + report_path = tmp_path / 'snapshot-job-a.tsv.native.json' + report_path.write_text(json.dumps({'stage': 'native_replace_started', + 'transaction': {'old': 'unrelated'}, 'batch_attempt': {'attempt_id': 'old'}})) + def unavailable_cad(snapshot, report): + raise RuntimeError('CAD unavailable before mutation') + monkeypatch.setattr(native, 'run_native', unavailable_cad) + assert native.run(snapshot) == 1 + report = json.loads(report_path.read_text()) + assert report['stage'] == 'preflight' and 'transaction' not in report + assert report['batch_attempt']['job_id'] == 'job-a' + assert attempts.read_attempt(path)['state'] == 'prepared' diff --git a/tests/v1_1/test_batch_attempt_vbs.py b/tests/v1_1/test_batch_attempt_vbs.py new file mode 100644 index 0000000..8e6c3d2 --- /dev/null +++ b/tests/v1_1/test_batch_attempt_vbs.py @@ -0,0 +1,60 @@ +import json +from pathlib import Path +import sys + +import pytest + +from test_accuracy_vbs_guards import run_vbs +from dx_productivity.trial_task_center.batch_attempt import prepare_attempt + + +@pytest.mark.parametrize('fault', ['', 'missing', 'stale', 'wrong-project', 'missing-path']) +def test_vbs_guard_prevents_property_write_without_durable_current_proof(tmp_path, monkeypatch, fault): + root = Path(__file__).resolve().parents[2] + monkeypatch.setenv('PYTHONPATH', str(root / 'src')) + directory = tmp_path / 'attempt' + record_path = directory / 'job-a.json' + record = prepare_attempt(record_path, session_id='session-a', generation=1, + task_id='task-a', job_id='job-a', project_path=tmp_path / 'board.prj') + monkeypatch.setenv('DXPART_ATTEMPT_FILE', str(directory)) + monkeypatch.setenv('DXPART_BATCH_SESSION_ID', 'session-a') + monkeypatch.setenv('DXPART_BATCH_GENERATION', '1') + monkeypatch.setenv('DXPART_ATTEMPT_ID', '0' * 32 if fault == 'stale' else record['attempt_id']) + if fault == 'missing': + record_path.unlink() + if fault == 'missing-path': + monkeypatch.delenv('DXPART_ATTEMPT_FILE') + monkeypatch.delenv('DXPART_BATCH_GENERATION') + monkeypatch.delenv('DXPART_ATTEMPT_ID') + project = tmp_path / ('other.prj' if fault == 'wrong-project' else 'board.prj') + output = run_vbs(tmp_path, ['QPMarkBatchMutation'], ''' +Dim Command, Attr, Failure +Set Command = CreateObject("Scripting.Dictionary") +Command.Add "job_id", "job-a": Command.Add "task_id", "task-a" +Command.Add "project_path", "''' + str(project) + '''" +Set Attr = New PropertySink +On Error Resume Next +GuardedWrite Command, Attr +Failure = Err.Number +On Error GoTo 0 +WScript.Echo CStr(Failure <> 0) +WScript.Echo Attr.Value +''', ''' +Dim QP_HelperExecutable, QP_HelperScript, QP_Fso +Set QP_Fso = CreateObject("Scripting.FileSystemObject") +QP_HelperExecutable = "''' + sys.executable + '''" +QP_HelperScript = "''' + str(root / 'src/dx_productivity/trial_task_center/application.py') + '''" +Class PropertySink + Public Value + Private Sub Class_Initialize + Value = "unchanged" + End Sub +End Class +Sub GuardedWrite(ByRef Command, ByRef Attr) + QPMarkBatchMutation Command + Attr.Value = "changed" +End Sub +''') + assert output.splitlines() == (['False', 'changed'] if not fault else ['True', 'unchanged']) + if not fault: + assert json.loads(record_path.read_text())['state'] == 'mutation_possible'