Spaces:
Paused
Paused
File size: 18,178 Bytes
5e0b58b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 | """Typed bridge contracts for structural dashboard endpoints.
This module defines the protocol and data types for the structural operator
bridge, which provides a clean interface between the dashboard HTTP layer
and the Brain-5D structural plasticity subsystem.
The StructuralOperatorBridge protocol defines all operations that can be
performed on the structural plasticity system, including:
- Querying status, proposals, history, configuration
- Approving/rejecting proposals
- Undoing changes
- Controlling auto-approval
- Runtime control (ticks, steps, snapshots)
This contract ensures consistency between the dashboard server and the
operator bridge implementation.
"""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime
from typing import Protocol, runtime_checkable
from .models import JSONValue
# ============================================================================
# Type Aliases
# ============================================================================
JSONMapping = dict[str, JSONValue]
"""Type alias for a JSON-serializable dictionary."""
# ============================================================================
# Command Result
# ============================================================================
@dataclass(frozen=True, slots=True)
class StructuralCommandResult:
"""Result of a structural operator command.
This immutable data class represents the outcome of a command executed
through the StructuralOperatorBridge. It contains a success flag and
a human-readable message describing the result.
Attributes:
ok: True if the command succeeded, False otherwise.
message: A human-readable message describing the result.
For successful commands, this typically describes what was done.
For failed commands, this describes the error that occurred.
"""
ok: bool
message: str
def to_json(self) -> JSONMapping:
"""Convert to a JSON-serializable dictionary."""
return {"ok": self.ok, "message": self.message}
@classmethod
def success(cls, message: str) -> StructuralCommandResult:
"""Create a successful result.
Args:
message: Description of the successful operation.
Returns:
StructuralCommandResult with ok=True.
"""
return cls(ok=True, message=message)
@classmethod
def failure(cls, message: str) -> StructuralCommandResult:
"""Create a failed result.
Args:
message: Description of the failure.
Returns:
StructuralCommandResult with ok=False.
"""
return cls(ok=False, message=message)
@property
def is_success(self) -> bool:
"""Return True if the command succeeded."""
return self.ok
@property
def is_failure(self) -> bool:
"""Return True if the command failed."""
return not self.ok
# ============================================================================
# Operator Bridge Protocol
# ============================================================================
@runtime_checkable
class StructuralOperatorBridge(Protocol):
"""Protocol defining the structural operator bridge interface.
This protocol defines the contract between the dashboard HTTP handlers
and the structural plasticity operator bridge implementation. All methods
are synchronous and return either JSON-serializable data or
StructuralCommandResult objects.
The bridge provides:
1. Status queries (current state of the structural plasticity system)
2. Proposal management (listing, approving, rejecting)
3. History access (past structural changes)
4. Heatmap generation (visualization data)
5. Configuration access (current settings)
6. Runtime control (ticks, steps, snapshots)
All methods should handle errors gracefully and return meaningful
error messages in the command results.
"""
# -------------------------------------------------------------------------
# Status Queries
# -------------------------------------------------------------------------
def structural_status(self) -> JSONMapping:
"""Get the current status of the structural plasticity system.
Returns:
A dictionary containing:
- configured: bool - whether the system is configured
- proposal_tick: int | None - last tick when proposals were generated
- proposal_count: int - number of pending proposals
- decision_count: int - total decisions made
- history_count: int - total history records
Raises:
RuntimeError: If the bridge is not properly initialized.
"""
...
def structural_proposals(self) -> list[JSONMapping]:
"""Get all pending structural plasticity proposals.
Returns:
A list of proposal dictionaries, each containing:
- proposal_id: str - unique identifier
- kind: str - type of proposal (e.g., 'neuron_add', 'synapse_prune')
- neuron_id: int | None - affected neuron
- target_id: int | None - target neuron for synapses
- reason: str - why the proposal was generated
- confidence: float - confidence score (0-1)
Raises:
RuntimeError: If the bridge is not properly initialized.
"""
...
def structural_history(self, limit: int) -> list[JSONMapping]:
"""Get the history of structural plasticity changes.
Args:
limit: Maximum number of records to return. Should be positive.
Returns:
A list of history record dictionaries, each containing:
- sequence: int - sequence number
- tick: int - simulation tick when the change occurred
- kind: str - type of change
- proposal_id: str - ID of the proposal that caused the change
- neuron_id: int | None - affected neuron
- source_id: int | None - source neuron (for synapses)
- target_id: int | None - target neuron (for synapses)
- reason: str - reason for the change
- approved_by: str - who approved the change
- automatic: bool - whether the change was automatic
- undo_of_sequence: int | None - sequence number if this is an undo
Raises:
ValueError: If limit is negative or zero.
RuntimeError: If the bridge is not properly initialized.
"""
...
def structural_heatmap(self, kind: str) -> JSONMapping:
"""Generate a structural plasticity heatmap.
Args:
kind: The type of heatmap to generate.
Valid values: 'neuron_additions', 'neuron_removals',
'synapse_additions', 'synapse_removals',
'total_structural_activity'.
Returns:
A dictionary containing:
- kind: str - the heatmap kind
- values: list[list[float]] - 2D array of heatmap values
- min_value: float - minimum value in the heatmap
- max_value: float - maximum value in the heatmap
- populated_cells: int - number of non-zero cells
- sequence_from: int - starting sequence number
- sequence_to: int - ending sequence number
Raises:
ValueError: If the heatmap kind is unknown.
RuntimeError: If the bridge is not properly initialized.
"""
...
def structural_config(self) -> JSONMapping:
"""Get the current structural plasticity configuration.
Returns:
A dictionary containing:
- configured: bool - whether the system is configured
- enabled: bool - whether structural plasticity is enabled
- dry_run: bool - whether changes are applied (dry run mode)
- auto_approval: bool - whether proposals are auto-approved
- auto_approval_threshold: float - confidence threshold for auto-approval
- max_changes_per_tick: int - maximum changes per tick
- max_neuron_additions_per_tick: int - max neuron additions per tick
- max_neuron_removals_per_tick: int - max neuron removals per tick
- max_synapse_additions_per_tick: int - max synapse additions per tick
- max_synapse_removals_per_tick: int - max synapse removals per tick
- min_neurons: int - minimum neuron count
- max_neurons: int - maximum neuron count
- allow_neuron_pruning: bool - whether neurons can be pruned
- allow_synapse_pruning: bool - whether synapses can be pruned
- cooldown_ticks: int - cooldown period between changes
Raises:
RuntimeError: If the bridge is not properly initialized.
"""
...
# -------------------------------------------------------------------------
# Proposal Management
# -------------------------------------------------------------------------
def approve_structural(self, proposal_id: str) -> StructuralCommandResult:
"""Approve a structural plasticity proposal.
This method records the approval decision and applies the proposed
change to the network.
Args:
proposal_id: ID of the proposal to approve.
Returns:
StructuralCommandResult with success status and message.
Raises:
ValueError: If proposal_id is empty or invalid.
RuntimeError: If the bridge is not properly initialized.
"""
...
def reject_structural(self, proposal_id: str) -> StructuralCommandResult:
"""Reject a structural plasticity proposal.
This method records the rejection decision without applying any changes.
Args:
proposal_id: ID of the proposal to reject.
Returns:
StructuralCommandResult with success status and message.
Raises:
ValueError: If proposal_id is empty or invalid.
RuntimeError: If the bridge is not properly initialized.
"""
...
def undo_structural(self) -> StructuralCommandResult:
"""Undo the last structural plasticity change.
This method reverts the most recent structural change that was applied.
Returns:
StructuralCommandResult with success status and message.
The message indicates whether a change was undone or if there
was nothing to undo.
Raises:
RuntimeError: If the bridge is not properly initialized.
"""
...
# -------------------------------------------------------------------------
# Configuration Management
# -------------------------------------------------------------------------
def set_auto_approval(self, enabled: bool) -> StructuralCommandResult:
"""Enable or disable automatic approval of proposals.
When auto-approval is enabled, proposals that meet the confidence
threshold are automatically approved without user intervention.
Args:
enabled: Whether to enable auto-approval.
Returns:
StructuralCommandResult with success status and message.
Raises:
RuntimeError: If the bridge is not properly initialized.
"""
...
# -------------------------------------------------------------------------
# Runtime Control
# -------------------------------------------------------------------------
def run_ticks(self, count: int) -> StructuralCommandResult:
"""Run a specified number of simulation ticks.
Args:
count: Number of ticks to execute. Must be positive.
Returns:
StructuralCommandResult with success status and message.
Raises:
ValueError: If count is negative or zero.
RuntimeError: If the bridge is not properly initialized.
"""
...
def single_step(self) -> StructuralCommandResult:
"""Execute a single simulation tick.
This is a convenience method that runs exactly one tick.
Returns:
StructuralCommandResult with success status and message.
Raises:
RuntimeError: If the bridge is not properly initialized.
"""
...
def request_snapshot(self) -> StructuralCommandResult:
"""Request a snapshot of the current system state.
This triggers the creation of a persistent snapshot that can be
used for later analysis or visualization.
Returns:
StructuralCommandResult with success status and message.
Raises:
RuntimeError: If the bridge is not properly initialized.
"""
...
# ============================================================================
# Utility Functions
# ============================================================================
def is_command_success(result: StructuralCommandResult) -> bool:
"""Check if a StructuralCommandResult indicates success.
Args:
result: The command result to check.
Returns:
True if the command succeeded, False otherwise.
"""
return result.ok
def is_command_failure(result: StructuralCommandResult) -> bool:
"""Check if a StructuralCommandResult indicates failure.
Args:
result: The command result to check.
Returns:
True if the command failed, False otherwise.
"""
return not result.ok
def command_result_to_json(result: StructuralCommandResult) -> JSONMapping:
"""Convert a StructuralCommandResult to a JSON-serializable dictionary.
Args:
result: The command result to convert.
Returns:
A dictionary with 'ok' and 'message' keys.
"""
return {"ok": result.ok, "message": result.message}
# ============================================================================
# Error Codes
# ============================================================================
class StructuralErrorCode:
"""Common error codes for structural operator operations.
These can be used to provide more structured error information
in command results.
"""
SUCCESS = "success"
NOT_FOUND = "not_found"
CONFIGURATION_ERROR = "configuration_error"
ENGINE_NOT_READY = "engine_not_ready"
INVALID_PROPOSAL = "invalid_proposal"
INVALID_KIND = "invalid_kind"
LIMIT_EXCEEDED = "limit_exceeded"
UNDO_FAILED = "undo_failed"
TICK_FAILED = "tick_failed"
SNAPSHOT_FAILED = "snapshot_failed"
AUTO_APPROVAL_ERROR = "auto_approval_error"
# ============================================================================
# Extended Command Result
# ============================================================================
@dataclass(frozen=True, slots=True)
class ExtendedStructuralCommandResult:
"""Extended command result with additional metadata.
This extends the basic StructuralCommandResult with optional
error codes, details, and timestamps. It can be used for
more detailed error reporting and debugging.
Attributes:
ok: True if the command succeeded, False otherwise.
message: A human-readable message describing the result.
code: Optional error code for categorized error handling.
details: Optional additional structured data.
timestamp: Optional ISO format timestamp of the result.
"""
ok: bool
message: str
code: str | None = None
details: dict[str, JSONValue] | None = None
timestamp: str | None = None
def to_json(self) -> JSONMapping:
"""Convert to a JSON-serializable dictionary."""
result: JSONMapping = {"ok": self.ok, "message": self.message}
if self.code is not None:
result["code"] = self.code
if self.details is not None:
result["details"] = self.details
if self.timestamp is not None:
result["timestamp"] = self.timestamp
return result
@classmethod
def success(
cls,
message: str,
code: str = StructuralErrorCode.SUCCESS,
details: dict[str, JSONValue] | None = None,
) -> ExtendedStructuralCommandResult:
"""Create a successful extended result."""
return cls(
ok=True,
message=message,
code=code,
details=details,
timestamp=datetime.now().isoformat(),
)
@classmethod
def failure(
cls,
message: str,
code: str = StructuralErrorCode.CONFIGURATION_ERROR,
details: dict[str, JSONValue] | None = None,
) -> ExtendedStructuralCommandResult:
"""Create a failed extended result."""
return cls(
ok=False,
message=message,
code=code,
details=details,
timestamp=datetime.now().isoformat(),
)
def to_basic(self) -> StructuralCommandResult:
"""Convert to a basic StructuralCommandResult."""
return StructuralCommandResult(ok=self.ok, message=self.message)
# ============================================================================
# Protocol Implementation Helper
# ============================================================================
# ... (restliche Datei bleibt unverändert) ...
def validate_bridge(
bridge: StructuralOperatorBridge | None,
) -> StructuralOperatorBridge:
"""Validate that a bridge is properly configured.
Args:
bridge: The bridge instance to validate.
Returns:
The validated bridge instance.
Raises:
TypeError: If bridge is not a StructuralOperatorBridge.
RuntimeError: If bridge is None.
"""
if bridge is None:
raise RuntimeError("Structural operator bridge is not configured")
# The type annotation guarantees bridge is a StructuralOperatorBridge when not None.
# No runtime isinstance check needed.
return bridge
|