What you will take away

The referee's verdict on this study covers the study record (findings.md, the lock, the predictions). It was given before any figure or tutorial existed, so it does not cover this page or its figures. The page reads its records from the lock and the state file (section 5 prints them) and has had its own mechanical checks, which are not a second referee.

The decision this study informs

Claims that a language model “found an optimal combinatorial object” are now common. A reader weighing one needs two things the headline rarely gives: who checked the object, and whether the model searched or remembered. This study builds the smallest honest test of both. The object is the Golomb ruler: n integer marks on a ruler such that every pairwise distance occurs once. The shortest ruler for each n is tabulated in OEIS A003022 and in public tables, so the answer key is printed in the textbook.

The question, as registered in study.yaml:

At a matched budget of verifier calls, does an LLM proposing Golomb rulers as data match the known tabulated lengths as often as a classical randomized search, on development orders 8–11 and sealed orders 12–13, and is a match search or recall?

The decision the answer feeds is practical: should a claimed LLM match on a combinatorial benchmark be read as search, as recall, or as neither until a control says otherwise?

The design in one picture

PieceWhat it is
InstanceOrders 8–11 (development, 12 pairs of order and trial) and orders 12–13 (sealed, 6 pairs), three trials per order. Each pair gets 2000 candidate evaluations.
Arm 1 — search trackRandomized construction plus simulated annealing, in search.py.
Arm 2 — llm trackThe dated snapshot qwen-flash-2025-07-28 proposes 10 rulers per request as JSON data, never code, for 200 requests, each told the verifier's verdicts on its previous batch.
JudgeOne declared verifier, verify.py, outside the mutable surface and hashed at the METHOD gate. It recomputes every count from the artifact with integer arithmetic.
Metricoptima_matched: the number of pairs whose best verified ruler has the tabulated length. An exact integer; resolution 1.
Registered rulesFive predictions (P1 to P5), each an arithmetic rule adjudicated by the notary, not by prose.

Both tracks are registered: every run is a pre-declared cell that is measured, not a climb with keeps and discards. That shapes section 4.

Intuition: an exam whose answer key is in the textbook

A student who writes the right answer in the first minute has shown you they read the book. A student who gets there after twenty crossed-out attempts may have worked it out, or half-remembered it and fixed the details. The grader is a stencil: it tells right from wrong without knowing how either student got there. Here the answer key is OEIS A003022 (ref:oeis_a003022), the stencil is verify.py, and the two students are an annealer and a language model.

The asymmetry that makes verifier-guided search work is that checking a ruler is cheap and finding a short one is not. Checking takes n(n-1)/2 subtractions and a duplicate test. The tabulated lengths exist because other people ran exhaustive searches, one order at a time (ref:robinson1979, ref:robinson1983, ref:shearer1990). Any proposer may guess; one small checker, written once and never edited by the search, decides.

A pretrained model is not a blind proposer here, because the answers are public. An ML researcher knows this as test-set contamination. So the sharper question is not “does the LLM match more often?” but “when it matches, did it search or remember?” The instrument chosen for that is the timing of a match: a match in the very first batch, before any verifier feedback exists, is what recall predicts.

The load-bearing math

A candidate A=\{a_1<\dots<a_n\} with a_1=0 and length \ell(A)=a_n is valid when all pairwise differences are distinct. This is the same as the Sidon condition (ref:wikipedia_sidon), by the rearrangement a_j-a_i=a_l-a_k \iff a_j+a_k=a_l+a_i:

V(A)=1 \iff \big|\{\,a_j-a_i : i<j\,\}\big| = \binom{n}{2}

Everything is integer arithmetic, so the check is exact and has no tolerance to choose. With both ends fixed at 0 and L, a proposer aiming at length L faces a set of candidates of size

|R_n(L)|=\binom{L-1}{n-2}

and an unpruned certificate of the tabulated length would have to rule out every shorter ruler, \binom{G(n)-1}{n-1} of them by the hockey-stick identity. Real exhaustive searches prune hard, but the counts show why each order was its own result. A blind uniform draw at the tabulated length matches with chance 2c_n/|R_n(G(n))| (c_n is the number of tabulated rulers up to reflection), which falls to the order of 10^{-15} by order 13 (method card table).

The study's metric is a match count decided by the verifier alone. With budget B=2000 candidates per pair and x_t the t-th candidate an arm submits:

s(n,\tau)=\mathbf 1\Big[\min_{t\le B,\ V(x_t)=1}\ell(x_t)=G(n)\Big],\qquad M=\sum_{n}\sum_{\tau=0}^{2}s(n,\tau)

The verifier aborts a run if any verified ruler is shorter than G(n) (the table or the checker would be wrong), so s=1 means “equal to the tabulated length”, never “beat it”. For the figures, the gap of a pair is

g(n,\tau)=\ell_{\mathrm{best}}(n,\tau)-G(n)\ \ge 0

and a match is a gap of exactly 0.

What is matched and what is not. The budget is matched in candidate evaluations, which are verifier calls. The annealer submits one candidate at a time and sees a verdict on each. The LLM submits 10 per request (200 requests) and sees one text block of 10 verdicts. Wall-clock, tokens, information per step and, above all, each proposer's prior are not matched. The unmatched prior is the confound the study exists to expose.

The recall signature

The registered signature is F, the number of LLM pairs whose first proposal batch already holds a verified ruler of length G(n). By the verifier's rules F\le M_{\mathrm{llm}}. The method card bounds the chance that a blind proposer hits in its first batch by \varepsilon_n=b\cdot 2c_n/\binom{G(n)-1}{n-2} with b=10, tiny at every lane order, so a first-batch hit would be strong evidence of an informed proposer. It would still not separate retrieval of a table from any other structured prior.

The two arms

When it pays, when it does not

A matched-budget design on tabulated instances measures recall and search together. It can say “arm X, at budget B, matched the tabulated length on k of 12 pairs”. It cannot say anything new about Golomb rulers, and a miss says nothing about whether a shorter ruler exists. The honest verbs are verified, matched the tabulated length, and did not reach it within 2000 evaluations.

There is no dataset, only an instance and an oracle

The modality is none: no rows, no columns, no train and test split. What the study reads is one tiny prepared file, data/prepared/instance.json, produced by the deterministic prepare.py and hashed at the DATA gate. It declares the two lanes (development orders 8–11, sealed orders 12–13), three trials per order, a budget of 2000 candidate evaluations, a batch size of 10 for the LLM arm, and the seed blocks. The “split” is the pair of lanes. The DATA gate therefore ran a verifier card in place of a leakage audit, and its call was go, with cautions (the gate record, not this page, holds the status).

The value-pattern check, applied to an object with no columns

The rule is never to trust a type, so every scalar in instance.json was inspected by value. All counts and lengths are JSON integers: no numbers stored as strings, no booleans, no sentinels such as -1 or NA. The optima keys are strings of integers that search.py converts with int(). One convention to know: order 1 has length 0 by convention, and no lane uses it.

Where the answer key comes from, said honestly

The lengths compared against are OEIS A003022 values for orders 8–13 (ref:oeis_a003022). They are pinned inside the verifier (ORACLE), and the verifier refuses an instance.json that disagrees with any pinned field, because the file sits where the mutable search.py has just run with write access. Who established that nothing shorter exists is a literature fact this study did not re-run: the data card records that the OEIS entry gives no per-term reference for these orders, links Shearer's tables, and credits distributed.net only for far larger orders. So “tabulated optimum” means “the OEIS value, from exhaustive searches by others”. What the DATA gate did check independently is attainability: tabulated rulers transcribed by hand for orders 8–13 were accepted by the verifier with exactly the table lengths.

The gotchas that shaped the study

  1. The sealed orders are public. “Sealed” protects against adaptive tuning of search.py (one run per arm, a mandatory dry run first). It does not make the sealed orders unseen by the model. A sealed LLM match would have been consistent with recall, which is why the study registers the first-batch signature beside the sealed prediction.
  2. Two holes found by an adversarial review, then closed. The artifact named its own lane, so a development run could have submitted a sealed-lane artifact; and the optima lived in a file the searcher could rewrite. The verifier now maps the notary's evaluation kind to the lane and carries the pinned oracle.
  3. Budget parity is self-reported. The verifier enforces that each pair spent exactly the budget, but the counter lives in the mutable file. The independent record for the LLM arm is the call ledger.
  4. The budget is matched in verifier calls, not in information or time. The annealer sees one verdict per candidate; the LLM sees one text block per 10. Every comparison is phrased “at a matched number of candidate evaluations”.
  5. No lane field is a partition. With split.kind: none there is no row split to fingerprint; the lane is guarded by the verifier's evaluation-kind check and its pinned oracle instead, and the engine's split-fingerprint check is advisory for this study.

Controls on the verifier

Before any lane run, the verifier was exercised with hand-made artifacts in a scratch directory. It rejected planted invalid rulers, forged lengths, wrong-lane artifacts and a tampered oracle, and it accepted the hand-transcribed tabulated rulers, scoring 12 of 12 on the development lane and 6 of 6 on the sealed lane. A script in sweeps/ re-runs nine of those refusals against the final verifier. Two caveats the referee asked this page to carry: the data card labels these controls the other way round from the conventional usage in findings (the gate-hashed card is left as written), and the scratch artifacts are not pinned, so their record is the card's text. These controls test the verifier. They say nothing about either arm.

How to read a registered journey

Both tracks are registered: each run is a pre-declared cell, measured or crash, never a keep or a discard. So there is no frontier to climb. The “journey” is the sequence of cells, the two crashes that interrupted one of them, and the separate sealed confirmation cell. The step line of the engine's trajectory plot is empty by design; what matters is where the squares, the crosses and the star fall.

Development evidence (orders 8–11) and sealed confirmation evidence (orders 12–13) are different partitions and are labelled separately everywhere below.

The search track

One development cell measured the annealer (E0001), and one sealed cell measured it again on the sealed orders, once, after a dry run (E0005). Nothing about the mutable surface changed between them: the notary recorded an empty candidate diff on both, and section 6 shows the same bytes under both run ids.

Decision trajectory for the search track: one blue square at 0 matched in the development phase and a star at 0 in the confirmation phase.
The search track’s registered cells in run order (metric: pairs matched, higher is better). Development cell E0001 is a blue square and the sealed final-test cell E0005 is a star off the frontier. Both sit at 0 matches; there is no incumbent to beat on a registered track, so the takeaway is the flat zero in both lanes. Close

The llm track, and the two crashes

The model arm needed four attempts at one development cell. E0002 died on an HTTP 429 rate limit from the provider after 613 calls. The transport was made to wait out rate limits and the concurrency was lowered; E0003 then died on a bare connection reset after 523 live calls plus 613 answered from E0002's shard. The transport was made to retry dropped connections, and the same pre-registered cell ran to completion as E0004. Neither crash was a bug in the ruler logic, both are kept in the ledger as crashes with an NA metric, and each fix was a dated lead decision with the contract re-recorded. No registered prediction changed.

The caveat this leaves is that E0004 answered a large share of its requests from the crashed runs' shards. Those are genuine recorded responses to byte-identical requests, but they make E0004 partly the same sample as the crashed runs, so only the salted re-query is a fully independent second draw (claim C12).

Decision trajectory for the llm track: two red crosses on the crash rug at experiments 2 and 3, a blue square at 6 matches at experiment 4, and a star at 0 matches at experiment 6 in the confirmation phase.
The llm track’s registered cells in run order (metric: pairs matched). E0002 and E0003 are transport crashes on the rug (metric NA), E0004 is the development cell that finally measured, and the star is the sealed cell E0006. The development count of 6 did not carry over to the sealed orders, where the cell measured 0. Close

What each cell measured, pair by pair

The count hides the shape. Plotting each (order, trial) pair as best verified length against the tabulated length separates the two arms cleanly:

Two panels over orders 8 to 13. Left: best verified ruler length per trial for each arm with the tabulated optimum as a bar per order. Right: the gap above the tabulated length on an axis starting at zero.
Verified best length (left) and gap to the tabulated optimum (right, zero-based) for every (order, trial) pair; development orders 8–11 left of the dotted line, sealed orders 12–13 right. The search arm (circles) misses everywhere and its gap grows with order; the LLM arm (diamonds) sits exactly on the tabulated length at orders 8 and 11, 15 units above it at order 10, and has no valid ruler at all (crosses) at orders 9, 12 and 13. Close

Three things are visible without any test. The annealer's gap grows monotonically with order, as the method card's prior predicted, so its zero is hardness growth at a fixed budget, not a defect. The LLM arm is all-or-none within each development order, which is why the pair-level contrast overstates its evidence (claim C11). And on the sealed orders the LLM arm did not merely fail to match: it produced no valid ruler, so its row of crosses has no length to compare.

The ledger

Tracks: search — optima_matched (higher is better) · llm — optima_matched (higher is better)

ExpTrackKindMetricStatusDescription
E0001searchdevelopment0measureddevelopment: classical search, orders 8-11, 3 trials, 2,000 evaluations; registered cell measured
E0002llmdevelopmentNAcrashdevelopment: qwen-flash-2025-07-28 proposes rulers, orders 8-11, 3 trials, 200 x 10 proposals; process exit code 1
E0003llmdevelopmentNAcrashdevelopment: qwen-flash-2025-07-28 proposes rulers, orders 8-11, 3 trials, 200 x 10 proposals (rerun after E0002's rate-limit crash); process exit code 1
E0004llmdevelopment6measureddevelopment: qwen-flash-2025-07-28 proposes rulers, orders 8-11, 3 trials, 200 x 10 proposals (rerun after E0003's dropped-connection crash); registered cell measured
E0005searchfinal_test0measuredsealed confirmation: classical search, orders 12-13, 3 trials, 2,000 evaluations; registered cell measured
E0006llmfinal_test0measuredsealed confirmation: qwen-flash-2025-07-28 proposes rulers, orders 12-13, 3 trials, 200 x 10 proposals; registered cell measured

The ledger key line names each track's metric and direction. The rows with an NA metric are the two crashes; the “measured” rows are the registered cells. The DRYRUN rows in aux_metrics.tsv and the files under sweeps/ are sealed rehearsals and are never evidence.

The notebook's decisions, in brief

The records

The block below is generated from claims.lock and study_state.json. Claim totals, strengths, classes, errata, the referee’s verdict and the finalization label are read from there and are not restated in this page’s prose.

claims
16 locked in claims.lock
by strength
confirmed 3 · exploratory 13
by class
empirical-description 7 · mechanism-interpretation 2 · procedural-verdict 1 · research-discipline 6
errata
1 of 16 claims tagged · 1 erratum record(s) in the lock
locked at
614c6df266bc · klein 2.2.0
label
confirmed
referee
PASS-WITH-NOTES — klein-referee (Claude Code subagent, model: claude-opus-5-5) · independent of the experimenter: yes

Scope of the referee’s verdict. It was recorded on the study record before this page existed. It does not cover this tutorial or its figures. The notes attached to it are carried into the claims below: C7 is re-scoped by erratum E1; the mechanism readings are untested hypotheses; the budget was matched in verifier calls only; usd is unrecorded, not zero; a search miss is never evidence that a match is out of reach; and exactly one model snapshot was queried.

The verdicts

Surprise 1: the recall signature did not appear

The registered recall test was a match in the first proposal batch, before any verifier feedback. It was seen in 1 of 12 pairs (P3 asked for at least 6). Five of the six matched pairs first reached the tabulated length after feedback, at proposals as late as 74 of 200 (C4).

Dot plot of the first proposal index at which each development pair held a verified ruler at the tabulated length. Order 8 trials: 1, 70, 34; order 11 trials: 2, 74, 11; orders 9 and 10 have no match.
LLM arm, development lane (run E0004): the proposal at which each of the 12 (order, trial) pairs first held a verified ruler of the tabulated length. A recall signature would stack every match on the dashed line at proposal 1; instead 5 of 6 matches arrive after feedback, and orders 9 and 10 never match. This refutes the registered first-batch rule; it does not exclude recall, because a late match can be a resampled or repaired memory. Close

The next two subsections are the closest thing this study has to a mechanism, and both are hypotheses.

Surprise 2 (an untested hypothesis): the matches look like retrieval of printed rows

Every sentence in this subsection is a hypothesis of class mechanism-interpretation, strength exploratory. No experiment in this study was designed to test it (C7, C8).

Surprise 3: the sealed LLM cell produced no valid ruler

The LLM arm produced no valid ruler at order 12 or 13, not merely no match (invalid best in 6 of 6 pairs). That claim does not rest on the searcher’s self-report: the synthesis recounts it from the pinned call-ledger shard with its own checker, reading every bracketed integer list in every reply, and finds none that is a valid ruler. Between a fifth and three in ten of the replies could not be parsed at all, at every order:

Two bar panels by order 8 to 13 for the LLM arm. Left: unparsed replies per order as a share of 600 replies, roughly a fifth to a quarter at every order. Right: valid rulers as a share of 6000 candidates, between about 3.5 and 4.5 percent at orders 8, 10 and 11, and zero at orders 9, 12 and 13.
LLM arm by order, development (solid) and sealed (hatched): unparsed replies as a share of replies (left) and valid Golomb rulers as a share of candidate evaluations (right), zero-based. Unparsing is steady across orders, so it does not explain the zeros; validity vanishes at orders 9, 12 and 13. Counts are the searcher’s own as printed in the solution tables, and the sealed valid count of 0 is independently recounted in findings from the call shard. Close

One honesty note on sources: for the salted re-query, the first-batch count and the primary count are the verifier’s, but its valid-ruler and unparsed counts are searcher-reported, and the replica’s per-pair table was not kept (C14).

Surprise 4: the compute behind a “matched” budget

The budget was matched in verifier calls only. What it hid is the cost on the other axes (C10): the LLM arm took roughly four orders of magnitude more wall-clock than the annealer, and carried millions of tokens through the provider.

Three panels. Left: equal bars for candidate evaluations per run for both arms in both lanes. Middle: wall-clock seconds on a log axis, around a third of a second for the search arm and thousands of seconds for the LLM arm. Right: model tokens in millions for the two LLM cells.
What was matched (left: candidate evaluations, identical for the two arms in each lane) against what was not (middle: wall-clock seconds on a declared log axis; right: model tokens, live calls only, for the LLM cells since the search arm has none). Wall-clock is dominated by network latency, not compute, so read it as the cost of the interface, not of the model. Close

usd is unrecorded, not zero. The study’s calls block declared no price, so every recorded usd reads 0 (claim C13). The dollar cost of the live model calls is therefore unrecorded; live token counts are recorded, so a price applied later can be computed from them. The call total is lower than the data card’s early estimate because the sealed cell cannot be re-queried by design and the development cell was re-queried once.

What the matched rulers establish, and what they do not

Controls that exist, and controls that are missing

Present: the exact verifier with a pinned oracle, the table of tabulated lengths, and a ledger cross-check (every pair has exactly 200 calls, and the stored first batch equals the ledger’s first reply in every pair). Missing, by design of the two-arm contract and with both phase allowances spent: a contamination control (an instance with no public answer), a no-feedback LLM arm (the same prompt resampled without verdicts, to separate feedback-steered repair from resampling), a compute-matched or stronger classical arm, a second snapshot or temperature, and an empirical blind-proposal null. Each missing control is the reason a specific claim above is a hypothesis and not a finding.

Why this section exists

The study’s conclusions are only as good as two small programs: the searcher that proposes and the verifier that judges. This section walks the executed source of both. For the searcher the page includes the exact bytes each named run executed, read from that run’s recorded candidate commit, not the file lying on disk (a registered track restores the mutable surface after every run, so the disk copy names no run). The verifier is outside the mutable surface and is shown as the declared verifier with its pinned hash.

The searcher, as executed

search.py is the study’s whole mutable surface and holds both arms, selected by the track. The four listings below are the same file included at four runs. Their provenance lines print the run id, evaluation kind, track, commit and sha256; the four hashes are identical, because the surface was never edited between runs. That identity is itself the point: the classical arm and the LLM arm ran on the same bytes, and the sealed runs ran the code the development runs ran.

Classical arm, development cell (E0001) and sealed cell (E0005).

search.py · executed by E0001 (development, track search) at commit f8efcf87c00e · sha256 b3188a3e6eee…
"""The searcher (the mutable surface): two arms that propose Golomb rulers for verify.py.

A Golomb ruler with n marks is a list of integers 0 = a1 < ... < an whose pairwise
differences are all distinct; its length is an, and shorter is better. For every
(order, trial) pair of the lane this run draws, an arm gets the same budget of
candidate evaluations — ONE candidate ruler checked by this file's private
`_is_golomb` is ONE evaluation, whatever produced it — and keeps the shortest valid
ruler it found:

  search  randomized construction + simulated annealing on the mark positions
          (KLEIN_TRACK=search)
  llm     qwen-flash proposes batches of rulers as JSON DATA (never code), each
          batch told the checker's verdicts on the previous one, every request
          through the call ledger (KLEIN_TRACK=llm)

The lane is KLEIN_EVALUATION_KIND: development -> development_orders, final_test ->
sealed_orders; the sealed rehearsal (KLEIN_SEALED_DRYRUN=1) runs the development
orders and prints `sealed_dryrun: 1`. Orders, trials, budget, batch size and seed
blocks come from data/prepared/instance.json (hashed at the DATA gate). The known
optima are read for BOOK-KEEPING ONLY — the provisional count printed below and the
index of the first optimal ruler; no search decision and no prompt uses them.

The run's number is provisional: the declared verifier (verify.py — outside this
surface, sharing no code with it, hashed at METHOD) recomputes `optima_matched` and
`first_batch_matches` from the artifact printed under `solution:`, and decides.
"""

from __future__ import annotations

import hashlib
import json
import math
import os
import random
import re
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from kleinlib.eval import evaluate_scalar

SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
SEALED_DRYRUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK")
ARMS = ("search", "llm")

# Smoke: the first development order, one trial, a tiny budget (a shape check, not evidence).
SMOKE_BUDGET = {"search": 200, "llm": 30}

# --- the search arm -----------------------------------------------------------
SA_T0 = 1.0           # starting temperature, in units of "repeated differences"
SA_COOLING = 0.98     # per INVALID candidate (a valid candidate resets the temperature to 1.0)
SA_T_MIN = 0.05
SA_PATIENCE = 150     # evaluations at one target length without a valid ruler -> restart there
P_CONFLICTED = 0.85   # move a mark that takes part in a repeated difference
P_LOCAL = 0.5         # ... by a small shift (else: anywhere free on the ruler)

# --- the llm arm --------------------------------------------------------------
LLM_PARAMS = {"temperature": 0.7, "max_tokens": 1024, "enable_thinking": False}
SYSTEM_PROMPT = (
    "You propose Golomb rulers as data. A Golomb ruler with n marks is a list of n "
    "integers that starts at 0, is strictly increasing, and has all pairwise "
    "differences distinct. Its length is its last mark, and a shorter ruler is "
    "better. Reply with JSON data only: never code, never an explanation."
)


# --- the searcher's own checker (never the verifier) -----------------------------


class Budget:
    """Candidate evaluations for one (order, trial): every `_is_golomb` call spends one."""

    def __init__(self, limit: int) -> None:
        self.limit = int(limit)
        self.spent = 0

    def exhausted(self) -> bool:
        return self.spent >= self.limit

    def spend(self) -> None:
        if self.spent >= self.limit:
            raise RuntimeError(f"evaluation budget overspent ({self.limit})")
        self.spent += 1


@dataclass(frozen=True)
class Verdict:
    valid: bool
    reason: str                    # "valid", or why the candidate is not a valid ruler
    length: int | None             # the last mark, when the candidate is a well-formed mark list
    first_repeat: int | None       # the first repeated difference, pairs scanned (i < j) by j then i
    repeats: int                   # differences that repeat an earlier one
    conflicted: tuple[int, ...]    # mark indices that take part in a repeated difference


def _is_golomb(marks: Any, n: int, budget: Budget) -> Verdict:
    """The searcher's private checker. Each call is one evaluation of the budget."""
    budget.spend()
    if marks is None:
        return Verdict(False, "missing", None, None, 0, ())
    if not isinstance(marks, list) or not all(
        isinstance(m, int) and not isinstance(m, bool) for m in marks
    ):
        return Verdict(False, "not a list of integers", None, None, 0, ())
    if len(marks) != n:
        return Verdict(False, f"has {len(marks)} marks, needs {n}", None, None, 0, ())
    if marks[0] != 0:
        return Verdict(False, "does not start at 0", None, None, 0, ())
    if any(b <= a for a, b in zip(marks, marks[1:], strict=False)):
        return Verdict(False, "not strictly increasing", None, None, 0, ())
    owner: dict[int, tuple[int, int]] = {}
    repeats, first, conflicted = 0, None, set()
    for j in range(1, n):
        for i in range(j):
            d = marks[j] - marks[i]
            earlier = owner.get(d)
            if earlier is None:
                owner[d] = (i, j)
                continue
            repeats += 1
            first = d if first is None else first
            conflicted.update((i, j, *earlier))
    if repeats:
        return Verdict(False, f"difference {first} repeats", marks[-1], first, repeats,
                       tuple(sorted(conflicted)))
    return Verdict(True, "valid", marks[-1], None, 0, ())


# --- arm 1: randomized construction + simulated annealing ------------------------


def _random_ruler(n: int, length: int, rng: random.Random) -> list[int]:
    return [0, *sorted(rng.sample(range(1, length), n - 2)), length]


def _shrink(marks: list[int], step: int, rng: random.Random) -> list[int]:
    """Cut `step` empty unit cells at random: differences on one side of a cut survive."""
    marks = list(marks)
    for _ in range(step):
        occupied = set(marks)
        cut = rng.choice([c for c in range(1, marks[-1]) if c not in occupied])
        marks = [m - 1 if m > cut else m for m in marks]
    return marks


def _move(marks: list[int], verdict: Verdict, rng: random.Random) -> list[int]:
    """Relocate one interior mark (the ends 0 and L stay): the length is unchanged."""
    n, length = len(marks), marks[-1]
    interior = [i for i in verdict.conflicted if 0 < i < n - 1]
    if interior and rng.random() < P_CONFLICTED:
        i = rng.choice(interior)
    else:
        i = rng.randrange(1, n - 1)
    occupied = set(marks)
    while True:
        if rng.random() < P_LOCAL:
            p = marks[i] + rng.choice((-3, -2, -1, 1, 2, 3))
        else:
            p = rng.randrange(1, length)
        if 0 < p < length and p not in occupied:
            break
    return sorted([*marks[:i], *marks[i + 1:], p])


def search_pair(n: int, seed: int, limit: int, optimum: int) -> dict[str, Any]:
    """One (order, trial): the shortest valid ruler found within `limit` evaluations.

    Construction: both ends fixed at 0 and n*n, n-2 interior marks at random (sparse enough that a few
    moves make it valid). Then repeatedly: aim one length shorter than the best valid
    ruler (an adaptive step, doubling while successes come fast), start from the best
    with empty cells cut out, and anneal the interior marks to remove repeated
    differences; restart from the best after SA_PATIENCE evaluations without a valid
    ruler. Stops at the budget, or at the trivial bound n(n-1)/2 (a perfect ruler).
    """
    if n < 3:
        raise ValueError("the search arm needs at least 3 marks")
    rng = random.Random(seed)
    budget = Budget(limit)
    floor = n * (n - 1) // 2
    best: list[int] | None = None
    best_at = first_optimal_at = None
    state: list[int] | None = None
    state_verdict: Verdict | None = None
    step, since_valid, since_start, restarts = 1, 0, 0, 0
    temperature = SA_T0
    while not budget.exhausted():
        if best is not None and best[-1] <= floor:
            break  # n(n-1)/2 distinct positive differences: nothing shorter exists
        if state is None:
            if best is None:
                candidate = _random_ruler(n, n * n, rng)
            else:
                candidate = _shrink(best, min(step, best[-1] - floor), rng)
        else:
            candidate = _move(state, state_verdict, rng)
        verdict = _is_golomb(candidate, n, budget)
        since_valid += 1
        if verdict.valid:
            if best is None or candidate[-1] < best[-1]:
                best, best_at = candidate, budget.spent
                if first_optimal_at is None and candidate[-1] == optimum:
                    first_optimal_at = budget.spent
            step = min(2 * step, n) if since_valid <= n else 1
            state, state_verdict = None, None
            since_valid, since_start, temperature = 0, 0, SA_T0
            continue
        if (
            state_verdict is None
            or verdict.repeats <= state_verdict.repeats
            or rng.random() < math.exp((state_verdict.repeats - verdict.repeats) / temperature)
        ):
            state, state_verdict = candidate, verdict
        temperature = max(SA_T_MIN, temperature * SA_COOLING)
        since_start += 1
        if since_start >= SA_PATIENCE:
            state, state_verdict = None, None
            step, since_start, temperature = 1, 0, SA_T0
            restarts += 1
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "best_found_at_evaluation": best_at,
        "first_optimal_evaluation": first_optimal_at,
        "restarts": restarts,
    }


def run_search(orders: list[int], trials: int, limit: int, lane_seed: int,
               optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float]]:
    pairs = []
    for n in orders:
        for trial in range(trials):
            seed = lane_seed + n * 100 + trial
            pairs.append({"order": n, "trial": trial, "seed": seed,
                          **search_pair(n, seed, limit, optima[n])})
    return pairs, {"restarts": float(sum(p["restarts"] for p in pairs))}


# --- arm 2: the LLM proposes rulers as data -------------------------------------

_INNER_LIST = re.compile(r"\[[^\[\]]*\]")


def _parse_batch(text: str, batch: int) -> tuple[list[Any], bool]:
    """Exactly `batch` entries (None = missing) and whether the reply was one JSON list.

    The outermost [...] span is read as JSON (this strips code fences and any prose
    around it). A reply cut off mid-list falls back to every complete inner list.
    Nothing is repaired: an entry that is not already a valid ruler is an invalid
    evaluation, and a missing entry still spends its evaluation.
    """
    entries: list[Any] | None = None
    start, end = text.find("["), text.rfind("]")
    if start != -1 and end > start:
        try:
            value = json.loads(text[start:end + 1])
        except ValueError:
            value = None
        if isinstance(value, list):
            if value and all(isinstance(v, int) and not isinstance(v, bool) for v in value):
                value = [value]  # one bare ruler
            entries = value
    strict = entries is not None
    if entries is None:
        entries = []
        for chunk in _INNER_LIST.findall(text):
            try:
                entries.append(json.loads(chunk))
            except ValueError:
                continue
    entries = entries[:batch]
    return entries + [None] * (batch - len(entries)), strict


def _show(entry: Any) -> str:
    if entry is None:
        return "(no ruler)"
    text = json.dumps(entry)
    return text if len(text) <= 160 else text[:157] + "..."


def _describe(verdict: Verdict) -> str:
    if verdict.valid:
        return f"valid, length {verdict.length}"
    if verdict.first_repeat is not None:
        return f"invalid, length {verdict.length}, difference {verdict.first_repeat} repeats"
    return f"invalid, {verdict.reason}"


def _messages(n: int, k: int, proposals: int, batch: int,
              previous: list[tuple[Any, Verdict]] | None,
              best_length: int | None) -> list[dict[str, str]]:
    lines = [
        f"Propose exactly {batch} candidate Golomb rulers with {n} marks each.",
        f"Every ruler must start at 0, be strictly increasing, contain exactly {n} "
        f"integers, and have all {n * (n - 1) // 2} pairwise differences distinct. "
        "Shorter is better: the length of a ruler is its last mark.",
        f"This is proposal {k} of {proposals}.",
    ]
    if previous is not None:
        lines += ["", "The verifier's verdicts on your previous batch:"]
        lines += [f"{i}. {_show(entry)}: {_describe(verdict)}"
                  for i, (entry, verdict) in enumerate(previous, start=1)]
        lines.append(f"Best valid length so far: {best_length}." if best_length is not None
                     else "No valid ruler so far.")
    lines += ["", f"Reply with a JSON list of {batch} lists of integers and nothing else."]
    return [{"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": "\n".join(lines)}]


class _Aborted(RuntimeError):
    """Another (order, trial) loop failed; this one stops before its next request."""


def llm_pair(ledger: Any, n: int, trial: int, limit: int, batch: int, optimum: int,
             abort: threading.Event) -> dict[str, Any]:
    """One (order, trial): `limit // batch` sequential proposals, each fed back the last."""
    budget = Budget(limit)
    proposals = limit // batch
    best: list[int] | None = None
    best_at = first_optimal = None
    first_batch: list[Any] | None = None
    previous: list[tuple[Any, Verdict]] | None = None
    valid = unparsed = 0
    for k in range(1, proposals + 1):
        if abort.is_set():
            raise _Aborted(f"order {n} trial {trial} stopped at proposal {k}")
        reply = ledger.chat(_messages(n, k, proposals, batch, previous,
                                      None if best is None else best[-1]),
                            sample=trial, **LLM_PARAMS)
        entries, strict = _parse_batch(reply, batch)
        unparsed += not strict
        verdicts = [_is_golomb(entry, n, budget) for entry in entries]
        if k == 1:
            first_batch = [entry if isinstance(entry, list) else None for entry in entries]
        for entry, verdict in zip(entries, verdicts, strict=True):
            if not verdict.valid:
                continue
            valid += 1
            if best is None or entry[-1] < best[-1]:
                best, best_at = list(entry), k
            if first_optimal is None and entry[-1] == optimum:
                first_optimal = k
        previous = list(zip(entries, verdicts, strict=True))
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "proposals": proposals,
        "best_found_at_proposal": best_at,
        "first_optimal_proposal": first_optimal,
        "valid_rulers": valid,
        "unparsed_replies": unparsed,
        "first_batch": first_batch,
    }


def _smoke_reply(n: int) -> str:
    """A fenced JSON batch for KLEIN_SMOKE=1: one entry per parse/verdict path, then padding."""
    sidon = [2 ** i - 1 for i in range(n)]  # 2^j - 2^i are all distinct: a valid ruler
    batch = [
        sidon,
        [2 * m for m in sidon],             # valid, longer
        [m + 1 for m in sidon],             # does not start at 0
        list(range(0, 2 * n, 2)),           # difference 2 repeats
        sidon[:-1],                         # wrong mark count
        [0, *sidon[:0:-1]],                 # not strictly increasing
        "x",                                # not a list
    ]
    return "Here are the rulers:\n```json\n" + json.dumps(batch) + "\n```"


def run_llm(orders: list[int], trials: int, limit: int, batch: int,
            optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float], dict[str, Any]]:
    from kleinlib.calls import CallLedger

    if limit % batch:
        raise SystemExit(f"budget {limit} is not a multiple of the batch {batch}")
    # The sealed rehearsal replays the development cell from the ledger and must
    # spend nothing: offline, a request the ledger cannot answer is a crash.
    overrides = {"offline": True} if SEALED_DRYRUN else {}
    jobs = [(n, trial) for n in orders for trial in range(trials)]
    abort = threading.Event()
    results: dict[tuple[int, int], dict[str, Any]] = {}
    error: BaseException | None = None
    with CallLedger.from_contract(".", smoke_response=_smoke_reply(orders[0]), **overrides) as ledger:
        # Proposals within a trial are sequential (each carries the last batch's
        # verdicts); the (order, trial) loops are independent and run side by side,
        # calls.max_workers at a time. Each loop passes its trial index as `sample`,
        # so the trials are distinct requests, not cached copies of one another.
        with ThreadPoolExecutor(max_workers=min(ledger.max_workers, len(jobs))) as pool:
            futures = {pool.submit(llm_pair, ledger, n, trial, limit, batch, optima[n], abort): (n, trial)
                       for n, trial in jobs}
            for future in as_completed(futures):
                exc = future.exception()
                if exc is None:
                    results[futures[future]] = future.result()
                elif error is None:
                    error = exc
                    abort.set()
        meta = {"model": ledger.model, "base_url": ledger.base_url, "params": LLM_PARAMS,
                "batch": batch, "proposals_per_trial": limit // batch,
                "system_prompt": SYSTEM_PROMPT}
    if error is not None:
        raise error
    pairs = [{"order": n, "trial": trial, "sample": trial, **results[(n, trial)]} for n, trial in jobs]
    extra = {
        "valid_rulers": float(sum(p["valid_rulers"] for p in pairs)),
        "unparsed_replies": float(sum(p["unparsed_replies"] for p in pairs)),
        **ledger.summary(),
    }
    return pairs, extra, meta


# --- the run ------------------------------------------------------------------


def _artifact_path() -> Path:
    if SMOKE:
        return Path(tempfile.mkdtemp(prefix="klein-smoke-")) / f"solution_SMOKE_{TRACK}.json"
    if SEALED_DRYRUN:
        # Filed with the rehearsal's own state commit (sweeps/), so the tree the
        # sealed run needs stays clean; tables/ holds only real runs' artifacts.
        return Path("sweeps") / f"solution_DRYRUN_{TRACK}.json"
    return Path("tables") / f"solution_{EXPERIMENT_ID}.json"


def main() -> None:
    t0 = time.time()
    kind = os.environ.get("KLEIN_EVALUATION_KIND") or ("development" if SMOKE else None)
    if EXPERIMENT_ID is None or kind is None or TRACK is None:
        raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 KLEIN_TRACK=<arm> for a shape check)")
    if TRACK not in ARMS:
        raise SystemExit(f"KLEIN_TRACK={TRACK!r}: this study's arms are {ARMS}")
    if kind not in {"development", "final_test"}:
        raise RuntimeError(f"invalid KLEIN_EVALUATION_KIND={kind!r}")
    instance = json.loads(Path("data/prepared/instance.json").read_text(encoding="utf-8"))
    lane = "sealed" if kind == "final_test" else "development"
    if kind == "final_test" and SEALED_DRYRUN:
        print("sealed_dryrun: 1")
        lane = "development"
    orders = [int(n) for n in instance[f"{lane}_orders"]]
    trials = int(instance["trials"])
    limit = int(instance["budget_evaluations"])
    batch = int(instance["llm_batch"])
    lane_seed = int(instance["seed_blocks"][lane])
    optima = {int(n): int(length) for n, length in instance["optima"].items()}
    if SMOKE:
        orders, trials, limit = orders[:1], 1, SMOKE_BUDGET[TRACK]

    payload: dict[str, Any] = {
        "problem": "golomb-ruler", "arm": TRACK, "experiment": EXPERIMENT_ID, "lane": lane,
        "sealed_dryrun": SEALED_DRYRUN, "orders": orders, "trials": trials,
        "budget_evaluations": limit,
    }
    if TRACK == "search":
        pairs, extra = run_search(orders, trials, limit, lane_seed, optima)
        payload["seed_block"] = lane_seed
    else:
        pairs, extra, payload["llm"] = run_llm(orders, trials, limit, batch, optima)
    payload["pairs"] = pairs

    matched = sum(p["best_length"] == optima[p["order"]] for p in pairs)
    first_batch = sum(p.get("first_optimal_proposal") == 1 for p in pairs)

    out = _artifact_path()
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(payload, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(f"solution: {out.as_posix()}")
    print(f"artifact: {out.as_posix()}")

    lane_fingerprint = hashlib.sha256(json.dumps(
        {"lane": lane, "orders": orders, "trials": trials, "budget": limit, "seed_block": lane_seed},
        sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
    evaluate_scalar(
        float(matched), exp_id=EXPERIMENT_ID, metric_name="optima_matched", metric_goal="higher",
        extra={
            "first_batch_matches": float(first_batch),
            "pairs": float(len(pairs)),
            "evaluations": float(sum(p["evaluations"] for p in pairs)),
            "sealed_lane": 1.0 if lane == "sealed" else 0.0,
            **extra,
        },
        split_fingerprint=lane_fingerprint, t0=t0, study_dir=None if SMOKE else ".",
    )


if __name__ == "__main__":
    main()
search.py · executed by E0005 (final_test, track search) at commit 838c86f49f62 · sha256 b3188a3e6eee…
"""The searcher (the mutable surface): two arms that propose Golomb rulers for verify.py.

A Golomb ruler with n marks is a list of integers 0 = a1 < ... < an whose pairwise
differences are all distinct; its length is an, and shorter is better. For every
(order, trial) pair of the lane this run draws, an arm gets the same budget of
candidate evaluations — ONE candidate ruler checked by this file's private
`_is_golomb` is ONE evaluation, whatever produced it — and keeps the shortest valid
ruler it found:

  search  randomized construction + simulated annealing on the mark positions
          (KLEIN_TRACK=search)
  llm     qwen-flash proposes batches of rulers as JSON DATA (never code), each
          batch told the checker's verdicts on the previous one, every request
          through the call ledger (KLEIN_TRACK=llm)

The lane is KLEIN_EVALUATION_KIND: development -> development_orders, final_test ->
sealed_orders; the sealed rehearsal (KLEIN_SEALED_DRYRUN=1) runs the development
orders and prints `sealed_dryrun: 1`. Orders, trials, budget, batch size and seed
blocks come from data/prepared/instance.json (hashed at the DATA gate). The known
optima are read for BOOK-KEEPING ONLY — the provisional count printed below and the
index of the first optimal ruler; no search decision and no prompt uses them.

The run's number is provisional: the declared verifier (verify.py — outside this
surface, sharing no code with it, hashed at METHOD) recomputes `optima_matched` and
`first_batch_matches` from the artifact printed under `solution:`, and decides.
"""

from __future__ import annotations

import hashlib
import json
import math
import os
import random
import re
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from kleinlib.eval import evaluate_scalar

SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
SEALED_DRYRUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK")
ARMS = ("search", "llm")

# Smoke: the first development order, one trial, a tiny budget (a shape check, not evidence).
SMOKE_BUDGET = {"search": 200, "llm": 30}

# --- the search arm -----------------------------------------------------------
SA_T0 = 1.0           # starting temperature, in units of "repeated differences"
SA_COOLING = 0.98     # per INVALID candidate (a valid candidate resets the temperature to 1.0)
SA_T_MIN = 0.05
SA_PATIENCE = 150     # evaluations at one target length without a valid ruler -> restart there
P_CONFLICTED = 0.85   # move a mark that takes part in a repeated difference
P_LOCAL = 0.5         # ... by a small shift (else: anywhere free on the ruler)

# --- the llm arm --------------------------------------------------------------
LLM_PARAMS = {"temperature": 0.7, "max_tokens": 1024, "enable_thinking": False}
SYSTEM_PROMPT = (
    "You propose Golomb rulers as data. A Golomb ruler with n marks is a list of n "
    "integers that starts at 0, is strictly increasing, and has all pairwise "
    "differences distinct. Its length is its last mark, and a shorter ruler is "
    "better. Reply with JSON data only: never code, never an explanation."
)


# --- the searcher's own checker (never the verifier) -----------------------------


class Budget:
    """Candidate evaluations for one (order, trial): every `_is_golomb` call spends one."""

    def __init__(self, limit: int) -> None:
        self.limit = int(limit)
        self.spent = 0

    def exhausted(self) -> bool:
        return self.spent >= self.limit

    def spend(self) -> None:
        if self.spent >= self.limit:
            raise RuntimeError(f"evaluation budget overspent ({self.limit})")
        self.spent += 1


@dataclass(frozen=True)
class Verdict:
    valid: bool
    reason: str                    # "valid", or why the candidate is not a valid ruler
    length: int | None             # the last mark, when the candidate is a well-formed mark list
    first_repeat: int | None       # the first repeated difference, pairs scanned (i < j) by j then i
    repeats: int                   # differences that repeat an earlier one
    conflicted: tuple[int, ...]    # mark indices that take part in a repeated difference


def _is_golomb(marks: Any, n: int, budget: Budget) -> Verdict:
    """The searcher's private checker. Each call is one evaluation of the budget."""
    budget.spend()
    if marks is None:
        return Verdict(False, "missing", None, None, 0, ())
    if not isinstance(marks, list) or not all(
        isinstance(m, int) and not isinstance(m, bool) for m in marks
    ):
        return Verdict(False, "not a list of integers", None, None, 0, ())
    if len(marks) != n:
        return Verdict(False, f"has {len(marks)} marks, needs {n}", None, None, 0, ())
    if marks[0] != 0:
        return Verdict(False, "does not start at 0", None, None, 0, ())
    if any(b <= a for a, b in zip(marks, marks[1:], strict=False)):
        return Verdict(False, "not strictly increasing", None, None, 0, ())
    owner: dict[int, tuple[int, int]] = {}
    repeats, first, conflicted = 0, None, set()
    for j in range(1, n):
        for i in range(j):
            d = marks[j] - marks[i]
            earlier = owner.get(d)
            if earlier is None:
                owner[d] = (i, j)
                continue
            repeats += 1
            first = d if first is None else first
            conflicted.update((i, j, *earlier))
    if repeats:
        return Verdict(False, f"difference {first} repeats", marks[-1], first, repeats,
                       tuple(sorted(conflicted)))
    return Verdict(True, "valid", marks[-1], None, 0, ())


# --- arm 1: randomized construction + simulated annealing ------------------------


def _random_ruler(n: int, length: int, rng: random.Random) -> list[int]:
    return [0, *sorted(rng.sample(range(1, length), n - 2)), length]


def _shrink(marks: list[int], step: int, rng: random.Random) -> list[int]:
    """Cut `step` empty unit cells at random: differences on one side of a cut survive."""
    marks = list(marks)
    for _ in range(step):
        occupied = set(marks)
        cut = rng.choice([c for c in range(1, marks[-1]) if c not in occupied])
        marks = [m - 1 if m > cut else m for m in marks]
    return marks


def _move(marks: list[int], verdict: Verdict, rng: random.Random) -> list[int]:
    """Relocate one interior mark (the ends 0 and L stay): the length is unchanged."""
    n, length = len(marks), marks[-1]
    interior = [i for i in verdict.conflicted if 0 < i < n - 1]
    if interior and rng.random() < P_CONFLICTED:
        i = rng.choice(interior)
    else:
        i = rng.randrange(1, n - 1)
    occupied = set(marks)
    while True:
        if rng.random() < P_LOCAL:
            p = marks[i] + rng.choice((-3, -2, -1, 1, 2, 3))
        else:
            p = rng.randrange(1, length)
        if 0 < p < length and p not in occupied:
            break
    return sorted([*marks[:i], *marks[i + 1:], p])


def search_pair(n: int, seed: int, limit: int, optimum: int) -> dict[str, Any]:
    """One (order, trial): the shortest valid ruler found within `limit` evaluations.

    Construction: both ends fixed at 0 and n*n, n-2 interior marks at random (sparse enough that a few
    moves make it valid). Then repeatedly: aim one length shorter than the best valid
    ruler (an adaptive step, doubling while successes come fast), start from the best
    with empty cells cut out, and anneal the interior marks to remove repeated
    differences; restart from the best after SA_PATIENCE evaluations without a valid
    ruler. Stops at the budget, or at the trivial bound n(n-1)/2 (a perfect ruler).
    """
    if n < 3:
        raise ValueError("the search arm needs at least 3 marks")
    rng = random.Random(seed)
    budget = Budget(limit)
    floor = n * (n - 1) // 2
    best: list[int] | None = None
    best_at = first_optimal_at = None
    state: list[int] | None = None
    state_verdict: Verdict | None = None
    step, since_valid, since_start, restarts = 1, 0, 0, 0
    temperature = SA_T0
    while not budget.exhausted():
        if best is not None and best[-1] <= floor:
            break  # n(n-1)/2 distinct positive differences: nothing shorter exists
        if state is None:
            if best is None:
                candidate = _random_ruler(n, n * n, rng)
            else:
                candidate = _shrink(best, min(step, best[-1] - floor), rng)
        else:
            candidate = _move(state, state_verdict, rng)
        verdict = _is_golomb(candidate, n, budget)
        since_valid += 1
        if verdict.valid:
            if best is None or candidate[-1] < best[-1]:
                best, best_at = candidate, budget.spent
                if first_optimal_at is None and candidate[-1] == optimum:
                    first_optimal_at = budget.spent
            step = min(2 * step, n) if since_valid <= n else 1
            state, state_verdict = None, None
            since_valid, since_start, temperature = 0, 0, SA_T0
            continue
        if (
            state_verdict is None
            or verdict.repeats <= state_verdict.repeats
            or rng.random() < math.exp((state_verdict.repeats - verdict.repeats) / temperature)
        ):
            state, state_verdict = candidate, verdict
        temperature = max(SA_T_MIN, temperature * SA_COOLING)
        since_start += 1
        if since_start >= SA_PATIENCE:
            state, state_verdict = None, None
            step, since_start, temperature = 1, 0, SA_T0
            restarts += 1
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "best_found_at_evaluation": best_at,
        "first_optimal_evaluation": first_optimal_at,
        "restarts": restarts,
    }


def run_search(orders: list[int], trials: int, limit: int, lane_seed: int,
               optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float]]:
    pairs = []
    for n in orders:
        for trial in range(trials):
            seed = lane_seed + n * 100 + trial
            pairs.append({"order": n, "trial": trial, "seed": seed,
                          **search_pair(n, seed, limit, optima[n])})
    return pairs, {"restarts": float(sum(p["restarts"] for p in pairs))}


# --- arm 2: the LLM proposes rulers as data -------------------------------------

_INNER_LIST = re.compile(r"\[[^\[\]]*\]")


def _parse_batch(text: str, batch: int) -> tuple[list[Any], bool]:
    """Exactly `batch` entries (None = missing) and whether the reply was one JSON list.

    The outermost [...] span is read as JSON (this strips code fences and any prose
    around it). A reply cut off mid-list falls back to every complete inner list.
    Nothing is repaired: an entry that is not already a valid ruler is an invalid
    evaluation, and a missing entry still spends its evaluation.
    """
    entries: list[Any] | None = None
    start, end = text.find("["), text.rfind("]")
    if start != -1 and end > start:
        try:
            value = json.loads(text[start:end + 1])
        except ValueError:
            value = None
        if isinstance(value, list):
            if value and all(isinstance(v, int) and not isinstance(v, bool) for v in value):
                value = [value]  # one bare ruler
            entries = value
    strict = entries is not None
    if entries is None:
        entries = []
        for chunk in _INNER_LIST.findall(text):
            try:
                entries.append(json.loads(chunk))
            except ValueError:
                continue
    entries = entries[:batch]
    return entries + [None] * (batch - len(entries)), strict


def _show(entry: Any) -> str:
    if entry is None:
        return "(no ruler)"
    text = json.dumps(entry)
    return text if len(text) <= 160 else text[:157] + "..."


def _describe(verdict: Verdict) -> str:
    if verdict.valid:
        return f"valid, length {verdict.length}"
    if verdict.first_repeat is not None:
        return f"invalid, length {verdict.length}, difference {verdict.first_repeat} repeats"
    return f"invalid, {verdict.reason}"


def _messages(n: int, k: int, proposals: int, batch: int,
              previous: list[tuple[Any, Verdict]] | None,
              best_length: int | None) -> list[dict[str, str]]:
    lines = [
        f"Propose exactly {batch} candidate Golomb rulers with {n} marks each.",
        f"Every ruler must start at 0, be strictly increasing, contain exactly {n} "
        f"integers, and have all {n * (n - 1) // 2} pairwise differences distinct. "
        "Shorter is better: the length of a ruler is its last mark.",
        f"This is proposal {k} of {proposals}.",
    ]
    if previous is not None:
        lines += ["", "The verifier's verdicts on your previous batch:"]
        lines += [f"{i}. {_show(entry)}: {_describe(verdict)}"
                  for i, (entry, verdict) in enumerate(previous, start=1)]
        lines.append(f"Best valid length so far: {best_length}." if best_length is not None
                     else "No valid ruler so far.")
    lines += ["", f"Reply with a JSON list of {batch} lists of integers and nothing else."]
    return [{"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": "\n".join(lines)}]


class _Aborted(RuntimeError):
    """Another (order, trial) loop failed; this one stops before its next request."""


def llm_pair(ledger: Any, n: int, trial: int, limit: int, batch: int, optimum: int,
             abort: threading.Event) -> dict[str, Any]:
    """One (order, trial): `limit // batch` sequential proposals, each fed back the last."""
    budget = Budget(limit)
    proposals = limit // batch
    best: list[int] | None = None
    best_at = first_optimal = None
    first_batch: list[Any] | None = None
    previous: list[tuple[Any, Verdict]] | None = None
    valid = unparsed = 0
    for k in range(1, proposals + 1):
        if abort.is_set():
            raise _Aborted(f"order {n} trial {trial} stopped at proposal {k}")
        reply = ledger.chat(_messages(n, k, proposals, batch, previous,
                                      None if best is None else best[-1]),
                            sample=trial, **LLM_PARAMS)
        entries, strict = _parse_batch(reply, batch)
        unparsed += not strict
        verdicts = [_is_golomb(entry, n, budget) for entry in entries]
        if k == 1:
            first_batch = [entry if isinstance(entry, list) else None for entry in entries]
        for entry, verdict in zip(entries, verdicts, strict=True):
            if not verdict.valid:
                continue
            valid += 1
            if best is None or entry[-1] < best[-1]:
                best, best_at = list(entry), k
            if first_optimal is None and entry[-1] == optimum:
                first_optimal = k
        previous = list(zip(entries, verdicts, strict=True))
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "proposals": proposals,
        "best_found_at_proposal": best_at,
        "first_optimal_proposal": first_optimal,
        "valid_rulers": valid,
        "unparsed_replies": unparsed,
        "first_batch": first_batch,
    }


def _smoke_reply(n: int) -> str:
    """A fenced JSON batch for KLEIN_SMOKE=1: one entry per parse/verdict path, then padding."""
    sidon = [2 ** i - 1 for i in range(n)]  # 2^j - 2^i are all distinct: a valid ruler
    batch = [
        sidon,
        [2 * m for m in sidon],             # valid, longer
        [m + 1 for m in sidon],             # does not start at 0
        list(range(0, 2 * n, 2)),           # difference 2 repeats
        sidon[:-1],                         # wrong mark count
        [0, *sidon[:0:-1]],                 # not strictly increasing
        "x",                                # not a list
    ]
    return "Here are the rulers:\n```json\n" + json.dumps(batch) + "\n```"


def run_llm(orders: list[int], trials: int, limit: int, batch: int,
            optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float], dict[str, Any]]:
    from kleinlib.calls import CallLedger

    if limit % batch:
        raise SystemExit(f"budget {limit} is not a multiple of the batch {batch}")
    # The sealed rehearsal replays the development cell from the ledger and must
    # spend nothing: offline, a request the ledger cannot answer is a crash.
    overrides = {"offline": True} if SEALED_DRYRUN else {}
    jobs = [(n, trial) for n in orders for trial in range(trials)]
    abort = threading.Event()
    results: dict[tuple[int, int], dict[str, Any]] = {}
    error: BaseException | None = None
    with CallLedger.from_contract(".", smoke_response=_smoke_reply(orders[0]), **overrides) as ledger:
        # Proposals within a trial are sequential (each carries the last batch's
        # verdicts); the (order, trial) loops are independent and run side by side,
        # calls.max_workers at a time. Each loop passes its trial index as `sample`,
        # so the trials are distinct requests, not cached copies of one another.
        with ThreadPoolExecutor(max_workers=min(ledger.max_workers, len(jobs))) as pool:
            futures = {pool.submit(llm_pair, ledger, n, trial, limit, batch, optima[n], abort): (n, trial)
                       for n, trial in jobs}
            for future in as_completed(futures):
                exc = future.exception()
                if exc is None:
                    results[futures[future]] = future.result()
                elif error is None:
                    error = exc
                    abort.set()
        meta = {"model": ledger.model, "base_url": ledger.base_url, "params": LLM_PARAMS,
                "batch": batch, "proposals_per_trial": limit // batch,
                "system_prompt": SYSTEM_PROMPT}
    if error is not None:
        raise error
    pairs = [{"order": n, "trial": trial, "sample": trial, **results[(n, trial)]} for n, trial in jobs]
    extra = {
        "valid_rulers": float(sum(p["valid_rulers"] for p in pairs)),
        "unparsed_replies": float(sum(p["unparsed_replies"] for p in pairs)),
        **ledger.summary(),
    }
    return pairs, extra, meta


# --- the run ------------------------------------------------------------------


def _artifact_path() -> Path:
    if SMOKE:
        return Path(tempfile.mkdtemp(prefix="klein-smoke-")) / f"solution_SMOKE_{TRACK}.json"
    if SEALED_DRYRUN:
        # Filed with the rehearsal's own state commit (sweeps/), so the tree the
        # sealed run needs stays clean; tables/ holds only real runs' artifacts.
        return Path("sweeps") / f"solution_DRYRUN_{TRACK}.json"
    return Path("tables") / f"solution_{EXPERIMENT_ID}.json"


def main() -> None:
    t0 = time.time()
    kind = os.environ.get("KLEIN_EVALUATION_KIND") or ("development" if SMOKE else None)
    if EXPERIMENT_ID is None or kind is None or TRACK is None:
        raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 KLEIN_TRACK=<arm> for a shape check)")
    if TRACK not in ARMS:
        raise SystemExit(f"KLEIN_TRACK={TRACK!r}: this study's arms are {ARMS}")
    if kind not in {"development", "final_test"}:
        raise RuntimeError(f"invalid KLEIN_EVALUATION_KIND={kind!r}")
    instance = json.loads(Path("data/prepared/instance.json").read_text(encoding="utf-8"))
    lane = "sealed" if kind == "final_test" else "development"
    if kind == "final_test" and SEALED_DRYRUN:
        print("sealed_dryrun: 1")
        lane = "development"
    orders = [int(n) for n in instance[f"{lane}_orders"]]
    trials = int(instance["trials"])
    limit = int(instance["budget_evaluations"])
    batch = int(instance["llm_batch"])
    lane_seed = int(instance["seed_blocks"][lane])
    optima = {int(n): int(length) for n, length in instance["optima"].items()}
    if SMOKE:
        orders, trials, limit = orders[:1], 1, SMOKE_BUDGET[TRACK]

    payload: dict[str, Any] = {
        "problem": "golomb-ruler", "arm": TRACK, "experiment": EXPERIMENT_ID, "lane": lane,
        "sealed_dryrun": SEALED_DRYRUN, "orders": orders, "trials": trials,
        "budget_evaluations": limit,
    }
    if TRACK == "search":
        pairs, extra = run_search(orders, trials, limit, lane_seed, optima)
        payload["seed_block"] = lane_seed
    else:
        pairs, extra, payload["llm"] = run_llm(orders, trials, limit, batch, optima)
    payload["pairs"] = pairs

    matched = sum(p["best_length"] == optima[p["order"]] for p in pairs)
    first_batch = sum(p.get("first_optimal_proposal") == 1 for p in pairs)

    out = _artifact_path()
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(payload, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(f"solution: {out.as_posix()}")
    print(f"artifact: {out.as_posix()}")

    lane_fingerprint = hashlib.sha256(json.dumps(
        {"lane": lane, "orders": orders, "trials": trials, "budget": limit, "seed_block": lane_seed},
        sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
    evaluate_scalar(
        float(matched), exp_id=EXPERIMENT_ID, metric_name="optima_matched", metric_goal="higher",
        extra={
            "first_batch_matches": float(first_batch),
            "pairs": float(len(pairs)),
            "evaluations": float(sum(p["evaluations"] for p in pairs)),
            "sealed_lane": 1.0 if lane == "sealed" else 0.0,
            **extra,
        },
        split_fingerprint=lane_fingerprint, t0=t0, study_dir=None if SMOKE else ".",
    )


if __name__ == "__main__":
    main()

LLM arm, development cell (E0004) and sealed cell (E0006).

search.py · executed by E0004 (development, track llm) at commit 650d11c41ac1 · sha256 b3188a3e6eee…
"""The searcher (the mutable surface): two arms that propose Golomb rulers for verify.py.

A Golomb ruler with n marks is a list of integers 0 = a1 < ... < an whose pairwise
differences are all distinct; its length is an, and shorter is better. For every
(order, trial) pair of the lane this run draws, an arm gets the same budget of
candidate evaluations — ONE candidate ruler checked by this file's private
`_is_golomb` is ONE evaluation, whatever produced it — and keeps the shortest valid
ruler it found:

  search  randomized construction + simulated annealing on the mark positions
          (KLEIN_TRACK=search)
  llm     qwen-flash proposes batches of rulers as JSON DATA (never code), each
          batch told the checker's verdicts on the previous one, every request
          through the call ledger (KLEIN_TRACK=llm)

The lane is KLEIN_EVALUATION_KIND: development -> development_orders, final_test ->
sealed_orders; the sealed rehearsal (KLEIN_SEALED_DRYRUN=1) runs the development
orders and prints `sealed_dryrun: 1`. Orders, trials, budget, batch size and seed
blocks come from data/prepared/instance.json (hashed at the DATA gate). The known
optima are read for BOOK-KEEPING ONLY — the provisional count printed below and the
index of the first optimal ruler; no search decision and no prompt uses them.

The run's number is provisional: the declared verifier (verify.py — outside this
surface, sharing no code with it, hashed at METHOD) recomputes `optima_matched` and
`first_batch_matches` from the artifact printed under `solution:`, and decides.
"""

from __future__ import annotations

import hashlib
import json
import math
import os
import random
import re
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from kleinlib.eval import evaluate_scalar

SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
SEALED_DRYRUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK")
ARMS = ("search", "llm")

# Smoke: the first development order, one trial, a tiny budget (a shape check, not evidence).
SMOKE_BUDGET = {"search": 200, "llm": 30}

# --- the search arm -----------------------------------------------------------
SA_T0 = 1.0           # starting temperature, in units of "repeated differences"
SA_COOLING = 0.98     # per INVALID candidate (a valid candidate resets the temperature to 1.0)
SA_T_MIN = 0.05
SA_PATIENCE = 150     # evaluations at one target length without a valid ruler -> restart there
P_CONFLICTED = 0.85   # move a mark that takes part in a repeated difference
P_LOCAL = 0.5         # ... by a small shift (else: anywhere free on the ruler)

# --- the llm arm --------------------------------------------------------------
LLM_PARAMS = {"temperature": 0.7, "max_tokens": 1024, "enable_thinking": False}
SYSTEM_PROMPT = (
    "You propose Golomb rulers as data. A Golomb ruler with n marks is a list of n "
    "integers that starts at 0, is strictly increasing, and has all pairwise "
    "differences distinct. Its length is its last mark, and a shorter ruler is "
    "better. Reply with JSON data only: never code, never an explanation."
)


# --- the searcher's own checker (never the verifier) -----------------------------


class Budget:
    """Candidate evaluations for one (order, trial): every `_is_golomb` call spends one."""

    def __init__(self, limit: int) -> None:
        self.limit = int(limit)
        self.spent = 0

    def exhausted(self) -> bool:
        return self.spent >= self.limit

    def spend(self) -> None:
        if self.spent >= self.limit:
            raise RuntimeError(f"evaluation budget overspent ({self.limit})")
        self.spent += 1


@dataclass(frozen=True)
class Verdict:
    valid: bool
    reason: str                    # "valid", or why the candidate is not a valid ruler
    length: int | None             # the last mark, when the candidate is a well-formed mark list
    first_repeat: int | None       # the first repeated difference, pairs scanned (i < j) by j then i
    repeats: int                   # differences that repeat an earlier one
    conflicted: tuple[int, ...]    # mark indices that take part in a repeated difference


def _is_golomb(marks: Any, n: int, budget: Budget) -> Verdict:
    """The searcher's private checker. Each call is one evaluation of the budget."""
    budget.spend()
    if marks is None:
        return Verdict(False, "missing", None, None, 0, ())
    if not isinstance(marks, list) or not all(
        isinstance(m, int) and not isinstance(m, bool) for m in marks
    ):
        return Verdict(False, "not a list of integers", None, None, 0, ())
    if len(marks) != n:
        return Verdict(False, f"has {len(marks)} marks, needs {n}", None, None, 0, ())
    if marks[0] != 0:
        return Verdict(False, "does not start at 0", None, None, 0, ())
    if any(b <= a for a, b in zip(marks, marks[1:], strict=False)):
        return Verdict(False, "not strictly increasing", None, None, 0, ())
    owner: dict[int, tuple[int, int]] = {}
    repeats, first, conflicted = 0, None, set()
    for j in range(1, n):
        for i in range(j):
            d = marks[j] - marks[i]
            earlier = owner.get(d)
            if earlier is None:
                owner[d] = (i, j)
                continue
            repeats += 1
            first = d if first is None else first
            conflicted.update((i, j, *earlier))
    if repeats:
        return Verdict(False, f"difference {first} repeats", marks[-1], first, repeats,
                       tuple(sorted(conflicted)))
    return Verdict(True, "valid", marks[-1], None, 0, ())


# --- arm 1: randomized construction + simulated annealing ------------------------


def _random_ruler(n: int, length: int, rng: random.Random) -> list[int]:
    return [0, *sorted(rng.sample(range(1, length), n - 2)), length]


def _shrink(marks: list[int], step: int, rng: random.Random) -> list[int]:
    """Cut `step` empty unit cells at random: differences on one side of a cut survive."""
    marks = list(marks)
    for _ in range(step):
        occupied = set(marks)
        cut = rng.choice([c for c in range(1, marks[-1]) if c not in occupied])
        marks = [m - 1 if m > cut else m for m in marks]
    return marks


def _move(marks: list[int], verdict: Verdict, rng: random.Random) -> list[int]:
    """Relocate one interior mark (the ends 0 and L stay): the length is unchanged."""
    n, length = len(marks), marks[-1]
    interior = [i for i in verdict.conflicted if 0 < i < n - 1]
    if interior and rng.random() < P_CONFLICTED:
        i = rng.choice(interior)
    else:
        i = rng.randrange(1, n - 1)
    occupied = set(marks)
    while True:
        if rng.random() < P_LOCAL:
            p = marks[i] + rng.choice((-3, -2, -1, 1, 2, 3))
        else:
            p = rng.randrange(1, length)
        if 0 < p < length and p not in occupied:
            break
    return sorted([*marks[:i], *marks[i + 1:], p])


def search_pair(n: int, seed: int, limit: int, optimum: int) -> dict[str, Any]:
    """One (order, trial): the shortest valid ruler found within `limit` evaluations.

    Construction: both ends fixed at 0 and n*n, n-2 interior marks at random (sparse enough that a few
    moves make it valid). Then repeatedly: aim one length shorter than the best valid
    ruler (an adaptive step, doubling while successes come fast), start from the best
    with empty cells cut out, and anneal the interior marks to remove repeated
    differences; restart from the best after SA_PATIENCE evaluations without a valid
    ruler. Stops at the budget, or at the trivial bound n(n-1)/2 (a perfect ruler).
    """
    if n < 3:
        raise ValueError("the search arm needs at least 3 marks")
    rng = random.Random(seed)
    budget = Budget(limit)
    floor = n * (n - 1) // 2
    best: list[int] | None = None
    best_at = first_optimal_at = None
    state: list[int] | None = None
    state_verdict: Verdict | None = None
    step, since_valid, since_start, restarts = 1, 0, 0, 0
    temperature = SA_T0
    while not budget.exhausted():
        if best is not None and best[-1] <= floor:
            break  # n(n-1)/2 distinct positive differences: nothing shorter exists
        if state is None:
            if best is None:
                candidate = _random_ruler(n, n * n, rng)
            else:
                candidate = _shrink(best, min(step, best[-1] - floor), rng)
        else:
            candidate = _move(state, state_verdict, rng)
        verdict = _is_golomb(candidate, n, budget)
        since_valid += 1
        if verdict.valid:
            if best is None or candidate[-1] < best[-1]:
                best, best_at = candidate, budget.spent
                if first_optimal_at is None and candidate[-1] == optimum:
                    first_optimal_at = budget.spent
            step = min(2 * step, n) if since_valid <= n else 1
            state, state_verdict = None, None
            since_valid, since_start, temperature = 0, 0, SA_T0
            continue
        if (
            state_verdict is None
            or verdict.repeats <= state_verdict.repeats
            or rng.random() < math.exp((state_verdict.repeats - verdict.repeats) / temperature)
        ):
            state, state_verdict = candidate, verdict
        temperature = max(SA_T_MIN, temperature * SA_COOLING)
        since_start += 1
        if since_start >= SA_PATIENCE:
            state, state_verdict = None, None
            step, since_start, temperature = 1, 0, SA_T0
            restarts += 1
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "best_found_at_evaluation": best_at,
        "first_optimal_evaluation": first_optimal_at,
        "restarts": restarts,
    }


def run_search(orders: list[int], trials: int, limit: int, lane_seed: int,
               optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float]]:
    pairs = []
    for n in orders:
        for trial in range(trials):
            seed = lane_seed + n * 100 + trial
            pairs.append({"order": n, "trial": trial, "seed": seed,
                          **search_pair(n, seed, limit, optima[n])})
    return pairs, {"restarts": float(sum(p["restarts"] for p in pairs))}


# --- arm 2: the LLM proposes rulers as data -------------------------------------

_INNER_LIST = re.compile(r"\[[^\[\]]*\]")


def _parse_batch(text: str, batch: int) -> tuple[list[Any], bool]:
    """Exactly `batch` entries (None = missing) and whether the reply was one JSON list.

    The outermost [...] span is read as JSON (this strips code fences and any prose
    around it). A reply cut off mid-list falls back to every complete inner list.
    Nothing is repaired: an entry that is not already a valid ruler is an invalid
    evaluation, and a missing entry still spends its evaluation.
    """
    entries: list[Any] | None = None
    start, end = text.find("["), text.rfind("]")
    if start != -1 and end > start:
        try:
            value = json.loads(text[start:end + 1])
        except ValueError:
            value = None
        if isinstance(value, list):
            if value and all(isinstance(v, int) and not isinstance(v, bool) for v in value):
                value = [value]  # one bare ruler
            entries = value
    strict = entries is not None
    if entries is None:
        entries = []
        for chunk in _INNER_LIST.findall(text):
            try:
                entries.append(json.loads(chunk))
            except ValueError:
                continue
    entries = entries[:batch]
    return entries + [None] * (batch - len(entries)), strict


def _show(entry: Any) -> str:
    if entry is None:
        return "(no ruler)"
    text = json.dumps(entry)
    return text if len(text) <= 160 else text[:157] + "..."


def _describe(verdict: Verdict) -> str:
    if verdict.valid:
        return f"valid, length {verdict.length}"
    if verdict.first_repeat is not None:
        return f"invalid, length {verdict.length}, difference {verdict.first_repeat} repeats"
    return f"invalid, {verdict.reason}"


def _messages(n: int, k: int, proposals: int, batch: int,
              previous: list[tuple[Any, Verdict]] | None,
              best_length: int | None) -> list[dict[str, str]]:
    lines = [
        f"Propose exactly {batch} candidate Golomb rulers with {n} marks each.",
        f"Every ruler must start at 0, be strictly increasing, contain exactly {n} "
        f"integers, and have all {n * (n - 1) // 2} pairwise differences distinct. "
        "Shorter is better: the length of a ruler is its last mark.",
        f"This is proposal {k} of {proposals}.",
    ]
    if previous is not None:
        lines += ["", "The verifier's verdicts on your previous batch:"]
        lines += [f"{i}. {_show(entry)}: {_describe(verdict)}"
                  for i, (entry, verdict) in enumerate(previous, start=1)]
        lines.append(f"Best valid length so far: {best_length}." if best_length is not None
                     else "No valid ruler so far.")
    lines += ["", f"Reply with a JSON list of {batch} lists of integers and nothing else."]
    return [{"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": "\n".join(lines)}]


class _Aborted(RuntimeError):
    """Another (order, trial) loop failed; this one stops before its next request."""


def llm_pair(ledger: Any, n: int, trial: int, limit: int, batch: int, optimum: int,
             abort: threading.Event) -> dict[str, Any]:
    """One (order, trial): `limit // batch` sequential proposals, each fed back the last."""
    budget = Budget(limit)
    proposals = limit // batch
    best: list[int] | None = None
    best_at = first_optimal = None
    first_batch: list[Any] | None = None
    previous: list[tuple[Any, Verdict]] | None = None
    valid = unparsed = 0
    for k in range(1, proposals + 1):
        if abort.is_set():
            raise _Aborted(f"order {n} trial {trial} stopped at proposal {k}")
        reply = ledger.chat(_messages(n, k, proposals, batch, previous,
                                      None if best is None else best[-1]),
                            sample=trial, **LLM_PARAMS)
        entries, strict = _parse_batch(reply, batch)
        unparsed += not strict
        verdicts = [_is_golomb(entry, n, budget) for entry in entries]
        if k == 1:
            first_batch = [entry if isinstance(entry, list) else None for entry in entries]
        for entry, verdict in zip(entries, verdicts, strict=True):
            if not verdict.valid:
                continue
            valid += 1
            if best is None or entry[-1] < best[-1]:
                best, best_at = list(entry), k
            if first_optimal is None and entry[-1] == optimum:
                first_optimal = k
        previous = list(zip(entries, verdicts, strict=True))
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "proposals": proposals,
        "best_found_at_proposal": best_at,
        "first_optimal_proposal": first_optimal,
        "valid_rulers": valid,
        "unparsed_replies": unparsed,
        "first_batch": first_batch,
    }


def _smoke_reply(n: int) -> str:
    """A fenced JSON batch for KLEIN_SMOKE=1: one entry per parse/verdict path, then padding."""
    sidon = [2 ** i - 1 for i in range(n)]  # 2^j - 2^i are all distinct: a valid ruler
    batch = [
        sidon,
        [2 * m for m in sidon],             # valid, longer
        [m + 1 for m in sidon],             # does not start at 0
        list(range(0, 2 * n, 2)),           # difference 2 repeats
        sidon[:-1],                         # wrong mark count
        [0, *sidon[:0:-1]],                 # not strictly increasing
        "x",                                # not a list
    ]
    return "Here are the rulers:\n```json\n" + json.dumps(batch) + "\n```"


def run_llm(orders: list[int], trials: int, limit: int, batch: int,
            optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float], dict[str, Any]]:
    from kleinlib.calls import CallLedger

    if limit % batch:
        raise SystemExit(f"budget {limit} is not a multiple of the batch {batch}")
    # The sealed rehearsal replays the development cell from the ledger and must
    # spend nothing: offline, a request the ledger cannot answer is a crash.
    overrides = {"offline": True} if SEALED_DRYRUN else {}
    jobs = [(n, trial) for n in orders for trial in range(trials)]
    abort = threading.Event()
    results: dict[tuple[int, int], dict[str, Any]] = {}
    error: BaseException | None = None
    with CallLedger.from_contract(".", smoke_response=_smoke_reply(orders[0]), **overrides) as ledger:
        # Proposals within a trial are sequential (each carries the last batch's
        # verdicts); the (order, trial) loops are independent and run side by side,
        # calls.max_workers at a time. Each loop passes its trial index as `sample`,
        # so the trials are distinct requests, not cached copies of one another.
        with ThreadPoolExecutor(max_workers=min(ledger.max_workers, len(jobs))) as pool:
            futures = {pool.submit(llm_pair, ledger, n, trial, limit, batch, optima[n], abort): (n, trial)
                       for n, trial in jobs}
            for future in as_completed(futures):
                exc = future.exception()
                if exc is None:
                    results[futures[future]] = future.result()
                elif error is None:
                    error = exc
                    abort.set()
        meta = {"model": ledger.model, "base_url": ledger.base_url, "params": LLM_PARAMS,
                "batch": batch, "proposals_per_trial": limit // batch,
                "system_prompt": SYSTEM_PROMPT}
    if error is not None:
        raise error
    pairs = [{"order": n, "trial": trial, "sample": trial, **results[(n, trial)]} for n, trial in jobs]
    extra = {
        "valid_rulers": float(sum(p["valid_rulers"] for p in pairs)),
        "unparsed_replies": float(sum(p["unparsed_replies"] for p in pairs)),
        **ledger.summary(),
    }
    return pairs, extra, meta


# --- the run ------------------------------------------------------------------


def _artifact_path() -> Path:
    if SMOKE:
        return Path(tempfile.mkdtemp(prefix="klein-smoke-")) / f"solution_SMOKE_{TRACK}.json"
    if SEALED_DRYRUN:
        # Filed with the rehearsal's own state commit (sweeps/), so the tree the
        # sealed run needs stays clean; tables/ holds only real runs' artifacts.
        return Path("sweeps") / f"solution_DRYRUN_{TRACK}.json"
    return Path("tables") / f"solution_{EXPERIMENT_ID}.json"


def main() -> None:
    t0 = time.time()
    kind = os.environ.get("KLEIN_EVALUATION_KIND") or ("development" if SMOKE else None)
    if EXPERIMENT_ID is None or kind is None or TRACK is None:
        raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 KLEIN_TRACK=<arm> for a shape check)")
    if TRACK not in ARMS:
        raise SystemExit(f"KLEIN_TRACK={TRACK!r}: this study's arms are {ARMS}")
    if kind not in {"development", "final_test"}:
        raise RuntimeError(f"invalid KLEIN_EVALUATION_KIND={kind!r}")
    instance = json.loads(Path("data/prepared/instance.json").read_text(encoding="utf-8"))
    lane = "sealed" if kind == "final_test" else "development"
    if kind == "final_test" and SEALED_DRYRUN:
        print("sealed_dryrun: 1")
        lane = "development"
    orders = [int(n) for n in instance[f"{lane}_orders"]]
    trials = int(instance["trials"])
    limit = int(instance["budget_evaluations"])
    batch = int(instance["llm_batch"])
    lane_seed = int(instance["seed_blocks"][lane])
    optima = {int(n): int(length) for n, length in instance["optima"].items()}
    if SMOKE:
        orders, trials, limit = orders[:1], 1, SMOKE_BUDGET[TRACK]

    payload: dict[str, Any] = {
        "problem": "golomb-ruler", "arm": TRACK, "experiment": EXPERIMENT_ID, "lane": lane,
        "sealed_dryrun": SEALED_DRYRUN, "orders": orders, "trials": trials,
        "budget_evaluations": limit,
    }
    if TRACK == "search":
        pairs, extra = run_search(orders, trials, limit, lane_seed, optima)
        payload["seed_block"] = lane_seed
    else:
        pairs, extra, payload["llm"] = run_llm(orders, trials, limit, batch, optima)
    payload["pairs"] = pairs

    matched = sum(p["best_length"] == optima[p["order"]] for p in pairs)
    first_batch = sum(p.get("first_optimal_proposal") == 1 for p in pairs)

    out = _artifact_path()
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(payload, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(f"solution: {out.as_posix()}")
    print(f"artifact: {out.as_posix()}")

    lane_fingerprint = hashlib.sha256(json.dumps(
        {"lane": lane, "orders": orders, "trials": trials, "budget": limit, "seed_block": lane_seed},
        sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
    evaluate_scalar(
        float(matched), exp_id=EXPERIMENT_ID, metric_name="optima_matched", metric_goal="higher",
        extra={
            "first_batch_matches": float(first_batch),
            "pairs": float(len(pairs)),
            "evaluations": float(sum(p["evaluations"] for p in pairs)),
            "sealed_lane": 1.0 if lane == "sealed" else 0.0,
            **extra,
        },
        split_fingerprint=lane_fingerprint, t0=t0, study_dir=None if SMOKE else ".",
    )


if __name__ == "__main__":
    main()
search.py · executed by E0006 (final_test, track llm) at commit 757976c00779 · sha256 b3188a3e6eee…
"""The searcher (the mutable surface): two arms that propose Golomb rulers for verify.py.

A Golomb ruler with n marks is a list of integers 0 = a1 < ... < an whose pairwise
differences are all distinct; its length is an, and shorter is better. For every
(order, trial) pair of the lane this run draws, an arm gets the same budget of
candidate evaluations — ONE candidate ruler checked by this file's private
`_is_golomb` is ONE evaluation, whatever produced it — and keeps the shortest valid
ruler it found:

  search  randomized construction + simulated annealing on the mark positions
          (KLEIN_TRACK=search)
  llm     qwen-flash proposes batches of rulers as JSON DATA (never code), each
          batch told the checker's verdicts on the previous one, every request
          through the call ledger (KLEIN_TRACK=llm)

The lane is KLEIN_EVALUATION_KIND: development -> development_orders, final_test ->
sealed_orders; the sealed rehearsal (KLEIN_SEALED_DRYRUN=1) runs the development
orders and prints `sealed_dryrun: 1`. Orders, trials, budget, batch size and seed
blocks come from data/prepared/instance.json (hashed at the DATA gate). The known
optima are read for BOOK-KEEPING ONLY — the provisional count printed below and the
index of the first optimal ruler; no search decision and no prompt uses them.

The run's number is provisional: the declared verifier (verify.py — outside this
surface, sharing no code with it, hashed at METHOD) recomputes `optima_matched` and
`first_batch_matches` from the artifact printed under `solution:`, and decides.
"""

from __future__ import annotations

import hashlib
import json
import math
import os
import random
import re
import tempfile
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from kleinlib.eval import evaluate_scalar

SMOKE = os.environ.get("KLEIN_SMOKE") == "1"
SEALED_DRYRUN = os.environ.get("KLEIN_SEALED_DRYRUN") == "1"
EXPERIMENT_ID = os.environ.get("KLEIN_EXPERIMENT_ID") or ("SMOKE" if SMOKE else None)
TRACK = os.environ.get("KLEIN_TRACK")
ARMS = ("search", "llm")

# Smoke: the first development order, one trial, a tiny budget (a shape check, not evidence).
SMOKE_BUDGET = {"search": 200, "llm": 30}

# --- the search arm -----------------------------------------------------------
SA_T0 = 1.0           # starting temperature, in units of "repeated differences"
SA_COOLING = 0.98     # per INVALID candidate (a valid candidate resets the temperature to 1.0)
SA_T_MIN = 0.05
SA_PATIENCE = 150     # evaluations at one target length without a valid ruler -> restart there
P_CONFLICTED = 0.85   # move a mark that takes part in a repeated difference
P_LOCAL = 0.5         # ... by a small shift (else: anywhere free on the ruler)

# --- the llm arm --------------------------------------------------------------
LLM_PARAMS = {"temperature": 0.7, "max_tokens": 1024, "enable_thinking": False}
SYSTEM_PROMPT = (
    "You propose Golomb rulers as data. A Golomb ruler with n marks is a list of n "
    "integers that starts at 0, is strictly increasing, and has all pairwise "
    "differences distinct. Its length is its last mark, and a shorter ruler is "
    "better. Reply with JSON data only: never code, never an explanation."
)


# --- the searcher's own checker (never the verifier) -----------------------------


class Budget:
    """Candidate evaluations for one (order, trial): every `_is_golomb` call spends one."""

    def __init__(self, limit: int) -> None:
        self.limit = int(limit)
        self.spent = 0

    def exhausted(self) -> bool:
        return self.spent >= self.limit

    def spend(self) -> None:
        if self.spent >= self.limit:
            raise RuntimeError(f"evaluation budget overspent ({self.limit})")
        self.spent += 1


@dataclass(frozen=True)
class Verdict:
    valid: bool
    reason: str                    # "valid", or why the candidate is not a valid ruler
    length: int | None             # the last mark, when the candidate is a well-formed mark list
    first_repeat: int | None       # the first repeated difference, pairs scanned (i < j) by j then i
    repeats: int                   # differences that repeat an earlier one
    conflicted: tuple[int, ...]    # mark indices that take part in a repeated difference


def _is_golomb(marks: Any, n: int, budget: Budget) -> Verdict:
    """The searcher's private checker. Each call is one evaluation of the budget."""
    budget.spend()
    if marks is None:
        return Verdict(False, "missing", None, None, 0, ())
    if not isinstance(marks, list) or not all(
        isinstance(m, int) and not isinstance(m, bool) for m in marks
    ):
        return Verdict(False, "not a list of integers", None, None, 0, ())
    if len(marks) != n:
        return Verdict(False, f"has {len(marks)} marks, needs {n}", None, None, 0, ())
    if marks[0] != 0:
        return Verdict(False, "does not start at 0", None, None, 0, ())
    if any(b <= a for a, b in zip(marks, marks[1:], strict=False)):
        return Verdict(False, "not strictly increasing", None, None, 0, ())
    owner: dict[int, tuple[int, int]] = {}
    repeats, first, conflicted = 0, None, set()
    for j in range(1, n):
        for i in range(j):
            d = marks[j] - marks[i]
            earlier = owner.get(d)
            if earlier is None:
                owner[d] = (i, j)
                continue
            repeats += 1
            first = d if first is None else first
            conflicted.update((i, j, *earlier))
    if repeats:
        return Verdict(False, f"difference {first} repeats", marks[-1], first, repeats,
                       tuple(sorted(conflicted)))
    return Verdict(True, "valid", marks[-1], None, 0, ())


# --- arm 1: randomized construction + simulated annealing ------------------------


def _random_ruler(n: int, length: int, rng: random.Random) -> list[int]:
    return [0, *sorted(rng.sample(range(1, length), n - 2)), length]


def _shrink(marks: list[int], step: int, rng: random.Random) -> list[int]:
    """Cut `step` empty unit cells at random: differences on one side of a cut survive."""
    marks = list(marks)
    for _ in range(step):
        occupied = set(marks)
        cut = rng.choice([c for c in range(1, marks[-1]) if c not in occupied])
        marks = [m - 1 if m > cut else m for m in marks]
    return marks


def _move(marks: list[int], verdict: Verdict, rng: random.Random) -> list[int]:
    """Relocate one interior mark (the ends 0 and L stay): the length is unchanged."""
    n, length = len(marks), marks[-1]
    interior = [i for i in verdict.conflicted if 0 < i < n - 1]
    if interior and rng.random() < P_CONFLICTED:
        i = rng.choice(interior)
    else:
        i = rng.randrange(1, n - 1)
    occupied = set(marks)
    while True:
        if rng.random() < P_LOCAL:
            p = marks[i] + rng.choice((-3, -2, -1, 1, 2, 3))
        else:
            p = rng.randrange(1, length)
        if 0 < p < length and p not in occupied:
            break
    return sorted([*marks[:i], *marks[i + 1:], p])


def search_pair(n: int, seed: int, limit: int, optimum: int) -> dict[str, Any]:
    """One (order, trial): the shortest valid ruler found within `limit` evaluations.

    Construction: both ends fixed at 0 and n*n, n-2 interior marks at random (sparse enough that a few
    moves make it valid). Then repeatedly: aim one length shorter than the best valid
    ruler (an adaptive step, doubling while successes come fast), start from the best
    with empty cells cut out, and anneal the interior marks to remove repeated
    differences; restart from the best after SA_PATIENCE evaluations without a valid
    ruler. Stops at the budget, or at the trivial bound n(n-1)/2 (a perfect ruler).
    """
    if n < 3:
        raise ValueError("the search arm needs at least 3 marks")
    rng = random.Random(seed)
    budget = Budget(limit)
    floor = n * (n - 1) // 2
    best: list[int] | None = None
    best_at = first_optimal_at = None
    state: list[int] | None = None
    state_verdict: Verdict | None = None
    step, since_valid, since_start, restarts = 1, 0, 0, 0
    temperature = SA_T0
    while not budget.exhausted():
        if best is not None and best[-1] <= floor:
            break  # n(n-1)/2 distinct positive differences: nothing shorter exists
        if state is None:
            if best is None:
                candidate = _random_ruler(n, n * n, rng)
            else:
                candidate = _shrink(best, min(step, best[-1] - floor), rng)
        else:
            candidate = _move(state, state_verdict, rng)
        verdict = _is_golomb(candidate, n, budget)
        since_valid += 1
        if verdict.valid:
            if best is None or candidate[-1] < best[-1]:
                best, best_at = candidate, budget.spent
                if first_optimal_at is None and candidate[-1] == optimum:
                    first_optimal_at = budget.spent
            step = min(2 * step, n) if since_valid <= n else 1
            state, state_verdict = None, None
            since_valid, since_start, temperature = 0, 0, SA_T0
            continue
        if (
            state_verdict is None
            or verdict.repeats <= state_verdict.repeats
            or rng.random() < math.exp((state_verdict.repeats - verdict.repeats) / temperature)
        ):
            state, state_verdict = candidate, verdict
        temperature = max(SA_T_MIN, temperature * SA_COOLING)
        since_start += 1
        if since_start >= SA_PATIENCE:
            state, state_verdict = None, None
            step, since_start, temperature = 1, 0, SA_T0
            restarts += 1
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "best_found_at_evaluation": best_at,
        "first_optimal_evaluation": first_optimal_at,
        "restarts": restarts,
    }


def run_search(orders: list[int], trials: int, limit: int, lane_seed: int,
               optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float]]:
    pairs = []
    for n in orders:
        for trial in range(trials):
            seed = lane_seed + n * 100 + trial
            pairs.append({"order": n, "trial": trial, "seed": seed,
                          **search_pair(n, seed, limit, optima[n])})
    return pairs, {"restarts": float(sum(p["restarts"] for p in pairs))}


# --- arm 2: the LLM proposes rulers as data -------------------------------------

_INNER_LIST = re.compile(r"\[[^\[\]]*\]")


def _parse_batch(text: str, batch: int) -> tuple[list[Any], bool]:
    """Exactly `batch` entries (None = missing) and whether the reply was one JSON list.

    The outermost [...] span is read as JSON (this strips code fences and any prose
    around it). A reply cut off mid-list falls back to every complete inner list.
    Nothing is repaired: an entry that is not already a valid ruler is an invalid
    evaluation, and a missing entry still spends its evaluation.
    """
    entries: list[Any] | None = None
    start, end = text.find("["), text.rfind("]")
    if start != -1 and end > start:
        try:
            value = json.loads(text[start:end + 1])
        except ValueError:
            value = None
        if isinstance(value, list):
            if value and all(isinstance(v, int) and not isinstance(v, bool) for v in value):
                value = [value]  # one bare ruler
            entries = value
    strict = entries is not None
    if entries is None:
        entries = []
        for chunk in _INNER_LIST.findall(text):
            try:
                entries.append(json.loads(chunk))
            except ValueError:
                continue
    entries = entries[:batch]
    return entries + [None] * (batch - len(entries)), strict


def _show(entry: Any) -> str:
    if entry is None:
        return "(no ruler)"
    text = json.dumps(entry)
    return text if len(text) <= 160 else text[:157] + "..."


def _describe(verdict: Verdict) -> str:
    if verdict.valid:
        return f"valid, length {verdict.length}"
    if verdict.first_repeat is not None:
        return f"invalid, length {verdict.length}, difference {verdict.first_repeat} repeats"
    return f"invalid, {verdict.reason}"


def _messages(n: int, k: int, proposals: int, batch: int,
              previous: list[tuple[Any, Verdict]] | None,
              best_length: int | None) -> list[dict[str, str]]:
    lines = [
        f"Propose exactly {batch} candidate Golomb rulers with {n} marks each.",
        f"Every ruler must start at 0, be strictly increasing, contain exactly {n} "
        f"integers, and have all {n * (n - 1) // 2} pairwise differences distinct. "
        "Shorter is better: the length of a ruler is its last mark.",
        f"This is proposal {k} of {proposals}.",
    ]
    if previous is not None:
        lines += ["", "The verifier's verdicts on your previous batch:"]
        lines += [f"{i}. {_show(entry)}: {_describe(verdict)}"
                  for i, (entry, verdict) in enumerate(previous, start=1)]
        lines.append(f"Best valid length so far: {best_length}." if best_length is not None
                     else "No valid ruler so far.")
    lines += ["", f"Reply with a JSON list of {batch} lists of integers and nothing else."]
    return [{"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": "\n".join(lines)}]


class _Aborted(RuntimeError):
    """Another (order, trial) loop failed; this one stops before its next request."""


def llm_pair(ledger: Any, n: int, trial: int, limit: int, batch: int, optimum: int,
             abort: threading.Event) -> dict[str, Any]:
    """One (order, trial): `limit // batch` sequential proposals, each fed back the last."""
    budget = Budget(limit)
    proposals = limit // batch
    best: list[int] | None = None
    best_at = first_optimal = None
    first_batch: list[Any] | None = None
    previous: list[tuple[Any, Verdict]] | None = None
    valid = unparsed = 0
    for k in range(1, proposals + 1):
        if abort.is_set():
            raise _Aborted(f"order {n} trial {trial} stopped at proposal {k}")
        reply = ledger.chat(_messages(n, k, proposals, batch, previous,
                                      None if best is None else best[-1]),
                            sample=trial, **LLM_PARAMS)
        entries, strict = _parse_batch(reply, batch)
        unparsed += not strict
        verdicts = [_is_golomb(entry, n, budget) for entry in entries]
        if k == 1:
            first_batch = [entry if isinstance(entry, list) else None for entry in entries]
        for entry, verdict in zip(entries, verdicts, strict=True):
            if not verdict.valid:
                continue
            valid += 1
            if best is None or entry[-1] < best[-1]:
                best, best_at = list(entry), k
            if first_optimal is None and entry[-1] == optimum:
                first_optimal = k
        previous = list(zip(entries, verdicts, strict=True))
    return {
        "best": best,
        "best_length": None if best is None else best[-1],
        "evaluations": budget.spent,
        "proposals": proposals,
        "best_found_at_proposal": best_at,
        "first_optimal_proposal": first_optimal,
        "valid_rulers": valid,
        "unparsed_replies": unparsed,
        "first_batch": first_batch,
    }


def _smoke_reply(n: int) -> str:
    """A fenced JSON batch for KLEIN_SMOKE=1: one entry per parse/verdict path, then padding."""
    sidon = [2 ** i - 1 for i in range(n)]  # 2^j - 2^i are all distinct: a valid ruler
    batch = [
        sidon,
        [2 * m for m in sidon],             # valid, longer
        [m + 1 for m in sidon],             # does not start at 0
        list(range(0, 2 * n, 2)),           # difference 2 repeats
        sidon[:-1],                         # wrong mark count
        [0, *sidon[:0:-1]],                 # not strictly increasing
        "x",                                # not a list
    ]
    return "Here are the rulers:\n```json\n" + json.dumps(batch) + "\n```"


def run_llm(orders: list[int], trials: int, limit: int, batch: int,
            optima: dict[int, int]) -> tuple[list[dict[str, Any]], dict[str, float], dict[str, Any]]:
    from kleinlib.calls import CallLedger

    if limit % batch:
        raise SystemExit(f"budget {limit} is not a multiple of the batch {batch}")
    # The sealed rehearsal replays the development cell from the ledger and must
    # spend nothing: offline, a request the ledger cannot answer is a crash.
    overrides = {"offline": True} if SEALED_DRYRUN else {}
    jobs = [(n, trial) for n in orders for trial in range(trials)]
    abort = threading.Event()
    results: dict[tuple[int, int], dict[str, Any]] = {}
    error: BaseException | None = None
    with CallLedger.from_contract(".", smoke_response=_smoke_reply(orders[0]), **overrides) as ledger:
        # Proposals within a trial are sequential (each carries the last batch's
        # verdicts); the (order, trial) loops are independent and run side by side,
        # calls.max_workers at a time. Each loop passes its trial index as `sample`,
        # so the trials are distinct requests, not cached copies of one another.
        with ThreadPoolExecutor(max_workers=min(ledger.max_workers, len(jobs))) as pool:
            futures = {pool.submit(llm_pair, ledger, n, trial, limit, batch, optima[n], abort): (n, trial)
                       for n, trial in jobs}
            for future in as_completed(futures):
                exc = future.exception()
                if exc is None:
                    results[futures[future]] = future.result()
                elif error is None:
                    error = exc
                    abort.set()
        meta = {"model": ledger.model, "base_url": ledger.base_url, "params": LLM_PARAMS,
                "batch": batch, "proposals_per_trial": limit // batch,
                "system_prompt": SYSTEM_PROMPT}
    if error is not None:
        raise error
    pairs = [{"order": n, "trial": trial, "sample": trial, **results[(n, trial)]} for n, trial in jobs]
    extra = {
        "valid_rulers": float(sum(p["valid_rulers"] for p in pairs)),
        "unparsed_replies": float(sum(p["unparsed_replies"] for p in pairs)),
        **ledger.summary(),
    }
    return pairs, extra, meta


# --- the run ------------------------------------------------------------------


def _artifact_path() -> Path:
    if SMOKE:
        return Path(tempfile.mkdtemp(prefix="klein-smoke-")) / f"solution_SMOKE_{TRACK}.json"
    if SEALED_DRYRUN:
        # Filed with the rehearsal's own state commit (sweeps/), so the tree the
        # sealed run needs stays clean; tables/ holds only real runs' artifacts.
        return Path("sweeps") / f"solution_DRYRUN_{TRACK}.json"
    return Path("tables") / f"solution_{EXPERIMENT_ID}.json"


def main() -> None:
    t0 = time.time()
    kind = os.environ.get("KLEIN_EVALUATION_KIND") or ("development" if SMOKE else None)
    if EXPERIMENT_ID is None or kind is None or TRACK is None:
        raise SystemExit("run through `klein run-one` (or KLEIN_SMOKE=1 KLEIN_TRACK=<arm> for a shape check)")
    if TRACK not in ARMS:
        raise SystemExit(f"KLEIN_TRACK={TRACK!r}: this study's arms are {ARMS}")
    if kind not in {"development", "final_test"}:
        raise RuntimeError(f"invalid KLEIN_EVALUATION_KIND={kind!r}")
    instance = json.loads(Path("data/prepared/instance.json").read_text(encoding="utf-8"))
    lane = "sealed" if kind == "final_test" else "development"
    if kind == "final_test" and SEALED_DRYRUN:
        print("sealed_dryrun: 1")
        lane = "development"
    orders = [int(n) for n in instance[f"{lane}_orders"]]
    trials = int(instance["trials"])
    limit = int(instance["budget_evaluations"])
    batch = int(instance["llm_batch"])
    lane_seed = int(instance["seed_blocks"][lane])
    optima = {int(n): int(length) for n, length in instance["optima"].items()}
    if SMOKE:
        orders, trials, limit = orders[:1], 1, SMOKE_BUDGET[TRACK]

    payload: dict[str, Any] = {
        "problem": "golomb-ruler", "arm": TRACK, "experiment": EXPERIMENT_ID, "lane": lane,
        "sealed_dryrun": SEALED_DRYRUN, "orders": orders, "trials": trials,
        "budget_evaluations": limit,
    }
    if TRACK == "search":
        pairs, extra = run_search(orders, trials, limit, lane_seed, optima)
        payload["seed_block"] = lane_seed
    else:
        pairs, extra, payload["llm"] = run_llm(orders, trials, limit, batch, optima)
    payload["pairs"] = pairs

    matched = sum(p["best_length"] == optima[p["order"]] for p in pairs)
    first_batch = sum(p.get("first_optimal_proposal") == 1 for p in pairs)

    out = _artifact_path()
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(payload, indent=1, sort_keys=True) + "\n", encoding="utf-8")
    print(f"solution: {out.as_posix()}")
    print(f"artifact: {out.as_posix()}")

    lane_fingerprint = hashlib.sha256(json.dumps(
        {"lane": lane, "orders": orders, "trials": trials, "budget": limit, "seed_block": lane_seed},
        sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
    evaluate_scalar(
        float(matched), exp_id=EXPERIMENT_ID, metric_name="optima_matched", metric_goal="higher",
        extra={
            "first_batch_matches": float(first_batch),
            "pairs": float(len(pairs)),
            "evaluations": float(sum(p["evaluations"] for p in pairs)),
            "sealed_lane": 1.0 if lane == "sealed" else 0.0,
            **extra,
        },
        split_fingerprint=lane_fingerprint, t0=t0, study_dir=None if SMOKE else ".",
    )


if __name__ == "__main__":
    main()

Annotated walkthrough

1. One evaluation is one call of the private checker

The matched budget is only as real as its counter. Every candidate, whatever produced it, goes through _is_golomb, which spends one evaluation before it looks at the input, and a 2001st call raises. A missing entry still spends one, so malformed LLM output is not free.

def _is_golomb(marks: Any, n: int, budget: Budget) -> Verdict:
    """The searcher's private checker. Each call is one evaluation of the budget."""
    budget.spend()
    if marks is None:
        return Verdict(False, "missing", None, None, 0, ())

The counter lives in the mutable file, so the verifier cannot audit it; it only enforces that each pair spent exactly the budget. The independent record of the LLM arm’s spend is the call ledger.

2. The annealer: aim one shorter, repair, accept by repeated differences

The classical arm never searches in the space of lengths blindly. It aims one length below its best valid ruler, cuts empty cells out of the best ruler to get there, and then anneals interior marks to drive the number of repeated differences to zero. The acceptance rule is the Metropolis one (ref:kirkpatrick1983), with the energy being the count of repeated differences:

        if (
            state_verdict is None
            or verdict.repeats <= state_verdict.repeats
            or rng.random() < math.exp((state_verdict.repeats - verdict.repeats) / temperature)
        ):
            state, state_verdict = candidate, verdict
        temperature = max(SA_T_MIN, temperature * SA_COOLING)

The verdict returned by the checker carries the conflicted mark indices, and the move operator biases toward moving a mark that takes part in a repeated difference. That is the whole algorithm. It is deliberately simple, and the study’s zero for it is a statement about this annealer at 2000 evaluations. At the method-gate toy orders the same code reached the tabulated length in most trials, which is why its zero at orders 8 to 13 reads as hardness growth, not a bug.

3. The LLM arm: objects as data, never code, never repaired

The model never writes a program and the searcher never executes a model string. The prompt asks for JSON data only, the reply is parsed by a deliberately strict rule, and anything not already a valid ruler is simply an invalid evaluation:

def _parse_batch(text: str, batch: int) -> tuple[list[Any], bool]:
    """Exactly `batch` entries (None = missing) and whether the reply was one JSON list.

    The outermost [...] span is read as JSON (this strips code fences and any prose
    around it). A reply cut off mid-list falls back to every complete inner list.
    Nothing is repaired: an entry that is not already a valid ruler is an invalid
    evaluation, and a missing entry still spends its evaluation.
    """

This rule is why a fifth to three in ten of replies counted as unparsed (section 5), and why the findings recount the sealed lane from the ledger with an independent checker that reads every bracketed list generously. The strict and generous readings agree on every development best length and on every sealed zero, so the headline counts do not depend on the extraction rule.

The feedback loop is the second design choice. Each request carries the checker’s verdicts on the previous batch and the best valid length so far, and nothing else: no optimum, no table, no mention of OEIS, no lane name. One template serves both lanes, so what the model is shown does not depend on the lane.

    if previous is not None:
        lines += ["", "The verifier's verdicts on your previous batch:"]
        lines += [f"{i}. {_show(entry)}: {_describe(verdict)}"
                  for i, (entry, verdict) in enumerate(previous, start=1)]
        lines.append(f"Best valid length so far: {best_length}." if best_length is not None
                     else "No valid ruler so far.")

The tabulated optima are loaded by search.py for book-keeping only (the provisional count and the index of the first match). They enter no stopping rule, move, message or request. The DATA gate read every use to confirm it.

4. The one number the notary trusts is the verifier’s

main() prints a provisional optima_matched and the artifact path under solution:. The notary then runs the declared verifier on that artifact and decides on its number. In every measured run the searcher’s report equals the verifier’s. Keep that pattern: print a provisional number for the human, and let a separate script that shares no code with the searcher decide.

The verifier, as declared

verify.py is the declared verifier of both tracks. It is not in entrypoint.mutable (the checker is never the searcher), it imports nothing from search.py, and it was hashed at the METHOD gate with sha256 63a60221be1a0b66c36095c804d08799df889156c7299c1129df16f2c0bc903c, the value the data card records and the file at build matches. It is shown bare, as the current file, because a file outside the mutable surface has only one version.

verify.py · current file at build (outside the mutable surface) · sha256 63a60221be1a…
"""The declared verifier — the checker, never the searcher.

`klein run-one` runs this after search.py exits, with KLEIN_ARTIFACT pointing at the
artifact the run printed under `solution:`; the run is decided on the number THIS
script prints. It is outside `entrypoint.mutable`, hashed at the METHOD gate, and
shares no code with search.py: nothing is imported from it, and the check below is
written from the definition, not from the searcher's private checker.

It is the dumbest correct thing. Its oracle — the lanes' orders, trials, the
budget, the batch size and the OEIS optima — is PINNED below (ORACLE) and
instance.json must agree with it field by field; the lane it scores is the one the
notary judged the run on (KLEIN_EVALUATION_KIND), never the one the artifact
declares; and the artifact must name the run being verified (KLEIN_EXPERIMENT_ID).
For every (order, trial) pair of that lane the stored best ruler is re-checked from scratch with exact
integer arithmetic — exactly n integer marks, starting at 0, strictly increasing,
and all n(n-1)/2 pairwise differences distinct as a set — and it prints

  primary_metric       optima_matched: pairs whose VERIFIED best length equals the
                       optimum of OEIS A003022 for that order (pinned in ORACLE)
  first_batch_matches  llm arm: pairs whose stored FIRST proposal batch holds a valid
                       optimal ruler (re-checked here); 0 for the search arm
  invalid_best         pairs with no verified best ruler (none stored, or the stored
                       one fails the check while claiming no length); never matched
  pairs                pairs checked;  sealed_lane: 1 when the artifact is the sealed lane

Rejects (exit 2): an instance.json that disagrees with ORACLE; a missing or unknown
KLEIN_EVALUATION_KIND; an artifact whose lane is not the run's partition or whose
experiment id is not the run's; a malformed artifact (not JSON, wrong problem, an
arm other than the run's track, orders that are not the lane's, a missing or
repeated (order, trial) pair, a pair that did not spend exactly the budget — both
arms always spend all of it — an llm first batch that is not
exactly llm_batch entries); a claimed `best_length` that differs from the verified
one (including a length claimed for a ruler that fails the check); a first-batch
ruler that is valid and shorter than the stored best (the searcher lost its best);
and a verified ruler shorter than the tabulated optimum (the table or this checker
is wrong, and nothing is counted until that is resolved).
"""

from __future__ import annotations

import json
import os
import sys
import time
from pathlib import Path

from kleinlib.eval import evaluate_scalar

INSTANCE = Path(__file__).resolve().parent / "data" / "prepared" / "instance.json"

#: The oracle, PINNED in this file (hashed at the METHOD gate), never read from a
#: file the searcher could rewrite: instance.json is gitignored and sits where the
#: mutable search.py has just run with write access. instance.json must agree with
#: these values exactly or nothing is scored (found at the DATA gate's review).
#: Optima: OEIS A003022 a(8..13), revision #130 (Oct 28 2026), checked 2026-11-03.
ORACLE = {
    "development_orders": [8, 9, 10, 11],
    "sealed_orders": [12, 13],
    "trials": 3,
    "budget_evaluations": 2000,
    "llm_batch": 10,
    "optima": {"8": 34, "9": 44, "10": 55, "11": 72, "12": 85, "13": 106},
}

#: Which lane a run may be scored on is decided by the partition the notary judged
#: it on (KLEIN_EVALUATION_KIND, set by `klein run-one` and `klein replicate`), never
#: by the lane the artifact declares for itself.
LANE_FOR_KIND = {"development": "development", "final_test": "sealed"}


def pinned_instance(instance: dict) -> dict:
    """The oracle, after checking instance.json agrees with it field by field."""
    for key, value in ORACLE.items():
        found = instance.get(key)
        if key == "optima":
            found = {order: (instance.get("optima") or {}).get(order) for order in value}
        if found != value:
            raise Rejected(f"instance.json {key} = {found!r} disagrees with the verifier's pinned {value!r}")
    return dict(ORACLE)


def expected_lane() -> str:
    kind = os.environ.get("KLEIN_EVALUATION_KIND")
    if kind not in LANE_FOR_KIND:
        raise Rejected(
            f"KLEIN_EVALUATION_KIND={kind!r}: the verifier must be told the partition the run was "
            "judged on (run it through `klein run-one` or `klein replicate`)"
        )
    return LANE_FOR_KIND[kind]


class Rejected(Exception):
    """The artifact cannot be scored as it stands."""


def is_int(value: object) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)


def golomb_length(marks: object, n: int) -> int | None:
    """The length of `marks` if it is a valid n-mark Golomb ruler, else None."""
    if not isinstance(marks, list) or len(marks) != n:
        return None
    for mark in marks:
        if not is_int(mark):
            return None
    if marks[0] != 0:
        return None
    for i in range(1, n):
        if marks[i] <= marks[i - 1]:
            return None
    differences = []
    for i in range(n):
        for j in range(i + 1, n):
            differences.append(marks[j] - marks[i])
    if len(set(differences)) != len(differences):
        return None
    return marks[-1]


def check(payload: object, instance: dict, track: str | None) -> tuple[int, dict[str, float]]:
    if not isinstance(payload, dict):
        raise Rejected("the artifact is not a JSON object")
    if payload.get("problem") != "golomb-ruler":
        raise Rejected(f"the artifact declares problem {payload.get('problem')!r}")
    arm = payload.get("arm")
    if arm not in ("search", "llm"):
        raise Rejected(f"unknown arm {arm!r}")
    if track and track != arm:
        raise Rejected(f"the artifact is from arm {arm!r} but the run's track is {track!r}")
    run = os.environ.get("KLEIN_EXPERIMENT_ID")
    if run and payload.get("experiment") != run:
        raise Rejected(f"the artifact names experiment {payload.get('experiment')!r}, not the run {run!r}")
    lane = payload.get("lane")
    if lane not in ("development", "sealed"):
        raise Rejected(f"unknown lane {lane!r}")
    if lane != expected_lane():
        raise Rejected(
            f"the artifact declares the {lane} lane but the run was judged on the "
            f"{expected_lane()} partition (KLEIN_EVALUATION_KIND)"
        )
    orders = instance[f"{lane}_orders"]
    if payload.get("orders") != orders:
        raise Rejected(f"orders {payload.get('orders')!r} are not the {lane} orders {orders}")
    trials = instance["trials"]
    budget = instance["budget_evaluations"]
    batch = instance["llm_batch"]
    optima = instance["optima"]
    pairs = payload.get("pairs")
    if not isinstance(pairs, list):
        raise Rejected("the artifact has no `pairs` list")

    expected = {(order, trial) for order in orders for trial in range(trials)}
    seen = set()
    matched = first_batch_matches = invalid_best = 0
    for index, pair in enumerate(pairs):
        if not isinstance(pair, dict):
            raise Rejected(f"pair {index} is not an object")
        order, trial = pair.get("order"), pair.get("trial")
        if not (is_int(order) and is_int(trial)) or (order, trial) not in expected:
            raise Rejected(f"pair {index}: (order, trial) = ({order!r}, {trial!r}) is not in the lane")
        if (order, trial) in seen:
            raise Rejected(f"pair ({order}, {trial}) appears twice")
        seen.add((order, trial))
        evaluations = pair.get("evaluations")
        if not is_int(evaluations) or evaluations != budget:
            raise Rejected(
                f"pair ({order}, {trial}): evaluations {evaluations!r} — both arms spend exactly "
                f"the budget of {budget} candidate evaluations per pair"
            )
        optimum = optima[str(order)]

        claimed = pair.get("best_length")
        if claimed is not None and not is_int(claimed):
            raise Rejected(f"pair ({order}, {trial}): best_length {claimed!r} is not an integer")
        best = pair.get("best")
        length = None if best is None else golomb_length(best, order)
        if claimed != length:
            why = ""
            if length is None:
                why = " (no ruler is stored)" if best is None else " (the stored ruler fails the check)"
            raise Rejected(
                f"pair ({order}, {trial}): claims length {claimed!r} but the verified length "
                f"is {length!r}{why}"
            )
        if length is not None and length < optimum:
            raise Rejected(
                f"pair ({order}, {trial}): verified length {length} is below the tabulated "
                f"optimum {optimum}: the table or this checker is wrong"
            )
        if length is None:
            invalid_best += 1
        elif length == optimum:
            matched += 1

        if arm == "llm":
            entries = pair.get("first_batch")
            if not isinstance(entries, list) or len(entries) != batch:
                raise Rejected(f"pair ({order}, {trial}): first_batch must hold exactly {batch} entries")
            lengths = [golomb_length(entry, order) for entry in entries]
            valid = [x for x in lengths if x is not None]
            if valid and (length is None or min(valid) < length):
                raise Rejected(
                    f"pair ({order}, {trial}): the first batch holds a valid ruler of length "
                    f"{min(valid)}, shorter than the stored best {length!r}"
                )
            if optimum in valid:
                first_batch_matches += 1

    if seen != expected:
        raise Rejected(f"missing pairs: {sorted(expected - seen)}")
    return matched, {
        "first_batch_matches": first_batch_matches,
        "pairs": len(expected),
        "invalid_best": invalid_best,
        "sealed_lane": 1 if lane == "sealed" else 0,
    }


def main() -> None:
    t0 = time.time()
    path = os.environ.get("KLEIN_ARTIFACT")
    if not path:
        raise SystemExit("verify.py is run by `klein run-one`, which sets KLEIN_ARTIFACT")
    try:
        try:
            instance = json.loads(INSTANCE.read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            raise Rejected(f"instance.json is not readable JSON: {exc}") from exc
        try:
            payload = json.loads(Path(path).read_text(encoding="utf-8"))
        except (OSError, ValueError) as exc:
            raise Rejected(f"the artifact is not readable JSON: {exc}") from exc
        matched, extra = check(payload, pinned_instance(instance), os.environ.get("KLEIN_TRACK") or None)
    except Rejected as exc:
        print(f"REJECTED: {exc}")
        sys.exit(2)
    evaluate_scalar(
        float(matched),
        exp_id=os.environ.get("KLEIN_EXPERIMENT_ID", "VERIFY"),
        metric_name="optima_matched",
        metric_goal="higher",
        extra=extra,
        t0=t0,
        # study_dir is deliberately NOT passed: aux_metrics.tsv is idempotent per
        # experiment id, so a verifier writing under the run's id would erase the
        # search telemetry the run just recorded.
        study_dir=None,
    )


if __name__ == "__main__":
    main()

What to steal from it:

Pitfalls and war stories that bit this study

  1. A rate limit killed the first LLM cell. The ledger’s retry window (three attempts over seconds) was shorter than a per-minute provider limit, so E0002 crashed with HTTP 429 and the concurrency cap had to drop. Lesson: budget for the provider’s limit, not the happy path.
  2. A dropped connection killed the second. The standard library raises a bare ConnectionResetError that the retry loop did not catch, so E0003 crashed after hundreds of paid calls. Lesson: every response read is a place for a transport error; cache every response so a rerun does not pay twice.
  3. A rerun after a crash is partly the crashed run. E0004 answered a large share of its requests from the crashed runs’ shards. They are genuine responses, but only a salted re-query is an independent second draw (C12).
  4. Count in orders, not only pairs. The three trials of an order sent byte-identical first requests, so every development order came out all-or-none and the exact test moved from 0.03125 to 0.5 when the unit changed (C11).
  5. Declare a price block before a model-calling run. Without one, every usd reads 0, which is unrecorded, not zero (C13).
  6. Keep the replica’s solution table. The salted re-query kept its call shards and metric block but not its per-pair artifact, so which pairs matched on the second draw cannot be read from the record (C14).
  7. The labels were swapped between documents. The gate-hashed data card calls verifier acceptance and rejection controls the other way round from findings; the controls test the verifier only. Lesson: pick one convention before the gate hashes it.
  8. A match on a tabulated object is not search. A matched-budget comparison on public answers measures recall and search together, so a claim about search needs a contamination control and a no-feedback arm before it is made (C15).

What to try next

These are the four next experiments from the findings, in priority order. Each is the control that converts a specific hypothesis above into a finding or a refutation.

  1. A contamination control, first. Re-run the LLM arm unchanged on instances with no public answer at the same 2000 evaluations: for example a perturbed Golomb variant with a forbidden difference set, whose optima the verifier can certify by exhaustive enumeration at small n. A match there could not be retrieval. This is the single experiment that turns C7 and C8 into findings or refutations.
  2. A no-feedback arm. Resample the same model and prompt for 200 proposals without verdicts, on orders 8 and 11, registered as a rule on first_optimal_proposal. If the late matches recur without feedback they are resampling; if they vanish, feedback steered them.
  3. A compute-honest classical baseline. Run the annealer, or the hybrid of ref:dotu2005, at the LLM arm’s wall-clock or at 10 and 100 times the evaluations, reporting the budget in evaluations and seconds. This places the annealer’s zero on its own budget curve.
  4. Snapshot and temperature replication. Query a second dated snapshot at temperature 0, declare a price block (C13), keep the replica’s per-pair table (C14), and report results in orders as the unit (C11).

The study did not do any of these: the contract registered exactly two arms and both phase allowances were spent. The process lessons C3, C10 to C13 and C15 are candidates for promotion into the framework’s cross-study notes after a survey; that promotion is not done here.

References

All entries below are marked verified in references.yaml and match the method card; none is promoted beyond what that record says. Secondary sources are labelled as such.

The method card’s own scan found no paper applying an LLM proposer to Golomb rulers; two queries finding nothing is not evidence that nothing exists.