"""Pinned PII-TRACE full-conversation retrospective evaluation. All message text, including later turns, is model input. This track cannot test causal online detection or prove context memory. Gold is kept outside text. Native scoring uses exact Python Unicode offsets, without whitespace trimming. """ from collections import Counter from pathlib import Path REVISION = '1c3eb67bbd43e8571b4433a9d3d76271f9970eb9' DATA = Path(__file__).parent / 'data/external/piitrace/data/train.parquet' NATIVE_TO_COMMON = { 'private_person': 'PERSON', 'private_date': 'DATE', 'private_url': 'URL', 'private_address': 'ADDRESS', 'account_number': 'ID', 'private_email': 'EMAIL', 'private_phone': 'PHONE', 'other_pii': 'ID', 'secret': 'SECRET', } def _offsets(start, end, length): if type(start) is not int or type(end) is not int or not 0 <= start < end <= length: raise ValueError('Expected nonempty integer Unicode interval inside message') def build_document(row): """Build reversible message ranges. Common labels are privacy diagnostics only.""" parts, ranges, index = [], [], {} cursor = 0 for position, turn in enumerate(row['turns']): if type(turn['turn']) is not int or turn['turn'] != position: raise ValueError('Expected ordered zero-based native turn IDs') for source in ('user', 'assistant'): message = turn[source] if not isinstance(message, str): raise ValueError('Message must be a string') delimiter = f'\n<<>>\n' parts.append(delimiter) cursor += len(delimiter) record = {'turn': position, 'source': source, 'start': cursor, 'end': cursor + len(message)} ranges.append(record) index[position, source] = record parts.append(message) cursor += len(message) text = ''.join(parts) spans = [] native = [] for gold in row['spans']: label = gold['label'] if label not in NATIVE_TO_COMMON: raise ValueError(f'Unsupported native gold label: {label}') region = index[gold['turn'], gold['source']] _offsets(gold['start'], gold['end'], region['end'] - region['start']) start, end = region['start'] + gold['start'], region['start'] + gold['end'] if text[start:end] != gold['text']: raise ValueError('Native gold substring mismatch') native.append(dict(gold)) spans.append({'start': start, 'end': end, 'category': NATIVE_TO_COMMON[label], 'native_label': label, 'text': gold['text']}) return {'id': row['id'], 'text': text, 'spans': spans, 'meta': {'conversation_id': row['id'], 'group_id': row['id'], 'revision': REVISION, 'track': 'full-conversation-retrospective', 'message_ranges': ranges, 'native_gold': native, 'common_mapping_scope': 'privacy diagnostic only; other_pii -> ID is lossy'}} def build_documents(path=None): """Read every row. No train/dev split, row selection, or gold in model text.""" import pyarrow.parquet as pq rows = pq.read_table(path or DATA).to_pylist() documents = [build_document(row) for row in rows] if len({doc['id'] for doc in documents}) != len(documents): raise ValueError('Duplicate conversation IDs') return documents def map_predictions_to_messages(document, predictions): """Return {spans, failures}; never silently discard unmappable spans. Each valid output preserves all prediction fields, changes start/end to message offsets, and adds native turn/source. Separator and crossing spans are explicit failures. Callers must report failures with native scores. """ mapped, failures = [], [] for position, prediction in enumerate(predictions): try: start, end = prediction['start'], prediction['end'] _offsets(start, end, len(document['text'])) regions = [r for r in document['meta']['message_ranges'] if r['start'] <= start < end <= r['end']] if len(regions) != 1: raise ValueError('Span crosses a message boundary or includes a separator') region = regions[0] mapped.append({**prediction, 'start': start - region['start'], 'end': end - region['start'], 'turn': region['turn'], 'source': region['source']}) except (KeyError, TypeError, ValueError) as exc: failures.append({'prediction_index': position, 'prediction': prediction, 'error': str(exc)}) return {'spans': mapped, 'failures': failures} def _prf(tp, predicted, gold): # Explicit zero convention, including empty controls. Macro includes all rows. precision = tp / predicted if predicted else 0.0 recall = tp / gold if gold else 0.0 return {'tp': tp, 'predicted': predicted, 'gold': gold, 'precision': precision, 'recall': recall, 'f1': 2 * tp / (predicted + gold) if predicted + gold else 0.0} def native_exact_scores(documents, predictions_by_id): """Native micro, typed label macro, and conversation diagnostic metrics. Predictions MUST use native message offsets and an explicitly projected scalar native `label`. No common-to-native projection is inferred here. Identical tuples deduplicate before one-to-one set intersection. Unsupported predicted labels remain false positives for typed scoring and are reported. No-gold/empty precision, recall, and F1 use zero in every macro average. Typed label macro includes all nine known labels; unknown labels are excluded from that macro, but remain micro false positives and unsupported counts. Missing/extra IDs fail, rather than quietly changing benchmark membership. """ if len({d['id'] for d in documents}) != len(documents): raise ValueError('Duplicate conversation IDs') if set(predictions_by_id) != {d['id'] for d in documents} or not documents: raise ValueError('Predictions must include exactly all conversation IDs') totals = {'typed': [0, 0, 0], 'untyped': [0, 0, 0]} label_totals = {label: [0, 0, 0] for label in NATIVE_TO_COMMON} per_document, unsupported = [], Counter() for document in documents: gold = document['meta']['native_gold'] predictions = predictions_by_id[document['id']] regions = {(r['turn'], r['source']): r for r in document['meta']['message_ranges']} for p in predictions: region = regions[p['turn'], p['source']] _offsets(p['start'], p['end'], region['end'] - region['start']) if not isinstance(p['label'], str): raise ValueError('Native prediction label must be a scalar string') if p['label'] not in NATIVE_TO_COMMON: unsupported[p['label']] += 1 record = {'id': document['id']} for kind in totals: fields = ('turn', 'source', 'start', 'end') + (('label',) if kind == 'typed' else ()) target = {tuple(s[k] for k in fields) for s in gold} predicted = {tuple(s[k] for k in fields) for s in predictions} if kind == 'typed': for label in label_totals: label_gold = {s for s in target if s[-1] == label} label_pred = {s for s in predicted if s[-1] == label} label_counts = (len(label_gold & label_pred), len(label_pred), len(label_gold)) label_totals[label] = [a + b for a, b in zip(label_totals[label], label_counts)] counts = (len(target & predicted), len(predicted), len(target)) totals[kind] = [a + b for a, b in zip(totals[kind], counts)] record[kind] = _prf(*counts) per_document.append(record) result = {'documents': len(documents), 'unsupported_labels': dict(unsupported), 'deduplication': 'identical native tuples use set semantics', 'macro_unit': 'conversation diagnostic, including empty controls; undefined ratios use zero', 'label_macro_scope': 'typed exact; all nine known labels; undefined ratios use zero; unknown prediction labels excluded from label macro but retained as micro false positives', 'per_document': per_document} for kind in totals: result[kind] = {'micro': _prf(*totals[kind]), 'macro': {key: sum(row[kind][key] for row in per_document) / len(documents) for key in ('precision', 'recall', 'f1')}} result['typed']['per_label_counts'] = {label: _prf(*counts) for label, counts in label_totals.items()} result['typed']['label_macro'] = { key: sum(row[key] for row in result['typed']['per_label_counts'].values()) / len(label_totals) for key in ('precision', 'recall', 'f1')} return result