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.
114 lines
5.1 KiB
Python
114 lines
5.1 KiB
Python
"""Query anonymization before INIT (his design, 22/10): the model must
|
|
decompose the question's SHAPE, not lean on its knowledge of the people in
|
|
it. Named entities are masked to typed placeholders (PERSON_1, ORGANIZATION_1,
|
|
...) before INIT sees the query; the placeholders are restored in the
|
|
returned subquestions — deterministically, by exact string replacement.
|
|
|
|
LLMs translate (NER proposal); fixed code applies and restores (ALGORITHM
|
|
§7: LLMs never decide). The mask map is run-scoped state, not a prompt.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
|
|
import dspy
|
|
from pydantic import BaseModel
|
|
|
|
|
|
class NamedEntity(BaseModel):
|
|
"""One named entity found in the question."""
|
|
name: str = dspy.OutputField(
|
|
desc="the entity's exact surface text as it appears in the question, copied verbatim")
|
|
kind: str = dspy.OutputField(
|
|
desc="PERSON, ORGANIZATION, PLACE, WORK, EVENT, or OTHER")
|
|
|
|
|
|
class EntityMaskSignature(dspy.Signature):
|
|
"""You are the MASK step of a reasoning machine. Find the named entities
|
|
in the question — people, organizations, places, titles of works, events.
|
|
Copy each one's text exactly as it appears; do not add entities that are
|
|
not explicitly named."""
|
|
question: str = dspy.InputField()
|
|
entities: list[NamedEntity] = dspy.OutputField(
|
|
desc="the named entities found; empty when none")
|
|
|
|
|
|
# placeholder order: PERSON_1, PERSON_2, ORGANIZATION_1, ...
|
|
_PREFIX = {"PERSON": "PERSON", "ORGANIZATION": "ORGANIZATION", "PLACE": "PLACE",
|
|
"WORK": "WORK", "EVENT": "EVENT", "OTHER": "OTHER"}
|
|
|
|
|
|
def apply_mask(question: str, entities: list[NamedEntity]) -> tuple[str, dict]:
|
|
"""Mask the question deterministically. Longer names first (so
|
|
'Pedro Sánchez Pérez-Castejón' is masked before its substrings).
|
|
Returns (masked_question, restore_map placeholder -> original)."""
|
|
restore: dict[str, str] = {}
|
|
counters: dict[str, int] = {}
|
|
masked = question
|
|
for ent in sorted(entities, key=lambda e: len(e.name), reverse=True):
|
|
name = ent.name.strip()
|
|
if not name or name not in masked:
|
|
continue
|
|
kind = ent.kind.strip().upper()
|
|
prefix = _PREFIX.get(kind, "OTHER")
|
|
counters[prefix] = counters.get(prefix, 0) + 1
|
|
ph = f"{prefix}_{counters[prefix]}"
|
|
if ph in restore: # same surface text twice: keep one mask
|
|
continue
|
|
masked = masked.replace(name, ph)
|
|
restore[ph] = name
|
|
return masked, restore
|
|
|
|
|
|
def restore_mask(text: str, restore: dict[str, str]) -> str:
|
|
"""Restore placeholders to the original names, longest first (so
|
|
PERSON_10 is not eaten by PERSON_1)."""
|
|
for ph, name in sorted(restore.items(), key=lambda kv: len(kv[0]),
|
|
reverse=True):
|
|
text = text.replace(ph, name)
|
|
return text
|
|
|
|
|
|
# an identity question about ONE placeholder — the model asking who/what
|
|
# the mask refers to. Detection lives in identity_answer: conservative
|
|
# by law (his: never over-detect) — 'who/what is <ph>' exactly, or the
|
|
# text names the mask mechanism ('placeholder', 'refer(s) to').
|
|
|
|
|
|
def identity_answer(masked_text: str, restore: dict[str, str]) -> str | None:
|
|
"""If a subquestion only asks who/what one placeholder refers to, the
|
|
answer is the mask map itself — no expert ever needed. None otherwise.
|
|
|
|
Conservative by law (never over-detect): exactly one placeholder in
|
|
the text, and the question is literally 'who/what is <ph>' (ending
|
|
there or in punctuation — 'who is PERSON_1's predecessor' does NOT
|
|
match) or it names the mask mechanism with the placeholder as the
|
|
REFERENT: 'refer(s) to' must govern <ph> DIRECTLY ('what does
|
|
PERSON_1 refer to?', 'the placeholder PERSON_1 refers to…'). A bare
|
|
'refer to' anywhere in the sentence no longer fires — his 23/10 run:
|
|
INIT's hidden-precondition phrasing 'does the title "President"
|
|
refer to in relation to PERSON_1?' asked about the TITLE, the old
|
|
clause seeded 'Pedro Sanchez' as the answer to which office was
|
|
meant (a false positive with wrong semantics)."""
|
|
phs = [ph for ph in restore if re.search(rf"\b{re.escape(ph)}\b",
|
|
masked_text)]
|
|
if len(phs) != 1:
|
|
return None
|
|
ph = phs[0]
|
|
t = masked_text.strip()
|
|
# lookahead: end-of-sentence/punctuation AFTER the placeholder — but
|
|
# never an apostrophe: "PERSON_1's predecessor" is a possessive, not an
|
|
# identity question (pre-existing trap found while verifying the 23/10
|
|
# fix; the old test only covered 'Who WAS…', which dodges the literal)
|
|
literal = re.match(
|
|
rf"^(?:who|what)\s+(?:is|are)\s+{re.escape(ph)}(?=$|[\s,.?!:;)\"])",
|
|
t, flags=re.IGNORECASE)
|
|
if literal:
|
|
return restore[ph]
|
|
# mechanism mention: strict — the placeholder must be the REFERENT of
|
|
# 'refer(s) to', not merely present in a sentence that uses the verb
|
|
for pat in (rf"\brefer(?:s)?\s+to\s+{re.escape(ph)}\b",
|
|
rf"{re.escape(ph)}\s+refer(?:s)?\s+to\b"):
|
|
if re.search(pat, t, flags=re.IGNORECASE):
|
|
return restore[ph]
|
|
return None |