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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Added

- **`skill novelty analyze --estimate-only` names each role's dollars and the role its figure is least sure of** — the payload gains `usd_by_role` (extractor, answerer and judge dollars, summing to `expected_usd`; panel judges count under `judge`) and `least_sure_role` (the role and a reason), both `null` when `expected_usd` is; stderr prints one line with that role and its share. `study` and an untiered run name the extractor, which borrows the standard profile; `triage` and `standard` name the role with the largest dollars. `expected_usd` and the notes are unchanged.
3 changes: 2 additions & 1 deletion dokimi/docs/skill-novelty-walkthrough.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ bill is `probes × arms × (answer + grade)` plus the retention oracle, which es
ambiguous band. The output carries `expected_calls`, the point figure, with `by_role` splitting
it into extractor, answerer and judge calls; `total_calls` and
`total_calls_if_every_pair_escalates` are the two ends. `expected_usd` prices `by_role` at list
prices, and is `null` when a model has no price. The probe term was validated to within 1–3% of
prices, and is `null` when a model has no price; `usd_by_role` gives each role's share of it and
`least_sure_role` names the role the figure is least sure of. The probe term was validated to within 1–3% of
counted calls at nine (skill, tier) points, on content that did not escalate.

`expected_usd` is a projection, not a ceiling (held-out runs ran up to 33% low): a call's price
Expand Down
7 changes: 6 additions & 1 deletion dokimi/docs/skill-novelty.md
Original file line number Diff line number Diff line change
Expand Up @@ -1463,7 +1463,12 @@ call `analyze` prints the run's expected cost at list prices to stderr.
The estimate payload has `expected_calls`, the point figure between
the two totals (stages, every probe, and half the oracle pairs, split by `by_role`), and
`expected_usd`: those calls priced at list prices by role, `null` when a model has no
price. The constants were fitted on 13 of the 25 measured runs; the other 12 are held out.
price. `usd_by_role` splits `expected_usd` into `extractor`, `answerer` and `judge` (panel judges
after the first count under `judge`), and `least_sure_role` names the role the figure is least
sure of with a reason; both are `null` with `expected_usd`, and `--estimate-only` prints the role and its
share on stderr. The rule, chosen without per-role error data: a run whose tier has no extractor
profile of its own (`study`, or no tier) names `extractor`, which borrows the standard profile;
`triage` and `standard` name the role with the largest dollars. The constants were fitted on 13 of the 25 measured runs; the other 12 are held out.
On those 12 every projection landed within 35%: calls within 13%, atoms within 11%, dollars
within 33%. The dollar projections ran high on 5 runs (up to +29%) and low on 7 (down to
-33%), so `expected_usd` is not a ceiling; the triage projection ran lower the larger the
Expand Down
9 changes: 7 additions & 2 deletions dokimi/dokimi/commands/novelty_budget.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,11 @@
estimate = settings.estimate(
len(spans), n_tokens=n_tokens, budgets=tuple(args.budgets), n_arms=n_arms
)
context_share = (n_arms - 1 - ("no_artifact_repeat" in args.arms)) / n_arms

Check warning on line 223 in dokimi/dokimi/commands/novelty_budget.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: swap-addsub `n_arms - 1 - ("no_artifact_repeat" in args.arms)` -> `n_arms - 1 + ('no_artifact_repeat' in args.arms)`
estimate["expected_usd"] = estimate_usd(
args, n_tokens, estimate["estimate"]["by_role"], settings.tier,
context_share=(n_arms - 1 - ("no_artifact_repeat" in args.arms)) / n_arms,
args, n_tokens, estimate["estimate"]["by_role"], settings.tier, context_share=context_share,
)
cost.add_role_usd(args, estimate, n_tokens, settings.tier, context_share)
cost.add_panel_calls(args, estimate["estimate"]) # after the price, which counts each judge itself
return estimate, n_tokens

Expand All @@ -246,6 +247,7 @@

def print_estimate_only(args: argparse.Namespace, settings, text: str, estimate_usd) -> None:
"""The ``--estimate-only`` output of ``analyze``: the projection as JSON, and what it rests on."""
from dokimi.novelty import cost
from dokimi.novelty.tiers import FITTED_TOKENS_MAX

estimate, n_tokens = run_estimate(args, settings, text, estimate_usd)
Expand All @@ -257,6 +259,9 @@
f"profiles were fitted on artifacts up to {FITTED_TOKENS_MAX}; the projection "
"ran low as the artifact grew", file=sys.stderr)
print(json.dumps(estimate, indent=2))
least_sure = cost.least_sure_line(estimate)
if least_sure:
print(least_sure, file=sys.stderr)
print("Estimate only, nothing was measured. ~4 calls per paired probe is the "
"measured shape; batch sizes and retries move the real figure.",
file=sys.stderr)
Expand Down
61 changes: 61 additions & 0 deletions dokimi/dokimi/novelty/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,67 @@
return usd


ROLES = ("extractor", "answerer", "judge")


def role_usd(args: argparse.Namespace, n_tokens: int, by_role: dict[str, int], tier: str | None,
context_share: float = 0.5) -> dict[str, float] | None:
"""Each role's list-price dollars, panel judges after the first counted under ``judge``.

``None`` when a role has no price. Called once :func:`estimate_usd` has priced every role and
panel judge, so the models resolve and the values sum to its ``expected_usd`` to rounding.
"""
from dokimi.novelty.tiers import usd_by_role

split = usd_by_role(by_role, n_tokens, role_models(args), tier, context_share)
if split is None:
return None
for model, provider in judge_refs(args)[1:]:
extra = usd_by_role({"judge": by_role.get("judge", 0)}, n_tokens,

Check warning on line 133 in dokimi/dokimi/novelty/cost.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `0` -> `1`
{"judge": (model, provider)}, tier, context_share) or {}
split["judge"] = split.get("judge", 0.0) + extra.get("judge", 0.0)
return {role: round(split.get(role, 0.0), 6) for role in ROLES}

Check warning on line 136 in dokimi/dokimi/novelty/cost.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `6` -> `7`


def least_sure_role(usd_by_role: dict[str, float], tier: str | None) -> dict[str, str]:
"""The role the dollar figure is least sure of, and why (#631).

A tier with no extractor profile of its own (``study``, an untiered run) borrows the
standard one, so the extractor is the least sure. Otherwise it is the role with the largest
dollars, where an error in the token profile moves the figure most; a tie goes to the first
of extractor, answerer, judge. There is no per-role error data behind this rule.
"""
from dokimi.novelty.tiers import EXTRACTOR_TOKENS

if tier not in EXTRACTOR_TOKENS:
return {"role": "extractor",
"reason": "the extractor's token profile is the standard tier's, borrowed, "
"since no run of this tier was measured"}
role = max(ROLES, key=lambda name: usd_by_role[name])
return {"role": role,
"reason": f"an error in the {role}'s token profile moves the dollar figure most"}


def add_role_usd(args: argparse.Namespace, estimate: dict, n_tokens: int, tier: str | None,
context_share: float) -> None:
"""Put ``usd_by_role`` and ``least_sure_role`` in a run estimate, both ``None`` without a figure."""
split = None
if estimate["expected_usd"] is not None:
split = role_usd(args, n_tokens, estimate["estimate"]["by_role"], tier, context_share)
estimate["usd_by_role"] = split
estimate["least_sure_role"] = None if split is None else least_sure_role(split, tier)


def least_sure_line(estimate: dict) -> str | None:
"""The stderr line naming the least sure role, its share of ``expected_usd`` and why."""
least = estimate.get("least_sure_role")
if not least:
return None
split = estimate["usd_by_role"]
share = 100 * split[least["role"]] / (sum(split.values()) or 1)

Check warning on line 174 in dokimi/dokimi/novelty/cost.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `1` -> `2`

Check warning on line 174 in dokimi/dokimi/novelty/cost.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `100` -> `101`
return f"Least sure of: {least['role']} ({share:.0f}% of expected_usd): {least['reason']}"


def add_panel_calls(args: argparse.Namespace, estimate: dict) -> None:
"""Count the panel's grading calls in a run estimate: each judge after the first grades every answer again."""

Expand Down
38 changes: 27 additions & 11 deletions dokimi/dokimi/novelty/tiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,31 @@
return max(0, round(base + per_token * n_tokens)), out


def usd_by_role(
by_role: dict[str, int],
n_tokens: int,
models: dict[str, tuple[str, str]],
tier: str | None = None,
context_share: float = MEASURED_CONTEXT_SHARE,
) -> dict[str, float] | None:
"""The list-price dollars of each role's calls, unrounded; ``None`` when a role has no price.

The one pricing loop: :func:`estimate_usd` sums it and the estimate payload's
``usd_by_role`` reports it. Arguments as in :func:`estimate_usd`.
"""
from dokimi.llm_pricing import list_cost_usd

out: dict[str, float] = {}
for role, calls in by_role.items():
model, provider = models[role]
tokens_in, tokens_out = call_tokens(role, n_tokens, tier, context_share)
cost = list_cost_usd(model, provider, tokens_in, tokens_out)
if cost is None:
return None
out[role] = calls * cost
return out


def estimate_usd(
by_role: dict[str, int],
n_tokens: int,
Expand All @@ -366,17 +391,8 @@
tier: The run's tier; it sets the extractor's output (see :func:`call_tokens`).
context_share: Arms that carry the artifact over arms run (see :func:`call_tokens`).
"""
from dokimi.llm_pricing import list_cost_usd

total = 0.0
for role, calls in by_role.items():
model, provider = models[role]
tokens_in, tokens_out = call_tokens(role, n_tokens, tier, context_share)
cost = list_cost_usd(model, provider, tokens_in, tokens_out)
if cost is None:
return None
total += calls * cost
return round(total, 6)
split = usd_by_role(by_role, n_tokens, models, tier, context_share)
return None if split is None else round(sum(split.values()), 6)

Check warning on line 395 in dokimi/dokimi/novelty/tiers.py

View workflow job for this annotation

GitHub Actions / Mutation of changed lines

mutant survived: bump-int `6` -> `7`


def estimate_calls(n_atoms: int, settings: dict, *, n_arms: int = 2,
Expand Down
102 changes: 102 additions & 0 deletions dokimi/tests/test_novelty_estimate_roles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Copyright (C) 2026 Intel Corporation
# SPDX-License-Identifier: Apache-2.0

"""``skill novelty analyze --estimate-only`` splits its dollars by role and names the least sure one (#631)."""

from __future__ import annotations

import json

import pytest

from dokimi.cli import build_parser
from dokimi.llm_pricing import list_cost_usd
from dokimi.novelty.cost import role_models, role_usd
from dokimi.novelty.tiers import call_tokens

ROLES = ("extractor", "answerer", "judge")
BORROWED = "the extractor's token profile is the standard tier's, borrowed, since no run of this tier was measured"


def _estimate(tmp_path, capsys, *flags):
body = "\n\n".join(f"Section {i}. Do not enable the legacy driver number {i} on a "
"production host without a rollback plan." for i in range(60))
(tmp_path / "SKILL.md").write_text(f"---\nname: s\ndescription: d\n---\n\n# S\n\n{body}\n",
encoding="utf-8")
args = build_parser().parse_args(["skill", "novelty", "analyze", "--artifact",
f"skill:{tmp_path}", "--dry-run", *flags])
args.func(args)
out = capsys.readouterr()
return args, json.loads(out.out), out.err


TIERS = [("--tier", "triage"), ("--tier", "standard"), ("--tier", "study"), ()]


@pytest.mark.parametrize("tier_flags", TIERS)
def test_usd_by_role_prices_each_roles_calls_and_sums_to_expected_usd(tmp_path, capsys, tier_flags):
args, payload, _ = _estimate(tmp_path, capsys, *tier_flags)
tier = tier_flags[1] if tier_flags else None
split = payload["usd_by_role"]
assert list(split) == list(ROLES)
assert sum(split.values()) == pytest.approx(payload["expected_usd"], abs=1e-5)
models = role_models(args)
for role in ROLES:
model, provider = models[role]
cost = list_cost_usd(model, provider, *call_tokens(role, payload["tokens"], tier))
assert split[role] == pytest.approx(payload["estimate"]["by_role"][role] * cost, abs=1e-6)


@pytest.mark.parametrize("tier_flags", [("--tier", "study"), ()])
def test_a_tier_without_an_extractor_profile_names_the_extractor_as_borrowed(
tmp_path, capsys, tier_flags):
_, payload, _ = _estimate(tmp_path, capsys, *tier_flags)
assert payload["least_sure_role"] == {"role": "extractor", "reason": BORROWED}


def test_triage_and_standard_name_the_role_with_the_largest_dollars(tmp_path, capsys):
named = {}
for tier in ("triage", "standard"):
_, payload, _ = _estimate(tmp_path, capsys, "--tier", tier)
split, least = payload["usd_by_role"], payload["least_sure_role"]
assert split[least["role"]] == max(split.values())
assert least["reason"] == (f"an error in the {least['role']}'s token profile "
"moves the dollar figure most")
named[tier] = least["role"]
# one of the two is not the extractor, so rule 2 is told apart from rule 1
assert set(named.values()) != {"extractor"}


def test_panel_judges_after_the_first_count_under_judge(tmp_path, capsys):
judges = ["openai/gpt-5.6-luna", "anthropic/claude-sonnet-5", "openai/gpt-6-luna"]
flags = [f for judge in judges for f in ("--judge", judge)]
_, one, _ = _estimate(tmp_path, capsys, "--tier", "standard", "--judge", judges[0])
_, three, _ = _estimate(tmp_path, capsys, "--tier", "standard", *flags)
assert three["usd_by_role"]["extractor"] == one["usd_by_role"]["extractor"]
assert three["usd_by_role"]["answerer"] == one["usd_by_role"]["answerer"]
assert three["usd_by_role"]["judge"] > one["usd_by_role"]["judge"]
assert sum(three["usd_by_role"].values()) == pytest.approx(three["expected_usd"], abs=1e-5)


def test_an_unpriced_model_gives_null_role_dollars_and_no_least_sure_role(tmp_path, capsys):
_, payload, err = _estimate(tmp_path, capsys, "--tier", "standard", "--model", "foo-bar-9",
"--provider", "openai")
assert payload["expected_usd"] is None
assert payload["usd_by_role"] is None
assert payload["least_sure_role"] is None
assert "Least sure of" not in err


def test_role_usd_is_none_for_an_unpriced_role(tmp_path, capsys):
args, payload, _ = _estimate(tmp_path, capsys, "--tier", "standard", "--model", "foo-bar-9",
"--provider", "openai")
assert role_usd(args, payload["tokens"], payload["estimate"]["by_role"], "standard") is None


def test_stderr_names_the_role_its_percent_and_the_reason_before_the_estimate_note(
tmp_path, capsys):
_, payload, err = _estimate(tmp_path, capsys, "--tier", "study")
percent = 100 * payload["usd_by_role"]["extractor"] / sum(payload["usd_by_role"].values())
line = f"Least sure of: extractor ({percent:.0f}% of expected_usd): {BORROWED}\n"
assert line in err
assert err.index(line) < err.index("Estimate only, nothing was measured.")
11 changes: 9 additions & 2 deletions dokimi/tests/test_novelty_settings_parity.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,10 @@ def scripted(model, provider, role, args):
# The stderr note the estimate prints: the one whose wording changed is cut from both sides.
_ESTIMATE_NOTES = ("The estimate counts calls", "expected_usd prices")
# The bill the estimate now projects, and the atom count and totals that move with it.
_BILL_KEYS = ("tokens", "expected_usd")
# usd_by_role and least_sure_role are new next to expected_usd (#631).
_BILL_KEYS = ("tokens", "expected_usd", "usd_by_role", "least_sure_role")
# The line `--estimate-only` now prints for least_sure_role (#631), before the notes above.
_LEAST_SURE_LINE = "Least sure of: "
_ESTIMATE_BILL_KEYS = (
"by_role",
"expected_calls",
Expand All @@ -235,12 +238,16 @@ def _kept_estimate(step: dict) -> dict:
if not step["stdout"]:
return step
payload = json.loads(step["stdout"])
has_role = payload.get("least_sure_role") is not None
for key in _BILL_KEYS:
payload.pop(key, None)
payload["estimate"] = {
key: value for key, value in payload["estimate"].items() if key not in _ESTIMATE_BILL_KEYS
}
stderr = step["stderr"]
lines = step["stderr"].splitlines(keepends=True)
named = [line for line in lines if line.startswith(_LEAST_SURE_LINE)]
assert bool(named) == has_role
stderr = "".join(line for line in lines if line not in named)
for note in _ESTIMATE_NOTES:
stderr = stderr.split(note)[0]
return {**step, "stdout": payload, "stderr": stderr}
Expand Down
Loading