From ef0ddd350f9f31e07cdf7ea26ec4563fb8345634 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Wed, 25 Nov 2026 16:53:35 +0000 Subject: [PATCH 1/2] fix(novelty): estimate-only splits dollars by role, names the least sure (#631) `novelty analyze --estimate-only` printed one `expected_usd` with no hint of which role's token profile it leans on, and a run billed above it (the issue's 777 calls at $6.00 against `expected_usd: 5.93`) gave no pointer to the extractor. The payload now carries `usd_by_role` (extractor, answerer and judge list-price dollars, panel judges after the first under `judge`) and `least_sure_role` (a role and a reason), both null when `expected_usd` is null. A tier with no extractor profile of its own (`study`, or no tier) names the extractor, which borrows the standard profile; `triage` and `standard` name the role with the largest dollars. There is no per-role error data behind that rule. stderr prints one line with the role and its share before the existing estimate notes. `tiers.estimate_usd` and the split share one pricing loop (`tiers.usd_by_role`); `expected_usd` and every existing note are unchanged. Refitting the token profile per tier needs measured paid runs and is left to a follow-up. Signed-off-by: Anton Volkov --- ...261125_150000_novelty-estimate-role-usd.md | 3 + dokimi/docs/skill-novelty-walkthrough.md | 3 +- dokimi/docs/skill-novelty.md | 7 +- dokimi/dokimi/commands/novelty_budget.py | 9 +- dokimi/dokimi/novelty/cost.py | 67 +++++++++++++ dokimi/dokimi/novelty/tiers.py | 38 +++++--- dokimi/tests/test_novelty_estimate_roles.py | 96 +++++++++++++++++++ dokimi/tests/test_novelty_settings_parity.py | 11 ++- 8 files changed, 217 insertions(+), 17 deletions(-) create mode 100644 dokimi/changelog.d/20261125_150000_novelty-estimate-role-usd.md create mode 100644 dokimi/tests/test_novelty_estimate_roles.py diff --git a/dokimi/changelog.d/20261125_150000_novelty-estimate-role-usd.md b/dokimi/changelog.d/20261125_150000_novelty-estimate-role-usd.md new file mode 100644 index 000000000..30bb3e5b0 --- /dev/null +++ b/dokimi/changelog.d/20261125_150000_novelty-estimate-role-usd.md @@ -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. diff --git a/dokimi/docs/skill-novelty-walkthrough.md b/dokimi/docs/skill-novelty-walkthrough.md index a20cfd3ab..d5ea88da0 100644 --- a/dokimi/docs/skill-novelty-walkthrough.md +++ b/dokimi/docs/skill-novelty-walkthrough.md @@ -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 diff --git a/dokimi/docs/skill-novelty.md b/dokimi/docs/skill-novelty.md index cde43d08c..adcd3e3b4 100644 --- a/dokimi/docs/skill-novelty.md +++ b/dokimi/docs/skill-novelty.md @@ -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 diff --git a/dokimi/dokimi/commands/novelty_budget.py b/dokimi/dokimi/commands/novelty_budget.py index 7cc1cbd04..885275bdc 100644 --- a/dokimi/dokimi/commands/novelty_budget.py +++ b/dokimi/dokimi/commands/novelty_budget.py @@ -220,10 +220,11 @@ def run_estimate(args: argparse.Namespace, settings, text: str, estimate_usd) -> 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 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 @@ -246,6 +247,7 @@ def print_run_estimate(args: argparse.Namespace, settings, text: str, estimate_u 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) @@ -257,6 +259,9 @@ def print_estimate_only(args: argparse.Namespace, settings, text: str, estimate_ 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) diff --git a/dokimi/dokimi/novelty/cost.py b/dokimi/dokimi/novelty/cost.py index 12260e36a..26173bf8c 100644 --- a/dokimi/dokimi/novelty/cost.py +++ b/dokimi/dokimi/novelty/cost.py @@ -114,6 +114,73 @@ def estimate_usd( 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``. + + Silent: :func:`estimate_usd` has said why a figure is missing. ``None`` when a role has no + price; the values sum to the estimate's ``expected_usd`` to rounding. + """ + from dokimi.novelty.tiers import usd_by_role + + try: + models = role_models(args) + except ValueError: + return None + split = usd_by_role(by_role, n_tokens, models, 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, + {"judge": (model, provider)}, tier, context_share) + if extra is None: + return None + split["judge"] = split.get("judge", 0.0) + extra["judge"] + return {role: round(split.get(role, 0.0), 6) for role in ROLES} + + +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) + 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.""" diff --git a/dokimi/dokimi/novelty/tiers.py b/dokimi/dokimi/novelty/tiers.py index 3308b16fd..7354b8761 100644 --- a/dokimi/dokimi/novelty/tiers.py +++ b/dokimi/dokimi/novelty/tiers.py @@ -346,6 +346,31 @@ def call_tokens(role: str, n_tokens: int, tier: str | None = None, 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, @@ -366,17 +391,8 @@ def estimate_usd( 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) def estimate_calls(n_atoms: int, settings: dict, *, n_arms: int = 2, diff --git a/dokimi/tests/test_novelty_estimate_roles.py b/dokimi/tests/test_novelty_estimate_roles.py new file mode 100644 index 000000000..abe39f390 --- /dev/null +++ b/dokimi/tests/test_novelty_estimate_roles.py @@ -0,0 +1,96 @@ +# 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 +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_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.") diff --git a/dokimi/tests/test_novelty_settings_parity.py b/dokimi/tests/test_novelty_settings_parity.py index 8e545bcbf..462d27dd8 100644 --- a/dokimi/tests/test_novelty_settings_parity.py +++ b/dokimi/tests/test_novelty_settings_parity.py @@ -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", @@ -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} From b4c4e37d12ec56e4c466fe1915b4f393ae0e5b54 Mon Sep 17 00:00:00 2001 From: Anton Volkov Date: Wed, 25 Nov 2026 17:42:47 +0000 Subject: [PATCH 2/2] test(novelty): cover role_usd's unpriced case and drop its unreachable guards Settles the codecov concern on cost.py. role_usd runs only after estimate_usd has resolved the role models and priced every role and panel judge, so its ValueError guard around role_models and its None return for a panel judge's price could not be reached; they are gone. The remaining None return for an unpriced role is now covered by a test that calls role_usd with an unpriced model. Signed-off-by: Anton Volkov --- dokimi/dokimi/novelty/cost.py | 16 +++++----------- dokimi/tests/test_novelty_estimate_roles.py | 8 +++++++- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/dokimi/dokimi/novelty/cost.py b/dokimi/dokimi/novelty/cost.py index 26173bf8c..bb1c7bdc9 100644 --- a/dokimi/dokimi/novelty/cost.py +++ b/dokimi/dokimi/novelty/cost.py @@ -121,24 +121,18 @@ def role_usd(args: argparse.Namespace, n_tokens: int, by_role: dict[str, int], t context_share: float = 0.5) -> dict[str, float] | None: """Each role's list-price dollars, panel judges after the first counted under ``judge``. - Silent: :func:`estimate_usd` has said why a figure is missing. ``None`` when a role has no - price; the values sum to the estimate's ``expected_usd`` to rounding. + ``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 - try: - models = role_models(args) - except ValueError: - return None - split = usd_by_role(by_role, n_tokens, models, tier, context_share) + 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, - {"judge": (model, provider)}, tier, context_share) - if extra is None: - return None - split["judge"] = split.get("judge", 0.0) + extra["judge"] + {"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} diff --git a/dokimi/tests/test_novelty_estimate_roles.py b/dokimi/tests/test_novelty_estimate_roles.py index abe39f390..7cdf97d9b 100644 --- a/dokimi/tests/test_novelty_estimate_roles.py +++ b/dokimi/tests/test_novelty_estimate_roles.py @@ -11,7 +11,7 @@ from dokimi.cli import build_parser from dokimi.llm_pricing import list_cost_usd -from dokimi.novelty.cost import role_models +from dokimi.novelty.cost import role_models, role_usd from dokimi.novelty.tiers import call_tokens ROLES = ("extractor", "answerer", "judge") @@ -87,6 +87,12 @@ def test_an_unpriced_model_gives_null_role_dollars_and_no_least_sure_role(tmp_pa 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")