Skip to content
Open
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@

### Added

- A service-reuse round can cite a Read receipt with `session round --knowledge-ref`
(Refs #893). The receipt must come from the same session and from the current
references: Find receipts, receipts from another session and receipts read before a
reference refresh are refused before a round slot or candidate is started. The citation
is stored on the attempt and shown in `session status`; a retry records its own. It is
provenance only and does not reach the evaluation protocol or change scoring.
- `tools/phibench_ab.py` runs a Φ-Bench A/B batch with one command: it draws
tasks in the suite's type mix, runs plain Codex and Codex + InferRSI per task
in an isolated run directory, retries unfinished arms on `--resume`, and
Expand Down
4 changes: 3 additions & 1 deletion docs/guides/operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ arguments until no continuation remains. Each page records only its returned
bytes, with UTF-8 boundaries preserved. The continuation keeps the same
resource, revision and search reference.
Cite a used read's `reference.path` with `round --knowledge-ref` in a one-shot
project or benchmark. A service-reuse attempt retains prepared contexts
project, a benchmark or a service-reuse campaign. A service-reuse round accepts
only a Read receipt delivered since the last reference refresh, and `session status`
lists each round's citations. Its attempt also retains prepared contexts
automatically. Record any passage that influenced the candidate in its
hypothesis. If the host clipped an asynchronous round's response, use
`session status --session DIR --round-receipt N` before closing the archive.
Expand Down
5 changes: 3 additions & 2 deletions src/inferrsi/apps/cli/arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,8 +289,9 @@ def _optimization_actions(stages, *, project=False, historical=False, typed_star
stage.add_argument("--selection-reason",
help="Why this candidate was chosen to try (benchmark or AB/BA)")
stage.add_argument("--knowledge-ref", action="append",
help="Cite a read receipt in a benchmark or AB/BA campaign round "
"(path, path#item-ref, or CANNBot receipt; repeatable)")
help="Cite a read receipt in a benchmark, AB/BA or service-reuse "
"round (repeatable). Benchmark/AB-BA: path, path#item-ref, "
"or CANNBot receipt. Service-reuse: local Read receipt path only.")
stage.add_argument("--mechanism-file", type=Path,

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.

This help line now reads as if a CANNBot receipt works in a service-reuse round, but that mode only accepts a local Read receipt. Could you separate the accepted forms by mode so users can tell which reference they can pass?

help="JSON mechanism with expected region/counter directions")
if project:
Expand Down
2 changes: 0 additions & 2 deletions src/inferrsi/harness/manager/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,8 +306,6 @@ def run_session(
if getattr(request, "alternative", None) is not None or getattr(
request, "selection_reason", None) is not None:
raise ValueError("Round decision declarations require a benchmark or AB/BA campaign")
if getattr(request, "knowledge_ref", None) is not None:
raise ValueError("Round knowledge references require a benchmark or AB/BA campaign")
result = state.service_command(root, request, ranking_policy_for=ranking_policy_for)
if request.action in ("round", "recover"):
return state.continue_static_round(
Expand Down
27 changes: 25 additions & 2 deletions src/inferrsi/harness/manager/_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -874,7 +874,8 @@ def read_external_context(root: Path, provider, *, search_ref, locator, page,
return {"reference": delivered, "receipt": receipt, "context": body}


def _validate_knowledge_refs(root, contexts, refs):
def _validate_knowledge_refs(root, contexts, refs, read_capture=None):
read_capture = read_capture or (lambda ref: knowledge_capture.read_retained(root, ref))
if not isinstance(refs, list) or any(not isinstance(ref, str) for ref in refs):
raise ValueError("Knowledge references must be a list of delivered references")
if len(set(refs)) != len(refs):
Expand All @@ -887,7 +888,7 @@ def _validate_knowledge_refs(root, contexts, refs):
if reference is None or (separator and reference["kind"] != "delivered_context"):
raise ValueError("Cite a delivered context or CANNBot read receipt from this session")
if reference["kind"] == "delivered_context":
capture = knowledge_capture.read_retained(root, reference)
capture = read_capture(reference)
if not any(not separator or entry["ref"] == item
for entry in knowledge_capture.delivered_contexts(capture)):
raise ValueError("Cite an item with delivered resources from this context")
Expand All @@ -899,6 +900,21 @@ def _validate_knowledge_refs(root, contexts, refs):
raise ValueError("Cite a scoped Read receipt; legacy captures are audit-only")


def _validate_service_knowledge_refs(root, state, refs):
"""Cite only Read receipts delivered since the last reference refresh."""
if any("#" in ref for ref in refs):
raise ValueError("Service-reuse rounds cite a Read receipt without #item")
_validate_knowledge_refs(
root, state["contexts"], refs,
read_capture=lambda ref: service_io.read(service_io.safe_path(root, ref["path"])),

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.

Dot, acting for @david6666666.

CLI help 已经改对了。这里仍复用普通 round 的报错:传入 Find 或未登记的路径时,Cite a delivered context or CANNBot read receipt 会让调用方继续尝试 service-reuse 明确不支持的 CANNBot 路径。当前负例也把这句提示锁住了。建议在 service-reuse 入口用「本 session 的 local Read receipt」报错,普通 round 保留原提示。

)
epochs = {item["id"]: item["reference_epoch"] for item in state.get("diagnoses", ())}
current = {entry["path"] for entry in state["contexts"]
if epochs.get(entry.get("diagnosis_id")) == state["reference_epoch"]}
if any(ref.partition("#")[0] not in current for ref in refs):
raise ValueError("Cite a Read receipt delivered under the current references")


def _usage_record(source, *, fingerprint=True):
if source is None:
return {"usage": None, "tool_calls": None, "usage_source": None}, None
Expand Down Expand Up @@ -2577,6 +2593,8 @@ def _service_status_with_rounds(root, plan, state):
if "stage_id" in attempt else {}),
"attempt_id": attempt["attempt_id"],
"verdict": attempt["assessment"]["verdict"],
**({"knowledge_refs": attempt["knowledge_refs"]}
if "knowledge_refs" in attempt else {}),
"profiling": _service_profiling(root, attempt),
}
for number, attempt in latest_by_round.items()
Expand Down Expand Up @@ -2800,6 +2818,7 @@ def service_command(root, request, *, ranking_policy_for=None):
open_round = _service_open_round(state)
reusable = _service_reusable_round(state)
refresh_epoch = state["reference_epoch"]
knowledge_refs = None
if stages.due(state) and (kind == "round" or kind == "refresh" and not stage_action):
raise ValueError("Mandatory stage switch due before another candidate or refresh")
if kind == "baseline":
Expand Down Expand Up @@ -2838,6 +2857,9 @@ def service_command(root, request, *, ranking_policy_for=None):
raise ValueError("Insufficient search time for first stage round")
if number > plan["round_limit"] or not request.hypothesis.strip():
raise ValueError("Round budget exhausted or hypothesis missing")
knowledge_refs = getattr(request, "knowledge_ref", None)
if knowledge_refs is not None:
_validate_service_knowledge_refs(root, state, knowledge_refs)
if request.candidate.is_symlink():
raise ValueError("Candidate root cannot be symbolic")
source = request.candidate.resolve()
Expand Down Expand Up @@ -2986,6 +3008,7 @@ def service_command(root, request, *, ranking_policy_for=None):
"parent": parent,
"initial": None if plan.get("stage_parent_only") else initial,
"contexts": list(state["contexts"]),
**({"knowledge_refs": knowledge_refs} if knowledge_refs is not None else {}),
"admission_failure": admission,
}
pending.update(stages.binding(state, plan))
Expand Down
145 changes: 145 additions & 0 deletions tests/apps/test_service_round_citations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"""Service-reuse round citations."""


import copy
import json

from inferrsi.apps.cli import main
from inferrsi.harness.records import knowledge_capture, service_io
from tests.fixtures.service_reuse import begin, call, commit, diagnose, rejected, settings
from tests.fixtures.service_reuse import campaign as campaign
from tests.fixtures.service_reuse import no_fingerprints as no_fingerprints

QUESTION = "前缀缓存"


def deliver(campaign):
root = str(campaign["root"])
assert main(["find", QUESTION, "--session", root, "--limit", "1", "--json"]) == 0
found = json.loads(campaign["capsys"].readouterr().out)
hit, = found["items"]
assert main(hit["read_args"]) == 0
opened = json.loads(campaign["capsys"].readouterr().out)
reference = opened["reference"]["path"]
retained = service_io.read(campaign["root"] / reference)
item = next(context["ref"] for context in knowledge_capture.delivered_contexts(retained))
return found["reference"]["path"], reference, item


def round_args(campaign, *refs, **config):
commit(campaign["repo"], **config)
args = ["--candidate", str(campaign["repo"]), "--hypothesis", "Cited candidate"]
for ref in refs:
args += ["--knowledge-ref", ref]
return args


def attempts(campaign):
return [item for item in service_io.read(campaign["root"] / "state.json")["attempts"]
if item["kind"] == "round"]


def test_round_cites_a_read_receipt_and_status_reports_it(campaign):
begin(campaign)
_, receipt, _ = deliver(campaign)
result = call(campaign, "round", *round_args(campaign, receipt, a=90))
attempt = result["latest_observation"]
assert attempt["assessment"]["verdict"] == "PASS"
assert attempt["knowledge_refs"] == [receipt]
status = call(campaign, "status")
assert status["rounds"][0]["knowledge_refs"] == [receipt]
request = json.loads((campaign["root"] / attempt["path"] / "request.json").read_text())
assert not any("knowledge" in key for key in request)


def test_round_without_a_citation_keeps_its_record_unchanged(campaign):
begin(campaign)
call(campaign, "round", *round_args(campaign, a=90))
assert "knowledge_refs" not in attempts(campaign)[0]
assert "knowledge_refs" not in call(campaign, "status")["rounds"][0]


def test_round_rejects_other_citations_before_any_dispatch(campaign):
begin(campaign)
found, receipt, item = deliver(campaign)
root = campaign["root"]
base = ["session", "round", "--session", str(root), *round_args(campaign, a=90)]
cases = [
([found], "Cite a delivered context or CANNBot read receipt from this session"),
(["knowledge/read-" + "0" * 32 + ".json"], "Cite a delivered context or CANNBot read"),
([receipt + "#package:missing"], "Service-reuse rounds cite a Read receipt without"),
([receipt + "#" + item], "Service-reuse rounds cite a Read receipt without"),
([receipt, receipt], "Cite unique delivered knowledge references"),
]
before = (root / "state.json").read_bytes()
for refs, message in cases:
flags = [part for ref in refs for part in ("--knowledge-ref", ref)]
assert rejected([*base, *flags]) == 2
assert message in campaign["capsys"].readouterr().err
assert rejected([*base, "--alternative", "Another option"]) == 2
assert "Round decision declarations require" in campaign["capsys"].readouterr().err
assert (root / "state.json").read_bytes() == before
assert not (root / "rounds").exists()


def test_round_rejects_a_receipt_read_before_a_reference_refresh(campaign):
begin(campaign)
_, stale, _ = deliver(campaign)
conditions = copy.deepcopy(settings()["conditions"])
conditions.update(id="c1", runtime="changed-stdlib")
path = campaign["root"].parent / "conditions.json"
path.write_text(json.dumps(conditions))
call(campaign, "refresh-references", "--conditions", path, "--reason", "Changed runtime")
diagnose(campaign)
root = campaign["root"]
args = round_args(campaign, stale, a=90)
before = (root / "state.json").read_bytes()
assert rejected(["session", "round", "--session", str(root), *args]) == 2
assert "delivered under the current references" in campaign["capsys"].readouterr().err
assert (root / "state.json").read_bytes() == before
_, fresh, _ = deliver(campaign)
attempt = call(campaign, "round", *round_args(campaign, fresh, a=91))["latest_observation"]
assert attempt["knowledge_refs"] == [fresh]


def test_each_retry_keeps_its_own_citations(campaign):
begin(campaign)
_, first_receipt, _ = deliver(campaign)
_, retry_receipt, _ = deliver(campaign)
first = call(campaign, "round", *round_args(campaign, first_receipt, missing_metric=True),
expected=2)["latest_observation"]
assert first["assessment"]["verdict"] == "INCONCLUSIVE"
retry = call(
campaign, "round",
*round_args(campaign, retry_receipt, version="rejected", a=110),
"--retry-of", first["attempt_id"], "--repair-reason", "Investigated the fixture",
)["latest_observation"]
assert retry["attempt_id"] != first["attempt_id"]
assert [item["knowledge_refs"] for item in attempts(campaign)] == [
[first_receipt], [retry_receipt],
]
call(campaign, "recover")
assert [item["knowledge_refs"] for item in attempts(campaign)] == [
[first_receipt], [retry_receipt],
]
summary = service_io.read(campaign["root"] / "summary.json")
assert [item["knowledge_refs"] for item in summary["attempts"] if item["kind"] == "round"] == [
[first_receipt], [retry_receipt],
]


def test_cited_round_survives_export_and_dashboard(campaign, tmp_path):
from inferrsi.apps.delivery import export_bundle, read_bundle
from inferrsi.apps.views.dashboard import dashboard_snapshot

begin(campaign)
_, receipt, _ = deliver(campaign)
attempt = call(campaign, "round", *round_args(campaign, receipt, a=90))["latest_observation"]
call(campaign, "final", "--reason", "Cited round accepted")
root = campaign["root"]
assert dashboard_snapshot(root)["data"]
export_bundle(root, tmp_path / "bundle", export_id="cited-round")
assert read_bundle(tmp_path / "bundle")
summary = service_io.read(root / "summary.json")
cited, = [item for item in summary["attempts"] if item["attempt_id"] == attempt["attempt_id"]]
assert cited["knowledge_refs"] == [receipt]
Loading