Skip to content

armgit / sie

Public Imported from GitHub
0

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

fix(examples): align graph evidence with recorded calls (#510)

svonavaef90dd602978
diff --git a/examples/knowledge-graph/README.md b/examples/knowledge-graph/README.md
index da8272214..0d6ffa879 100644
--- a/examples/knowledge-graph/README.md
+++ b/examples/knowledge-graph/README.md
@@ -10,12 +10,14 @@ want, such as acquired, subsidiary of and develops. What comes back is a graph
whose nodes carry character offsets into the paragraph, so every node points at
the text it came from.
-The run is already recorded. The twenty requests and the entities and relations
-they returned live in the public HuggingFace dataset
+The run is already recorded. Forty calls cover ten paragraphs through GLiNER2
+Large and Base. This example scores the twenty Large calls, each projected from
+the unchanged full recording with its request, result, headers and timing.
+Both forms 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 counts with **no API key and no inference spend**. Those are the same
-values behind the figures on
+recorded counts with **no API key and no inference spend**. The current Large
+results support the examples on
[superlinked.com/knowledge-graph](https://superlinked.com/knowledge-graph), whose
sources are in its [SOURCES.md](https://superlinked.com/reference/knowledge-graph/SOURCES.md).
@@ -66,18 +68,30 @@ SIE_API_KEY=sk-sie-... uv run python run.py --output run-output
`score.py` prints a row per paragraph and ends with:
```
-10 paragraphs recorded, 5 shown on the page
-8 edges across the 4 proof paragraphs and 5 in the hero graph, 13 drawn in total
+10 paragraphs recorded, 5 in the original display selection
+8 edges across the 4 proof paragraphs and 5 in the original hero, 13 selected in total
```
-13 drawn is the figure the task page publishes. The scorer counts every
-displayed paragraph after the hero as a proof paragraph, and the page lays one
-of the five out as its playground, so the 8 and the 5 split the same 13 the
-page draws.
+These counts describe the frozen five-case page-role manifest. The current
+page highlights Flex's credit agreement, Ford's vehicle recall and Tarsus's
+acquisition filing. The original selection remains reproducible; it is not an
+aggregate accuracy claim.
-The five paragraphs the page leaves out are printed too, each with the edge
-count and the reason it was not displayed. Four of the five returned two edges
-or fewer, and the fifth comes from a filing another task page already uses.
+`canonical-calls.json` retains all forty original calls, including the recorded
+usage headers and original digest scopes. `calls.json` is a Large-only per-item
+projection for this example. `projection.json` pins the full recording's byte
+digest and maps each projected call to its original entry. The scorer refuses
+a changed source file or a projection whose requests, results, headers,
+timings or model revisions differ from that source.
+
+The two Flex calls each meter 92 input tokens. A hosted estimate must price
+both calls at the current published Large rate and round each terminal event
+as the credit book requires. The historical credits in a recording do not
+establish a current list price.
+
+The five paragraphs outside that original selection are printed too, each with
+the edge count and the recorded selection reason. Four returned two edges or
+fewer, and the fifth comes from a filing another task page already used.
`score.py` fails rather than skipping. It refuses a paragraph whose text no
longer matches its digest, a candidate with a missing call, a response that
@@ -90,28 +104,25 @@ asked for, and a displayed edge with no recorded reading.
- **Not that the graph is correct.** Nothing mechanical checks these edges.
Every relation the model returns carries a confidence score and no
- correctness signal, and a high score is not evidence the paragraph says it. A
- graph built from this output without a person reading the source will contain
- claims the source does not make.
+ correctness signal, and a high score is not evidence the paragraph says it.
+ Check each returned relation against the retained source before using it as
+ a verified fact.
- **Not an accuracy rate.** Eight edges over the four paragraphs outside the
hero is far too small to support a percentage, and the ten paragraphs were
chosen to be readable rather than sampled from anything.
-- **Not that offsets pin a relation.** GLiNER2 names each end of a relation by
- its text, not by an offset, and returns at most one span per text and label.
+- **Not that offsets pin a relation.** The recorded SIE relation results name
+ each endpoint by text, without an offset. Their entity results have at most
+ one span per text and label.
Where a paragraph mentions the same text twice, the relation does not say
which mention it means, and no threshold changes that. The task page marks
every occurrence in that case rather than choosing one.
- **Not a benchmark.** The recorded `duration_ms` values are provenance. One
call took 15.8 seconds against about 0.5 seconds for every other, which is
the shape of a cold model load rather than a measurement of anything.
-- **Not bound to the website.** The same run backs the fixtures in
- `superlinked/sie-web` under
- `apps/site/tests/fixtures/reference/knowledge-graph/`, which is what that
- repository's CI checks. Nothing automatically ties the two copies together,
- so they could drift.
-- **Not a guarantee the dataset is unchanged.** `fetch.py` pins a dataset
- revision rather than `main`, so a later upload cannot silently change what
- you score. It does not prove the revision holds what it held yesterday.
+- **Not a check of the current website.** `projection.json` identifies the
+ full recording within the pinned public dataset. Its byte digest ties the
+ scored projection to that recording; scoring it does not fetch
+ or inspect a later website deployment.
## Inputs
@@ -120,10 +131,9 @@ text, the URL and SHA-256 of the document it was taken from, and a note saying
how the paragraph was derived from that document. Sources are SEC EDGAR
filings, NHTSA recall reports and FDA recall notices, all public records.
-Each candidate also records `page_role`, which says whether the task page shows
-it and why. `score.py` reads the counts off those roles, so the "5 shown" and
-"8 proof edges" figures come from the pinned data rather than from anything
-the display trims.
+Each candidate also records `page_role`, the original selection and its reason.
+`score.py` reads the counts off those frozen roles, so the five-case selection
+and eight proof edges come from pinned data rather than the current display.
`evidence/inputs/review.json` holds the readings. `score.py` checks each
flagged triple against the recorded relations, so the review cannot flag an
diff --git a/examples/knowledge-graph/fetch.py b/examples/knowledge-graph/fetch.py
index e1f29d64e..7006aacd2 100755
--- a/examples/knowledge-graph/fetch.py
+++ b/examples/knowledge-graph/fetch.py
@@ -24,7 +24,7 @@ HERE = Path(__file__).resolve().parent
EVIDENCE = HERE / "evidence"
DATASET = "superlinked/sie-task-evidence"
-REVISION = "f79ce47607dafc4ab9ee7d796d24a6e22fbbd042"
+REVISION = "492389541d278e8b75cc9407e5170566e4523fa5"
TASK = "knowledge-graph"
API = f"https://huggingface.co/api/datasets/{DATASET}/tree/{REVISION}"
diff --git a/examples/knowledge-graph/graph.py b/examples/knowledge-graph/graph.py
index b0dfb68b0..da6abfdde 100644
--- a/examples/knowledge-graph/graph.py
+++ b/examples/knowledge-graph/graph.py
@@ -134,7 +134,7 @@ def relations_body(candidate: dict[str, Any], entities: list[dict[str, Any]]) ->
def shown(doc: dict[str, Any]) -> list[dict[str, Any]]:
- """The candidates the task page renders: the hero, then the proof paragraphs.
+ """The frozen study's original display selection: hero, then proof paragraphs.
Proof candidates come back in the order they sit in candidates.json, which
is not the order the page lays them out. Nothing counted here depends on it.
diff --git a/examples/knowledge-graph/run.py b/examples/knowledge-graph/run.py
index 45e059bc5..a4ab29933 100755
--- a/examples/knowledge-graph/run.py
+++ b/examples/knowledge-graph/run.py
@@ -32,9 +32,10 @@ import sys
import time
from datetime import UTC, datetime
from pathlib import Path
-from typing import Any
+from typing import TYPE_CHECKING, Any
-from sie_sdk import SIEClient
+if TYPE_CHECKING:
+ from sie_sdk import SIEClient
import graph
@@ -134,6 +135,8 @@ def main() -> int:
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
+
client = SIEClient(os.environ.get("SIE_BASE_URL", graph.ENDPOINT), api_key=api_key, timeout_s=900)
base_url = client.base_url.rstrip("/")
print(f"endpoint {base_url}{graph.extract_path(model)}")
diff --git a/examples/knowledge-graph/score.py b/examples/knowledge-graph/score.py
index edcef8c5c..f80b3cdd4 100755
--- a/examples/knowledge-graph/score.py
+++ b/examples/knowledge-graph/score.py
@@ -4,8 +4,8 @@
python3 score.py
Reads everything from evidence/, which `python3 fetch.py` downloads: the
-pinned paragraphs, the recorded calls and the hand review. Prints the five
-figures the /knowledge-graph task page publishes.
+pinned paragraphs, the recorded calls and the hand review. Prints the figures
+for the recorded study's original five-case display selection.
Every check is fail-closed. A paragraph whose text no longer matches its
digest, a candidate with a missing call, a response that does not match its
@@ -39,6 +39,57 @@ def expected_url(manifest: dict[str, Any], model: str) -> str:
return manifest["endpoint"].rstrip("/") + path
+def verify_projection(recorded: dict[tuple[str, str], Any]) -> None:
+ """Verify the Large view retains each matching call from the pinned source."""
+ projection = graph.read_json(graph.EVIDENCE / "projection.json")
+ source_bytes = (graph.EVIDENCE / "canonical-calls.json").read_bytes()
+ if graph.sha256_bytes(source_bytes) != projection["source"]["sha256"]:
+ raise InputError("canonical-calls.json does not match its pinned source digest")
+ source = graph.read_json(graph.EVIDENCE / "canonical-calls.json")
+ source_by_slug = {entry["slug"]: entry for entry in source["calls"]}
+ if len(source_by_slug) != len(source["calls"]) or len(source["calls"]) != projection["source"]["calls"]:
+ raise InputError("canonical source call identities or total disagree with the projection")
+ projected_by_slug = {entry["slug"]: entry for entry in recorded.values()}
+ links = {entry["projected_slug"]: entry for entry in projection["calls"]}
+ if len(links) != len(projection["calls"]) or set(links) != set(projected_by_slug):
+ raise InputError("projection must map every scored call exactly once")
+ selected_sources = {entry["slug"] for entry in source["calls"] if entry["request"]["model"] == projection["model"]}
+ if {link["source_slug"] for link in links.values()} != selected_sources:
+ raise InputError("projection must retain every source call for its model")
+ for slug, link in links.items():
+ entry = projected_by_slug[slug]
+ original = source_by_slug[link["source_slug"]]
+ request = original["request"]
+ value = original["response"]["value"]
+ expected_request = {
+ "method": request["method"],
+ "url": request["endpoint"].rstrip("/") + request["path"],
+ "model": request["model"],
+ "body": request["body"],
+ }
+ if len(value["items"]) != 1 or entry["response"] != {"model": value["model"], "item": value["items"][0]}:
+ raise InputError(f"{slug}: projected model result differs from the source")
+ if entry["request"] != expected_request or (entry["candidate"], entry["kind"]) != (
+ original["case"],
+ original["kind"],
+ ):
+ raise InputError(f"{slug}: projected request differs from the source")
+ if entry["status"] != original["http_status"] or original["status"] != "ok":
+ raise InputError(f"{slug}: source HTTP status differs")
+ if entry["headers"] != original["headers"] or entry["timing"] != original["timing"]:
+ raise InputError(f"{slug}: projected usage headers or timing differ from the source")
+ if (
+ entry["model_hf_revision"] != original["model_revision"]
+ or entry["model_revision"] != original["headers"]["x-sie-model-revision"]
+ ):
+ raise InputError(f"{slug}: projected model revision differs from the source")
+ if (
+ entry["source_entry_sha256"] != original["entry_sha256"]
+ or link["source_entry_sha256"] != original["entry_sha256"]
+ ):
+ raise InputError(f"{slug}: source entry digest differs")
+
+
def load_recorded(manifest: dict[str, Any], model: str) -> dict[tuple[str, str], Any]:
"""Recorded calls keyed by (candidate, kind), rejecting duplicates."""
doc = graph.read_json(graph.CALLS_PATH)
@@ -65,6 +116,7 @@ def load_recorded(manifest: dict[str, Any], model: str) -> dict[tuple[str, str],
if observed_revisions != allowed:
unused = sorted(allowed - observed_revisions)
raise InputError(f"manifest names revision {unused[0]}, which no recorded call used")
+ verify_projection(recorded)
return recorded
@@ -111,11 +163,10 @@ def resolve(candidates_doc: dict[str, Any], recorded: dict[tuple[str, str], Any]
# that file claims, written out so the scorer can hold each displayed edge to
# it. Sixteen edges: eleven across the proof paragraphs and five in the hero.
#
-# The page's claim is that a person read every edge it shows. Checking only the
-# flagged triples left that claim unenforced, so a displayed edge nobody had
-# read would have scored clean. Narrowing a schema removes edges from a run and
-# never adds one, which is why this set is a superset of what any later run can
-# display, and why an edge outside it means a person has not read it.
+# Checking only flagged triples would leave review coverage unenforced. The
+# current recording's selected edges are a subset of these reviewed triples;
+# that is checked below rather than assumed from its narrower request labels.
+# A future result outside this set requires another reading before it can pass.
REVIEWED_EDGES = frozenset(
{
("flex-credit-facility", "Citibank, N.A.", "administrative agent of", "Flex Ltd."),
@@ -238,10 +289,12 @@ def main() -> int:
for row in summary["not_shown"]:
print(f"{row['id']:<24} {'not shown':<22} {'':>8} {row['edges']:>6} {row['reason']}")
print()
- print(f"{summary['candidates_recorded']} paragraphs recorded, {summary['candidates_shown']} shown on the page")
+ print(
+ f"{summary['candidates_recorded']} paragraphs recorded, {summary['candidates_shown']} in the original display selection"
+ )
print(
f"{summary['proof_edges']} edges across the {len(summary['displayed']) - 1} proof paragraphs "
- f"and {summary['hero_edges']} in the hero graph, {summary['edges_drawn']} drawn in total"
+ f"and {summary['hero_edges']} in the original hero, {summary['edges_drawn']} selected in total"
)
return 0