fix: complete issue17 cleanup and bounded native verification

This commit is contained in:
阿白叔 committed 2026-11-18 19:13:49 +08:00
1 parent 14cacb1d1c
commit 07eab61695
12 files changed
+642 -26

No files matched your search

+38 -1
View File
@@ -44,6 +44,18 @@ def _cancel_target(snapshot):
from .dialog_rules import pcb_version_choice
if exact_prompt(snapshot):
return 'read_write_access', next(c for c in snapshot.controls if c.control_id == 7)
text = ' '.join(' '.join(c.name for c in snapshot.controls
if c.class_name == 'Static').split())
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
if (snapshot.window_class == '#32770' and snapshot.title == 'Expedition PCB'
and text == ('Problem encountered while opening one of the database files. '
'See PCBLogFile.txt for details. Loading of the job has failed. '
'Do you wish to view the log file now?')
and {c.control_id for c in buttons} == {6, 7}
and len(buttons) == 2):
no = next(c for c in buttons if c.control_id == 7)
if no.enabled:
return 'database_load_log', no
if pcb_version_choice(snapshot) is not None:
buttons = [c for c in snapshot.controls if c.class_name == 'Button']
cancel = [c for c in buttons if c.control_id == 2 and c.name == 'Cancel' and c.enabled]
@@ -62,6 +74,31 @@ def _tip_target(snapshot):
return target if target is not None and target.class_name == 'Button' else None
def _database_log_declined(root, pcb_pid):
"""The supervisor can dismiss this exact failed-open question before cleanup."""
from dataclasses import fields
from .dialog_models import WindowSnapshot
path = root/'dialogs.jsonl'
try:
if path.stat().st_size > 1024*1024:
return False
for line in path.read_text(encoding='utf-8').splitlines():
record = json.loads(line)
if (record.get('pid') != pcb_pid or record.get('phase') != 'PCB_STARTING'
or record.get('error_code') != 'MENTOR_DATABASE_LOAD_FAILED'
or record.get('action') != 'acknowledge_fatal'
or record.get('accepted_control') != [7]):
continue
snapshot = WindowSnapshot.from_record({f.name:record[f.name]
for f in fields(WindowSnapshot) if f.name in record})
target = _cancel_target(snapshot)
if target is not None and target[0] == 'database_load_log':
return True
except (OSError, ValueError, TypeError, KeyError):
pass
return False
def cancelled_prewrite_startup(job, pcb_pid=None):
"""Positive ordinary pre-document cancellation proof; absence of Save is insufficient."""
from .session_record import IDENTITY_KEYS, read_session_record
@@ -150,7 +187,7 @@ def close_failed_startup(job, pcb_pid, *, baseline_pids=(), emit=lambda **event:
sent = False
declined_hwnd = None
declined_kind = None
cancelled_open = False
cancelled_open = _database_log_declined(root, pcb_pid)
dismissed_tips = set()
close_handle = None
close_identity = None
+1 -1
View File
@@ -911,7 +911,7 @@ def execute_job(job, emit):
pass
if helper is not None and helper.poll() is None:
emit(stage='save_helper_retained', helper_pid=helper.pid)
elif helper is not None:
elif helper is not None and not completed:
# A failed/truncated Save result never authorizes discard-close.
emit(stage='save_result_retained', detail='保存或关闭结果不完整,保留原生会话供核对')
elif diagnostic_close_attempted:
+20 -8
View File
@@ -1,6 +1,6 @@
Option Explicit
Dim app, doc, pi, licensing, token, expected, attempt, stable, measuredStart, operationOK, remaining
Dim nativeError, nativeDescription
Dim nativeError, nativeDescription, actualProject, actualDocument, expectedDocument, savedState
WaitForStartGate
CheckCancellation
expected = WScript.Arguments(0)
@@ -79,13 +79,25 @@ If Not stable Then
WScript.Quit 7
End If
WScript.Echo "POST_SAVE_SYNCHRONIZED"
On Error Resume Next
operationOK = doc.IsSaved() And LCase(pi.ProjectFile) = LCase(expected)
If WScript.Arguments.Count > 1 Then operationOK = operationOK And LCase(doc.Name) = LCase(WScript.Arguments(1))
nativeError = Err.Number
nativeDescription = Err.Description
Err.Clear
On Error GoTo 0
expectedDocument = ""
If WScript.Arguments.Count > 1 Then expectedDocument = WScript.Arguments(1)
For attempt = 1 To 10
On Error Resume Next
savedState = doc.IsSaved()
actualProject = pi.ProjectFile
actualDocument = ""
If expectedDocument <> "" Then actualDocument = doc.Name
nativeError = Err.Number
nativeDescription = Err.Description
Err.Clear
On Error GoTo 0
WScript.Echo "POST_SAVE_IDENTITY|project=" & actualProject & "|expected=" & expected & "|document=" & actualDocument & "|expected_document=" & expectedDocument
WScript.Echo "POST_SAVE_STATE|saved=" & CStr(savedState) & "|attempt=" & CStr(attempt) & "|error=" & CStr(nativeError)
operationOK = savedState And LCase(actualProject) = LCase(expected) And LCase(actualDocument) = LCase(expectedDocument)
If operationOK Or nativeError <> 0 Then Exit For
If LCase(actualProject) <> LCase(expected) Or LCase(actualDocument) <> LCase(expectedDocument) Then Exit For
WScript.Sleep 200
Next
If nativeError <> 0 Or Not operationOK Then
WScript.Echo "POST_SAVE_FAILED|" & CStr(nativeError) & "|identity_or_saved_state_unconfirmed|" & nativeDescription
WScript.Quit 8
+21 -10
View File
@@ -407,6 +407,7 @@ class MainWindow(QWidget):
elif not any(other.lease is job.lease for other in self._jobs.values()):
self._close_path_lease(job.lease)
if self._job_current(job): self._finished()
else: self._update()
def _release_library_lease(self):
lease, self.library_lease = self.library_lease, None
@@ -509,8 +510,8 @@ class MainWindow(QWidget):
'请选择一个当前可见的非 READY CBB。' if native_target is None else '')
self.native_repair_button.setToolTip(reason or '打开原生工具;请在其中手动选择 Repair。')
ready = ready and not self._native_backup_same_library()
self.batch_button.setEnabled(ready and bool(self._eligible_names()))
self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True)))
self.batch_button.setEnabled(ready and bool(self._eligible_names(require_status=True)))
self.selected_batch_button.setEnabled(ready and bool(self._eligible_names(checked_only=True, require_status=True)))
self.icdb_repair_button.setEnabled(ready and not self._icdb_active() and bool(self._maintenance_names()))
self.icdb_stop_button.setEnabled(self._icdb_active() and not self.icdb_task.stop.is_set())
self.backup_restore_button.setEnabled(ready and bool(
@@ -547,8 +548,11 @@ class MainWindow(QWidget):
self.timeout_spin, self.advanced_toggle, self.advanced_panel):
widget.setEnabled(not self._closing)
counts = self.visible_counts()
unknown = sum(r.status == 'UNKNOWN' for r in self.visible_records())
pending = sum(r.status == 'PENDING' for r in self.visible_records())
self.counts_label.setText(f'可见 {counts["visible"]} / {len(self._records_by_name)} · '
f'READY {counts["ready"]} · 异常/待确认 {counts["error"]}')
f'READY {counts["ready"]} · 待验证 {pending} · 待读取 {unknown} · '
f'异常 {counts["error"]}')
directory, native, missing = self._read_counts
if directory is not None:
self.counts_label.setText(self.counts_label.text() +
@@ -956,12 +960,13 @@ class MainWindow(QWidget):
def visible_counts(self):
records = self.visible_records()
return {'visible': len(records), 'ready': sum(r.status == 'READY' for r in records),
'error': sum(r.status not in {'READY', 'PENDING'} or r.name in self.skipped_names
'error': sum(r.status not in {'READY', 'PENDING', 'UNKNOWN'} or r.name in self.skipped_names
for r in records)}
def _eligible_names(self, *, checked_only=False):
def _eligible_names(self, *, checked_only=False, require_status=False):
records = self.selected_records() if checked_only else self.visible_records()
return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names]
return [r.name for r in records if r.status != 'READY' and r.name not in self.skipped_names
and (not require_status or self.catalog_reader is None or r.status == 'PENDING')]
def _maintenance_names(self):
records = self.selected_records() or self.visible_records()
@@ -1435,7 +1440,9 @@ class MainWindow(QWidget):
result = LibraryReadResult(tuple(records), directory_count=len(directories), native_count=len(native),
missing_project_count=sum(name in native for name in reasons), catalog_verified=True)
return result, reasons, lease, library, False
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context))
# Full-library status and preflight follow native catalog IO; ten seconds
# is not enough even on a local 364-entry library. Keep one bounded task.
worker = ServiceWorker(lambda:self.native_queue.run(reconcile, context=context, timeout_seconds=120))
self._lifecycle_workers.add(worker)
def completed(payload):
if self._job_current(read_job): deliver(payload)
@@ -1480,10 +1487,10 @@ class MainWindow(QWidget):
return [record.name for record in self.selected_records()]
def verify_selected(self):
self._confirm_verify(self._eligible_names(checked_only=True))
self._confirm_verify(self._eligible_names(checked_only=True, require_status=True))
def verify_all(self):
self._confirm_verify(self._eligible_names())
self._confirm_verify(self._eligible_names(require_status=True))
def _confirm_verify(self, names):
from .backup_notice import MANUAL_BACKUP_NOTICE
@@ -1709,7 +1716,7 @@ class MainWindow(QWidget):
if self._native_backup_same_library():
self.status_label.setText('请先关闭该库的版本与备份窗口。')
return
eligible = set(self._maintenance_names() if maintenance else self._eligible_names())
eligible = set(self._eligible_names(require_status=True))
names = [name for name in names if name in eligible]
if not names:
self.status_label.setText('当前可见选择中没有可校验的非 READY CBB。')
@@ -1757,6 +1764,10 @@ class MainWindow(QWidget):
if statuses.get(req.block_name) == 'NOT_REGISTERED':
from cbb_refresh_verify.verify_runner import VerifyResult
return VerifyResult('SKIPPED', stderr='仅发现目录,原生目录未登记此 CBB。')
if statuses.get(req.block_name) != 'PENDING':
from cbb_refresh_verify.verify_runner import VerifyResult
return VerifyResult('SKIPPED', error_category='STATUS_UNCONFIRMED',
error_stage='admission', stderr='STATUS_UNCONFIRMED: 当前状态未确认,未启动校验;请重新读取。')
if maintenance:
self._emit_job(job, 'event', {'block': req.block_name, 'stage': 'icdb_check_start'})
return verify(req)
+53 -2
View File
@@ -670,6 +670,46 @@ def _run_verify_task(request, *, progress=None, flag_reader=None, process_runner
request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
facts = result.write_outcome or {}
if (not request.diagnostic_only and not request.auto_repair and request.post_repair_proof is None
and result.status == 'FAIL' and result.safe_to_continue and result.evidence_path
and result.library_flag == 'NOT_GREEN' and result.error_stage == 'library_flag'
and result.error_category == 'MENTOR_VERIFY_NOT_COMMITTED'
and all(facts.get(key) == value for key, value in (
('save_state','COMMITTED'), ('close_state','CLOSED'), ('helper_state','EXITED'),
('resource_state','RELEASED'), ('interrupted',False)))
and not (stop is not None and stop.is_set())):
# A new reusable design can save its Work data on the first open,
# then publish Cert on the next native Save. Never retry an open/write failure.
followup_path = result.evidence_path.with_name('commit-followup.json')
followup = dict(kind='NATIVE_COMMIT_FOLLOWUP', status='STARTED',
library=str(request.lmc_file), block=request.block_name, max_additional_runs=1,
original_evidence=str(result.evidence_path))
initial_seconds = result.timings_seconds.get('total', 0.0)
release_confirmed = True # Completed first run stays releasable until the next native attempt.
try:
followup_path.write_text(json.dumps(followup, ensure_ascii=False, indent=2), encoding='utf-8')
except OSError as error:
_notify_progress(progress, {'stage':'commit_followup_unavailable', 'block':request.block_name,
'detail':str(error)})
else:
check_active()
_notify_progress(progress, {'stage':'commit_followup', 'block':request.block_name,
'detail':'原生已保存关闭并释放,但 READY 尚未提交;补充一次原生校验。'})
check_active()
release_confirmed = False
result = _run_verify_serialized(request, progress=progress, flag_reader=flag_reader,
process_runner=process_runner, port_check=port_check,
dialog_supervisor_factory=dialog_supervisor_factory, version_prompt=version_prompt, stop=stop)
followup.update(status='READY' if result.status == 'PASS' and result.library_flag == 'GREEN'
and result.safe_to_continue else 'UNCONFIRMED', final_evidence=str(result.evidence_path or ''))
_write_optional_evidence(followup_path, followup)
second_seconds = result.timings_seconds.get('total', 0.0)
result = replace(result, recovery_attempts=(*result.recovery_attempts, followup),
timings_seconds={**result.timings_seconds, 'initial_verify':initial_seconds,
'commit_followup':second_seconds, 'total':initial_seconds+second_seconds})
if result.evidence_path:
_write_optional_evidence(result.evidence_path, {'block_name':request.block_name, **asdict(result)})
if (request.auto_repair and result.status not in {'TIMEOUT', 'BLOCKED'}
and result.error_category == 'ICDB_REPAIR_REQUIRED'
and result.evidence_path):
@@ -1476,10 +1516,21 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
stop=stop, context=context) # noqa: E731
results = []
queue_stop = False
retained_libraries = set()
retained_libraries = {}
for request in requests:
from .operation_queue import request_library_keys
library_keys = request_library_keys(request, context)
for index in {retained_libraries[key][1] for key in library_keys.intersection(retained_libraries)}:
previous = next(value[0] for value in retained_libraries.values() if value[1] == index)
if queue_stop or stop is not None and stop.is_set():
break
if not results[index].evidence_path:
continue
from .operation_lifecycle import recheck_failed_release
refreshed = recheck_failed_release(previous.lmc_file, previous.block_name, results[index], stop=stop)
if refreshed.safe_to_continue:
results[index] = refreshed
retained_libraries = {k:v for k,v in retained_libraries.items() if v[1] != index}
if (queue_stop or stop is not None and stop.is_set()
or context is not None and context.stop.is_set()):
result = VerifyResult('SKIPPED', stderr='队列已停止,未操作此 CBB')
@@ -1503,7 +1554,7 @@ def run_batch(requests, max_workers=1, verifier=None, *, stop=None, progress=Non
results.append(result)
# Never start another writer after an unconfirmed native shutdown.
if not result.safe_to_continue:
retained_libraries.update(library_keys)
retained_libraries.update({key:(request, len(results)-1) for key in library_keys})
queue_stop = queue_stop or result.status in {'QUEUE_STOP', 'CANCELLED'}
if queue_stop and stop is not None:
stop.set()