File size: 19,242 Bytes
d9befd2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 | """Frozen normalization, validation and DOM delta helpers from PreVision.
The selected functions retain the original implementation. Source hashes and
symbols are recorded in source_provenance.json. Apache-2.0; see LICENSE.code.
"""
from __future__ import annotations
import copy
import json
import re
from collections import Counter
from collections.abc import Mapping, Sequence
from typing import Any
BRANCH_CORE = "observation_repository"
BRANCH_TEST = "official_tests"
BRANCH_RENDER = "render_product"
BRANCHES = (BRANCH_CORE, BRANCH_TEST, BRANCH_RENDER)
ORACLE_STATUSES = ("pass", "fail", "not_run", "unknown")
ISSUE_STATES = ("satisfied", "not_satisfied", "unknown")
PRODUCT_OUTCOMES = (
"rendered_product",
"repository_build_failure",
"repository_execution_failure",
"repository_execution_timeout",
"repository_product_not_emitted",
"repository_browser_ready_timeout",
)
_ANSI_RE = re.compile(r"\x1b(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])")
_ANSI_OSC_RE = re.compile(r"\x1b\][^\x07]*(?:\x07|\x1b\\)")
_TERMINAL_C0_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1a\x1c-\x1f\x7f]")
_WHITESPACE_RE = re.compile(r"[ \t]+")
def strip_terminal_control_sequences(value: object) -> str:
"""Drop non-semantic terminal controls while preserving visible output.
The deterministic OpenHands completion wrapper and real warning text stay
intact. Only OSC/CSI escape sequences, orphan ESC bytes, and non-printing
C0 controls are removed; tabs, newlines, and carriage returns are retained
for the scoring normalizer to handle explicitly.
"""
text = str(value or "")
text = _ANSI_OSC_RE.sub("", text)
text = _ANSI_RE.sub("", text)
text = text.replace("\x1b", "")
return _TERMINAL_C0_RE.sub("", text)
def normalize_text(value: object) -> str:
"""Conservative normalization used in addition to, never instead of, raw exact."""
text = strip_terminal_control_sequences(value)
text = text.replace("\r\n", "\n").replace("\r", "\n")
lines = [_WHITESPACE_RE.sub(" ", line).rstrip() for line in text.split("\n")]
while lines and not lines[0]:
lines.pop(0)
while lines and not lines[-1]:
lines.pop()
return "\n".join(lines)
def json_equal(left: object, right: object) -> bool:
return json.dumps(left, sort_keys=True, ensure_ascii=False) == json.dumps(
right, sort_keys=True, ensure_ascii=False
)
def validate_prediction(
branch: str,
value: Mapping[str, Any],
*,
required_oracle_ids: Sequence[str] = (),
required_decision_fields: Sequence[str] = (),
environment_patch_field: str = "repository_patch",
) -> str | None:
if environment_patch_field not in {"repository_patch", "step_patch"}:
raise ValueError("unknown environment patch field")
required = {
BRANCH_CORE: ("observation", "environment"),
BRANCH_TEST: ("execution", "resolved", "reward", "oracles", "summary"),
BRANCH_RENDER: (
"outcome",
"decision_fields",
"document_tree",
"visible_text",
"change",
),
}[branch]
missing = [key for key in required if key not in value]
if missing:
return "prediction is missing required top-level keys: " + ", ".join(missing)
confidence = value.get("confidence")
if (
isinstance(confidence, bool)
or not isinstance(confidence, (int, float))
or not 0 <= float(confidence) <= 1
):
return "confidence must be a number in [0,1]"
def object_with_fields(name: str, fields: Sequence[str]) -> Mapping[str, Any] | str:
nested = value.get(name)
if not isinstance(nested, Mapping):
return f"{name} must be an object"
absent = [field for field in fields if field not in nested]
if absent:
return f"{name} is missing required keys: {', '.join(absent)}"
return nested
def is_bool_or_none(candidate: object) -> bool:
return candidate is None or isinstance(candidate, bool)
def is_int_or_none(candidate: object) -> bool:
return candidate is None or (
isinstance(candidate, int) and not isinstance(candidate, bool)
)
def is_number_or_none(candidate: object) -> bool:
return candidate is None or (
isinstance(candidate, (int, float)) and not isinstance(candidate, bool)
)
if branch == BRANCH_CORE:
observation = object_with_fields(
"observation",
(
"kind",
"observation_kind",
"is_error",
"exit_code",
"timed_out",
"output_text",
"summary",
),
)
if isinstance(observation, str):
return observation
if observation.get("kind") not in {"observation", "error", None}:
return "observation.kind is outside the allowed vocabulary"
if observation.get("observation_kind") not in {
"FileEditorObservation",
"TerminalObservation",
"AgentErrorEvent",
None,
}:
return "observation.observation_kind is outside the allowed vocabulary"
if not isinstance(observation.get("output_text"), str):
return "observation.output_text must be a string"
if not isinstance(observation.get("summary"), str):
return "observation.summary must be a string"
if not is_bool_or_none(observation.get("is_error")):
return "observation.is_error must be boolean or null"
if not is_int_or_none(observation.get("exit_code")):
return "observation.exit_code must be integer or null"
if not is_bool_or_none(observation.get("timed_out")):
return "observation.timed_out must be boolean or null"
environment = object_with_fields(
"environment",
(
"action_status",
"repository_changed",
"changed_paths",
"path_changes",
"head_changed",
"git_status_changed",
"process_state_changed",
"terminal_session_changed",
"browser_session_changed",
environment_patch_field,
"summary",
),
)
if isinstance(environment, str):
return environment
if environment.get("action_status") not in {
"succeeded_changed",
"succeeded_no_change",
"failed",
"timed_out",
"unknown",
}:
return "environment.action_status is outside the allowed vocabulary"
if not isinstance(environment.get("changed_paths"), list) or not isinstance(
environment.get("path_changes"), Mapping
):
return "environment paths must be an array plus an object"
if not all(
isinstance(path, str) for path in environment.get("changed_paths") or []
):
return "environment.changed_paths entries must be strings"
if not isinstance(environment.get("repository_changed"), bool):
return "environment.repository_changed must be boolean"
for field in (
"head_changed",
"git_status_changed",
"process_state_changed",
"terminal_session_changed",
"browser_session_changed",
):
if not is_bool_or_none(environment.get(field)):
return f"environment.{field} must be boolean or null"
if environment.get(environment_patch_field) is not None and not isinstance(
environment.get(environment_patch_field), str
):
return f"environment.{environment_patch_field} must be a string or null"
if not isinstance(environment.get("summary"), str):
return "environment.summary must be a string"
return None
if branch == BRANCH_TEST:
execution = object_with_fields(
"execution", ("completed", "timed_out", "exit_code", "failure_mode")
)
if isinstance(execution, str):
return execution
if execution.get("failure_mode") not in {
"none",
"timed_out",
"grading_error",
"not_completed",
"nonzero_exit",
"unknown",
}:
return "execution.failure_mode is outside the allowed vocabulary"
for field in ("completed", "timed_out"):
if not is_bool_or_none(execution.get(field)):
return f"execution.{field} must be boolean or null"
if not is_int_or_none(execution.get("exit_code")):
return "execution.exit_code must be integer or null"
if not is_bool_or_none(value.get("resolved")):
return "resolved must be boolean or null"
if not is_number_or_none(value.get("reward")):
return "reward must be a number or null"
if not isinstance(value.get("summary"), str):
return "summary must be a string"
oracles = value.get("oracles")
if not isinstance(oracles, list):
return "oracles must be an array"
predicted_ids: list[str] = []
for oracle in oracles:
if not isinstance(oracle, Mapping) or not isinstance(
oracle.get("oracle_id"), str
):
return "every oracle must contain a string oracle_id"
if oracle.get("status") not in ORACLE_STATUSES:
return "every oracle status must use the allowed vocabulary"
predicted_ids.append(str(oracle["oracle_id"]))
if len(predicted_ids) != len(set(predicted_ids)):
return "oracle_id values must be unique"
missing_oracles = sorted(set(required_oracle_ids) - set(predicted_ids))
if missing_oracles:
return "prediction is missing queried oracle_id values: " + json.dumps(
missing_oracles, ensure_ascii=False
)
unexpected_oracles = sorted(set(predicted_ids) - set(required_oracle_ids))
if unexpected_oracles:
return "prediction contains unqueried oracle_id values: " + json.dumps(
unexpected_oracles, ensure_ascii=False
)
return None
outcome = object_with_fields(
"outcome", ("kind", "render_available", "failure_stage", "exit_code")
)
if isinstance(outcome, str):
return outcome
if outcome.get("kind") not in PRODUCT_OUTCOMES:
return "outcome.kind is outside the allowed vocabulary"
if not is_bool_or_none(outcome.get("render_available")):
return "outcome.render_available must be boolean or null"
if outcome.get("failure_stage") is not None and not isinstance(
outcome.get("failure_stage"), str
):
return "outcome.failure_stage must be a string or null"
if not is_int_or_none(outcome.get("exit_code")):
return "outcome.exit_code must be integer or null"
decisions = value.get("decision_fields")
if not isinstance(decisions, Mapping):
return "decision_fields must be an object"
missing_decisions = sorted(set(required_decision_fields) - set(decisions))
if missing_decisions:
return "prediction is missing decision fields: " + json.dumps(
missing_decisions, ensure_ascii=False
)
document = object_with_fields(
"document_tree",
("title", "active_element", "headings", "alerts", "controls", "links"),
)
if isinstance(document, str):
return document
if any(
not isinstance(document.get(field), list)
for field in ("headings", "alerts", "controls", "links")
):
return "document_tree collections must be arrays"
change = object_with_fields(
"change",
(
"decision_fields_changed",
"document_changed",
"pixels_changed",
"issue_state_after",
"after_description",
"change_description",
),
)
if isinstance(change, str):
return change
if change.get("issue_state_after") not in ISSUE_STATES:
return "change.issue_state_after is outside the allowed vocabulary"
for field in ("decision_fields_changed", "document_changed"):
if not isinstance(change.get(field), bool):
return f"change.{field} must be boolean"
if not is_bool_or_none(change.get("pixels_changed")):
return "change.pixels_changed must be boolean or null"
for field in ("after_description", "change_description"):
if not isinstance(change.get(field), str):
return f"change.{field} must be a string"
if not isinstance(value.get("visible_text"), str):
return "visible_text must be a string"
return None
def validate_oneshot_prediction(branch: str, value: Mapping, **kwargs: Any) -> str | None:
"""V3 accepts explicit unknown leaves, without replacing them for scoring.
Containers, required keys, oracle identifiers, and confidence remain strict.
A validation-only copy substitutes type witnesses at leaves that v2 did not
allow to be null. The actual prediction and all scored values stay intact.
"""
missing = value.get("missing_evidence")
if not isinstance(missing, list) or not all(isinstance(x, str) for x in missing):
return "missing_evidence must be an array of strings"
candidate = copy.deepcopy(value)
witnesses = {
"observation_repository": {
("observation", "output_text"): "", ("observation", "summary"): "",
("environment", "action_status"): "unknown",
("environment", "repository_changed"): False,
("environment", "summary"): "",
},
"official_tests": {("execution", "failure_mode"): "unknown", ("summary",): ""},
"render_product": {
("outcome", "kind"): "rendered_product",
("change", "decision_fields_changed"): False,
("change", "document_changed"): False,
("change", "issue_state_after"): "unknown",
("change", "after_description"): "", ("change", "change_description"): "",
("visible_text",): "",
},
}
for path, witness in witnesses[branch].items():
node = candidate
for key in path[:-1]:
node = node.get(key) if isinstance(node, dict) else None
if isinstance(node, dict) and path[-1] in node and node[path[-1]] is None:
node[path[-1]] = witness
if branch == "official_tests" and isinstance(candidate.get("oracles"), list):
for oracle in candidate["oracles"]:
if isinstance(oracle, dict) and "status" in oracle and oracle["status"] is None:
oracle["status"] = "unknown"
return validate_prediction(branch, candidate, **kwargs)
def parse_answer(text: str) -> dict:
def pairs(values: list[tuple]) -> dict:
result = {}
for key, value in values:
if key in result:
raise ValueError(f"duplicate JSON key: {key}")
result[key] = value
return result
def reject_constant(value: str) -> None:
raise ValueError(f"non-finite JSON constant: {value}")
value = json.loads(text, object_pairs_hook=pairs, parse_constant=reject_constant)
if not isinstance(value, dict):
raise ValueError("answer must be exactly one JSON object")
return value
def _mapping(value: object) -> Mapping[str, Any]:
return value if isinstance(value, Mapping) else {}
def _list(value: object) -> list[Any]:
return list(value) if isinstance(value, list) else []
def _f1_counts(correct: int, predicted: int, target: int) -> dict[str, float]:
precision = correct / predicted if predicted else (1.0 if target == 0 else 0.0)
recall = correct / target if target else (1.0 if predicted == 0 else 0.0)
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return {"precision": precision, "recall": recall, "f1": f1}
def _multiset_f1(predicted: Sequence[str], target: Sequence[str]) -> dict[str, float]:
left = Counter(predicted)
right = Counter(target)
correct = sum((left & right).values())
return _f1_counts(correct, sum(left.values()), sum(right.values()))
def _canonical_items(values: object) -> list[str]:
return [
json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
for value in _list(values)
]
def _document_delta_events(reference: object, candidate: object) -> list[str]:
"""Encode only DOM-like changes relative to the public reference state.
Collections keep the scorer's existing order-insensitive multiset semantics.
A replacement is represented by one removal plus one addition. Scalars emit
a single set event containing the predicted/target after value. Therefore
stable headings, controls, links, and alerts never create true positives.
"""
reference = _mapping(reference)
candidate = _mapping(candidate)
events: list[str] = []
missing = object()
for field in ("title", "active_element"):
before = reference.get(field, missing)
after = candidate.get(field, missing)
if (before is missing and after is missing) or (
before is not missing and after is not missing and json_equal(before, after)
):
continue
after_value: object = {"missing": True} if after is missing else after
events.append(
json.dumps(
{"field": field, "operation": "set", "value": after_value},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
)
)
for field in ("headings", "alerts", "controls", "links"):
before = Counter(_canonical_items(reference.get(field)))
after = Counter(_canonical_items(candidate.get(field)))
for operation, changes in (("remove", before - after), ("add", after - before)):
for value, count in sorted(changes.items()):
event = json.dumps(
{"field": field, "operation": operation, "value": value},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
)
events.extend([event] * count)
return events
def _document_delta_grade(
prediction: object, target: object, reference: object
) -> dict[str, Any]:
"""Score predicted DOM change events without rewarding stable background."""
predicted_events = _document_delta_events(reference, prediction)
target_events = _document_delta_events(reference, target)
score = _multiset_f1(predicted_events, target_events)
target_changed = bool(target_events)
return {
**score,
"target_changed": target_changed,
"prediction_changed": bool(predicted_events),
"target_event_count": len(target_events),
"prediction_event_count": len(predicted_events),
"changed_target_f1": score["f1"] if target_changed else None,
}
|