feat: bind native CRUD to prepared engine identity transactions

This commit is contained in:
阿白叔 committed 2026-11-03 11:54:56 +08:00
1 parent 89500cbb5f
commit 55a82fdc5f
8 files changed
+492 -13

No files matched your search

+14 -1
View File
@@ -29,6 +29,7 @@ class ManagementRequest:
timeout_seconds: float = 180
mapped_drive: str = ''
mapped_remote_root: str = ''
transaction_token: str = ''
@dataclass(frozen=True)
@@ -53,6 +54,7 @@ class NativeOutcome:
detail: str
identity_matches: bool | None = None
evidence_path: Path | None = None
identity_proof: dict | None = None
@dataclass(frozen=True)
@@ -268,6 +270,14 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
identity = engineering_identity(staged.source)
if build_manifest(source.parent) != source_manifest:
raise OSError('来源工程在暂存期间变化。')
if source and hasattr(adapter, 'prepare_add_transaction'):
checkpoint('prepare_identity')
owner_safe = False
staged, proof = adapter.prepare_add_transaction(staged, root, original_source=source)
owner_safe = proof.safe_to_continue
if not owner_safe or proof.identity is None:
return finish('UPLOAD_FAILED', proof.detail, owner_safe)
identity = proof.identity
if build_manifest(library_root, scope=scope) != original:
raise OSError('备份后中心库内容变化,停止写入。')
if request.operation in ('remove', 'update'):
@@ -302,8 +312,11 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
owner_safe = after.safe_to_continue
matches = [entry for entry in after.entries if entry.name == request.name
and entry.partition == request.partition]
proof_matches = (native.identity_matches is True and native.identity_proof == identity
if hasattr(adapter, 'prepare_add_transaction') else
len(matches) == 1 and matches[0].engineering_identity == identity)
if (not owner_safe or Path(after.library).resolve() != canonical_library or after.flow != 1
or len(matches) != 1 or matches[0].engineering_identity != identity):
or len(matches) != 1 or not proof_matches):
return finish('RECOVERY_REQUIRED', '原生新增后名称、分区或来源工程内容未确认一致。', False)
uploaded = True
checkpoint('uploaded')
@@ -0,0 +1,127 @@
"""Prepared Add authority bound to the engine checkpoint, snapshot and live lease."""
import json
import os
from pathlib import Path
import threading
from uuid import uuid4
from .management import _write_json, engineering_identity
from .scoped_manifest import build_manifest, ManifestScope
def _read(path):
return json.loads(Path(path).read_text(encoding='utf-8'))
def fixture_authority(root, library, token):
root = Path(root).resolve()
expected = root/'native-add/fixture/mentor_lib.lmc'
owner = _read(root/'probe-owner.json')
if (not token or owner.get('token') != token or not expected.is_file()
or Path(library).resolve() != expected.resolve()
or Path(owner.get('library', '')).resolve() != expected.resolve()):
raise ValueError('Management research requires the exact newly created owned fixture.')
return {'root': str(root), 'token': token}
def current_lease(library):
from .library_lock import LibraryLock, _guard, _owners, blocker_path, checkpoint_record
lease = LibraryLock(library)
with _guard:
owner = _owners.get(lease.key)
guard = checkpoint_record(blocker_path(library))
if (owner is None or owner['retained'] or owner['thread'] != threading.get_ident()
or guard is None or guard['pid'] != os.getpid()
or guard['status'] != 'OPERATION_IN_PROGRESS'
or owner['lease_id'] != guard['lease_id']
or Path(guard['library']).resolve() != Path(library).resolve()):
raise ValueError('Management transaction requires the current thread exact active library lease.')
return {'lease_id': owner['lease_id'], 'lease_handle': int(owner['handle']), 'supervisor_pid': os.getpid()}
def _authorize(record, mentor_home):
fixture = record.get('fixture')
if fixture is not None:
fixture_authority(fixture['root'], record['library'], fixture['token'])
else:
from .native_management import NativeManagementAdapter
capability = NativeManagementAdapter(mentor_home=mentor_home).capabilities()['add']
if not capability.supported: raise ValueError(capability.reason)
def prepare_transaction(request, root, expected_identity, *, mentor_home, fixture=None):
root = Path(root).resolve()
source = Path(request.source).resolve()
if source.parent != root/'source':
raise ValueError('Native Add accepts only the management engine staged source.')
library = Path(request.library).resolve()
if root.is_relative_to(library.parent) or library.parent.is_relative_to(root):
raise ValueError('Management transaction evidence overlaps the target library.')
checkpoint = _read(root/'checkpoint.json')
stages = {item['stage'] for item in checkpoint.get('history', [])}
if (checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'prepare_identity'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != request.name or checkpoint['partition'] != request.partition
or not {'backup', 'stage_source'}.issubset(stages)):
raise ValueError('Native Add requires the engine backup/staging checkpoint.')
backup = _read(root/'library-before-manifest.json')
if build_manifest(root/'library-before', scope=ManifestScope.library(request.name, library.name)) != backup:
raise ValueError('Management backup has not been verified.')
baseline = _read(root/'source-identity/identity.json')
if baseline.get('safe_to_continue') is not True or baseline.get('identity') != expected_identity:
raise ValueError('Native source identity evidence is missing or changed.')
record = {**current_lease(library), 'nonce': uuid4().hex, 'library': str(library),
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
'source_name': source.name, 'source_identity': engineering_identity(source),
'source_manifest': build_manifest(source.parent), 'backup_manifest': backup,
'expected_identity': expected_identity, 'fixture': fixture}
_authorize(record, mentor_home)
_write_json(root/'native-add-prepared.json', record)
return record['nonce']
def validate_transaction(job, root, *, check_source=True):
from .library_lock import blocker_path, checkpoint_record, _supervisor_alive
import win32api, win32con, win32file
root = Path(root).resolve()
record = _read(root/'native-add-prepared.json')
library = Path(job['library']).resolve()
source = root/'source'/record['source_name']
guard = checkpoint_record(blocker_path(library))
checkpoint = _read(root/'checkpoint.json')
if (not job.get('transaction_nonce') or job['transaction_nonce'] != record['nonce']
or Path(record['library']).resolve() != library
or any(job.get(key) != record[key] for key in ('name', 'partition', 'top_level_block', 'source_identity'))
or source.parent != root/'source' or source.resolve().parent != (root/'source').resolve()
or Path(job['source']).resolve() != source.resolve()
or guard is None or guard['lease_id'] != record['lease_id']
or guard['pid'] != record['supervisor_pid'] or guard['pid'] != job['supervisor_pid']
or guard['status'] != 'OPERATION_IN_PROGRESS'
or Path(guard['library']).resolve() != library or not _supervisor_alive(guard['pid'])
or checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'native_add'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != record['name'] or checkpoint['partition'] != record['partition']):
raise ValueError('Native Add transaction authority is missing, stale or foreign.')
_authorize(record, job['mentor_home'])
baseline = _read(root/'source-identity/identity.json')
if (baseline.get('safe_to_continue') is not True or baseline.get('identity') != record['expected_identity']
or build_manifest(root/'library-before', scope=ManifestScope.library(record['name'], library.name))
!= record['backup_manifest']
or check_source and (build_manifest(source.parent) != record['source_manifest']
or engineering_identity(source) != record['source_identity'])):
raise ValueError('Native Add baseline, backup or staged source proof changed.')
process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, record['supervisor_pid'])
duplicate = None
try:
duplicate = win32api.DuplicateHandle(process, record['lease_handle'], win32api.GetCurrentProcess(),
0, False, win32con.DUPLICATE_SAME_ACCESS)
final_path = win32file.GetFinalPathNameByHandle(duplicate, 0)
if final_path.startswith('\\\\?\\UNC\\'): final_path = '\\\\'+final_path[8:]
elif final_path.startswith('\\\\?\\'): final_path = final_path[4:]
expected_lock = library.with_name('.'+library.stem+'.cbb-upload.lock')
if Path(final_path).resolve() != expected_lock.resolve():
raise ValueError('Native Add supervisor lease belongs to another library.')
finally:
if duplicate is not None: duplicate.Close()
process.Close()
return record
+168 -11
View File
@@ -3,7 +3,7 @@
The installed Tcl CleanWGLib/F4 contract has isolated removal proof. Discovery
of an Add dialog is deliberately insufficient to enable production Add/Update.
"""
from dataclasses import asdict
from dataclasses import asdict, replace
import ctypes
import json
import os
@@ -21,6 +21,9 @@ from .scoped_manifest import hash_file
from .network_path import absolute_preserving_drive
_retained_workers = []
# Promotion requires coordinator-owned native CRUD evidence, in a separate change.
_PRODUCTION_ADD_VALIDATED = False
_PRODUCTION_UPDATE_VALIDATED = False
_BINARY_PROOF = {
'lm/win32/bin/CleanWGLib.exe': '7808ded326555f1fd5d5c14f68803dbb4f970d624f9ad6e1c7982dc9ed867917',
'lm/win32/bin/LibraryManager.exe': 'a9c4c3d806794dbdc56d2bc4c637a1cf25e87e98644a7d5fd4eb0067ca5845e0',
@@ -89,8 +92,9 @@ class NativeManagementAdapter:
reason = self._binary_capability()
return {
'remove': Capability(not reason, reason or '已验证 CleanWGLib/F4;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
'add': Capability(False, '原生新增已调用并注册,但工程身份复读尚未通过;生产新增保持禁用。'),
'update': Capability(False, '同名更新需要原生移除、重新导入及完整端到端隔离验证,目前不可用。'),
'add': Capability(not reason and _PRODUCTION_ADD_VALIDATED, '原生新增及工程身份已有隔离证据;完整事务验证通过前生产新增保持禁用。'),
'update': Capability(not reason and _PRODUCTION_ADD_VALIDATED and _PRODUCTION_UPDATE_VALIDATED,
'同名更新需要原生移除、重新导入及完整端到端隔离验证,目前不可用。'),
}
def _worker(self, job, evidence):
@@ -111,7 +115,11 @@ class NativeManagementAdapter:
win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired:
raise RuntimeError('Another CBB operation owns the management mutex.')
job = prepare_owned_fixture_add(job, evidence)
if job.get('authority_kind') == 'management':
from .management_transaction import validate_transaction
validate_transaction(job, evidence.parent)
else:
job = prepare_owned_fixture_add(job, evidence)
from .library_lock import LibraryLock
owner_safe = False
# Nest only after preparation proves an existing caller lease.
@@ -124,7 +132,7 @@ class NativeManagementAdapter:
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
if job['operation'] == 'probe_create_add':
if job['operation'] in ('probe_create_add', 'probe_create'):
# Prepare the fixed NEW fixture before a native owner can start.
# The parent owns its sidecar for the entire create/add invocation.
from .library_lock import LibraryLock
@@ -197,8 +205,93 @@ class NativeManagementAdapter:
def add(self, request, evidence):
# Route readiness never grants production mutation authority.
return NativeOutcome(False, True, self.capabilities()['add'].reason,
evidence_path=Path(evidence))
capability = self.capabilities()['add']
if not capability.supported:
return NativeOutcome(False, True, capability.reason, evidence_path=Path(evidence))
return self._add_transaction(request, Path(evidence))
def prepare_add_transaction(self, request, root, *, original_source):
from .native_engineering_identity import project_library, asset_identity, capture_identity
from .management_transaction import current_lease, prepare_transaction
from .management import source_project
from .backup_recovery import _align_library
if not self.capabilities()['add'].supported:
raise ValueError(self.capabilities()['add'].reason)
current_lease(request.library)
original_assets = asset_identity(original_source, project_library(original_source))
staged, pcb, _ = source_project(request.source, request.top_level_block)
if staged.parent != Path(root).resolve()/'source':
raise ValueError('Only the engine staged source can be aligned for native Add.')
_align_library(staged, pcb, request.library)
if asset_identity(staged, request.library) != original_assets:
raise ValueError('Staged engineering assets differ from the original source.')
proof = capture_identity(staged, Path(root)/'source-identity', expected_library=request.library,
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
if proof.identity is None or not proof.safe_to_continue:
return request, proof
token = prepare_transaction(request, root, proof.identity, mentor_home=self.home,
fixture=getattr(self, '_fixture_authority', None))
return replace(request, transaction_token=token), proof
def _add_transaction(self, request, evidence):
from .management_transaction import validate_transaction
from .library_lock import LibraryLock
from .native_engineering_identity import capture_identity, project_library
from .management import source_project
from .backup_recovery import _align_library, _idle_check
job = {'operation': 'add', 'authority_kind': 'management', 'transaction_nonce': request.transaction_token,
'library': str(absolute_preserving_drive(request.library)), 'source': str(request.source),
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
'source_identity': engineering_identity(request.source), 'supervisor_pid': os.getpid(),
'mentor_home': str(self.home), 'timeout_seconds': request.timeout_seconds,
'mapped_drive': request.mapped_drive, 'mapped_remote_root': request.mapped_remote_root}
prepared = validate_transaction(job, evidence.parent)
owner_safe = False
with LibraryLock(request.library, safe_to_release=lambda: owner_safe):
result = self._worker(job, evidence)
owner_safe = result.get('safe_to_continue') is True
if not owner_safe or not result.get('success'):
return NativeOutcome(False, owner_safe, result.get('detail', 'Native Add failed.'), evidence_path=evidence)
owner_safe = False
# The native editor may leave PCB/pcb.prj relative to the staged
# location. Correct only documented library-reference tokens after
# its owner has exited, then reopen the native catalog independently.
validate_transaction(job, evidence.parent, check_source=False)
work = Path(request.library).parent/'ReusableBlocksLP'/request.name/'Work'
projects = list(work.glob('*.prj'))
if len(projects) != 1:
owner_safe = False
return NativeOutcome(True, False, 'Registered engineering project is not unique.',
identity_matches=False, evidence_path=evidence)
target, pcb, _ = source_project(projects[0], request.top_level_block)
_idle_check(request.library, target, pcb)
owner_safe = False
before_refs = {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}
_align_library(target, pcb, request.library)
if project_library(target) != Path(request.library).resolve():
raise ValueError('Registered project references do not resolve to the exact target library.')
_write_json(evidence/'reference-alignment.json', {'before': before_refs,
'after': {str(p): hash_file(p) for p in (target, pcb.parent/'pcb.prj')}, 'library': job['library']})
catalog = self.catalog(request.library, evidence/'reopen-aligned')
owner_safe = catalog.safe_to_continue
entries = [entry for entry in catalog.entries if entry.name == request.name and entry.partition == request.partition]
if (not owner_safe or Path(catalog.library).resolve() != Path(request.library).resolve()
or catalog.flow != 1 or len(entries) != 1):
owner_safe = False
return NativeOutcome(True, False, 'Aligned target did not reopen with the exact catalog identity.',
identity_matches=False, evidence_path=evidence)
owner_safe = False
proof = capture_identity(target, evidence/'registered-identity', expected_library=request.library,
owner_library=request.library, mentor_home=self.home, timeout_seconds=request.timeout_seconds)
owner_safe = proof.safe_to_continue
matched = proof.identity is not None and proof.identity == prepared['expected_identity']
_write_json(evidence/'identity-comparison.json', {'identity_matches': matched,
'expected': prepared['expected_identity'], 'registered': proof.identity,
'safe_to_continue': owner_safe, 'detail': proof.detail})
return NativeOutcome(True, owner_safe,
'Native ASCII/CSV/EDIF, physical assets and library references match.' if matched else
'Native registration succeeded but complete engineering identity proof did not match: '+proof.detail,
identity_matches=matched, evidence_path=evidence, identity_proof=proof.identity)
def add_owned_fixture(self, request, evidence, *, probe_token):
"""Research only: stage and back up a token-bound, actively leased fixture."""
@@ -240,6 +333,64 @@ class NativeManagementAdapter:
detail, identity_matches=identity_matches, evidence_path=evidence)
class _OwnedFixtureManagementAdapter(NativeManagementAdapter):
"""Diagnostic capability grant restricted to a token-bound created fixture."""
def __init__(self, root, token, **kwargs):
super().__init__(**kwargs)
from .management_transaction import fixture_authority
self._fixture_authority = fixture_authority(root, Path(root)/'native-add/fixture/mentor_lib.lmc', token)
def capabilities(self):
from .management_transaction import fixture_authority
from .native_engineering_identity import check_exporters
fixture = self._fixture_authority
fixture_authority(fixture['root'], Path(fixture['root'])/'native-add/fixture/mentor_lib.lmc', fixture['token'])
caps = super().capabilities()
reason = self._binary_capability()
try: check_exporters(self.home)
except (ValueError, OSError) as error: reason = str(error)
for operation in ('add', 'update'):
caps[operation] = Capability(not reason, reason or 'Owned fixture engine validation only; production capability unchanged.')
return caps
def preflight(self, request, catalog):
from .management_transaction import fixture_authority
fixture = self._fixture_authority
fixture_authority(fixture['root'], request.library, fixture['token'])
super().preflight(request, catalog)
def run_owned_fixture_management(request, root, *, probe_token, mentor_home=None, **kwargs):
"""Run the real engine with a narrow fixture grant, never a public override."""
from .management import run_management
from .management_transaction import fixture_authority
fixture_authority(root, request.library, probe_token)
adapter = _OwnedFixtureManagementAdapter(root, probe_token, mentor_home=mentor_home)
return run_management(request, adapter=adapter, **kwargs)
def create_owned_fixture(root, *, mentor_home=None):
"""Diagnostic-only empty native library, guarded by the existing creation protocol."""
import win32con, win32event
root = absolute_preserving_drive(root)
if root.exists(): raise ValueError('Native fixture root must be entirely new.')
adapter = NativeManagementAdapter(mentor_home=mentor_home)
if not adapter.route_capabilities()['add'].supported:
raise ValueError(adapter.route_capabilities()['add'].reason)
mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795')
acquired = False
token = uuid4().hex
try:
acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED)
if not acquired: raise RuntimeError('Another CBB operation owns the management mutex.')
library = root/'native-add/fixture/mentor_lib.lmc'
result = adapter._worker({'operation': 'probe_create', 'library': str(library), 'probe_token': token}, root/'native-add')
return {**result, 'probe_token': token, 'fixture_root': str(root)}
finally:
if acquired: win32event.ReleaseMutex(mutex)
mutex.Close()
def prepare_owned_fixture_add(job, root):
"""Create fresh transaction evidence while this thread owns the fixture."""
from .library_lock import LibraryLock, owned_snapshot, checkpoint_record, blocker_path, _guard, _owners
@@ -461,7 +612,9 @@ def _probe_add_dialog_impl(app, job, desktop, owned_pids, root, *, library=None)
from .management import source_project
source, pcb, top = source_project(job['source'], job.get('top_level_block', ''))
source_folder = 'source-replacement' if job['operation'] == 'probe_readd' else 'source'
source_root = Path(root).resolve()/'source' if job['operation'] == 'add' else Path(root).parent.resolve()/source_folder
source_root = (Path(root).resolve()/'source'
if job['operation'] == 'add' and job.get('authority_kind') != 'management'
else Path(root).parent.resolve()/source_folder)
if not source.is_relative_to(source_root):
raise ValueError('隔离新增只允许使用本次复制的来源工程。')
_align_library(source, pcb, Path(job['library']))
@@ -716,7 +869,11 @@ def _catalog_com(job, root):
import pythoncom, win32com.client, win32con, win32gui, win32process
from .mentor_adapter import _process_details
if job['operation'] == 'add':
validate_owned_fixture_add(job, root)
if job.get('authority_kind') == 'management':
from .management_transaction import validate_transaction
validate_transaction(job, root.parent)
else:
validate_owned_fixture_add(job, root)
desktop, name = _current_desktop()
if name != job['desktop'] or not name.startswith('CbbManagement_'):
raise RuntimeError('拒绝在非本次私有桌面读取原生目录。')
@@ -762,7 +919,7 @@ def _catalog_com(job, root):
raise RuntimeError('COM 注册指向不同的 Library Manager 安装,拒绝打开中心库。')
watcher = threading.Thread(target=observe_dialogs, daemon=True)
watcher.start()
if job['operation'] == 'probe_create_add':
if job['operation'] in ('probe_create_add', 'probe_create'):
target = prepare_probe_library(job, root)
library = app.CreateLibrary(str(target), 1)
_write_json(root.parent/'probe-owner.json', {'library': str(target), 'token': job['probe_token']})
@@ -854,7 +1011,7 @@ def management_worker_main(request_path):
if job.get('mapped_drive') and job.get('mapped_remote_root'):
from .network_path import ensure_mapped_drive_visible
ensure_mapped_drive_visible(job['mapped_drive'], job['mapped_remote_root'])
if job['operation'] in ('catalog', 'add', 'probe_create_add', 'probe_readd'):
if job['operation'] in ('catalog', 'add', 'probe_create', 'probe_create_add', 'probe_readd'):
if job['operation'] == 'add':
route = NativeManagementAdapter(mentor_home=job['mentor_home']).route_capabilities()['add']
if not route.supported:
+1 -1
View File
@@ -200,7 +200,7 @@ class MainWindow(QWidget):
management_layout = QVBoxLayout(management)
management_buttons = QHBoxLayout()
self.add_button = QPushButton('新增 CBB…')
self.update_button = QPushButton('同名更新已选…')
self.update_button = QPushButton('用工程替换已选 CBB…(原生重新导入)')
self.remove_button = QPushButton('移除已选…')
for operation, widget in (('add', self.add_button), ('update', self.update_button), ('remove', self.remove_button)):
widget.clicked.connect(lambda _=False, op=operation: self.manage_cbb(op))