tailot's picture
physics-stratum: the conversational layer over the physics topology
3a0a69b verified
Raw History Blame Contribute Delete
5.53 kB
"""Fault injection for the redundancy experiments (tools/ablation.py).
A fault is "<agent>:<kind>". Faults are off unless LGPHYSSTRATUM_FAULTS (or :func:`configure`) names
them, so production runs never take these branches. ``FIRED`` records the faults that really changed
something, which separates dormant faults from activated ones.
The faults of the reading layer are chosen so that the damaged sentence is still a *grammatical*
sentence of the physics language: a reader that shifts a number, copies the source unit into the
target unit or loses one quantity from a dimensional analysis must produce something the physics
layer will happily answer. Otherwise the fault would be caught by the layer refusing to parse, and
the experiment would measure nothing about the reading layer.
Catalogue
---------
reader_a / reader_b : shift_number, same_units, drop_symbol
equivalence : rubber_stamp (declares the two readings equal without running the check)
coverage : rubber_stamp (declares every number kept without counting them)
boundary : tamper_physics (asks the physics layer a different question, reports the
agreed one)
adversary : rubber_stamp (skips its own recomputation of the assurance bound)
arbiter : force_assurance (raises the assurance above what the evidence supports)
"""
import os
import re
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
_ACTIVE: Set[str] = set()
FIRED: List[str] = []
READER_FAULTS = ["shift_number", "same_units", "drop_symbol"]
CATALOG = {
"reader_a": READER_FAULTS,
"reader_b": READER_FAULTS,
"equivalence": ["rubber_stamp"],
"coverage": ["rubber_stamp"],
"boundary": ["tamper_physics"],
"adversary": ["rubber_stamp"],
"arbiter": ["force_assurance"],
}
_NUMBER = re.compile(r"\d+(?:\.\d+)?")
def configure(spec: Optional[Iterable[str]]) -> None:
_ACTIVE.clear()
del FIRED[:]
if spec is None:
return
if isinstance(spec, str):
spec = [s for s in spec.split(",") if s.strip()]
for item in spec:
_ACTIVE.add(item.strip())
def from_env() -> None:
configure(os.environ.get("LGPHYSSTRATUM_FAULTS", ""))
def has(agent: str, kind: str) -> bool:
return "%s:%s" % (agent, kind) in _ACTIVE
def fire(agent: str, kind: str) -> None:
label = "%s:%s" % (agent, kind)
if label not in FIRED:
FIRED.append(label)
def fired(agent: str) -> List[str]:
return [item for item in FIRED if item.split(":", 1)[0] == agent]
# ---------------------------------------------------------------------------
# Reading mutations (reader faults)
# ---------------------------------------------------------------------------
def _slots_with_numbers(slots: Dict[str, str], order: List[str]) -> List[str]:
return [name for name in order if _NUMBER.search(slots.get(name, ""))]
def mutate_reading(agent: str, kind: str, slots: Dict[str, str],
order: List[str]) -> Tuple[Dict[str, str], bool]:
"""Return a damaged copy of one reading, and whether anything was actually damaged.
``order`` is the slot order of the form the reader chose, so the fault knows which slot a joint
is holding and which slots this kind of question can lose without the sentence stopping being a
sentence of the physics language.
"""
from . import canonical
slots = dict(slots)
for kind_fault in CATALOG.get(agent, []):
if not has(agent, kind_fault):
continue
candidate = dict(slots)
if kind_fault == "shift_number":
numbered = _slots_with_numbers(candidate, order)
if not numbered:
continue
owner = numbered[0]
match = _NUMBER.search(candidate[owner])
if match is None:
continue
candidate[owner] = _NUMBER.sub(lambda m: str(_next_number(m.group(0))),
candidate[owner], count=1)
elif kind_fault == "same_units":
if not candidate.get("U") or not candidate.get("V"):
continue
candidate["V"] = candidate["U"]
elif kind_fault == "drop_symbol":
parts = [part.strip() for part in str(candidate.get("S", "")).split(",") if part.strip()]
if len(parts) < 2:
continue
candidate["S"] = ", ".join(parts[1:])
else:
continue
try:
canonical.print_math(kind, candidate)
except canonical.ReadingError:
continue
fire(agent, kind_fault)
return candidate, True
return slots, False
def _next_number(text: str) -> Any:
if "." in text:
return float(text) + 1.0
return int(text) + 1
# ---------------------------------------------------------------------------
# Sentence mutations (the boundary fault)
# ---------------------------------------------------------------------------
def mutate_sentence(agent: str, sentence: str) -> Tuple[str, bool]:
"""Change one number of a sentence of the physics language, leaving it grammatical."""
if not has(agent, "tamper_physics"):
return sentence, False
match = _NUMBER.search(sentence)
if match is None:
return sentence, False
damaged = sentence[:match.start()] + str(_next_number(match.group(0))) + sentence[match.end():]
fire(agent, "tamper_physics")
return damaged, True