Files
floop/code/tests/anonymize.py
T
onibot 8a3f8b37e3 floop: strict mask-seed detection + WARNING on seeded answers
His 23/10 review of the merged run found Q1's answer missing from the
stream. Chain, verified against the real code:

1. Q1 ('...does the title "President" refer to in relation to
   PERSON_1?') fired the mask-seed detector's loose mechanism clause —
   any 'refer to' in the sentence, even when the verb governs the
   TITLE, not the placeholder. The seed answered 'Pedro Sanchez' to a
   question that asked which OFFICE 'President' means: wrong semantics,
   a false positive born from the collision of the detector's word
   list with INIT's new hidden-precondition phrasing.

Fixes (both his ask):
- identity_answer STRICT: the mechanism clause now fires only with the
  placeholder as the REFERENT of 'refer(s) to' (regex adjacency, both
  orders). The literal 'who/what is <ph>' clause is unchanged.
- Found while verifying: the literal clause's lookahead accepted
  apostrophes, so 'Who is PERSON_1's predecessor?' (possessive) seeded
  too — the old test only covered 'Who WAS...'. Apostrophe removed from
  the end-of-question char class; possessives never seed again.
- THE SEED IS NOW LOUD: RunStreams.warn() (new channel — WARNING line
  in run.log, [W] on screen ALWAYS, even non-verbose) fires on every
  seeded answer: 'WARNING SEED auto-answered Q1 ... (mask map; zero
  expert calls)'. Self-improvement signal (META): which phrasings the
  seed eats belongs to the lessons bank, and it must be legible that
  the machine auto-answered without any expert.

Also: ARCHITECTURE.md §9-bis — OpenTelemetry observability roadmap
(his future plan ask): run = trace, calls/steps/rows = spans carrying
today's log fields, events.jsonl as the shared bus, warnings as
first-class span events; deferred until the loop hardening settles.

Tests: anonymize +4 assertions (his false positive, possessive trap,
strict positive shapes), machine +1 (seed WARNING lands in run.log).
Suite 17/17.
2026-10-23 16:03:13 +02:00

155 lines
6.8 KiB
Python

"""Query anonymization tests (his design, 22/10): INIT must decompose the
question's SHAPE, not lean on its knowledge of the named people in it.
Laws under test:
1. MASK proposes entities; apply_mask/restore_mask are DETERMINISTIC —
longer names first, one mask per surface text, typed placeholders.
2. init_decompose masks before INIT and restores in the subquestions.
3. No entities found -> the question reaches INIT unchanged.
4. MASK dying (AdapterParseError) -> passthrough, never a dead run.
No network; RawEngine returns raw text (DummyLM bypasses the adapter).
Run: .venv/bin/python tests/anonymize.py
"""
from __future__ import annotations
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import warnings
warnings.filterwarnings("ignore")
import dspy
from dspy._vendor.lm15 import Response, TextPart, Message, Usage
from dspy.utils.exceptions import AdapterParseError
from floop.dspy_modules import FloopModules
from floop.anonymize import NamedEntity, apply_mask, identity_answer, restore_mask
def _lm(script: list[str]) -> None:
"""An engine replaying a script: one raw response per LM call."""
class RawEngine:
def __init__(self):
self.i = 0
def complete(self, request):
raw = script[min(self.i, len(script) - 1)]
self.i += 1
return Response(
id="x", model="t",
message=Message(role="assistant",
parts=(TextPart(text=raw),)),
finish_reason="stop",
usage=Usage(input_tokens=1, output_tokens=1, total_tokens=2))
dspy.configure(lm=dspy.LM("openai/test", engine=RawEngine(), cache=False))
Q = "Who was the President before Pedro Sanchez?"
_MASKED_ENTS = '''[[ ## entities ## ]]
[{"name": "Pedro Sanchez", "kind": "PERSON"}]
[[ ## completed ## ]]'''
_TWO_SUBS = '''[[ ## subquestions ## ]]
[{"text": "Which office does PERSON_1 hold as President?", "depends_on": [], "answer_type": "OPEN"},
{"text": "Who held that same office before PERSON_1 took office?", "depends_on": [1], "answer_type": "OPEN"}]
[[ ## completed ## ]]'''
def test_apply_restore_deterministic():
ents = [NamedEntity(name="Pedro Sanchez", kind="PERSON")]
masked, restore = apply_mask(Q, ents)
assert masked == "Who was the President before PERSON_1?", masked
assert restore == {"PERSON_1": "Pedro Sanchez"}
# longer first: a full name is never half-masked by a shorter one
ents2 = [NamedEntity(name="Pedro Sanchez", kind="PERSON"),
NamedEntity(name="Pedro", kind="PERSON")]
m2, r2 = apply_mask("Pedro Sanchez and Pedro", ents2)
assert m2 == "PERSON_1 and PERSON_2", m2
assert restore_mask(m2, r2) == "Pedro Sanchez and Pedro"
# restore order: PERSON_10 before PERSON_1
r3 = {f"PERSON_{i}": f"name{i}" for i in range(1, 11)}
assert "name10" in restore_mask("PERSON_10", r3)
print("ok: apply/restore deterministic (longest-first, typed, reorder-safe)")
def test_init_decompose_masks_and_restores():
# script: first call = MASK, second = INIT
_lm([_MASKED_ENTS, _TWO_SUBS])
subs, raw = FloopModules().init_decompose(Q)
assert len(subs) == 2, subs
assert "Pedro Sanchez" in subs[0]["text"] and "PERSON_1" not in subs[0]["text"], subs[0]
assert subs[1]["deps"] == [1]
print("ok: INIT sees the masked query; subquestions come back restored")
def test_no_entities_passthrough():
_lm(['''[[ ## entities ## ]]
[]
[[ ## completed ## ]]''', _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
subs, _ = FloopModules().init_decompose(Q)
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
print("ok: no entities found -> question reaches INIT unchanged")
_TWO_SUBS_ID = '''[[ ## subquestions ## ]]
[{"text": "Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", "depends_on": [], "answer_type": "OPEN"},
{"text": "Which office does PERSON_1 hold as President?", "depends_on": [1], "answer_type": "OPEN"},
{"text": "Who held that office before PERSON_1?", "depends_on": [2], "answer_type": "OPEN"}]
[[ ## completed ## ]]'''
def test_identity_subquestion_seeded():
# the live PR-16 shape: subquestion 1 asks who PERSON_1 is — the mask
# map already knows. It must come back marked known_answer, never routed.
_lm([_MASKED_ENTS, _TWO_SUBS_ID])
subs, _ = FloopModules().init_decompose(Q)
assert len(subs) == 3, subs
assert subs[0].get("known_answer") == "Pedro Sanchez", subs[0]
assert not subs[1].get("known_answer") and not subs[2].get("known_answer")
print("ok: identity subquestion carries known_answer (never routed)")
def test_identity_detection_conservative():
# 'who is PERSON_1's predecessor' is NOT an identity question
r = {"PERSON_1": "Pedro Sanchez"}
assert identity_answer("Who is PERSON_1?", r) == "Pedro Sanchez"
assert identity_answer("What is ORGANIZATION_1?", {"ORGANIZATION_1": "PSOE"}) == "PSOE"
assert identity_answer("Which specific individual does the placeholder refer to?", r) is None
assert identity_answer("Who is PERSON_1, i.e., which specific individual does the placeholder refer to?", r) == "Pedro Sanchez"
assert identity_answer("Who is PERSON_1's predecessor?", r) is None
assert identity_answer("Who was PERSON_1's predecessor?", r) is None
assert identity_answer("What office does PERSON_1 hold?", r) is None
assert identity_answer("Who is PERSON_1 compared to PERSON_2?", {**r, "PERSON_2": "x"}) is None
# his 23/10 false positive: 'refer to' about the TITLE, not the
# placeholder — the hidden-precondition INIT phrasing. Strict law:
# 'refer(s) to' fires only with the placeholder as its REFERENT.
assert identity_answer(
'What country, organization, or office does the title "President" '
'refer to in relation to PERSON_1?', r) is None
# and the strict mechanism shapes still fire
assert identity_answer("What does the placeholder PERSON_1 refer to?", r) == "Pedro Sanchez"
assert identity_answer("the term PERSON_1 refers to in the question", r) == "Pedro Sanchez"
print("ok: identity detection conservative (possessives/comparatives/title-refer not eaten)")
def test_mask_death_passthrough():
# MASK response violates the schema -> AdapterParseError -> passthrough
_lm(["garbage", _TWO_SUBS.replace("PERSON_1", "Pedro Sanchez")])
subs, _ = FloopModules().init_decompose(Q)
assert len(subs) == 2 and "Pedro Sanchez" in subs[0]["text"]
print("ok: MASK death -> passthrough, never a dead run")
if __name__ == "__main__":
test_apply_restore_deterministic()
test_init_decompose_masks_and_restores()
test_no_entities_passthrough()
test_identity_subquestion_seeded()
test_identity_detection_conservative()
test_mask_death_passthrough()
print("\nanonymization tests passed")