"""Core normalization logic for Nebius SWE-rebench OpenHands trajectories. The upstream parquet stores ``tool_call.function.arguments`` as a *serialized JSON string*. Chat templates (e.g. Qwen3-Coder) iterate ``arguments|items`` and therefore require a mapping -- feeding the raw string produces empty or broken tool calls at train/infer time. This module deserializes arguments, canonicalizes message fields per role, and optionally validates tool calls against the upstream ``tools.json``. """ from __future__ import annotations import ast import json from dataclasses import dataclass, field from typing import Any, Iterable, Optional # Canonical per-role fields, mirroring the upstream README's role2field_names. ROLE_FIELDS = { "system": ("role", "content"), "user": ("role", "content"), "assistant": ("role", "content", "tool_calls"), "tool": ("role", "content", "name", "tool_call_id"), } KNOWN_ROLES = frozenset(ROLE_FIELDS) @dataclass class Stats: """Accumulates fix/drop counters; serialized into meta.json.""" input_rows: int = 0 resolved_rows: int = 0 written_success: int = 0 written_fail: int = 0 skipped_unresolved: int = 0 drop_reasons: dict = field(default_factory=dict) fixes: dict = field(default_factory=dict) unknown_tools: dict = field(default_factory=dict) missing_required_params: dict = field(default_factory=dict) unparseable_examples: list = field(default_factory=list) def bump(self, bucket: dict, key: str, n: int = 1) -> None: bucket[key] = bucket.get(key, 0) + n def drop(self, reason: str) -> None: self.bump(self.drop_reasons, reason) def fix(self, kind: str, n: int = 1) -> None: self.bump(self.fixes, kind, n) def load_tools_schema(path: Optional[str]) -> Optional[dict]: """Load an OpenAI-style tools.json -> {name: {required: set, properties: set}}.""" if not path: return None with open(path) as f: tools = json.load(f) schema = {} for entry in tools: fn = entry.get("function", entry) name = fn.get("name") if not name: continue params = fn.get("parameters") or {} schema[name] = { "required": set(params.get("required") or []), "properties": set((params.get("properties") or {}).keys()), } return schema def deserialize_arguments(raw: Any, stats: Stats) -> tuple[Optional[dict], Optional[str]]: """Return (arguments_dict, drop_reason). arguments_dict is None on failure.""" if raw is None: stats.fix("missing_arguments") return {}, None if isinstance(raw, dict): return raw, None if not isinstance(raw, str): return None, "arguments_not_object" value: Any = raw rounds = 0 while isinstance(value, str): rounds += 1 if rounds > 3: return None, "arguments_unparseable" try: value = json.loads(value) except (json.JSONDecodeError, ValueError): try: value = ast.literal_eval(value) stats.fix("literal_eval_fallback") except (ValueError, SyntaxError, MemoryError): snippet = value[:200] if isinstance(value, str) else repr(value)[:200] if len(stats.unparseable_examples) < 5: stats.unparseable_examples.append(snippet) return None, "arguments_unparseable" if rounds > 1: stats.fix("double_encoded_arguments") stats.fix("arguments_deserialized") if not isinstance(value, dict): return None, "arguments_not_object" return value, None def normalize_tool_call(tc: Any, stats: Stats) -> tuple[Optional[dict], Optional[str]]: """Normalize one tool call to {"id"?, "type"?, "function": {"name", "arguments": dict}}.""" if not isinstance(tc, dict): return None, "tool_call_not_object" # Some producers put name/arguments at the top level instead of under "function". fn = tc.get("function") if isinstance(tc.get("function"), dict) else None if fn is None: if "name" in tc or "arguments" in tc: fn = {"name": tc.get("name"), "arguments": tc.get("arguments")} stats.fix("flattened_tool_call") else: return None, "tool_call_missing_function" args, err = deserialize_arguments(fn.get("arguments"), stats) if err: return None, err out = {"type": tc.get("type", "function"), "function": {"name": fn.get("name"), "arguments": args}} if tc.get("id") is not None: out["id"] = tc["id"] return out, None def normalize_message(msg: Any, stats: Stats) -> tuple[Optional[dict], Optional[str]]: if not isinstance(msg, dict): return None, "message_not_object" role = msg.get("role") if role not in KNOWN_ROLES: return None, f"unknown_role:{role}" out = {k: msg.get(k) for k in ROLE_FIELDS[role] if msg.get(k) is not None or k in ("role", "content")} if role == "assistant": tcs = msg.get("tool_calls") if tcs: norm = [] for tc in tcs: ntc, err = normalize_tool_call(tc, stats) if err: return None, err norm.append(ntc) out["tool_calls"] = norm else: out.pop("tool_calls", None) return out, None def validate_against_tools(messages: Iterable[dict], schema: dict, stats: Stats) -> int: """Soft validation: count tool calls whose name or required params are off. Returns the number of calls in *these* messages using an unknown tool name. """ unknown = 0 for msg in messages: if msg.get("role") != "assistant": continue for tc in msg.get("tool_calls") or []: fn = tc.get("function", {}) name = fn.get("name") spec = schema.get(name) if spec is None: stats.bump(stats.unknown_tools, str(name)) unknown += 1 continue missing = spec["required"] - set((fn.get("arguments") or {}).keys()) for p in missing: stats.bump(stats.missing_required_params, f"{name}:{p}") return unknown def normalize_row(row: dict, stats: Stats, tools_schema: Optional[dict] = None, strict_tools: bool = False) -> tuple[Optional[list], Optional[str]]: """Normalize one parquet row -> messages list, or (None, drop_reason).""" traj = row.get("trajectory") if not traj: return None, "empty_trajectory" messages = [] for msg in traj: nm, err = normalize_message(msg, stats) if err: return None, err messages.append(nm) if not any(m["role"] == "assistant" for m in messages): return None, "no_assistant_messages" if tools_schema: n_unknown = validate_against_tools(messages, tools_schema, stats) if strict_tools and n_unknown: return None, "unknown_tool" return messages, None def row_to_record(row: dict, messages: list, emit_tools: bool = True) -> dict: rec = { "messages": messages, "trajectory_id": row.get("trajectory_id"), "instance_id": row.get("instance_id"), "repo": row.get("repo"), "resolved": int(row.get("resolved") or 0), "exit_status": row.get("exit_status"), "model_patch": row.get("model_patch"), "gen_tests_correct": row.get("gen_tests_correct"), "pred_passes_gen_tests": row.get("pred_passes_gen_tests"), } if emit_tools and row.get("tools"): rec["tools"] = row["tools"] return rec