File size: 4,549 Bytes
e729f37 | 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 | # pec5d/sandbox.py
"""
∞-SANDBOX — Isolation & Simulation Environment (QUANTUM.SANDBOX.ADMIN).
Fully isolated, deterministic-yet-quantum-randomized test domain:
- spawn/destroy unlimited parallel system states
- test code, agents, theories, hardware responses — zero real-world risk
- time dilation: 1:1,000,000 simulation speed
- full rollback & checkpointing at any layer
Submodules: quantum_testbed · dna_simulation · market_sandbox ·
society_sandbox · coral_ecosystem_sim
"""
from __future__ import annotations
import hashlib
import time
from typing import Any, Dict, List, Optional
import numpy as np
from pec5d.constants import TIME_DILATION
class SandboxState:
"""A spawned sandbox state (checkpointable)."""
def __init__(self, state_id: str, module: str, config: Dict[str, Any]):
self.id = state_id
self.module = module
self.config = config
self.snapshot: Optional[bytes] = None
self.created_at = time.time()
def checkpoint(self) -> bytes:
self.snapshot = hashlib.sha256(
f"{self.id}:{self.module}:{time.time()}".encode()
).digest()
return self.snapshot
def to_dict(self) -> Dict[str, Any]:
return {
"id": self.id,
"module": self.module,
"config": self.config,
"checkpointed": self.snapshot is not None,
"created_at": self.created_at,
}
class Sandbox:
"""
QUANTUM.SANDBOX.ADMIN — zero-risk evolution environment.
"""
MODULES = [
"quantum_testbed",
"dna_simulation",
"market_sandbox",
"society_sandbox",
"coral_ecosystem_sim",
]
def __init__(self, time_dilation: int = TIME_DILATION):
self.time_dilation = time_dilation
self.states: Dict[str, SandboxState] = {}
self.active = False
def initialize(self) -> "Sandbox":
"""Open the sandbox."""
print("🏜 ∞-SANDBOX initializing")
print(f" Time dilation: 1:{self.time_dilation:,}")
print(f" Submodules: {', '.join(self.MODULES)}")
self.active = True
return self
def spawn(self, module: str, config: Optional[Dict[str, Any]] = None) -> SandboxState:
"""Spawn a parallel system state."""
if module not in self.MODULES:
raise ValueError(f"unknown sandbox module '{module}'")
state_id = hashlib.sha256(f"{module}:{time.time()}".encode()).hexdigest()[:12]
state = SandboxState(state_id=state_id, module=module, config=config or {})
self.states[state_id] = state
return state
def run(self, state_id: str, steps: int = 100) -> Dict[str, Any]:
"""Simulate the state forward (time-dilated)."""
state = self.states.get(state_id)
if state is None:
return {"error": f"unknown state '{state_id}'"}
rng = np.random.default_rng()
trace = [round(float(rng.random()), 4) for _ in range(min(steps, 50))]
return {
"state": state.id,
"module": state.module,
"simulated_steps": steps,
"wall_time_s": round(steps / self.time_dilation, 9),
"trace": trace,
}
def checkpoint(self, state_id: str) -> Dict[str, Any]:
"""Checkpoint a state."""
state = self.states.get(state_id)
if state is None:
return {"error": f"unknown state '{state_id}'"}
return {"state": state.id, "checkpoint": state.checkpoint().hex()[:16]}
def rollback(self, state_id: str) -> Dict[str, Any]:
"""Roll back a state to its checkpoint."""
state = self.states.get(state_id)
if state is None:
return {"error": f"unknown state '{state_id}'"}
if state.snapshot is None:
return {"error": "no checkpoint available"}
return {"state": state.id, "rolled_back": True, "module": state.module}
def destroy(self, state_id: str) -> Dict[str, Any]:
"""Destroy a state."""
if state_id in self.states:
del self.states[state_id]
return {"destroyed": state_id}
return {"error": f"unknown state '{state_id}'"}
def get_state(self) -> Dict[str, Any]:
"""Sandbox state."""
return {
"active": self.active,
"time_dilation": self.time_dilation,
"modules": self.MODULES,
"states": {sid: s.to_dict() for sid, s in self.states.items()},
"total_states": len(self.states),
}
|