fix: address PR review identity and snapshot safety gaps

This commit is contained in:
阿白叔 committed 2026-10-30 17:48:08 +08:00
1 parent 131b6dbbb3
commit f0a0131aac
15 files changed
+312 -64

No files matched your search

@@ -62,7 +62,8 @@ def _force_owned_supervisor(root, journal, process):
"""Persist uncertainty before terminating the exact process/Job we own."""
from .batch_resources import write_record
path = Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json'
if journal.get('force_state') in {'termination_requested', 'confirmed'}:
if (journal.get('force_state') in {'termination_requested', 'confirmed'}
and process.poll() is not None):
return
journal['stop_mode'] = 'forced'
journal.setdefault('force_requested_at', time.time())
@@ -97,6 +98,8 @@ def _retain_supervisor_after_control_error(root, journal, process, control, erro
"""Do not turn a GUI/transport exception into an unconfirmed Job kill."""
from .batch_resources import write_record
control.set()
control.waiting_for_resolution = True
control.resolution_error = str(error)
control.control_error = '控制通信异常,已请求安全停止并保留应用;可导出诊断或明确强制结束:' + str(error)
journal['protect_all_targets'] = True
try:
@@ -108,7 +111,14 @@ def _retain_supervisor_after_control_error(root, journal, process, control, erro
{'version': VERSION, 'batch_id': journal['batch_id'], 'attempt_id': journal['attempt_id']})
except OSError:
pass # Keep ownership; failure to request stop is not permission to kill.
last_notice = time.monotonic()
while True:
if time.monotonic() - last_notice >= 15:
import logging
logging.getLogger(__name__).warning(
'supervisor_retained_waiting_for_resolution batch_id=%s error=%s',
journal['batch_id'], control.control_error)
last_notice = time.monotonic()
if control.force_event.is_set():
try:
_force_owned_supervisor(root, journal, process)
@@ -249,7 +259,19 @@ def _finish_response(root, journal, response, context):
resource = json.loads(resource_path.read_text(encoding='utf-8'))
except FileNotFoundError:
resource = {}
shutdown = resource.get('cad_shutdown') or {}
except (OSError, ValueError, TypeError) as failure:
journal.update(state='blocked', shutdown_record_error=str(failure))
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
raise application_shutdown_error(result, error, primary) from failure
shutdown = resource.get('cad_shutdown') if isinstance(resource, dict) else None
if shutdown is None and isinstance(resource, dict):
shutdown = {}
if (not isinstance(shutdown, dict)
or not isinstance(shutdown.get('cleanup_errors', ()), (list, tuple))
or any(not isinstance(item, dict) for item in shutdown.get('cleanup_errors', ()))):
journal.update(state='blocked', shutdown_record_error='invalid shutdown record shape')
write_record(Path(root) / 'batch-resources' / journal['batch_id'] / 'supervisor.json', journal)
raise application_shutdown_error(result, error, primary)
if (shutdown.get('orderly_shutdown') is False or shutdown.get('forced_termination')
or shutdown.get('diagnostic_errors')
or any(item.get('stage') != 'desktop_release' for item in shutdown.get('cleanup_errors', ()))):
@@ -558,7 +558,7 @@ def replacement_matches(components, records, target, require_part_label, *, libr
if expected_name is not None and (part_name != expected_name
or (expected_label and part_label != expected_label)):
raise ValueError(f'Native replacement does not match the selected target library identity; uid={candidate.UID}')
matches.append(str(candidate.UID))
matches.append(_component_uid(candidate))
if len(set(matches)) != len(records):
raise ValueError("Duplicate replacement association")
return matches
@@ -578,7 +578,7 @@ def verify_replacement_readback(snapshot, components, metadata, records, before_
actual = None if component is None else (
str(component.Refdes), *(attribute_value(component, name)
for name in ('Part Number', 'Value', 'Part Name', 'Part Label')))
if actual != identity:
if actual != identity:
raise ValueError('An unselected component was changed')
verified = replacement_matches(components, records, metadata[3], require_part_label,
library_row=library_row)
@@ -31,6 +31,9 @@ def protect_interruption(root, reason):
# A previous create/write/fsync may have failed. Existence alone does
# not establish durable evidence; preserve its bytes but sync again.
with marker.open('r+b') as existing:
if not existing.read(1):
existing.write(str(reason).encode('utf-8'))
existing.flush()
os.fsync(existing.fileno())
else:
with stream:
@@ -131,8 +131,10 @@ def _atomic_text(path: Path, text: str) -> None:
def _publish_progress(path: Path, snapshot: dict) -> None:
try:
_atomic_text(path, json.dumps(snapshot, ensure_ascii=False))
except OSError:
pass # Display telemetry failure must not terminate a possible CAD write.
except OSError as error:
# Telemetry cannot interrupt a CAD write, but the lost state must remain diagnosable.
import logging
logging.getLogger(__name__).warning('worker_progress_publish_failed path=%s error=%s', path, error)
def _decode(data: bytes) -> str: