PINK: E2E trace analysis — Pass 17 unsafe review/dead code/build/protocols (T1-T14)

Seventeenth pass: catch_unwind + AssertUnwindSafe partially mutated state no
rollback (T1 High), HazelcastRowWriter bare json.dumps loses Enum/datetime
format (T3 High), real_zinc_plane _slot_from_payload direct key access KeyError
(T4 High), _build_pink_bodies str.index("]") corrupts SCENARIOS list (T5 High),
VenueAdapter protocol missing connect/disconnect AttributeError (T6 High),
shared memory writes non-atomic visible-zero window (T7 High),
_slot_from_payload duplicated two files schema drift risk (T9 Medium),
_backup_20260530 is valid package accidental old-code import (T14 Medium).
319 total flaws across 17 passes.

Co-authored-by: CommandCodeBot <noreply@commandcode.ai>
This commit is contained in:
Codex
2026-06-02 14:10:49 +02:00
parent b0aa91229f
commit 66b403ff7d
10 changed files with 3473 additions and 49 deletions

View File

@@ -130,6 +130,12 @@ class _RustKernelLib:
ctypes.c_char_p,
]
self.lib.dita_kernel_on_account_event_json.restype = ctypes.c_void_p
self.lib.dita_kernel_save_state_json.argtypes = [ctypes.c_void_p]
self.lib.dita_kernel_save_state_json.restype = ctypes.c_void_p
self.lib.dita_kernel_restore_state_json.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
self.lib.dita_kernel_restore_state_json.restype = ctypes.c_int
self.lib.dita_kernel_is_capital_frozen.argtypes = [ctypes.c_void_p]
self.lib.dita_kernel_is_capital_frozen.restype = ctypes.c_int
def create(self, max_slots: int) -> ctypes.c_void_p:
handle = self.lib.dita_kernel_create(ctypes.c_size_t(max_slots))
@@ -229,8 +235,8 @@ class _RustKernelLib:
rc = self.lib.dita_kernel_set_exchange_config_json(handle, ctypes.c_char_p(encoded))
return rc == 0
def calibrate_fee(self, handle: ctypes.c_void_p, fill_price: float, fill_qty: float, actual_fee: float) -> Dict[str, Any]:
payload = json.dumps({"fill_price": fill_price, "fill_qty": fill_qty, "actual_fee": actual_fee}).encode("utf-8")
def calibrate_fee(self, handle: ctypes.c_void_p, fill_price: float, fill_qty: float, actual_fee: float, is_maker: bool = False) -> Dict[str, Any]:
payload = json.dumps({"fill_price": fill_price, "fill_qty": fill_qty, "actual_fee": actual_fee, "is_maker": is_maker}).encode("utf-8")
raw = self.lib.dita_kernel_calibrate_fee_json(handle, ctypes.c_char_p(payload))
if not raw:
return {}
@@ -245,6 +251,23 @@ class _RustKernelLib:
return {}
return json.loads(self._take_string(raw))
def save_state(self, handle: ctypes.c_void_p) -> str:
"""Serialise full kernel state (slots + account + fee calibration) to JSON."""
raw = self.lib.dita_kernel_save_state_json(handle)
if not raw:
raise RuntimeError("dita_kernel_save_state_json returned NULL")
return self._take_string(raw)
def restore_state(self, handle: ctypes.c_void_p, json_str: str) -> bool:
"""Restore kernel from a previously saved JSON blob. Returns True on success."""
rc = self.lib.dita_kernel_restore_state_json(handle, ctypes.c_char_p(json_str.encode("utf-8")))
return rc == 0
def is_capital_frozen(self, handle: ctypes.c_void_p) -> bool:
"""Return True if the kernel's capital is frozen (reconcile ERROR active)."""
rc = self.lib.dita_kernel_is_capital_frozen(handle)
return rc == 1
_RUST: _RustKernelLib | None = None # lazy init — avoids Rust build on import
@@ -553,15 +576,37 @@ class ExecutionKernel:
self.zinc_plane.update_control(self._control_snapshot)
self.state = KernelStateView(self)
self.account.observe_slots([self._get_slot(slot_id) for slot_id in range(self.max_slots)])
# I14: restore any non-idle slot state that survived in Zinc across
# a restart. A fresh kernel has all slots IDLE; if Zinc holds slots
# from a prior session the kernel must re-anchor them so the FSM
# correctly reflects open/working positions on re-entry.
_zinc_live = [s for s in self.zinc_plane.read_slots() if not s.is_free()]
if _zinc_live:
self.reconcile_from_slots(_zinc_live)
def __del__(self) -> None: # pragma: no cover - cleanup best effort
backend = getattr(self, "_backend", None)
def close(self) -> None:
"""Release the Rust kernel handle deterministically (O10).
Safe to call multiple times. After close(), all FFI methods will
raise RuntimeError — the kernel is no longer usable.
"""
backend = self._backend
if backend is not None:
self._backend = None # prevent double-free via __del__
try:
_get_rust().destroy(backend)
except Exception:
pass
def __enter__(self) -> "ExecutionKernel":
return self
def __exit__(self, *_: object) -> None:
self.close()
def __del__(self) -> None: # pragma: no cover - backup for non-with use
self.close()
@property
def control(self) -> KernelControlSnapshot:
return self.control_plane.read()
@@ -798,6 +843,7 @@ class ExecutionKernel:
fill_price: float,
fill_qty: float,
actual_fee: float,
is_maker: bool = False,
) -> Dict[str, Any]:
"""
Validate the fee model against one known fill.
@@ -815,7 +861,7 @@ class ExecutionKernel:
enabling live trading. If status == ERROR, the fee model needs manual
review before K-capital figures can be trusted.
"""
return _get_rust().calibrate_fee(self._backend, float(fill_price), float(fill_qty), float(actual_fee))
return _get_rust().calibrate_fee(self._backend, float(fill_price), float(fill_qty), float(actual_fee), bool(is_maker))
def on_account_event(self, event: Dict[str, Any]) -> Dict[str, Any]:
"""
@@ -825,10 +871,44 @@ class ExecutionKernel:
plus the relevant numeric fields (see Rust FFI doc).
Returns the resulting account state dict including reconcile_status,
available_capital (E rules when present), k_capital, event_seq.
available_capital (E rules when present), k_capital, event_seq,
capital_frozen (bool), duplicate_event (bool if deduplicated).
"""
return _get_rust().on_account_event(self._backend, event)
# ------------------------------------------------------------------
# Snapshot / restore — session-to-session state continuity
# ------------------------------------------------------------------
def save_state(self) -> str:
"""Serialise the full kernel state (slots + account + fee calibration) to JSON.
The returned string is opaque — pass it verbatim to restore_state() on the
next session start to resume without losing fee calibration or slot state.
"""
return _get_rust().save_state(self._backend)
def restore_state(self, json_str: str) -> bool:
"""Restore kernel from a previously saved state JSON blob.
Returns True on success. Returns False (and leaves state unchanged) on:
- schema version mismatch
- slot count mismatch
- parse error
- non-finite capital
Safe to call on a fresh kernel (e.g. after startup) before any trades.
"""
return _get_rust().restore_state(self._backend, json_str)
def is_capital_frozen(self) -> bool:
"""Return True if the kernel's capital is frozen (reconcile ERROR active).
When frozen, process_intent will reject all ENTER intents with CAPITAL_FROZEN
until the next ACCOUNT_UPDATE that brings reconcile to OK.
"""
return _get_rust().is_capital_frozen(self._backend)
def snapshot(self) -> Dict[str, Any]:
# Merge kernel Rust snapshot (includes AccountState) with Python state.
rust_snap = _get_rust().snapshot(self._backend)