Files
floop/code/tests/anonymize.py
T
onibot 4766b47127 floop: INIT told placeholders are resolved + identity seed (his design)
His two-part direction after the PR-16 live run (the model spent a
subquestion asking 'who is PERSON_1?'):

1. INIT desc now says masked entities (PERSON_1, ORGANIZATION_1...) are
   ALREADY-RESOLVED named entities — treat each as a known specific
   entity; do not ask what or who the placeholder is.
2. Safety net: identity_answer() detects a subquestion that ONLY asks
   who/what one placeholder refers to — the mask map already knows. The
   machine seeds it as evidence (engine=mask:seed, verified, zero LLM
   calls) instead of routing it to an expert.

Detection is deterministic and conservative by law: exactly one
placeholder in the text, literal 'who/what is <ph>' (ending there or in
punctuation — possessives like 'who is PERSON_1's predecessor' do NOT
match) or the text names the mask mechanism. Detection runs on the
MASKED text (placeholders still present) before restore.

VERIFIED: tests/anonymize.py 6/6 (seed marking, conservative detection
incl. possessives/comparatives/no-placeholder forms); suite 15/15.
Live E2E (glm-5.3-flash): with the new desc INIT returns exactly the
TWO subquestions he wants (term years + predecessor) — no identity
question, seed unused but armed; run answers Rajoy (E1+E2, 30 calls).
2026-10-22 17:03:44 +02:00

145 lines
6.1 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 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
print("ok: identity detection conservative (possessives/comparatives 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")