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
123 changes: 123 additions & 0 deletions src/inferrsi/knowledge/ranking_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import sys
from collections.abc import Mapping
from dataclasses import dataclass, field
from decimal import Decimal
from fractions import Fraction
from types import MappingProxyType

# Bump when the scoring or tie-breaking semantics change.
Expand Down Expand Up @@ -48,9 +50,130 @@ def receipt(self) -> dict:
raw = json.dumps(configuration, sort_keys=True, separators=(",", ":")).encode("utf-8")
return {**configuration, "config_sha256": hashlib.sha256(raw).hexdigest()}

@classmethod
def from_configuration(cls, configuration: Mapping) -> RankingPolicy:
"""Rebuild a policy from a frozen configuration or receipt and verify it.

The configuration must name every weight field, carry no extra fields or
hooks, use the current scoring version and, when it carries
``config_sha256``, match its own digest.
"""
if not isinstance(configuration, Mapping):
raise ValueError("Ranking configuration must be a mapping")
keys = set(configuration)
if keys - {"config_sha256"} != {"id", "version", "weights"}:
raise ValueError("Ranking configuration requires id, version and weights only")
version = configuration["version"]
if type(version) is not int or version != RANKING_VERSION:
raise ValueError(
f"Ranking configuration version {version!r} differs from {RANKING_VERSION}"
)
weights = configuration["weights"]
if not isinstance(weights, Mapping) or set(weights) != set(_DEFAULT_WEIGHTS):
raise ValueError("Ranking configuration must list every weight field")
policy = cls(configuration["id"], dict(weights))
if any(policy.weights[name] != weights[name] for name in weights):
raise ValueError("Ranking configuration weights are not canonical")
if "config_sha256" in configuration and (
configuration["config_sha256"] != policy.receipt()["config_sha256"]
):
raise ValueError("Ranking configuration digest does not match its weights")
return policy


DEFAULT_RANKING_POLICY = RankingPolicy()


@dataclass(frozen=True)
class RankingSpace:
"""Caller-declared editable weights: inclusive bounds and a step per field.

Fields absent from ``bounds`` stay fixed at ``base``'s effective weights
(defaulting to ``DEFAULT_RANKING_POLICY``). Bounds belong to a frozen
experiment plan; this module declares no default search range. Step
membership is decided by exact rational divisibility of the shortest
decimal form of each value, so ``0.3`` lies on a ``0.1`` grid regardless of
binary rounding, and the result does not depend on magnitude or the
caller's decimal context.
"""

bounds: Mapping[str, tuple[float, float, float]]
base: RankingPolicy = DEFAULT_RANKING_POLICY

def __post_init__(self) -> None:
if not isinstance(self.base, RankingPolicy):
raise ValueError("Ranking space base must be a RankingPolicy")
if not isinstance(self.bounds, Mapping) or not self.bounds:
raise ValueError("Ranking space requires at least one editable weight field")
if self.bounds.keys() - _DEFAULT_WEIGHTS.keys():
raise ValueError("Unknown ranking weight field in ranking space")
canonical = {}
for name, bound in self.bounds.items():
if not isinstance(bound, (tuple, list)) or len(bound) != 3 or any(
type(value) not in (float, int)
or not -sys.float_info.max <= value <= sys.float_info.max
for value in bound
):
raise ValueError(f"Ranking space for {name} needs finite minimum, maximum and step")
low, high, step = (float(value) for value in bound)
if not 0 <= low <= high or step <= 0:
raise ValueError(
f"Ranking space for {name} needs 0 <= minimum <= maximum, step > 0"
)
canonical[name] = (low + 0.0, high + 0.0, step)
object.__setattr__(self, "bounds", MappingProxyType(dict(sorted(canonical.items()))))

def document(self) -> dict:
return {
"version": RANKING_VERSION,
"base": self.base.configuration(),
"fixed": {k: v for k, v in self.base.weights.items() if k not in self.bounds},
"bounds": {k: list(v) for k, v in self.bounds.items()},
}

def digest(self) -> str:
raw = json.dumps(self.document(), sort_keys=True, separators=(",", ":")).encode("utf-8")
return hashlib.sha256(raw).hexdigest()

def check(self, policy: RankingPolicy) -> RankingPolicy:
"""Return ``policy`` if every weight lies inside this space, else raise."""
if not isinstance(policy, RankingPolicy):
raise ValueError("Ranking space checks a RankingPolicy")
for name, value in policy.weights.items():
if name not in self.bounds:
if value != self.base.weights[name]:
raise ValueError(
f"Ranking weight for {name} is fixed at {self.base.weights[name]} "
"in this space"
)
continue
low, high, step = self.bounds[name]
steps = (_exact(value) - _exact(low)) / _exact(step)
if not low <= value <= high or steps.denominator != 1:
raise ValueError(
f"Ranking weight for {name} must lie on [{low}, {high}] in steps of {step}"
)
return policy

def apply(self, policy_id: str, overrides: Mapping[str, float]) -> RankingPolicy:
"""Derive a candidate from ``base`` with partial ``overrides`` and check it."""
if not isinstance(overrides, Mapping):
raise ValueError("Ranking space overrides must be a mapping")
if overrides.keys() - _DEFAULT_WEIGHTS.keys():
raise ValueError("Unknown ranking weight field")
for name in overrides:
if name not in self.bounds:
raise ValueError(
f"Ranking weight for {name} is fixed at {self.base.weights[name]} in this space"
)
return self.check(RankingPolicy(policy_id, {**self.base.weights, **overrides}))


def _exact(value: float) -> Fraction:
# The shortest decimal form, as an exact rational: no rounding, no Decimal context.
return Fraction(Decimal(repr(float(value))))


MANAGED_RANKING_POLICIES = MappingProxyType({
"default": DEFAULT_RANKING_POLICY,
"applicability": RankingPolicy("applicability", {"applicability": 3}),
Expand Down
166 changes: 165 additions & 1 deletion tests/knowledge/test_ranking_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@

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
from inferrsi.knowledge.ranking_policy import (
DEFAULT_RANKING_POLICY,
MANAGED_RANKING_POLICIES,
RankingPolicy,
RankingSpace,
)


def test_effective_weights_are_immutable_and_canonical():
Expand Down Expand Up @@ -82,3 +87,162 @@ def test_service_rejects_finite_weights_that_overflow_a_score(tmp_path):
KnowledgeReader().find(
"cgroupv2", limit=1, retained_source=tmp_path / "find-overflow", ranking_policy=policy,
)


@pytest.mark.parametrize(
"policy", [*MANAGED_RANKING_POLICIES.values(), RankingPolicy("t", {"body": 0})]
)
def test_frozen_configuration_and_receipt_rebuild_the_same_policy(policy):
for frozen in (policy.configuration(), policy.receipt()):
rebuilt = RankingPolicy.from_configuration(frozen)
assert rebuilt == policy
assert rebuilt.receipt() == policy.receipt()


def test_named_policy_receipts_are_unchanged():
assert DEFAULT_RANKING_POLICY.receipt() == {
"id": "default", "version": 1,
"weights": {"title": 5.0, "summary": 4.0, "tags": 4.0, "findings": 4.0,
"applicability": 2.0, "body": 1.0},
"config_sha256": RankingPolicy.from_configuration(
DEFAULT_RANKING_POLICY.configuration()).receipt()["config_sha256"],
}
applicability = MANAGED_RANKING_POLICIES["applicability"]
assert applicability.receipt() == {
"id": "applicability", "version": 1,
"weights": {"title": 5.0, "summary": 4.0, "tags": 4.0, "findings": 4.0,
"applicability": 3.0, "body": 1.0},
"config_sha256": RankingPolicy.from_configuration(
applicability.configuration()).receipt()["config_sha256"],
}


def _receipt(**changes):
receipt = RankingPolicy("candidate", {"applicability": 3}).receipt()
return {**receipt, **changes}


@pytest.mark.parametrize("frozen, message", [
([], "mapping"),
(_receipt(extra=1), "id, version and weights only"),
(_receipt(scorer="custom"), "id, version and weights only"),
(_receipt(tie_break="custom"), "id, version and weights only"),
({"id": "candidate", "weights": DEFAULT_RANKING_POLICY.configuration()["weights"]},
"id, version and weights only"),
(_receipt(version=2), "version 2 differs"),
(_receipt(version=True), "version True differs"),
(_receipt(weights={"title": 5.0}), "every weight field"),
(_receipt(weights={**DEFAULT_RANKING_POLICY.weights, "typo": 1.0}), "every weight field"),
(_receipt(weights={**DEFAULT_RANKING_POLICY.weights, "body": -1.0}), "weight for body"),
(_receipt(weights={**DEFAULT_RANKING_POLICY.weights, "body": True}), "weight for body"),
(_receipt(id="bad id"), "identifier"),
(_receipt(config_sha256="0" * 64), "digest does not match"),
(_receipt(weights={**DEFAULT_RANKING_POLICY.weights, "applicability": 4.0}),
"digest does not match"),
])
def test_frozen_configuration_rejects_drift_and_malformed_input(frozen, message):
with pytest.raises(ValueError, match=message):
RankingPolicy.from_configuration(frozen)


def test_ranking_space_accepts_on_grid_weights_and_fixes_the_rest():
space = RankingSpace({"applicability": (0, 6, 0.5), "body": (0.0, 2, 1)})
assert space.check(RankingPolicy("a", {"applicability": 3.5, "body": 2})).policy_id == "a"
assert space.check(DEFAULT_RANKING_POLICY) is DEFAULT_RANKING_POLICY
assert space.document() == {
"version": 1,
"base": DEFAULT_RANKING_POLICY.configuration(),
"fixed": {"title": 5.0, "summary": 4.0, "tags": 4.0, "findings": 4.0},
"bounds": {"applicability": [0.0, 6.0, 0.5], "body": [0.0, 2.0, 1.0]},
}
same = RankingSpace({"body": [0, 2, 1], "applicability": (0.0, 6.0, 0.5)})
assert same.digest() == space.digest()
assert RankingSpace({"body": (0, 3, 1)}).digest() != space.digest()


def test_ranking_space_preserves_explicit_base_policy_weights():
base = MANAGED_RANKING_POLICIES["applicability"]
space = RankingSpace({"body": (0, 2, 0.5)}, base=base)
derived = space.apply("trial-body", {"body": 2.0})
assert derived.weights["applicability"] == 3.0
assert derived.weights["body"] == 2.0
assert space.document()["base"] == base.configuration()
assert space.document()["fixed"]["applicability"] == 3.0
assert space.digest() != RankingSpace({"body": (0, 2, 0.5)}).digest()

# A candidate that silently reverted applicability to default (2.0) is rejected.
with pytest.raises(ValueError, match="applicability is fixed at 3.0"):
space.check(RankingPolicy("reverted", {"body": 2.0}))
with pytest.raises(ValueError, match="applicability is fixed at 3.0"):
space.apply("edit-fixed", {"applicability": 4.0})
with pytest.raises(ValueError, match="Unknown ranking weight field"):
space.apply("edit-unknown", {"typo": 1.0})
with pytest.raises(ValueError, match="must lie on"):
space.apply("off-grid", {"body": 0.25})
with pytest.raises(ValueError, match="base must be a RankingPolicy"):
RankingSpace({"body": (0, 2, 0.5)}, base="applicability")


@pytest.mark.parametrize("weights, message", [
({"applicability": 6.5}, "must lie on"),
({"applicability": -0.5}, "weight for applicability"),
({"applicability": 3.25}, "must lie on"),
({"title": 6}, "title is fixed"),
])
def test_ranking_space_rejects_out_of_range_off_grid_and_fixed_edits(weights, message):
space = RankingSpace({"applicability": (0, 6, 0.5)})
with pytest.raises(ValueError, match=message):
space.check(RankingPolicy("candidate", weights))


@pytest.mark.parametrize("bounds, message", [
({}, "at least one"),
({"typo": (0, 1, 1)}, "Unknown ranking weight field"),
({"body": (0, 1)}, "finite minimum"),
({"body": (0, float("inf"), 1)}, "finite minimum"),
({"body": (0, float("nan"), 1)}, "finite minimum"),
({"body": (0, 10**400, 1)}, "finite minimum"),
({"body": (0, 1, 10**400)}, "finite minimum"),
({"body": (-10**400, 1, 1)}, "finite minimum"),
({"body": (0, 1, True)}, "finite minimum"),
({"body": (2, 1, 1)}, "minimum <= maximum"),
({"body": (-1, 1, 1)}, "minimum <= maximum"),
({"body": (0, 1, 0)}, "step > 0"),
])
def test_ranking_space_rejects_malformed_bounds(bounds, message):
with pytest.raises(ValueError, match=message):
RankingSpace(bounds)


@pytest.mark.parametrize("bound, value, accepted", [
((0, 1, 0.1), 0.3, True), ((0, 1, 0.1), 0.7, True), ((0, 1, 0.1), 1.0, True),
((0, 1, 0.1), 0.35, False), ((0.1, 0.7, 0.2), 0.7, True), ((0.1, 0.7, 0.2), 0.6, False),
((0, 1, 0.1), 1.0000000001, False), ((0, 1, 3e-30), 1.0, False),
((0, 1, 3e-30), 3e-29, True), ((0, 1e30, 3), 1e30, False),
((0, 1e30, 3), 3e29, True), ((0, 1e30, 3), 2e29, False),
((0, 1e30, 2), 1e30, True), ((0, 1e30, 0.5), 7.5e29, True),
])
def test_ranking_space_step_membership_uses_decimal_values(bound, value, accepted):
space, policy = RankingSpace({"body": bound}), RankingPolicy("candidate", {"body": value})
if accepted:
assert space.check(policy) is policy
else:
with pytest.raises(ValueError, match="must lie on"):
space.check(policy)


def test_ranking_space_step_membership_ignores_the_callers_decimal_context():
import decimal

space = RankingSpace({"body": (0, 1e30, 3)})
small = RankingSpace({"body": (0, 1, 3e-30)})
with decimal.localcontext() as context:
context.prec = 3
context.traps[decimal.Inexact] = True
with pytest.raises(ValueError, match="must lie on"):
space.check(RankingPolicy("candidate", {"body": 1e30}))
with pytest.raises(ValueError, match="must lie on"):
small.check(RankingPolicy("candidate", {"body": 1.0}))
assert RankingSpace({"body": (0, 1, 0.1)}).check(
RankingPolicy("candidate", {"body": 0.3})
).weights["body"] == 0.3
Loading