From 2ded3ab94a0e8d0ac18b88a2b7f3345318f30069 Mon Sep 17 00:00:00 2001 From: Nikolay Petrov Date: Sat, 5 Dec 2026 23:27:20 -0800 Subject: [PATCH] feat(spend): paid guards slice 4: triggers generate --rewrite is priced and capped - eval triggers generate --rewrite: --dry-run prints the estimate (200 reply tokens per rewrite) and makes no client; --max-usd refuses before the first call or stops mid-run with exit 1 and writes no file. - --concurrency with --max-usd: a call in flight reserves its list-price estimate before dispatch and releases it on return, so calls in flight cannot pass the cap together (questions analyze/review). - The cap refusal names only the flags the leaf has: SpendCap.measure_less is set per leaf (novelty names --tier/--max-atoms only where they exist). Part of #94 (F1b, spend: paid-guards slice 4). Signed-off-by: Nikolay Petrov --- .../20261205_120000_cli-paid-guards-4.md | 16 ++ dokimi/docs/reference/cli-interface.json | 2 + dokimi/dokimi/commands/catalog.py | 34 ++--- dokimi/dokimi/commands/catalog_novelty.py | 8 +- dokimi/dokimi/commands/catalog_rewrite.py | 103 +++++++++++++ dokimi/dokimi/commands/questions.py | 5 +- dokimi/dokimi/novelty/client.py | 18 ++- dokimi/dokimi/novelty/cost.py | 9 +- dokimi/dokimi/questions/metered.py | 28 +++- dokimi/dokimi/questions/panel_reviewer.py | 3 +- dokimi/dokimi/questions/quality_analyzer.py | 3 +- dokimi/dokimi/spend.py | 44 +++++- dokimi/dokimi/spend_preview.py | 5 + dokimi/tests/test_cli_spend_controls.py | 1 - dokimi/tests/test_spend_inflight_reserve.py | 112 ++++++++++++++ dokimi/tests/test_triggers_dry_run_and_cap.py | 137 ++++++++++++++++++ 16 files changed, 474 insertions(+), 54 deletions(-) create mode 100644 dokimi/changelog.d/20261205_120000_cli-paid-guards-4.md create mode 100644 dokimi/dokimi/commands/catalog_rewrite.py create mode 100644 dokimi/tests/test_spend_inflight_reserve.py create mode 100644 dokimi/tests/test_triggers_dry_run_and_cap.py diff --git a/dokimi/changelog.d/20261205_120000_cli-paid-guards-4.md b/dokimi/changelog.d/20261205_120000_cli-paid-guards-4.md new file mode 100644 index 000000000..e24f4780a --- /dev/null +++ b/dokimi/changelog.d/20261205_120000_cli-paid-guards-4.md @@ -0,0 +1,16 @@ + + +### Added + +- **`eval triggers generate --rewrite` can be priced before it spends.** `--dry-run` prices one rewrite call per question at list prices and prints the estimate. It builds no model client, calls no model and writes no set. Without `--rewrite` it makes no model call and says so. The estimate assumes 200 reply tokens per rewrite. + +- **`eval triggers generate --rewrite --max-usd X`.** A real run exits 3 before its first call and builds no client if the estimate exceeds the cap or the model has no list price. A stop mid-run exits 1 and writes no set. `--max-usd` without `--rewrite` is an input error (exit 2). + +### Changed + +- **`--max-usd` holds each call's estimate while the call is in flight.** A call's list-price estimate is reserved from the cap until the call finishes, so calls running together under `--concurrency` cannot pass the cap between them. A call that raises gives its reservation back. This applies to `eval questions analyze` and `eval questions review`; the other metered leaves keep check-then-record. + +- **The cap refusal names only the flags the leaf has.** The refusal said `--tier` and `--max-atoms` on every leaf. Now `--tier` and `--max-atoms` are named only on the novelty leaves that take them; the other leaves get "measure less". diff --git a/dokimi/docs/reference/cli-interface.json b/dokimi/docs/reference/cli-interface.json index 7f35347ea..7101a9def 100644 --- a/dokimi/docs/reference/cli-interface.json +++ b/dokimi/docs/reference/cli-interface.json @@ -1345,9 +1345,11 @@ "allow_abbrev": true, "params": [ {"key": "--catalog", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": true, "type": null}, + {"key": "--dry-run", "action": "_StoreTrueAction", "choices": null, "const": true, "default": false, "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, {"key": "--fail-on", "action": "_StoreAction", "choices": ["'warn'"], "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--format", "action": "_StoreAction", "choices": ["'questions'", "'reach'", "'skill-creator'"], "const": null, "default": "reach", "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--help/-h", "action": "_HelpAction", "choices": null, "const": null, "default": "==SUPPRESS==", "group_key": null, "group_required": null, "hidden": false, "is_flag": true, "kind": "option", "nargs": 0, "position": null, "required": false, "type": null}, + {"key": "--max-usd", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": "dokimi.cli_types.positive_usd#3f7e5c8902a3"}, {"key": "--model", "action": "ProviderModelAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, {"key": "--out", "action": "_StoreAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": true, "type": null}, {"key": "--questions", "action": "_AppendAction", "choices": null, "const": null, "default": null, "group_key": null, "group_required": null, "hidden": false, "is_flag": false, "kind": "option", "nargs": null, "position": null, "required": false, "type": null}, diff --git a/dokimi/dokimi/commands/catalog.py b/dokimi/dokimi/commands/catalog.py index 3bd7e5a9e..cdb19950a 100644 --- a/dokimi/dokimi/commands/catalog.py +++ b/dokimi/dokimi/commands/catalog.py @@ -17,18 +17,18 @@ import argparse import json import sys -from collections.abc import Callable -from functools import cache from pathlib import Path from dokimi.cli_model_ref import add_model_flag +from dokimi.cli_types import positive_usd +from dokimi.commands.catalog_rewrite import build_queries from dokimi.commands.catalog_scan import ( ROW_STATES, fail_on_reason, fails_on_finding, is_plain_markdown, listing_failed, listing_message, listing_tally, not_checked, row_ignore, ok_text, plain_note, print_skill_row, skill_row, skipped_note, unrestricted_and_risky, ) from dokimi.external.catalog_rates import RateTally, text_lines -from dokimi.llm import ANSWER_PROVIDERS, PROVIDER_ALIASES, is_litellm_route from dokimi.files import InputError +from dokimi.llm import ANSWER_PROVIDERS, PROVIDER_ALIASES, is_litellm_route def _print_strict_reasons(rows: list, strict: bool) -> None: @@ -415,24 +415,6 @@ def _trigger_rewrite_model(model: str, provider: str, *, named: bool) -> tuple[s return model, provider -def _trigger_rewriter(args: argparse.Namespace, prompt: str) -> Callable[[str], str] | None: - if not args.rewrite: - return None - if not args.model: - raise InputError("--rewrite needs --model") - from dokimi.llm import llm_call - - @cache - def rewrite_model() -> tuple[str, str]: - return _trigger_rewrite_model(args.model, args.provider, named=args.rewrite_provider_named) - - def rewrite(text: str) -> str: - model, provider = rewrite_model() - return llm_call(prompt + text, model=model, provider=provider) - - return rewrite - - def cmd_catalog_trigger_set(args: argparse.Namespace) -> None: import json @@ -458,10 +440,8 @@ def cmd_catalog_trigger_set(args: argparse.Namespace) -> None: specs = list(args.questions or []) + [ None if args.format == "questions" else spec for spec in (args.trigger_set or [])] - rewrite = _trigger_rewriter(args, ts.REWRITE_PROMPT) - try: - queries = ts.build_trigger_set(sources, catalog, rewrite=rewrite, specs=specs) + queries = build_queries(args, sources, catalog, specs, _trigger_rewrite_model) except (ts.TriggerSetInputError, InputError) as exc: raise InputError(str(exc)) from exc except ValueError as exc: @@ -777,6 +757,12 @@ def register(sub, positive_int, eval_sub) -> None: ts_p.add_argument("--target", help="Target skill for --format skill-creator") ts_p.add_argument("--rewrite", action="store_true", help="Rewrite each question into first-person user voice (model sees only the question)") + ts_p.add_argument("--max-usd", type=positive_usd, default=None, dest="max_usd", metavar="X", + help=("With --rewrite: refuse before the first call if the cost estimate exceeds the cap or has " + "no list price (USD, exit 3). A mid-run stop exits 1 and writes no set.")) + cli_flags.add(ts_p, "dry_run", "--dry-run", action="store_true", dest="dry_run", + help="With --rewrite: price the rewrite calls at list prices and print the estimate; call no " + "model, build no client, write nothing") add_model_flag( ts_p, "--model", dest="model", provider_dest="provider", providers=(*ANSWER_PROVIDERS, *PROVIDER_ALIASES), named_dest="rewrite_provider_named", diff --git a/dokimi/dokimi/commands/catalog_novelty.py b/dokimi/dokimi/commands/catalog_novelty.py index 329c8dc10..7dfcb3d18 100644 --- a/dokimi/dokimi/commands/catalog_novelty.py +++ b/dokimi/dokimi/commands/catalog_novelty.py @@ -386,7 +386,8 @@ def _review_one(item: _Item, *, args: argparse.Namespace, run_cap: "SpendCap", p if run_cap.spent: return None - cap = NestedSpendCap(limit_usd=per_skill, parent=run_cap, hard_stop=hard_stop) + cap = NestedSpendCap(limit_usd=per_skill, parent=run_cap, hard_stop=hard_stop, + measure_less=run_cap.measure_less) def row(status: str, **fields: Any) -> dict: return make_row(key=item.key, name=item.name, path=str(item.skill_md), @@ -460,7 +461,10 @@ def cmd_catalog_novelty(args: argparse.Namespace) -> None: kept, todo, others = _plan(items, all_items, jsonl, args, fingerprint) print(f"# catalog novelty: {len(items)} skills under {root}; {len(kept)} measured and kept, " f"{len(todo)} to run", file=sys.stderr) - run_cap = SpendCap(limit_usd=args.max_usd, max_calls=getattr(args, "max_calls", None)) + from dokimi.novelty.cost import measure_less + + run_cap = SpendCap(limit_usd=args.max_usd, max_calls=getattr(args, "max_calls", None), + measure_less=measure_less(args)) per = f", ${args.max_usd_per_skill:g} per skill" if args.max_usd_per_skill else "" whole = " and ".join(([f"${args.max_usd:g}"] if args.max_usd is not None else []) + ([f"{args.max_calls} calls"] if getattr(args, "max_calls", None) else [])) diff --git a/dokimi/dokimi/commands/catalog_rewrite.py b/dokimi/dokimi/commands/catalog_rewrite.py new file mode 100644 index 000000000..06134757b --- /dev/null +++ b/dokimi/dokimi/commands/catalog_rewrite.py @@ -0,0 +1,103 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""The ``--rewrite`` calls of ``eval triggers generate``: priced under ``--dry-run``, capped by ``--max-usd``. + +Part of #94 (F1b, spend: paid-guards slice 4). The command's flags and writes stay in +:mod:`dokimi.commands.catalog`; this module owns what a rewrite costs and when it may run. +""" + +from __future__ import annotations + +import argparse +import sys +from collections.abc import Callable +from functools import cache + +from dokimi import spend_preview +from dokimi.exit_codes import EXIT_FAILURE, EXIT_INCONCLUSIVE +from dokimi.files import InputError +from dokimi.spend import SpendCap, SpendCapReached + +# A rewrite's reply is one short first-person question: 200 tokens is the assumption the estimate prices. +REWRITE_REPLY_TOKENS = 200 + + +# The provider resolver of ``eval triggers generate`` (catalog's ``_trigger_rewrite_model``), passed in: this module +# is imported by the command module, so it cannot import that module back. +Resolver = Callable[..., tuple[str, str]] + + +def build_queries(args: argparse.Namespace, sources, catalog, specs, resolve: Resolver): + """The trigger set with its --rewrite calls priced and capped. A dry run exits 0 before any call is made. + + A stop at the --max-usd cap exits 1 here: the set is written after the last rewrite, so no file is left. + """ + from dokimi.external import trigger_set as ts + + check_rewrite_flags(args) + if args.rewrite and (args.dry_run or args.max_usd is not None): + rewrite_gate(args, sources, catalog, specs, resolve) + cap = SpendCap(args.max_usd) if args.max_usd is not None else None + rewrite = trigger_rewriter(args, ts.REWRITE_PROMPT, resolve, cap) + try: + return ts.build_trigger_set(sources, catalog, rewrite=rewrite, specs=specs) + except SpendCapReached as exc: + print(f"Error: the --max-usd cap was reached: {exc}", file=sys.stderr) + sys.exit(EXIT_FAILURE) + + +def check_rewrite_flags(args: argparse.Namespace) -> None: + """Refuse a bad combination of --rewrite flags before any call; a dry run without --rewrite exits 0 here.""" + if args.max_usd is not None and not args.rewrite: + raise InputError("--max-usd needs --rewrite: a trigger set makes no model call without it") + if args.dry_run and not args.rewrite: + print("Dry run: no --rewrite, so the trigger set makes no model call; nothing is written.") + sys.exit(0) + if args.rewrite and not args.model: + raise InputError("--rewrite needs --model") + + +def trigger_rewriter(args: argparse.Namespace, prompt: str, resolve: Resolver, + cap: SpendCap | None = None) -> Callable[[str], str] | None: + if not args.rewrite: + return None + from dokimi.llm import llm_call, llm_call_with_usage + + @cache + def rewrite_model() -> tuple[str, str]: + return resolve(args.model, args.provider, named=args.rewrite_provider_named) + + def rewrite(text: str) -> str: + model, provider = rewrite_model() + if cap is None: + return llm_call(prompt + text, model=model, provider=provider) + # Under --max-usd: the cap is checked before the call and the call's usage is counted after it. + cap.before_call(model) + reply, usage = llm_call_with_usage(prompt + text, model=model, provider=provider) + cap.record(usage, model) + return reply + + return rewrite + + +def price_rewrites(args: argparse.Namespace, sources, catalog, specs, resolve: Resolver) -> str | None: + """Price the --rewrite calls before any is made: one per question. Returns the gate verdict (None: go ahead).""" + from dokimi.external import trigger_set as ts + + # Client-free: labels and lint only, the rewrite step is left out. + queries = ts.build_trigger_set(sources, catalog, rewrite=None, specs=specs) + model, provider = resolve(args.model, args.provider, named=args.rewrite_provider_named) + prompts = [ts.REWRITE_PROMPT + q.text for q in queries] + return spend_preview.gate(lambda: prompts, model=model, provider=provider, reply_tokens=REWRITE_REPLY_TOKENS, + dry_run=args.dry_run, max_usd=args.max_usd, + mid_run_stop_note=f"a stop mid-run exits {EXIT_FAILURE} and writes no set") + + +def rewrite_gate(args: argparse.Namespace, sources, catalog, specs, resolve: Resolver) -> None: + """Under --dry-run or --max-usd: exit 0 after a dry run, exit 3 when the estimate is refused; otherwise return.""" + verdict = price_rewrites(args, sources, catalog, specs, resolve) + if verdict == spend_preview.REFUSED: + sys.exit(EXIT_INCONCLUSIVE) + if verdict == spend_preview.DRY: + sys.exit(0) diff --git a/dokimi/dokimi/commands/questions.py b/dokimi/dokimi/commands/questions.py index 953c67fc1..c437685a0 100644 --- a/dokimi/dokimi/commands/questions.py +++ b/dokimi/dokimi/commands/questions.py @@ -23,10 +23,7 @@ from dokimi.model_names import warn_recorded_self_judge from dokimi.spend import SpendCap, SpendCapReached -# Reply tokens assumed per call for the --dry-run estimate and the --max-usd check before the first call. -# A classification is a short JSON object; a panel vote is one score per dimension, a reason and flags. -CLASSIFY_REPLY_TOKENS = 400 -REVIEW_REPLY_TOKENS = 800 +from dokimi.spend_preview import CLASSIFY_REPLY_TOKENS, REVIEW_REPLY_TOKENS def _load_questions_json(path: str): diff --git a/dokimi/dokimi/novelty/client.py b/dokimi/dokimi/novelty/client.py index 82db63c07..91e34d873 100644 --- a/dokimi/dokimi/novelty/client.py +++ b/dokimi/dokimi/novelty/client.py @@ -73,27 +73,29 @@ class NestedSpendCap(SpendCap): def __init__(self, limit_usd: float | None, spent_usd: float = 0.0, calls: int = 0, *, parent: SpendCap | None = None, hard_stop: threading.Event | None = None, - **counts: int) -> None: - super().__init__(limit_usd, spent_usd, calls, **counts) + measure_less: str = "measure less", **counts: int) -> None: + super().__init__(limit_usd, spent_usd, calls, measure_less=measure_less, **counts) self.parent, self.hard_stop = parent, hard_stop - def before_call(self, model: str, *, reserve: bool = True) -> None: + def before_call(self, model: str, *, reserve: bool = True, reserve_usd: float = 0.0) -> None: if self.hard_stop is not None and self.hard_stop.is_set(): raise SpendCapReached(f"stopped by a second signal; not calling {model}", reason="stopped") - super().before_call(model, reserve=reserve) + super().before_call(model, reserve=reserve, reserve_usd=reserve_usd) if self.parent is not None: try: - self.parent.before_call(model, reserve=reserve) + self.parent.before_call(model, reserve=reserve, reserve_usd=reserve_usd) except SpendCapReached: if reserve: with self._lock: self.release_call() # the call is not made: its slot here is free again + self._release_usd_locked(reserve_usd) raise - def record(self, usage: UsageRecord | None, model: str, *, reserved: bool = True) -> None: + def record(self, usage: UsageRecord | None, model: str, *, reserved: bool = True, + reserve_usd: float = 0.0) -> None: if self.parent is not None: - self.parent.record(usage, model, reserved=reserved) - super().record(usage, model, reserved=reserved) + self.parent.record(usage, model, reserved=reserved, reserve_usd=reserve_usd) + super().record(usage, model, reserved=reserved, reserve_usd=reserve_usd) @dataclass diff --git a/dokimi/dokimi/novelty/cost.py b/dokimi/dokimi/novelty/cost.py index 4711ac884..f3bed06ee 100644 --- a/dokimi/dokimi/novelty/cost.py +++ b/dokimi/dokimi/novelty/cost.py @@ -219,6 +219,13 @@ def usd_cap_refusal(max_usd: float | None, providers: Iterable[str]) -> str | No "price per call. Cap the run with --max-calls N instead, or use an API provider") +def measure_less(args: argparse.Namespace) -> str: + """What a cap refusal suggests besides a higher ``--max-usd``: only the cost flags this leaf has.""" + flags = [text for name, text in (("tier", "a cheaper --tier"), ("max_atoms", "a lower --max-atoms")) + if hasattr(args, name)] + return f"measure less ({', '.join(flags)})" if flags else "measure less" + + def spend_cap(args: argparse.Namespace, provider: str | None = None): """The invocation's one cap (``--max-usd``, ``--max-calls`` or both), shared by every role client. @@ -237,7 +244,7 @@ def spend_cap(args: argparse.Namespace, provider: str | None = None): return args._spend_cap if limit is None and max_calls is None: return None - args._spend_cap = SpendCap(limit_usd=limit, max_calls=max_calls) + args._spend_cap = SpendCap(limit_usd=limit, max_calls=max_calls, measure_less=measure_less(args)) return args._spend_cap diff --git a/dokimi/dokimi/questions/metered.py b/dokimi/dokimi/questions/metered.py index ecee6ad34..afa210c68 100644 --- a/dokimi/dokimi/questions/metered.py +++ b/dokimi/dokimi/questions/metered.py @@ -13,24 +13,42 @@ from dokimi.spend import Spend, SpendCap + class MeteredCalls: - """One analyzer run's model calls: the usage of each is added to ``spend`` and, with a cap, checked first.""" + """One analyzer run's model calls: the usage of each is added to ``spend`` and, with a cap, checked first. + + With a cap, a call's list-price estimate (``reply_tokens`` assumed back) is held from the cap while the call + is in flight, so ``--concurrency`` calls cannot pass ``--max-usd`` together; a call that raises gives it back. + """ - def __init__(self, model: str, provider: str, cap: Optional[SpendCap]): + def __init__(self, model: str, provider: str, cap: Optional[SpendCap], reply_tokens: int = 0): self.model = model self.provider = provider self.cap = cap + self.reply_tokens = reply_tokens self.spend = Spend() self._lock = threading.Lock() + def _estimate(self, prompt: str) -> float: + """The call's list price, as ``spend_preview`` prices it; 0 when it has none (the cap refuses that on record).""" + from dokimi.spend_preview import price_calls + + return price_calls([prompt], self.model, self.provider, self.reply_tokens)["usd"] or 0.0 + def __call__(self, prompt: str, call: Callable[..., Tuple[str, UsageRecord]]) -> str: """Make one call through ``call`` (the caller passes its ``llm_call_with_usage``) and return the reply text.""" + held = self._estimate(prompt) if self.cap is not None and self.cap.limit_usd is not None else 0.0 if self.cap is not None: - self.cap.before_call(self.model) - text, usage = call(prompt, model=self.model, provider=self.provider) + self.cap.before_call(self.model, reserve_usd=held) + try: + text, usage = call(prompt, model=self.model, provider=self.provider) + except BaseException: + if self.cap is not None: + self.cap.release_usd(held) + raise with self._lock: self.spend.add_call(usage) if self.cap is not None: - self.cap.record(usage, self.model) + self.cap.record(usage, self.model, reserve_usd=held) return text diff --git a/dokimi/dokimi/questions/panel_reviewer.py b/dokimi/dokimi/questions/panel_reviewer.py index 30e9d370d..04fa0ed61 100644 --- a/dokimi/dokimi/questions/panel_reviewer.py +++ b/dokimi/dokimi/questions/panel_reviewer.py @@ -25,6 +25,7 @@ from dokimi.llm import llm_call_with_usage, extract_json_object from dokimi.defaults import DEFAULT_GENERATOR_MODEL, DEFAULT_GENERATOR_PROVIDER from dokimi.questions.metered import MeteredCalls +from dokimi.spend_preview import REVIEW_REPLY_TOKENS from dokimi.spend import SpendCap logger = logging.getLogger(__name__) @@ -179,7 +180,7 @@ def __init__( self.provider = provider self.concurrency = concurrency self.cap = cap - self._meter = MeteredCalls(self.model, self.provider, cap) + self._meter = MeteredCalls(self.model, self.provider, cap, reply_tokens=REVIEW_REPLY_TOKENS) self.spend = self._meter.spend def _build_prompt(self, reviewer: str, question: str, library_name: str) -> str: diff --git a/dokimi/dokimi/questions/quality_analyzer.py b/dokimi/dokimi/questions/quality_analyzer.py index e86a1fbb7..4c3de7c76 100644 --- a/dokimi/dokimi/questions/quality_analyzer.py +++ b/dokimi/dokimi/questions/quality_analyzer.py @@ -14,6 +14,7 @@ from dokimi.llm import llm_call_with_usage from dokimi.defaults import DEFAULT_GENERATOR_MODEL, DEFAULT_GENERATOR_PROVIDER from dokimi.questions.metered import MeteredCalls +from dokimi.spend_preview import CLASSIFY_REPLY_TOKENS from dokimi.spend import SpendCap logger = logging.getLogger(__name__) @@ -92,7 +93,7 @@ def __init__( self.provider = provider self.concurrency = concurrency self.cap = cap - self._meter = MeteredCalls(model, provider, cap) + self._meter = MeteredCalls(model, provider, cap, reply_tokens=CLASSIFY_REPLY_TOKENS) self.spend = self._meter.spend def _call(self, prompt: str) -> str: diff --git a/dokimi/dokimi/spend.py b/dokimi/dokimi/spend.py index eb8cbc7e3..22376cf68 100644 --- a/dokimi/dokimi/spend.py +++ b/dokimi/dokimi/spend.py @@ -164,23 +164,31 @@ class SpendCap(Spend): limit_usd: float | None max_calls: int | None = None + #: What the refusal suggests besides a higher ``--max-usd``: the leaf's own flags, if it has any. + measure_less: str = "measure less" started_calls: int = field(default=0, init=False) + #: The list-price estimates of the calls in flight: a call's estimate is held until it finishes. + reserved_usd: float = field(default=0.0, init=False) _lock: threading.Lock = field(default_factory=threading.Lock, init=False, repr=False, compare=False) def __init__(self, limit_usd: float | None, spent_usd: float = 0.0, calls: int = 0, *, - max_calls: int | None = None, **counts: int) -> None: + max_calls: int | None = None, measure_less: str = "measure less", **counts: int) -> None: # Positional as before the move to Spend: SpendCap(limit_usd, spent_usd, calls). super().__init__(spent_usd=spent_usd, calls=calls, **counts) self.limit_usd = limit_usd self.max_calls = max_calls + self.measure_less = measure_less self.started_calls = calls + self.reserved_usd = 0.0 self._lock = threading.Lock() - def before_call(self, model: str, *, reserve: bool = True) -> None: + def before_call(self, model: str, *, reserve: bool = True, reserve_usd: float = 0.0) -> None: """Refuse a call the limits forbid; with ``reserve`` (the default) take its call slot too. - ``reserve=False`` checks the USD limit only: for a call that may be answered from the response - cache, whose provider requests (if any) reserve their slots one by one. + ``reserve_usd`` is the call's list-price estimate: it is held from the USD limit until + :meth:`record` (or :meth:`release_usd`) gives it back, so calls in flight cannot pass the cap + together. ``reserve=False`` checks the USD limit only: for a call that may be answered from the + response cache, whose provider requests (if any) reserve their slots one by one. """ with self._lock: # An unpriced call stops every worker, not just the one whose call raised. @@ -194,10 +202,18 @@ def before_call(self, model: str, *, reserve: bool = True) -> None: raise SpendCapReached( f"spend cap reached: ${self.spent_usd:.2f} of ${self.limit_usd:.2f} " f"after {self.calls} calls (next call: {model}). " - "Raise --max-usd, or measure less (a cheaper --tier, a lower --max-atoms)" + f"Raise --max-usd, or {self.measure_less}" ) if not reserve: return + if self.limit_usd is not None and reserve_usd > 0 and ( + self.spent_usd + self.reserved_usd + reserve_usd > self.limit_usd): + raise SpendCapReached( + f"spend cap would be passed: ${self.spent_usd:.2f} spent and ${self.reserved_usd:.2f} " + f"in flight, plus about ${reserve_usd:.2f} for the next call ({model}), is over " + f"${self.limit_usd:.2f} (after {self.calls} calls). " + f"Raise --max-usd, or {self.measure_less}" + ) if self.max_calls is not None and self.started_calls >= self.max_calls: raise SpendCapReached( f"call cap reached: {self.started_calls} of {self.max_calls} calls made " @@ -205,11 +221,16 @@ def before_call(self, model: str, *, reserve: bool = True) -> None: reason="call_cap", ) self.started_calls += 1 + if reserve_usd > 0 and self.limit_usd is not None: # no USD limit, nothing to hold + self.reserved_usd += reserve_usd - def record(self, usage: UsageRecord | None, model: str, *, reserved: bool = True) -> None: - """Count a finished call; ``reserved`` says :meth:`before_call` took a slot for it up front.""" + def record(self, usage: UsageRecord | None, model: str, *, reserved: bool = True, + reserve_usd: float = 0.0) -> None: + """Count a finished call; ``reserved`` says :meth:`before_call` took a slot for it up front, and + ``reserve_usd`` gives back the estimate it held.""" with self._lock: unpriced = self.unpriced_calls + self._release_usd_locked(reserve_usd) self.add_call(usage) if reserved and usage is not None and usage.replayed: self.release_call() @@ -231,3 +252,12 @@ def release_call(self) -> None: """Give back a slot :meth:`before_call` took for a call that was not paid for (or not made).""" self.started_calls = max(self.started_calls - 1, 0) + def release_usd(self, reserve_usd: float) -> None: + """Give back the estimate :meth:`before_call` held for a call that raised before it was paid for.""" + with self._lock: + self._release_usd_locked(reserve_usd) + + def _release_usd_locked(self, reserve_usd: float) -> None: + if reserve_usd > 0: + self.reserved_usd = max(self.reserved_usd - reserve_usd, 0.0) + diff --git a/dokimi/dokimi/spend_preview.py b/dokimi/dokimi/spend_preview.py index 866637f19..1097581a8 100644 --- a/dokimi/dokimi/spend_preview.py +++ b/dokimi/dokimi/spend_preview.py @@ -18,6 +18,11 @@ DRY = "dry" REFUSED = "refused" +# Reply tokens assumed per call for the --dry-run estimate and the --max-usd check before the first call. +# Here, not in dokimi.questions: importing that package pulls in optional deps (httpx) that commands must not need. +CLASSIFY_REPLY_TOKENS = 400 # a short JSON object +REVIEW_REPLY_TOKENS = 800 # one score per dimension, a reason and flags + def price_calls(prompts: Sequence[str], model: str, provider: str, reply_tokens: int) -> dict[str, Any]: """Token counts and list-price cost of one call per prompt, priced before any call is made. diff --git a/dokimi/tests/test_cli_spend_controls.py b/dokimi/tests/test_cli_spend_controls.py index dee75b1da..65684f9e8 100644 --- a/dokimi/tests/test_cli_spend_controls.py +++ b/dokimi/tests/test_cli_spend_controls.py @@ -47,7 +47,6 @@ eval score pointwise eval score ragas eval score reference -eval triggers generate evaluate explore run repo reach diff --git a/dokimi/tests/test_spend_inflight_reserve.py b/dokimi/tests/test_spend_inflight_reserve.py new file mode 100644 index 000000000..f308b5abd --- /dev/null +++ b/dokimi/tests/test_spend_inflight_reserve.py @@ -0,0 +1,112 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""SpendCap reserves the list-price estimate of each call in flight, and names the leaf's own cap hint. + +Part of #94 (F1b, spend: paid-guards slice 4, the leftovers of #1576). +""" + +from __future__ import annotations + +import pytest + +from dokimi import llm_pricing +from dokimi.metrics.usage import UsageRecord +from dokimi.questions.metered import MeteredCalls +from dokimi.spend import SpendCap, SpendCapReached + + +def _usage(cost: float) -> UsageRecord: + return UsageRecord(prompt_tokens=10, completion_tokens=5, cost_usd=cost) + + +def test_calls_in_flight_cannot_pass_the_cap_together(): + cap = SpendCap(1.0) + cap.before_call("m", reserve_usd=0.4) + cap.before_call("m", reserve_usd=0.4) # 0.8 reserved: fits + with pytest.raises(SpendCapReached) as stop: + cap.before_call("m", reserve_usd=0.4) # 1.2 would pass the cap before any of the three has finished + assert stop.value.reason == "spend_cap" + assert cap.spent_usd == 0.0 + + +def test_a_finished_call_gives_its_reservation_back(): + cap = SpendCap(1.0) + cap.before_call("m", reserve_usd=0.4) + cap.before_call("m", reserve_usd=0.4) + cap.record(_usage(0.1), "m", reserve_usd=0.4) # paid 0.1, reservation released + # 0.1 spent, one 0.4 still in flight: a new 0.4 fits; a second one would not + cap.before_call("m", reserve_usd=0.4) + with pytest.raises(SpendCapReached): + cap.before_call("m", reserve_usd=0.4) + assert cap.spent_usd == pytest.approx(0.1) + + +def test_a_failed_call_gives_its_reservation_back(): + cap = SpendCap(1.0) + cap.before_call("m", reserve_usd=0.6) + cap.release_usd(0.6) # the call raised: nothing was paid, nothing stays reserved + assert cap.reserved_usd == pytest.approx(0.0) + cap.before_call("m", reserve_usd=0.6) # fits again: the first reservation is gone + assert cap.reserved_usd == pytest.approx(0.6) + + +def test_reservation_is_not_taken_without_a_usd_cap(): + cap = SpendCap(None, max_calls=5) + cap.before_call("m", reserve_usd=99.0) + assert cap.reserved_usd == 0.0 + assert cap.spent_usd == 0.0 + + +def test_default_hint_names_no_leaf_flag(): + cap = SpendCap(0.01, spent_usd=0.02) + with pytest.raises(SpendCapReached) as stop: + cap.before_call("m") + assert str(stop.value).endswith("Raise --max-usd, or measure less") + assert "--tier" not in str(stop.value) and "--max-atoms" not in str(stop.value) + + +def test_leaf_hint_is_used_as_given(): + hint = "measure less (a lower --max-atoms)" + cap = SpendCap(0.01, spent_usd=0.02, measure_less=hint) + with pytest.raises(SpendCapReached) as stop: + cap.before_call("m") + assert str(stop.value).endswith(f"Raise --max-usd, or {hint}") + + +def test_metered_calls_reserve_the_list_price_while_the_call_runs(monkeypatch): + monkeypatch.setattr(llm_pricing, "list_cost_usd", lambda *_a, **_k: 0.25) + cap = SpendCap(1.0) + seen: dict = {} + + def call(prompt, model, provider): + seen["reserved"] = cap.reserved_usd # observed while the call is in flight + return "ok", _usage(0.2) + + meter = MeteredCalls("m", "openai", cap, reply_tokens=400) + assert meter("a prompt", call) == "ok" + assert seen["reserved"] == pytest.approx(0.25) + assert cap.reserved_usd == pytest.approx(0.0) + assert cap.spent_usd == pytest.approx(0.2) + + +def test_metered_calls_give_the_reservation_back_when_the_call_raises(monkeypatch): + monkeypatch.setattr(llm_pricing, "list_cost_usd", lambda *_a, **_k: 0.25) + cap = SpendCap(1.0) + + def call(prompt, model, provider): + raise RuntimeError("provider down") + + meter = MeteredCalls("m", "openai", cap, reply_tokens=400) + with pytest.raises(RuntimeError): + meter("a prompt", call) + assert cap.reserved_usd == pytest.approx(0.0) + + +def test_metered_calls_without_a_cap_price_nothing(monkeypatch): + def boom(*_a, **_k): + raise AssertionError("priced without a cap") + + monkeypatch.setattr(llm_pricing, "list_cost_usd", boom) + meter = MeteredCalls("m", "openai", None, reply_tokens=400) + assert meter("p", lambda prompt, model, provider: ("ok", _usage(0.0))) == "ok" diff --git a/dokimi/tests/test_triggers_dry_run_and_cap.py b/dokimi/tests/test_triggers_dry_run_and_cap.py new file mode 100644 index 000000000..c814b4e20 --- /dev/null +++ b/dokimi/tests/test_triggers_dry_run_and_cap.py @@ -0,0 +1,137 @@ +# Copyright (C) 2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +"""`eval triggers generate --rewrite`: --dry-run prices the rewrite calls and builds no client; --max-usd gates them. + +Part of #94 (F1b, spend: paid-guards slice 4, the trigger-set rewrite leaf). +""" + +from __future__ import annotations + +import json + +import pytest + +from dokimi import cli, llm, llm_pricing +from dokimi.metrics.usage import UsageRecord + +QUESTIONS = ["How do I pin the thread count?", "Why does parallel_for hang?", "Explain task_arena reuse"] + + +def _cli(monkeypatch, *argv: str) -> int: + monkeypatch.setattr("sys.argv", ["dokimi", *argv]) + try: + cli.main() + except SystemExit as exc: + return int(exc.code or 0) + return 0 + + +def _catalog(tmp_path): + root = tmp_path / "skills" + for name in ("alpha", "beta"): + (root / name).mkdir(parents=True) + (root / name / "SKILL.md").write_text( + f"---\nname: {name}\ndescription: Does {name} things.\n---\nbody\n", encoding="utf-8") + return root + + +def _questions(tmp_path, items=QUESTIONS): + path = tmp_path / "questions.json" + path.write_text(json.dumps([{"id": f"q{i}", "question": q} for i, q in enumerate(items, 1)]), encoding="utf-8") + return path + + +def _argv(tmp_path, *extra: str) -> list[str]: + return ["eval", "triggers", "generate", "--catalog", str(_catalog(tmp_path)), + "--questions", f"{_questions(tmp_path)}=none", "--out", str(tmp_path / "set.json"), *extra] + + +@pytest.fixture +def priced(monkeypatch): + """Every call's list price is 0.1 USD, whatever the model.""" + monkeypatch.setattr(llm_pricing, "list_cost_usd", lambda *_a, **_k: 0.1) + + +@pytest.fixture +def no_client(monkeypatch): + """A model call or a client construction fails the test: a dry run and a refusal must make neither.""" + + def refuse(*_a, **_k): + raise AssertionError("a model client was built or called") + + monkeypatch.setattr(llm, "llm_call_with_usage", refuse) + monkeypatch.setattr(llm.LLM, "__init__", refuse) + return refuse + + +@pytest.fixture +def replies(monkeypatch): + """The rewrite calls: each returns a first-person text and records the prompt it was given.""" + seen: list[str] = [] + + def call(prompt, model, provider="openai", **_k): + seen.append(prompt) + return "Please help me with the thing.", UsageRecord(prompt_tokens=10, completion_tokens=5, cost_usd=0.5) + + monkeypatch.setattr(llm, "llm_call_with_usage", call) + return seen + + +def test_dry_run_prices_one_rewrite_per_question_and_writes_nothing(tmp_path, monkeypatch, priced, no_client): + code = _cli(monkeypatch, *_argv(tmp_path, "--rewrite", "--model", "gpt-4o-mini", "--dry-run")) + assert code == 0 + assert not (tmp_path / "set.json").exists() + + +def test_dry_run_prints_the_estimate_for_the_rewrite_calls(tmp_path, monkeypatch, priced, no_client, capsys): + _cli(monkeypatch, *_argv(tmp_path, "--rewrite", "--model", "gpt-4o-mini", "--dry-run")) + out = capsys.readouterr().out + assert "Estimate: 3 model calls" in out + assert "no model was called" in out + + +def test_dry_run_without_rewrite_calls_no_model_and_writes_nothing(tmp_path, monkeypatch, no_client, capsys): + assert _cli(monkeypatch, *_argv(tmp_path, "--dry-run")) == 0 + assert not (tmp_path / "set.json").exists() + assert "no model call" in capsys.readouterr().out + + +def test_max_usd_refuses_before_the_first_call_when_the_estimate_is_over(tmp_path, monkeypatch, priced, no_client, + capsys): + # 3 calls at 0.1 = 0.3 estimated; a cap of 0.2 is refused before any client exists. + code = _cli(monkeypatch, *_argv(tmp_path, "--rewrite", "--model", "gpt-4o-mini", "--max-usd", "0.2")) + assert code == 3 + assert not (tmp_path / "set.json").exists() + assert "no call was made" in capsys.readouterr().err + + +def test_max_usd_stops_mid_run_with_exit_1_and_writes_nothing(tmp_path, monkeypatch, priced, replies, capsys): + # The estimate (0.3) fits the cap (0.6). Each real call costs 0.5: after the first, 0.5 is spent and + # under 0.6, so the second call goes ahead and brings it to 1.0; the third is refused. + code = _cli(monkeypatch, *_argv(tmp_path, "--rewrite", "--model", "gpt-4o-mini", "--max-usd", "0.6")) + assert code == 1 + assert len(replies) == 2 + assert not (tmp_path / "set.json").exists() + assert "--max-usd cap was reached" in capsys.readouterr().err + + +def test_max_usd_refusal_hint_names_no_leaf_flag_this_leaf_lacks(tmp_path, monkeypatch, priced, replies, capsys): + _cli(monkeypatch, *_argv(tmp_path, "--rewrite", "--model", "gpt-4o-mini", "--max-usd", "0.6")) + err = capsys.readouterr().err + assert "spend cap reached" in err and "measure less" in err + assert "--tier" not in err and "--max-atoms" not in err + + +def test_max_usd_without_rewrite_is_an_input_error_before_any_call(tmp_path, monkeypatch, no_client, capsys): + assert _cli(monkeypatch, *_argv(tmp_path, "--max-usd", "1")) == 2 + assert not (tmp_path / "set.json").exists() + assert "--max-usd needs --rewrite" in capsys.readouterr().err + + +def test_plain_rewrite_still_writes_the_set(tmp_path, monkeypatch, replies): + assert _cli(monkeypatch, *_argv(tmp_path, "--rewrite", "--model", "gpt-4o-mini")) == 0 + assert len(replies) == len(QUESTIONS) + assert all(any(q in p for q in QUESTIONS) for p in replies) # each prompt carries its question + data = json.loads((tmp_path / "set.json").read_text(encoding="utf-8")) + assert data # written once every rewrite returned