#!/usr/bin/env python3 """Reproduce synthetic documentation evidence-retention and drift experiments. Run with a real tokenizer: python3 scripts/documentation_benchmark.py --tokenizer cl100k_base For an explicitly different, byte-only experiment: python3 scripts/documentation_benchmark.py --tokenizer utf8_bytes No LLM, embeddings, API requests, human participants, or production system are used. """ from __future__ import annotations import argparse import hashlib import importlib.metadata import json import platform import re import statistics import sys from collections import Counter from datetime import datetime, timezone from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / 'scripts')) from lib.documentation_contracts import (MODES, classify_drift, evidence, normalize, pack_records, rank_records, render_record, revision_baseline, wrap_blocks) DATA = ROOT / 'datasets' / 'documentation-contracts' def read_json(path): return json.loads(path.read_text(encoding='utf-8')) def sha256(path): return hashlib.sha256(path.read_bytes()).hexdigest() def make_counter(name): if name == 'utf8_bytes': return (lambda value: len(value.encode('utf-8'))), {'name': 'utf8_bytes', 'unit': 'UTF-8 bytes'} if name != 'cl100k_base': raise ValueError('Unsupported counter: ' + name) try: import tiktoken enc = tiktoken.get_encoding(name) except Exception as exc: raise RuntimeError('cl100k_base requires tiktoken and its vocabulary; no automatic token estimate or fallback is used') from exc return (lambda value: len(enc.encode(value, disallowed_special=()))), { 'name': name, 'unit': 'tokens', 'package': 'tiktoken', 'package_version': importlib.metadata.version('tiktoken'), 'scope': 'Serialized context only; excludes question, instructions, model response, tools, and cache pricing.'} def decode_block(mode, text, expected_record_id=None): if mode in ('compact_core', 'task_bundle'): data = json.loads(text) if data.get('record') != expected_record_id or not isinstance(data.get('evidence'), list) or any(not isinstance(item, str) for item in data['evidence']): raise ValueError('Invalid compact record identity or evidence') return '\n'.join(data['evidence']) return text def score_blocks(blocks, mode, required, records_by_id): """Exact whole evidence spans inside the correct retained record block. This is an evidence-availability metric, not semantic entailment or answer accuracy. Whole fact strings must survive; an ID or an operator without its qualifier earns no credit. JSON is decoded before matching to avoid escaping artifacts. """ visible, invalid = {}, [] for rid, text in blocks: try: visible[rid] = normalize(decode_block(mode, text, rid)) except (ValueError, TypeError, KeyError): invalid.append(rid) retained, missing = [], [] for fact_id in required: rid = fact_id.split('.', 1)[0] fact_text = normalize(evidence(records_by_id[rid])[fact_id]) (retained if fact_text in visible.get(rid, '') else missing).append(fact_id) return {'retained': len(retained), 'required': len(required), 'complete': not missing, 'missing_fact_ids': missing, 'invalid_block_ids': invalid} def aggregate(rows): total = sum(row['required'] for row in rows) retained = sum(row['retained'] for row in rows) return {'tasks': len(rows), 'complete_tasks': sum(row['complete'] for row in rows), 'complete_task_rate': round(sum(row['complete'] for row in rows) / len(rows), 6), 'required_evidence_items': total, 'retained_evidence_items': retained, 'evidence_retention': round(retained / total, 6), 'median_context_units': statistics.median(row['context_units'] for row in rows), 'median_context_utf8_bytes': statistics.median(row['context_utf8_bytes'] for row in rows), 'min_context_units': min(row['context_units'] for row in rows), 'max_context_units': max(row['context_units'] for row in rows)} def confusion_binary(rows, prediction): matrix = {'tp': 0, 'fp': 0, 'tn': 0, 'fn': 0} for row in rows: actual = row['expected_status'] == 'DIVERGED' pred = prediction(row) matrix['tp' if actual and pred else 'fn' if actual else 'fp' if pred else 'tn'] += 1 matrix['precision'] = round(matrix['tp'] / (matrix['tp'] + matrix['fp']), 6) if matrix['tp'] + matrix['fp'] else None matrix['recall'] = round(matrix['tp'] / (matrix['tp'] + matrix['fn']), 6) if matrix['tp'] + matrix['fn'] else None return matrix def prefix_blocks(text): # Negative control uses Markdown only; complete spans in the clipped final block can score. pieces = re.split(r'\n', text) return [(pieces[i], pieces[i+1]) for i in range(1, len(pieces)-1, 2)] def prefix_under_budget(text, budget, count): # Character-safe bisection preserves valid Unicode. Count the actual serialized prefix. low, high = 0, len(text) while low < high: mid = (low + high + 1) // 2 if count(text[:mid]) <= budget: low = mid else: high = mid - 1 candidate = text[:low] # Token count is not strictly monotone across prefixes. This is a valid-budget # prefix, not a claim to find the mathematically longest prefix for BPE. while count(candidate) > budget: candidate = candidate[:-1] return candidate def run(tokenizer='cl100k_base'): corpus = read_json(DATA / 'corpus.json') task_data = read_json(DATA / 'tasks.json') event_data = read_json(DATA / 'drift-events.json') records, tasks, events = corpus['records'], task_data['tasks'], event_data['events'] records_by_id = {record['id']: record for record in records} count, measurement = make_counter(tokenizer) budgets = [256, 512, 1024] if tokenizer == 'cl100k_base' else [1024, 2048, 4096] rows, representation_rows, negative_rows, retrieval_rows = [], [], [], [] full_blocks = [(r['id'], render_record(r, 'full_markdown')) for r in records] full_text = wrap_blocks(full_blocks) full_rows = [] for task in tasks: # Gold required_fact_ids is not passed to the ranker, renderer, or packer. ranked = rank_records(task['query'], records) retrieval_rows.append({'task_id': task['id'], 'candidate_record_ids': ranked[:3]}) base = {'task_id': task['id'], 'kind': task['kind']} scored = score_blocks(full_blocks, 'full_markdown', task['required_fact_ids'], records_by_id) full_rows.append({**base, **scored, 'context_units': count(full_text), 'context_utf8_bytes': len(full_text.encode('utf-8'))}) for mode in MODES: unconstrained = pack_records(ranked, records_by_id, mode, task['kind'], count) context = wrap_blocks(unconstrained) scored = score_blocks(unconstrained, mode, task['required_fact_ids'], records_by_id) representation_rows.append({**base, 'mode': mode, 'selected_record_ids': [r for r, _ in unconstrained], **scored, 'context_units': count(context), 'context_utf8_bytes': len(context.encode('utf-8'))}) for budget in budgets: blocks = pack_records(ranked, records_by_id, mode, task['kind'], count, budget) context = wrap_blocks(blocks) scored = score_blocks(blocks, mode, task['required_fact_ids'], records_by_id) rows.append({**base, 'mode': mode, 'budget': budget, 'selected_record_ids': [r for r, _ in blocks], **scored, 'context_units': count(context), 'context_utf8_bytes': len(context.encode('utf-8'))}) for budget in budgets: context = prefix_under_budget(full_text, budget, count) scored = score_blocks(prefix_blocks(context), 'full_markdown', task['required_fact_ids'], records_by_id) negative_rows.append({**base, 'mode': 'corpus_prefix_negative_control', 'budget': budget, **scored, 'context_units': count(context), 'context_utf8_bytes': len(context.encode('utf-8'))}) drift_rows = [] for event in events: actual = classify_drift(event['policy'], event['snapshots'], event['as_of'], event['unresolved_prose_change']) drift_rows.append({'id': event['id'], 'label': event['label'], 'expected_status': event['expected_status'], **actual, 'expected_match': actual['status'] == event['expected_status'], 'revision_baseline': revision_baseline(event)}) decisive = [r for r in drift_rows if r['expected_status'] in ('ALIGNED', 'DIVERGED')] paths = ['datasets/documentation-contracts/corpus.json', 'datasets/documentation-contracts/tasks.json', 'datasets/documentation-contracts/drift-events.json', 'scripts/documentation_benchmark.py', 'scripts/lib/documentation_contracts.py', 'datasets/documentation-contracts/schema.json', 'tests/test_documentation_benchmark.py'] output = { 'schema_version': '1.0', 'benchmark': 'Documentation Contract Study', 'version': '0.2.0', 'protocol_as_of': '2026-12-03', 'run_date': datetime.now(timezone.utc).date().isoformat(), 'synthetic': True, 'measurement': measurement, 'runtime': {'python': platform.python_version()}, 'inputs': {'records': len(records), 'domains': sorted(set(r['domain'] for r in records)), 'tasks': len(tasks), 'explanation_tasks': sum(t['kind'] == 'explanation' for t in tasks), 'drift_events': len(events), 'sha256': {p: sha256(ROOT / p) for p in paths}}, 'protocol': {'retriever': 'BM25 k1=1.2 b=0.75 over full Markdown; no embeddings, query expansion or tuning', 'candidate_limit': 3, 'packing': 'ranked first-fit whole-record packing', 'budgets': budgets, 'task_kinds_visible_to_renderer': ['decision', 'explanation'], 'gold_fields_visible_to_renderer': False, 'metric': 'Exact complete evidence strings within the correct record', 'ordering': 'corpus file order for full/prefix; score descending then record ID for BM25'}, 'full_corpus_ceiling': aggregate(full_rows), 'same_selected_records': {mode: aggregate([r for r in representation_rows if r['mode'] == mode]) for mode in MODES}, 'budget_results': {str(b): {mode: aggregate([r for r in rows if r['mode'] == mode and r['budget'] == b]) for mode in MODES} for b in budgets}, 'prefix_negative_control': {str(b): aggregate([r for r in negative_rows if r['budget'] == b]) for b in budgets}, 'drift': {'events': len(events), 'exact_status_matches': sum(r['expected_match'] for r in drift_rows), 'observed_status_counts': dict(sorted(Counter(r['status'] for r in drift_rows).items())), 'decisive_cases': len(decisive), 'schema_aware_on_decisive_cases': confusion_binary(decisive, lambda r: r['status'] == 'DIVERGED'), 'revision_alarm_on_decisive_cases': confusion_binary(decisive, lambda r: r['revision_baseline'] == 'ALERT'), 'undecidable_cases_excluded_from_binary_scores': len(drift_rows)-len(decisive), 'cases': drift_rows}, 'limitations': [ 'Designed, hand-authored development fixtures, not a representative or hidden test set.', 'No LLM, production system, user study, elapsed maintenance effort, API cost, or semantic answer accuracy measured.', 'Exact evidence availability cannot prove that a model or a person will use it correctly.', 'Compact projections use prestructured records; extraction and authoring costs are not included.', 'The fixed lexical retriever has no hybrid search, query expansion, reranker, access controls, or temporal filtering.', 'The compact-core profile deliberately omits rationale and examples; explanation tasks expose that loss.', 'The structured drift checker knows mapped fields and explicitly abstains for unmapped prose; it cannot judge arbitrary text.', 'Perfect designed-case drift agreement is a functional fixture result, not real-world precision or recall.', 'Context token counts exclude prompts, questions, responses and pricing; other tokenizers give different counts.', 'No statistical generalization or confidence interval is claimed for this designed corpus.' ], 'per_task_same_records': representation_rows, 'per_task_budgets': rows, 'per_task_prefix_control': negative_rows, 'retrieval_candidates': retrieval_rows, } return output def render_report(result): unit = result['measurement']['unit'] lines = ['# Documentation benchmark results', '', f"Synthetic development experiment, version 0.2.0. Protocol date: {result['protocol_as_of']}; executed: {result['run_date']}.", '', '**Measured:** exact evidence availability and serialized context size; structured drift fixture behaviour. ' '**Not measured:** LLM answer quality, human productivity, production freshness or operating cost.', '', f"Corpus: {result['inputs']['records']} records in {len(result['inputs']['domains'])} domains; " f"{result['inputs']['tasks']} fixed tasks, including {result['inputs']['explanation_tasks']} explanation tasks; " f"{result['inputs']['drift_events']} drift cases.", '', f"Measurement: {result['measurement']['name']} ({unit}); tiktoken {result['measurement'].get('package_version', 'not used')}.", '', '## Same retrieved records, no context budget', '', 'All five projections receive the same BM25 top-three record IDs. Differences here describe representation and included evidence, not improved retrieval.', '', '| Projection | Median context '+unit+' | Evidence retained | Complete tasks |', '|---|---:|---:|---:|'] for mode, row in result['same_selected_records'].items(): lines.append(f"| {mode} | {row['median_context_units']:g} | {row['retained_evidence_items']}/{row['required_evidence_items']} ({row['evidence_retention']:.1%}) | {row['complete_tasks']}/{row['tasks']} |") ceiling = result['full_corpus_ceiling'] lines += ['', f"Full unfiltered Markdown is the ceiling: {ceiling['median_context_units']:g} {unit}, " f"{ceiling['retained_evidence_items']}/{ceiling['required_evidence_items']} evidence items, {ceiling['complete_tasks']}/{ceiling['tasks']} complete tasks.", '', '## Shared retrieval and context budgets', '', 'Each projection uses ranked first-fit packing of complete records from the same three candidates. A candidate that does not fit is skipped. Scope and exceptions are never cut from an included record.', '', '| Budget ('+unit+') | Projection | Median actual '+unit+' | Evidence retained | Complete tasks |', '|---:|---|---:|---:|---:|'] for budget, modes in result['budget_results'].items(): for mode, row in modes.items(): lines.append(f"| {budget} | {mode} | {row['median_context_units']:g} | {row['evidence_retention']:.1%} | {row['complete_tasks']}/{row['tasks']} |") lines += ['', '## Prefix clipping: negative control', '', 'This clips the full corpus in fixed file order without retrieval. It is intentionally weak and is not a substitute for the retrieved Markdown baseline.', '', '| Budget ('+unit+') | Evidence retained | Complete tasks |', '|---:|---:|---:|'] for budget, row in result['prefix_negative_control'].items(): lines.append(f"| {budget} | {row['evidence_retention']:.1%} | {row['complete_tasks']}/{row['tasks']} |") drift = result['drift'] lines += ['', '## Structured drift fixtures', '', f"Expected state matched in {drift['exact_status_matches']}/{drift['events']} designed cases. " f"Only {drift['decisive_cases']} cases have a binary aligned/diverged ground truth. " f"The other {drift['undecidable_cases_excluded_from_binary_scores']} cases test abstention, conflict or scope/time boundaries and are excluded from binary precision/recall.", '', '| Method on decisive fixtures | TP | FP | TN | FN | Precision | Recall |', '|---|---:|---:|---:|---:|---:|---:|'] for label, key in [('Mapped-field checker','schema_aware_on_decisive_cases'), ('Source-revision alarm','revision_alarm_on_decisive_cases')]: v=drift[key] lines.append(f"| {label} | {v['tp']} | {v['fp']} | {v['tn']} | {v['fn']} | {v['precision']:.1%} | {v['recall']:.1%} |") lines += ['', 'These are functional checks on designed examples. The source-revision alarm is useful for starting a review; it does not claim to identify semantic divergence. The mapped-field checker only knows the declared schema.', '', '## Limits', '', *('- '+item for item in result['limitations']), '', '## Reproduce', '', '```sh', 'python3 -m pip install tiktoken==0.14.0', 'python3 scripts/documentation_benchmark.py --tokenizer cl100k_base', 'python3 -m unittest discover -s tests -p test_documentation_benchmark.py', '```', '', 'The JSON result includes corpus, task, event, scorer and renderer SHA-256 hashes, exact missing evidence IDs, selected record IDs and every scored case. Task gold is used only after context construction.', ''] return '\n'.join(lines) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--tokenizer', choices=['cl100k_base','utf8_bytes'], default='cl100k_base') parser.add_argument('--output-dir', type=Path, default=DATA) args = parser.parse_args() result = run(args.tokenizer) args.output_dir.mkdir(parents=True, exist_ok=True) (args.output_dir / 'results.json').write_text(json.dumps(result, ensure_ascii=False, indent=2)+'\n', encoding='utf-8') (args.output_dir / 'results.md').write_text(render_report(result), encoding='utf-8') (args.output_dir / 'corpus.md').write_text('# Synthetic documentation corpus\n\n'+wrap_blocks([(r['id'], render_record(r)) for r in read_json(DATA/'corpus.json')['records']])+'\n', encoding='utf-8') print(json.dumps({'records':result['inputs']['records'],'tasks':result['inputs']['tasks'], 'measurement':result['measurement'],'same_selected_records':result['same_selected_records'], 'drift_status_matches':result['drift']['exact_status_matches']}, indent=2)) if __name__ == '__main__': main()