This commit is contained in:
Lars committed 2026-08-28 08:40:28 +02:00
1 parent f17b3083e8
commit 4f37991ad1
48 files changed
+4919 -540

No files matched your search

+100 -42
View File
@@ -22,12 +22,12 @@ from identity_store import remember_mapping
from main import app
from privacy_gateway import (
ERROR_EGRESS_VALIDATION,
IDENTITY_LEAK_RETRY,
ActiveReplacement,
GatewayRequest,
MaskingManifest,
PrivacyGatewayError,
_demask,
_process_response,
_validate_response,
complete,
last_trace,
@@ -90,14 +90,10 @@ def main() -> None:
kinship = mask_prompt("Meine Frau Sushi kam später.", sushi, "journal_generate")
expect(len(kinship.replacements) == 1, "identity mention of the same word is active")
blocked = False
try:
_validate_response("Sushi kam vorbei.", kinship)
except PrivacyGatewayError as exc:
blocked = exc.code == "response_validation_failed"
expect(exc.diagnostics.get("leak_tokens") == ["PERSON:01"], "block reports the token, not the label")
expect("Sushi" not in json.dumps(exc.diagnostics), "validation diagnostics omit the clear name")
expect(blocked, "active clear name in the raw reply is a leak")
normalized, meta = _process_response("Sushi kam vorbei.", kinship)
expect(normalized.startswith("[[PERSON:01]]"), "active cleartext is remapped to the request token")
expect(meta.get("response_normalization") == "active_cleartext_normalized", "normalization is named")
expect(_demask(normalized, kinship) == "Sushi kam vorbei.", "normalized reply demasks locally")
homonym_ok = _validate_response("Danach Sushi essen.", kinship)
expect("Sushi essen" in homonym_ok, "homonym in the reply uses the same classification rule")
@@ -107,7 +103,9 @@ def main() -> None:
leftover = _demask("[[PERSON:01]] und [[PERSON:99]]", kinship)
expect("Sushi" in leftover and "[[PERSON:99]]" in leftover, "inactive placeholder is not rematerialized")
expect("Clarissa" not in leftover, "inactive mapping label is not introduced by demask")
expect("[[" not in IDENTITY_LEAK_RETRY, "retry instruction must not teach bracket placeholders")
import privacy_gateway as gw
expect(not hasattr(gw, "IDENTITY_LEAK_RETRY"), "automatic identity-leak retry instruction is gone")
expect(
_demask("[[ person:01 ]] war ruhig.", kinship) == "Sushi war ruhig.",
"demask ignores case and inner spacing",
@@ -121,6 +119,25 @@ def main() -> None:
"generic ellipsis placeholders are not rematerialized",
)
alias_rows = [
{
"local_label": "Sushi",
"token": "PERSON:07",
"canonical_label": "Clarissa",
"demask_label": "Clarissa",
"aliases": ["Sushi"],
"labels": ["Clarissa", "Sushi"],
"entity_type": "PERSON",
}
]
aliased = mask_prompt("Sushi kam ins Wohnzimmer.", alias_rows, "journal_generate")
expect(len(aliased.replacements) == 1, "confirmed alias activates its token")
spellings = {label.casefold() for label in aliased.replacements[0].all_labels()}
expect(spellings == {"sushi", "clarissa"}, "request manifest keeps every spelling of the active token")
expect(_demask("[[PERSON:07]] kam.", aliased) == "Clarissa kam.", "confirmed alias demasks to the canonical spelling")
canonical_clear, _meta = _process_response("Clarissa kam vorbei.", aliased)
expect(canonical_clear.startswith("[[PERSON:07]]"), "canonical spelling of an active alias token is remapped")
overlap = mask_prompt(
"Anna-Lena kam vorbei.",
[
@@ -133,6 +150,54 @@ def main() -> None:
expect("[[PERSON:08]]" in overlap.masked_text, "longer label is the one replaced")
expect("Anna-Lena" not in overlap.masked_text, "replaced longer label is gone")
mixed_word = "Ich aß Sushi. Sushi kam später."
second = mixed_word.find("Sushi", mixed_word.find("Sushi") + 1)
span_only = mask_prompt(
mixed_word,
[
{
"local_label": "Sushi",
"token": "PERSON:01",
"entity_type": "PERSON",
"start": second,
"end": second + 5,
"text": "Sushi",
"source": "request_local",
}
],
"journal_generate",
)
expect(span_only.masked_text.startswith("Ich aß Sushi."), "undetected same wording stays unmasked")
expect("[[PERSON:01]] kam später." in span_only.masked_text, "only the detected span is masked")
validate_pre_egress(span_only.masked_text, span_only)
overlapping_spans = mask_prompt(
"Anna-Lena kam vorbei.",
[
{
"local_label": "Anna",
"token": "PERSON:01",
"entity_type": "PERSON",
"start": 0,
"end": 4,
"text": "Anna",
"source": "request_local",
},
{
"local_label": "Anna-Lena",
"token": "PERSON:08",
"entity_type": "PERSON",
"start": 0,
"end": 9,
"text": "Anna-Lena",
"source": "request_local",
},
],
"journal_generate",
)
expect("[[PERSON:08]]" in overlapping_spans.masked_text, "longest overlapping span wins")
expect("[[PERSON:01]]" not in overlapping_spans.masked_text, "shorter overlapping span is dropped")
subject = mask_prompt(
"Clarissa kaufte Kirschen.",
[{"local_label": "Clarissa", "token": "PERSON:99"}],
@@ -166,7 +231,7 @@ def main() -> None:
second = pool.submit(check, "Heute nur Markt.", anna + lars, "Anna kam.")
code_a, _text_a, tokens_a = first.result()
code_b, text_b, tokens_b = second.result()
expect(code_a == "response_validation_failed", "parallel request A still blocks its own active leak")
expect(code_a == "ok" and "[[PERSON:01]]" in (_text_a or ""), "parallel request A normalizes its own active cleartext")
expect(tokens_a == ["PERSON:01"], "parallel request A keeps its own active set")
expect(code_b == "ok" and "Anna kam" in (text_b or ""), "parallel request B is not blocked by A's mapping")
expect(tokens_b == [], "parallel request B does not inherit A's active set")
@@ -218,30 +283,26 @@ def main() -> None:
seen = []
def leak_then_ok(messages, _policy):
def leak_once(messages, _policy):
seen.append(messages[0].get("content") or "")
if len(seen) == 1:
return ChatResult(
content="Anna stand den ganzen Nachmittag am Markt.",
model="fake",
usage={"prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18, "cost": 0.01},
context_compression="not_applicable",
)
return ChatResult(
content="[[PERSON:01]] stand den ganzen Nachmittag am Markt.",
content="Anna stand den ganzen Nachmittag am Markt.",
model="fake",
usage={"prompt_tokens": 12, "completion_tokens": 8, "total_tokens": 20, "cost": 0.02},
usage={"prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18, "cost": 0.01},
context_compression="not_applicable",
)
with patch("privacy_gateway.complete_model", leak_then_ok):
with patch("privacy_gateway.complete_model", leak_once):
repaired = _run_gateway(profile_id, "Ich war mit Anna am Markt.")
expect(len(seen) == 2, "a real leak retries exactly once")
expect(IDENTITY_LEAK_RETRY in seen[1], "retry uses the generic correction instruction")
expect("Anna stand den ganzen Nachmittag" not in seen[1], "discarded raw reply is not part of the retry prompt")
expect("[[PERSON:01]]" in seen[0] and "Anna" not in seen[0].replace("[[PERSON:01]]", ""), "retry keeps the already masked prompt")
expect("Anna" in (repaired.content or ""), "successful retry is demasked locally")
expect(repaired.diagnostics.get("response_validation_retry") == 1, "retry is recorded without the raw reply")
expect(len(seen) == 1, "active cleartext does not start a second generate call")
expect("[[PERSON:01]]" in seen[0] and "Anna" not in seen[0].replace("[[PERSON:01]]", ""), "egress stays masked")
expect("Anna" in (repaired.content or ""), "normalized cleartext is demasked locally")
expect(repaired.diagnostics.get("generate_calls") == 1, "exactly one generate call")
expect(
repaired.diagnostics.get("response_normalization") == "active_cleartext_normalized",
"active cleartext is recorded as local normalization",
)
expect("Anna" not in json.dumps(repaired.diagnostics), "compact diagnostics omit the clear name")
def spaced_token(_messages, _policy):
return ChatResult(
@@ -258,10 +319,10 @@ def main() -> None:
"gateway demasks case and spacing variants",
)
expect("[[" not in (restored.content or ""), "no leftover placeholder after a successful demask")
expect(repaired.diagnostics.get("prompt_tokens") == 22, "retry aggregates prompt tokens")
expect(repaired.diagnostics.get("completion_tokens") == 16, "retry aggregates completion tokens")
expect(repaired.diagnostics.get("total_tokens") == 38, "retry aggregates total tokens")
expect(abs(float(repaired.diagnostics.get("cost") or 0) - 0.03) < 1e-9, "retry aggregates cost")
expect(repaired.diagnostics.get("prompt_tokens") == 10, "single call keeps prompt tokens")
expect(repaired.diagnostics.get("completion_tokens") == 8, "single call keeps completion tokens")
expect(repaired.diagnostics.get("total_tokens") == 18, "single call keeps total tokens")
expect(abs(float(repaired.diagnostics.get("cost") or 0) - 0.01) < 1e-9, "single call keeps cost")
inactive_calls = {"n": 0}
@@ -287,20 +348,17 @@ def main() -> None:
return ChatResult(
content="Anna stand den ganzen Nachmittag am Markt.",
model="fake",
usage={},
usage={"prompt_tokens": 4, "completion_tokens": 6, "total_tokens": 10, "cost": 0.002},
context_compression="not_applicable",
)
failed = False
with patch("privacy_gateway.complete_model", always_leak):
try:
_run_gateway(profile_id, "Ich war mit Anna am Markt.")
except PrivacyGatewayError as exc:
failed = exc.code == "response_validation_failed"
expect(exc.diagnostics.get("response_validation_retry") == 1, "failed retry is still only one extra call")
expect("Anna stand" not in json.dumps(exc.diagnostics.get("log") or []), "discarded reply is not persisted in the log")
expect(failed, "second leak stays fail-closed")
expect(len(retry_fail) == 2, "gateway stops after one retry")
accepted = _run_gateway(profile_id, "Ich war mit Anna am Markt.")
expect(len(retry_fail) == 1, "cleartext in the reply does not start a second model call")
expect("Anna" in (accepted.content or ""), "source-attested name is demasked after local normalization")
expect(accepted.diagnostics.get("generate_calls") == 1, "still exactly one generate call")
expect(accepted.trace.get("model") == "fake" or accepted.diagnostics.get("model") == "fake", "error-free trace keeps the model")
expect(accepted.diagnostics.get("completion_tokens") == 6, "token usage of the only call remains")
print("All privacy manifest tests passed.")