Spaces:
Sleeping
Sleeping
File size: 7,139 Bytes
3d5c3e3 | 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 | """Deterministic registered rules and seed derivation for world engines."""
import hashlib
import inspect
import math
from collections.abc import Callable
from datetime import UTC, datetime
from world_compiler.domain.events import (
EventEnvelope,
EventType,
Provenance,
ResolvedPrincipal,
RuleAppliedPayload,
WorldStateChangedPayload,
)
from world_compiler.domain.schemas.rules import DecisionRule
from world_compiler.infrastructure.database.store import EventStore
from world_compiler.runtime.orchestrator.context import SessionScope
from world_compiler.runtime.rules.symbols import REGISTRY_VERSION
__all__ = [
"REGISTRY_VERSION",
"RULE_REGISTRY",
"apply_rule",
"derive_seed",
"registry_hashes",
"rule_hash",
]
def defect_rate_update(current: float, adjustment: float) -> float:
"""Return the deterministic next defect rate for the registered v1 rule."""
return round(current + adjustment, 6)
RULE_REGISTRY: dict[str, Callable] = {"defect_rate_update": defect_rate_update}
def rule_hash(name: str) -> str:
"""Return the source hash for one registered deterministic rule."""
try:
fn = RULE_REGISTRY[name]
except KeyError as exc:
raise KeyError(f"unknown registered rule {name!r}") from exc
return hashlib.sha256(inspect.getsource(fn).encode("utf-8")).hexdigest()
def registry_hashes() -> dict[str, str]:
"""Return the source hashes for the complete registered-rule catalog."""
return {name: rule_hash(name) for name in RULE_REGISTRY}
def derive_seed(session_seed: int, stream: str, turn: int | str) -> int:
"""Derive a stable SQLite-safe seed from a stream discriminator."""
material = f"{session_seed}:{stream}:{turn}".encode()
return int.from_bytes(hashlib.sha256(material).digest()[:8], "big") & (
(1 << 63) - 1
)
def apply_rule(
rule: DecisionRule,
world: dict,
store: EventStore,
scope: SessionScope,
turn: int,
) -> dict:
"""Apply one registered pure rule and append its auditable state delta."""
if len(rule.writes_variables) != 1:
raise ValueError("v1 deterministic rules must write exactly one variable")
try:
fn = RULE_REGISTRY[rule.registered_fn]
except KeyError as exc:
raise KeyError(f"unknown registered rule {rule.registered_fn!r}") from exc
variable_id = rule.writes_variables[0]
try:
current = world[variable_id]
except KeyError as exc:
raise KeyError(f"world is missing rule variable {variable_id!r}") from exc
world_inputs = {"current": current}
collisions = world_inputs.keys() & rule.params.keys()
if collisions:
names = ", ".join(sorted(collisions))
raise ValueError(f"rule params collide with world-derived inputs: {names}")
inputs = {**rule.params, **world_inputs}
_require_finite_numbers(inputs, "rule inputs")
output = fn(**inputs)
_require_finite_numbers({variable_id: output}, "rule outputs")
new_world = dict(world)
new_world[variable_id] = output
outputs = {variable_id: output}
changes = {variable_id: {"from": current, "to": output}}
state_visibility = _variable_visibility(scope, variable_id)
existing = {
event.event_id: event
for event in store.read_all(
scope.tenant_id,
scope.course_id,
scope.session_id,
scope.scenario_id,
scope.scenario_version,
)
}
scope_prefix = f"{scope.tenant_id}:{scope.course_id}:{scope.session_id}"
rule_event_id = f"rule:{scope_prefix}:{rule.rule_id}:{turn}"
state_event_id = f"world:{scope_prefix}:{rule.rule_id}:{turn}"
rule_event = _event(
event_id=rule_event_id,
scope=scope,
turn=turn,
event_type=EventType.RULE_APPLIED,
payload=RuleAppliedPayload(
rule_id=rule.rule_id,
rule_hash=rule_hash(rule.registered_fn),
inputs=inputs,
outputs=outputs,
).model_dump(mode="json"),
visibility=[_instructor(scope)],
created_at=_existing_or_now(existing, rule_event_id),
)
store.append("rules_engine", rule_event, idempotency_key=rule_event_id)
state_event = _event(
event_id=state_event_id,
scope=scope,
turn=turn,
event_type=EventType.WORLD_STATE_CHANGED,
payload=WorldStateChangedPayload(changes=changes).model_dump(mode="json"),
visibility=state_visibility,
parent_event_ids=[rule_event.event_id],
created_at=_existing_or_now(existing, state_event_id),
)
store.append("rules_engine", state_event, idempotency_key=state_event_id)
return new_world
def _event(
*,
event_id: str,
scope: SessionScope,
turn: int,
event_type: EventType,
payload: dict,
visibility: list[ResolvedPrincipal],
parent_event_ids: list[str] | None = None,
created_at: datetime,
) -> EventEnvelope:
parent_event_ids = parent_event_ids or []
return EventEnvelope(
event_id=event_id,
tenant_id=scope.tenant_id,
course_id=scope.course_id,
session_id=scope.session_id,
scenario_id=scope.scenario_id,
scenario_version=scope.scenario_version,
turn=turn,
actor_id=None,
event_type=event_type,
payload=payload,
visibility=visibility,
provenance=Provenance(source_event_ids=list(parent_event_ids)),
rng_seed=None,
parent_event_ids=list(parent_event_ids),
retention_class=scope.retention_class,
created_at=created_at,
)
def _variable_visibility(
scope: SessionScope, variable_id: str
) -> list[ResolvedPrincipal]:
templates = scope.world_variable_visibility.get(variable_id)
if not templates:
raise ValueError(f"world variable {variable_id!r} has no governance visibility")
return [
template.resolve(
scope.tenant_id,
scope.course_id,
scope.session_id,
dict(scope.role_to_actor),
)
for template in templates
]
def _require_finite_numbers(values: dict, label: str) -> None:
nonfinite = [
name
for name, value in values.items()
if isinstance(value, (int, float))
and not isinstance(value, bool)
and not math.isfinite(value)
]
if nonfinite:
names = ", ".join(sorted(nonfinite))
raise ValueError(f"{label} must be finite: {names}")
def _existing_or_now(existing: dict[str, EventEnvelope], event_id: str) -> datetime:
prior = existing.get(event_id)
return prior.created_at if prior is not None else datetime.now(UTC)
def _instructor(scope: SessionScope) -> ResolvedPrincipal:
return ResolvedPrincipal(
kind="instructor",
tenant_id=scope.tenant_id,
course_id=scope.course_id,
session_id=scope.session_id,
)
|