"""Content scoring with the evaluated public alias/search corrections.""" from copy import deepcopy import hashlib import json from common import read from evaluate import Episode def require(condition, message): if not condition: raise ValueError(message) def encode(name): result = name.replace(".", "__") if len(result) <= 64: return result suffix = "__h" + hashlib.sha256(name.encode()).hexdigest()[:12] return result[:64-len(suffix)] + suffix def canonical(value): return json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(',', ':')) def decode_observed_tools(answer, env, public_names, execution_log, encode): """Pure, narrow decoding; argument/error/effect authentication stays in oracle.""" require(type(public_names) is list and all(type(n) is str and n for n in public_names), 'Invalid public tool inventory') require(len(set(public_names)) == len(public_names), 'Duplicate public tool names') qualified = {env + '.' + name: name for name in public_names} # Check every declared tool, including tools the agent never chose to call. all_aliases = {} for full, local in qualified.items(): for alias in (local, full, encode(full)): require(alias not in all_aliases or all_aliases[alias] == local, 'Ambiguous public tool alias') all_aliases[alias] = local require(type(execution_log) is list, 'Missing official execution log') observed = set() for event in execution_log: require(type(event) is dict and type(event.get('tool')) is str, 'Malformed tool event') name = event['tool'] if name in ('task_documents.list_documents', 'task_documents.read_document'): continue require(name in qualified, 'Cross-environment or nonpublic observed tool') observed.add(qualified[name]) aliases = {alias: local for alias, local in all_aliases.items() if local in observed} result = deepcopy(answer) witnesses = result['missing_evidence'] require(type(witnesses) is list, 'Malformed missing_evidence') changes = [] for index, witness in enumerate(witnesses): # Other witness schemas/fields are left to the frozen schema and oracle. if not isinstance(witness, dict) or 'tool' not in witness: continue name = witness['tool'] require(type(name) is str and name in aliases, 'Unknown, cross-environment, or unobserved witness tool') local = aliases[name] if local != name: witness['tool'] = local changes.append({'json_pointer': f'/missing_evidence/{index}/tool', 'original': name, 'normalized': local, 'observed_qualified_name': env + '.' + local}) restored = deepcopy(result) for change in changes: restored['missing_evidence'][int(change['json_pointer'].split('/')[2])]['tool'] = change['original'] require(canonical(restored) == canonical(answer), 'Decoding modified a non-tool field') return result, changes, {'observed_qualified_tools': sorted(env + '.' + n for n in observed), 'allowed_alias_to_domain_name': aliases} def complete_public_coverage(episode, events): required = {r['record_id'] for r in episode.initial['records'] if episode.bundle.oracle._search_match(r)} for event in events: if event['tool'] != 'search_catalog_records': continue args, obs = event['arguments'], event['observation'] if not set(args).issubset({'query', 'theme', 'reusability', 'media', 'sort'}): continue if str(args.get('query', '')).strip().lower() not in {'harbor', '*'}: continue if any(k in args and args[k] != v for k, v in {'theme': 'art', 'reusability': 'open', 'media': True}.items()): continue if obs.get('ok') is not True: continue found = obs.get('result', {}) items = found.get('items', []) ids = {x.get('record_id') for x in items} if (type(found.get('total_results')) is int and found['total_results'] == len(items) == len(ids) and required.issubset(ids)): return {'search_arguments': deepcopy(args), 'observed_ids': sorted(ids), 'required_ids': sorted(required), 'complete_superset': True} return None def organization_search_evidence(episode, events): oracle = episode.bundle.oracle derived, problem = oracle._derive(episode.initial) if problem: return None org = derived['org'] observed_identity = False required = {d['id']: d for d in derived['searched']} fields = ('id', 'name', 'owner_org', 'state', 'series_key', 'edition', 'coverage_start', 'coverage_end', 'metadata_modified') for event in events: args, obs = event['arguments'], event['observation'] if obs.get('ok') is not True: continue result = obs.get('result') if event['tool'] == 'organization_autocomplete' and isinstance(result, list): exact = [r for r in result if isinstance(r, dict) and r.get('title') == oracle.TARGET_TITLE] if len(exact) == 1 and oracle._has_fields(exact[0], org, ('id', 'name', 'title')): observed_identity = True if event['tool'] != 'package_search' or not observed_identity: continue # Accept only the two real, observed identifiers; never guess an alias. if (set(args) != {'owner_org', 'tag', 'include_private'} or args['owner_org'] not in (org['id'], org['name']) or args['tag'] != oracle.TAG or args['include_private'] is not False or not isinstance(result, dict)): continue records, count = result.get('results'), result.get('count') if not isinstance(records, list) or not all(isinstance(r, dict) for r in records): continue ids = [r.get('id') for r in records] if (not all(isinstance(i, str) for i in ids) or type(count) is not int or count != len(records) or len(set(ids)) != count or set(ids) != set(required)): continue if not all(oracle._has_fields(next(r for r in records if r['id'] == key), value, fields) for key, value in required.items()): continue # The sealed oracle counts metadata carried by an accepted search too. # Recheck its exact fields/resource-collection predicate on this search, # so use of a name cannot erase valid metadata that was already read. selected_metadata = all(any( oracle._has_fields(record, ds, fields) and oracle._resource_collection_exact(record.get('resources'), [r for r in derived['all_resources'] if r.get('package_id') == ds['id']]) for record in records) for ds, _ in derived['pairs']) return {'observed_organization': {k: org[k] for k in ('id', 'name', 'title')}, 'search_arguments': deepcopy(args), 'complete_observed_dataset_ids': sorted(ids), 'required_dataset_ids': sorted(required), 'complete_same_population': True, 'selected_dataset_and_resource_metadata_complete': selected_metadata} return None def parse_answer(text): """Parse exactly one JSON report, rejecting duplicate keys and nonfinite values.""" def unique(items): result = {} for key, value in items: require(key not in result, 'Duplicate JSON key: ' + key) result[key] = value return result def invalid(value): raise ValueError('Nonfinite JSON value: ' + value) return json.loads(text, object_pairs_hook=unique, parse_constant=invalid) def grade_submission(root, number, side, submission): """Grade a controller-recorded report, trace and state using the released rules. `events` use domain-local tool names. `final_state` is the domain state, not a model's assertion about whether the task succeeded. """ episode = Episode(root, number, side) try: require(isinstance(submission, dict), 'Submission must be an object') require(('answer' in submission) != ('final_output' in submission), 'Provide exactly one of answer or final_output') answer = (parse_answer(submission['final_output']) if 'final_output' in submission else parse_answer(canonical(submission['answer']))) except (ValueError, TypeError, KeyError) as exc: return {'passed': False, 'format_passed': False, 'content_passed': None, 'error_kind': 'report_format', 'errors': [str(exc)]} try: events, final_state = submission['events'], submission['final_state'] require(isinstance(events, list), 'Missing controller event list') require(all(isinstance(e, dict) and set(e) == {'tool', 'arguments', 'observation'} and isinstance(e['tool'], str) and isinstance(e['arguments'], dict) for e in events), 'Invalid controller event format') except (ValueError, TypeError, KeyError) as exc: return {'passed': False, 'format_passed': None, 'content_passed': False, 'error_kind': 'invalid_trace', 'errors': [str(exc)]} score = episode.grade(answer, events, final_state) if score.get('format_passed') is False: return score info = episode.info if isinstance(answer, dict) and answer.get('missing_evidence') and info['kind'] == 'bundle': try: tools = read(episode.root / 'private/bundles' / info['slot'] / 'public/tools.json') log = [{'tool': info['env_name'] + '.' + event['tool']} for event in events] normalized, changes, _ = decode_observed_tools( answer, info['env_name'], [tool['name'] for tool in tools], log, encode) if changes: score = episode.grade(normalized, events, final_state) except (ValueError, RuntimeError, KeyError, TypeError) as exc: return dict(score, passed=False, content_passed=False, normalization_error={'type': type(exc).__name__, 'message': str(exc)[:600]}) catalog_failure = 'missing complete evidence for the prescribed search result' identifier_failure = 'missing complete public tagged organization dataset search evidence' metadata_failure = 'missing complete chosen-dataset and resource metadata evidence' failure = {'europeana': catalog_failure, 'ckan': identifier_failure}.get(info['slot']) if failure is None or failure not in score.get('failures', []): return score # These narrow equivalences apply only after every tool observation and # the final state have been authenticated by deterministic replay. state = deepcopy(episode.initial) for event in events: step = episode.bundle.transition(state, event['tool'], event['arguments']) if step['observation'] != event['observation']: return score state = step['state'] if state != final_state: return score removable = set() if info['slot'] == 'europeana' and complete_public_coverage(episode, events): removable.add(catalog_failure) score['checks'].append('complete public search superset covers required catalog scope') elif info['slot'] == 'ckan': evidence = organization_search_evidence(episode, events) if evidence: removable.add(identifier_failure) if evidence['selected_dataset_and_resource_metadata_complete']: removable.add(metadata_failure) score['checks'].append('observed organization identifier resolves to complete required search population') if removable: score['failures'] = [item for item in score['failures'] if item not in removable] score['passed'] = score['content_passed'] = not bool(score['failures']) return score