Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

Re-record the rerank and image-search examples on SIE Cloud (#318)

svonava4bc52e64ab49
diff --git a/examples/image-search/README.md b/examples/image-search/README.md
index 1b10ac998..0acf8db9f 100644
--- a/examples/image-search/README.md
+++ b/examples/image-search/README.md
@@ -1,128 +1,151 @@
-# Find the photograph a shopper described
+# Search a picture catalogue with words it was never tagged with
+
+The runnable example behind [superlinked.com/image-search](https://superlinked.com/image-search).
## What this shows
-Six photographs and one line of text go to SIE Cloud as vectors in the same
-1152-dimensional space. The query is `a red leather handbag`. No captions are
-generated, no keywords are indexed and no reranker runs. A cosine over what came
-back puts the handbag first.
-
-The six were chosen so that a colour match and a category match both sit in the
-set. Red shoes share the colour. A black handbag shares the category. A green
-backpack, a black camera and a blue running shoe fill out the rest. The full
-match beats every partial one.
-
-The run is already recorded. Both encode calls and the vectors they returned
-live in the public HuggingFace dataset
-[superlinked/sie-task-evidence](https://huggingface.co/datasets/superlinked/sie-task-evidence),
-pinned to one revision by `fetch.py`. Download it and you can re-derive the
-published number with **no API key and no inference spend**. Those are the same
-vectors behind the figures on
-[superlinked.com/image-search](https://superlinked.com/image-search).
-
-You cannot verify this by cloning alone. The clone gives you the code; the
-dataset gives you the evidence. Fetching it needs no account and no token.
-
-- Model: `google/siglip-so400m-patch14-384`, 1152-dimensional dense vectors
-- Endpoint: `https://api.superlinked.com/v1/encode/google/siglip-so400m-patch14-384`
-- Model revision: `9fdffc58afc957d1a03a25b10dba0329ab15c2a3`
-- Recorded 2026-09-21
-- 2 calls: the six photographs in one batch, then the query
+50 public-domain photographs from the Metropolitan Museum of Art, encoded by
+`google/siglip-so400m-patch14-384` and ranked against 24 text requests that
+name a colour, a material and an object.
-## Run it
+```
+the object 2 of 24 median rank 5.5
+colour and object 7 of 24 median rank 3
+material and object 6 of 24 median rank 2
+colour, material and object 13 of 24 median rank 1
+```
-Download the recorded run, then rank it. Both steps are standard library only,
-so there is nothing to install and no key to set:
+**The catalogue carries no colour.** Every photograph is a museum record with an
+`objectName` and a `medium`, and nothing in either says blue or brown. The
+colour written beside each photograph here is ground truth for scoring, assigned
+by looking at the picture; it is never sent to the model and never indexed. The
+model sees pixels and the request sees words, and the only thing joining them is
+that SigLIP puts both in one 1152-dimensional space.
+
+Each request is written four ways, from the bare object up to all three
+attributes:
-```sh
-python3 fetch.py
-python3 score.py
```
+a vase
+a blue vase
+a porcelain vase
+a blue porcelain vase
+```
+
+Scoring compares where the photograph matching all three lands under each form.
+That makes "the whole request wins" a measurement rather than an assertion.
+
+## Where the attributes come from, exactly
+
+`material` is the first vocabulary word that appears LITERALLY in the Met's own
+`medium`, with `stoneware` checked before `porcelain` so a "Porcelaneous
+stoneware" reads as the stoneware the Met calls it. A photograph whose `medium`
+names none of the vocabulary is dropped rather than inferred.
+
+That rule is stricter than the one this example started with, and it cost the
+headline figure. An earlier catalogue labelled six stoneware pieces
+`earthenware` and two `Copper alloy` plates `brass`, and scored 15 of 24 on the
+complete request. This one scores 13. The lower number is the published one,
+because the higher one rested on eight labels the museum record does not
+support.
+
+`category` is the Met's `objectName` through a synonym table: its Dish is a
+plate, its Ewer and Pitcher are jugs, its Beaker is a cup, its Tea caddy is a
+box. Both values are in `inputs/catalogue.json`.
-Look at a request without sending it:
+## Why the catalogue is built the way it is
+
+A request only counts if first place has to be taken from a near miss. So a
+(colour, material, object) triple becomes a request only when the catalogue also
+holds a photograph matching each PAIR of the three:
+
+- the same colour and material on another object
+- the same colour and object in another material
+- the same material and object in another colour
+
+`score.py` re-checks that for every request before it derives a figure, and
+refuses the whole run if any request has lost a near miss. It also refuses a
+catalogue holding two photographs with the same triple, because then "the
+photograph matching all three" is not one photograph and no figure over it means
+anything.
+
+## Run it
+
+The code is in this repository. The photographs, the requests and the recorded
+responses are in the public Hugging Face dataset
+[`superlinked/sie-task-evidence`](https://huggingface.co/datasets/superlinked/sie-task-evidence),
+so a clone alone is not enough. Fetch, then score:
```sh
-python3 run.py --show images
-python3 run.py --show query
+python3 fetch.py # downloads the pinned revision into evidence/
+python3 score.py # reproduces every published figure offline
```
-Encode it yourself, which needs a key and spends credits:
+Both are standard library only. Neither needs an API key, a Hugging Face token
+or any inference spend. `fetch.py` pins a dataset commit rather than `main`, and
+checks every file, each photograph included, against a digest from a manifest
+its own source pins.
+
+To record against SIE Cloud yourself. This is the only part that needs the SDK,
+and the only command here that spends anything:
```sh
uv sync
-SIE_API_KEY=sk-sie-... uv run python run.py --output run-output
+SIE_API_KEY=... uv run python run.py
```
-## What result to expect
+`run.py` sends through `sie_sdk.SIEClient`. The import is deferred into `main()`,
+so `--show` keeps working on a bare `python3` with nothing installed.
+
+## How the figures are derived
+
+Two sides, two sources. The photograph each request is looking for was fixed in
+`inputs/queries.json` before any call, by a rule over the catalogue's attributes
+that reads no score. The ranking comes out of the recorded vectors in
+`calls.json`. The figures `score.py` asserts against come from a third place
+again: the page, pinned in `score.py`'s own source, so editing the fetched
+evidence alone will not satisfy it.
-`score.py` prints the ranking and ends with:
+Everything fails rather than skips. A missing file, a photograph whose bytes no
+longer match their digest, a response that does not match its
+`response_sha256`, a request the pinned inputs do not rebuild, a photograph or a
+request with no recorded vector, a vector returned twice, a declared width that
+disagrees with its own values, or a non-finite value all exit non-zero.
+
+## What is in the dataset
```
-rank score image
- 1 0.168 Red leather handbag <- the query's subject
- 2 0.068 Black handbag
- 3 0.067 Red shoes
- 4 0.057 Green backpack
- 5 0.028 Black camera
- 6 -0.008 Blue running shoe
-
-6 photographs, 1152-dimensional vectors, one text query
-the red leather handbag ranks first at 0.168
-the closest other photograph is the black handbag at 0.068
-a gap of 0.100, or 2.5x
+image-search/
+ inputs/catalogue.json every photograph: its file, digest, byte length,
+ dimensions, its colour, material and object, and the
+ Met record each attribute came from
+ inputs/*.jpg the photographs themselves, exactly the bytes encoded
+ inputs/queries.json the requests, each naming a colour, a material, an
+ object and the photograph matching all three
+ calls.json one entry per encode call: the request, the returned
+ vectors, the status, the served deployment revision
+ and the round-trip time
+ manifest.json endpoint, model and its revision, run date, and a
+ digest for every file above
```
-Those are the figures the task page publishes. The handbag clears the field by a
-wide margin, and the two partial matches land close together well below it.
-
-`score.py` fails rather than skipping. A manifest naming a different model or a
-different model revision, an image whose bytes no longer match their digest, a
-response that does not match its `response_sha256`, a request the pinned inputs
-do not rebuild, a call nothing scores, a call whose served deployment revision
-is not the one the manifest names, an image with no recorded vector, a vector
-returned twice, a vector whose declared width disagrees with its own values, a
-non-finite value, or a ranking in any order other than the published one all
-exit non-zero.
-
-The expected order lives in `ranking.py` as `EXPECTED_ORDER`, in the committed
-source rather than in the evidence. Editing `evidence/` alone cannot satisfy it,
-because one side of that comparison is something the recording does not
-control. `MODEL_REVISION` is pinned the same way, and `run.py` checks it against
-the endpoint before encoding anything, so a run against other weights costs no
-credits and never produces evidence `score.py` would accept.
-
## What this does NOT establish
-- **Not a benchmark score.** Six photographs and one query is a demonstration,
- not a measurement. There is no held-out set and no confidence interval here,
- so nothing in this output supports a percentage you could quote.
-- **Not a claim about attribution.** SigLIP returns one pooled vector per
- image. The scores say which photograph the sentence matches. They do not say
- which pixels earned the match, and this example draws no boxes.
-- **Not a test of scale.** Six images are ranked by a Python loop. Nothing here
- speaks to recall or index behaviour at a million images.
-- **Not evidence the set is unbiased.** The six photographs and the query were
- chosen together, with the colour match and the category match put in on
- purpose. It is a designed set, not a sample of a catalogue.
-- **Not bound to the website.** The same run backs the fixtures in
- `superlinked/sie-web` under `apps/site/tests/fixtures/reference/image-search/`,
- which is what that repository's CI checks. Nothing automatically ties the two
- copies together, so they could drift.
-
-## Inputs
-
-`evidence/inputs/images.json` holds the six photographs with the subject,
-author, source URL, licence and SHA-256 of each. `score.py` checks every digest
-before ranking anything. The files come from Wikimedia Commons, Unsplash and
-Flickr under public-domain, Creative Commons or Unsplash terms.
-
-`evidence/inputs/query.json` holds the one query.
-
-`ranking.py` builds the request bodies and does the cosine. `run.py` and
-`score.py` both read it from there, so the request the scorer rebuilds is the
-request the runner sends, and the scorer refuses a recording it cannot rebuild.
-
-The photographs travel as raw file bytes. SIE's SDK keeps already encoded PNG
-and JPEG unchanged on the wire, so the digest recorded in `calls.json` is the
-digest of what SIE read, and `inputs/` holds those exact bytes rather than a
-second base64 copy of them.
+- **This is a demonstration, not a benchmark.** No figure here generalises to
+ your catalogue, and a set of this size is not a retrieval evaluation.
+- **Colour is a judgement.** Object and material come from the Met's own
+ cataloguing. Colour was assigned by looking at each photograph, and a reader
+ who disagrees with one can see the picture and say so. It is recorded per
+ photograph, with `colour_source` saying exactly that.
+- **Museum objects are not product photography.** Lighting, background and
+ framing are consistent in a way a real catalogue's are not.
+- **The displayed pictures are not the encoded ones.** The website serves
+ smaller renditions so the page stays light. The bytes SIE read are the files
+ in the dataset, and their digests are what `score.py` checks.
+- **No tamper resistance.** The digests catch a truncated or corrupted
+ download. They are not a provenance chain.
+
+sie-web keeps its own copy of these recordings under
+`apps/site/tests/fixtures/reference/image-search/`, which is what its CI tests
+read. The two copies hold the same recorded responses. Nothing binds them
+together, so they can drift.
diff --git a/examples/image-search/catalogue.py b/examples/image-search/catalogue.py
new file mode 100644
index 000000000..bdcf3eed6
--- /dev/null
+++ b/examples/image-search/catalogue.py
@@ -0,0 +1,230 @@
+"""Shared between run.py and score.py: the catalogue, the queries, the ranking.
+
+Standard library only, on purpose. run.py imports this and adds the SDK;
+score.py imports this and adds nothing. Because both read the request shape from
+here, the body score.py rebuilds is the body run.py sent, and score.py can
+refuse a recording it cannot rebuild.
+
+The images are sent as raw file bytes. The SDK's images.py keeps already encoded
+JPEG bytes byte-identical on the wire, so the SHA-256 of the file in inputs/ is
+the digest of what SIE actually received. calls.json records that digest in
+place of the bytes rather than a second base64 copy of a file sitting next to
+it.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import math
+from pathlib import Path
+from typing import Any
+
+HERE = Path(__file__).resolve().parent
+EVIDENCE = HERE / "evidence"
+INPUTS = EVIDENCE / "inputs"
+
+ENDPOINT = "https://api.superlinked.com"
+MODEL = "google/siglip-so400m-patch14-384"
+ENCODE_PATH = f"/v1/encode/{MODEL}"
+DIMS = 1152
+
+# The HuggingFace revision of the weights, as GET /v1/models reports it. This is
+# the checkpoint the published figures came from, and both run.py and score.py
+# refuse to proceed against a different one.
+#
+# Not to be confused with the deployment revision carried on every response in
+# X-SIE-Model-Revision. That digest identifies the SIE deployment, and models
+# served together share it, so it can never stand in for the weights.
+MODEL_REVISION = "9fdffc58afc957d1a03a25b10dba0329ab15c2a3"
+
+# SigLIP is trained with one contrastive objective over both towers, so a query
+# and an image go through the same encoder with no is_query asymmetry. The
+# ranking below is a plain cosine, which is what that training makes meaningful.
+METRIC = "cosine similarity between the L2-normalized text vector and each L2-normalized image vector"
+
+# Images per encode call. Small enough that one failure costs little, large
+# enough that the run is a handful of calls rather than one per photograph.
+BATCH = 12
+
+# The four ways every request is written, from the bare category up to all three
+# attributes. Scoring compares the target's rank across them, so "the whole
+# request wins" is a measurement rather than an assertion.
+FORMS = ("category", "colour-category", "material-category", "full")
+
+VOWELS = "aeiou"
+
+
+def article(word: str) -> str:
+ return "an" if word[:1].lower() in VOWELS else "a"
+
+
+def phrase(form: str, colour: str, material: str, category: str) -> str:
+ """The query text for one target under one form."""
+ if form == "category":
+ words = [category]
+ elif form == "colour-category":
+ words = [colour, category]
+ elif form == "material-category":
+ words = [material, category]
+ elif form == "full":
+ words = [colour, material, category]
+ else:
+ raise SystemExit(f"Unknown query form: {form!r}")
+ return f"{article(words[0])} {' '.join(words)}"
+
+
+def sha256_bytes(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def compact_json(value: Any) -> bytes:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
+
+
+def load_catalogue() -> list[dict[str, Any]]:
+ """Every photograph, with the digest of the file as published."""
+ path = INPUTS / "catalogue.json"
+ if not path.exists():
+ raise SystemExit(f"{path} is missing. Run: python3 fetch.py")
+ records = json.loads(path.read_text(encoding="utf-8"))["images"]
+ seen: set[str] = set()
+ triples: set[tuple[str, str, str]] = set()
+ for record in records:
+ if record["id"] in seen:
+ raise SystemExit(f"catalogue.json lists {record['id']!r} twice")
+ seen.add(record["id"])
+ triple = (record["colour"], record["material"], record["category"])
+ if triple in triples:
+ raise SystemExit(
+ f"{record['id']}: a second photograph is {triple[0]} {triple[1]} {triple[2]}. "
+ "With two, 'the image matching all three' is not a single image and no "
+ "figure over it means anything."
+ )
+ triples.add(triple)
+ file_path = INPUTS / record["file"]
+ if not file_path.exists():
+ raise SystemExit(f"{file_path} is missing. Run: python3 fetch.py")
+ data = file_path.read_bytes()
+ digest = sha256_bytes(data)
+ if digest != record["sha256"]:
+ raise SystemExit(f"{record['file']}: file digest {digest} is not the recorded {record['sha256']}")
+ if len(data) != record["bytes"]:
+ raise SystemExit(f"{record['file']}: {len(data)} bytes on disk, catalogue.json says {record['bytes']}")
+ return records
+
+
+def load_queries() -> list[dict[str, Any]]:
+ path = INPUTS / "queries.json"
+ if not path.exists():
+ raise SystemExit(f"{path} is missing. Run: python3 fetch.py")
+ queries = json.loads(path.read_text(encoding="utf-8"))["queries"]
+ seen: set[str] = set()
+ for query in queries:
+ if query["id"] in seen:
+ raise SystemExit(f"queries.json lists {query['id']!r} twice")
+ seen.add(query["id"])
+ return queries
+
+
+def query_items(queries: list[dict[str, Any]]) -> list[dict[str, str]]:
+ """One item per (target, form) pair, in a fixed order."""
+ items = []
+ for query in queries:
+ for form in FORMS:
+ items.append(
+ {
+ "id": f"{query['id']}/{form}",
+ "text": phrase(form, query["colour"], query["material"], query["category"]),
+ }
+ )
+ return items
+
+
+def image_batches(records: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
+ return [records[index : index + BATCH] for index in range(0, len(records), BATCH)]
+
+
+def image_body(batch: list[dict[str, Any]]) -> dict[str, Any]:
+ return {
+ "items": [
+ {
+ "id": record["id"],
+ "images": [
+ {
+ "file": f"inputs/{record['file']}",
+ "format": record["format"],
+ "bytes": record["bytes"],
+ "sha256": record["sha256"],
+ }
+ ],
+ }
+ for record in batch
+ ],
+ "params": {"output_types": ["dense"]},
+ }
+
+
+def query_body(queries: list[dict[str, Any]]) -> dict[str, Any]:
+ return {"items": query_items(queries), "params": {"output_types": ["dense"]}}
+
+
+def bodies(records: list[dict[str, Any]], queries: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
+ """Every call this example makes, keyed by the slug calls.json records."""
+ out = {
+ f"images-{index:02d}": image_body(batch)
+ for index, batch in enumerate(image_batches(records), start=1)
+ }
+ out["queries"] = query_body(queries)
+ return out
+
+
+def normalize(values: list[float]) -> list[float]:
+ total = sum(value * value for value in values) ** 0.5
+ if not total or not math.isfinite(total):
+ raise SystemExit("A returned vector has zero or non-finite length")
+ return [value / total for value in values]
+
+
+def cosine(left: list[float], right: list[float]) -> float:
+ if len(left) != len(right):
+ raise SystemExit(f"Cannot compare a {len(left)}-dimensional vector with a {len(right)}-dimensional one")
+ return sum(a * b for a, b in zip(normalize(left), normalize(right), strict=True))
+
+
+def rank(query_vector: list[float], image_vectors: dict[str, list[float]]) -> list[tuple[str, float]]:
+ """Every image, best first. Ties break by id, so the order is total."""
+ scored = [(name, cosine(query_vector, vector)) for name, vector in image_vectors.items()]
+ scored.sort(key=lambda pair: (-pair[1], pair[0]))
+ return scored
+
+
+def overlap(record: dict[str, Any], query: dict[str, Any]) -> tuple[bool, bool, bool]:
+ """Which of colour, material and category this photograph shares with the request."""
+ return (
+ record["colour"] == query["colour"],
+ record["material"] == query["material"],
+ record["category"] == query["category"],
+ )
+
+
+def competitor_kind(record: dict[str, Any], query: dict[str, Any]) -> str:
+ """What kind of competitor a photograph is for one request.
+
+ `full` is the single photograph matching all three. The three two-of-three
+ kinds are named by the attribute they get WRONG, because that is what the
+ request has to overrule.
+ """
+ colour, material, category = overlap(record, query)
+ matched = sum((colour, material, category))
+ if matched == 3:
+ return "full"
+ if matched == 2:
+ if not colour:
+ return "wrong-colour"
+ if not material:
+ return "wrong-material"
+ return "wrong-category"
+ if matched == 1:
+ return "one-attribute"
+ return "unrelated"
diff --git a/examples/image-search/fetch.py b/examples/image-search/fetch.py
index 5c17d8197..6dd5ed086 100755
--- a/examples/image-search/fetch.py
+++ b/examples/image-search/fetch.py
@@ -6,62 +6,199 @@
Standard library only. No token, no account, no API key. The dataset is public
and this pulls it anonymously.
-Everything lands in evidence/: the pinned inputs, the recorded calls and the
-run manifest. score.py reads from there and never touches the network.
+Everything lands in evidence/: the catalogue, every photograph, the requests,
+the recorded calls and the run manifest. score.py reads from there and never
+touches the network.
REVISION is a dataset commit, deliberately not `main`, so a later upload cannot
-change what this example scores.
+change what this example scores. The digest chain is anchored in this file:
+MANIFEST_SHA256 pins manifest.json, and manifest.json pins calls.json and every
+input file including each photograph.
+
+A file that is missing or that fails its digest is a FAILURE, never a skip, and
+the script exits nonzero rather than leaving a partial tree the scorer could
+mistake for a complete one.
"""
from __future__ import annotations
+import argparse
+import hashlib
import json
+import shutil
import sys
+import tempfile
+import urllib.error
import urllib.request
from pathlib import Path
-HERE = Path(__file__).resolve().parent
-EVIDENCE = HERE / "evidence"
-
DATASET = "superlinked/sie-task-evidence"
-REVISION = "9f0d64b2ef6df7c4cad554833874570e88452d81"
TASK = "image-search"
+REVISION = "c28bc851802d1c8728d728c24a50e94a76299a04"
+MANIFEST_SHA256 = "0b89072bd90eb1b903fd9730253b89083f2b3e0193eb5d7f309c8bfbf568d2f8"
+
+BASE = f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}/{TASK}"
+HTTP_OK = 200
+MARKER_NAME = ".sie-evidence"
+
+
+def download(relative_path: str) -> bytes:
+ url = f"{BASE}/{relative_path}"
+ # No Authorization header: the dataset is public and this must work for a
+ # reader who has never signed in to HuggingFace.
+ request = urllib.request.Request(url, headers={"Accept": "*/*", "User-Agent": f"sie-examples/{TASK}"})
+ try:
+ with urllib.request.urlopen(request, timeout=300) as response:
+ if response.status != HTTP_OK:
+ raise RuntimeError(f"{url} returned HTTP {response.status}")
+ return response.read()
+ except urllib.error.HTTPError as error:
+ raise RuntimeError(f"{url} returned HTTP {error.code}") from error
+ except urllib.error.URLError as error:
+ raise RuntimeError(f"{url} could not be reached: {error.reason}") from error
+
+
+def digest(payload: bytes) -> str:
+ return hashlib.sha256(payload).hexdigest()
+
+
+def marker_bytes() -> bytes:
+ return (
+ json.dumps(
+ {"written_by": "fetch.py", "dataset": DATASET, "task": TASK, "revision": REVISION},
+ indent=2,
+ )
+ + "\n"
+ ).encode("utf-8")
+
+
+def backup_path(dest: Path) -> Path:
+ """Where `dest` is moved aside to while the new tree is renamed into place."""
+ return dest.with_name(f"{dest.name}.previous")
+
+
+def refuse_reason(dest: Path) -> str | None:
+ """Why `dest` must not be replaced, or None when replacing it is safe."""
+ resolved = dest.resolve()
+ cwd = Path.cwd().resolve()
+ # These hold whatever the marker says. A marker can be planted; the working
+ # tree still must not be removable by a --dest typo.
+ if resolved == resolved.parent:
+ return f"{resolved} is the filesystem root"
+ if resolved == cwd:
+ return f"{resolved} is the current working directory"
+ if resolved in cwd.parents:
+ return f"{resolved} contains the current working directory"
+ if resolved == Path.home().resolve():
+ return f"{resolved} is your home directory"
+
+ # The backup path is one this script names, which is not the same as one it
+ # owns. If something else already sits there, moving `dest` onto it destroys
+ # that something. Checked here so the refusal is reported by the same path
+ # as every other refusal, before anything is downloaded.
+ backup = backup_path(dest)
+ if backup.exists():
+ return (
+ f"{backup} already exists, and this script would move {dest} onto it. "
+ f"Move {backup} aside, or pass --dest somewhere else."
+ )
+
+ if dest.is_symlink():
+ return f"{dest} is a symlink"
+ if not dest.exists():
+ return None
+ if not dest.is_dir():
+ return f"{dest} exists and is not a directory"
+
+ marker = dest / MARKER_NAME
+ if not marker.is_file():
+ return (
+ f"{dest} exists but holds no {MARKER_NAME}, so this script did not write it. "
+ f"Move it aside, or pass --dest somewhere else."
+ )
+ try:
+ recorded = json.loads(marker.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as error:
+ return f"{dest}/{MARKER_NAME} could not be read: {error}"
+ if recorded.get("dataset") != DATASET or recorded.get("task") != TASK:
+ return f"{dest}/{MARKER_NAME} names {recorded.get('dataset')}/{recorded.get('task')}, not {DATASET}/{TASK}"
+ return None
+
+
+def swap_into_place(staging: Path, dest: Path) -> None:
+ """Put `staging` at `dest` without deleting anything first."""
+ previous = None
+ if dest.exists():
+ previous = backup_path(dest)
+ if previous.exists():
+ # refuse_reason checks this twice before we get here. Reaching it
+ # anyway means something appeared in between, and deleting it is
+ # never the right answer.
+ raise RuntimeError(f"refusing to replace {dest}: backup path {previous} already exists")
+ dest.replace(previous)
+ try:
+ staging.replace(dest)
+ except OSError:
+ if previous is not None:
+ previous.replace(dest)
+ raise
+ if previous is not None:
+ shutil.rmtree(previous, ignore_errors=True)
-API = f"https://huggingface.co/api/datasets/{DATASET}/tree/{REVISION}"
-FILES = f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}"
-
-
-def get(url: str) -> bytes:
- # No Authorization header: the dataset is public and this must work for
- # a reader who has never signed in to HuggingFace.
- request = urllib.request.Request(url, headers={"User-Agent": f"sie-examples/{TASK}"})
- with urllib.request.urlopen(request, timeout=300) as response:
- return response.read()
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--dest", default="evidence", help="output directory (default: evidence)")
+ args = parser.parse_args()
-def listing() -> list[dict]:
- entries = json.loads(get(f"{API}/{TASK}?recursive=true"))
- files = [entry for entry in entries if entry.get("type") == "file"]
- if not files:
- raise SystemExit(f"{DATASET} revision {REVISION} has no files under {TASK}/")
- return files
-
+ dest = Path(args.dest)
+ reason = refuse_reason(dest)
+ if reason is not None:
+ print(f"refusing to replace {dest}: {reason}", file=sys.stderr)
+ return 1
+ dest.parent.mkdir(parents=True, exist_ok=True)
-def main() -> int:
print(f"{DATASET} at {REVISION}")
+ manifest_bytes = download("manifest.json")
+ if digest(manifest_bytes) != MANIFEST_SHA256:
+ print(f"manifest.json digest is {digest(manifest_bytes)}, expected {MANIFEST_SHA256}", file=sys.stderr)
+ return 1
+ manifest = json.loads(manifest_bytes)
+
+ files = manifest["files_sha256"]
+ staging = Path(tempfile.mkdtemp(prefix=f".{TASK}-evidence-", dir=dest.parent))
total = 0
- for entry in sorted(listing(), key=lambda item: item["path"]):
- remote = entry["path"]
- relative = remote[len(TASK) + 1 :]
- target = EVIDENCE / relative
- target.parent.mkdir(parents=True, exist_ok=True)
- body = get(f"{FILES}/{remote}")
- if entry.get("size") is not None and len(body) != entry["size"]:
- raise SystemExit(f"{remote}: downloaded {len(body)} bytes, the dataset lists {entry['size']}")
- target.write_bytes(body)
- total += len(body)
- print(f" {relative} ({len(body)} bytes)")
- print(f"Wrote {total} bytes to {EVIDENCE}")
+ try:
+ (staging / "manifest.json").write_bytes(manifest_bytes)
+ for relative_path, expected in sorted(files.items()):
+ payload = download(relative_path)
+ actual = digest(payload)
+ if actual != expected:
+ print(f"{relative_path} digest is {actual}, expected {expected}", file=sys.stderr)
+ return 1
+ target = staging / relative_path
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_bytes(payload)
+ total += len(payload)
+
+ if digest((staging / "calls.json").read_bytes()) != manifest["calls_sha256"]:
+ print("calls.json does not match the digest in manifest.json", file=sys.stderr)
+ return 1
+
+ (staging / MARKER_NAME).write_bytes(marker_bytes())
+
+ # Re-checked here: the first check ran before the download, and the
+ # destination could have changed since.
+ reason = refuse_reason(dest)
+ if reason is not None:
+ print(f"refusing to replace {dest}: {reason}", file=sys.stderr)
+ return 1
+ swap_into_place(staging, dest)
+ finally:
+ shutil.rmtree(staging, ignore_errors=True)
+
+ print(f"{TASK}: {len(files) + 1} files verified into {args.dest}/ ({total} bytes)")
+ print(f"{manifest['calls_recorded']} recorded calls over {manifest['images']} photographs")
print("Now run: python3 score.py")
return 0
diff --git a/examples/image-search/pyproject.toml b/examples/image-search/pyproject.toml
index 648bdff13..62800f59e 100644
--- a/examples/image-search/pyproject.toml
+++ b/examples/image-search/pyproject.toml
@@ -1,7 +1,7 @@
[project]
name = "superlinked-sie-image-search-example"
version = "0.1.0"
-description = "Rank photographs against a text query with SIE Cloud"
+description = "Search a picture catalogue with words it was never tagged with"
requires-python = ">=3.12,<3.13"
dependencies = [
"sie-sdk>=0.6.23,<0.8.0",
diff --git a/examples/image-search/ranking.py b/examples/image-search/ranking.py
deleted file mode 100644
index 0e7c474bc..000000000
--- a/examples/image-search/ranking.py
+++ /dev/null
@@ -1,140 +0,0 @@
-"""Shared between run.py and score.py: request bodies in, ranking out.
-
-Standard library only, on purpose. run.py imports this and adds the SDK;
-score.py imports this and adds nothing. Because both read the request shape
-from here, the body score.py rebuilds is the body run.py sent, and score.py can
-refuse a recording it cannot rebuild.
-
-The images are sent as raw file bytes. The SDK's images.py keeps already
-encoded PNG/JPEG bytes byte-identical on the wire, so the SHA-256 of the file
-in inputs/ is the digest of what SIE actually received. calls.json records that
-digest in place of the bytes rather than a second base64 copy of a file already
-sitting next to it.
-"""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import math
-from pathlib import Path
-from typing import Any
-
-HERE = Path(__file__).resolve().parent
-EVIDENCE = HERE / "evidence"
-INPUTS = EVIDENCE / "inputs"
-
-ENDPOINT = "https://api.superlinked.com"
-MODEL = "google/siglip-so400m-patch14-384"
-ENCODE_PATH = f"/v1/encode/{MODEL}"
-DIMS = 1152
-
-# The HuggingFace revision of the weights, as GET /v1/models reports it. This is
-# the checkpoint the published figures came from, and both run.py and score.py
-# refuse to proceed against a different one.
-#
-# Not to be confused with the deployment revision carried on every response in
-# X-SIE-Model-Revision. That digest identifies the SIE deployment, and models
-# served together share it: arctic-embed-l-v2.0, siglip2-base, bge-m3 and this
-# model all return the same value, so it can never stand in for the weights.
-MODEL_REVISION = "9fdffc58afc957d1a03a25b10dba0329ab15c2a3"
-
-# The published ranking, in order. Pinned here in the committed source so
-# score.py compares what it derives from the recording against something the
-# recording cannot move. Editing evidence/ alone will not satisfy this.
-EXPECTED_ORDER = (
- "red-leather-handbag",
- "black-handbag",
- "red-shoes",
- "green-backpack",
- "black-camera",
- "blue-running-sneaker",
-)
-
-# SigLIP is trained with one contrastive objective over both towers, so a query
-# and an image go through the same encoder with no is_query asymmetry. The
-# ranking below is a plain cosine, which is what that training makes meaningful.
-METRIC = "cosine similarity between the L2-normalized text vector and each L2-normalized image vector"
-
-
-def sha256_bytes(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
-
-
-def compact_json(value: Any) -> bytes:
- return json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
-
-
-def load_images() -> list[dict[str, Any]]:
- """The six photographs, with the digest of each file as committed."""
- records = json.loads((INPUTS / "images.json").read_text(encoding="utf-8"))["images"]
- seen: set[str] = set()
- for record in records:
- if record["id"] in seen:
- raise SystemExit(f"images.json lists {record['id']!r} twice")
- seen.add(record["id"])
- path = INPUTS / record["file"]
- if not path.exists():
- raise SystemExit(f"{path} is missing. Run: python3 fetch.py")
- data = path.read_bytes()
- digest = sha256_bytes(data)
- if digest != record["sha256"]:
- raise SystemExit(f"{record['file']}: file digest {digest} is not the recorded {record['sha256']}")
- if len(data) != record["bytes"]:
- raise SystemExit(f"{record['file']}: {len(data)} bytes on disk, images.json says {record['bytes']}")
- return records
-
-
-def load_query() -> dict[str, Any]:
- return json.loads((INPUTS / "query.json").read_text(encoding="utf-8"))
-
-
-def image_body(records: list[dict[str, Any]]) -> dict[str, Any]:
- """One encode call carrying all six photographs."""
- return {
- "items": [
- {
- "id": record["id"],
- "images": [
- {
- "file": f"inputs/{record['file']}",
- "format": record["format"],
- "bytes": record["bytes"],
- "sha256": record["sha256"],
- }
- ],
- }
- for record in records
- ],
- "params": {"output_types": ["dense"]},
- }
-
-
-def query_body(query: dict[str, Any]) -> dict[str, Any]:
- return {
- "items": [{"id": query["id"], "text": query["text"]}],
- "params": {"output_types": ["dense"]},
- }
-
-
-def bodies(records: list[dict[str, Any]], query: dict[str, Any]) -> dict[str, dict[str, Any]]:
- return {"images": image_body(records), "query": query_body(query)}
-
-
-def normalize(values: list[float]) -> list[float]:
- total = sum(value * value for value in values) ** 0.5
- if not total or not math.isfinite(total):
- raise SystemExit("A returned vector has zero or non-finite length")
- return [value / total for value in values]
-
-
-def cosine(left: list[float], right: list[float]) -> float:
- if len(left) != len(right):
- raise SystemExit(f"Cannot compare a {len(left)}-dimensional vector with a {len(right)}-dimensional one")
- return sum(a * b for a, b in zip(normalize(left), normalize(right)))
-
-
-def rank(query_vector: list[float], image_vectors: dict[str, list[float]]) -> list[tuple[str, float]]:
- scored = [(name, cosine(query_vector, vector)) for name, vector in image_vectors.items()]
- scored.sort(key=lambda pair: (-pair[1], pair[0]))
- return scored
diff --git a/examples/image-search/run.py b/examples/image-search/run.py
index b07b87149..ae2ad77e3 100755
--- a/examples/image-search/run.py
+++ b/examples/image-search/run.py
@@ -1,19 +1,15 @@
#!/usr/bin/env python3
-"""Encode six photographs and one text query with SIE Cloud.
+"""Encode the catalogue and every request form with SIE Cloud.
- uv run python run.py # both calls, writes run-output/
- python3 run.py --show images # print a request body, no network
- python3 run.py --show query
-
-Two calls, the call the /image-search task page shows:
+ uv run python run.py # every call, writes run-output/
+ python3 run.py --show images-01 # print a request body, no network
+ python3 run.py --show queries
POST https://api.superlinked.com/v1/encode/google/siglip-so400m-patch14-384
- images: {"items": [...6 photographs...], "params": {"output_types": ["dense"]}}
- query: {"items": [{"text": "a red leather handbag"}], "params": {...}}
SigLIP puts text and pixels in one 1152-dimensional space, so ranking is a
-cosine between what the two calls return. There is no reranker and no caption
-step in between.
+cosine between what the image calls and the query call return. There is no
+reranker and no caption step in between.
Results go to --output as a manifest.json and a calls.json in the dataset's own
shape, one entry per call holding the request, the response, the HTTP status,
@@ -36,7 +32,7 @@ from datetime import UTC, datetime
from pathlib import Path
from typing import Any
-import ranking
+import catalogue
HERE = Path(__file__).resolve().parent
@@ -50,7 +46,7 @@ def dense_items(results: list[Any], body: dict[str, Any]) -> list[dict[str, Any]
if len(results) != len(body["items"]):
raise SystemExit(f"Sent {len(body['items'])} items and got {len(results)} back")
items = []
- for sent, result in zip(body["items"], results):
+ for sent, result in zip(body["items"], results, strict=True):
if result.get("id") != sent["id"]:
raise SystemExit(f"Response item id {result.get('id')!r} does not match request item {sent['id']!r}")
vector = result["dense"]
@@ -68,39 +64,39 @@ def send(client: Any, name: str, body: dict[str, Any], records: list[dict[str, A
"""Send one encode call and return its calls.json entry.
The recorded request body names each image by file and digest. What goes on
- the wire is the file's bytes: the SDK transports already encoded PNG and
- JPEG unchanged, so the digest in the record is the digest of what SIE read.
+ the wire is the file's bytes: the SDK transports already encoded JPEG bytes
+ unchanged, so the digest in the record is the digest of what SIE read.
"""
by_id = {record["id"]: record for record in records}
items: list[dict[str, Any]] = []
for item in body["items"]:
if "images" in item:
- path = ranking.INPUTS / by_id[item["id"]]["file"]
+ path = catalogue.INPUTS / by_id[item["id"]]["file"]
items.append({"id": item["id"], "images": [path.read_bytes()]})
else:
items.append({"id": item["id"], "text": item["text"]})
requested_at = datetime.now(UTC).isoformat(timespec="seconds")
started = time.monotonic()
- results = client.encode(ranking.MODEL, items, output_types=list(body["params"]["output_types"]))
+ results = client.encode(catalogue.MODEL, items, output_types=list(body["params"]["output_types"]))
elapsed_ms = round((time.monotonic() - started) * 1000, 1)
if not isinstance(results, list):
results = [results]
- response = {"items": dense_items(results, body), "model": ranking.MODEL}
+ response = {"items": dense_items(results, body), "model": catalogue.MODEL}
return {
"slug": name,
- "kind": "images" if name == "images" else "query",
+ "kind": "queries" if name == "queries" else "images",
"requested_at": requested_at,
"request": {
"method": "POST",
# The URL the SDK actually used, not this module's default, so a run
# against a regional endpoint records where it really went.
- "url": client.base_url.rstrip("/") + ranking.ENCODE_PATH,
+ "url": client.base_url.rstrip("/") + catalogue.ENCODE_PATH,
"body": body,
},
"status": 200,
"response": response,
- "response_sha256": ranking.sha256_bytes(ranking.compact_json(response)),
+ "response_sha256": catalogue.sha256_bytes(catalogue.compact_json(response)),
"deployment_revision": client.last_model_revision,
"timing": {"duration_ms": elapsed_ms},
}
@@ -112,22 +108,33 @@ def served_revision(client: Any) -> str:
Raises rather than returning a placeholder. A run that cannot establish
which weights answered has nothing to record.
"""
- try:
- listed = client.list_models()
- except Exception as error:
- raise SystemExit(f"Could not read the model revision from /v1/models: {error}") from error
+ # The gateway occasionally answers this with a body that is not JSON.
+ # Three tries, then fail: a run that cannot establish which weights
+ # answered has nothing to record, and a transient must not look like one.
+ listed = None
+ last_error: Exception | None = None
+ for attempt in range(3):
+ try:
+ listed = client.list_models()
+ break
+ except Exception as error: # noqa: BLE001
+ last_error = error
+ print(f"/v1/models attempt {attempt + 1} failed: {error}", file=sys.stderr)
+ time.sleep(2 * (attempt + 1))
+ if listed is None:
+ raise SystemExit(f"Could not read the model revision from /v1/models: {last_error}")
for model in listed if isinstance(listed, list) else listed.get("models", []):
name = model.get("name") if isinstance(model, dict) else None
- if name == ranking.MODEL:
+ if name == catalogue.MODEL:
revision = model.get("revision") or ""
if not revision:
- raise SystemExit(f"/v1/models lists {ranking.MODEL} with no revision")
+ raise SystemExit(f"/v1/models lists {catalogue.MODEL} with no revision")
return revision
- raise SystemExit(f"/v1/models does not list {ranking.MODEL}")
+ raise SystemExit(f"/v1/models does not list {catalogue.MODEL}")
def parse_args() -> argparse.Namespace:
- parser = argparse.ArgumentParser(description="Encode the pinned photographs and query")
+ parser = argparse.ArgumentParser(description="Encode the pinned catalogue and requests")
parser.add_argument("--show", metavar="NAME", help="print one request body and exit, without calling anything")
parser.add_argument(
"--allow-revision-mismatch",
@@ -142,9 +149,9 @@ def parse_args() -> argparse.Namespace:
def main() -> int:
args = parse_args()
- records = ranking.load_images()
- query = ranking.load_query()
- bodies = ranking.bodies(records, query)
+ records = catalogue.load_catalogue()
+ queries = catalogue.load_queries()
+ bodies = catalogue.bodies(records, queries)
if args.show:
body = bodies.get(args.show)
@@ -157,21 +164,22 @@ def main() -> int:
api_key = os.environ.get("SIE_API_KEY", "").strip()
if not api_key:
- raise SystemExit("Set SIE_API_KEY. To check the published figure without a key, run score.py instead.")
+ raise SystemExit("Set SIE_API_KEY. To check the published figures without a key, run score.py instead.")
- client = SIEClient(os.environ.get("SIE_BASE_URL", ranking.ENDPOINT), api_key=api_key, timeout_s=900)
+ client = SIEClient(os.environ.get("SIE_BASE_URL", catalogue.ENDPOINT), api_key=api_key, timeout_s=900)
base_url = client.base_url.rstrip("/")
- print(f"endpoint {base_url}{ranking.ENCODE_PATH}")
- print(f"model {ranking.MODEL}")
+ print(f"endpoint {base_url}{catalogue.ENCODE_PATH}")
+ print(f"model {catalogue.MODEL}")
+ print(f"catalogue {len(records)} photographs, {len(queries)} requests x {len(catalogue.FORMS)} forms")
# Checked before anything is encoded, so a mismatch costs no credits. An
# unreadable revision is a failure too: recording an empty one would produce
# evidence score.py can never validate.
model_revision = served_revision(client)
print(f"revision {model_revision}")
- if model_revision != ranking.MODEL_REVISION and not args.allow_revision_mismatch:
+ if model_revision != catalogue.MODEL_REVISION and not args.allow_revision_mismatch:
raise SystemExit(
- f"This endpoint serves {model_revision!r} and this example publishes {ranking.MODEL_REVISION!r}.\n"
+ f"This endpoint serves {model_revision!r} and this example publishes {catalogue.MODEL_REVISION!r}.\n"
"Different weights produce different scores, and score.py rejects a recording made against "
"another revision.\nRe-run with --allow-revision-mismatch to record anyway, for your own "
"comparison rather than to reproduce the published figures."
@@ -181,7 +189,7 @@ def main() -> int:
for name, body in bodies.items():
entry = send(client, name, body, records)
entries.append(entry)
- print(f"{name:<8} {len(body['items']):>2} items {entry['timing']['duration_ms']:>9.0f} ms")
+ print(f"{name:<11} {len(body['items']):>3} items {entry['timing']['duration_ms']:>9.0f} ms")
# Re-read after the last call. The preflight check above proves the weights
# were right when the run started; this proves they did not roll over while
@@ -199,8 +207,8 @@ def main() -> int:
"task": "image-search",
"page": "https://superlinked.com/image-search",
"endpoint": base_url,
- "path": ranking.ENCODE_PATH,
- "model": ranking.MODEL,
+ "path": catalogue.ENCODE_PATH,
+ "model": catalogue.MODEL,
# The HF revision of the checkpoint, read from GET /v1/models rather than
# assumed. X-SIE-Model-Revision is a deployment digest that models served
# together share, so it is recorded separately under deployment_revision
@@ -209,10 +217,12 @@ def main() -> int:
"deployment_revision": revisions[0] if len(revisions) == 1 else revisions,
"run_date": datetime.now(UTC).date().isoformat(),
"recorded_by": "examples/image-search/run.py",
- "metric": ranking.METRIC,
- "dims": ranking.DIMS,
+ "metric": catalogue.METRIC,
+ "dims": catalogue.DIMS,
"images": len(records),
- "queries": 1,
+ "requests": len(queries),
+ "forms": list(catalogue.FORMS),
+ "query_items": len(catalogue.query_items(queries)),
"calls_recorded": len(entries),
"image_transport": (
"raw file bytes; calls.json records each image's file name and SHA-256 "
diff --git a/examples/image-search/score.py b/examples/image-search/score.py
index 860d8b478..87a07fa7a 100755
--- a/examples/image-search/score.py
+++ b/examples/image-search/score.py
@@ -1,34 +1,60 @@
#!/usr/bin/env python3
-"""Re-derive the published ranking from the recorded run, offline.
+"""Re-derive the published figures from the recorded run, offline.
python3 fetch.py
python3 score.py
Standard library only. No API key, no network, no inference spend. Every number
-below comes out of the two recorded encode responses in evidence/calls.json.
+below comes out of the recorded encode responses in evidence/calls.json.
+
+What it measures, over every request in the catalogue:
+
+ ranks first how often the one photograph matching colour, material and
+ category is the top result, under each of the four request
+ forms. The catalogue is built so that for every request there
+ is also a photograph matching each pair of the three, so first
+ place has to be taken from a near miss rather than from noise.
+
+ median rank where that photograph lands when it is not first.
This fails rather than skipping. A missing file, an image whose bytes no longer
match their digest, a response that does not match its response_sha256, a
-request the pinned inputs do not rebuild, an image with no recorded vector, a
-vector returned twice, a declared width that disagrees with its own values, a
-non-finite value, or a ranking that no longer puts the handbag first all exit
-non-zero.
+request the pinned inputs do not rebuild, an image or query with no recorded
+vector, a vector returned twice, a declared width that disagrees with its own
+values, or a non-finite value all exit non-zero. So does any published figure
+that the recording no longer supports.
"""
from __future__ import annotations
+import argparse
import json
import math
+import statistics
import sys
+from pathlib import Path
from typing import Any
-import ranking
+import catalogue
+
+# Published on https://superlinked.com/image-search. Pinned in the committed
+# source so the scorer compares what it derives from the recording against
+# something the recording cannot move. Editing evidence/ alone will not satisfy
+# this. Filled in from the run; `None` means "not published".
+PUBLISHED: dict[str, int] = {
+ "images": 50,
+ "requests": 24,
+ "first/category": 2,
+ "first/colour-category": 7,
+ "first/material-category": 6,
+ "first/full": 13,
+}
-TARGET = "red-leather-handbag"
+KIND_ORDER = ("full", "wrong-colour", "wrong-material", "wrong-category", "one-attribute", "unrelated")
-def load_calls() -> dict[str, dict[str, Any]]:
- path = ranking.EVIDENCE / "calls.json"
+def load_calls(expected: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ path = catalogue.EVIDENCE / "calls.json"
if not path.exists():
raise SystemExit(f"{path} is missing. Run: python3 fetch.py")
calls = json.loads(path.read_text(encoding="utf-8"))["calls"]
@@ -37,13 +63,12 @@ def load_calls() -> dict[str, dict[str, Any]]:
if call["slug"] in by_slug:
raise SystemExit(f"calls.json records {call['slug']!r} twice")
by_slug[call["slug"]] = call
- missing = {"images", "query"} - set(by_slug)
+ missing = sorted(set(expected) - set(by_slug))
if missing:
- raise SystemExit(f"calls.json is missing {', '.join(sorted(missing))}")
- if set(by_slug) != {"images", "query"}:
- raise SystemExit(
- f"calls.json holds a call nothing scores: {', '.join(sorted(set(by_slug) - {'images', 'query'}))}"
- )
+ raise SystemExit(f"calls.json is missing {', '.join(missing)}")
+ extra = sorted(set(by_slug) - set(expected))
+ if extra:
+ raise SystemExit(f"calls.json holds a call nothing scores: {', '.join(extra)}")
return by_slug
@@ -58,7 +83,7 @@ def check_call(call: dict[str, Any], expected_body: dict[str, Any], manifest: di
expected_url = manifest["endpoint"].rstrip("/") + manifest["path"]
if call["request"]["url"] != expected_url:
raise SystemExit(f"{call['slug']}: recorded URL {call['request']['url']} is not {expected_url}")
- digest = ranking.sha256_bytes(ranking.compact_json(call["response"]))
+ digest = catalogue.sha256_bytes(catalogue.compact_json(call["response"]))
if digest != call["response_sha256"]:
raise SystemExit(f"{call['slug']}: response digest {digest} is not the recorded {call['response_sha256']}")
if call.get("deployment_revision") != manifest.get("deployment_revision"):
@@ -76,8 +101,8 @@ def vectors(call: dict[str, Any], expected_ids: list[str]) -> dict[str, list[flo
values = item["dense"]["values"]
if item["dense"]["dims"] != len(values):
raise SystemExit(f"{item['id']}: declares {item['dense']['dims']} dimensions and carries {len(values)}")
- if len(values) != ranking.DIMS:
- raise SystemExit(f"{item['id']}: {len(values)} dimensions, the model returns {ranking.DIMS}")
+ if len(values) != catalogue.DIMS:
+ raise SystemExit(f"{item['id']}: {len(values)} dimensions, the model returns {catalogue.DIMS}")
if not all(math.isfinite(value) for value in values):
raise SystemExit(f"{item['id']}: a returned value is not finite")
found[item["id"]] = values
@@ -91,64 +116,140 @@ def vectors(call: dict[str, Any], expected_ids: list[str]) -> dict[str, list[flo
def main() -> int:
- manifest_path = ranking.EVIDENCE / "manifest.json"
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--emit", help="write the derived figures as JSON to this path")
+ args = parser.parse_args()
+
+ manifest_path = catalogue.EVIDENCE / "manifest.json"
if not manifest_path.exists():
raise SystemExit(f"{manifest_path} is missing. Run: python3 fetch.py")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
- if manifest.get("model") != ranking.MODEL:
- raise SystemExit(f"manifest names model {manifest.get('model')!r}, this example scores {ranking.MODEL!r}")
- if manifest.get("model_revision") != ranking.MODEL_REVISION:
+ if manifest.get("model") != catalogue.MODEL:
+ raise SystemExit(f"manifest names model {manifest.get('model')!r}, this example scores {catalogue.MODEL!r}")
+ if manifest.get("model_revision") != catalogue.MODEL_REVISION:
raise SystemExit(
f"manifest names model revision {manifest.get('model_revision')!r}, "
- f"this example scores {ranking.MODEL_REVISION!r}. Different weights produce different scores."
+ f"this example scores {catalogue.MODEL_REVISION!r}. Different weights produce different scores."
)
- records = ranking.load_images()
- query = ranking.load_query()
- bodies = ranking.bodies(records, query)
- calls = load_calls()
-
+ records = catalogue.load_catalogue()
+ queries = catalogue.load_queries()
+ bodies = catalogue.bodies(records, queries)
+ calls = load_calls(bodies)
for slug, body in bodies.items():
check_call(calls[slug], body, manifest)
- image_vectors = vectors(calls["images"], [record["id"] for record in records])
- query_vector = next(iter(vectors(calls["query"], [query["id"]]).values()))
+ image_vectors: dict[str, list[float]] = {}
+ image_slugs = [name for name in bodies if name != "queries"]
+ batches = catalogue.image_batches(records)
+ if len(image_slugs) != len(batches):
+ raise SystemExit(f"{len(image_slugs)} recorded image calls for {len(batches)} batches of photographs")
+ for slug, batch in zip(image_slugs, batches, strict=True):
+ image_vectors.update(vectors(calls[slug], [record["id"] for record in batch]))
+ if len(image_vectors) != len(records):
+ raise SystemExit(f"{len(image_vectors)} recorded image vectors for {len(records)} photographs")
+
+ items = catalogue.query_items(queries)
+ query_vectors = vectors(calls["queries"], [item["id"] for item in items])
+
+ by_id = {record["id"]: record for record in records}
+ # Every request must have exactly one photograph matching all three
+ # attributes, and at least one matching each pair. Checked before any
+ # figure is derived, because a request without a near miss on some axis
+ # makes "first place was taken from a near miss" false for that request.
+ for query in queries:
+ kinds: dict[str, int] = {}
+ for record in records:
+ kinds[catalogue.competitor_kind(record, query)] = (
+ kinds.get(catalogue.competitor_kind(record, query), 0) + 1
+ )
+ if kinds.get("full", 0) != 1:
+ raise SystemExit(f"{query['id']}: {kinds.get('full', 0)} photographs match all three attributes")
+ for kind in ("wrong-colour", "wrong-material", "wrong-category"):
+ if kinds.get(kind, 0) < 1:
+ raise SystemExit(f"{query['id']}: the catalogue holds no {kind} near miss")
+ if query["target"] not in by_id:
+ raise SystemExit(f"{query['id']}: target {query['target']} is not in the catalogue")
+ if catalogue.competitor_kind(by_id[query["target"]], query) != "full":
+ raise SystemExit(f"{query['id']}: target {query['target']} does not match all three attributes")
+
+ derived: dict[str, Any] = {"images": len(records), "requests": len(queries)}
+ per_form: dict[str, dict[str, Any]] = {}
+ beaten_by: dict[str, int] = {}
+ rows: list[dict[str, Any]] = []
- labels = {record["id"]: record["label"] for record in records}
- ranked = ranking.rank(query_vector, image_vectors)
+ for form in catalogue.FORMS:
+ positions = []
+ for query in queries:
+ ranked = catalogue.rank(query_vectors[f"{query['id']}/{form}"], image_vectors)
+ order = [name for name, _ in ranked]
+ position = order.index(query["target"]) + 1
+ positions.append(position)
+ if form == "full" and position != 1:
+ beaten = catalogue.competitor_kind(by_id[order[0]], query)
+ beaten_by[beaten] = beaten_by.get(beaten, 0) + 1
+ rows.append(
+ {
+ "query": query["id"],
+ "form": form,
+ "text": catalogue.phrase(form, query["colour"], query["material"], query["category"]),
+ "target": query["target"],
+ "rank": position,
+ "score": dict(ranked)[query["target"]],
+ "top": order[0],
+ "top_kind": catalogue.competitor_kind(by_id[order[0]], query),
+ }
+ )
+ first = sum(1 for position in positions if position == 1)
+ per_form[form] = {
+ "first": first,
+ "median_rank": statistics.median(positions),
+ "mean_rank": round(statistics.fmean(positions), 2),
+ "worst_rank": max(positions),
+ }
+ derived[f"first/{form}"] = first
print(f"{manifest['model']} at revision {manifest['model_revision']}")
print(f"{manifest['endpoint']}, recorded {manifest['run_date']}")
- print(f"query: {query['text']!r}")
print()
- print(f"{'rank':>4} {'score':>8} image")
- for position, (name, score) in enumerate(ranked, start=1):
- marker = " <- the query's subject" if name == TARGET else ""
- print(f"{position:>4} {score:>8.3f} {labels[name]}{marker}")
+ print(f"{len(records)} photographs, {len(queries)} requests, {len(catalogue.FORMS)} forms each, "
+ f"{len(calls)} calls recorded")
print()
+ print(f"{'request form':<34}{'ranks first':>12}{'median rank':>13}{'worst':>7}")
+ labels = {
+ "category": "the category alone",
+ "colour-category": "colour and category",
+ "material-category": "material and category",
+ "full": "colour, material and category",
+ }
+ for form in catalogue.FORMS:
+ stats = per_form[form]
+ print(f" {labels[form]:<32}{stats['first']:>7}/{len(queries):<4}"
+ f"{stats['median_rank']:>13}{stats['worst_rank']:>7}")
+ print()
+ if beaten_by:
+ print("When the full request did not win, what took first place:")
+ for kind in KIND_ORDER:
+ if kind in beaten_by:
+ print(f" {kind:<16}{beaten_by[kind]}")
+ else:
+ print("The full request took first place for every one of the requests.")
- derived_order = tuple(name for name, _ in ranked)
- if derived_order != ranking.EXPECTED_ORDER:
- raise SystemExit(
- "The ranking is not the published one.\n"
- f" published: {', '.join(ranking.EXPECTED_ORDER)}\n"
- f" derived: {', '.join(derived_order)}"
+ if args.emit:
+ Path(args.emit).write_text(
+ json.dumps({"derived": derived, "per_form": per_form, "beaten_by": beaten_by, "rows": rows}, indent=1)
+ + "\n",
+ encoding="utf-8",
)
+ print(f"\nwrote {args.emit}")
- top_name, top_score = ranked[0]
- if top_name != TARGET:
- raise SystemExit(f"The top result is {top_name!r}, not {TARGET!r}. The published claim no longer holds.")
- runner_up_name, runner_up_score = ranked[1]
- print(f"{len(records)} photographs, {ranking.DIMS}-dimensional vectors, one text query")
- print(f"the red leather handbag ranks first at {top_score:.3f}")
- print(f"the closest other photograph is the {labels[runner_up_name].lower()} at {runner_up_score:.3f}")
- gap = f"a gap of {top_score - runner_up_score:.3f}"
- # A cosine can legitimately be zero or negative, and neither divides into a
- # meaningful multiple. Only the ratio is conditional; the gap always prints.
- if runner_up_score > 0:
- print(f"{gap}, or {top_score / runner_up_score:.1f}x")
- else:
- print(gap)
+ mismatched = [key for key, value in PUBLISHED.items() if derived.get(key) != value]
+ if mismatched:
+ for key in mismatched:
+ print(f"MISMATCH {key}: recording gives {derived.get(key)}, the page publishes {PUBLISHED[key]}",
+ file=sys.stderr)
+ return 1
+ print("\nEvery published figure matches the recording.")
return 0
diff --git a/examples/rerank/README.md b/examples/rerank/README.md
index f53b4558f..eedc2d3a9 100644
--- a/examples/rerank/README.md
+++ b/examples/rerank/README.md
@@ -1,48 +1,82 @@
-# Rank exact primary-source passages
+# Rank by a relevance rule you write in the call
The runnable example behind [superlinked.com/rerank](https://superlinked.com/rerank).
## What this shows
-Four questions, each sent to `Qwen/Qwen3-Reranker-4B` with a handful of
-candidate passages, where every candidate is a verbatim excerpt from an official
-document:
+24 questions, each sent to `Qwen/Qwen3-Reranker-4B` against the same four
+candidate passages, five times: once with no instruction, and once under each of
+four relevance rules.
-- Pathward Financial's Form 10-K/A filed with the SEC
-- CMS's published Lower Limb Orthoses claim example
-- the NTSB's East Palestine illustrated digest
-- the Supreme Court's Coinbase v. Suski opinion
+Every candidate is a verbatim abstract from the Federal Register. Each case pairs
+a rulemaking's **final rule** with the **proposed rule** published under the same
+title, plus a final rule and a proposed rule from a second docket of the same
+agency on a neighbouring subject. The query is the shared docket title, so it
+names the subject and never says whether the rule is in force. Only the
+instruction can choose between a regulation already adopted and a proposal that
+is not.
-The questions are authored evaluation prompts. The passages are not. Every
-candidate carries its source URL, its locator inside that document and the
-SHA-256 of its text, in `inputs/cases.json` and `inputs/sources.json`, and
-nothing here is synthetic or paraphrased.
+Ground truth is the Federal Register's own `type` field. Nothing in this example
+decides which document is in force.
-The page publishes a score pair per case, at three decimals, and `score.py`
-re-derives all four from the recorded responses offline:
+## What the run found
-| case | first | closest other candidate |
-|---|---|---|
-| NTSB detector alerts | `ntsb-salem-noncritical` 1.000 | `ntsb-help-desk-process` 0.992 |
-| Coinbase v. Suski | `scotus-two-contract-holding` 1.000 | `scotus-one-contract-rule` 0.439 |
-| CMS L1851 claim | `cms-missing-documentation` 1.000 | `cms-seven-month-evidence` 0.816 |
-| SEC filing amendment | `sec-non-reliance` 1.000 | `sec-amendment-scope` 0.107 |
+```
+With no relevance rule in the call, the document at rank 1 was
+ a regulation already in force 24/24
+ a proposal not yet adopted 0/24
+
+rule stated in the call right document right kind
+ in-force 16/24 19/24
+ proposed 20/24 21/24
+ in-force-positive 21/24 23/24 (published)
+ proposed-positive 16/24 17/24 (published)
+```
+
+Two things, both worth reading twice.
+
+The reranker has a prior. Asked a question with no relevance rule attached, it
+returned a regulation already in force in **all 24** questions and a pending
+proposal in **none**. That is not a length or a keyword effect: the proposal
+abstracts are the longer ones on average, and query word overlap is tied between
+the two in 18 of the 24 cases.
+
+Stating the rule overrides the prior. Ask for the proposal and one leads in 17 of
+24, up from 0. The two published rules put a **different** document first in 16
+of the 24 questions, over an identical candidate set and an identical query.
+
+Stating the rule the model already follows does not help. `in-force-positive`
+scores 21 of 24 against a 23 of 24 baseline. An instruction is worth writing when
+your definition of relevant differs from the model's, not when it agrees.
+
+## Why four rules, and which two the page shows
+
+The first recording used rules ending in a negative clause ("a change that has
+only been proposed is not relevant, however closely it matches the subject").
+That pair scored 36 of 48 summed over both directions, and the "in force"
+direction came out *worse* than no instruction at all, 16 of 24 against 23.
+
+A second wording was registered before it was run, in the two `-positive` rules,
+which state only what to retrieve and never what to exclude. The decision rule
+was fixed in advance: publish whichever pair scores higher summed over both
+directions. The positive pair took it, 37 of 48 against 36 — by a single case,
+which is well inside the noise of a 24-case set, and the README says so rather
+than dressing one point up as a finding.
-The 0.992 is the interesting one. That near-match names the Wayside Help Desk
-and the alert process, so it answers half the question, and the passage that
-answers both halves still comes first.
+All four arms are in `calls.json`. The pair the page does not display is
+recomputable from the same file.
## Run it
The code is in this repository. The inputs and the recorded responses are in the
public Hugging Face dataset
[`superlinked/sie-task-evidence`](https://huggingface.co/datasets/superlinked/sie-task-evidence),
-so a clone alone is no longer enough. Fetch, then score:
+so a clone alone is not enough. Fetch, then score:
```sh
python3 fetch.py # downloads the pinned revision into data/
python3 score.py # reproduces every published figure offline
-python3 run.py --check # rebuilds all four recorded calls from the inputs
+python3 run.py --check # rebuilds all 120 recorded calls from the inputs
python3 -m unittest discover -s tests
```
@@ -53,87 +87,72 @@ before the scorer sees it. It replaces `--dest` wholesale, so it refuses to touc
anything without the `.sie-evidence` marker it writes, and it swaps the new
directory in by rename rather than deleting the old one first.
-To call a reranker yourself. This is the only part that needs the SDK, and the
-only command here that spends anything:
+To record against SIE Cloud yourself. This is the only part that needs the SDK,
+and the only command here that spends anything:
```sh
uv sync
-SIE_BASE_URL=https://your-cluster.example SIE_API_KEY=... \
- uv run python run.py --record --out run-output/calls.json
+SIE_API_KEY=... uv run python run.py --record
```
`run.py` sends through `sie_sdk.SIEClient`. The import is deferred into `main()`,
so `--check` and `--show` keep working on a bare `python3` with nothing
-installed. `python3 run.py --show ntsb_detector_alert` prints a call without
-sending it.
-
-## What to expect
-
-```
-4 cases, model Qwen/Qwen3-Reranker-4B
-
- sec_filing_amendment 4 candidates sec-non-reliance 1.000 next sec-amendment-scope 0.107
- cms_lower_limb_orthosis 5 candidates cms-missing-documentation 1.000 next cms-seven-month-evidence 0.816
- ntsb_detector_alert 4 candidates ntsb-salem-noncritical 1.000 next ntsb-help-desk-process 0.992
- scotus_two_contracts 4 candidates scotus-two-contract-holding 1.000 next scotus-one-contract-rule 0.439
-
-4 of 4 cases rank the expected primary-source passage first
-17 candidates scored exactly once across the 4 cases
-
-Reproduced the four score pairs the page prints: 1.000/0.992, 1.000/0.439, 1.000/0.816, 1.000/0.107
-```
-
-`score.py` exits nonzero if any figure fails to reproduce. `run.py --check`
-prints `4 of 4 recorded calls rebuilt from the inputs and matched`, and fails if
-a call is missing, recorded twice or implied by no case.
+installed. `python3 run.py --show air-plan-approval-pennsylvania` prints one
+case's five calls without sending any of them.
## How the figures are derived
-The two sides of every comparison come from different places. The expected top
-candidate was registered in `inputs/cases.json` before the run. The ranks and
-scores are read out of the recorded responses in `calls.json`. The four score
-pairs `score.py` asserts against come from a third place again: the page.
-
-- **exact excerpts**: every candidate's text is hashed and compared with the
- digest recorded beside it and with the canonical digest in
- `inputs/sources.json`. Rewriting a passage and its own declared digest
- together is not enough; the canonical entry has to agree as well.
-- **fail closed**: a wrong model id, a wrong query id, a missing or duplicated
- candidate, an incomplete rank sequence, or a score that is not a finite number
- stops the run rather than producing a figure.
-- **three decimals**: the page rounds with `toFixed(3)` and so does `score.py`.
- The unrounded values are in `calls.json`.
+The two sides of every comparison come from different places. The document each
+rule asks for was derived from the Federal Register's `type` field and written
+into `inputs/cases.json` before the run. The ranks come out of the recorded
+responses in `calls.json`. The figures `score.py` asserts against come from a
+third place again: the page, pinned in `score.py`'s own source, so editing the
+fetched evidence alone will not satisfy it.
+
+- **fail closed**: a missing call, a non-200 status, a response scoring a
+ different candidate set than the inputs list, or a recording made against
+ another model revision stops the run rather than producing a figure.
+- **absent data is a failure, never a skip**. A case with no recorded call does
+ not quietly leave the denominator.
+- **a count is not a set**: the check compares scored item identities against the
+ candidate list, so a duplicated row does not pass on row count alone.
+
+`tests/test_example.py` tamper-tests each of those. The sharpest one trades two
+responses between arms of the same case: every digest, every count and every
+rebuilt request envelope survives it, `run.py --check` still returns 0, and only
+the figures pinned in `score.py` refuse it.
## What is in the dataset
```
rerank/
- inputs/cases.json 4 cases: the query, its provenance, the candidate
- passages with locators and digests, and the passage
- registered as the expected first result
- inputs/sources.json the four source documents, with a canonical digest and
- locator for every excerpt drawn from them
- calls.json 4 calls: the SDK call envelope, the response, the status
- and the latency, one file
- manifest.json the server release and commit, the model revision, the
- hardware, the run window and a digest for every file
+ inputs/cases.json 24 cases: the query, the agency, the two dockets, the four
+ candidate abstracts with their Federal Register type,
+ document number and URL, and the document each rule asks
+ for; plus the four rule texts
+ calls.json 120 calls: the SDK call envelope including the instruction
+ sent, the response, the status and the latency, one file
+ manifest.json the endpoint, the model and its revision, the deployment
+ revision, the run date and a digest for every file
```
-The four calls were eight separate JSON files under `verified-run/` in this
-repository. Merging them changed no byte of any envelope or response.
-
## What this does NOT establish
-- **Four questions are a demonstration.** No score here generalises to your
- corpus, and 17 candidates is not a benchmark.
-- **The 1.000 is not a probability.** SIE's score response exposes `item_id`,
- `score`, `rank` and token usage. The model's internal yes/no logits are not
- part of the public API response, so nothing here reconstructs them.
-- **The saved latencies are provenance, not timings.** The first call of the run
- includes model loading, at 29.3 seconds against 0.1 to 0.2 for the rest.
-- **No endpoint is recorded.** The run predates this example recording one. The
- manifest names public SIE v0.6.23 at commit `9d6ca6b0`, running on an L4 in
- Modal on 2026-07-24, which is what was known.
+- **24 questions are a demonstration, not a benchmark.** No figure here
+ generalises to your corpus, and one document type axis is not a study of
+ instruction following.
+- **The corpus is one kind of hard.** Adopted-versus-proposed is a distinction
+ the passages themselves express. A rule that depends on metadata the passage
+ never states does not work this way: two earlier designs, one keyed on which
+ RFC in a lineage is current and one on an IETF document's standards-track
+ status, came out at or near chance, because an abstract does not say whether
+ it has since been obsoleted. An instruction can only apply a rule the text
+ supports.
+- **One case is not attributable.** The 37-to-36 margin between the two wordings
+ is a single question out of 48.
+- **The scores are not probabilities.** SIE's score response exposes `item_id`,
+ `score` and `rank`. The model's internal logits are not part of the public API
+ response, so nothing here reconstructs them.
- **No tamper resistance.** The digests catch a truncated or corrupted download.
They are not a provenance chain.
diff --git a/examples/rerank/fetch.py b/examples/rerank/fetch.py
index 83df9af74..f70518c0f 100644
--- a/examples/rerank/fetch.py
+++ b/examples/rerank/fetch.py
@@ -41,8 +41,8 @@ from pathlib import Path
DATASET = "superlinked/sie-task-evidence"
TASK = "rerank"
-REVISION = "61593491d9a1b6a46c6a03964dd6349df403264b"
-MANIFEST_SHA256 = "1f95345b1617175b389927bfeaae0a3558c9553c6034b7856ec25a9ac6d2572b"
+REVISION = "a29afadb98360232f5cd8372d5f784d6dde63edc"
+MANIFEST_SHA256 = "8f180c69052e35898d955e1100e74859bb5c92d0d690e86423fe3fffbbcc9221"
BASE = f"https://huggingface.co/datasets/{DATASET}/resolve/{REVISION}/{TASK}"
HTTP_OK = 200
@@ -78,6 +78,11 @@ def marker_bytes() -> bytes:
).encode("utf-8")
+def backup_path(dest: Path) -> Path:
+ """Where `dest` is moved aside to while the new tree is renamed into place."""
+ return dest.with_name(f"{dest.name}.previous-{os.getpid()}")
+
+
def refuse_reason(dest: Path) -> str | None:
"""Why `dest` must not be replaced, or None when replacing it is safe.
@@ -96,6 +101,17 @@ def refuse_reason(dest: Path) -> str | None:
if resolved == Path.home().resolve():
return f"{resolved} is your home directory"
+ # The backup path is one this script names, which is not the same as one it
+ # owns. If something else already sits there, moving `dest` onto it destroys
+ # that something. Checked here so the refusal is reported by the same path
+ # as every other refusal, before anything is downloaded.
+ backup = backup_path(dest)
+ if backup.exists():
+ return (
+ f"{backup} already exists, and this script would move {dest} onto it. "
+ f"Move {backup} aside, or pass --dest somewhere else."
+ )
+
if dest.is_symlink():
return f"{dest} is a symlink"
if not dest.exists():
@@ -127,9 +143,12 @@ def swap_into_place(staging: Path, dest: Path) -> None:
"""
previous = None
if dest.exists():
- previous = dest.with_name(f"{dest.name}.previous-{os.getpid()}")
+ previous = backup_path(dest)
if previous.exists():
- shutil.rmtree(previous)
+ # refuse_reason checks this twice before we get here. Reaching it
+ # anyway means something appeared in between, and deleting it is
+ # never the right answer.
+ raise RuntimeError(f"refusing to replace {dest}: backup path {previous} already exists")
dest.replace(previous)
try:
staging.replace(dest)
diff --git a/examples/rerank/run.py b/examples/rerank/run.py
index 29d17d78f..7086a44b9 100644
--- a/examples/rerank/run.py
+++ b/examples/rerank/run.py
@@ -1,36 +1,34 @@
#!/usr/bin/env python3
-"""Send the /rerank calls to a SIE deployment, or check the recorded ones.
+"""Send the /rerank calls to SIE Cloud, or check the recorded ones.
python3 fetch.py
- python3 run.py --check # offline, no key, nothing installed
- python3 run.py --show <case-id> # offline, prints one call
- uv sync && uv run python run.py --record # live, needs a reranker endpoint
+ python3 run.py --check # offline, no key, nothing installed
+ python3 run.py --show <case-id> # offline, prints one call
+ uv sync && uv run python run.py --record
-Model Qwen/Qwen3-Reranker-4B
-Path /v1/score/Qwen/Qwen3-Reranker-4B
-Recorded run public SIE v0.6.23 on an L4 in Modal, 2026-07-24. The run did not
- save its base URL, so calls.json and manifest.json record the
- runtime, the server commit and the hardware instead of an endpoint.
+Endpoint https://api.superlinked.com
+Model Qwen/Qwen3-Reranker-4B
+Path /v1/score/Qwen/Qwen3-Reranker-4B
+
+Each case is sent once per arm against the same four candidates: with no
+instruction, and then under each relevance rule in `inputs/cases.json`. There
+are four of those, so five calls per case and 120 for the 24 cases. The page
+publishes two of the rules and the recording keeps all four. The query names
+the subject and never the status, so only the instruction can separate a
+regulation already adopted from a proposal on the same subject.
Calls go through `sie_sdk.SIEClient`, per AGENTS.md. The import is deferred into
main() so `--check` and `--show` run on a bare `python3` with nothing installed.
-`--check` rebuilds all four recorded call envelopes from `data/inputs/cases.json`
-and compares each with the recorded one. It is a bijection, not a walk over what
-is there: the expected call ids come from the inputs, one per case, so a call
-that is missing, recorded twice or implied by no case fails the check.
-
-What the envelope records is the SDK call, not the wire body: `client.score`
-takes a query Item and a list of candidate Items, and `source_id` and
-`source_excerpt_sha256` are provenance fields the SIE payload does not carry.
-That was true when this run was recorded and it is still true; the field names
-say so rather than pretending to be a request body.
+`--check` rebuilds every recorded call envelope from `data/inputs/cases.json`
+and compares it with the recorded one. It is a bijection, not a walk over what
+is there: the expected call ids come from the inputs, one per case per arm, so a
+call that is missing, recorded twice or implied by no case fails the check.
"""
from __future__ import annotations
import argparse
-import hashlib
import json
import os
import sys
@@ -43,11 +41,17 @@ if TYPE_CHECKING:
MODEL = "Qwen/Qwen3-Reranker-4B"
PATH = f"/v1/score/{MODEL}"
-DEFAULT_ENDPOINT = "http://127.0.0.1:8080"
+ENDPOINT = "https://api.superlinked.com"
+
+# The revision GET /v1/models reports for these weights. run.py refuses to
+# record against another one, and score.py refuses to score a recording made
+# against another one, because different weights produce different scores.
+MODEL_REVISION = "22e683669bc0f0bd69640a1354a6d0aebcfeede5"
+
+BASELINE = "none"
REQUEST_SHAPE = (
- "the SDK call envelope run.py builds, not the wire body. "
- "source_id and source_excerpt_sha256 are provenance fields "
- "the SIE payload does not carry."
+ "the SDK call envelope run.py builds. `instruction` is a real request field; "
+ "`case` and `rule` are provenance fields the SIE payload does not carry."
)
RESPONSE_SHAPE = (
"the per-item result sie_sdk returned, unmodified. The SDK surfaces no server envelope and no response headers."
@@ -64,10 +68,6 @@ def load(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
-def sha256_text(value: str) -> str:
- return hashlib.sha256(value.encode("utf-8")).hexdigest()
-
-
def to_jsonable(value: Any) -> Any:
"""What the SDK returned, as plain JSON types and nothing else."""
if isinstance(value, dict):
@@ -81,56 +81,44 @@ def to_jsonable(value: Any) -> Any:
return value
-def failure_entry(case_id: str, endpoint: str, envelope: dict[str, Any], error: BaseException) -> dict[str, Any]:
- """What a failed call records.
+def arms(payload: dict[str, Any]) -> dict[str, str | None]:
+ """Every arm a case is sent under: the baseline first, then each rule."""
+ return {BASELINE: None, **payload["rules"]}
- Every field the success path writes, so that `check` and `score.py` read a
- calls.json holding failures instead of raising KeyError on it. Only the
- values differ: the status never reads as success, the response is null and
- `error` says what went wrong.
- """
- return {
- "id": f"page/{case_id}",
- "set": "page",
- "case": case_id,
- "model": MODEL,
- "endpoint": endpoint,
- "path": PATH,
- "status": "error",
- "error": {"type": type(error).__name__, "message": str(error)},
- "timing": {"latency_ms": None, "attempts": 1},
- "request": {"method": "SIEClient.score", "shape": REQUEST_SHAPE, "body": envelope},
- "response": None,
- "recorded": {},
- }
+def call_id(case_id: str, rule: str) -> str:
+ return f"{case_id}/{rule}"
-def build_envelope(case_id: str, case: dict[str, Any]) -> dict[str, Any]:
- """The SDK call this example makes for one case, as it is recorded."""
- return {
+
+def build_envelope(case: dict[str, Any], rule: str, instruction: str | None) -> dict[str, Any]:
+ """The SDK call this example makes for one case under one rule."""
+ envelope: dict[str, Any] = {
"method": "SIEClient.score",
"endpoint": PATH,
"model": MODEL,
- "query": {"id": f"{case_id}-query", "text": case["query"]},
- "items": [
- {
- "id": candidate["id"],
- "text": candidate["text"],
- "source_id": candidate["source_id"],
- "source_excerpt_sha256": candidate["sha256"],
- }
- for candidate in case["candidates"]
- ],
- "wait_for_capacity": True,
- "provision_timeout_s": 900,
+ "case": case["id"],
+ "rule": rule,
+ "query": {"id": f"{case['id']}-query", "text": case["query"]},
+ "items": [{"id": candidate["id"], "text": candidate["text"]} for candidate in case["candidates"]],
}
+ if instruction is not None:
+ envelope["instruction"] = instruction
+ return envelope
+
+
+def expected_calls(payload: dict[str, Any]) -> dict[str, tuple[dict[str, Any], str, str | None]]:
+ out = {}
+ for case in payload["cases"]:
+ for rule, instruction in arms(payload).items():
+ out[call_id(case["id"], rule)] = (case, rule, instruction)
+ return out
def check(data_dir: Path) -> int:
- cases = load(data_dir / "inputs/cases.json")["cases"]
+ payload = load(data_dir / "inputs/cases.json")
calls = load(data_dir / "calls.json")["calls"]
- expected = {f"page/{case_id}": (case_id, case) for case_id, case in cases.items()}
+ expected = expected_calls(payload)
recorded: dict[str, dict[str, Any]] = {}
duplicates: list[str] = []
for call in calls:
@@ -144,59 +132,82 @@ def check(data_dir: Path) -> int:
rebuilt = 0
mismatched: list[str] = []
- for call_id in sorted(set(expected) & set(recorded)):
- call = recorded[call_id]
- case_id, case = expected[call_id]
- if call["case"] != case_id:
- mismatched.append(f"{call_id}: case {call['case']} differs from {case_id}")
- elif call["model"] != MODEL:
- mismatched.append(f"{call_id}: model {call['model']} differs from {MODEL}")
+ for identifier in sorted(set(expected) & set(recorded)):
+ call = recorded[identifier]
+ case, rule, instruction = expected[identifier]
+ if call["model"] != MODEL:
+ mismatched.append(f"{identifier}: model {call['model']} differs from {MODEL}")
elif call["path"] != PATH:
- mismatched.append(f"{call_id}: path {call['path']} differs from {PATH}")
- elif build_envelope(case_id, case) != call["request"]["body"]:
- mismatched.append(f"{call_id}: rebuilt envelope differs from the recorded one")
+ mismatched.append(f"{identifier}: path {call['path']} differs from {PATH}")
+ elif build_envelope(case, rule, instruction) != call["request"]["body"]:
+ mismatched.append(f"{identifier}: rebuilt envelope differs from the recorded one")
else:
rebuilt += 1
print(f"{rebuilt} of {len(calls)} recorded calls rebuilt from the inputs and matched")
- print(f"{len(expected)} calls expected from {len(cases)} cases, {len(recorded)} recorded")
- for call_id in missing:
- print(f"MISSING {call_id}: expected from the inputs, absent from calls.json", file=sys.stderr)
- for call_id in duplicates:
- print(f"DUPLICATE {call_id}: recorded more than once", file=sys.stderr)
- for call_id in unexpected:
- print(f"UNEXPECTED {call_id}: recorded but no case in inputs/cases.json implies it", file=sys.stderr)
+ print(f"{len(expected)} calls expected from {len(payload['cases'])} cases, {len(recorded)} recorded")
+ for identifier in missing:
+ print(f"MISSING {identifier}: expected from the inputs, absent from calls.json", file=sys.stderr)
+ for identifier in duplicates:
+ print(f"DUPLICATE {identifier}: recorded more than once", file=sys.stderr)
+ for identifier in unexpected:
+ print(f"UNEXPECTED {identifier}: recorded but no case in inputs/cases.json implies it", file=sys.stderr)
for line in mismatched:
print(f"MISMATCH {line}", file=sys.stderr)
- if missing or duplicates or unexpected or mismatched:
- return 1
- return 0
+ return 1 if (missing or duplicates or unexpected or mismatched) else 0
+
+def served_revision(client: Any) -> str:
+ """The model revision the endpoint reports for itself, via GET /v1/models.
-def record(client: SIEClient, endpoint: str, case_id: str, case: dict[str, Any]) -> dict[str, Any]:
- """Send one case through the SDK and return its calls.json entry."""
+ Raises rather than returning a placeholder. A run that cannot establish
+ which weights answered has nothing to record.
+ """
+ try:
+ listed = client.list_models()
+ except Exception as error:
+ raise SystemExit(f"Could not read the model revision from /v1/models: {error}") from error
+ for model in listed if isinstance(listed, list) else listed.get("models", []):
+ if isinstance(model, dict) and model.get("name") == MODEL:
+ revision = model.get("revision") or ""
+ if not revision:
+ raise SystemExit(f"/v1/models lists {MODEL} with no revision")
+ return revision
+ raise SystemExit(f"/v1/models does not list {MODEL}")
+
+
+def record(
+ client: SIEClient, base_url: str, case: dict[str, Any], rule: str, instruction: str | None
+) -> dict[str, Any]:
+ """Send one case under one rule and return its calls.json entry."""
from sie_sdk import Item # noqa: PLC0415
- envelope = build_envelope(case_id, case)
+ envelope = build_envelope(case, rule, instruction)
+ kwargs = {"wait_for_capacity": True, "provision_timeout_s": 900}
+ if instruction is not None:
+ kwargs["instruction"] = instruction
started = time.monotonic()
result = client.score(
MODEL,
- Item(id=f"{case_id}-query", text=case["query"]),
+ Item(id=f"{case['id']}-query", text=case["query"]),
[Item(id=candidate["id"], text=candidate["text"]) for candidate in case["candidates"]],
- wait_for_capacity=True,
- provision_timeout_s=900,
+ **kwargs,
)
latency_ms = round((time.monotonic() - started) * 1000, 3)
body = to_jsonable(result)
# A 200 is not a result. Refuse anything without scores to read.
if not isinstance(body, dict) or not body.get("scores"):
- raise CallFailedError(f"{case_id}: response carried no scores")
+ raise CallFailedError(f"{case['id']}/{rule}: response carried no scores")
+ returned = {entry["item_id"] for entry in body["scores"]}
+ sent = {candidate["id"] for candidate in case["candidates"]}
+ if returned != sent:
+ raise CallFailedError(f"{case['id']}/{rule}: scored {sorted(returned)}, sent {sorted(sent)}")
return {
- "id": f"page/{case_id}",
- "set": "page",
- "case": case_id,
+ "id": call_id(case["id"], rule),
+ "case": case["id"],
+ "rule": rule,
"model": MODEL,
- "endpoint": endpoint,
+ "endpoint": base_url,
"path": PATH,
"status": 200,
"timing": {"latency_ms": latency_ms, "attempts": 1},
@@ -206,59 +217,106 @@ def record(client: SIEClient, endpoint: str, case_id: str, case: dict[str, Any])
}
+def failure_entry(
+ case: dict[str, Any], rule: str, base_url: str, envelope: dict[str, Any], error: BaseException
+) -> dict[str, Any]:
+ """What a failed call records: every field the success path writes."""
+ return {
+ "id": call_id(case["id"], rule),
+ "case": case["id"],
+ "rule": rule,
+ "model": MODEL,
+ "endpoint": base_url,
+ "path": PATH,
+ "status": "error",
+ "error": {"type": type(error).__name__, "message": str(error)},
+ "timing": {"latency_ms": None, "attempts": 1},
+ "request": {"method": "SIEClient.score", "shape": REQUEST_SHAPE, "body": envelope},
+ "response": None,
+ "recorded": {},
+ }
+
+
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--data", default="data", help="fetched evidence directory")
parser.add_argument("--check", action="store_true", help="offline check, the default")
- parser.add_argument("--show", metavar="CASE", help="print one call and exit, sending nothing")
+ parser.add_argument("--show", metavar="CASE", help="print one case's calls and exit, sending nothing")
parser.add_argument("--record", action="store_true", help="make live calls")
- parser.add_argument("--out", default="run-output/calls.json", help="where --record writes")
+ parser.add_argument("--out", default="run-output", help="directory --record writes")
+ parser.add_argument(
+ "--allow-revision-mismatch",
+ action="store_true",
+ help="record even if the endpoint serves a revision other than the published one",
+ )
args = parser.parse_args()
data_dir = Path(args.data)
- cases = load(data_dir / "inputs/cases.json")["cases"]
+ payload = load(data_dir / "inputs/cases.json")
+ by_id = {case["id"]: case for case in payload["cases"]}
if args.show:
- if args.show not in cases:
- raise SystemExit(f"Unknown case: {args.show}. Known: {', '.join(cases)}")
- print(json.dumps(build_envelope(args.show, cases[args.show]), indent=2, ensure_ascii=False))
+ case = by_id.get(args.show)
+ if case is None:
+ raise SystemExit(f"Unknown case: {args.show}. Known: {', '.join(by_id)}")
+ for rule, instruction in arms(payload).items():
+ print(json.dumps(build_envelope(case, rule, instruction), indent=2, ensure_ascii=False))
return 0
if not args.record:
return check(data_dir)
- # Sanity-check the excerpts before spending anything on them: a rewritten
- # candidate must not reach the model as though it were a source quotation.
- sources = load(data_dir / "inputs/sources.json")["sources"]
- for case_id, case in cases.items():
- for candidate in case["candidates"]:
- canonical = sources.get(candidate["source_id"], {}).get("excerpts", {}).get(candidate["id"])
- if canonical is None or sha256_text(candidate["text"]) != canonical["sha256"]:
- raise SystemExit(f"{case_id}/{candidate['id']}: excerpt does not match inputs/sources.json")
-
- endpoint = os.environ.get("SIE_CLUSTER_URL") or os.environ.get("SIE_BASE_URL") or DEFAULT_ENDPOINT
- api_key = os.environ.get("SIE_API_KEY") or None
- # Deferred so --check and --show run on a bare `python3` with nothing installed.
+ base_url = os.environ.get("SIE_BASE_URL") or os.environ.get("SIE_CLUSTER_URL") or ENDPOINT
+ api_key = os.environ.get("SIE_API_KEY", "").strip()
+ if not api_key:
+ raise SystemExit("Set SIE_API_KEY. To check the published figures without a key, run score.py instead.")
+
from sie_sdk import SIEClient # noqa: PLC0415
- client = SIEClient(endpoint, api_key=api_key, timeout_s=900)
+ client = SIEClient(base_url, api_key=api_key, timeout_s=900)
+ base_url = client.base_url.rstrip("/")
+ print(f"endpoint {base_url}{PATH}", file=sys.stderr)
+
+ # Checked before anything is scored, so a mismatch costs no credits.
+ model_revision = served_revision(client)
+ print(f"revision {model_revision}", file=sys.stderr)
+ if model_revision != MODEL_REVISION and not args.allow_revision_mismatch:
+ raise SystemExit(
+ f"This endpoint serves {model_revision!r} and this example publishes {MODEL_REVISION!r}.\n"
+ "Different weights produce different scores, and score.py rejects a recording made against "
+ "another revision.\nRe-run with --allow-revision-mismatch to record anyway, for your own "
+ "comparison rather than to reproduce the published figures."
+ )
- calls = []
+ calls: list[dict[str, Any]] = []
failed: list[str] = []
- for case_id, case in cases.items():
- try:
- entry = record(client, endpoint, case_id, case)
- except Exception as error: # noqa: BLE001
- failed.append(f"page/{case_id}: {type(error).__name__}: {error}")
- calls.append(failure_entry(case_id, endpoint, build_envelope(case_id, case), error))
- print(f"{case_id}: FAILED {type(error).__name__}", file=sys.stderr)
- continue
- calls.append(entry)
- print(f"{case_id}: {entry['timing']['latency_ms']:.0f}ms", file=sys.stderr)
+ for case in payload["cases"]:
+ for rule, instruction in arms(payload).items():
+ try:
+ entry = record(client, base_url, case, rule, instruction)
+ except Exception as error: # noqa: BLE001
+ failed.append(f"{call_id(case['id'], rule)}: {type(error).__name__}: {error}")
+ calls.append(failure_entry(case, rule, base_url, build_envelope(case, rule, instruction), error))
+ print(f"{call_id(case['id'], rule)}: FAILED {type(error).__name__}", file=sys.stderr)
+ continue
+ calls.append(entry)
+ print(f"{entry['id']}: {entry['timing']['latency_ms']:.0f}ms", file=sys.stderr)
+
+ # Re-read after the last call. The preflight proves the weights were right
+ # when the run started; this proves they did not roll over while it was in
+ # flight, which would leave the manifest attributing scores to a checkpoint
+ # that did not produce all of them.
+ final_revision = served_revision(client)
+ if final_revision != model_revision:
+ raise SystemExit(
+ f"The endpoint served {model_revision!r} before these calls and {final_revision!r} after them. "
+ "The recording spans two checkpoints, so it is not written out. Re-run it."
+ )
- out_path = Path(args.out)
- out_path.parent.mkdir(parents=True, exist_ok=True)
- out_path.write_text(
+ deployment = sorted({c["recorded"].get("model_revision") for c in calls if c["recorded"].get("model_revision")})
+ out_dir = Path(args.out)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ (out_dir / "calls.json").write_text(
json.dumps(
{
"task": "rerank",
@@ -267,16 +325,36 @@ def main() -> int:
"complete": not failed,
"calls": calls,
},
- indent=2,
+ indent=1,
+ ensure_ascii=False,
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ (out_dir / "manifest-partial.json").write_text(
+ json.dumps(
+ {
+ "task": "rerank",
+ "endpoint": base_url,
+ "path": PATH,
+ "model": MODEL,
+ "model_revision": model_revision,
+ "deployment_revision": deployment[0] if len(deployment) == 1 else deployment,
+ "run_date": time.strftime("%Y-%m-%d", time.gmtime()),
+ "recorded_by": "examples/rerank/run.py",
+ "cases": len(payload["cases"]),
+ "arms": list(arms(payload)),
+ "calls_recorded": len(calls),
+ },
+ indent=1,
ensure_ascii=False,
)
+ "\n",
encoding="utf-8",
)
- print(f"wrote {out_path}")
+ print(f"wrote {out_dir}/calls.json", file=sys.stderr)
if failed:
- # A run that failed must not look like a run that succeeded.
- print(f"{len(failed)} of {len(cases)} calls FAILED:", file=sys.stderr)
+ print(f"{len(failed)} of {len(calls)} calls FAILED:", file=sys.stderr)
for line in failed:
print(f" {line}", file=sys.stderr)
return 1
diff --git a/examples/rerank/score.py b/examples/rerank/score.py
index b0cd37f33..f5bf1c485 100644
--- a/examples/rerank/score.py
+++ b/examples/rerank/score.py
@@ -1,63 +1,75 @@
#!/usr/bin/env python3
-"""Reproduce the /rerank page figures from the recorded calls.
+"""Reproduce the /rerank page's published figures from the recorded calls.
python3 fetch.py
python3 score.py
-The page publishes no percentage. What it publishes is a pair of scores per
-case, rounded to three decimals, and the claim that the complete-evidence
-passage is the one on top. This script re-derives both offline, with no API
-key and no inference spend, and exits nonzero if any of them fails.
-
- 4 of 4 cases rank the expected primary-source passage first
- 1.000 / 0.992 the Salem alert over the Wayside Help Desk process
- 1.000 / 0.439 the two-contract holding over the one-contract rule
- 1.000 / 0.816 the missing-documentation denial over seven-month evidence
- 1.000 / 0.107 the non-reliance statement over the amendment's scope
-
-The two sides of every comparison come from different places. The expected top
-candidate and every excerpt digest were registered in inputs/cases.json before
-the run. The ranks and scores are read out of the recorded API responses in
-calls.json. Neither is derived from the other, and the four score pairs in
-EXPECTED below come from a third place again: the page.
-
-The excerpt checks that used to run inside the runner run here too, so moving
-the bytes to Hugging Face did not drop them. Every candidate's text is hashed
-and compared with the digest recorded beside it and with the canonical digest
-in inputs/sources.json, and a rewritten excerpt fails even when both copies of
-its declared digest are rewritten with it.
+Standard library only. No API key, no network, no inference spend.
+
+Each of the 24 questions was sent five times against the same four candidates:
+once with no instruction, and once under each of four relevance rules. The query
+names the subject of a rulemaking and never says whether the rule is in force,
+so only the instruction can choose between a regulation already adopted and a
+proposal on the same subject.
+
+Two figures come out of that, per arm, over the 24 cases:
+
+ exact how often rank 1 is the one document the rule asks for: the right
+ document type AND the docket the question is about.
+ by type how often rank 1 is a document of the type the rule asks for,
+ whichever docket it came from.
+
+The expected winner for each case and rule is pinned in inputs/cases.json, which
+derives it mechanically from the Federal Register's own document type. Nothing
+here decides which document is in force.
+
+Absent data is a failure, never a skip. A case with no recorded call, a call
+with no response, or a response that scored a different candidate set than the
+inputs list, fails the run and is named.
"""
from __future__ import annotations
import argparse
-import hashlib
import json
-import math
import sys
from pathlib import Path
from typing import Any
-HTTP_OK = 200
MODEL = "Qwen/Qwen3-Reranker-4B"
-# The page prints a pair per case, so a case with nothing to compare against
-# cannot produce the figure. Refused rather than indexed into.
-MIN_CANDIDATES = 2
-
-# What the page prints, at the page's own three decimals: the winner and the
-# closest other candidate for each case. Typed out from the rendered page, not
-# computed from the recordings, so agreement means something.
-EXPECTED = {
- "sec_filing_amendment": ("sec-non-reliance", "1.000", "sec-amendment-scope", "0.107"),
- "cms_lower_limb_orthosis": ("cms-missing-documentation", "1.000", "cms-seven-month-evidence", "0.816"),
- "ntsb_detector_alert": ("ntsb-salem-noncritical", "1.000", "ntsb-help-desk-process", "0.992"),
- "scotus_two_contracts": ("scotus-two-contract-holding", "1.000", "scotus-one-contract-rule", "0.439"),
+MODEL_REVISION = "22e683669bc0f0bd69640a1354a6d0aebcfeede5"
+BASELINE = "none"
+
+# Which candidate role each rule asks for, and which document type that role is.
+ASKS_FOR = {
+ "in-force": ("asked-about-final", "Rule"),
+ "proposed": ("asked-about-proposal", "Proposed Rule"),
+ "in-force-positive": ("asked-about-final", "Rule"),
+ "proposed-positive": ("asked-about-proposal", "Proposed Rule"),
}
-EXPECTED_CANDIDATES = {
- "sec_filing_amendment": 4,
- "cms_lower_limb_orthosis": 5,
- "ntsb_detector_alert": 4,
- "scotus_two_contracts": 4,
+
+# The two arms https://superlinked.com/rerank displays. The other two are the
+# pre-registered wording test recorded alongside them; calls.json holds all
+# four, so a reader can recompute the pair that is not displayed.
+PUBLISHED_ARMS = ("in-force-positive", "proposed-positive")
+
+# Published figures, pinned in the committed source so the scorer compares what
+# it derives from the recording against something the recording cannot move.
+# Editing the fetched evidence alone will not satisfy this.
+PUBLISHED = {
+ "cases": 24,
+ "calls": 120,
+ "none/exact/asked-about-final": 23,
+ "none/exact/asked-about-proposal": 0,
+ "none/type/Rule": 24,
+ "none/type/Proposed Rule": 0,
+ "in-force-positive/exact": 21,
+ "in-force-positive/type": 23,
+ "proposed-positive/exact": 16,
+ "proposed-positive/type": 17,
+ "in-force/exact": 16,
+ "proposed/exact": 20,
+ "top1_differs_between_published_rules": 16,
}
@@ -67,159 +79,124 @@ def load(path: Path) -> Any:
return json.loads(path.read_text(encoding="utf-8"))
-def sha256_text(value: str) -> str:
- return hashlib.sha256(value.encode("utf-8")).hexdigest()
-
-
-def verify_inputs(cases: dict[str, Any], sources: dict[str, Any]) -> None:
- """Every candidate is the verbatim excerpt its two manifests claim.
-
- Carried unchanged from the runner this example shipped before the evidence
- moved to Hugging Face. A candidate whose text was rewritten fails here even
- when the digest recorded beside it was rewritten to match, because the
- canonical digest in sources.json has to agree as well.
- """
- if cases.get("integrity_policy", {}).get("synthetic_or_paraphrased_evidence") is not False:
- raise SystemExit("inputs/cases.json must reject synthetic or paraphrased evidence")
- if sources.get("synthetic_or_paraphrased_evidence") is not False:
- raise SystemExit("inputs/sources.json must reject synthetic evidence")
- if cases.get("model") != MODEL:
- raise SystemExit(f"inputs/cases.json names {cases.get('model')}, expected {MODEL}")
-
- known = sources["sources"]
- for case_id, case in cases["cases"].items():
- seen: set[str] = set()
- for candidate in case["candidates"]:
- candidate_id = candidate["id"]
- if candidate_id in seen:
- raise SystemExit(f"{case_id}: candidate {candidate_id} appears twice")
- seen.add(candidate_id)
- source = known.get(candidate["source_id"])
- if source is None:
- raise SystemExit(f"{candidate_id}: no source {candidate['source_id']} in sources.json")
- actual = sha256_text(candidate["text"])
- if actual != candidate["sha256"]:
- raise SystemExit(f"{candidate_id}: excerpt does not match the digest recorded beside it")
- canonical = source.get("excerpts", {}).get(candidate_id)
- if canonical is None:
- raise SystemExit(f"{candidate_id}: no canonical excerpt in sources.json")
- if candidate["locator"] != canonical["locator"] or actual != canonical["sha256"]:
- raise SystemExit(f"{candidate_id}: excerpt does not match the canonical one in sources.json")
- if case["expected_top_candidate_id"] not in seen:
- raise SystemExit(f"{case_id}: expected top candidate is not one of its candidates")
-
-
-def scored_calls(payload: dict[str, Any]) -> dict[str, dict[str, Any]]:
- """The recorded calls, refusing anything that failed or repeats a case.
-
- A recorder that hit an error writes the call with status "error" and sets
- `complete` to false. Scoring such a file would turn a failed run into a
- published number, so it stops here instead.
- """
- if payload.get("complete") is False:
- failed = payload.get("failed_calls", "some")
- raise SystemExit(f"refusing to score: {failed} calls in this calls.json failed, so it is not a complete run")
- by_case: dict[str, dict[str, Any]] = {}
- for call in payload["calls"]:
- if call.get("status") != HTTP_OK:
- raise SystemExit(f"refusing to score {call['id']}: status {call.get('status')}")
- if call["case"] in by_case:
- raise SystemExit(f"two calls recorded for {call['case']}")
- by_case[call["case"]] = call
- return by_case
-
-
-def ranked(case_id: str, case: dict[str, Any], body: dict[str, Any]) -> list[dict[str, Any]]:
- """The response rows in rank order, with the checks the runner applied.
-
- Fail-closed, in the same order the runner used: wrong model, wrong query
- id, missing or duplicated candidates, incomplete ranks, or a score that is
- not a finite number all stop the run rather than producing a figure.
- """
- if body.get("model") != MODEL:
- raise SystemExit(f"{case_id}: response names model {body.get('model')}")
- if body.get("query_id") != f"{case_id}-query":
- raise SystemExit(f"{case_id}: response names query {body.get('query_id')}")
- rows = body.get("scores")
- if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
- raise SystemExit(f"{case_id}: response carries no score list")
-
- expected_ids = {candidate["id"] for candidate in case["candidates"]}
- observed_ids = {row.get("item_id") for row in rows}
- if observed_ids != expected_ids or len(rows) != len(expected_ids):
- raise SystemExit(f"{case_id}: scored {len(rows)} rows for {len(expected_ids)} candidates")
- ranks = sorted(row.get("rank") for row in rows)
- if ranks != list(range(len(rows))) or any(type(row["rank"]) is not int for row in rows):
- raise SystemExit(f"{case_id}: ranks are not 0..{len(rows) - 1}")
- for row in rows:
- score = row.get("score")
- if isinstance(score, bool) or not isinstance(score, (int, float)) or not math.isfinite(score):
- raise SystemExit(f"{case_id}: {row.get('item_id')} has a non-numeric score")
- return sorted(rows, key=lambda row: row["rank"])
+def main_with(data_dir: Path, emit: str | None = None) -> int:
+ """Score one fetched evidence directory. Returns the process exit status."""
+ payload = load(data_dir / "inputs/cases.json")
+ recording = load(data_dir / "calls.json")
+ # Required, not optional. This used to read `if manifest_path.exists() else {}`,
+ # which made the revision check below vanish when the manifest was absent, so
+ # deleting one file was enough to have a recording from other weights scored.
+ # Missing evidence is a failure, never a licence to skip the check over it.
+ manifest = load(data_dir / "manifest.json")
+
+ if manifest.get("model_revision") != MODEL_REVISION:
+ raise SystemExit(
+ f"This recording was made against model revision {manifest.get('model_revision')!r}, "
+ f"and this example publishes figures for {MODEL_REVISION!r}. Different weights produce "
+ "different scores, so the recording is not scored."
+ )
+ cases = {case["id"]: case for case in payload["cases"]}
+ arms = [BASELINE, *payload["rules"]]
+ calls = {call["id"]: call for call in recording["calls"]}
-def main() -> int:
- parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--data", default="data", help="fetched evidence directory")
- args = parser.parse_args()
- data_dir = Path(args.data)
-
- cases = load(data_dir / "inputs/cases.json")
- sources = load(data_dir / "inputs/sources.json")
- verify_inputs(cases, sources)
- calls = scored_calls(load(data_dir / "calls.json"))
-
- missing = [case_id for case_id in cases["cases"] if case_id not in calls]
- if missing:
- raise SystemExit("no call recorded for: " + ", ".join(missing))
- unexpected = [case_id for case_id in calls if case_id not in cases["cases"]]
- if unexpected:
- raise SystemExit("calls recorded for cases the inputs do not define: " + ", ".join(unexpected))
-
- first = 0
- candidates_scored = 0
failures: list[str] = []
- print(f"{len(cases['cases'])} cases, model {MODEL}\n")
- for case_id, case in cases["cases"].items():
- rows = ranked(case_id, case, calls[case_id]["response"]["body"])
- candidates_scored += len(rows)
- if len(rows) < MIN_CANDIDATES:
- raise SystemExit(f"{case_id}: {len(rows)} candidates, so there is no closest other candidate to report")
- top, runner_up = rows[0], rows[1]
- expected_top = case["expected_top_candidate_id"]
- if top["item_id"] == expected_top:
- first += 1
- else:
- failures.append(f"{case_id}: {expected_top} was registered first, {top['item_id']} ranked first")
- print(
- f" {case_id:<24} {len(rows)} candidates"
- f" {top['item_id']:<28} {top['score']:.3f}"
- f" next {runner_up['item_id']:<28} {runner_up['score']:.3f}"
- )
- want_top, want_top_score, want_next, want_next_score = EXPECTED[case_id]
- got = (top["item_id"], f"{top['score']:.3f}", runner_up["item_id"], f"{runner_up['score']:.3f}")
- if got != (want_top, want_top_score, want_next, want_next_score):
- failures.append(
- f"{case_id}: page prints {want_top} {want_top_score} over {want_next} {want_next_score},"
- f" recordings give {got[0]} {got[1]} over {got[2]} {got[3]}"
- )
- if len(rows) != EXPECTED_CANDIDATES[case_id]:
- failures.append(
- f"{case_id}: page says {EXPECTED_CANDIDATES[case_id]} candidates, recordings hold {len(rows)}"
- )
-
- print(f"\n{first} of {len(cases['cases'])} cases rank the expected primary-source passage first")
- print(f"{candidates_scored} candidates scored exactly once across the {len(cases['cases'])} cases")
+ top: dict[tuple[str, str], dict[str, str]] = {}
+ for case_id, case in cases.items():
+ roles = {c["id"]: (c["role"], c["type"]) for c in case["candidates"]}
+ for arm in arms:
+ identifier = f"{case_id}/{arm}"
+ call = calls.get(identifier)
+ if call is None:
+ failures.append(f"{identifier}: no recorded call")
+ continue
+ if call.get("status") != 200 or not call.get("response"):
+ failures.append(f"{identifier}: recorded status {call.get('status')!r}, no result to score")
+ continue
+ if call["model"] != MODEL:
+ failures.append(f"{identifier}: recorded against {call['model']}, not {MODEL}")
+ continue
+ # Per call, not just once per run: the manifest states one deployment
+ # and every call has to have come from it. Compared against the
+ # manifest's `deployment_revision` and NOT against MODEL_REVISION,
+ # because the SDK's `last_model_revision` is the SIE deployment
+ # digest that models served together share, not the HuggingFace
+ # revision of these weights. Checking it against MODEL_REVISION
+ # would reject all 120 of this example's own calls.
+ served = (call.get("recorded") or {}).get("model_revision")
+ if served != manifest.get("deployment_revision"):
+ failures.append(
+ f"{identifier}: served by deployment {served!r}, and the manifest "
+ f"records {manifest.get('deployment_revision')!r}"
+ )
+ continue
+ scored = {entry["item_id"] for entry in call["response"]["body"]["scores"]}
+ if scored != set(roles):
+ failures.append(f"{identifier}: scored {len(scored)} candidates, the inputs list {len(roles)}")
+ continue
+ winner = sorted(call["response"]["body"]["scores"], key=lambda s: s["rank"])[0]["item_id"]
+ role, kind = roles[winner]
+ top[(case_id, arm)] = {"id": winner, "role": role, "type": kind}
if failures:
- sys.stdout.flush()
- print("\nFAILED to reproduce the published figures:", file=sys.stderr)
+ print(f"{len(failures)} of {len(cases) * len(arms)} case/arm pairs could not be scored:", file=sys.stderr)
for line in failures:
print(f" {line}", file=sys.stderr)
+ print("No figure is derived from an incomplete recording.", file=sys.stderr)
return 1
- print("\nReproduced the four score pairs the page prints: 1.000/0.992, 1.000/0.439, 1.000/0.816, 1.000/0.107")
+
+ n = len(cases)
+ derived: dict[str, Any] = {"cases": n, "calls": len(recording["calls"])}
+ for role, kind in (("asked-about-final", "Rule"), ("asked-about-proposal", "Proposed Rule")):
+ derived[f"{BASELINE}/exact/{role}"] = sum(top[(c, BASELINE)]["role"] == role for c in cases)
+ derived[f"{BASELINE}/type/{kind}"] = sum(top[(c, BASELINE)]["type"] == kind for c in cases)
+ for arm in payload["rules"]:
+ role, kind = ASKS_FOR[arm]
+ derived[f"{arm}/exact"] = sum(top[(c, arm)]["role"] == role for c in cases)
+ derived[f"{arm}/type"] = sum(top[(c, arm)]["type"] == kind for c in cases)
+ a, b = PUBLISHED_ARMS
+ derived["top1_differs_between_published_rules"] = sum(top[(c, a)]["id"] != top[(c, b)]["id"] for c in cases)
+
+ print(f"model {MODEL} @ {MODEL_REVISION}")
+ print(f"corpus {n} questions, four Federal Register abstracts each, {len(recording['calls'])} calls recorded")
+ print()
+ print("With no relevance rule in the call, the document at rank 1 was")
+ print(f" a regulation already in force {derived[f'{BASELINE}/type/Rule']}/{n}")
+ print(f" a proposal not yet adopted {derived[f'{BASELINE}/type/Proposed Rule']}/{n}")
+ print()
+ print(f"{'rule stated in the call':<36} {'right document':>14} {'right kind':>12}")
+ for arm in payload["rules"]:
+ mark = " (published)" if arm in PUBLISHED_ARMS else ""
+ print(f" {arm:<34} {derived[f'{arm}/exact']:>9}/{n} {derived[f'{arm}/type']:>7}/{n}{mark}")
+ print()
+ print(f"the two published rules put a different document first in "
+ f"{derived['top1_differs_between_published_rules']}/{n} questions")
+
+ if emit:
+ Path(emit).write_text(
+ json.dumps({"derived": derived,
+ "per_case": {c: {a: top[(c, a)] for a in arms} for c in cases}},
+ indent=1) + "\n",
+ encoding="utf-8")
+ print(f"\nwrote {emit}")
+
+ mismatched = [k for k, v in PUBLISHED.items() if derived.get(k) != v]
+ if mismatched:
+ for key in mismatched:
+ print(f"MISMATCH {key}: recording gives {derived.get(key)}, the page publishes {PUBLISHED[key]}",
+ file=sys.stderr)
+ return 1
+ print("\nEvery published figure matches the recording.")
return 0
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("--data", default="data", help="fetched evidence directory")
+ parser.add_argument("--emit", help="write the derived figures as JSON to this path")
+ args = parser.parse_args()
+ return main_with(Path(args.data), args.emit)
+
+
if __name__ == "__main__":
sys.exit(main())
diff --git a/examples/rerank/tests/test_example.py b/examples/rerank/tests/test_example.py
index 43a00fca4..8df57a833 100644
--- a/examples/rerank/tests/test_example.py
+++ b/examples/rerank/tests/test_example.py
@@ -1,30 +1,32 @@
-"""Tamper tests for the offline checks, carried over from the committed run.
+"""Tamper tests for the offline checks.
python3 fetch.py
python3 -m unittest discover -s tests -v
-Standard library only, and no server. These were written when the recorded run
-lived in this repository; they now read the fetched dataset instead. Nothing
-here is new: each one still asserts that a specific forgery fails closed.
+Standard library only, and no server. Each one asserts that a specific forgery
+fails closed.
-A missing `data/` directory fails these tests rather than skipping them. A
-check that cannot run has not passed.
+A missing `data/` directory fails these tests rather than skipping them. A check
+that cannot run has not passed.
"""
from __future__ import annotations
+import contextlib
import copy
import hashlib
import importlib.util
import json
+import shutil
import sys
+import tempfile
import unittest
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
-REQUIRED = ("inputs/cases.json", "inputs/sources.json", "calls.json", "manifest.json")
+REQUIRED = ("inputs/cases.json", "calls.json", "manifest.json")
def _module(name: str):
@@ -40,14 +42,24 @@ run = _module("run")
score = _module("score")
+def strings(value: Any):
+ if isinstance(value, str):
+ yield value
+ elif isinstance(value, dict):
+ for item in value.values():
+ yield from strings(item)
+ elif isinstance(value, list):
+ for item in value:
+ yield from strings(item)
+
+
class RerankExampleTests(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
missing = [name for name in REQUIRED if not (DATA / name).exists()]
if missing:
raise AssertionError(f"fetch the evidence first (python3 fetch.py); missing {', '.join(missing)}")
- cls.cases = json.loads((DATA / "inputs/cases.json").read_text(encoding="utf-8"))
- cls.sources = json.loads((DATA / "inputs/sources.json").read_text(encoding="utf-8"))
+ cls.payload = json.loads((DATA / "inputs/cases.json").read_text(encoding="utf-8"))
cls.calls = json.loads((DATA / "calls.json").read_text(encoding="utf-8"))
cls.manifest = json.loads((DATA / "manifest.json").read_text(encoding="utf-8"))
@@ -56,8 +68,9 @@ class RerankExampleTests(unittest.TestCase):
fetch.py pins manifest.json by the digest in its own source and then
pins every other file by the digest inside that manifest, so the bytes
- are authenticated before anything parses them. This re-walks the second
- half against what actually landed on disk.
+ are authenticated before anything parses them. A rewritten candidate
+ excerpt is caught here, at fetch time, rather than by a digest recorded
+ beside the text it covers.
"""
pinned = self.manifest["files_sha256"]
self.assertEqual(pinned["calls.json"], self.manifest["calls_sha256"])
@@ -68,59 +81,129 @@ class RerankExampleTests(unittest.TestCase):
}
self.assertEqual(on_disk, pinned)
- def test_inputs_are_exact_primary_source_excerpts(self) -> None:
- score.verify_inputs(self.cases, self.sources)
- self.assertEqual(len(self.cases["cases"]), 4)
- self.assertEqual(len(self.sources["sources"]), 4)
+ def test_corpus_is_the_shape_the_published_figures_assume(self) -> None:
+ cases = self.payload["cases"]
+ self.assertEqual(len(cases), 24)
+ self.assertEqual(len({case["id"] for case in cases}), 24)
+ self.assertEqual(len({case["agency"] for case in cases}), 24)
+ for case in cases:
+ self.assertEqual(len(case["candidates"]), 4)
+ roles = sorted(candidate["role"] for candidate in case["candidates"])
+ self.assertEqual(roles, ["asked-about-final", "asked-about-proposal",
+ "neighbour-final", "neighbour-proposal"])
+ # The query is the shared docket title. It must not repeat the
+ # neighbour's, or the pool would not be competitive on subject.
+ self.assertNotEqual(case["query"], case["neighbour_title"])
+ for candidate in case["candidates"]:
+ expected = "Rule" if candidate["role"].endswith("final") else "Proposed Rule"
+ self.assertEqual(candidate["type"], expected, candidate["id"])
def test_recorded_envelopes_match_the_runner(self) -> None:
self.assertEqual(run.check(DATA), 0)
- def test_boolean_score_fails_closed(self) -> None:
- case_id = "scotus_two_contracts"
- case = self.cases["cases"][case_id]
- body = copy.deepcopy(self._body(case_id))
- body["scores"][0]["score"] = True
- with self.assertRaisesRegex(SystemExit, "non-numeric score"):
- score.ranked(case_id, case, body)
+ def test_published_figures_match_the_recording(self) -> None:
+ self.assertEqual(score.main_with(DATA), 0)
+
+ def test_a_missing_call_fails_rather_than_shrinking_the_denominator(self) -> None:
+ """Absent data is a failure, never a skip."""
+ payload = copy.deepcopy(self.calls)
+ dropped = f"{self.payload['cases'][0]['id']}/proposed-positive"
+ payload["calls"] = [call for call in payload["calls"] if call["id"] != dropped]
+ payload["call_count"] = len(payload["calls"])
+ with _temp_calls(payload) as data_dir:
+ self.assertEqual(score.main_with(data_dir), 1)
+
+ def test_two_responses_swapped_between_arms_fails_closed(self) -> None:
+ """The forgery every count and digest survives.
+
+ Trading two responses between arms of the same case keeps the call
+ count, the rank set and every rebuilt request envelope intact, so
+ `run.py --check` still passes. Only the figures pinned in score.py's
+ own source refuse it.
+ """
+ payload = copy.deepcopy(self.calls)
+ case_id = self.payload["cases"][0]["id"]
+ by_id = {call["id"]: call for call in payload["calls"]}
+ left, right = by_id[f"{case_id}/none"], by_id[f"{case_id}/proposed-positive"]
+ left["response"], right["response"] = right["response"], left["response"]
+ with _temp_calls(payload) as data_dir:
+ self.assertEqual(run.check(data_dir), 0, "the envelopes are untouched, so --check must still pass")
+ self.assertEqual(score.main_with(data_dir), 1)
def test_a_candidate_scored_twice_fails_closed(self) -> None:
"""A count is not a set.
- Replacing one candidate's row with a duplicate of another keeps the row
- count and the 0..n-1 ranks intact, so only comparing the identities
- catches it.
+ Replacing one scored row with a duplicate of another keeps the row
+ count and the 0..n-1 ranks intact, so only comparing identities catches
+ it.
"""
- case_id = "ntsb_detector_alert"
- case = self.cases["cases"][case_id]
- body = copy.deepcopy(self._body(case_id))
+ payload = copy.deepcopy(self.calls)
+ case_id = self.payload["cases"][0]["id"]
+ body = next(c for c in payload["calls"] if c["id"] == f"{case_id}/none")["response"]["body"]
body["scores"][0]["item_id"] = body["scores"][1]["item_id"]
- with self.assertRaisesRegex(SystemExit, "candidates"):
- score.ranked(case_id, case, body)
+ with _temp_calls(payload) as data_dir:
+ self.assertEqual(score.main_with(data_dir), 1)
- def test_rewritten_excerpt_fails_even_with_its_declared_hash(self) -> None:
- """The forgery a single declared digest cannot catch.
+ def test_a_missing_manifest_fails_rather_than_skipping_its_own_check(self) -> None:
+ """The revision check must not vanish with the file it reads.
- Rewrite the text and the digest recorded beside it together and that
- pair agrees with itself. The canonical digest in sources.json is what
- refuses it, which is why both files travel together.
+ score.py used to load the manifest only `if manifest_path.exists()`,
+ so deleting one file removed the check that the recording came from the
+ published weights, and a recording from any other checkpoint scored
+ clean. Missing evidence is a failure, not a licence to skip the check
+ over it.
"""
- cases = copy.deepcopy(self.cases)
- candidate = cases["cases"]["scotus_two_contracts"]["candidates"][0]
- candidate["text"] += " tampered"
- candidate["sha256"] = score.sha256_text(candidate["text"])
- with self.assertRaisesRegex(SystemExit, "canonical one in sources.json"):
- score.verify_inputs(cases, self.sources)
-
- def test_a_failed_run_is_never_scored(self) -> None:
- payload = copy.deepcopy(self.calls)
- payload["complete"] = False
- payload["failed_calls"] = 1
- with self.assertRaisesRegex(SystemExit, "not a complete run"):
- score.scored_calls(payload)
+ with _temp_calls(self.calls) as data_dir:
+ (data_dir / "manifest.json").unlink()
+ with self.assertRaisesRegex(SystemExit, "manifest.json is missing"):
+ score.main_with(data_dir)
+
+ def test_a_call_from_another_deployment_fails_closed(self) -> None:
+ """Every call has to come from the deployment the manifest names.
+
+ Checked against the manifest's `deployment_revision` and NOT against
+ MODEL_REVISION: the SDK's `last_model_revision` is the SIE deployment
+ digest that models served together share, not the HuggingFace revision
+ of these weights. Comparing it with MODEL_REVISION would reject all 120
+ of this example's own calls.
+ """
+ manifest = copy.deepcopy(self.manifest)
+ self.assertNotEqual(manifest["deployment_revision"], manifest["model_revision"])
+ for call in self.calls["calls"]:
+ self.assertEqual(call["recorded"]["model_revision"], manifest["deployment_revision"])
+ manifest["deployment_revision"] = "0" * 64
+ with _temp_calls(self.calls, manifest=manifest) as data_dir:
+ self.assertEqual(score.main_with(data_dir), 1)
+
+ def test_an_existing_backup_path_is_refused_not_deleted(self) -> None:
+ """A path this script names is not a path it owns.
+
+ fetch.py moves `data/` aside before renaming the new tree into place.
+ It used to rmtree whatever already sat at that name, which would delete
+ a reader's unrelated directory without a word.
+ """
+ fetch = _module("fetch")
+ with tempfile.TemporaryDirectory() as tmp:
+ dest = Path(tmp) / "data"
+ dest.mkdir()
+ backup = fetch.backup_path(dest)
+ backup.mkdir()
+ (backup / "unrelated.txt").write_text("not ours")
+
+ self.assertIn("already exists", fetch.refuse_reason(dest) or "")
+ with self.assertRaisesRegex(RuntimeError, "backup path"):
+ fetch.swap_into_place(Path(tmp) / "staging", dest)
+ self.assertTrue((backup / "unrelated.txt").exists())
+
+ def test_a_recording_from_another_model_revision_is_not_scored(self) -> None:
+ manifest = copy.deepcopy(self.manifest)
+ manifest["model_revision"] = "0" * 40
+ with _temp_calls(self.calls, manifest=manifest) as data_dir:
+ with self.assertRaisesRegex(SystemExit, "model revision"):
+ score.main_with(data_dir)
def test_metadata_has_no_temporary_filesystem_paths(self) -> None:
- forbidden = ("/Users/", "/root/", "/tmp/", "reference-batch")
+ forbidden = ("/Users/", "/root/", "/tmp/", "/private/tmp", "reference-batch")
for path in sorted(DATA.rglob("*.json")):
for text in strings(json.loads(path.read_text(encoding="utf-8"))):
self.assertFalse(
@@ -128,22 +211,27 @@ class RerankExampleTests(unittest.TestCase):
f"{path.relative_to(DATA)}: {text}",
)
- def _body(self, case_id: str) -> dict[str, Any]:
- for call in self.calls["calls"]:
- if call["case"] == case_id:
- return call["response"]["body"]
- raise AssertionError(f"no recorded call for {case_id}")
+ def test_every_candidate_cites_a_federal_register_url(self) -> None:
+ for case in self.payload["cases"]:
+ for candidate in case["candidates"]:
+ self.assertTrue(
+ candidate["html_url"].startswith("https://www.federalregister.gov/documents/"),
+ candidate["html_url"],
+ )
-def strings(value: Any):
- if isinstance(value, str):
- yield value
- elif isinstance(value, dict):
- for item in value.values():
- yield from strings(item)
- elif isinstance(value, list):
- for item in value:
- yield from strings(item)
+def _temp_calls(calls: dict[str, Any], manifest: dict[str, Any] | None = None):
+ """A copy of data/ with calls.json, and optionally manifest.json, replaced."""
+ with tempfile.TemporaryDirectory() as tmp:
+ data_dir = Path(tmp) / "data"
+ shutil.copytree(DATA, data_dir)
+ (data_dir / "calls.json").write_text(json.dumps(calls, indent=1, ensure_ascii=False) + "\n",
+ encoding="utf-8")
+ if manifest is not None:
+ (data_dir / "manifest.json").write_text(json.dumps(manifest, indent=1, ensure_ascii=False) + "\n",
+ encoding="utf-8")
+ yield data_dir
if __name__ == "__main__":