From 52dede270a8778d4cab6b157f2aaf36e550f863d Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:04:42 +0800 Subject: [PATCH 1/3] Make Knowledge ranking weights explicit in retrieval receipts Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/knowledge/README.md | 5 ++ src/inferrsi/knowledge/_skill_selection.py | 5 +- src/inferrsi/knowledge/catalog.py | 5 +- src/inferrsi/knowledge/knowledge_find.py | 37 ++++---- .../knowledge/knowledge_operations.py | 23 +++-- src/inferrsi/knowledge/ranking_policy.py | 52 +++++++++++ src/inferrsi/knowledge/research.py | 5 +- tests/apps/test_indexer_deliveries.py | 88 +++++++++++++++++++ tests/knowledge/test_ranking_policy.py | 72 +++++++++++++++ 9 files changed, 261 insertions(+), 31 deletions(-) create mode 100644 src/inferrsi/knowledge/ranking_policy.py create mode 100644 tests/apps/test_indexer_deliveries.py create mode 100644 tests/knowledge/test_ranking_policy.py diff --git a/src/inferrsi/knowledge/README.md b/src/inferrsi/knowledge/README.md index 1d89001af..a5738a2f4 100644 --- a/src/inferrsi/knowledge/README.md +++ b/src/inferrsi/knowledge/README.md @@ -10,6 +10,11 @@ Benchmark owns assessment of the results those workflows produce. - [`knowledge_operations.py`](knowledge_operations.py) exposes `KnowledgeReader.collect` for context, `read` for bundles, and `resource` for files at a pinned revision. +- [`RankingPolicy`](ranking_policy.py) supplies field weights to Find and + Collect. For example, pass `ranking_policy=RankingPolicy("trial", {"applicability": 3})` + to compare results against the default on the same library. A ranked Collect + records the version and effective weights in `retrieval.selection.ranking_policy`. + Inspect `contexts` and `context_omissions` to see which material fit the budget. - [`knowledge_store.py`](knowledge_store.py) exposes `KnowledgeStore.create` and `update` for an authorized writable store. The packaged library is authored in the repository. diff --git a/src/inferrsi/knowledge/_skill_selection.py b/src/inferrsi/knowledge/_skill_selection.py index 910b09623..552db20e0 100644 --- a/src/inferrsi/knowledge/_skill_selection.py +++ b/src/inferrsi/knowledge/_skill_selection.py @@ -7,6 +7,7 @@ from ._source_snapshot import source_entry from .catalog import _skill_search_source, packaged_skill_id +from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy FIND_RELEVANCE = "find-lexical-v1" TASK_STOP_WORDS = frozenset({"a", "an", "and", "for", "in", "of", "on", "the", "to", "with"}) @@ -152,7 +153,7 @@ def skill_procedure(path: str, raw: bytes) -> tuple[bytes, dict]: def context_view( index: tuple[str, list[str], list[str]], view: dict, content: dict[str, bytes], - cue: str | None, available: int, + cue: str | None, available: int, ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, ) -> tuple[dict | None, dict | None]: core, required, optional = index selected = {path: skill_procedure(path, content[path]) for path in [*required, *optional]} @@ -207,7 +208,7 @@ def include(path: str) -> None: ) for path, text in candidates.items() ] - _, _, ranked = rank(cue, Corpus(documents)) + _, _, ranked = rank(cue, Corpus(documents), ranking_policy) paths = [documents[index].identity for _, _, index, _ in ranked] matched = set(paths) omissions.extend( diff --git a/src/inferrsi/knowledge/catalog.py b/src/inferrsi/knowledge/catalog.py index 8972a3e11..6313c5f9d 100644 --- a/src/inferrsi/knowledge/catalog.py +++ b/src/inferrsi/knowledge/catalog.py @@ -11,6 +11,7 @@ from ..resources.repository_packs import REPO_TYPES from . import _source_snapshot +from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy from .retrieval import observation if TYPE_CHECKING: @@ -394,6 +395,7 @@ def search_knowledge( scenario: str | None = None, limit: int = 10, explain: bool = False, + ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, ) -> list[dict[str, Any]] | dict[str, Any]: """List exact package records, using Find when a text query is supplied.""" if limit < 1: @@ -404,7 +406,7 @@ def search_knowledge( from .knowledge_find import rank corpus, document_records = _catalog_corpus(records) - _, _, scored = rank(query, corpus) + _, _, scored = rank(query, corpus, ranking_policy) matches = [ (document_records[index], score, components) for score, _, index, components in scored ] @@ -435,6 +437,7 @@ def search_knowledge( selection={ "method": FIND_RELEVANCE if ranking else None, "scope": "package-records", "ranking_applied": ranking, "state": "applied" if ranking else "not_requested", + **({"ranking_policy": ranking_policy.receipt()} if ranking else {}), "tie_break": "state_then_id_then_ref" if ranking else None, }, items=observed, diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index 456e0b326..810698960 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -45,17 +45,7 @@ from ._knowledge_errors import MissingSkillsExtra from ._skill_selection import TASK_STOP_WORDS, indexed_skill, named_backends from .catalog import BACKENDS, packaged_skill_id - -# Author-written intent outranks bulk prose: a term in a title is evidence the -# document is about it, the same term in a long body often is not. -FIELD_WEIGHTS = { - "title": 5.0, - "summary": 4.0, - "tags": 4.0, - "findings": 4.0, - "applicability": 2.0, - "body": 1.0, -} +from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy # Ties break towards stronger evidence rather than alphabetical identity. STATE_RANK = { @@ -634,10 +624,7 @@ def __init__( lengths = [fields["body"].total() if "body" in fields else 0 for fields in self._counts] nonempty_lengths = [length for length in lengths if length] typical_length = median(nonempty_lengths) if nonempty_lengths else 1 - self._body_weights = [ - FIELD_WEIGHTS["body"] / math.sqrt(max(1, length / typical_length)) - for length in lengths - ] + self._body_normalizers = [math.sqrt(max(1, length / typical_length)) for length in lengths] for fields in self._counts: appearances.update({token for counts in fields.values() for token in counts}) self._idf = { @@ -650,7 +637,8 @@ def idf(self, token: str) -> float: return self._idf.get(token, self._unseen) def score( - self, index: int, query_tokens: list[str], *, query_backend: str | None = None + self, index: int, query_tokens: list[str], *, query_backend: str | None = None, + ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, ) -> tuple[float, dict]: """Sum of idf x field weight x sqrt(occurrences). @@ -661,14 +649,15 @@ def score( """ total = 0.0 detail: dict[str, float] = {} - body_weight = self._body_weights[index] + weights = ranking_policy.weights + body_weight = weights["body"] / self._body_normalizers[index] backend_weight = _backend_weight(self.documents[index].backend, query_backend) for token in query_tokens: weight = self.idf(token) * backend_weight for name, counts in self._counts[index].items(): hits = counts[token] if hits: - field_weight = body_weight if name == "body" else FIELD_WEIGHTS[name] + field_weight = body_weight if name == "body" else weights[name] gain = weight * field_weight * math.sqrt(hits) total += gain detail[token] = round(detail.get(token, 0.0) + gain, 2) @@ -921,7 +910,9 @@ def link(selector: str | None = None) -> dict: return None -def rank(query: str, corpus: Corpus) -> tuple[ +def rank( + query: str, corpus: Corpus, ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, +) -> tuple[ list[str], dict[str, tuple[str, ...]], list[tuple[float, int, int, dict]] ]: """Score matches without opening a Bundle or formatting a delivery.""" @@ -929,7 +920,9 @@ def rank(query: str, corpus: Corpus) -> tuple[ query_tokens, applied = expand(query) scored = [] for index, document in enumerate(corpus.documents): - value, detail = corpus.score(index, query_tokens, query_backend=query_backend) + value, detail = corpus.score( + index, query_tokens, query_backend=query_backend, ranking_policy=ranking_policy, + ) if value > 0: scored.append((value, STATE_RANK.get(document.state, 0), index, detail)) scored.sort(key=lambda row: ( @@ -956,6 +949,7 @@ def find( limit: int = 5, explain: bool = False, decision_cards: bool = False, + ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, registry: "ChannelRegistry | None" = None, backend: str | None = None, platform: str | None = None, @@ -967,7 +961,7 @@ def find( """Find local matches, optionally annotating them from the verified ranking source.""" if type(limit) is not int or limit < 1: raise ValueError("limit must be a positive integer") - query_tokens, applied, scored = rank(query, corpus) + query_tokens, applied, scored = rank(query, corpus, ranking_policy) query_backend = _query_backend(query) if decision_cards else None index = None if searchspace_coordinate is not None: @@ -1030,6 +1024,7 @@ def find( "query": query, "tokens": query_tokens, "corpus_size": len(corpus.documents), + "ranking_policy": ranking_policy.receipt(), "matched": len(scored), "items": items, "no_match": not scored, diff --git a/src/inferrsi/knowledge/knowledge_operations.py b/src/inferrsi/knowledge/knowledge_operations.py index 940435ac6..3b5af8a67 100644 --- a/src/inferrsi/knowledge/knowledge_operations.py +++ b/src/inferrsi/knowledge/knowledge_operations.py @@ -20,6 +20,7 @@ validate_relevance_method, ) from .catalog import KNOWLEDGE_SCOPES, SCENARIO_ALIASES, knowledge_records, lookup_record +from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy if TYPE_CHECKING: from .knowledge_find import Document @@ -310,7 +311,10 @@ def _tree( class KnowledgeReader: - def collect_service_context(self, cue, *, relevance_method, limit, context_bytes): + def collect_service_context( + self, cue, *, relevance_method, limit, context_bytes, + ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, + ): """Package knowledge for service campaigns; no Bundle/content identity path.""" from .catalog import _catalog_corpus, without_file_fingerprints from .context_projection import assemble_context_text @@ -327,7 +331,7 @@ def collect_service_context(self, cue, *, relevance_method, limit, context_bytes ): raise ValueError("Valid cue and positive limit/context budget required") corpus, records = _catalog_corpus(knowledge_records(file_fingerprints=False)) - _, _, ranked = rank(cue, corpus) + _, _, ranked = rank(cue, corpus, ranking_policy) package = files("inferrsi").joinpath("knowledge") contexts, omissions, used = [], [], 0 for score, _, index, _ in ranked: @@ -386,6 +390,7 @@ def collect_service_context(self, cue, *, relevance_method, limit, context_bytes "request": { "relevance": cue, "relevance_method": FIND_RELEVANCE, + "ranking_policy": ranking_policy.configuration(), "limit": limit, "context_bytes": context_bytes, }, @@ -698,7 +703,7 @@ def resource(self, identity: str, path: str, *, revision: str) -> bytes: def _search_order( self, cue: str, matches, *, kind: str | None, package_only: bool, backend: str | None, - store_documents: list[Document], + store_documents: list[Document], ranking_policy: RankingPolicy, ) -> tuple[dict, int, dict[str, int]]: from .knowledge_find import ( Corpus, @@ -764,7 +769,7 @@ def _search_order( else: excluded["filters"] += 1 - _, _, scored = rank(cue, Corpus(eligible)) + _, _, scored = rank(cue, Corpus(eligible), ranking_policy) results = { references[index]: {"score": round(score, 2), "components": components} for score, _, index, components in scored @@ -788,6 +793,7 @@ def collect( material: bool = False, relevance: str | None = None, relevance_method: str | None = None, + ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, context_bytes: int | None = None, decision_cards: dict[str, str | None] | None = None, ) -> dict: @@ -932,7 +938,7 @@ def matches(metadata: dict, authority: str) -> bool: found, considered, rank_excluded = self._search_order( cue, matches, kind=kind, backend=backend, package_only=package_filters or kind == "knowledge", - store_documents=store_documents, + store_documents=store_documents, ranking_policy=ranking_policy, ) considered += len(omitted) requested = list(found) @@ -991,7 +997,9 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: if is_skill: if index is None: index = indexed_skill(record, view, bundle.content) - context, omission = context_view(index, view, bundle.content, cue, available) + context, omission = context_view( + index, view, bundle.content, cue, available, ranking_policy, + ) else: context, omission = record_context(record, view, bundle.content, available) except (ValueError, KeyError, TypeError) as exc: @@ -1133,6 +1141,8 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: from .retrieval import observation selection = result.get("selection", {}) + if selection: + selection["ranking_policy"] = ranking_policy.receipt() result["retrieval"] = observation( entrypoint="collect", request={ "query": query, "relevance": relevance, "relevance_method": relevance_method, @@ -1145,6 +1155,7 @@ def select(reference: str, bundle: Bundle, view: dict) -> None: }, selection={ "method": selection.get("method"), "scope": selection.get("scope"), + **({"ranking_policy": selection["ranking_policy"]} if selection else {}), "ranking_applied": find_ranking, "state": "applied" if find_ranking else "explicit_ids" if ids is not None else "not_requested", diff --git a/src/inferrsi/knowledge/ranking_policy.py b/src/inferrsi/knowledge/ranking_policy.py new file mode 100644 index 000000000..bfbd7c5f1 --- /dev/null +++ b/src/inferrsi/knowledge/ranking_policy.py @@ -0,0 +1,52 @@ +"""Versioned field weights for the shared lexical Knowledge ranking.""" + +from __future__ import annotations + +import hashlib +import json +import re +import sys +from collections.abc import Mapping +from dataclasses import dataclass, field +from types import MappingProxyType + +# Bump when the scoring or tie-breaking semantics change. +RANKING_VERSION = 1 +_DEFAULT_WEIGHTS = MappingProxyType({ + "title": 5.0, "summary": 4.0, "tags": 4.0, "findings": 4.0, + "applicability": 2.0, "body": 1.0, +}) + + +@dataclass(frozen=True) +class RankingPolicy: + """A named set of overrides, expanded once into immutable effective weights.""" + + policy_id: str = "default" + weights: Mapping[str, float] = field(default_factory=dict) + + def __post_init__(self) -> None: + if not isinstance(self.policy_id, str) or not re.fullmatch( + r"[a-zA-Z0-9][a-zA-Z0-9_.-]*", self.policy_id + ): + raise ValueError("Ranking policy requires a nonempty identifier") + if not isinstance(self.weights, Mapping) or self.weights.keys() - _DEFAULT_WEIGHTS.keys(): + raise ValueError("Unknown ranking weight field") + effective = dict(_DEFAULT_WEIGHTS) + for name, value in self.weights.items(): + if type(value) not in (float, int) or not 0 <= value <= sys.float_info.max: + raise ValueError(f"Ranking weight for {name} must be finite and nonnegative") + effective[name] = float(value) if value else 0.0 + object.__setattr__(self, "weights", MappingProxyType(effective)) + + def configuration(self) -> dict: + """Return the full effective rule, also suitable for service-mode receipts.""" + return {"id": self.policy_id, "version": RANKING_VERSION, "weights": dict(self.weights)} + + def receipt(self) -> dict: + configuration = self.configuration() + raw = json.dumps(configuration, sort_keys=True, separators=(",", ":")).encode("utf-8") + return {**configuration, "config_sha256": hashlib.sha256(raw).hexdigest()} + + +DEFAULT_RANKING_POLICY = RankingPolicy() diff --git a/src/inferrsi/knowledge/research.py b/src/inferrsi/knowledge/research.py index f3e0b1a02..280985e52 100644 --- a/src/inferrsi/knowledge/research.py +++ b/src/inferrsi/knowledge/research.py @@ -9,6 +9,7 @@ from .catalog import _catalog_corpus, _scoped_records from .knowledge_find import rank +from .ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy PROCEDURE = ( "data/skill_library/workflows/research/inference-engine-research/" @@ -42,6 +43,7 @@ def research_knowledge( target_backend: str | None = None, target_device: str | None = None, target_memory_gib: float | None = None, + ranking_policy: RankingPolicy = DEFAULT_RANKING_POLICY, ) -> dict: """Union separate research queries, preserving every package filter and record. @@ -82,7 +84,7 @@ def research_knowledge( continue seen.add(term.casefold()) query = {"group": group, "query": term} - _, _, scored = rank(term, corpus) + _, _, scored = rank(term, corpus, ranking_policy) records = [document_records[index] for _, _, index, _ in scored] queries.append({**query, "matches": len(records)}) streams.append(records) @@ -100,6 +102,7 @@ def research_knowledge( break return { "model": model, + "ranking_policy": ranking_policy.receipt(), "profile": profile, "queries": queries, "filters": filters, diff --git a/tests/apps/test_indexer_deliveries.py b/tests/apps/test_indexer_deliveries.py new file mode 100644 index 000000000..160e59821 --- /dev/null +++ b/tests/apps/test_indexer_deliveries.py @@ -0,0 +1,88 @@ +import hashlib +import json + +import pytest + +from inferrsi.apps.workflows.campaign import create_campaign, save_retrieval, verify_capture +from inferrsi.knowledge.knowledge_find import Corpus, find, load_documents +from inferrsi.knowledge.knowledge_operations import KnowledgeReader +from inferrsi.knowledge.ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy + +CUE = "qxrankprobe" +A, B = "case.qxrankprobe", "case.alternate" +ALTERNATE = RankingPolicy("applicability", {"applicability": 3}) + + +@pytest.fixture() +def library(tmp_path): + root = tmp_path / "library" + owner = root / "demo" + cases = owner / "cases" + cases.mkdir(parents=True) + (owner / "SKILL.md").write_bytes(b"---\nname: demo\ndescription: Demo owner\n---\n\nbody\n") + for name, identity, applicability in [("alpha", A, []), ("bravo", B, [CUE] * 4)]: + (cases / f"{name}.md").write_bytes(f"source {name}\n".encode()) + record = { + "id": identity, "kind": "case", "content": f"{name}.md", + "state": "historical_observation", "backend": "ascend", + "applicability": applicability, "limitations": [], "attribution": "Demo", + "sources": [{"type": "internal", "issue": "local", "artifact": "fixture"}], + } + (cases / f"{name}.json").write_text(json.dumps(record), encoding="utf-8") + return root + + +@pytest.mark.parametrize(("options", "order", "scores", "source"), [ + ({}, (A, B), (5, 4), "alpha"), + ({"ranking_policy": ALTERNATE}, (B, A), (6, 5), "bravo"), +]) +def test_find_collect_and_retained_context(library, tmp_path, options, order, scores, source): + reader = KnowledgeReader(skill_root=library) + corpus = Corpus(load_documents(library, kinds=("case",))) + hits = find(CUE, corpus, **options) + assert [(hit["id"], hit["score"]) for hit in hits["items"]] == list(zip(order, scores)) + + result = reader.collect(CUE, kind="case", limit=1, context_bytes=2048, **options) + observed, = result["retrieval"]["items"] + context, = result["contexts"] + ref = "checkout:" + order[0] + assert (observed["ref"], observed["score"], observed["revision"]) == ( + ref, scores[0], reader.read(ref).revision, + ) + assert (context["ref"], context["revision"]) == (ref, observed["revision"]) + resource = next(r for r in context["resources"] if r["path"] == f"{source}.md") + raw = reader.resource(ref, resource["path"], revision=observed["revision"]) + assert raw == resource["content"].encode() == f"source {source}\n".encode() + assert hashlib.sha256(raw).hexdigest() == resource["sha256"] + assert context["sources"] == result["items"][0]["sources"] + assert result["retrieval"]["counts"]["excluded"]["item_limit"] == 1 + + campaign = tmp_path / "run" + create_campaign(campaign, "replay") + path, _ = save_retrieval(campaign, context_id="selected", result=result) + saved, state = verify_capture(path.read_bytes()) + assert state == "verified" + assert resource["content"] in saved["assembled_text"] + assert saved["contexts"][0]["ref"] == ref + assert saved["contexts"][0]["revision"] == observed["revision"] + policy = options.get("ranking_policy", DEFAULT_RANKING_POLICY) + assert hits["ranking_policy"] == saved["retrieval"]["selection"]["ranking_policy"] + assert saved["selection"]["ranking_policy"] == policy.receipt() + + bounded = reader.collect(CUE, kind="case", limit=1, context_bytes=128, **options) + assert bounded["retrieval"]["items"] == [observed] + assert bounded["contexts"] == [] + omission, = bounded["context_omissions"] + assert (omission["ref"], omission["reason"]) == (ref, "context_limit") + + +def test_explicit_ids_keep_caller_order_under_alternative_policy(library): + reader = KnowledgeReader(skill_root=library) + refs = ["checkout:" + A, "checkout:" + B] + pins = {ref: reader.read(ref).revision for ref in refs} + result = reader.collect( + ids=refs, revisions=pins, relevance=CUE, ranking_policy=ALTERNATE, context_bytes=2048, + ) + assert [view["ref"] for view in result["items"]] == refs + assert [context["ref"] for context in result["contexts"]] == refs + assert result["selection"]["ranking_applied"] is False diff --git a/tests/knowledge/test_ranking_policy.py b/tests/knowledge/test_ranking_policy.py new file mode 100644 index 000000000..6bc0430f3 --- /dev/null +++ b/tests/knowledge/test_ranking_policy.py @@ -0,0 +1,72 @@ +import math + +import pytest + +from inferrsi.knowledge._skill_selection import FIND_RELEVANCE +from inferrsi.knowledge.knowledge_find import Corpus, Document, rank +from inferrsi.knowledge.knowledge_operations import KnowledgeReader +from inferrsi.knowledge.ranking_policy import DEFAULT_RANKING_POLICY, RankingPolicy + + +def test_effective_weights_are_immutable_and_canonical(): + overrides = {"body": -0.0, "applicability": 3} + policy = RankingPolicy("trial", overrides) + overrides["body"] = 8 + same = RankingPolicy("trial", {"applicability": 3.0, "body": 0}) + assert policy.receipt() == same.receipt() + assert policy.configuration()["weights"] == { + "title": 5, "summary": 4, "tags": 4, "findings": 4, "applicability": 3, "body": 0, + } + assert policy.configuration()["version"] == 1 + assert policy.receipt()["config_sha256"] != RankingPolicy("trial").receipt()["config_sha256"] + with pytest.raises(TypeError): + policy.weights["title"] = 1 + + +@pytest.mark.parametrize("weights", [ + {"typo": 1}, {"body": False}, {"tags": -1}, {"title": float("nan")}, {"body": float("inf")}, + {"summary": 10**400}, +]) +def test_invalid_policy_rejected(weights): + with pytest.raises(ValueError, match="weight"): + RankingPolicy("trial", weights) + + +def test_default_preserves_body_length_idf_backend_and_all_tie_breaks(): + docs = [ + Document(name, "record", state, None, name, "", fields, qualified=ref, backend=backend) + for name, ref, state, fields, backend in [ + ("a", "checkout:a", "candidate", {"body": "probe"}, "ascend"), + ("b", "checkout:b", "validated", {"body": "probe"}, "ascend"), + ("a", "store:a", "validated", {"body": "probe"}, "ascend"), + ("a", "package:a", "validated", {"body": "probe"}, "ascend"), + ("long", "store:long", "validated", {"body": "probe a b c"}, "cuda"), + ("none", "store:none", "validated", {"body": "other"}, "ascend"), + ] + ] + corpus = Corpus(docs) + idf = math.log(7 / 6) + 1 + assert corpus.score(4, ["probe"], query_backend="ascend")[0] == pytest.approx(idf / 4) + for args in [(), (DEFAULT_RANKING_POLICY,)]: + _, _, rows = rank("probe", corpus, *args) + assert [docs[i].qualified for _, _, i, _ in rows] == [ + "package:a", "store:a", "checkout:b", "checkout:a", "store:long", + ] + assert [r[0] for r in rows] == pytest.approx([idf] * 4 + [idf / 2]) + + +def test_packaged_service_uses_same_weights_without_content_fingerprints(): + reader = KnowledgeReader() + args = {"relevance_method": FIND_RELEVANCE, "limit": 1, "context_bytes": 65536} + implicit = reader.collect_service_context("cgroupv2", **args) + explicit = reader.collect_service_context( + "cgroupv2", **args, ranking_policy=DEFAULT_RANKING_POLICY, + ) + assert implicit == explicit + context, = implicit["contexts"] + assert context["ref"] == "package:inferrsi.common.skills.cgroup_resource_controls" + assert implicit["request"]["ranking_policy"] == DEFAULT_RANKING_POLICY.configuration() + zero = RankingPolicy("zero", dict.fromkeys(DEFAULT_RANKING_POLICY.weights, 0)) + other = reader.collect_service_context("cgroupv2", **args, ranking_policy=zero) + assert other["request"]["ranking_policy"] == zero.configuration() + assert other["contexts"] == [] From e3489a3be925d03552a501aaf1a9bc50244d4375 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:12:17 +0800 Subject: [PATCH 2/3] Reject nonfinite ranking scores before context delivery Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- src/inferrsi/knowledge/README.md | 6 ++++-- src/inferrsi/knowledge/knowledge_find.py | 2 ++ tests/knowledge/test_ranking_policy.py | 11 +++++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/inferrsi/knowledge/README.md b/src/inferrsi/knowledge/README.md index a5738a2f4..ad2f0f5c5 100644 --- a/src/inferrsi/knowledge/README.md +++ b/src/inferrsi/knowledge/README.md @@ -12,8 +12,10 @@ Benchmark owns assessment of the results those workflows produce. files at a pinned revision. - [`RankingPolicy`](ranking_policy.py) supplies field weights to Find and Collect. For example, pass `ranking_policy=RankingPolicy("trial", {"applicability": 3})` - to compare results against the default on the same library. A ranked Collect - records the version and effective weights in `retrieval.selection.ranking_policy`. + to compare results against the default on the same library. Collect records + its version and effective weights in `retrieval.selection.ranking_policy` when + 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. - [`knowledge_store.py`](knowledge_store.py) exposes `KnowledgeStore.create` and `update` for an authorized writable store. The packaged library is authored diff --git a/src/inferrsi/knowledge/knowledge_find.py b/src/inferrsi/knowledge/knowledge_find.py index 810698960..e5fec6f5e 100644 --- a/src/inferrsi/knowledge/knowledge_find.py +++ b/src/inferrsi/knowledge/knowledge_find.py @@ -661,6 +661,8 @@ def score( gain = weight * field_weight * math.sqrt(hits) total += gain detail[token] = round(detail.get(token, 0.0) + gain, 2) + if not math.isfinite(total) or not all(map(math.isfinite, detail.values())): + raise ValueError(f"Ranking score overflow for policy {ranking_policy.policy_id!r}") return total, detail diff --git a/tests/knowledge/test_ranking_policy.py b/tests/knowledge/test_ranking_policy.py index 6bc0430f3..d8ac3e2b7 100644 --- a/tests/knowledge/test_ranking_policy.py +++ b/tests/knowledge/test_ranking_policy.py @@ -1,4 +1,5 @@ import math +import sys import pytest @@ -70,3 +71,13 @@ def test_packaged_service_uses_same_weights_without_content_fingerprints(): other = reader.collect_service_context("cgroupv2", **args, ranking_policy=zero) assert other["request"]["ranking_policy"] == zero.configuration() assert other["contexts"] == [] + + +def test_service_rejects_finite_weights_that_overflow_a_score(): + weights = dict.fromkeys(DEFAULT_RANKING_POLICY.weights, sys.float_info.max) + policy = RankingPolicy("large", weights) + with pytest.raises(ValueError, match="Ranking score overflow for policy 'large'"): + KnowledgeReader().collect_service_context( + "cgroupv2", relevance_method=FIND_RELEVANCE, limit=1, + context_bytes=65536, ranking_policy=policy, + ) From e5cb11eb372ab55cd220ae02b3b818a0ff9c1151 Mon Sep 17 00:00:00 2001 From: Dong1017 <55723162+Dong1017@users.noreply.github.com> Date: Wed, 25 Nov 2026 19:34:50 +0800 Subject: [PATCH 3/3] Refresh the retrieval review fixture and register its new consumer Agent-assisted-by: Codex / gpt-6.2-astra [effort=max] (author) Signed-off-by: Dong1017 <55723162+Dong1017@users.noreply.github.com> --- docs/apps-module-migrations.json | 1 + docs/examples/dashboard-profile-review.html | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/apps-module-migrations.json b/docs/apps-module-migrations.json index cff09bbdd..9256effd3 100644 --- a/docs/apps-module-migrations.json +++ b/docs/apps-module-migrations.json @@ -235,6 +235,7 @@ "tests/apps/test_apps_module_migrations.py", "tests/apps/test_campaign_record_injection.py", "tests/apps/test_campaign_task_selection.py", + "tests/apps/test_indexer_deliveries.py", "tests/apps/test_knowledge_navigation_browser.py", "tests/apps/test_optimization_session.py", "tests/apps/test_optimization_story.py", diff --git a/docs/examples/dashboard-profile-review.html b/docs/examples/dashboard-profile-review.html index a4c275065..0e73f6339 100644 --- a/docs/examples/dashboard-profile-review.html +++ b/docs/examples/dashboard-profile-review.html @@ -1144,7 +1144,7 @@
}}; - +