from __future__ import annotations import heapq import json import random from typing import Any from .models import BenchCase DEFAULT_FAMILIES = [ "ledger", "shortest_path", "interval_schedule", "table_join", "event_state", "instruction_order", "code_chunks", "code_window", "code_normalize", "code_percentile", ] SYSTEM = ( "You are being evaluated by a deterministic harness. Follow the requested format " "exactly and return no explanation or hidden reasoning." ) def _case(case_id: str, family: str, prompt: str, expected: Any, scorer: str = "strict_json_exact") -> BenchCase: return BenchCase( case_id=case_id, suite_id="shiftedx-quality-v1", lane="quality", messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": prompt}], scorer=scorer, expected=expected, max_output_tokens=4096, metadata={"family": family, "procedural": True}, ) def _shortest_path(graph: dict[str, dict[str, int]], source: str, target: str) -> tuple[int, list[str]]: queue: list[tuple[int, list[str], str]] = [(0, [source], source)] best: dict[str, tuple[int, list[str]]] = {} while queue: distance, path, node = heapq.heappop(queue) if node in best and best[node] <= (distance, path): continue best[node] = (distance, path) if node == target: return distance, path for neighbor, weight in graph[node].items(): heapq.heappush(queue, (distance + weight, path + [neighbor], neighbor)) raise ValueError("unreachable") def _interval_solution(jobs: list[tuple[int, int, int]]) -> tuple[int, list[int]]: best_weight = -1 best_indices: list[int] = [] for mask in range(1 << len(jobs)): indices = [index for index in range(len(jobs)) if mask & (1 << index)] selected = sorted((jobs[index][0], jobs[index][1], index) for index in indices) if any(selected[index][1] > selected[index + 1][0] for index in range(len(selected) - 1)): continue weight = sum(jobs[index][2] for index in indices) if weight > best_weight or (weight == best_weight and indices < best_indices): best_weight, best_indices = weight, indices return best_weight, best_indices def generate_quality_cases(seeds: list[int], families: list[str] | None = None) -> list[BenchCase]: families = families or DEFAULT_FAMILIES cases: list[BenchCase] = [] for seed in seeds: rng = random.Random(seed) for family in families: case_id = f"{family}__s{seed}" if family == "ledger": values = [rng.randrange(-90, 160) for _ in range(14)] expected = {"net": sum(values), "credits": sum(value > 0 for value in values)} prompt = ( f"Transactions: {values}. Return bare JSON with exactly two keys: " "net and credits. credits is the number of positive transactions." ) cases.append(_case(case_id, family, prompt, expected)) elif family == "shortest_path": graph = { "A": {"B": rng.randrange(1, 7), "C": rng.randrange(4, 10)}, "B": {"C": rng.randrange(1, 5), "D": rng.randrange(3, 9)}, "C": {"D": rng.randrange(1, 5), "E": rng.randrange(4, 9)}, "D": {"E": rng.randrange(1, 5)}, "E": {}, } distance, path = _shortest_path(graph, "A", "E") prompt = ( f"Directed weighted graph: {json.dumps(graph, sort_keys=True)}. " "Return bare JSON with the shortest distance and lexicographically smallest path from A to E." ) cases.append(_case(case_id, family, prompt, {"distance": distance, "path": path})) elif family == "interval_schedule": jobs = [] for index in range(8): start = rng.randrange(0, 14) jobs.append((start, start + rng.randrange(1, 6), rng.randrange(1, 20))) weight, indices = _interval_solution(jobs) prompt = ( f"Jobs as [start,end,weight]: {jobs}. Select non-overlapping jobs where end <= next start. " "Return bare JSON with max_weight and selected original indices; break ties lexicographically." ) cases.append(_case(case_id, family, prompt, {"max_weight": weight, "indices": indices})) elif family == "table_join": items = [f"sku-{index}" for index in range(6)] quantities = {item: rng.randrange(0, 9) for item in items} prices = {item: rng.randrange(3, 30) for item in reversed(items)} total = sum(quantities[item] * prices[item] for item in items) prompt = ( f"Quantities={json.dumps(quantities)}; unit_prices={json.dumps(prices)}. " "Join by SKU and return bare JSON with total_value and zero_stock SKUs in sorted order." ) expected = {"total_value": total, "zero_stock": sorted(k for k, v in quantities.items() if v == 0)} cases.append(_case(case_id, family, prompt, expected)) elif family == "event_state": value = rng.randrange(10, 30) events = [] for _ in range(9): operation = rng.choice(["add", "subtract", "double", "ignore"]) amount = rng.randrange(1, 6) events.append([operation, amount]) if operation == "add": value += amount elif operation == "subtract": value -= amount elif operation == "double": value *= 2 initial = rng.randrange(10, 30) value = initial for operation, amount in events: if operation == "add": value += amount elif operation == "subtract": value -= amount elif operation == "double": value *= 2 prompt = ( f"Initial value={initial}; ordered events={events}. Ignore events named ignore. " "For ['double', amount], multiply the current value by exactly 2; amount is metadata " "and is ignored. " "Return bare JSON with final_value and applied_event_count." ) expected = {"final_value": value, "applied_event_count": sum(e[0] != "ignore" for e in events)} cases.append(_case(case_id, family, prompt, expected)) elif family == "instruction_order": words = ["amber", "cinder", "fjord", "opal", "raven", "willow"] rng.shuffle(words) chosen = sorted(words[1:5], key=lambda value: (len(value), value), reverse=True) prompt = ( f"Words={words}. Discard the first and last list elements, then sort the remainder by " "descending length and reverse alphabetical order for ties. Return the bare JSON array." ) cases.append(_case(case_id, family, prompt, chosen)) elif family == "code_chunks": prompt = ( "Return only Python code defining chunked(values, size). It must return consecutive lists, " "include a final short chunk, reject size <= 0 with ValueError, and not mutate input." ) tests = """ assert chunked([1,2,3,4,5], 2) == [[1,2],[3,4],[5]] assert chunked([], 3) == [] x=[1,2,3]; assert chunked(x, 5)==[[1,2,3]] and x==[1,2,3] for bad in (0,-1): try: chunked([1], bad); raise AssertionError('missing ValueError') except ValueError: pass """ cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code")) elif family == "code_window": prompt = ( "Return only Python code defining max_window_sum(values, width). Return the largest sum of " "exactly width consecutive values. Raise ValueError for empty input or invalid width." ) tests = """ assert max_window_sum([2,-1,5,1,-3], 2) == 6 assert max_window_sum([-8,-3,-5], 1) == -3 assert max_window_sum([4,2], 2) == 6 for args in [([],1),([1],0),([1],2)]: try: max_window_sum(*args); raise AssertionError('missing ValueError') except ValueError: pass """ cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code")) elif family == "code_normalize": prompt = ( "Return only Python code defining normalize_segments(path). Collapse empty and '.' segments; " "resolve '..'; absolute paths cannot rise above root; relative paths preserve leading '..'." ) tests = """ assert normalize_segments('/a//b/../c') == '/a/c' assert normalize_segments('../../a') == '../../a' assert normalize_segments('a/../../b') == '../b' assert normalize_segments('/../../a') == '/a' assert normalize_segments('') == '.' """ cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code")) elif family == "code_percentile": prompt = ( "Return only Python code defining percentile(values, p). Use sorted values and linear " "interpolation at rank p/100*(n-1). Reject empty input and p outside 0..100 with ValueError." ) tests = """ assert percentile([1,2,3,4], 50) == 2.5 assert percentile([10,0,20], 25) == 5 assert percentile([7], 99) == 7 for args in [([],50),([1],-1),([1],101)]: try: percentile(*args); raise AssertionError('missing ValueError') except ValueError: pass """ cases.append(_case(case_id, family, prompt, {"tests": tests}, "python_code")) else: raise ValueError(f"Unknown quality family: {family}") return cases