fix: reconcile saved database locks without replaying replacements
Core regression / Python core, intervention UI and release configuration (push) Successful in 4m44s
Core regression / JavaScript syntax (push) Successful in 6s
Core regression / Python core, intervention UI and release configuration (pull_request) Successful in 3m57s
Core regression / JavaScript syntax (pull_request) Successful in 6s

This commit is contained in:
阿白叔 committed 2026-11-18 18:24:50 +08:00
1 parent cdbc92fab8
commit e63a82b695
10 files changed
+748 -15

No files matched your search

@@ -19,6 +19,13 @@ LIVE_RESOURCES = {}
class BatchResourceCleanupError(TaskCenterError):
def __init__(self, message, *, completed_result=None, primary_error=None, cleanup_error=None):
original, seen = primary_error, set()
while original is not None and id(original) not in seen:
if getattr(original, 'code', None) in {'saved_source_pending', 'saved_source_changed'}:
message = str(original) + ';资源收尾异常:' + message
break
seen.add(id(original))
original = getattr(original, 'primary_error', None)
super().__init__('batch_resources_pending', message)
self.completed_result = completed_result
self.primary_error = primary_error
@@ -422,8 +422,6 @@ class BatchCadRuntime:
def _checkpoint(self, root, project, attempt_id):
self.cad.checkpoint(root / ('cad-closed-' + attempt_id + '.json'))
key = str(root).casefold()
self.record['checkpoints'][key] = attempt_id
self._save(state='ready')
checkpoint = {'version': 1, 'resource_record': str(self.path),
'session_id': self.session_id, 'generation': self.generation, 'attempt_id': attempt_id,
'evidence_root': str(root), 'project_path': str(project), 'project_closed': True,
@@ -455,7 +453,6 @@ class BatchCadRuntime:
raise WorkerMonitorError('native project commit marker has an invalid outcome')
proof = capture_project_commit(self.root, root, {'session_token': request[0],
'project_path': str(project).casefold(), 'jobs_json': json.dumps(jobs)})
proof = bind_project_commit_source(proof, self.root, root, project)
proof['marker_sha256'] = hashlib.sha256(marker.read_bytes()).hexdigest()
proof['files'].append({'path': str(canonical_path(marker)), 'sha256': proof['marker_sha256']})
readback_names = []
@@ -503,10 +500,29 @@ class BatchCadRuntime:
if saved_only:
proof.update(marker_state='project_saved', saved_only=True, validation_required='saved_netlist_v1',
native_outcomes=dict(rows[1:]), outcomes=dict(rows[1:]))
# Keep the saved marker and attempt evidence before any file-lock wait.
write_record(root / 'project-save-pending.json', dict(checkpoint, project_commit_pending=proof))
proof = bind_project_commit_source(proof, self.root, root, project,
stop_event=self.stop_event, release_mentor=self._release_saved_source_owner if saved_only else None)
checkpoint['project_commit_source'] = proof
write_record(root / 'project-checkpoint.json', checkpoint)
self.record['checkpoints'][key] = attempt_id
self._save()
self._active_attempts = []
def _release_saved_source_owner(self, error):
"""Only a closed project's read handoff may recycle an idle CAD here."""
try:
self.close(rebuilding=True, reason='saved_source_locked')
except Exception as cleanup:
self.record['primary_error'] = {'type': type(error).__name__, 'code': error.code, 'message': str(error)}
try:
self._save()
except Exception as diagnostic:
error.add_note('资源收尾记录写入失败:' + str(diagnostic))
raise BatchResourceCleanupError(str(cleanup), primary_error=error, cleanup_error=cleanup) from cleanup
self.desktop = self.cad = None
def _certify_unlaunched_worker(self, root, project, command, attempt_id, expected, before, inputs, *, failure=None,
worker_creation_rejected=False):
"""Certify no worker was created, using exact launch and release provenance."""
@@ -20,7 +20,7 @@ class ExecutionFeedback:
def wait_reason_for_stage(stage):
return {'save_and_close': 'save', 'verify_saved_project': 'readback',
return {'save_and_close': 'save', 'verify_saved_project': 'readback', 'saved_source_wait': 'readback',
'native_snapshot_read': 'readback', 'capture_semantic_state': 'readback',
'private_shutdown': 'desktop_release',
'awaiting_reconciliation': 'reconciliation', 'mentor_exit': 'mentor_exit',
@@ -160,18 +160,11 @@ def capture_project_commit(data_root, root, commit):
raise TaskCenterError('quick_run_uncertain', '工程统一保存或回读尚未得到完整证明,保留全部暂存项待核验。') from error
def bind_project_commit_source(proof, data_root, root, project):
def bind_project_commit_source(proof, data_root, root, project, *, stop_event=None, release_mentor=None):
"""Capture saved bytes only at the completed native-close callback."""
from .project_session_health import _source_parameters, _source_digest
from .project_isolation import write_sources
value = dict(proof, **_source_parameters(Path(project), data_root))
value['source_sha256'] = _source_digest(value)
value['command_sha256'] = hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest()
value['saved_sources'] = {source: hashlib.sha256(internal_path(source).read_bytes()).hexdigest()
for source in write_sources(project)}
if not value['source_sha256']:
raise TaskCenterError('quick_run_uncertain', '已保存工程源文件无法稳定绑定,保留待核验。')
return value
from .saved_source import bind_sources
return bind_sources(proof, data_root, root, project,
stop_event=stop_event, release_mentor=release_mentor)
def validate_project_commit_source(proof, root):
@@ -0,0 +1,51 @@
"""Read-only Restart Manager observations; never shut down registered applications."""
import ctypes
from ctypes import wintypes as w
import os
from .path_access import strip_extended_prefix
def locking_processes(path):
result = dict(method='windows_restart_manager', processes=[], complete=False)
if os.name != 'nt':
return dict(result, error='unsupported platform')
class UniqueProcess(ctypes.Structure):
_fields_ = [('pid', w.DWORD), ('started', w.FILETIME)]
class ProcessInfo(ctypes.Structure):
_fields_ = [('process', UniqueProcess), ('name', w.WCHAR*256), ('service', w.WCHAR*64),
('type', ctypes.c_int), ('status', w.ULONG), ('session', w.DWORD), ('restartable', w.BOOL)]
session = w.DWORD()
api = ctypes.WinDLL('rstrtmgr')
api.RmStartSession.argtypes = [ctypes.POINTER(w.DWORD), w.DWORD, w.LPWSTR]
api.RmRegisterResources.argtypes = [w.DWORD, w.UINT, ctypes.POINTER(w.LPCWSTR), w.UINT,
ctypes.POINTER(UniqueProcess), w.UINT, ctypes.POINTER(w.LPCWSTR)]
api.RmGetList.argtypes = [w.DWORD, ctypes.POINTER(w.UINT), ctypes.POINTER(w.UINT),
ctypes.POINTER(ProcessInfo), ctypes.POINTER(w.DWORD)]
api.RmEndSession.argtypes = [w.DWORD]
started = False
try:
code = api.RmStartSession(ctypes.byref(session), 0, ctypes.create_unicode_buffer(33))
if code: raise OSError(code, 'RmStartSession')
started = True
files = (w.LPCWSTR*1)(strip_extended_prefix(path))
code = api.RmRegisterResources(session, 1, files, 0, None, 0, None)
if code: raise OSError(code, 'RmRegisterResources')
needed, count, reboot = w.UINT(), w.UINT(), w.DWORD()
code = api.RmGetList(session, ctypes.byref(needed), ctypes.byref(count), None, ctypes.byref(reboot))
for _ in range(3):
if code != 234: break # ERROR_MORE_DATA
count.value = needed.value
items = (ProcessInfo*count.value)()
code = api.RmGetList(session, ctypes.byref(needed), ctypes.byref(count), items, ctypes.byref(reboot))
if code == 0:
result['processes'] = [dict(pid=item.process.pid, name=item.name,
creation_filetime=(item.process.started.dwHighDateTime << 32) | item.process.started.dwLowDateTime)
for item in items[:count.value]]
if code: raise OSError(code, 'RmGetList')
result['complete'] = True # Complete RM result, not an exhaustive kernel-handle scan.
except Exception as error:
result['error'] = str(error)
finally:
if started: api.RmEndSession(session)
return result
@@ -0,0 +1,156 @@
"""Read saved sources after native close, retrying only actual Windows locks."""
import hashlib
import json
import os
from pathlib import Path
import time
from .errors import TaskCenterError
from .file_lock_diagnostics import locking_processes
from .path_access import internal_path
LOCK_WAIT_SECONDS = 3.0
class SavedSourceReadError(TaskCenterError):
def __init__(self, error, path, *, interrupted=False):
self.winerror = getattr(error, 'winerror', None)
self.path = str(path)
self.retryable = self.winerror in (32, 33)
self.interrupted = interrupted
reason = '核验已暂停' if interrupted else '数据库仍被占用' if self.retryable else '源文件读取失败'
super().__init__('saved_source_pending',
f'工程已返回保存,{reason},结果待核验;不会重复替换。文件:{path};Windows 错误码:{self.winerror};{error}')
def source_hash(path):
"""Retain CreateFile's error code; Python open can reduce sharing errors to EACCES."""
path = internal_path(path)
if os.name != 'nt':
with path.open('rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
import msvcrt
import pywintypes
import win32file
try:
# Match the CRT reads used by subsequent source validation.
handle = win32file.CreateFile(str(path), 0x80000000, 3, None, 3, 0, None)
except pywintypes.error as error:
failure = OSError(error.winerror, error.strerror, str(path))
failure.winerror = error.winerror
raise failure from error
try:
fd = msvcrt.open_osfhandle(int(handle), os.O_RDONLY | os.O_BINARY)
handle.Detach() # The file descriptor now owns this handle.
finally:
handle.Close()
with os.fdopen(fd, 'rb') as stream:
return hashlib.file_digest(stream, 'sha256').hexdigest()
def bind_sources(proof, data_root, root, project, *, stop_event=None, release_mentor=None):
from .batch_resources import write_record
from .operation_diagnostics import record_operation
from .project_session_health import _source_parameters, _source_digest
from .project_isolation import write_sources
from .worker_monitor import _publish_progress
root = Path(root)
parameters = _source_parameters(Path(project), data_root)
started = time.monotonic()
deadline = started + LOCK_WAIT_SECONDS
status = dict(session_token=proof.get('session_token'), project_path=str(project),
replacement_replayed=False, mentor_released_for_read=False)
try:
prior = json.loads(internal_path(root / 'saved-source-status.json').read_text(encoding='utf-8'))
if (proof.get('session_token') and prior.get('session_token') == proof['session_token']
and prior.get('project_path', '').casefold() == str(project).casefold()):
status.update({key: prior[key] for key in ('first_error', 'last_error', 'lock_observation') if key in prior})
status['mentor_released_for_read'] = prior.get('mentor_released_for_read') is True
except (OSError, ValueError, AttributeError, TypeError):
pass # Historical diagnostics never authorize a saved result.
last_lock = None
observed = False
released_this_call = False
def publish(state, error=None):
status.update(state=state, elapsed_seconds=time.monotonic()-started)
if error is not None:
status['last_error'] = dict(path=getattr(error, 'path', str(project)),
winerror=getattr(error, 'winerror', None), message=str(error))
status.setdefault('first_error', status['last_error'])
write_record(root / 'saved-source-status.json', status)
try:
progress = json.loads(internal_path(root / 'worker-progress.json').read_text(encoding='utf-8'))
except (OSError, ValueError):
progress = {}
if not isinstance(progress, dict) or type(progress.get('sequence', 0)) is not int:
progress = {}
progress.update(stage='saved_source_wait' if state in {'waiting', 'releasing_mentor'} else
'awaiting_reconciliation' if state == 'pending' else 'verify_saved_project',
wait_reason='readback', waiting_for_safe_completion=False,
sequence=progress.get('sequence', 0)+1, stage_seconds={})
if state == 'pending': progress['primary_error'] = str(error)
_publish_progress(internal_path(root / 'worker-progress.json'), progress)
def publish_read(state, error):
try:
publish(state, error)
except Exception as diagnostic:
error.add_note('保存源文件交接状态记录失败:' + str(diagnostic))
raise error from diagnostic
def check_paused():
if last_lock is not None and stop_event is not None and stop_event.is_set():
raise SavedSourceReadError(last_lock[0], last_lock[1], interrupted=True) from last_lock[0]
record_operation(root, 'saved_source_bind', 'enter', item_id=proof.get('session_token', ''))
try:
while True:
check_paused()
path = project
try:
before = _source_digest(parameters)
hashes = {}
for path in sorted(write_sources(project)):
hashes[path] = source_hash(path)
if not before or before != _source_digest(parameters):
raise TaskCenterError('saved_source_changed', '保存后的源文件仍在变化,结果待核验;不会重复替换。')
value = dict(proof, **parameters, source_sha256=before, saved_sources=hashes,
command_sha256=hashlib.sha256(internal_path(root / 'command.tsv').read_bytes()).hexdigest())
check_paused()
publish('bound')
record_operation(root, 'saved_source_bind', 'return', item_id=proof.get('session_token', ''))
return value
except OSError as failure:
error = SavedSourceReadError(failure, path)
stopped = stop_event is not None and stop_event.is_set()
if stopped:
raise SavedSourceReadError(failure, path, interrupted=True) from failure
if not error.retryable:
raise error from failure
last_lock = failure, path
if not observed:
publish_read('waiting', error)
status['lock_observation'] = locking_processes(path)
observed = True
continue # The lock may have disappeared during this diagnostic.
if time.monotonic() >= deadline:
if release_mentor is None or released_this_call:
raise error from failure
publish_read('releasing_mentor', error)
check_paused()
release_mentor(error)
released_this_call = True
status['mentor_released_for_read'] = True
deadline = time.monotonic() + LOCK_WAIT_SECONDS
else:
if status.get('state') != 'waiting': publish_read('waiting', error)
time.sleep(.05)
except Exception as error:
record_operation(root, 'saved_source_bind', 'error', item_id=proof.get('session_token', ''), error=str(error))
try:
publish('pending', error)
except Exception as diagnostic:
error.add_note('保存源文件交接状态记录失败:' + str(diagnostic))
raise
@@ -16,6 +16,7 @@ STAGES = {
'restore_attribute_fields': '恢复属性字段', 'restore_attributes': '恢复属性',
'verify_restoration': '核验恢复结果', 'verify_attribute_fields': '核验属性字段',
'save_and_close': '保存并关闭工程', 'verify_saved_project': '回读工程并核对',
'saved_source_wait': '工程已保存,等待数据库释放后核验',
'awaiting_reconciliation': '当前结果待核验,已保留工程现场',
}