diff --git a/experiments/analysis-efficiency/pcap-small-captures.md b/experiments/analysis-efficiency/pcap-small-captures.md index b8fe74853..1697da82d 100644 --- a/experiments/analysis-efficiency/pcap-small-captures.md +++ b/experiments/analysis-efficiency/pcap-small-captures.md @@ -122,7 +122,7 @@ validated. Both real CLI complete results match full MCP normalized results, subjects, parameters, IDs and limitations. Portable CLI summary/URI views match MCP retained normalized facts and subjects; source forms/caller parameters remain distinct. -Source bytes stay unchanged. Nine context/grading regressions pass. Five real-answer +Source bytes stay unchanged. Twelve context/grading regressions pass. Five real-answer mutations—omitted null, false page exhaustion, contradictory source scope, unsupported absence claim and non-string receipt identity—fail correctly. Malformed identities produce failed facts rather than crashing the grader. @@ -143,3 +143,11 @@ events are verified; missing terminal whole-scope counters remain unknown, so strict whole-resource grades stay false. No raw capture, trace, credential, runtime or result JSON is committed. No unrelated REA product bug is identified or fixed, and no release is performed. + +Review follow-up binds the cited URI page to its exact requested facet/range, +reported values and the summary retained parent. Small synthetic trial receipts +exercise the entire grading entrypoint, including faithful but wrong-page/range/ +parent citations, missing nulls, false scope and malformed identities. These are +grader regressions, not real-provider evidence. All four stored actual model +answers still pass; no model reruns are required. Transcript readers close their +owned file handles after grading. diff --git a/experiments/analysis-efficiency/review-model.py b/experiments/analysis-efficiency/review-model.py index 23fe9a21f..074a44ecf 100644 --- a/experiments/analysis-efficiency/review-model.py +++ b/experiments/analysis-efficiency/review-model.py @@ -103,24 +103,25 @@ def main(): observed_ids = set() producer_results = {} tool_errors = [] - for line in (args.trial / 'events.jsonl').open(): - event = json.loads(line) - item = event.get('item', {}) - if event.get('type') != 'item.completed' or item.get('type') != 'mcp_tool_call': - continue - result = item.get('result') or {} - parsed = decode(result) - if item['status'] == 'completed': - # Only response text contributes observed IDs, never model arguments. - for text in strings(result): - observed_ids.update(re.findall(r'ev_[a-f0-9]{64}', text)) - if parsed is not None: - producer_results.setdefault(item['tool'], []).append(parsed) - else: - tool_errors.append({'tool': item['tool'], 'arguments': item['arguments'], 'response': parsed if parsed is not None else result}) - if parsed is not None and parsed.get('error', {}).get('code') == 'resource_constraint': - reference_value = parsed['error'].get('details', {}).get('reported_limits', {}).get('evidence_reference') - observed_ids.update(evidence_ids(reference_value)) + with (args.trial / 'events.jsonl').open() as event_lines: + for line in event_lines: + event = json.loads(line) + item = event.get('item', {}) + if event.get('type') != 'item.completed' or item.get('type') != 'mcp_tool_call': + continue + result = item.get('result') or {} + parsed = decode(result) + if item['status'] == 'completed': + # Only response text contributes observed IDs, never model arguments. + for text in strings(result): + observed_ids.update(re.findall(r'ev_[a-f0-9]{64}', text)) + if parsed is not None: + producer_results.setdefault(item['tool'], []).append(parsed) + else: + tool_errors.append({'tool': item['tool'], 'arguments': item['arguments'], 'response': parsed if parsed is not None else result}) + if parsed is not None and parsed.get('error', {}).get('code') == 'resource_constraint': + reference_value = parsed['error'].get('details', {}).get('reported_limits', {}).get('evidence_reference') + observed_ids.update(evidence_ids(reference_value)) reported_ids = evidence_ids(answer.get('evidence_ids')) checks = { 'reported_evidence_ids_observed_in_responses': bool(reported_ids) and reported_ids <= observed_ids, @@ -202,11 +203,42 @@ def main(): if isinstance(canonical_observations, list) and all(isinstance(x, dict) for x in canonical_observations): check('pcap_requested_delivery_chain', [x.get('kind', 'complete') for x in canonical_observations], [x.get('kind', 'complete') for x in reference['delivery_observations']]) + check('pcap_requested_views', [x.get('view') for x in canonical_observations], + [x.get('view') for x in reference['delivery_observations']]) identities = [x.get('evidence_id') for x in canonical_observations] checks['pcap_observations_have_reported_ids'] = all(isinstance(value, str) for value in identities) and set(identities) <= reported_ids + cited = [records.get(identity) if isinstance(identity, str) else None for identity in identities] + checks['pcap_cited_source_supports_uri_prefix'] = False + if all(isinstance(record, dict) for record in cited): + if len(cited) == 1: + source = cited[0]['normalized_result'] + checks['pcap_cited_source_supports_uri_prefix'] = ( + source.get('target') == reference['capture']['target'] + and isinstance(source.get('http_request_uris'), list) + and json.dumps(source['http_request_uris'][:2], sort_keys=True) == json.dumps(prefix, sort_keys=True) + ) + elif len(cited) == 2: + source, page = [record['normalized_result'] for record in cited] + capture = source.get('summary', {}) + selected_page = page.get('page', {}) + checks['pcap_cited_source_supports_uri_prefix'] = ( + source.get('kind') == 'summary' + and source.get('parent_operation') == 'inspect_pcap_capture' + and capture == reference['capture'] + and isinstance(source.get('parent_evidence_id'), str) + and page.get('parent_evidence_id') == source['parent_evidence_id'] + and page.get('parent_operation') == 'inspect_pcap_capture' + and page.get('view') == {'kind': 'pcap', 'facet': 'http-uris', 'offset': 0, 'limit': 2} + and selected_page.get('facet') == 'http-uris' + and json.dumps(selected_page.get('items'), sort_keys=True) == json.dumps(prefix, sort_keys=True) + and page.get('source_coverage') == capture.get('coverage') + and page.get('artifact') == {key: capture['target'][key] for key in ['path', 'sha256']} + ) else: checks['pcap_requested_delivery_chain'] = False checks['pcap_observations_have_reported_ids'] = False + checks['pcap_requested_views'] = False + checks['pcap_cited_source_supports_uri_prefix'] = False elif domain == 'flutter-aot': for key in ['target', 'abi', 'libapp', 'string_pool', 'coverage', 'limitations']: check(key, answer.get(key), reference[key]) diff --git a/experiments/analysis-efficiency/test_codex_context.py b/experiments/analysis-efficiency/test_codex_context.py index 73d91d8b5..ca8f8b141 100644 --- a/experiments/analysis-efficiency/test_codex_context.py +++ b/experiments/analysis-efficiency/test_codex_context.py @@ -1,6 +1,7 @@ """Distinct capture/cleanup failures; simulated CLI is not real-model evidence.""" import importlib.util +import copy import io import json import os @@ -70,6 +71,108 @@ class PcapCoverageTests(unittest.TestCase): self.assertIsNone(canonical(None)) +class PcapGraderWorkflowTests(unittest.TestCase): + """Synthetic receipts test the grader boundary, not Wireshark or real models.""" + + def fixture(self): + parent, summary_id, page_id = ['ev_' + value * 64 for value in ['a', 'b', 'c']] + capture = {'target': {'path': '/fixture/http.pcapng', 'sha256': 'd' * 64}, + 'capture_start': None, 'coverage': 'complete', + 'retained_counts': {'http_request_uris': 3}} + prefix = ['http://example.test/one', 'http://example.test/two'] + coverage = {'status': 'page', 'examined': 2, 'total': 3, 'next_offset': 2, 'exhausted': False} + summary = {'evidence_id': summary_id, 'limitations': ['source', 'view'], + 'normalized_result': {'kind': 'summary', 'view': {'kind': 'summary'}, + 'parent_operation': 'inspect_pcap_capture', 'parent_evidence_id': parent, + 'summary': capture, 'coverage': {'status': 'complete-within-view', 'examined': 1, 'total': 1, 'next_offset': None, 'exhausted': True}, + 'limitations': ['source', 'view'], 'unknowns': ['unrecorded traffic']}} + page = {'evidence_id': page_id, 'limitations': ['source', 'view'], + 'normalized_result': {'kind': 'pcap', + 'view': {'kind': 'pcap', 'facet': 'http-uris', 'offset': 0, 'limit': 2}, + 'parent_operation': 'inspect_pcap_capture', 'parent_evidence_id': parent, + 'page': {'facet': 'http-uris', 'items': prefix}, 'coverage': coverage, + 'source_coverage': 'complete', 'artifact': capture['target'], + 'limitations': ['source', 'view'], 'unknowns': ['unrecorded traffic']}} + observations = [self.observation(value) for value in [summary, page]] + reference = {'artifact_sha256': 'd' * 64, 'capture': capture, + 'http_request_uris_first2': prefix, 'delivery_observations': observations} + answer = copy.deepcopy({**reference, 'http_request_uris_first2': { + 'items': prefix, 'coverage': coverage, 'source_coverage': 'complete'}, + 'evidence_ids': [summary_id, page_id]}) + return answer, [summary, page], copy.deepcopy(reference) + + def observation(self, record): + value = record['normalized_result'] + return {'evidence_id': record['evidence_id'], 'limitations': record['limitations'], + 'kind': value['kind'], 'view': value['view'], + 'parent_evidence_id': value['parent_evidence_id'], 'coverage': value['coverage'], + 'unknowns': value['unknowns'], 'normalized_limitations': value['limitations']} + + def grade(self, answer, records, reference): + review = runpy.run_path(str(Path(__file__).with_name('review-model.py'))) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory);trial = root / 'trial';trial.mkdir() + for name, value in [('summary.json', {'completed_mcp_calls': []}), + ('trial-settings.json', {}), ('cleanup.json', {'profile_removed': True})]: + (trial / name).write_text(json.dumps(value)) + (trial / 'answer.txt').write_text(json.dumps(answer)) + events = [{'type': 'item.completed', 'item': {'type': 'mcp_tool_call', + 'tool': 'inspect_pcap_capture' if value['normalized_result']['kind'] == 'summary' else 'inspect_analysis_view', + 'status': 'completed', 'result': {'structuredContent': value}}} for value in records] + (trial / 'events.jsonl').write_text(''.join(json.dumps(value) + '\n' for value in events)) + source = root / 'reference';source.mkdir();(source / 'answer.json').write_text(json.dumps(reference)) + resource = root / 'resource.log' + resource.write_text(json.dumps({'resource_scope': 'simulated-grader-only', 'abort': None, + 'resource_counters_verified': False, 'resource_events_final': None}) + '\n') + output = root / 'review.json' + argv = ['review-model.py', '--domain', 'pcap', '--trial', str(trial), '--reference', str(source), + '--resource-log', str(resource), '--output', str(output)] + with patch.object(sys, 'argv', argv), patch('sys.stdout', io.StringIO()), self.assertRaises(SystemExit) as stopped: + review['main']() + self.assertEqual(stopped.exception.code, 1) # Unknown resource counters stay false. + return json.loads(output.read_text()) + + def test_complete_grader_accepts_supported_receipts_and_equivalent_labels(self): + answer, records, reference = self.fixture() + self.assertTrue(self.grade(answer, records, reference)['all_factual_checks_pass']) + for observation in answer['delivery_observations']: + observation['outer_limitations'] = observation.pop('limitations') + observation['normalized_coverage'] = observation.pop('coverage') + self.assertTrue(self.grade(answer, records, reference)['all_factual_checks_pass']) + + def test_complete_grader_rejects_missing_nulls_bad_scope_and_malformed_identity(self): + mutations = [lambda x: x['capture'].pop('capture_start'), + lambda x: x['http_request_uris_first2']['coverage'].__setitem__('exhausted', True), + lambda x: x['delivery_observations'][-1].__setitem__('evidence_id', {'unexpected': 'value'}), + lambda x: x['delivery_observations'][-1].__setitem__('unrecorded_traffic_absent', True)] + for mutate in mutations: + with self.subTest(mutation=mutate): + answer, records, reference = self.fixture();mutate(answer) + self.assertFalse(self.grade(answer, records, reference)['all_factual_checks_pass']) + + def test_faithful_wrong_receipts_do_not_support_the_reported_uri_prefix(self): + for wrong in ['facet', 'range', 'parent']: + with self.subTest(wrong=wrong): + answer, records, reference = self.fixture() + page = copy.deepcopy(records[-1]);page['evidence_id'] = 'ev_' + 'e' * 64 + value = page['normalized_result'] + if wrong == 'facet': + value['view']['facet'] = 'endpoints' + value['page'] = {'facet': 'endpoints', 'items': [{'address': '127.0.0.1'}]} + elif wrong == 'range': + value['view']['offset'] = 1 + value['page']['items'] = ['http://example.test/two', 'http://example.test/three'] + else: + value['parent_evidence_id'] = 'ev_' + 'f' * 64 + records.append(page) + answer['delivery_observations'][-1] = self.observation(page) + answer['evidence_ids'][-1] = page['evidence_id'] + report = self.grade(answer, records, reference) + self.assertTrue(report['factual_checks']['pcap_original_delivery_observations']) + self.assertFalse(report['factual_checks']['pcap_cited_source_supports_uri_prefix']) + self.assertFalse(report['all_factual_checks_pass']) + + class ContextCaptureTests(unittest.TestCase): def test_filters_ambient_account_and_nested_usage_state(self): with tempfile.TemporaryDirectory() as directory: