This commit is contained in:
Lars committed 2026-08-29 11:04:34 +02:00
1 parent 4f37991ad1
commit be11f82f84
39 files changed
+2490 -239

No files matched your search

+35 -11
View File
@@ -9,7 +9,7 @@ import re
import time
from entity_detect import DetectError, detect_personal_egress, reset_detect_test_hooks, user_detect_message
from identity_store import KINSHIP, is_maskable_label, mapping_spellings
from identity_store import KINSHIP, is_maskable_label, is_registry_maskable_label, mapping_spellings
from journal_reconstruct import claim_texts, fake_reconstruction, is_dialogue_role_line
from prompt_budget import (
ERROR_PROVIDER_CONTEXT_LENGTH,
@@ -75,7 +75,9 @@ COMPACT_DIAGNOSTIC_KEYS = (
"chunks_ok",
"entity_counts",
"confirmed_registry_hits",
"confirmed_registry_applied",
"request_local_hits",
"semantic_identity_guaranteed",
"detect_calls",
"detect_prompt_tokens",
"detect_completion_tokens",
@@ -338,7 +340,7 @@ def is_identity_mention(text: str, start: int, end: int, token: str) -> bool:
def identity_occurrence_count(text: str, label: str, token: str) -> int:
"""Public, intent-neutral count of identity mentions for one mapping."""
if not label or not is_maskable_label(label):
if not label or not is_registry_maskable_label(label):
return 0
return sum(
1
@@ -373,12 +375,22 @@ def _identity_occurrence_count(text: str, label: str, token: str) -> int:
return identity_occurrence_count(text, label, token)
def _mapping_label_allowed(item: dict) -> bool:
label = (item.get("local_label") or "").strip()
token = (item.get("token") or "").strip()
if not label or not token:
return False
if (item.get("source") or "") == "confirmed_registry":
return is_registry_maskable_label(label)
return is_maskable_label(label)
def _active_replacements(text: str, mappings: list[dict]) -> tuple[ActiveReplacement, ...]:
found: list[ActiveReplacement] = []
for item in mappings or []:
label = (item.get("local_label") or "").strip()
token = (item.get("token") or "").strip()
if not label or not token or not is_maskable_label(label):
if not _mapping_label_allowed(item):
continue
count = _identity_occurrence_count(text, label, token)
if count <= 0:
@@ -447,7 +459,7 @@ def _mask_body(text: str, mappings: list[dict]) -> str:
for item in sorted(mappings, key=lambda row: len(row.get("local_label") or ""), reverse=True):
label = (item.get("local_label") or "").strip()
token = (item.get("token") or "").strip()
if not label or not token or not is_maskable_label(label):
if not _mapping_label_allowed(item):
continue
placeholder = _placeholder_of(token)
pattern = _label_pattern(label)
@@ -572,7 +584,7 @@ def mask_prompt(rendered: str, mappings: list[dict], purpose: str) -> MaskingMan
for item in mappings or []:
label = (item.get("local_label") or "").strip()
token = (item.get("token") or "").strip()
if not label or not token or not is_maskable_label(label):
if not _mapping_label_allowed(item):
continue
has_span_fields = item.get("start") is not None and item.get("end") is not None
grounded = _ground_mapping_span(text, item) if has_span_fields else None
@@ -683,8 +695,13 @@ def _demask(text: str, manifest: MaskingManifest | None) -> str:
return PLACEHOLDER_RE.sub(repl, result)
def _visible_response(content: str, manifest: MaskingManifest | None) -> str:
"""Stored output: original model text with only emitted placeholders rehydrated."""
return _demask((content or "").strip(), manifest)
def _normalize_active_cleartext(text: str, manifest: MaskingManifest | None) -> tuple[str, int]:
"""Map active identity cleartext back to the request token. Local only, no retry."""
"""Map active identity cleartext back to the request token. Check copy only; never stored."""
if not manifest or not manifest.replacements:
return text or "", 0
hits: list[tuple[int, int, str]] = []
@@ -711,7 +728,7 @@ def _normalize_active_cleartext(text: str, manifest: MaskingManifest | None) ->
def _process_response(content: str, manifest: MaskingManifest | None = None) -> tuple[str, dict[str, Any]]:
"""Integrity check after the model reply. Does not undo egress and does not retry."""
"""Integrity check after the model reply. Tokenized copy is not the visible output."""
text = (content or "").strip()
if not text:
raise PrivacyGatewayError("empty_provider_response", "Der Provider lieferte keine Antwort.")
@@ -725,7 +742,7 @@ def _process_response(content: str, manifest: MaskingManifest | None = None) ->
def _validate_response(content: str, manifest: MaskingManifest | None = None) -> str:
"""Compatibility wrapper: normalize active cleartext, then return tokenized text."""
"""Compatibility wrapper: tokenized check copy. Not the stored user-facing text."""
text, _meta = _process_response(content, manifest)
return text
@@ -910,6 +927,8 @@ def complete(request: GatewayRequest) -> GatewayResult:
detect_calls=detect_stats.get("detect_calls"),
request_local_hits=detect_stats.get("request_local_hits"),
confirmed_registry_hits=detect_stats.get("confirmed_registry_hits"),
confirmed_registry_applied=detect_stats.get("confirmed_registry_applied"),
semantic_identity_guaranteed=False,
entity_counts=detect_stats.get("entity_counts"),
detect_ms=detect_stats.get("detect_ms"),
detect_prompt_tokens=detect_stats.get("detect_prompt_tokens"),
@@ -982,7 +1001,9 @@ def complete(request: GatewayRequest) -> GatewayResult:
"chunks_ok": detect_stats.get("chunks_ok"),
"entity_counts": detect_stats.get("entity_counts"),
"confirmed_registry_hits": detect_stats.get("confirmed_registry_hits"),
"confirmed_registry_applied": detect_stats.get("confirmed_registry_applied"),
"request_local_hits": detect_stats.get("request_local_hits"),
"semantic_identity_guaranteed": False,
"detect_calls": detect_stats.get("detect_calls"),
"detect_ms": detect_stats.get("detect_ms"),
"generate_called": False,
@@ -1048,7 +1069,6 @@ def complete(request: GatewayRequest) -> GatewayResult:
)
usages: list[dict] = []
raw = ""
validated = ""
chat = None
try:
_log_event(
@@ -1067,7 +1087,7 @@ def complete(request: GatewayRequest) -> GatewayResult:
request_trace["generate_calls"] = 1
_log_event(events, started, "model_result", attempt=1, **_usage_bits(chat.usage))
raw = chat.content
validated, process_meta = _process_response(raw, manifest)
_tokenized, process_meta = _process_response(raw, manifest)
diagnostics["response_validation"] = process_meta["response_validation"]
diagnostics["response_normalization"] = process_meta["response_normalization"]
diagnostics["normalized_cleartext_count"] = process_meta["normalized_cleartext_count"]
@@ -1124,7 +1144,7 @@ def complete(request: GatewayRequest) -> GatewayResult:
sum_usages(usages) or chat.usage,
chat.model or (config.model if config else None),
)
result.content = _demask(validated, manifest)
result.content = _visible_response(raw, manifest)
result.allowed = True
result.local_identities = local_identities
result.diagnostics = compact_diagnostics(diagnostics)
@@ -1169,8 +1189,12 @@ def public_trace(trace: dict | None) -> dict | None:
"chunks_ok": trace.get("chunks_ok"),
"entity_counts": trace.get("entity_counts"),
"confirmed_registry_hits": trace.get("confirmed_registry_hits"),
"confirmed_registry_applied": trace.get("confirmed_registry_applied"),
"request_local_hits": trace.get("request_local_hits"),
"semantic_identity_guaranteed": False,
"detect_calls": trace.get("detect_calls"),
"stored_title": trace.get("stored_title"),
"stored_body": trace.get("stored_body"),
"detect_ms": trace.get("detect_ms"),
"generate_ms": (trace.get("budget") or {}).get("generate_ms") if isinstance(trace.get("budget"), dict) else trace.get("generate_ms"),
"generate_called": trace.get("generate_called"),