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
10 changes: 9 additions & 1 deletion docs/dashboard.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,15 @@ retrievals require separate evidence. Review query text and paths before sharing
dashboard derives a percentage only for a `complete` part, never shows 0%
for a zero denominator, and shows "Not recorded" for earlier records without
this block. These figures are associations; they do not establish causal or
performance credit, and they include no token or cost data.
performance credit.
- In **Knowledge trace**, **Managed search attempt tokens** shows the input,
cached input, uncached input, output and total from each retained caller usage
export. The round filter includes each settled attempt, including separate
service retries under the same round number. Follow the receipt path in the
session directory to inspect the recorded source. Verified counts stay visible
when a receipt has missing fields. Missing or unverifiable values show
**Unknown**, and a recorded zero shows **0**. Total requires both input and
output. Uncached input requires input and a valid cached subset.
- Supply `--complete` only when the selected inputs cover every in-scope
retrieval for the round. Otherwise only observed counts are known and
`counts` is null. A complete round without a search has zero searches.
Expand Down
28 changes: 26 additions & 2 deletions docs/examples/dashboard-profile-review.html
Original file line number Diff line number Diff line change
Expand Up @@ -805,17 +805,41 @@ <h2 class="panel-heading" aria-labelledby="chart-title"></h2>
links(b,s.links,s.path);
});
}
function roundUsage(box,attempts){
if(!attempts.length)return;
const format=new Intl.NumberFormat(getLanguage());
const token=value=>value==null?tr('Unknown','未知'):format.format(value);
const headers=[
tr('Round','轮次'),tr('Attempt','尝试'),tr('Input','输入'),tr('Cached input','缓存输入'),
tr('Uncached input','未缓存输入'),tr('Output','输出'),tr('Total','总计'),tr('Receipt','凭据'),
];
const rows=attempts.map(({round,attempt_id,tokens,source})=>[
'R'+round,attempt_id,token(tokens?.input_tokens),token(tokens?.cached_input_tokens),
token(tokens?.uncached_input_tokens),token(tokens?.output_tokens),
token(tokens?.total_tokens),source,
]);
fold(box,tr('Managed search attempt tokens','受管搜索尝试 token 用量'),'round-usage',b=>{
p(b,tr('Caller-exported tokens cover each attempt. Total counts input and output. Cached input is included in input.',
'调用方按尝试提供 token 用量。总计为输入与输出之和,缓存输入已计入输入。'),'kt-note');
table(b,headers,rows);
});
}
function render(){
const root=document.getElementById('knowledge-navigation');if(!root)return;
root.replaceChildren();root.classList.add('kt-view');root.setAttribute('data-no-translate','');
const view=getData(),data=view.knowledge_trace||{}, captures=data.retrievals||[],searches=data.searches||[];
const service=view.evaluation_mode==='service_reuse', deliveries=service?view.managed_retrievals||[]:[];
const usage=view.round_token_usage||[];
const title=tr('Knowledge trace','知识检索 Trace');
if(navLink){navLink.textContent=title;navLink.hidden=!service&&!captures.length&&!searches.length;}
if(navLink){navLink.textContent=title;navLink.hidden=!service&&!captures.length&&!searches.length&&!usage.length;}
fold(root,title,'navigation',box=>{
const rounds=[...new Set([...searches.map(s=>s.round),...captures.flatMap(c=>(c.links||[]).map(l=>l.round)),...deliveries.map(d=>d.round)].filter(Number.isInteger))].sort((a,b)=>a-b);
const rounds=[...new Set([
...searches.map(s=>s.round),...captures.flatMap(c=>(c.links||[]).map(l=>l.round)),
...deliveries.map(d=>d.round),...usage.map(a=>a.round),
].filter(Number.isInteger))].sort((a,b)=>a-b);
if(round && !rounds.includes(Number(round)))round='';
const control=el('select');control.setAttribute('aria-label',tr('Knowledge round','知识轮次'));control.append(new Option(tr('All rounds','全部轮次'),''));rounds.forEach(n=>control.append(new Option('R'+n,String(n))));control.value=round;control.onchange=()=>{round=control.value;selected=null;render();};box.append(control);
roundUsage(box,usage.filter(a=>!round||a.round===Number(round)));
if(service){
const visible=deliveries.filter(d=>!round||d.round===Number(round));
if(!visible.length)p(box,tr('No retrieval capture recorded.','未记录检索快照。'));
Expand Down
11 changes: 11 additions & 0 deletions src/inferrsi/apps/views/dashboard_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from inferrsi.harness.records.optimization_trace import read_optimization_trace

from .dashboard_workflow import command_state, run_workflow, validation_progress
from .round_usage import round_token_usage

PHASE_STAGES = {
"source_snapshot": "execution",
Expand Down Expand Up @@ -810,6 +811,11 @@ def _managed_dashboard(root: Path, campaign: dict) -> dict:
"campaign_id": sanitized_text(campaign["campaign_id"]), "synthetic": False,
"rounds": rounds, "rounds_state": "present", "corrupt_round_lines": [],
"candidates": rows, "optimization_session": displayed_summary,
"round_token_usage": [
round_token_usage(root, record, round_number=number,
attempt_id=Path(record["path"]).name)
for number, record in enumerate(state["rounds"], 1)
],
"managed_retrievals": retrievals, "pending_candidate": pending_candidate,
"managed_diagnoses": _managed_diagnoses(state, submissions),
"integration": {"state": "connected" if rows else "not_connected",
Expand Down Expand Up @@ -862,6 +868,11 @@ def load_dashboard(source: Path) -> dict:
"campaign_id": sanitized_text(header["campaign_id"]),
"evaluation_mode": "service_reuse",
"service_optimization": public_value(summary),
"round_token_usage": [
round_token_usage(root, attempt, round_number=attempt["round_number"],
attempt_id=attempt["attempt_id"], require_sha256=False)
for attempt in state["attempts"] if attempt["kind"] == "round"
],
**service_inputs(plan, state, captures),
}
single = (root / "run.lock.json").is_file()
Expand Down
28 changes: 26 additions & 2 deletions src/inferrsi/apps/views/knowledge_view.html
Original file line number Diff line number Diff line change
Expand Up @@ -168,17 +168,41 @@
links(b,s.links,s.path);
});
}
function roundUsage(box,attempts){
if(!attempts.length)return;
const format=new Intl.NumberFormat(getLanguage());
const token=value=>value==null?tr('Unknown','未知'):format.format(value);
const headers=[
tr('Round','轮次'),tr('Attempt','尝试'),tr('Input','输入'),tr('Cached input','缓存输入'),
tr('Uncached input','未缓存输入'),tr('Output','输出'),tr('Total','总计'),tr('Receipt','凭据'),
];
const rows=attempts.map(({round,attempt_id,tokens,source})=>[
'R'+round,attempt_id,token(tokens?.input_tokens),token(tokens?.cached_input_tokens),
token(tokens?.uncached_input_tokens),token(tokens?.output_tokens),
token(tokens?.total_tokens),source,
]);
fold(box,tr('Managed search attempt tokens','受管搜索尝试 token 用量'),'round-usage',b=>{
p(b,tr('Caller-exported tokens cover each attempt. Total counts input and output. Cached input is included in input.',
'调用方按尝试提供 token 用量。总计为输入与输出之和,缓存输入已计入输入。'),'kt-note');
table(b,headers,rows);
});
}
function render(){
const root=document.getElementById('knowledge-navigation');if(!root)return;
root.replaceChildren();root.classList.add('kt-view');root.setAttribute('data-no-translate','');
const view=getData(),data=view.knowledge_trace||{}, captures=data.retrievals||[],searches=data.searches||[];
const service=view.evaluation_mode==='service_reuse', deliveries=service?view.managed_retrievals||[]:[];
const usage=view.round_token_usage||[];
const title=tr('Knowledge trace','知识检索 Trace');
if(navLink){navLink.textContent=title;navLink.hidden=!service&&!captures.length&&!searches.length;}
if(navLink){navLink.textContent=title;navLink.hidden=!service&&!captures.length&&!searches.length&&!usage.length;}
fold(root,title,'navigation',box=>{
const rounds=[...new Set([...searches.map(s=>s.round),...captures.flatMap(c=>(c.links||[]).map(l=>l.round)),...deliveries.map(d=>d.round)].filter(Number.isInteger))].sort((a,b)=>a-b);
const rounds=[...new Set([
...searches.map(s=>s.round),...captures.flatMap(c=>(c.links||[]).map(l=>l.round)),
...deliveries.map(d=>d.round),...usage.map(a=>a.round),
].filter(Number.isInteger))].sort((a,b)=>a-b);
if(round && !rounds.includes(Number(round)))round='';
const control=el('select');control.setAttribute('aria-label',tr('Knowledge round','知识轮次'));control.append(new Option(tr('All rounds','全部轮次'),''));rounds.forEach(n=>control.append(new Option('R'+n,String(n))));control.value=round;control.onchange=()=>{round=control.value;selected=null;render();};box.append(control);
roundUsage(box,usage.filter(a=>!round||a.round===Number(round)));
if(service){
const visible=deliveries.filter(d=>!round||d.round===Number(round));
if(!visible.length)p(box,tr('No retrieval capture recorded.','未记录检索快照。'));
Expand Down
62 changes: 62 additions & 0 deletions src/inferrsi/apps/views/round_usage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Project caller-exported tokens from retained managed search attempts."""

import json
from hashlib import sha256
from pathlib import Path

from inferrsi.harness.records.evidence import bounded_record_bytes
from inferrsi.harness.records.service_io import JSON_SIZE_LIMIT
from inferrsi.harness.records.usage import normalize_usage


def round_token_usage(
root: Path, attempt: dict, *, round_number: int, attempt_id: str, require_sha256: bool = True,
) -> dict:
"""Keep usage on its recorded attempt, including failed attempts and retries."""
result = {"round": round_number, "attempt_id": attempt_id, "tokens": None, "source": None}
observations = attempt.get("observations") or {}
source = observations.get("usage_source") or {}
if source.get("kind") != "caller_export":
return result

relative = f"{attempt['path']}/agent-usage.json"
raw, _ = bounded_record_bytes(root, relative, JSON_SIZE_LIMIT)
if raw is None:
return result
# Ordinary records pin the bytes. Service reuse records the values without a hash.
if require_sha256 and sha256(raw).hexdigest() != source.get("sha256"):
return result
try:
usage = normalize_usage(json.loads(raw))
except (ValueError, RecursionError):
return result
if not usage or usage != normalize_usage(observations.get("usage")):
return result

input_tokens = usage.get("input_tokens")
output_tokens = usage.get("output_tokens")
cached_input_tokens = usage.get("cached_input_tokens")
uncached_input_tokens = None
if input_tokens is not None and cached_input_tokens is not None:
if cached_input_tokens <= input_tokens:
uncached_input_tokens = input_tokens - cached_input_tokens
else:
cached_input_tokens = None
if input_tokens is None and output_tokens is None and cached_input_tokens is None:
return result

total_tokens = (
input_tokens + output_tokens if input_tokens is not None and output_tokens is not None
else None
)
return {
**result,
"source": relative,
"tokens": {
"input_tokens": input_tokens,
"cached_input_tokens": cached_input_tokens,
"uncached_input_tokens": uncached_input_tokens,
"output_tokens": output_tokens,
"total_tokens": total_tokens,
},
}
44 changes: 44 additions & 0 deletions tests/apps/dashboard/test_dashboard_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from inferrsi.apps.views.dashboard_data import load_dashboard
from inferrsi.apps.views.dashboard_service import service_dashboard_view, service_inputs
from inferrsi.apps.views.dashboard_timeline import temporal_chart
from inferrsi.apps.views.round_usage import round_token_usage
from inferrsi.harness.records import evidence


Expand All @@ -27,6 +28,49 @@ def test_null_evaluation_labels_fall_back_to_frozen_metric_for_display(tmp_path)
assert (candidate["metric_key"], candidate["metric_unit"]) == ("latency", "ms")


@pytest.mark.parametrize("require_sha256", [True, False], ids=["ordinary", "service-reuse"])
@pytest.mark.parametrize(
("usage", "known_tokens"),
[
pytest.param({"input_tokens": 0}, {"input_tokens": 0}, id="input-only"),
pytest.param({"output_tokens": 3}, {"output_tokens": 3}, id="output-only"),
pytest.param(
{"input_tokens": 8, "cached_input_tokens": 0},
{"input_tokens": 8, "cached_input_tokens": 0, "uncached_input_tokens": 8},
id="uncached-input-without-output",
),
pytest.param(
{"output_tokens": 0, "cached_input_tokens": 2},
{"output_tokens": 0, "cached_input_tokens": 2},
id="cached-input-without-input-total",
),
],
)
def test_attempt_token_usage_keeps_verified_partial_receipts(
tmp_path, require_sha256, usage, known_tokens,
):
directory = "rounds/attempt-1"
relative = f"{directory}/agent-usage.json"
receipt = tmp_path / relative
write_json(receipt, usage)
source = {"kind": "caller_export"}
if require_sha256:
source["sha256"] = hashlib.sha256(receipt.read_bytes()).hexdigest()
attempt = {"path": directory, "observations": {"usage_source": source, "usage": usage}}

row = round_token_usage(
tmp_path, attempt, round_number=1, attempt_id="attempt-1", require_sha256=require_sha256,
)

assert row == {
"round": 1, "attempt_id": "attempt-1", "source": relative,
"tokens": {
"input_tokens": None, "cached_input_tokens": None, "uncached_input_tokens": None,
"output_tokens": None, "total_tokens": None, **known_tokens,
},
}


def test_service_dashboard_keeps_reference_epochs_separate_and_missing_values_unknown():
attempts = []
for number, epoch, value in [(1, 0, 12), (2, 0, 0), (3, 1, 9)]:
Expand Down
30 changes: 30 additions & 0 deletions tests/apps/test_knowledge_navigation_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,36 @@
playwright = pytest.importorskip("playwright.sync_api")


def test_round_filter_shows_attempt_tokens_and_unknown_values(browser, tmp_path):
make_campaign(tmp_path)
snapshot = dashboard_snapshot(tmp_path)
snapshot["data"]["round_token_usage"] = [
{"round": 1, "attempt_id": "attempt-1", "source": "rounds/r1/agent-usage.json",
"tokens": {"input_tokens": 0, "cached_input_tokens": 0, "uncached_input_tokens": 0,
"output_tokens": 0, "total_tokens": 0}},
{"round": 2, "attempt_id": "attempt-2", "source": None, "tokens": None},
]
html = tmp_path / "dashboard.html"
html.write_text(render_dashboard(snapshot), encoding="utf-8")
page = browser.new_page()
try:
page.goto(html.as_uri())
page.get_by_role("link", name="Knowledge trace", exact=True).click()
usage = page.locator('[data-kt-key="round-usage"]')
usage.locator("summary").click()
rows = usage.get_by_role("row")
playwright.expect(rows).to_have_count(3)
playwright.expect(rows.nth(1).get_by_role("cell", name="0", exact=True)).to_have_count(5)
playwright.expect(rows.nth(1)).to_contain_text("rounds/r1/agent-usage.json")
page.get_by_role("combobox", name="Knowledge round").select_option("2")
playwright.expect(rows).to_have_count(2)
playwright.expect(rows.nth(1)).to_contain_text("attempt-2")
unknown = rows.nth(1).get_by_role("cell", name="Unknown", exact=True)
playwright.expect(unknown).to_have_count(5)
finally:
page.close()


@pytest.mark.parametrize("profile_first", [False, True])
@pytest.mark.parametrize("live", [False, True])
def test_redacted_context_tail_and_original_hash_note(browser, tmp_path, profile_first, live):
Expand Down
50 changes: 50 additions & 0 deletions tests/apps/test_optimization_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,56 @@ def test_missing_usage_remains_unknown_and_baseline_noise_is_not_a_gain(session,
assert report["optimization_speedup"] == 1


def test_dashboard_binds_ordinary_round_usage_to_its_export(session, capsys):
from inferrsi.apps.views.dashboard import dashboard_snapshot

recorded = submit(session, 2, capsys, {
"input_tokens": 24, "cached_input_tokens": 12, "output_tokens": 3,
})["latest_observation"]
submit(session, 3, capsys)
submit(session, 4, capsys, {"input_tokens": 0, "output_tokens": 0})
state = (session / "state.json").read_bytes()
first, missing, zero = dashboard_snapshot(session)["data"]["round_token_usage"]
assert first == {
"round": 1, "attempt_id": Path(recorded["path"]).name,
"source": recorded["path"] + "/agent-usage.json",
"tokens": {"input_tokens": 24, "cached_input_tokens": 12, "uncached_input_tokens": 12,
"output_tokens": 3, "total_tokens": 27},
}
assert missing["round"] == 2 and missing["tokens"] is None and missing["source"] is None
assert zero["round"] == 3 and zero["tokens"] == {
"input_tokens": 0, "cached_input_tokens": None, "uncached_input_tokens": None,
"output_tokens": 0, "total_tokens": 0,
}
assert (session / "state.json").read_bytes() == state


@pytest.mark.parametrize("damage", ["changed_bytes", "missing_hash"])
def test_dashboard_drops_unverifiable_ordinary_usage(
session, capsys, monkeypatch, damage,
):
from inferrsi.apps.views.dashboard import dashboard_snapshot

attempt = submit(session, 2, capsys, {"input_tokens": 8, "output_tokens": 3})[
"latest_observation"
]
receipt = session / attempt["path"] / "agent-usage.json"
read = manager.read_session_records

def load_then_damage_receipt(root):
plan, state, summary = read(root)
if damage == "changed_bytes":
receipt.write_bytes(receipt.read_bytes() + b"\n")
else:
del state["rounds"][0]["observations"]["usage_source"]["sha256"]
return plan, state, summary

monkeypatch.setattr(manager, "read_session_records", load_then_damage_receipt)
usage, = dashboard_snapshot(session)["data"]["round_token_usage"]
assert usage == {"round": 1, "attempt_id": Path(attempt["path"]).name,
"source": None, "tokens": None}


def test_round_budget_is_enforced(session, capsys):
for factor in (2, 3, 4):
submit(session, factor, capsys)
Expand Down
Loading
Loading