fix(execution): bind explicit target cells to native save and recovery
This commit is contained in:
1 parent
976a72d572
commit
bb506a3550
7 files changed
+356
-20
No files matched your search
@@ -61,13 +61,53 @@ def snapshot_sha256(path):
|
||||
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_count=1):
|
||||
def snapshot_target_cell(path, *, required=True):
|
||||
rows = [line.split("\t") for line in Path(path).read_text(encoding="utf-8-sig").splitlines()
|
||||
if line.split("\t", 1)[0] == "L"]
|
||||
if not rows and not required:
|
||||
return None
|
||||
if len(rows) != 1 or len(rows[0]) != 2:
|
||||
raise ValueError("Snapshot requires one explicit target Cell selection")
|
||||
value = decode(rows[0][1])
|
||||
if not value or value != value.strip() or any(ord(c) < 32 for c in value):
|
||||
raise ValueError("Snapshot target Cell selection is empty or invalid")
|
||||
return value
|
||||
|
||||
|
||||
def target_cell_catalog(app, snapshot, metadata, selected):
|
||||
raw_path = str(app.GetProjectData().CentralLibraryPath)
|
||||
library = Path(raw_path)
|
||||
if not raw_path.strip() or not library.is_absolute():
|
||||
raise ValueError("Active project has no absolute central library path for Cell validation")
|
||||
return cell_catalog_binding(library, metadata[3], selected, Path(snapshot).parent.parent / "cell-catalog")
|
||||
|
||||
|
||||
def cell_catalog_binding(library, part_number, selected, evidence_root):
|
||||
from .cell_catalog import read_library_cell_catalog
|
||||
|
||||
catalog = read_library_cell_catalog(library, part_number, evidence_root)
|
||||
if catalog.library_path.resolve() != library.resolve() or catalog.part_number != part_number:
|
||||
raise ValueError("Cell catalog does not match the active project and target part")
|
||||
names = [cell.name for cell in catalog.cells]
|
||||
if len(names) != len(set(names)) or names.count(selected) != 1:
|
||||
raise ValueError("Selected target Cell is unavailable or ambiguous in the actual project library")
|
||||
return {
|
||||
"library_path": str(library.resolve()),
|
||||
"source_fingerprint": catalog.source_fingerprint,
|
||||
"part_partition": catalog.part_partition,
|
||||
"part_number": catalog.part_number,
|
||||
"cells": sorted([[cell.partition, cell.name] for cell in catalog.cells]),
|
||||
"selected": selected,
|
||||
}
|
||||
|
||||
|
||||
def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_count=1, *, cell_catalog=None):
|
||||
if len(library_row) < 6 or not str(library_row[4]).strip() or not str(library_row[5]).strip():
|
||||
raise ValueError("Library target has incomplete identity fields")
|
||||
slots = int(slot_count)
|
||||
if slots < 1:
|
||||
raise ValueError("Library target has no valid slots")
|
||||
return {
|
||||
result = {
|
||||
"snapshot_sha256": snapshot_sha256(snapshot),
|
||||
"project_path": os.path.normcase(os.path.abspath(metadata[1])),
|
||||
"sheet_identity": metadata[4],
|
||||
@@ -79,6 +119,14 @@ def transaction_binding(snapshot, metadata, records, library_row, symbol, slot_c
|
||||
"target_symbol": str(symbol),
|
||||
"slot_count": slots,
|
||||
}
|
||||
cell = snapshot_target_cell(snapshot, required=False)
|
||||
if cell is not None:
|
||||
result["target_cell"] = cell
|
||||
if cell_catalog is not None:
|
||||
if cell_catalog.get("selected") != cell or cell_catalog.get("part_partition") != str(library_row[0]):
|
||||
raise ValueError("Native library row differs from authoritative Cell catalog")
|
||||
result["cell_catalog"] = cell_catalog
|
||||
return result
|
||||
|
||||
|
||||
def require_resumable_transaction(snapshot, report, metadata, records):
|
||||
@@ -99,6 +147,9 @@ def require_resumable_transaction(snapshot, report, metadata, records):
|
||||
"source_uids": sorted(row[1] for row in records),
|
||||
"target_selectors": metadata[9] if len(metadata) == 10 else None,
|
||||
}
|
||||
cell = snapshot_target_cell(snapshot, required=False)
|
||||
if cell is not None:
|
||||
expected["target_cell"] = cell
|
||||
if not isinstance(binding, dict) or any(binding.get(key) != value for key, value in expected.items()):
|
||||
raise ValueError("Native replacement evidence does not match this snapshot")
|
||||
library_row = binding.get("library_row")
|
||||
@@ -452,9 +503,11 @@ def run_native(snapshot, report):
|
||||
from pywinauto import Desktop
|
||||
|
||||
metadata, records = read_snapshot(snapshot)
|
||||
target_cell = snapshot_target_cell(snapshot)
|
||||
require_part_label = snapshot_value_mode(metadata) == "part_label"
|
||||
app, api = attach()
|
||||
check_active_context(app, metadata)
|
||||
cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell)
|
||||
components = components_on_sheet(app, api)
|
||||
wanted = {row[1] for row in records}
|
||||
if len(metadata) == 10:
|
||||
@@ -466,6 +519,8 @@ def run_native(snapshot, report):
|
||||
}
|
||||
if source_uids != wanted:
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, records)
|
||||
if binding.get("cell_catalog") != cell_proof:
|
||||
raise ValueError("Current Cell catalog differs from recorded native transaction")
|
||||
report["replaced_uids"] = existing_replacement_uids(
|
||||
components, records, metadata[3], binding, require_part_label=require_part_label
|
||||
)
|
||||
@@ -634,7 +689,11 @@ def run_native(snapshot, report):
|
||||
if read_target() != ready:
|
||||
raise ValueError('Native target changed during final context verification')
|
||||
symbol = ready[1]
|
||||
report["transaction"] = transaction_binding(snapshot, metadata, records, columns, symbol, slot_count)
|
||||
current_cell_proof = target_cell_catalog(app, snapshot, metadata, target_cell)
|
||||
if current_cell_proof != cell_proof:
|
||||
raise ValueError("Cell catalog changed before native replacement; no replacement submitted")
|
||||
report["transaction"] = transaction_binding(snapshot, metadata, records, columns, symbol, slot_count,
|
||||
cell_catalog=cell_proof)
|
||||
report["stage"] = "native_replace_started"
|
||||
save_report(snapshot, report)
|
||||
click(dlg_item(dialog, 1695))
|
||||
|
||||
@@ -275,7 +275,7 @@ class QuickRunPreparer:
|
||||
command_lines = handoff.command_path.read_text(encoding='utf-8-sig').splitlines()
|
||||
job_column = command_lines[0].split('\t').index('job_id')
|
||||
target_command_rows = ({line.split('\t')[job_column]: line for line in command_lines[1:] if line}
|
||||
if 'target_scope' in command_lines[0].split('\t') else {})
|
||||
if {'target_scope', 'target_cell'} & set(command_lines[0].split('\t')) else {})
|
||||
return QuickRunBatchSession(
|
||||
task_id,
|
||||
_value_mode(copy_part_number_to_value),
|
||||
@@ -765,6 +765,7 @@ class QuickRunPreparer:
|
||||
for rule in rules:
|
||||
_validate_field(rule.old_part_number, "old part number")
|
||||
_validate_field(rule.new_part_number, "new part number")
|
||||
_validate_field(str(getattr(rule, "target_cell", "")), "target Cell")
|
||||
if bool(getattr(rule, "custom_value_enabled", False)):
|
||||
custom_value = str(getattr(rule, "custom_value", ""))
|
||||
_validate_field(custom_value, "custom Value")
|
||||
@@ -1410,6 +1411,11 @@ def _queue_matches_inputs(
|
||||
rules: tuple[RuleRecord, ...],
|
||||
) -> bool:
|
||||
base_mode = _queue_value_mode(command_path)
|
||||
cells = _read_command_cells(command_path)
|
||||
actual_cells = {cells.get(command[1], "") for command in commands}
|
||||
expected_cells = {str(getattr(rule, "target_cell", "")) for rule in rules}
|
||||
if actual_cells != expected_cells:
|
||||
return False
|
||||
if "target_scope" in command_path.read_text(encoding="utf-8-sig").splitlines()[0].split("\t"):
|
||||
sheets = _read_command_sheet_targets(command_path)
|
||||
manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects) if sheets is not None else None
|
||||
@@ -1425,26 +1431,26 @@ def _queue_matches_inputs(
|
||||
expected = tuple(
|
||||
(
|
||||
str(project.path), rule.old_part_number, rule.new_part_number,
|
||||
*_rule_command_options(rule, base_mode)[:3],
|
||||
*_rule_command_options(rule, base_mode)[:3], str(getattr(rule, "target_cell", "")),
|
||||
)
|
||||
for project in projects
|
||||
for rule in rules
|
||||
)
|
||||
return tuple((*command[2:], *options[command[1]][:3]) for command in commands) == expected
|
||||
return tuple((*command[2:], *options[command[1]][:3], cells.get(command[1], "")) for command in commands) == expected
|
||||
if set(sheets) != {command[1] for command in commands} or len(commands) != len(sheets):
|
||||
return False
|
||||
manifest = _read_sheet_manifest(command_path.with_name("sheets.tsv"), projects)
|
||||
expected = tuple(
|
||||
(
|
||||
str(project.path), schematic_name, sheet_number, rule.old_part_number, rule.new_part_number,
|
||||
*_rule_command_options(rule, base_mode)[:3],
|
||||
*_rule_command_options(rule, base_mode)[:3], str(getattr(rule, "target_cell", "")),
|
||||
)
|
||||
for project in projects
|
||||
for schematic_name, sheet_number in manifest[_path_key(project.path)]
|
||||
for rule in rules
|
||||
)
|
||||
actual = tuple(
|
||||
(command[2], *sheets[command[1]], command[3], command[4], *options[command[1]][:3])
|
||||
(command[2], *sheets[command[1]], command[3], command[4], *options[command[1]][:3], cells.get(command[1], ""))
|
||||
for command in commands
|
||||
)
|
||||
return actual == expected
|
||||
@@ -1808,6 +1814,31 @@ def _queue_value_mode(path: Path) -> str:
|
||||
raise TaskCenterError("quick_run_command", "queue Value policy is invalid") from error
|
||||
|
||||
|
||||
def _read_command_cells(path: Path) -> dict[str, str]:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
header = lines[0].split("\t")
|
||||
if "target_cell" not in header:
|
||||
return {}
|
||||
if header.count("target_cell") != 1 or header.count("job_id") != 1:
|
||||
raise ValueError("duplicate Cell header")
|
||||
result = {}
|
||||
for line in lines[1:]:
|
||||
if not line:
|
||||
continue
|
||||
fields = line.split("\t")
|
||||
if len(fields) != len(header):
|
||||
raise ValueError("Cell field count")
|
||||
job = fields[header.index("job_id")]
|
||||
cell = _decode_vbs_field(fields[header.index("target_cell")])
|
||||
if not job or job in result or cell != cell.strip() or any(ord(c) < 32 for c in cell):
|
||||
raise ValueError("invalid Cell option")
|
||||
result[job] = cell
|
||||
return result
|
||||
except (OSError, UnicodeError, IndexError, ValueError) as error:
|
||||
raise TaskCenterError("quick_run_command", "queue target Cell options are invalid") from error
|
||||
|
||||
|
||||
def _read_command_options(path: Path) -> dict[str, tuple[str, str, bool, str]]:
|
||||
try:
|
||||
lines = path.read_text(encoding="utf-8-sig").splitlines()
|
||||
@@ -1871,6 +1902,9 @@ def _command_text(
|
||||
if targeted and sheet_targets is None:
|
||||
raise TaskCenterError("target_scope", "target execution requires sheet-addressed commands")
|
||||
suffix = "\ttarget_scope\ttarget_selectors" if targeted else ""
|
||||
has_cell = any(getattr(rule, "target_cell", "") for rule in rules)
|
||||
if has_cell:
|
||||
suffix += "\ttarget_cell"
|
||||
if sheet_targets is None:
|
||||
rows = ["task_id\tjob_id\tproject_path\told_part\tnew_part\tvalue_mode\tcustom_value\tsync_nc\tbase_value_mode" + suffix]
|
||||
else:
|
||||
@@ -1900,6 +1934,7 @@ def _command_text(
|
||||
f"{rule.old_part_number}\t{rule.new_part_number}\t{rule_mode}\t{custom_value}\t"
|
||||
f"{'1' if sync_nc else '0'}\t{base_mode}"
|
||||
+ (f"\t{scope}\t{selectors}" if targeted else "")
|
||||
+ ("\t" + _encode_vbs_field(str(getattr(rule, "target_cell", ""))) if has_cell else "")
|
||||
)
|
||||
job_index += 1
|
||||
return "\r\n".join(rows) + "\r\n"
|
||||
|
||||
@@ -12,13 +12,14 @@ import subprocess
|
||||
from uuid import uuid4
|
||||
|
||||
from .errors import TaskCenterError
|
||||
from .native_helper import read_snapshot, require_resumable_transaction
|
||||
from .native_helper import read_snapshot, require_resumable_transaction, snapshot_target_cell, cell_catalog_binding
|
||||
from .quick_run import (
|
||||
TERMINAL_STATES, IDLE_PROGRESS_TIMEOUT_SECONDS, QuickRunStepResult,
|
||||
_native_helper_launch_arguments, _next_unfinished_command, _path_key,
|
||||
_queue_matches_inputs, _queue_value_mode, _read_command_sheet_targets,
|
||||
_read_command_options, _read_commands, _read_status_details, _safe_run_token,
|
||||
_value_mode_matches_option, _write_status_details, _write_uncertain_flag, _decode_vbs_field,
|
||||
_read_command_cells, _encode_vbs_field,
|
||||
)
|
||||
from .retention import maintain_quick_run_storage
|
||||
from .schematic_backup import create_schematic_backup
|
||||
@@ -83,6 +84,18 @@ def _recovery_copytree(source: Path, destination: Path) -> None:
|
||||
) from error
|
||||
|
||||
|
||||
def require_current_cell_binding(snapshot, binding, project, metadata):
|
||||
cell = snapshot_target_cell(snapshot)
|
||||
if binding.get('target_cell') != cell or not isinstance(binding.get('cell_catalog'), dict):
|
||||
raise ValueError('Recovery has no bound target Cell catalog')
|
||||
from .cell_catalog import project_library_path
|
||||
library = project_library_path(project)
|
||||
current = cell_catalog_binding(library, metadata[3], cell, snapshot.parent.parent / 'cell-catalog')
|
||||
if current != binding['cell_catalog']:
|
||||
raise ValueError('Recovery target Cell catalog has changed')
|
||||
return current
|
||||
|
||||
|
||||
def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=False, confirmed=False):
|
||||
if not confirmed:
|
||||
raise TaskCenterError('quick_run_recovery_confirmation', '核验恢复需要明确确认,不能作为自动重试执行。')
|
||||
@@ -142,10 +155,14 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
raise ValueError('snapshot target scope missing from command')
|
||||
report = json.loads(snapshot.with_suffix('.tsv.native.json').read_text(encoding='utf-8'))
|
||||
binding = require_resumable_transaction(snapshot, report, metadata, components)
|
||||
selected_cell = _read_command_cells(root / 'command.tsv').get(job_id)
|
||||
if selected_cell != snapshot_target_cell(snapshot):
|
||||
raise ValueError('snapshot target Cell mismatch')
|
||||
cell_proof = require_current_cell_binding(snapshot, binding, Path(selected[2]), metadata)
|
||||
identity = binding['library_row'][4:6]
|
||||
if any(not value or any(character in value for character in '\t\r\n') for value in identity):
|
||||
raise ValueError('invalid library identity')
|
||||
except (OSError, ValueError, KeyError, TypeError) as error:
|
||||
except (OSError, ValueError, KeyError, TypeError, TaskCenterError) as error:
|
||||
raise TaskCenterError('quick_run_recovery', '快照或原生替换证据无法与此任务绑定,保护状态保持不变。') from error
|
||||
if not uncertain.is_file():
|
||||
_write_uncertain_flag(uncertain, 'recovery_in_progress')
|
||||
@@ -191,6 +208,8 @@ def recover(preparer, task_id, projects, rules, *, copy_part_number_to_value=Fal
|
||||
if len(metadata) == 10:
|
||||
header += '\ttarget_scope\ttarget_selectors'
|
||||
row = (*row, 'targets', selectors)
|
||||
header += '\ttarget_cell\trecovery_library_path'
|
||||
row = (*row, _encode_vbs_field(selected_cell), _encode_vbs_field(cell_proof['library_path']))
|
||||
(worker / 'command.tsv').write_text(header + '\n' + '\t'.join(row) + '\n', encoding='utf-8')
|
||||
_write_status_details(worker / 'status.tsv', ())
|
||||
from .quick_run import _vbs_worker_paths
|
||||
|
||||
Reference in new issue
Block a user