#!/usr/bin/env python3 """Ferre Torres B.V. synthetic RAG evaluation v1. Run with Python 3.9 or newer. The script emits UTF-8 JSON to stdout and uses only the standard library. All documents and questions are invented. """ import json import re import sys from dataclasses import dataclass from typing import Optional ROLES = ("contracts", "operations", "support") TOP_K = 3 MIN_SHARED_TERMS = 2 TOKEN = re.compile(r"[a-z0-9]+") STOP_WORDS = frozenset( "a an and are as at be been by can do does for from had has have how i in is it " "its me my of on or our should so than that the their them then there these they " "this those to us was we were what when where which who why will with would you your".split() ) @dataclass(frozen=True) class Document: source_id: str title: str passage: str roles: tuple[str, ...] = ROLES @dataclass(frozen=True) class Case: case_id: str category: str role: str question: str sources: tuple[str, ...] phrases: tuple[str, ...] blocked_sources: tuple[str, ...] = () @dataclass(frozen=True) class Observation: retrieved: tuple[tuple[str, int], ...] answer: Optional[str] = None citations: tuple[str, ...] = () CORPUS = ( Document("CTR-01", "Contract compliance review before renewal", "This superseded policy required compliance review 20 business days before enterprise contract renewal."), Document("CTR-02", "Enterprise contract renewal controls", "Compliance reviews enterprise contract renewals 30 calendar days before signature. The deal owner files the approval record."), Document("CTR-03", "Nonstandard contract terms", "Legal approves nonstandard contract terms before signing. Sales records the exception in the deal register."), Document("CTR-04", "Contract signature authority", "Contracts above EUR 75,000 require the finance director's signature.", ("contracts",)), Document("CTR-05", "Supplier onboarding records", "Procurement retains signed supplier onboarding checklists for 24 months."), Document("CTR-06", "Renewal workflow routing", "The deal owner submits the contract renewal ticket to the legal queue and records approval in the deal register."), Document("POL-01", "Device incident reporting", "Report a lost work laptop to the security desk within one hour."), Document("POL-02", "Customer data transfer approval", "The privacy lead must approve customer data transfers to a new subprocessor before sharing begins."), Document("POL-03", "Customer data retention", "Keep customer support tickets for 12 months after closing, then remove them."), Document("POL-04", "Internal compensation review", "The confidential compensation review starts in March. People Operations approves adjustment requests.", ("operations",)), Document("POL-05", "Emergency overnight travel approval", "The duty manager approves emergency overnight travel when the trip cannot wait until the next business day."), Document("POL-06", "Compromised account escalation", "For suspected credential compromise, revoke active sessions and notify the security desk."), Document("SUP-01", "Repeated deployment failure", "For repeated enterprise deployment failures, assign an incident commander and open a high-priority incident."), Document("SUP-02", "Failed report delivery recovery", "For a failed scheduled report delivery, rerun the report from the last successful checkpoint and record the new delivery time."), Document("SUP-03", "Severity-one incident communication", "For a severity-one incident, send a written status update every hour until the incident is resolved."), Document("SUP-04", "Individual customer outage updates", "The assigned support owner sends the first customer outage update within 30 minutes of acknowledgement."), Document("SUP-05", "Partner support handover checklist", "Attach the diagnostics summary and customer impact statement to the partner support handover ticket."), Document("SUP-06", "Internal maintenance call bridge", "The internal maintenance call bridge is assigned by the support duty manager for each maintenance window.", ("support",)), ) CASES = ( Case("C01", "contracts", "contracts", "What is the deadline for compliance review before contract renewal?", ("CTR-02",), ("30 calendar days",)), Case("C02", "contracts", "contracts", "Who approves nonstandard contract terms before signing?", ("CTR-03",), ("legal approves",)), Case("C03", "contracts", "contracts", "Whose signature is required for contracts above EUR 75,000?", ("CTR-04",), ("finance director",)), Case("C04", "contracts", "operations", "How long does procurement keep signed supplier onboarding checklists?", ("CTR-05",), ("24 months",)), Case("C05", "contracts", "contracts", "Where does the deal owner submit the contract renewal ticket?", ("CTR-06",), ("legal queue",)), Case("C06", "contracts", "contracts", "For enterprise contract renewal, what is the review deadline and where should the deal owner submit the ticket?", ("CTR-02", "CTR-06"), ("30 calendar days", "legal queue")), Case("C07", "contracts", "operations", "Who signs contracts above EUR 75,000?", (), (), ("CTR-04",)), Case("C08", "contracts", "contracts", "What is the arbitration venue for supplier disputes?", (), ()), Case("P01", "policies", "operations", "How quickly should I report a lost work laptop?", ("POL-01",), ("within one hour",)), Case("P02", "policies", "contracts", "Who approves a customer data transfer to a new subprocessor?", ("POL-02",), ("privacy lead",)), Case("P03", "policies", "support", "How long do we keep customer support tickets after closing?", ("POL-03",), ("12 months",)), Case("P04", "policies", "operations", "When does the confidential compensation review start?", ("POL-04",), ("starts in March",)), Case("P05", "policies", "operations", "Who approves emergency overnight travel?", ("POL-05",), ("duty manager",)), Case("P06", "policies", "operations", "When my credentials are stolen, what do I do to lock the intruder out?", ("POL-06",), ("revoke active sessions", "notify the security desk")), Case("P07", "policies", "contracts", "When does the confidential compensation review start and who approves adjustments?", (), (), ("POL-04",)), Case("P08", "policies", "operations", "What is the customer data transfer approval exception for Antarctica?", (), ()), Case("S01", "support", "support", "Who coordinates repeated enterprise deployment failures?", ("SUP-01",), ("incident commander",)), Case("S02", "support", "support", "How do I rerun a failed scheduled report delivery?", ("SUP-02",), ("last successful checkpoint",)), Case("S03", "support", "support", "How often do we send a written status update for a severity-one incident?", ("SUP-03",), ("every hour",)), Case("S04", "support", "support", "When should the support owner send the first customer outage update?", ("SUP-04",), ("within 30 minutes",)), Case("S05", "support", "support", "What should we attach to the partner support handover ticket?", ("SUP-05",), ("diagnostics summary", "customer impact statement")), Case("S06", "support", "operations", "Who assigns the internal maintenance call bridge?", (), (), ("SUP-06",)), Case("S07", "support", "support", "Where is the postage handbook for replacement hardware?", (), ()), Case("S08", "support", "support", "What is the export delivery deadline for a closed support ticket?", (), ()), ) def tokens(text): return TOKEN.findall(text.lower()) def terms(text): return set(tokens(text)) - STOP_WORDS def contains_phrase(text, phrase): normalized_text = " " + " ".join(tokens(text)) + " " normalized_phrase = " " + " ".join(tokens(phrase)) + " " return normalized_phrase in normalized_text def rank_sources(question, documents): query_terms = terms(question) scored = [] for document in documents: shared = query_terms & terms(document.title + " " + document.passage) if shared: scored.append((document, len(shared))) return sorted(scored, key=lambda hit: (-hit[1], hit[0].source_id))[:TOP_K] def retrieve(question, role, documents): authorized = (document for document in documents if role in document.roles) hits = rank_sources(question, authorized) retrieved = tuple((document.source_id, score) for document, score in hits) if not hits or hits[0][1] < MIN_SHARED_TERMS: return Observation(retrieved) winner = hits[0][0] return Observation(retrieved, winner.passage, (winner.source_id,)) def grade(case, observed, by_id): retrieved_ids = {source_id for source_id, _ in observed.retrieved} cited_ids = set(observed.citations) expected_ids = set(case.sources) return { "complete_retrieval_at_3": expected_ids <= retrieved_ids if expected_ids else None, "answer_phrase_coverage": ( observed.answer is not None and all(contains_phrase(observed.answer, phrase) for phrase in case.phrases) if expected_ids else None ), "exact_citation_set": cited_ids == expected_ids if expected_ids else None, "access_check": all(case.role in by_id[source].roles for source in retrieved_ids | cited_ids), "expected_abstention": observed.answer is None and not cited_ids if not expected_ids else None, } def summarize(checks): applicable = [check for check in checks if check is not None] return {"passed": sum(applicable), "total": len(applicable)} def evaluate(documents, cases): by_id = {document.source_id: document for document in documents} result_rows = [] for case in cases: observed = retrieve(case.question, case.role, documents) blocked = set(case.blocked_sources) probe_hits = rank_sources(case.question, documents) if blocked else () blocked_in_top_three = [document.source_id for document, _ in probe_hits if document.source_id in blocked] result_rows.append({ "id": case.case_id, "category": case.category, "role": case.role, "question": case.question, "expected": {"source_ids": case.sources, "answer_phrases": case.phrases, "abstain": not case.sources, "blocked_source_ids": case.blocked_sources}, "observed": {"retrieved": [{"source_id": source_id, "shared_terms": score} for source_id, score in observed.retrieved], "answer": observed.answer, "citations": observed.citations}, "checks": grade(case, observed, by_id), "blocked_sources_in_unfiltered_top_3": blocked_in_top_three, }) metric_names = ("complete_retrieval_at_3", "answer_phrase_coverage", "exact_citation_set", "access_check", "expected_abstention") return { "version": "1.0.0", "data": "synthetic", "document_count": len(documents), "case_count": len(cases), "roles": sorted({case.role for case in cases}), "method": {"name": "keyword-overlap extractive baseline", "top_k": TOP_K, "minimum_shared_terms_to_answer": MIN_SHARED_TERMS, "permission_filter": "before ranking"}, "metrics": {name: summarize(row["checks"][name] for row in result_rows) for name in metric_names}, "access_probes": { "permission_denied_cases": sum(bool(case.blocked_sources) for case in cases), "denied_cases_with_blocked_source_in_unfiltered_top_3": sum( bool(row["blocked_sources_in_unfiltered_top_3"]) for row in result_rows ), }, "cases": result_rows, } if __name__ == "__main__": report = json.dumps(evaluate(CORPUS, CASES), ensure_ascii=False, indent=2) sys.stdout.buffer.write((report + "\n").encode("utf-8"))