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
2 changes: 2 additions & 0 deletions src/inferrsi/apps/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def _round_provider(plan):

def _optimization_session(args, *, task_source=None, report_metadata=None):
from ...harness.optimization_session import session_command
from ...knowledge.ranking_policy import managed_ranking_policy

settings = None
external_project = None
Expand All @@ -46,6 +47,7 @@ def _optimization_session(args, *, task_source=None, report_metadata=None):
external_project = freeze_project(args.repo if args.project_task else None)
return session_command(
args, task_source=task_source, retain_context=capture_context,
ranking_policy_for=managed_ranking_policy,
knowledge_reader=KnowledgeReader() if args.session_action == "knowledge" else None,
external_knowledge=settings, external_project=external_project,
external_provider_for=_round_provider,
Expand Down
4 changes: 4 additions & 0 deletions src/inferrsi/apps/cli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,10 @@ def _optimization_actions(stages, *, project=False):
start.add_argument("--condition", default="current-agent" if project else None,
required=not project)
start.add_argument("--knowledge", choices=("on", "off"), default="on")
from ...knowledge.ranking_policy import MANAGED_RANKING_POLICIES

start.add_argument("--ranking-policy", choices=tuple(MANAGED_RANKING_POLICIES),
default="default", help="Freeze the Knowledge ranking rule for this session")
from ..integrations.cannbot.project import PLATFORMS

start.add_argument("--cannbot-platform", choices=PLATFORMS,
Expand Down
9 changes: 8 additions & 1 deletion src/inferrsi/apps/workflows/campaign.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "",
backend: str | None = None, scenario: str | None = None,
limit: int = 5, context_bytes: int = 65536,
sources: tuple[str, ...] = ("package",),
ranking_policy=None,
diagnosis_binding: dict | None = None) -> tuple[Path, str]:
"""Run ``collect`` with a context budget and keep its complete envelope.

Expand All @@ -55,10 +56,11 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "",
if backend is None:
backend = campaign.get("backend")
pins = {"revisions": revisions} if revisions else {}
ranking = {"ranking_policy": ranking_policy} if ranking_policy is not None else {}
result = reader.collect(
query, ids=ids, kind=kind, repo=repo, tier=tier, backend=backend,
scenario=scenario, limit=limit, relevance=relevance,
relevance_method=relevance_method, context_bytes=context_bytes, **pins,
relevance_method=relevance_method, context_bytes=context_bytes, **pins, **ranking,
)
observation = result.get("retrieval")
source_types = list(sources)
Expand All @@ -72,6 +74,11 @@ def capture_context(root: Path, *, context_id: str, reader, query: str = "",
"backend": backend, "scenario": scenario, "limit": limit,
"context_bytes": context_bytes, "sources": source_types, **pins,
}
if ranking_policy is not None:
effective = ranking_policy.receipt()
if (observation or {}).get("selection", {}).get("ranking_policy") != effective:
raise ValueError("Delivered ranking policy differs from the frozen session")
request["ranking_policy"] = effective
if _supplies_no_observation(result):
# Such a reader gets the record this entry wrote before observations
# existed: the same fields, order and bytes, with no empty provenance.
Expand Down
32 changes: 32 additions & 0 deletions src/inferrsi/harness/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,38 @@ measurement and assessment rules.
receipts and budget accounting in the shared RunStore. See the
[speculative search design](../../../docs/guides/speculative-search.md) for recovery rules.

## Managed optimization loop

`campaign` and `benchmarks session` enter through [session_command](optimization_session.py).
The agent chooses a hypothesis and edits a candidate between rounds.

- **Analyzer.** The agent supplies the measured bottleneck and its evidence.
[record_diagnosis](optimization.py) retains that evidence and binds later deliveries
and rounds to the diagnosis.
- **Indexer.** Knowledge [ranks matches](../knowledge/knowledge_find.py) and assembles
context within the requested byte budget. Inspect the capture for delivered material,
source revisions and omissions. Start a fresh session with `--ranking-policy applicability`
to raise the applicability weight from 2 to 3. The default keeps the original six weights.
- **Executor.** [The round controller](optimization.py) owns attempts, time and round
budgets, pending work, recovery and final retests. It dispatches the retained candidate
to the task runner or the [service lifecycle](project_service.py).
- **Evaluator.** [_session_assess](optimization_session.py) dispatches packaged tasks to
their frozen assessment protocol and projects to [the AB/BA assessor](project.py).
In service mode, the optional screening report is diagnostic. Formal performance
and quality measurements in [evaluate](project_service.py) determine acceptance.

New plans freeze the ranking ID, scoring version and all effective weights. Ordinary
plans and delivery receipts include a configuration digest. Service plans, manifests
and deliveries retain the values directly. Use the original runtime to continue a
historical plan without these fields or a session whose installed rule has changed.

To reproduce a ranking experiment, pin the scoring runtime revision and the complete
eligible corpus alongside the query, filters and policy. Document frequency and median
body length depend on entries outside the delivered context. The [ranking regression](../../../tests/apps/test_indexer_deliveries.py)
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.

## Evaluate retained runs

With the Apps saved-request CLI, a trusted caller allocates the attempt before
Expand Down
43 changes: 42 additions & 1 deletion src/inferrsi/harness/optimization.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,36 @@ def initialize(root: Path, plan: dict) -> dict:
return status(root)


def _require_ranking_policy(recorded, effective):
if (not isinstance(recorded, dict) or not isinstance(effective, dict)
or type(recorded.get("version")) is not int
or not isinstance(recorded.get("weights"), dict)
or any(type(value) not in (int, float) for value in recorded["weights"].values())
or recorded != effective):
raise ValueError("Frozen ranking policy changed or is incomplete, use its original runtime")


def resolve_frozen_ranking(plan, ranking_policy_for, *, read_only=False):
if read_only and "ranking_policy" not in plan:
return None
recorded = plan.get("ranking_policy")
if not isinstance(recorded, dict) or not isinstance(recorded.get("id"), str):
raise ValueError("Missing frozen ranking policy, use the original runtime to resume")
if ranking_policy_for is None:
raise ValueError("A resolver for the frozen ranking policy is required")
policy = ranking_policy_for(recorded["id"])
effective = (policy.configuration() if plan.get("evaluation_mode") == "service_reuse"
else policy.receipt())
_require_ranking_policy(recorded, effective)
return policy


def _check_context_ranking(plan, context):
if "ranking_policy" in plan:
_require_ranking_policy(context.get("request", {}).get("ranking_policy"),
plan["ranking_policy"])


def _control(root):
plan = json.loads((root / "plan.json").read_text(encoding="utf-8"))
state = json.loads((root / "state.json").read_text(encoding="utf-8"))
Expand All @@ -82,6 +112,8 @@ def _control(root):
)
):
raise ValueError("Incompatible service campaign records")
if "ranking_policy" in manifest or "ranking_policy" in plan:
_require_ranking_policy(manifest.get("ranking_policy"), plan.get("ranking_policy"))
service.no_fingerprints(plan)
service.no_fingerprints(state)
return plan, state
Expand Down Expand Up @@ -129,6 +161,7 @@ def _load(root, *, read_only=False):
retained = _read_context(root, context)
if context.get("kind") not in ("external_search", "external_read"):
_check_context_diagnosis(plan, diagnoses, context, retained)
_check_context_ranking(plan, retained)
contexts[context["path"]] = context
for record in [*state["rounds"], *([state["final"]] if state["final"] else [])]:
directory = root / record["path"]
Expand Down Expand Up @@ -806,6 +839,7 @@ def _service_initialize(root, plan):
"evaluation_mode": "service_reuse",
"protocol_id": state["protocol_id"],
"diagnosis_required": plan.get("diagnosis_required", False),
**({"ranking_policy": plan["ranking_policy"]} if "ranking_policy" in plan else {}),
},
)
atomic_write_json(root / "state.json", state)
Expand Down Expand Up @@ -838,6 +872,7 @@ def _service_load(root, plan, state, *, read_only=False):
_check_activity_diagnosis(plan, diagnoses, attempt)
for context in state["contexts"]:
retained = service.read(service.safe_path(root, context["path"]))
_check_context_ranking(plan, retained)
_check_context_diagnosis(plan, diagnoses, context, retained)
for event in state["recovery_events"]:
if event["kind"] == "cleanup_inspection":
Expand Down Expand Up @@ -1330,7 +1365,7 @@ def _service_cleanup_receipt(root, state, path):
atomic_write_json(root / "state.json", state)


def service_command(root, args, *, knowledge_reader=None):
def service_command(root, args, *, ranking_policy_for=None, knowledge_reader=None):
"""Service-mode operations inside the shared controller's lock and control record."""
from . import project_service as service
from . import service_evidence
Expand All @@ -1340,8 +1375,12 @@ def service_command(root, args, *, knowledge_reader=None):
if action == "profile":
from . import service_backfill

plan, _ = _control(root)
resolve_frozen_ranking(plan, ranking_policy_for)
return service_backfill.run(root, args)
plan, state = _load(root, read_only=action == "status")
ranking_policy = resolve_frozen_ranking(plan, ranking_policy_for,
read_only=action == "status")
if getattr(args, "cleanup_receipt", None) is not None:
_service_cleanup_receipt(root, state, args.cleanup_receipt)
if action == "status":
Expand Down Expand Up @@ -1416,7 +1455,9 @@ def service_command(root, args, *, knowledge_reader=None):
relevance_method=args.relevance_method,
limit=args.limit,
context_bytes=args.context_bytes,
ranking_policy=ranking_policy,
)
_check_context_ranking(plan, context)
if binding:
context["diagnosis_binding"] = binding
service.no_fingerprints(context)
Expand Down
20 changes: 16 additions & 4 deletions src/inferrsi/harness/optimization_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,13 @@ def _runtime_identity():
"harness/protocol_child.py",
"harness/candidates.py", "harness/project.py", "harness/measurement.py",
"harness/records/knowledge_capture.py", "apps/workflows/campaign.py",
"knowledge/context_projection.py")
"knowledge/context_projection.py", "knowledge/knowledge_find.py",
"knowledge/ranking_policy.py")
return {name: sha256(root / name) for name in names}


def session_command(args, *, task_source: Path | None = None, knowledge_reader=None,
def session_command(args, *, ranking_policy_for, task_source: Path | None = None,
knowledge_reader=None,
retain_context=None, external_knowledge=None, external_provider=None,
external_project=None, external_provider_for=None,
report_metadata=None) -> dict:
Expand All @@ -148,6 +150,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N
raise ValueError("A positive round/time budget and condition label are required")
if root.exists():
raise ValueError("Session directory must be new")
ranking_policy = ranking_policy_for(args.ranking_policy)
reserve = (args.final_reserve_seconds if args.final_reserve_seconds is not None
else args.evaluation_timeout_seconds)
if not math.isfinite(reserve) or not 0 < reserve < args.max_minutes * 60:
Expand Down Expand Up @@ -195,6 +198,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N
"round_mode": args.round_mode,
"final_reserve_seconds": reserve,
"knowledge_allowed": args.knowledge == "on",
"ranking_policy": ranking_policy.configuration(),
"evaluation_timeout_seconds": args.evaluation_timeout_seconds,
"evaluation_prefix": evaluation_prefix,
"python": args.python,
Expand Down Expand Up @@ -258,6 +262,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N
"round_limit": args.rounds, "max_seconds": args.max_minutes * 60,
"round_mode": args.round_mode, "final_reserve_seconds": reserve,
"knowledge_allowed": args.knowledge == "on",
"ranking_policy": ranking_policy.receipt(),
"evaluation_timeout_seconds": args.evaluation_timeout_seconds,
"evaluation_prefix": evaluation_prefix, "python": args.python,
"runtime_identity": _runtime_identity(), **candidate, **settings}
Expand Down Expand Up @@ -295,7 +300,9 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N
):
if args.session_action == "profile":
try:
return optimization.service_command(root, args)
return optimization.service_command(
root, args, ranking_policy_for=ranking_policy_for,
)
except (ValueError, OSError) as exc:
message = "Campaign lock is busy" if isinstance(exc, BlockingIOError) else str(exc)
return {
Expand All @@ -312,7 +319,8 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N
if getattr(args, "alternative", None) is not None or getattr(
args, "selection_reason", None) is not None:
raise ValueError("Round decision declarations require a benchmark or AB/BA campaign")
return optimization.service_command(root, args, knowledge_reader=knowledge_reader)
return optimization.service_command(root, args, knowledge_reader=knowledge_reader,
ranking_policy_for=ranking_policy_for)
if (
args.session_action in ("baseline", "refresh-references", "resume", "profile")
or getattr(args, "retry_of", None)
Expand All @@ -323,6 +331,9 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N
raise ValueError("Service lifecycle/retry operations require a service-reuse campaign")
if plan["runtime_identity"] != _runtime_identity():
raise ValueError("Optimization runtime changed, use its frozen runtime to resume")
ranking_policy = optimization.resolve_frozen_ranking(
plan, ranking_policy_for, read_only=args.session_action == "status",
)
if args.session_action == "status":
return optimization.status(root)
if args.session_action == "diagnose":
Expand All @@ -334,6 +345,7 @@ def session_command(args, *, task_source: Path | None = None, knowledge_reader=N
root,
knowledge_reader,
retain_context=retain_context,
ranking_policy=ranking_policy,
external_provider=external_provider,
external_provider_for=external_provider_for,
query="",
Expand Down
14 changes: 14 additions & 0 deletions src/inferrsi/knowledge/ranking_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,17 @@ def receipt(self) -> dict:


DEFAULT_RANKING_POLICY = RankingPolicy()

MANAGED_RANKING_POLICIES = MappingProxyType({
"default": DEFAULT_RANKING_POLICY,
"applicability": RankingPolicy("applicability", {"applicability": 3}),
})


def managed_ranking_policy(name: str) -> RankingPolicy:
try:
return MANAGED_RANKING_POLICIES[name]
except KeyError:
raise ValueError(
f"Unknown frozen ranking policy {name!r}, use its original runtime"
) from None
50 changes: 35 additions & 15 deletions tests/apps/test_indexer_deliveries.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import hashlib
import json
import shutil
from pathlib import Path

import pytest

Expand All @@ -11,25 +13,12 @@
CUE = "qxrankprobe"
A, B = "case.qxrankprobe", "case.alternate"
ALTERNATE = RankingPolicy("applicability", {"applicability": 3})
FROZEN_CORPUS = Path(__file__).resolve().parents[1] / "fixtures" / "indexer" / "ranking-corpus"


@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
return shutil.copytree(FROZEN_CORPUS, tmp_path / "library")


@pytest.mark.parametrize(("options", "order", "scores", "source"), [
Expand Down Expand Up @@ -76,6 +65,37 @@ def test_find_collect_and_retained_context(library, tmp_path, options, order, sc
assert (omission["ref"], omission["reason"]) == (ref, "context_limit")


def test_undelivered_corpus_change_preserves_capture_but_changes_ranking(library, tmp_path):
def collect():
reader = KnowledgeReader(skill_root=library)
return reader.collect(f"{CUE} alpha", kind="case", limit=1, context_bytes=2048)

original = collect()
campaign = tmp_path / "run"
create_campaign(campaign, "replay")
path, _ = save_retrieval(campaign, context_id="original", result=original)

cases = library / "demo" / "cases"
extra = json.loads((cases / "alpha.json").read_text(encoding="utf-8"))
extra.update(id="case.extra", content="extra.md")
(cases / "extra.json").write_text(json.dumps(extra), encoding="utf-8")
(cases / "extra.md").write_bytes(f"{CUE}\n".encode())
changed = collect()

saved, state = verify_capture(path.read_bytes())
assert state == "verified"
assert saved["retrieval"]["items"] == original["retrieval"]["items"]
before, = saved["retrieval"]["items"]
after, = changed["retrieval"]["items"]
assert before["ref"] == after["ref"] == "checkout:" + A
assert before["revision"] == after["revision"]
assert before["score"] != after["score"]
assert original["contexts"] == changed["contexts"]
assert "source alpha\n" in saved["assembled_text"]
assert saved["retrieval"]["counts"]["excluded"]["item_limit"] == 1
assert changed["retrieval"]["counts"]["excluded"]["item_limit"] == 2


def test_explicit_ids_keep_caller_order_under_alternative_policy(library):
reader = KnowledgeReader(skill_root=library)
refs = ["checkout:" + A, "checkout:" + B]
Expand Down
Loading
Loading