From 0fbec573ccd60388ee694a9e3d9b205648ed6bef Mon Sep 17 00:00:00 2001 From: Mby159 Date: Sat, 27 Jun 2026 00:37:21 +0800 Subject: [PATCH] fix: record placeholder validation metadata --- splitmind/core/engine.py | 120 ++++++++++++++++++++++++- tests/test_placeholder_preservation.py | 81 ++++++++++++++++- 2 files changed, 198 insertions(+), 3 deletions(-) diff --git a/splitmind/core/engine.py b/splitmind/core/engine.py index a0d14ae..b514e45 100644 --- a/splitmind/core/engine.py +++ b/splitmind/core/engine.py @@ -2,11 +2,12 @@ SplitMind Engine - Main orchestration engine. """ -from typing import List, Dict, Any, Optional +from typing import List, Dict, Any, Optional, Iterable from pydantic import BaseModel, Field from enum import Enum import asyncio from datetime import datetime +import re from splitmind.core.splitter import TaskSplitter, TaskSplitResult, SubTask, TaskType from splitmind.core.aggregator import ( @@ -173,6 +174,8 @@ async def execute( else: subtask_results = await self._execute_with_local(split_result.subtasks) + self._attach_placeholder_validation(split_result.subtasks, subtask_results) + # Step 5: Result Aggregation aggregated_result = self.result_aggregator.aggregate( results=subtask_results, @@ -193,6 +196,12 @@ async def execute( for st in split_result.subtasks: all_sensitive.update(st.sensitive_info) + provider_placeholder_validation = self._merge_placeholder_validation(subtask_results) + placeholder_validation = self._validate_placeholders_in_text( + final_result, + all_sensitive.keys(), + ) + if all_sensitive and isinstance(final_result, str): final_result = self.result_aggregator.restore_sensitive_info( final_result, @@ -206,6 +215,8 @@ async def execute( "local_model_used": bool(self.local_model and self.local_model.is_available()), "split_strategy_used": split_strategy, "providers_used": list(set(r.provider for r in subtask_results)), + "placeholder_validation": placeholder_validation, + "provider_placeholder_validation": provider_placeholder_validation, } return ExecutionResult( @@ -373,6 +384,113 @@ async def execute_single(subtask: SubTask, provider_name: str) -> SubTaskResult: return results + @staticmethod + def _validate_placeholders_in_text( + text: str, + expected_placeholders: Iterable[str], + ) -> Dict[str, Any]: + """Lightweight placeholder integrity check for provider output. + + This records evidence only. It does not attempt fuzzy recovery or mutate + model output. Restoration remains the exact placeholder replacement step. + """ + expected = list(expected_placeholders) + expected_set = set(expected) + text = text or "" + + observed = re.findall(r"\[REDACTED_[A-Z0-9_]+_\d+\]", text) + observed_set = set(observed) + found = [placeholder for placeholder in expected if placeholder in text] + missing = [placeholder for placeholder in expected if placeholder not in text] + unexpected = sorted(observed_set - expected_set) + + placeholder_like = re.findall(r"\[?REDACTED[^\s,。,.!?;:]*\]?", text, flags=re.IGNORECASE) + mangled = sorted( + { + candidate + for candidate in placeholder_like + if candidate not in expected_set and candidate not in observed_set + } + ) + + return { + "ok": not missing and not unexpected and not mangled, + "expected_placeholders": expected, + "found_placeholders": found, + "missing_placeholders": missing, + "unexpected_placeholders": unexpected, + "mangled_placeholders": mangled, + } + + def _attach_placeholder_validation( + self, + subtasks: List[SubTask], + results: List[SubTaskResult], + ) -> None: + """Attach per-subtask placeholder validation metadata to results.""" + subtasks_by_id = {subtask.id: subtask for subtask in subtasks} + for result in results: + subtask = subtasks_by_id.get(result.subtask_id) + expected = list(subtask.sensitive_info.keys()) if subtask else [] + result.metadata["placeholder_validation"] = self._validate_placeholders_in_text( + result.result, + expected, + ) + + @staticmethod + def _merge_placeholder_validation(results: List[SubTaskResult]) -> Dict[str, Any]: + """Merge per-result placeholder validation into execution metadata.""" + validations = [ + result.metadata.get("placeholder_validation", {}) + for result in results + if result.metadata.get("placeholder_validation") + ] + + def unique_ordered(values: Iterable[str]) -> List[str]: + seen = set() + ordered = [] + for value in values: + if value not in seen: + seen.add(value) + ordered.append(value) + return ordered + + expected = unique_ordered( + placeholder + for validation in validations + for placeholder in validation.get("expected_placeholders", []) + ) + found = unique_ordered( + placeholder + for validation in validations + for placeholder in validation.get("found_placeholders", []) + ) + missing = unique_ordered( + placeholder + for validation in validations + for placeholder in validation.get("missing_placeholders", []) + ) + unexpected = unique_ordered( + placeholder + for validation in validations + for placeholder in validation.get("unexpected_placeholders", []) + ) + mangled = unique_ordered( + placeholder + for validation in validations + for placeholder in validation.get("mangled_placeholders", []) + ) + + return { + "ok": not missing and not unexpected and not mangled, + "expected_placeholders": expected, + "found_placeholders": found, + "missing_placeholders": missing, + "unexpected_placeholders": unexpected, + "mangled_placeholders": mangled, + "subtasks_checked": len(validations), + } + def execute_sync( self, task: str, diff --git a/tests/test_placeholder_preservation.py b/tests/test_placeholder_preservation.py index 6f8c9be..6c57aab 100644 --- a/tests/test_placeholder_preservation.py +++ b/tests/test_placeholder_preservation.py @@ -5,8 +5,6 @@ placeholders exactly. The original sensitive values must never be sent. """ -import asyncio - from splitmind.core.engine import SplitMindEngine, ExecutionConfig, ExecutionMode from splitmind.providers.base import ( BaseProvider, @@ -21,6 +19,7 @@ class CapturingProvider(BaseProvider): last_prompt = None last_system_prompt = None + response_template = None def _default_model(self) -> str: return "capturing-model" @@ -38,11 +37,15 @@ def get_info(self): def generate(self, prompt, system_prompt=None, task_type=None, **kwargs): CapturingProvider.last_prompt = prompt CapturingProvider.last_system_prompt = system_prompt + if CapturingProvider.response_template is not None: + return CapturingProvider.response_template.format(prompt=prompt) return f"echo: {prompt}" async def generate_async(self, prompt, system_prompt=None, task_type=None, **kwargs): CapturingProvider.last_prompt = prompt CapturingProvider.last_system_prompt = system_prompt + if CapturingProvider.response_template is not None: + return CapturingProvider.response_template.format(prompt=prompt) return f"echo: {prompt}" @@ -99,6 +102,7 @@ def _run_online(self, task): def test_system_prompt_contains_placeholders_and_no_raw_values(self): CapturingProvider.last_prompt = None CapturingProvider.last_system_prompt = None + CapturingProvider.response_template = None task = "请分析这个客户需求,客户邮箱是 alice@example.com,手机号是 13800138000。" result = self._run_online(task) @@ -119,6 +123,7 @@ def test_system_prompt_contains_placeholders_and_no_raw_values(self): def test_no_instruction_when_no_sensitive_info(self): CapturingProvider.last_prompt = None CapturingProvider.last_system_prompt = None + CapturingProvider.response_template = None task = "Please summarize the benefits of unit testing." result = self._run_online(task) @@ -127,3 +132,75 @@ def test_no_instruction_when_no_sensitive_info(self): system_prompt = CapturingProvider.last_system_prompt assert system_prompt is not None assert "[REDACTED" not in system_prompt + + +class TestPlaceholderValidationMetadata: + """Engine records placeholder integrity evidence without fuzzy recovery.""" + + def _run_online(self, task): + engine = SplitMindEngine( + providers=[CapturingProvider()], + config=ExecutionConfig(execution_mode=ExecutionMode.ONLINE), + ) + return engine.execute_sync( + task, split_strategy="single", providers=["capturing"] + ) + + def setup_method(self): + CapturingProvider.last_prompt = None + CapturingProvider.last_system_prompt = None + CapturingProvider.response_template = None + + def test_records_found_placeholders_before_restoration(self): + CapturingProvider.response_template = "Provider kept placeholders: {prompt}" + + task = "请分析客户邮箱 alice@example.com 和手机号 13800138000。" + result = self._run_online(task) + + validation = result.metadata["placeholder_validation"] + assert validation["ok"] is True + assert validation["expected_placeholders"] == [ + "[REDACTED_EMAIL_0]", + "[REDACTED_PHONE_0]", + ] + assert validation["found_placeholders"] == validation["expected_placeholders"] + assert validation["missing_placeholders"] == [] + assert validation["mangled_placeholders"] == [] + # Restoration still happens after validation. + assert "alice@example.com" in result.final_result + assert "13800138000" in result.final_result + + def test_records_missing_placeholders_without_recovery(self): + CapturingProvider.response_template = "Provider omitted the private values." + + task = "请分析客户邮箱 alice@example.com 和手机号 13800138000。" + result = self._run_online(task) + + validation = result.metadata["placeholder_validation"] + assert validation["ok"] is False + assert validation["expected_placeholders"] == [ + "[REDACTED_EMAIL_0]", + "[REDACTED_PHONE_0]", + ] + assert validation["found_placeholders"] == [] + assert validation["missing_placeholders"] == validation["expected_placeholders"] + assert validation["mangled_placeholders"] == [] + assert result.final_result == "Provider omitted the private values." + + def test_records_mangled_placeholders_without_fuzzy_recovery(self): + CapturingProvider.response_template = ( + "Email token became REDACTED_EMAIL_0 but phone stayed [REDACTED_PHONE_0]." + ) + + task = "请分析客户邮箱 alice@example.com 和手机号 13800138000。" + result = self._run_online(task) + + validation = result.metadata["placeholder_validation"] + assert validation["ok"] is False + assert validation["found_placeholders"] == ["[REDACTED_PHONE_0]"] + assert validation["missing_placeholders"] == ["[REDACTED_EMAIL_0]"] + assert validation["mangled_placeholders"] == ["REDACTED_EMAIL_0"] + # Exact restoration only: the mangled email token is not guessed/recovered. + assert "REDACTED_EMAIL_0" in result.final_result + assert "alice@example.com" not in result.final_result + assert "13800138000" in result.final_result