fix: bound task handoff and preserve native writer ownership

This commit is contained in:
阿白叔 committed 2026-11-16 18:57:36 +08:00
1 parent 0440b2efbf
commit ddff6bd857
18 files changed
+1397 -118

No files matched your search

+32 -19
View File
@@ -20,6 +20,21 @@ def _library_guard(key):
return _library_guards.setdefault(key, threading.RLock())
def duplicate_worker_lease(library, process_handle):
"""Keep the exact admitted exclusive file object alive across parent exit."""
import win32api, win32con
lease = LibraryLock(library)
with _library_guard(lease.key):
owner = _owners.get(lease.key)
if owner is None:
return None
if owner['thread'] != threading.get_ident() or owner['retained'] or not owner['depth']:
raise LibraryBusy('不能将其他任务的库锁交给工作进程。')
remote = win32api.DuplicateHandle(win32api.GetCurrentProcess(), owner['handle'],
process_handle, 0, False, win32con.DUPLICATE_SAME_ACCESS)
return remote.Detach() # This handle belongs to the target process only.
class LibraryBusy(OSError):
pass
@@ -407,14 +422,12 @@ def _owner_is_blocking(item, library, roots):
def _enter_maintenance(lease):
"""Transfer only a valid known lease, after project admission under lock."""
import win32con, win32event, win32file
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
import win32con, win32file
from .operation_queue import check_active
handle = None
existing = None
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: raise LibraryBusy('已有 CBB 操作运行,维护不能接续')
check_active()
with _library_guard(lease.key):
marker = blocker_path(lease.library)
if marker.with_suffix('.pending').exists():
@@ -449,6 +462,7 @@ def _enter_maintenance(lease):
with saved.open('xb') as stream:
stream.write(old); stream.flush(); os.fsync(stream.fileno())
if saved.read_bytes() != old: raise OSError('原检查点归档校验失败')
check_active()
lease_id = uuid4().hex
_persist_blocker(lease.library, 'OPERATION_IN_PROGRESS', lease_id=lease_id)
_owners[lease.key] = {'thread': threading.get_ident(), 'depth': 1, 'handle': handle,
@@ -456,12 +470,9 @@ def _enter_maintenance(lease):
'release_probe': lease.safe_to_release, 'block_name': None}
lease.maintenance_proof = proof
lease.entered = True
lease.maintenance_mutex = mutex
return lease
except Exception:
if handle is not None and existing is None: handle.Close()
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
raise
@@ -550,7 +561,13 @@ def _prove_library_released(library, block_name=None, *, block_names=(), allow_u
# and compare the exact address/project binding before commit.
stack.close()
from .icdb_ownership import inspect_release_addresses
inspections = inspect_release_addresses(files, stop=stop)
# Checkpoint I/O is per-library; only native inspection owns
# the host channel. The sidecar still excludes other writers.
from .operation_queue import native_channel
with native_channel(inspection_only=True):
if stop is not None and stop.is_set():
raise InterruptedError('已停止释放检查')
inspections = inspect_release_addresses(files, stop=stop)
try:
current = stack.enter_context(hold_release_files(library, roots, stop=stop))
except OSError as error:
@@ -582,7 +599,7 @@ def release_retained_library(library, evidence_dir, *, block_name=None, block_na
The upload sidecar is never deleted. This acknowledges process release,
not the correctness of a partially changed library or its recovery state.
"""
import win32con, win32event, win32file
import win32con, win32file
library = Path(library).resolve(strict=True)
from .session_record import (retained_session_snapshot, acknowledge_library_release,
reconciled_retained_sessions)
@@ -594,15 +611,10 @@ def release_retained_library(library, evidence_dir, *, block_name=None, block_na
if evidence.is_relative_to(library.parent) or library.parent.is_relative_to(evidence):
raise ValueError('释放检查证据必须位于目标库之外。')
lease = LibraryLock(library)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
external = None
try:
if stop is not None and stop.is_set():
raise InterruptedError('已停止释放检查')
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
raise LibraryBusy('另一个 CBB 操作仍在运行。')
with _library_guard(lease.key):
owner = _owners.get(lease.key)
if owner and (not owner['retained'] or owner['depth']):
@@ -675,7 +687,8 @@ def release_retained_library(library, evidence_dir, *, block_name=None, block_na
'block_names': list(scoped_blocks),
'lease_id': owner['lease_id'] if owner else None,
'operation_ids': [item['operation_id'] for item in reconciled_sessions]}
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
pending = {**record, 'status': 'RELEASE_PENDING', 'lease_state': 'PENDING'}
(root/'release.json').write_text(json.dumps(pending, ensure_ascii=False, indent=2), encoding='utf-8')
for index, checkpoint in enumerate(checkpoints):
if checkpoint.exists():
data = checkpoint.read_bytes()
@@ -683,15 +696,15 @@ def release_retained_library(library, evidence_dir, *, block_name=None, block_na
archived.write_bytes(data)
if archived.read_bytes() != data:
raise OSError('阻止记录归档校验失败,保持库锁。')
if stop is not None and stop.is_set():
raise InterruptedError('已停止释放检查')
checkpoint.unlink() # Checkpoint JSON only; never .lock.
if owner:
owner['handle'].Close()
del _owners[lease.key]
(root/'release.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
acknowledge_library_release(record, matching_retained, block_name=scoped)
return record
finally:
if external is not None:
external.Close()
if acquired:
win32event.ReleaseMutex(mutex)
mutex.Close()