Files
qtalker---/backend/tests/test_entropy.py
Indiana b8e69b4bd3 feat: the room decides — physical entropy, real astronomy, unprompted speech
Three changes that together replace "deterministic hash decides everything"
with "the physical world genuinely participates".

PHYSICAL ENTROPY (app/entropy.py, lib/entropy.ts)

Contact was a database lookup: signature_from_anomalies() hashed the
anomaly pattern, so identical conditions always produced an identical
spirit. Now the client harvests real thermal/acoustic/RF noise from the
microphone and receiver noise floors — Von Neumann debiased, SHA-256
conditioned — and contributes it to every summon.

The client is untrusted by construction. A contribution is never a seed:
every draw is HMAC-SHA256(fresh server secret, client bytes || context).
Because fresh CSPRNG server bytes are always present, the output is
unpredictable and uniform no matter what the client sends — all-zeros, a
replayed value, or one chosen adversarially. The room can only ever ADD
unpredictability, never steer the result. Tests assert this directly:
400 replays of one contribution stay uniformly distributed.

A signature now identifies a *channel*, not a spirit. Whether the familiar
presence answers or something else picks up is a real draw
(RETURN_CHANCE). The Codex stays collectable; it is just no longer
guaranteed. test_same_signature_recontacts_same_entity became two tests —
one pinning the probability to prove re-contact works, one pinning it to
zero to prove something else can answer — because at 0.72 the original
would have passed ~72% of the time, which is worse than failing.

REAL ASTRONOMY (app/celestial.py)

Moon phase from the standard mean-synodic approximation, and true solar
midnight from the seeker's own longitude — the real witching hour for
where they are standing, not clock 3am. Computed, never fetched: an API
that can fail would mean the veil silently changes behaviour during
someone else's outage. Validated against published ephemeris dates (2024
full moons, 2025 new moons) rather than against its own output. A thinner
veil erodes the familiar presence's claim on a channel, so a full moon at
solar midnight makes strangers likelier. Only longitude is kept, never a
full coordinate; a denied location degrades to moon-only, silently.

GENERATION FROM NOTHING (SpiritService.manifest)

Not chat_stream with an empty question. The prompt contains no seeker
input at all — only measured room state, rendered as measurements
("deviation above the floor: 31.4") rather than interpretations
("terrifying spike"), so the horror comes from the entity instead of from
us. And the Ollama `seed` is derived from the physical entropy harvested
in that room, which fixes the token-sampling path: the room genuinely
selects the words. Change the noise, get different speech. Two rooms
cannot produce the same utterance.

Rendered as an intrusion rather than a reply — violet edge, full opacity
against the faded ambient murmurs, brief blur-in. The unsettling part is
that it is perfectly clear and completely unbidden.

Also fixes a hang I introduced: the two new summon tests consumed the
shared module-level per-IP budget, so test_summon_rate_limited_* blocked
forever on an entity frame that had been rate-limited away. They now scope
their own limiters.

264 backend + 355 frontend tests pass; i18n parity gate passes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 05:38:59 +00:00

118 lines
4.5 KiB
Python

"""Tests for the veil's randomness mixing.
The property that actually matters here is adversarial: a client that
controls its entropy contribution completely must not be able to control,
predict, or bias the outcome. Most of these tests attack that directly
rather than just checking the happy path.
"""
import collections
from app.entropy import (
contribution_bits,
normalize_contribution,
veil_float,
veil_random,
veil_seed,
)
class TestNormalizeContribution:
def test_parses_a_hex_digest(self):
assert normalize_contribution("00ff10") == b"\x00\xff\x10"
def test_empty_for_non_string_input(self):
for junk in (None, 123, {"a": 1}, [1, 2], b"bytes"):
assert normalize_contribution(junk) == b""
def test_empty_for_blank_string(self):
assert normalize_contribution("") == b""
assert normalize_contribution(" ") == b""
def test_non_hex_still_contributes_rather_than_being_discarded(self):
# A client with a different encoding shouldn't silently stop
# contributing physical noise; mixing raw text is harmless.
assert normalize_contribution("not-hex-at-all") != b""
def test_truncates_an_oversized_payload(self):
huge = "ab" * 10_000
assert len(normalize_contribution(huge)) <= 512
def test_never_raises_on_hostile_input(self):
for junk in ("zz", "0", "0x1234", "\x00\x01", "💀" * 50, "-1"):
normalize_contribution(junk) # must not raise
class TestVeilSeed:
def test_returns_32_bytes(self):
assert len(veil_seed("aabb")) == 32
def test_identical_input_produces_different_seeds(self):
# THE core security property: the same client contribution must
# NOT reproduce the same draw, or a seeker could replay a
# contribution that once yielded a mythic entity.
seeds = {veil_seed("deadbeef").hex() for _ in range(200)}
assert len(seeds) == 200
def test_unpredictable_even_with_no_contribution_at_all(self):
seeds = {veil_seed().hex() for _ in range(200)}
assert len(seeds) == 200
def test_unpredictable_with_an_adversarially_degenerate_contribution(self):
# All-zeros is the worst case a client can send.
seeds = {veil_seed("00" * 32).hex() for _ in range(200)}
assert len(seeds) == 200
def test_context_domain_separates_draws(self):
# Two draws from one contribution must not be correlated, so
# learning one (e.g. the visible rarity) reveals nothing about the
# other (the hidden traits).
a = {veil_seed("aabb", "entity").hex() for _ in range(100)}
b = {veil_seed("aabb", "traits").hex() for _ in range(100)}
assert not (a & b)
class TestVeilRandom:
def test_returns_a_usable_random_instance(self):
rng = veil_random("aabb")
assert 0.0 <= rng.random() < 1.0
assert rng.choice([1, 2, 3]) in (1, 2, 3)
def test_successive_calls_are_independent(self):
first = [veil_random("same").random() for _ in range(50)]
assert len(set(first)) == 50
def test_client_cannot_force_a_repeated_outcome(self):
# Simulates a seeker replaying one contribution to grind for a rare
# result: the distribution must stay spread out.
draws = [veil_random("c0ffee", "rarity").random() for _ in range(400)]
assert len(set(draws)) == 400
buckets = collections.Counter(int(d * 4) for d in draws)
# With 400 draws across 4 buckets, a client steering the result
# would show up as a badly skewed histogram.
for count in buckets.values():
assert 40 < count < 210
def test_output_is_roughly_uniform(self):
draws = [veil_float() for _ in range(2000)]
buckets = collections.Counter(int(d * 10) for d in draws)
assert len(buckets) == 10
for count in buckets.values():
assert 120 < count < 290 # ~200 expected, generous bounds
def test_mean_is_near_a_half(self):
draws = [veil_float("aabb", "spread") for _ in range(2000)]
assert 0.45 < sum(draws) / len(draws) < 0.55
class TestContributionBits:
def test_counts_bits_of_real_contribution(self):
assert contribution_bits("00ff") == 16
assert contribution_bits("") == 0
assert contribution_bits(None) == 0
def test_a_lying_client_cannot_inflate_beyond_the_cap(self):
# Display-only, but it still must not become an unbounded number
# driven by client input.
assert contribution_bits("ab" * 10_000) <= 512 * 8