FTSeffectCodecircuit-breaker
Chapter 10 · Code Snippet 10.2

The Circuit Breaker

FTSeffect 2.0 entropy engine

Reference implementation of the FTSeffect 2.0 Entropy Engine: a probabilistic model that scores velocity, sentiment, the Provenance Gap, and bot-style repetition into a single chaos score, and trips a throttling circuit breaker above 0.90.

fts_entropy_engine.py165 lines · Python
# File: fts_entropy_engine.py
# Purpose: The 'Circuit Breaker' algorithm for throttling viral disinformation.
#
# Note on variable names (FTSeffect 2.0 deconfliction):
# The original FTSeffect formula (Chapter 5) reserves V = Volume,
# R = Rational Deliberation, and P is unused. To avoid collisions,
# the 2.0 additions use two-letter codes:
# VE = Velocity (rate of spread, distinct from Volume)
# RP = Repetition (bot-swarm pattern, distinct from R)
# PG = Provenance Gap (share of unsigned content)
# s is the sentiment (Emotion) signal inherited from the original FTSeffect.
import math
from dataclasses import dataclass
# Engine actions (p. 184).
CIRCUIT_BREAK = "CIRCUIT_BREAK"
PASS = "PASS"
CIRCUIT_BREAK_THRESHOLD = 0.90
@dataclass
class Event:
"""One claim as the engine sees it: every share of it so far."""
timestamps: list[float] # when each share happened, in seconds
text_samples: list[str] # the message text of each share
sentiment_valence: float # -1.0 (negative) to 1.0 (positive)
sentiment_arousal: float # 0.0 (calm) to 1.0 (agitated)
provenance_gap: float # Notary provenance_gap, else unsigned share; clamped to [0, 1]
class FTSeffectCalculator:
"""
The Entropy Engine (FTSeffect 2.0): a probabilistic model for detecting
saturation attacks by measuring the Provenance Gap.
"""
def __init__(self, repetition_weight: float = 1.0):
# The Provenance Gap is added to the raw score as is (weight 1): the
# formula on p. 184 already weights it heavily by adding it outside
# the ve * s * rp product.
self.repetition_weight = repetition_weight
self.signal_buffer: list[dict] = []
def ingest_stream(self, data_packet: dict) -> None:
"""
Ingests a real-time social signal (one share of the claim).
Expected packet shape:
{
'timestamp': float, # seconds
'text': str, # message text
'sentiment_valence': float, # -1.0 to 1.0 (rage is strongly negative)
'sentiment_arousal': float, # 0.0 to 1.0
'has_c2pa': bool, # True if cryptographically signed
'provenance_gap': float, # optional: RealityValidator result
}
"""
self.signal_buffer.append(data_packet)
# --- Signals -----------------------------------------------------------
@staticmethod
def velocity(timestamps: list[float]) -> float:
"""VE: shares per second across the observed window. Uncapped, so a
fast enough swarm can push the score past the threshold."""
if not timestamps:
return 0.0
span = max(timestamps) - min(timestamps)
return len(timestamps) / max(span, 1.0)
def repetition(self, text_samples: list[str]) -> float:
"""RP: share of messages that repeat near-identical wording, in
[0.0, 1.0]. A value near 1 indicates coordinated/bot behavior."""
if not text_samples:
return 0.0
normalized = {" ".join(t.lower().split()) for t in text_samples}
ratio = 1 - (len(normalized) / len(text_samples))
return max(0.0, min(1.0, ratio * self.repetition_weight))
@staticmethod
def sentiment(valence: float, arousal: float) -> float:
"""s: emotional intensity in [0.0, 1.0], from 0.0 (neutral) to
1.0 (extreme rage or euphoria)."""
return max(0.0, min(1.0, abs(valence) * arousal))
def current_event(self) -> Event:
"""Aggregates the buffered shares into one Event."""
n = len(self.signal_buffer)
# Per share: the Notary's provenance_gap if present, else 0.0 for
# signed and 1.0 for unsigned (so the mean is the unsigned share).
gaps = [p.get("provenance_gap", 0.0 if p.get("has_c2pa") else 1.0)
for p in self.signal_buffer]
return Event(
timestamps=[p["timestamp"] for p in self.signal_buffer],
text_samples=[p["text"] for p in self.signal_buffer],
sentiment_valence=sum(p["sentiment_valence"] for p in self.signal_buffer) / n,
sentiment_arousal=sum(p["sentiment_arousal"] for p in self.signal_buffer) / n,
provenance_gap=sum(gaps) / n,
)
# --- Score -------------------------------------------------------------
def calculate_entropy_score(self) -> float:
"""
Returns the current chaos score (entropy) in [0.0, 1.0).
A score above 0.90 triggers the 'circuit breaker' (throttling).
"""
if not self.signal_buffer:
return 0.0
event = self.current_event()
ve = self.velocity(event.timestamps)
rp = self.repetition(event.text_samples)
s = self.sentiment(event.sentiment_valence, event.sentiment_arousal)
pg = max(0.0, min(1.0, event.provenance_gap))
# Implements the formula printed on p. 184.
raw = (ve * s * rp) + pg
entropy = 1.0 - math.exp(-raw)
return entropy
def evaluate(self) -> str:
"""Returns CIRCUIT_BREAK if the entropy score exceeds 0.90, else PASS."""
entropy = self.calculate_entropy_score()
action = CIRCUIT_BREAK if entropy > 0.90 else PASS
return action
def circuit_breaker_triggered(self, threshold: float = CIRCUIT_BREAK_THRESHOLD) -> bool:
"""Returns True if the platform should throttle algorithmic boost
on the current signal until verification can catch up."""
return self.calculate_entropy_score() > threshold
def _stream(engine, shares, seconds, text, valence, arousal, signed):
for i in range(shares):
engine.ingest_stream({
"timestamp": i * seconds / shares,
"text": text(i),
"sentiment_valence": valence,
"sentiment_arousal": arousal,
"has_c2pa": signed,
})
return engine
if __name__ == "__main__":
# Runnable example: python3 fts_entropy_engine.py
cases = (
# Organic: 50 shares over 100 s, calm, signed, every message different.
("organic", PASS, _stream(FTSeffectCalculator(), 50, 100.0,
lambda i: f"my take {i}", 0.2, 0.2, True)),
# Unsigned but organic: PG alone gives 1 - e^-1 (about 0.63).
("unsigned", PASS, _stream(FTSeffectCalculator(), 50, 100.0,
lambda i: f"my take {i}", 0.2, 0.2, False)),
# Bot swarm: 500 shares in 2 s, enraged, unsigned, one script.
("bot swarm", CIRCUIT_BREAK, _stream(FTSeffectCalculator(), 500, 2.0,
lambda i: "THEY are lying to you", -0.95, 1.0, False)),
)
for name, expected, engine in cases:
entropy = engine.calculate_entropy_score()
action = engine.evaluate()
print(f"{name}: entropy={entropy:.4f} action={action}")
assert action == expected, (name, action)
assert engine.circuit_breaker_triggered() == (action == CIRCUIT_BREAK)
print("all checks passed")