Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/inferrsi/harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,10 @@ body length depend on entries outside the delivered context. The [ranking regres
runs both policies against the same [complete corpus](../../../tests/fixtures/indexer/ranking-corpus)
at that Git revision. It also verifies an old capture after an undelivered entry changes
the score in a fresh search.
Knowledge's [`verify_replay`](../knowledge/ranking_replay.py) reproduces a bound Find and
delivery from its frozen rule, including an unregistered candidate. It reports
`reproduced` only for the identical corpus and scoring version, separately from capture
verification.

## Managed session interfaces

Expand Down
6 changes: 6 additions & 0 deletions src/inferrsi/knowledge/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ Benchmark owns assessment of the results those workflows produce.
it ranks matches or selects skill sections by relevance. Explicit item IDs
keep caller order even when section selection uses these weights.
Inspect `contexts` and `context_omissions` to see which material fit the budget.
- [`ranking_replay.py`](ranking_replay.py) binds a Find and delivery with
`replay_binding` (query, limit, backend filter, byte budget, frozen rule receipt,
scoring version and corpus digest) and checks it with `verify_replay`. Only an
identical corpus and scoring version can report `reproduced`; archival capture
verification is a separate check, and `delivery_difference` compares ranked,
delivered and omitted outputs.
- [`knowledge_store.py`](knowledge_store.py) exposes `KnowledgeStore.create` and
`update` for an authorized writable store. The packaged library is authored
in the repository.
Expand Down
302 changes: 302 additions & 0 deletions src/inferrsi/knowledge/ranking_replay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,302 @@
"""Replay a retained Find ranking from its frozen rule over a pinned corpus.

Two checks are kept apart. Archival verification (``verify_capture``) proves the
retained bytes are intact; it still passes when an undelivered corpus entry
changes. Exact replay, here, reproduces the returned, delivered and omitted
order, which requires the same query, backend filter, limit, byte budget, frozen
rule receipt (with ``config_sha256``), scoring version and identical corpus. A
changed corpus, upgraded scoring version, unverified delivery or missing binding
is never reported as a reproduced ranking.
"""

from __future__ import annotations

import hashlib
import json
import re
from collections.abc import Callable, Iterable, Mapping

from .knowledge_find import Corpus, find
from .ranking_policy import RANKING_VERSION, RankingPolicy

BINDING_FIELDS = (
"query", "limit", "backend", "context_bytes", "ranking_policy", "scoring_version",
"corpus_sha256",
)
_SHA256_RE = re.compile(r"[0-9a-f]{64}")


def corpus_digest(corpus: Corpus) -> str:
"""Identify the scoring inputs of every eligible document, in a stable order."""
rows = sorted(
[doc.qualified or doc.identity, doc.kind, doc.state, getattr(doc, "backend", None),
doc.fields]
for doc in corpus.documents
)
raw = json.dumps(rows, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8")
return hashlib.sha256(raw).hexdigest()


def _verify_replay_policy_receipt(recorded: object) -> tuple[dict, int]:
"""Require and verify a frozen ranking receipt (including ``config_sha256``)."""
if not isinstance(recorded, Mapping):
raise ValueError("Replay binding ranking_policy must be a receipt mapping")
required = {"id", "version", "weights", "config_sha256"}
if set(recorded) != required:
raise ValueError(
"Replay binding ranking_policy requires id, version, weights and config_sha256"
)
policy_id = recorded["id"]
version = recorded["version"]
weights = recorded["weights"]
digest_value = recorded["config_sha256"]
if not isinstance(policy_id, str) or not policy_id.strip():
raise ValueError("Replay binding ranking_policy requires a nonempty id")
if type(version) is not int or version < 1:
raise ValueError("Replay binding ranking_policy version must be a positive integer")
if not isinstance(weights, Mapping):
raise ValueError("Replay binding ranking_policy weights must be a mapping")
if not isinstance(digest_value, str) or not _SHA256_RE.fullmatch(digest_value):
raise ValueError("Replay binding ranking_policy requires a valid config_sha256")
configuration = {"id": policy_id, "version": version, "weights": dict(weights)}
try:
raw = json.dumps(
configuration, sort_keys=True, separators=(",", ":"), allow_nan=False,
).encode("utf-8")
except (TypeError, ValueError) as exc:
raise ValueError(
"Replay binding ranking_policy weights must be finite JSON values"
) from exc
if hashlib.sha256(raw).hexdigest() != digest_value:
raise ValueError("Ranking configuration digest does not match its weights")
return {**configuration, "config_sha256": digest_value}, version


def replay_binding(*, query: str, limit: int, ranking_policy: Mapping, corpus: Corpus,
backend: str | None = None, context_bytes: int | None = None,
collect_unreadable: bool | None = None) -> dict:
"""Record everything an exact replay of one Find and delivery depends on."""
policy = RankingPolicy.from_configuration(ranking_policy)
if collect_unreadable is None:
collect_unreadable = context_bytes is not None
elif type(collect_unreadable) is not bool:
raise ValueError("Replay binding collect_unreadable must be a boolean")
if context_bytes is not None and not collect_unreadable:
raise ValueError("Delivery replay binding requires collect_unreadable=True")
return {
"query": query, "limit": limit, "backend": backend, "context_bytes": context_bytes,
"collect_unreadable": collect_unreadable,
"ranking_policy": policy.receipt(), "scoring_version": RANKING_VERSION,
"corpus_sha256": corpus_digest(corpus),
}


def _project_hit(item: Mapping) -> dict:
ref = item.get("material_ref") or item.get("ref")
if ref is not None:
projected: dict = {"ref": ref, "revision": item.get("revision")}
if "score" in item:
projected["score"] = item["score"]
return projected
if "unreadable" in item:
projected = {"unreadable": item["unreadable"]}
if "score" in item:
projected["score"] = item["score"]
if "id" in item:
projected["id"] = item["id"]
if "path" in item:
projected["path"] = item["path"]
if "revision" in item:
projected["revision"] = item["revision"]
return projected
raise ValueError("Ranking hit requires material_ref, ref, or unreadable status")


def ranked_items(items: Iterable[Mapping]) -> list[dict]:
"""Project hits to the fields a replay must reproduce, in rank order."""
return [_project_hit(item) for item in items]


def replay_find(binding: Mapping, corpus: Corpus, *,
pack: Callable[[list, RankingPolicy, int], Mapping] | None = None) -> dict:
"""Recompute the ranking, and optionally the delivery, bound in ``binding``.

``pack(hits, policy, context_bytes)`` assembles the delivery the same way the
original call did and returns its ``contexts`` and ``context_omissions``.
When ``binding["collect_unreadable"]`` is true (default for delivery bindings
where ``context_bytes`` is set), unreadable hits are collected separately
under ``unreadable`` so ``pack`` receives only readable pinned hits. When
false (default for ordinary ranking-only Find bindings), unreadable hits stay
in ``items`` just as ordinary ``find(..., pin_material=True)`` returns them.
When ``binding`` was produced under a different scoring version, its receipt
integrity is still verified and ``scoring_matches`` is returned as ``False``
without attempting to rebuild the rule under the newer runtime version.
"""
missing = [name for name in BINDING_FIELDS if name not in binding]
if missing:
raise ValueError(f"Replay binding lacks {', '.join(missing)}")
scoring_version = binding["scoring_version"]
if type(scoring_version) is not int or scoring_version < 1:
raise ValueError("Replay binding scoring_version must be a positive integer")
recorded_receipt, policy_version = _verify_replay_policy_receipt(binding["ranking_policy"])
if policy_version != scoring_version:
raise ValueError("Replay binding scoring_version differs from ranking_policy version")
if pack is not None and binding["context_bytes"] is None:
raise ValueError("Replay binding lacks the delivery byte budget")
collect_unreadable = binding.get("collect_unreadable")
if collect_unreadable is None:
collect_unreadable = binding["context_bytes"] is not None
elif type(collect_unreadable) is not bool:
raise ValueError("Replay binding collect_unreadable must be a boolean")
if (pack is not None or binding["context_bytes"] is not None) and not collect_unreadable:
raise ValueError("Delivery replay requires collect_unreadable=True")

corpus_matches = binding["corpus_sha256"] == corpus_digest(corpus)
if scoring_version != RANKING_VERSION:
replayed: dict = {
"scoring_matches": False,
"corpus_matches": corpus_matches,
"ranking_policy": recorded_receipt,
"items": [],
"unreadable": [],
}
if pack is not None:
replayed["delivered"] = []
replayed["omitted"] = []
return replayed

policy = RankingPolicy.from_configuration(recorded_receipt)
unreadable: list[dict] = []
find_kwargs = {"unreadable_hits": unreadable} if collect_unreadable else {}
result = find(binding["query"], corpus, limit=binding["limit"], pin_material=True,
ranking_policy=policy, backend=binding["backend"], **find_kwargs)
replayed = {
"scoring_matches": True,
"corpus_matches": corpus_matches,
"ranking_policy": policy.receipt(),
"items": ranked_items(result["items"]),

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

用本 PR 的冻结语料,default、limit=2、context_bytes=13 时仅交付 case.qxrankprobe,省略 case.alternate。删除省略项的 demo/cases/bravo.md 后重新加载语料,原归档仍是 verified,首项仍可读,且第 117 行已经判定 corpus_matches=False。此时 Find 返回一条标记为 unreadable 的命中,其中没有 material_ref 或 ref;这里投影该命中时抛出 KeyError('ref'),verify_replay 无法返回约定的 corpus_changed。请在这种情况下保留语料变化状态,并让诊断和 pack 能处理不可读命中。可用上述仅删除未交付正文的场景补一个回归。

"unreadable": ranked_items(unreadable),
}
if pack is not None:
delivery = pack(result["items"], policy, binding["context_bytes"])
replayed["delivered"] = [context["ref"] for context in delivery["contexts"]]
replayed["omitted"] = [omission["ref"] for omission in delivery["context_omissions"]]
return replayed


def verify_replay(binding: Mapping, retained: Mapping, corpus: Corpus, *,
pack: Callable[[list, RankingPolicy, int], Mapping] | None = None) -> dict:
"""Compare a retained ranking with its replay.

``retained`` holds ``items`` and, when delivery is bound (``context_bytes``
is not ``None``) or ``delivered``/``omitted`` are present in ``retained``,
``pack`` is required so delivery and omission order are verified too. The
state is ``reproduced`` only when the scoring version and corpus match and
every checked rank, delivery and omission is identical.
"""
has_delivery = (
binding.get("context_bytes") is not None
or "delivered" in retained
or "omitted" in retained
)
if has_delivery and pack is None:
raise ValueError(
"Delivery replay requires pack when context_bytes or delivered/omitted refs are bound"
)
if pack is not None:
for key in ("delivered", "omitted"):
if key not in retained:
raise ValueError(f"Retained delivery lacks {key}")
replayed = replay_find(binding, corpus, pack=pack)
if not replayed["scoring_matches"]:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

真正升级评分器时,旧绑定中的 scoring_version 和 ranking_policy.version 会一起落后。我用版本 1 创建完整绑定,再把运行时评分版本升为 2,结果在重建规则时抛出 ValueError,无法返回这里声明的 scoring_changed。当前测试只改外层版本。请先识别完整旧绑定的版本差异,再尝试用当前版本重建规则,并用一次真实形态的旧回执做回归。

return {"state": "scoring_changed", "mismatches": [], "replayed": replayed}
state = None if replayed["corpus_matches"] else "corpus_changed"
mismatches = _rank_mismatches(ranked_items(retained["items"]), replayed["items"])
for key in ("delivered", "omitted") if pack is not None else ():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

绑定已记录 2048 字节交付预算时,默认调用 verify_replay 仍会跳过交付核对。我用同一候选规则、查询和 limit=2 分别保留 2048 字节与 1 字节两份结果:前者交付两项,后者两项全被省略。把后者交给前者的绑定,省略 pack 返回 reproduced,传入 pack 才返回 differs。请在回放带交付预算或交付记录时要求 pack,或把仅验证排名的结果标成单独状态。

if list(retained[key]) != replayed[key]:
mismatches.append({key: {"retained": list(retained[key]),
"replayed": replayed[key]}})
return {"state": state or ("differs" if mismatches else "reproduced"),
"mismatches": mismatches, "replayed": replayed}


def _rank_mismatches(retained: list[dict], replayed: list[dict]) -> list[dict]:
mismatches = []
for rank in range(max(len(retained), len(replayed))):
before = retained[rank] if rank < len(retained) else None
after = replayed[rank] if rank < len(replayed) else None
if (
before is not None
and after is not None
and "score" not in before
and "score" in after
and before == {k: v for k, v in after.items() if k != "score"}
):
continue
if before != after:
mismatches.append({"rank": rank + 1, "retained": before, "replayed": after})
return mismatches


def _extract_refs(entries: Iterable[str | Mapping]) -> list[str]:
refs: list[str] = []
for entry in entries:
if isinstance(entry, str):
refs.append(entry)
elif isinstance(entry, Mapping):
ref = entry.get("material_ref") or entry.get("ref")
if isinstance(ref, str):
refs.append(ref)
elif "unreadable" in entry:
ident = entry.get("id") or entry.get("path") or "unknown"
refs.append(f"unreadable:{ident}")
else:
raise ValueError("Ranking entry requires a string ref")
else:
raise ValueError("Ranking entry must be a string ref or mapping")
return refs


def _ref_list_difference(first_refs: list[str], second_refs: list[str]) -> dict:
shared = [ref for ref in first_refs if ref in second_refs]
return {
"only_first": [ref for ref in first_refs if ref not in second_refs],
"only_second": [ref for ref in second_refs if ref not in first_refs],
"reordered": shared != [ref for ref in second_refs if ref in first_refs],
}


def delivery_difference(
first: Mapping | Iterable[str | Mapping],
second: Mapping | Iterable[str | Mapping],
) -> dict:
"""Compare two rankings or full replay/delivery outputs.

When passed two replay mappings (carrying ``items`` and/or ``delivered`` and
``omitted``), compares each present sequence so differences in actual
delivered and omitted sets are reported alongside ranked hits. When passed
two sequences of refs or hit mappings, compares that single ordered list.
"""
if isinstance(first, Mapping) and isinstance(second, Mapping):
diff: dict[str, dict] = {}
if "items" in first or "items" in second:
diff["ranked"] = _ref_list_difference(
_extract_refs(first.get("items", ())),
_extract_refs(second.get("items", ())),
)
if "delivered" in first or "delivered" in second:
diff["delivered"] = _ref_list_difference(
_extract_refs(first.get("delivered", ())),
_extract_refs(second.get("delivered", ())),
)
if "omitted" in first or "omitted" in second:
diff["omitted"] = _ref_list_difference(
_extract_refs(first.get("omitted", ())),
_extract_refs(second.get("omitted", ())),
)
if not diff:
raise ValueError("Replay comparison mappings require items, delivered or omitted")
return diff
if isinstance(first, Mapping) != isinstance(second, Mapping):
raise ValueError("Compare either two replay mappings or two ordered ref sequences")
return _ref_list_difference(_extract_refs(first), _extract_refs(second))
Loading
Loading