Datasets:
Download code/src/pvr_eval/contracts/calibration_bundle.py from wenjieshu/solveedit_benchmark_2728: direct link, hf CLI and curl.
- Browser
- Download file 22.2 kB
-
https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/contracts/calibration_bundle.py
- Command line
-
hf download hf://datasets/wenjieshu/solveedit_benchmark_2728/code/src/pvr_eval/contracts/calibration_bundle.py
-
curl -L -o calibration_bundle.py https://huggingface.co/datasets/wenjieshu/solveedit_benchmark_2728/resolve/main/code/src/pvr_eval/contracts/calibration_bundle.py
22.2 kB
| """Build immutable prepared-contract bundles for calibration runs. | |
| The evaluator historically reused ``prepared.tsv`` files from prior runs. That | |
| made a compiled contract an accidental source of truth and allowed later | |
| predicate fixes to disappear when the wrong intermediate artifact was reused. | |
| This module makes the selected source contract for every case explicit and | |
| records its digest and provenance in one self-contained bundle. | |
| """ | |
| from __future__ import annotations | |
| import hashlib | |
| import json | |
| from copy import deepcopy | |
| from pathlib import Path | |
| from typing import Any, Mapping, Sequence | |
| from pvr_eval.agent.executable_predicate import compile_executable_predicate | |
| from pvr_eval.core.io import dump_json, load_json, read_tsv, write_tsv | |
| CALIBRATION_BUNDLE_SCHEMA_VERSION = "pvr.calibration_prepared_bundle.v1" | |
| QUESTION_SUPPORT_ROSTER_SCHEMA_VERSION = "pvr.question_support_roster.v1" | |
| _APPROVED_SOURCE_ANNOTATION_PROVENANCE = frozenset({"human_verified_fixed_input_v1"}) | |
| def _sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for chunk in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def _value_sha256(value: Any) -> str: | |
| payload = json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) | |
| return hashlib.sha256(payload.encode("utf-8")).hexdigest() | |
| def _case_id(case_key: str) -> str: | |
| return case_key.split("__", 1)[-1] | |
| def _decision_parameters(check: Mapping[str, Any], *, case_key: str, check_id: str) -> dict[str, Any]: | |
| params = check.get("params") | |
| if not isinstance(params, dict): | |
| raise ValueError(f"check params must be an object for {case_key}:{check_id}") | |
| decision_rule = params.get("decision_rule") | |
| if not isinstance(decision_rule, dict): | |
| raise ValueError(f"check has no decision_rule object for {case_key}:{check_id}") | |
| parameters = decision_rule.get("parameters") | |
| if not isinstance(parameters, dict): | |
| raise ValueError(f"check decision_rule has no parameters object for {case_key}:{check_id}") | |
| return parameters | |
| def _validated_source_annotations( | |
| check: Mapping[str, Any], *, case_key: str, check_id: str, | |
| ) -> tuple[list[dict[str, Any]], dict[str, int]]: | |
| parameters = _decision_parameters(check, case_key=case_key, check_id=check_id) | |
| raw_annotations = parameters.get("source_instance_annotations") | |
| if not isinstance(raw_annotations, list) or not raw_annotations: | |
| raise ValueError(f"source roster is missing annotations for {case_key}:{check_id}") | |
| annotations: list[dict[str, Any]] = [] | |
| counts: dict[str, int] = {} | |
| seen_ids: set[str] = set() | |
| for index, raw in enumerate(raw_annotations): | |
| if not isinstance(raw, Mapping): | |
| raise ValueError(f"source roster annotation is not an object for {case_key}:{check_id}:{index}") | |
| annotation = deepcopy(dict(raw)) | |
| instance_id = str(annotation.get("instance_id") or "").strip() | |
| group_id = str(annotation.get("group_id") or annotation.get("semantic_class") or "").strip() | |
| query = str(annotation.get("query_text") or "").strip() | |
| provenance = str(annotation.get("provenance") or "").strip() | |
| bbox = annotation.get("bbox_xyxy") | |
| if not instance_id or instance_id in seen_ids: | |
| raise ValueError(f"source roster instance ids must be non-empty and unique for {case_key}:{check_id}") | |
| if not group_id or not query: | |
| raise ValueError(f"source roster annotation lacks group/query for {case_key}:{check_id}:{instance_id}") | |
| if provenance not in _APPROVED_SOURCE_ANNOTATION_PROVENANCE: | |
| raise ValueError( | |
| f"source roster annotation provenance is not approved for {case_key}:{check_id}:{instance_id}" | |
| ) | |
| if not ( | |
| isinstance(bbox, (list, tuple)) and len(bbox) == 4 | |
| and all(isinstance(value, (int, float)) for value in bbox) | |
| and float(bbox[2]) > float(bbox[0]) and float(bbox[3]) > float(bbox[1]) | |
| ): | |
| raise ValueError(f"source roster annotation bbox is invalid for {case_key}:{check_id}:{instance_id}") | |
| seen_ids.add(instance_id) | |
| counts[group_id] = counts.get(group_id, 0) + 1 | |
| annotations.append(annotation) | |
| expected = parameters.get("expected_instances") | |
| if isinstance(expected, Mapping): | |
| normalized_expected = {str(key): int(value) for key, value in expected.items()} | |
| if counts != normalized_expected: | |
| raise ValueError( | |
| f"source roster annotations do not match expected_instances for {case_key}:{check_id}: " | |
| f"observed={counts}, expected={normalized_expected}" | |
| ) | |
| return annotations, counts | |
| def _bind_question_support_roster( | |
| *, case_key: str, target_check_id: str, source_check_ids: Sequence[str], | |
| checks_by_id: Mapping[str, dict[str, Any]], | |
| ) -> dict[str, Any]: | |
| if target_check_id in source_check_ids: | |
| raise ValueError(f"question support roster cannot reference itself: {case_key}:{target_check_id}") | |
| target = checks_by_id[target_check_id] | |
| combined: list[dict[str, Any]] = [] | |
| combined_counts: dict[str, int] = {} | |
| seen_ids: set[str] = set() | |
| for source_check_id in source_check_ids: | |
| annotations, counts = _validated_source_annotations( | |
| checks_by_id[source_check_id], case_key=case_key, check_id=source_check_id, | |
| ) | |
| for annotation in annotations: | |
| instance_id = str(annotation["instance_id"]) | |
| if instance_id in seen_ids: | |
| raise ValueError(f"duplicate source roster instance across bindings for {case_key}:{instance_id}") | |
| seen_ids.add(instance_id) | |
| combined.append(annotation) | |
| for group_id, count in counts.items(): | |
| combined_counts[group_id] = combined_counts.get(group_id, 0) + count | |
| target_parameters = _decision_parameters(target, case_key=case_key, check_id=target_check_id) | |
| existing = target_parameters.get("source_instance_annotations") | |
| if existing not in (None, []) and existing != combined: | |
| raise ValueError(f"target already has a conflicting source roster for {case_key}:{target_check_id}") | |
| question_support = { | |
| "schema_version": QUESTION_SUPPORT_ROSTER_SCHEMA_VERSION, | |
| "purpose": "allowed_edit_and_vacated_context_support_for_target_question", | |
| "target_check_id": target_check_id, | |
| "target_question": str(target.get("question") or ""), | |
| "source_check_ids": list(source_check_ids), | |
| "annotation_provenance": "human_verified_fixed_input_v1", | |
| "instance_count": len(combined), | |
| "expected_counts": combined_counts, | |
| } | |
| target_parameters.update( | |
| { | |
| "source_instance_annotations": combined, | |
| "source_roster_complete": True, | |
| "source_inventory_provenance": "contract_source_annotations", | |
| "source_roster_expected_counts": combined_counts, | |
| "question_support_roster": question_support, | |
| } | |
| ) | |
| roster_queries = list(dict.fromkeys(str(item["query_text"]) for item in combined)) | |
| params = target.get("params") | |
| updated_region_ids: list[str] = [] | |
| for region in params.get("planned_regions", []) if isinstance(params, Mapping) else []: | |
| if not isinstance(region, dict): | |
| continue | |
| region_id = str(region.get("region_id") or region.get("id") or "") | |
| rule = str(region.get("query_or_rule") or "").lower() | |
| if "allowed" in region_id.lower() or "input animal mask" in rule or "wildlife instance" in rule: | |
| region["object_queries"] = roster_queries | |
| region["question_support_roster"] = { | |
| "schema_version": QUESTION_SUPPORT_ROSTER_SCHEMA_VERSION, | |
| "target_check_id": target_check_id, | |
| "source_check_ids": list(source_check_ids), | |
| } | |
| updated_region_ids.append(region_id) | |
| return {**question_support, "updated_region_ids": updated_region_ids} | |
| def build_calibration_bundle( | |
| *, | |
| base_prepared: str | Path, | |
| output_dir: str | Path, | |
| source_label: str, | |
| contract_overrides: Mapping[str, str | Path] | None = None, | |
| predicate_recompiles: Mapping[str, Sequence[str]] | None = None, | |
| region_support_queries: Mapping[str, Mapping[str, Mapping[str, Sequence[str]]]] | None = None, | |
| source_roster_bindings: Mapping[str, Mapping[str, Sequence[str]]] | None = None, | |
| decision_parameter_overrides: Mapping[str, Mapping[str, Mapping[str, Any]]] | None = None, | |
| ) -> dict[str, Any]: | |
| """Copy selected contracts into a provenance-locked prepared bundle. | |
| ``contract_overrides`` and ``predicate_recompiles`` are keyed by the exact | |
| ``case_key`` from the base prepared TSV. Predicate recompilation is also | |
| opt-in per exact check id, so a new compiler family cannot silently replace | |
| already reviewed predicates in unrelated checks. | |
| """ | |
| base_path = Path(base_prepared).resolve() | |
| destination = Path(output_dir).resolve() | |
| rows = read_tsv(base_path) | |
| if not rows: | |
| raise ValueError(f"base prepared TSV has no rows: {base_path}") | |
| if destination.exists() and any(destination.iterdir()): | |
| raise ValueError(f"output directory is not empty: {destination}") | |
| destination.mkdir(parents=True, exist_ok=True) | |
| overrides = {key: Path(value).resolve() for key, value in (contract_overrides or {}).items()} | |
| recompiles = { | |
| key: tuple(dict.fromkeys(str(check_id) for check_id in check_ids)) | |
| for key, check_ids in (predicate_recompiles or {}).items() | |
| } | |
| support_overrides = { | |
| str(case_key): { | |
| str(check_id): { | |
| str(region_id): tuple(dict.fromkeys(str(query) for query in queries if str(query).strip())) | |
| for region_id, queries in regions.items() | |
| } | |
| for check_id, regions in checks.items() | |
| } | |
| for case_key, checks in (region_support_queries or {}).items() | |
| } | |
| roster_bindings = { | |
| str(case_key): { | |
| str(target_check_id): tuple(dict.fromkeys(str(value) for value in source_check_ids if str(value))) | |
| for target_check_id, source_check_ids in targets.items() | |
| } | |
| for case_key, targets in (source_roster_bindings or {}).items() | |
| } | |
| parameter_overrides = { | |
| str(case_key): { | |
| str(check_id): {str(key): deepcopy(value) for key, value in parameters.items()} | |
| for check_id, parameters in checks.items() | |
| } | |
| for case_key, checks in (decision_parameter_overrides or {}).items() | |
| } | |
| available_keys = [row.get("case_key", "") for row in rows] | |
| missing_selected_keys = sorted( | |
| ( | |
| set(overrides) | set(recompiles) | set(support_overrides) | |
| | set(roster_bindings) | set(parameter_overrides) | |
| ) - set(available_keys) | |
| ) | |
| if missing_selected_keys: | |
| raise ValueError(f"contract overrides or recompiles do not match prepared rows: {missing_selected_keys}") | |
| if len(available_keys) != len(set(available_keys)): | |
| raise ValueError("base prepared TSV contains duplicate case_key rows") | |
| output_rows: list[dict[str, object]] = [] | |
| manifest_cases: list[dict[str, Any]] = [] | |
| for row in rows: | |
| case_key = row["case_key"] | |
| base_contract = Path(row.get("contract_path") or row.get("eval_spec") or "").resolve() | |
| selected_contract = overrides.get(case_key, base_contract) | |
| if not selected_contract.is_file(): | |
| raise ValueError(f"missing selected contract for {case_key}: {selected_contract}") | |
| contract = deepcopy(load_json(selected_contract)) | |
| contract_case_id = str(contract.get("case_id") or "") | |
| expected_case_id = _case_id(case_key) | |
| if contract_case_id and contract_case_id != expected_case_id: | |
| raise ValueError( | |
| f"contract case_id mismatch for {case_key}: {contract_case_id!r} != {expected_case_id!r}" | |
| ) | |
| checks = contract.get("atomic_checks") | |
| if not isinstance(checks, list) or not checks: | |
| raise ValueError(f"selected contract has no atomic_checks: {selected_contract}") | |
| checks_by_id = { | |
| str(check.get("id") or check.get("check_id") or ""): check | |
| for check in checks | |
| if isinstance(check, dict) | |
| } | |
| case_support_overrides = support_overrides.get(case_key, {}) | |
| case_roster_bindings = roster_bindings.get(case_key, {}) | |
| case_parameter_overrides = parameter_overrides.get(case_key, {}) | |
| missing_support_check_ids = sorted(set(case_support_overrides) - set(checks_by_id)) | |
| if missing_support_check_ids: | |
| raise ValueError( | |
| f"region support overrides do not match checks for {case_key}: {missing_support_check_ids}" | |
| ) | |
| referenced_roster_check_ids = set(case_roster_bindings) | |
| for source_check_ids in case_roster_bindings.values(): | |
| referenced_roster_check_ids.update(source_check_ids) | |
| missing_roster_check_ids = sorted(referenced_roster_check_ids - set(checks_by_id)) | |
| if missing_roster_check_ids: | |
| raise ValueError( | |
| f"source roster bindings do not match checks for {case_key}: {missing_roster_check_ids}" | |
| ) | |
| missing_parameter_check_ids = sorted(set(case_parameter_overrides) - set(checks_by_id)) | |
| if missing_parameter_check_ids: | |
| raise ValueError( | |
| f"decision parameter overrides do not match checks for {case_key}: {missing_parameter_check_ids}" | |
| ) | |
| parameter_records: list[dict[str, Any]] = [] | |
| for check_id, updates in case_parameter_overrides.items(): | |
| parameters = _decision_parameters(checks_by_id[check_id], case_key=case_key, check_id=check_id) | |
| for key, value in updates.items(): | |
| parameter_records.append( | |
| { | |
| "check_id": check_id, | |
| "parameter": key, | |
| "previous_value": deepcopy(parameters.get(key)), | |
| "value": deepcopy(value), | |
| } | |
| ) | |
| parameters[key] = deepcopy(value) | |
| roster_records = [ | |
| _bind_question_support_roster( | |
| case_key=case_key, | |
| target_check_id=target_check_id, | |
| source_check_ids=source_check_ids, | |
| checks_by_id=checks_by_id, | |
| ) | |
| for target_check_id, source_check_ids in case_roster_bindings.items() | |
| ] | |
| support_records: list[dict[str, Any]] = [] | |
| for check_id, region_overrides in case_support_overrides.items(): | |
| check = checks_by_id[check_id] | |
| params = check.setdefault("params", {}) | |
| if not isinstance(params, dict): | |
| raise ValueError(f"check params must be an object for {case_key}:{check_id}") | |
| planned_regions = params.get("planned_regions") | |
| if not isinstance(planned_regions, list): | |
| raise ValueError(f"check has no planned regions for {case_key}:{check_id}") | |
| regions_by_id = { | |
| str(region.get("region_id") or region.get("id") or ""): region | |
| for region in planned_regions if isinstance(region, dict) | |
| } | |
| missing_region_ids = sorted(set(region_overrides) - set(regions_by_id)) | |
| if missing_region_ids: | |
| raise ValueError( | |
| f"region support overrides do not match regions for {case_key}:{check_id}: " | |
| f"{missing_region_ids}" | |
| ) | |
| for region_id, queries in region_overrides.items(): | |
| if not queries: | |
| raise ValueError( | |
| f"region support override has no queries for {case_key}:{check_id}:{region_id}" | |
| ) | |
| region = regions_by_id[region_id] | |
| previous_queries = list(region.get("object_queries") or region.get("queries") or []) | |
| region["object_queries"] = list(queries) | |
| support_records.append( | |
| { | |
| "check_id": check_id, | |
| "region_id": region_id, | |
| "previous_queries": previous_queries, | |
| "reviewed_support_queries": list(queries), | |
| } | |
| ) | |
| requested_recompiles = tuple(dict.fromkeys( | |
| ( | |
| *recompiles.get(case_key, ()), *case_support_overrides, | |
| *case_roster_bindings, *case_parameter_overrides, | |
| ) | |
| )) | |
| missing_check_ids = sorted(set(requested_recompiles) - set(checks_by_id)) | |
| if missing_check_ids: | |
| raise ValueError(f"predicate recompiles do not match checks for {case_key}: {missing_check_ids}") | |
| recompile_records: list[dict[str, Any]] = [] | |
| for check_id in requested_recompiles: | |
| check = checks_by_id[check_id] | |
| params = check.setdefault("params", {}) | |
| if not isinstance(params, dict): | |
| raise ValueError(f"check params must be an object for {case_key}:{check_id}") | |
| previous = check.get("executable_predicate") or params.get("executable_predicate") or {} | |
| check.pop("predicate_ir_candidate", None) | |
| params.pop("predicate_ir_candidate", None) | |
| compiler_input = deepcopy(check) | |
| compiler_input.pop("executable_predicate", None) | |
| compiler_input.pop("predicate_ir_candidate", None) | |
| compiler_params = compiler_input.setdefault("params", {}) | |
| compiler_params.pop("executable_predicate", None) | |
| compiler_params.pop("predicate_ir_candidate", None) | |
| compiler_params.pop("require_executable_predicate", None) | |
| compiled = compile_executable_predicate(compiler_input) | |
| check["executable_predicate"] = compiled | |
| params["executable_predicate"] = compiled | |
| params["require_executable_predicate"] = True | |
| recompile_records.append( | |
| { | |
| "check_id": check_id, | |
| "previous_predicate_sha256": _value_sha256(previous), | |
| "compiled_predicate_sha256": _value_sha256(compiled), | |
| "previous_status": previous.get("status", "") if isinstance(previous, Mapping) else "", | |
| "compiled_status": compiled.get("status", ""), | |
| "compiled_family": compiled.get("family", ""), | |
| } | |
| ) | |
| case_dir = destination / "cases" / case_key | |
| contract_output = case_dir / "eval_contract.json" | |
| selected_digest = _sha256(selected_contract) | |
| metadata = contract.setdefault("metadata", {}) | |
| if not isinstance(metadata, dict): | |
| raise ValueError(f"contract metadata must be an object: {selected_contract}") | |
| metadata["calibration_bundle_source"] = { | |
| "schema_version": CALIBRATION_BUNDLE_SCHEMA_VERSION, | |
| "source_label": source_label, | |
| "base_prepared": str(base_path), | |
| "base_contract": str(base_contract), | |
| "selected_contract": str(selected_contract), | |
| "selected_contract_sha256": selected_digest, | |
| "overridden": case_key in overrides, | |
| "predicate_recompiles": recompile_records, | |
| "region_support_queries": support_records, | |
| "source_roster_bindings": roster_records, | |
| "decision_parameter_overrides": parameter_records, | |
| } | |
| dump_json(contract_output, contract) | |
| observations_output = case_dir / "observations.json" | |
| observations_source = Path(row.get("observations") or "") | |
| if observations_source.is_file(): | |
| dump_json(observations_output, load_json(observations_source)) | |
| else: | |
| dump_json(observations_output, {}) | |
| output_row: dict[str, object] = dict(row) | |
| output_row.update( | |
| { | |
| "case_dir": str(case_dir), | |
| "eval_spec": str(contract_output), | |
| "contract_path": str(contract_output), | |
| "observations": str(observations_output), | |
| } | |
| ) | |
| output_rows.append(output_row) | |
| manifest_cases.append( | |
| { | |
| "case_key": case_key, | |
| "case_id": expected_case_id, | |
| "selected_contract": str(selected_contract), | |
| "selected_contract_sha256": selected_digest, | |
| "overridden": case_key in overrides, | |
| "predicate_recompiles": recompile_records, | |
| "region_support_queries": support_records, | |
| "source_roster_bindings": roster_records, | |
| "decision_parameter_overrides": parameter_records, | |
| "atomic_checks": len(checks), | |
| } | |
| ) | |
| prepared_output = destination / "prepared.tsv" | |
| write_tsv(prepared_output, output_rows, list(rows[0])) | |
| summary = { | |
| "schema_version": CALIBRATION_BUNDLE_SCHEMA_VERSION, | |
| "source_label": source_label, | |
| "base_prepared": str(base_path), | |
| "prepared_tsv": str(prepared_output), | |
| "cases": manifest_cases, | |
| "case_count": len(manifest_cases), | |
| "override_count": sum(bool(case["overridden"]) for case in manifest_cases), | |
| "predicate_recompile_count": sum(len(case["predicate_recompiles"]) for case in manifest_cases), | |
| "region_support_query_override_count": sum( | |
| len(case["region_support_queries"]) for case in manifest_cases | |
| ), | |
| "source_roster_binding_count": sum( | |
| len(case["source_roster_bindings"]) for case in manifest_cases | |
| ), | |
| "decision_parameter_override_count": sum( | |
| len(case["decision_parameter_overrides"]) for case in manifest_cases | |
| ), | |
| } | |
| dump_json(destination / "source_manifest.json", summary) | |
| return summary | |