From 41b6c72cb1a90385c6463aebb2d35e3123825e6d Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Mon, 30 Nov 2026 18:57:05 +0530 Subject: [PATCH 1/2] `loom code describe` stops at `--limit` and `--max-usd` and prints what it spent `--limit N` bounded nothing a run had already queued: the stop flag was read once at the top of each file and chunk coroutine, before it waited on its semaphore, and every coroutine had started before the first description landed. Over 3 files of 10 pending chunks, `--limit 5 --concurrency 8` made 30 provider calls. The command also printed no usage: provider clients report to a cost accumulator that the command never bound. A description is now admitted after it holds its concurrency slot, and the count of calls started moves with the check, so at most N calls start. Each description runs under its own accumulator and the run sums them into its last line: chunks described, already described and remaining, input, output and embedding tokens, and dollars from the price table, or the unpriced model's name. `--max-usd` reserves the dearest description so far for each call in flight and for the next one, runs the first description alone to learn that cost, and refuses a description model without a price. A stopped run still reads every selected file, as every run did before, to count what is left. The CLI help snapshot is regenerated under Python 3.12: `--limit` has new help text and `--max-usd` is added. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/operations/code-index-operations.md | 13 +- docs/reference/cli.md | 2 +- server/cli/code.py | 14 +- server/cli/code_maintenance.py | 203 +++++++++++----- tests/unit/snapshots/cli_help.json | 4 +- tests/unit/snapshots/cli_tree.json | 18 +- tests/unit/test_code_describe_bounds.py | 221 ++++++++++++++++++ .../test_code_description_provider_guard.py | 4 +- tests/unit/test_code_embed_exclude.py | 2 +- 9 files changed, 419 insertions(+), 62 deletions(-) create mode 100644 tests/unit/test_code_describe_bounds.py diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 0447639b153..9a18a1e4463 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -322,7 +322,18 @@ Then: searches then read `medium` or `high`, and the coding-agent plugins send no search pointers for them. - `loom code describe --top-pct 20` (optional, LLM cost) writes one-line descriptions for - the most central chunks. + the most central chunks. `--limit N` starts at most N description calls. `--max-usd D` + stops before a call that would take the run's spend past D dollars: it counts each + call in flight, and the next one, at the cost of the dearest description so far, and + runs the first description alone to learn that cost. Only a description that costs + more than every earlier one can take the run past D, by that difference. It refuses a + description model the server's price table does not list. The last line counts the + chunks described, already described and remaining in the selected files, the tokens + the provider calls reported and their price from the price table (tokens only for a + model the table does not list): + `describe complete: 40 described, 310 current, 1150 remaining (stopped at --limit 40); 52114 input + 1876 output tokens, 9120 embedding tokens, $0.0127`. + A run that was bounded or interrupted is resumed by running the command again, which + skips the chunks already described. - `loom code stats` prints the watermarks (`git_head`, `scip_commit`, …) and live row counts; `POST /v1/code.index_status` answers the same from the API. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 5141ff16320..f3e8e5bc339 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -239,7 +239,7 @@ python scripts/codegen/docs_reference.py | `loom code export-pairs` | Export (query -> acted-on unit, hard negatives) retrieval pairs from real traffic (trace x outcome join) for embedder/reranker fine-tuning. | `--org`, `--namespace`, `--days`, `--out` | | `loom code backfill-prs` | Merged-PR history from GitHub. | `--org`, `--namespace`, `--months`, `--max-prs` | | `loom code repack` | Regenerate context packs for recently merged PRs in the current pack shape. | `--org`, `--namespace`, `--days`, `--limit`, `--dry-run` | -| `loom code describe` | LLM contextual one-liners for top-PageRank chunks. | `--org`, `--namespace`, `--top-pct`, `--limit`, `--suffix`, `--concurrency` | +| `loom code describe` | LLM contextual one-liners for top-PageRank chunks. | `--org`, `--namespace`, `--top-pct`, `--limit`, `--max-usd`, `--suffix`, `--concurrency` | | `loom code answers-purge` | Tombstone cached code.ask answers (after a synthesis-model upgrade, stale weaker-model answers would otherwise be served forever — the cache only self-invalidates on cited-file change). | `--llm-model`, `--all`, `--apply`, `--dry-run`, `--org`, `--namespace` | | `loom code scip-full` | Full compiler-tier re-index by hand (the code_scip_full worker runs it weekly by default: heals the TU-cap degrades of per-merge deltas and any drift). | `--checkout`, `--jobs`, `--keep-delta`, `--apply-delta`, `--org`, `--namespace` | | `loom code scip-lock-path` | Print the entry's compiler-tier lock file on this host. | `--org`, `--namespace` | diff --git a/server/cli/code.py b/server/cli/code.py index 8a6527f0856..0a8ba3992d7 100644 --- a/server/cli/code.py +++ b/server/cli/code.py @@ -248,7 +248,19 @@ def _add_describe_parser(csub: argparse._SubParsersAction[argparse.ArgumentParse p_desc = csub.add_parser("describe", help="LLM contextual one-liners for top-PageRank chunks.") _add_common(p_desc) p_desc.add_argument("--top-pct", type=float, default=20.0) - p_desc.add_argument("--limit", type=int, default=0, help="max chunks (0 = all in pct)") + p_desc.add_argument( + "--limit", + type=int, + default=0, + help="most chunks this run describes (0 = all in pct); a rerun skips described chunks", + ) + p_desc.add_argument( + "--max-usd", + type=float, + default=0.0, + help="stop before a description that would take this run's provider spend past " + "this many dollars (0 = no cap); needs a description model the price table lists", + ) p_desc.add_argument( "--suffix", default="", diff --git a/server/cli/code_maintenance.py b/server/cli/code_maintenance.py index 21f9e3aef49..958c05b122e 100644 --- a/server/cli/code_maintenance.py +++ b/server/cli/code_maintenance.py @@ -11,6 +11,7 @@ import pathlib import sys import time +from dataclasses import dataclass, field from typing import Any from server.cli._ch import OrgFree, connect_code_plane, connect_declared, reads, writes @@ -435,6 +436,73 @@ async def _answers_purge(args: argparse.Namespace) -> int: return 0 +@dataclass +class _DescribeRun: + """One `loom code describe` run: its bounds, what it did and what it spent.""" + + limit: int # most descriptions to start; 0 = no bound + max_usd: float # most dollars to spend; 0 = no cap + embed_model: str + started: int = 0 + finished: int = 0 + described: int = 0 + current: int = 0 + pending: int = 0 + tokens_in: int = 0 + tokens_out: int = 0 + embed_tokens: int = 0 + usd: float = 0.0 + dearest: float = 0.0 # the most one definition has cost: what a call in flight reserves + unpriced: set[str] = field(default_factory=set) + stopped: str = "" # the bound that refused a description + + def admit(self) -> bool: + """Count one more description as started, or name the bound that refuses it. No + await separates the check from the count, so concurrent calls cannot pass a bound + together.""" + if self.stopped: + return False + in_flight = self.started - self.finished + if self.limit and self.started >= self.limit: + self.stopped = f"--limit {self.limit}" + elif self.max_usd and self.unpriced: + self.stopped = f"--max-usd, no price for {', '.join(sorted(self.unpriced))}" + elif self.max_usd and self.usd + (in_flight + 1) * self.dearest > self.max_usd: + self.stopped = f"--max-usd {self.max_usd:g}" + else: + self.started += 1 + return True + return False + + def settle(self, spent: Any, described: bool) -> None: + """Count one finished description and the usage its provider calls reported.""" + from server.observability.cost_accumulator import is_priced + + self.finished += 1 + self.described += described + self.tokens_in += spent.llm_input_tokens + self.tokens_out += spent.llm_output_tokens + self.embed_tokens += spent.embed_tokens + self.usd += spent.cost_usd + self.dearest = max(self.dearest, spent.cost_usd) + models = set(spent.by_model) | ({self.embed_model} if spent.embed_tokens else set()) + self.unpriced |= {m for m in models if not is_priced(m)} + + def summary(self) -> str: + cost = ( + f"no price for {', '.join(sorted(self.unpriced))}" + if self.unpriced + else f"${self.usd:.4f}" + ) + return ( + f"describe complete: {self.described} described, {self.current} current, " + f"{self.pending - self.described} remaining" + + (f" (stopped at {self.stopped})" if self.stopped else "") + + f"; {self.tokens_in} input + {self.tokens_out} output tokens, " + f"{self.embed_tokens} embedding tokens, {cost}" + ) + + async def _describe(args: argparse.Namespace) -> int: """Generate contextual one-liners for chunks in the top PageRank files and re-embed them (context_text changes with the description). @@ -448,12 +516,20 @@ async def _describe(args: argparse.Namespace) -> int: from server.core.ch import get_client from server.embedding.embedder import get_embedder from server.llm.client import get_llm_client + from server.observability import cost_accumulator await connect_code_plane(get_client(), args) org, ns = _identity(args) repo = CodeRepo() embedder = get_embedder() llm = get_llm_client() + if args.max_usd and not cost_accumulator.is_priced(llm.model): + print( + f"--max-usd needs a price for the description model, and the price table " + f"has none for {llm.model!r}", + file=sys.stderr, + ) + return 2 ranked = await repo.top_summaries(org, ns, embedder.model_name, limit=100000) n_files = max(1, int(len(ranked) * args.top_pct / 100.0)) @@ -473,82 +549,101 @@ async def _describe(args: argparse.Namespace) -> int: ) sem = asyncio.Semaphore(max(1, args.concurrency)) - done = 0 - stop = False + run = _DescribeRun(args.limit, args.max_usd, embedder.model_name) + first_settled = asyncio.Event() + + async def _write(path: str, live: dict[str, Any], card: str) -> bool: + chunk = Chunk( + path=path, + scope=str(live.get("scope") or ""), + kind=str(live.get("kind")), + start_line=int(live.get("start_line") or 0), + end_line=int(live.get("end_line") or 0), + content=str(live.get("content") or ""), + ) + desc = await _describe_chunk(llm, chunk, card=card) + if not desc: + return False + # the ingest's own head lines (signature, calls, callers) stay + ctx = ( + with_description( + str(live.get("context_text") or ""), scope=chunk.scope, description=desc + ) + if live.get("context_text") + else build_context_text( + path=path, scope=chunk.scope, description=desc, content=chunk.content + ) + ) + try: + vec = await embedder.embed(ctx) + except Exception as e: # noqa: BLE001 — one chunk's embed failure skips that chunk + print(f" ! embed failed for {path}#{chunk.scope}: {e}", file=sys.stderr) + return False + row = CodeRepo.moved_of( + "code_chunks", + live, + context_description=desc, + context_source="llm", + context_text=ctx, + embedding=vec, + embedding_dim=len(vec), + ) + await repo.insert_rows("code_chunks", [row]) + return True async def _one(path: str, live: dict[str, Any], card: str) -> None: - nonlocal done, stop - if stop: - return async with sem: - chunk = Chunk( - path=path, - scope=str(live.get("scope") or ""), - kind=str(live.get("kind")), - start_line=int(live.get("start_line") or 0), - end_line=int(live.get("end_line") or 0), - content=str(live.get("content") or ""), - ) - desc = await _describe_chunk(llm, chunk, card=card) - if not desc: + if run.max_usd and run.started and not run.finished: + # the first description runs alone: its cost is what each later call reserves + await first_settled.wait() + if not run.admit(): return - # the ingest's own head lines (signature, calls, callers) stay - ctx = ( - with_description( - str(live.get("context_text") or ""), scope=chunk.scope, description=desc - ) - if live.get("context_text") - else build_context_text( - path=path, scope=chunk.scope, description=desc, content=chunk.content - ) - ) - try: - vec = await embedder.embed(ctx) - except Exception as e: # noqa: BLE001 — one chunk's embed failure skips that chunk - print(f" ! embed failed for {path}#{chunk.scope}: {e}", file=sys.stderr) - return - row = CodeRepo.moved_of( - "code_chunks", - live, - context_description=desc, - context_source="llm", - context_text=ctx, - embedding=vec, - embedding_dim=len(vec), - ) - await repo.insert_rows("code_chunks", [row]) - done += 1 - if done % 200 == 0: - print(f" {done} chunks described", flush=True) - if args.limit and done >= args.limit: - stop = True + described = False + # the provider clients report this definition's usage here + with cost_accumulator.isolated_op() as spent: + try: + described = await _write(path, live, card) + finally: + run.settle(spent, described) + first_settled.set() + if described and run.described % 200 == 0: + print(f" {run.described} chunks described", flush=True) # files are read and described several at a time: one file's reads are a # round trip each, so a serial walk of a large repository is read-bound files = asyncio.Semaphore(max(1, args.concurrency)) async def _file(path: str) -> None: - if stop: - return async with files: rows = await repo.live_chunks_for_path(org, ns, path, embedder.model_name) - pending = [ + wanted = [ r for r in rows - if str(r.get("context_source")) != "llm" - and str(r.get("kind")) in ("function", "class_skeleton") + if str(r.get("kind")) in ("function", "class_skeleton") # an embed-excluded path's chunk stays without a vector and not unembedded_by_design(r.get("embed_last_error")) ] - if not pending: + pending = [r for r in wanted if str(r.get("context_source")) != "llm"] + run.current += len(wanted) - len(pending) + run.pending += len(pending) + # a stopped run still reads every file: the summary counts what is left + if not pending or run.stopped: return card = await _card_for(repo, org, ns, embedder.model_name, path, True) await asyncio.gather(*(_one(path, r, card) for r in pending)) await asyncio.gather(*(_file(p) for p in target_paths)) - print(f"describe complete: {done} chunks") - await _compact_after_bulk(done, embedder.model_name) - _note(described=done, files=len(target_paths)) + print(run.summary()) + await _compact_after_bulk(run.described, embedder.model_name) + _note( + described=run.described, + current=run.current, + remaining=run.pending - run.described, + files=len(target_paths), + input_tokens=run.tokens_in, + output_tokens=run.tokens_out, + cost_usd=run.usd, + ) return 0 diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index 46a61f1879d..ca5ba4c0c73 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -55,8 +55,8 @@ "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE --days DAYS --limit LIMIT --dry-run" ], "loom code describe": [ - "usage: loom code describe [-h] [--org ORG] [--namespace NAMESPACE] [--top-pct TOP_PCT] [--limit LIMIT] [--suffix SUFFIX] [--concurrency CONCURRENCY]", - "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE --top-pct TOP_PCT --limit LIMIT max chunks (0 = all in pct) --suffix SUFFIX only files with this suffix (e.g. .cpp — implementation files move conceptual retrieval; headers dominate PageRank) --concurrency CONCURRENCY" + "usage: loom code describe [-h] [--org ORG] [--namespace NAMESPACE] [--top-pct TOP_PCT] [--limit LIMIT] [--max-usd MAX_USD] [--suffix SUFFIX] [--concurrency CONCURRENCY]", + "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE --top-pct TOP_PCT --limit LIMIT most chunks this run describes (0 = all in pct); a rerun skips described chunks --max-usd MAX_USD stop before a description that would take this run's provider spend past this many dollars (0 = no cap); needs a description model the price table lists --suffix SUFFIX only files with this suffix (e.g. .cpp — implementation files move conceptual retrieval; headers dominate PageRank) --concurrency CONCURRENCY" ], "loom code answers-purge": [ "usage: loom code answers-purge [-h] [--llm-model LLM_MODEL] [--all] [--apply | --dry-run] [--org ORG] [--namespace NAMESPACE]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 6b9a8bf04f0..2f26b3da870 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -1625,6 +1625,7 @@ "namespace", "top_pct", "limit", + "max_usd", "suffix", "concurrency" ] @@ -1705,7 +1706,22 @@ "nargs": null, "type": "builtins:int", "required": false, - "help": "max chunks (0 = all in pct)", + "help": "most chunks this run describes (0 = all in pct); a rerun skips described chunks", + "metavar": null + }, + { + "option_strings": [ + "--max-usd" + ], + "dest": "max_usd", + "action": "_StoreAction", + "default": 0.0, + "const": null, + "choices": null, + "nargs": null, + "type": "builtins:float", + "required": false, + "help": "stop before a description that would take this run's provider spend past this many dollars (0 = no cap); needs a description model the price table lists", "metavar": null }, { diff --git a/tests/unit/test_code_describe_bounds.py b/tests/unit/test_code_describe_bounds.py new file mode 100644 index 00000000000..08c95f59408 --- /dev/null +++ b/tests/unit/test_code_describe_bounds.py @@ -0,0 +1,221 @@ +"""`loom code describe` stops at `--limit` and `--max-usd` and prints what the run spent.""" + +from __future__ import annotations + +import argparse +import asyncio +import unittest +from contextlib import redirect_stderr, redirect_stdout +from io import StringIO +from typing import Any +from unittest.mock import AsyncMock, Mock, patch + +from server.cli import code_maintenance +from server.code.app.index import describe +from server.llm.client import LLMResult +from server.observability import cost_accumulator + +_LLM, _EMBEDDER = "priced-llm", "priced-embedder" +_PRICES = {_LLM: (0.001, 0.002), _EMBEDDER: (0.0005, 0.0)} +_IN, _OUT, _EMBED = 1000, 50, 200 +# one definition: its description call and the re-embedding of its context text +_EACH_USD = _IN / 1000 * 0.001 + _OUT / 1000 * 0.002 + _EMBED / 1000 * 0.0005 +_FILES, _PER_FILE = 3, 10 + + +class _Index: + """The chunk rows of a few files, rewritten in place the way the table's newest version reads.""" + + def __init__(self) -> None: + self.rows = { + f"pkg/f{i}.py": [ + { + "path": f"pkg/f{i}.py", + "scope": f"fn{j}", + "kind": "function", + "start_line": j, + "end_line": j, + "content": f"def fn{j}(): return {j}", + "context_text": "", + "context_source": "structural", + "embed_last_error": "", + } + for j in range(_PER_FILE) + ] + for i in range(_FILES) + } + + async def top_summaries(self, *_: Any, **__: Any) -> list[dict[str, Any]]: + return [{"scope_path": path} for path in self.rows] + + async def live_chunks_for_path(self, _o: str, _n: str, path: str, _m: str) -> list[Any]: + return list(self.rows[path]) + + async def insert_rows(self, _table: str, rows: list[dict[str, Any]]) -> None: + for row in rows: + self.rows[row["path"]] = [ + row if live["scope"] == row["scope"] else live for live in self.rows[row["path"]] + ] + + @staticmethod + def moved_of(_table: str, live: dict[str, Any], **updates: Any) -> dict[str, Any]: + return {**live, **updates} + + +class _Provider: + """A description model that counts its calls and reports usage as a provider client does.""" + + provider = "primary" + + def __init__(self, model: str = _LLM, served: str = "primary") -> None: + self.model, self.served = model, served + self.calls = self.in_flight = self.most_in_flight = 0 + + async def complete(self, _system: str, _user: str, max_tokens: int = 1024) -> LLMResult: + self.calls += 1 + self.in_flight += 1 + self.most_in_flight = max(self.most_in_flight, self.in_flight) + await asyncio.sleep(0) # let the other definitions in flight reach their own call + self.in_flight -= 1 + cost_accumulator.report_llm(self.model, _IN, _OUT) + return LLMResult("Returns a number.", _IN, _OUT, self.served, self.model) + + +class _Embedder: + def __init__(self, model_name: str = _EMBEDDER) -> None: + self.model_name = model_name + + async def embed(self, _text: str) -> list[float]: + cost_accumulator.report_embed(self.model_name, _EMBED) + return [0.0] + + +class DescribeBoundsTest(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.index = _Index() + + async def _run( + self, + provider: _Provider, + *, + limit: int = 0, + max_usd: float = 0.0, + embedder: str = _EMBEDDER, + ) -> tuple[int, str, str]: + args = argparse.Namespace( + top_pct=100.0, suffix="", concurrency=8, limit=limit, max_usd=max_usd + ) + out, err = StringIO(), StringIO() + with ( + patch.dict(cost_accumulator.PRICE_PER_1K_TOKENS, _PRICES), + patch.object(code_maintenance, "connect_code_plane", new_callable=AsyncMock), + patch.object(code_maintenance, "_identity", return_value=("example-org", "example-ns")), + patch.object(code_maintenance, "_compact_after_bulk", new_callable=AsyncMock), + patch.object(code_maintenance, "_note", new_callable=Mock), + patch( + "server.code.store.index.CodeRepo", + Mock(return_value=self.index, moved_of=_Index.moved_of), + ), + patch("server.core.ch.get_client", return_value=object()), + patch("server.embedding.embedder.get_embedder", return_value=_Embedder(embedder)), + patch("server.llm.client.get_llm_client", return_value=provider), + patch.object(describe, "_card_for", new_callable=AsyncMock, return_value=""), + redirect_stdout(out), + redirect_stderr(err), + ): + code = await code_maintenance._describe(args) + return code, out.getvalue().splitlines()[-1] if out.getvalue() else "", err.getvalue() + + def _described(self) -> int: + return sum( + row["context_source"] == "llm" for rows in self.index.rows.values() for row in rows + ) + + async def test_limit_holds_across_files_and_concurrent_calls(self) -> None: + # 12 is past the first file's 10 definitions and not a multiple of the concurrency + provider = _Provider() + code, summary, _ = await self._run(provider, limit=12) + self.assertEqual(code, 0) + self.assertEqual(provider.calls, 12) + self.assertGreater(provider.most_in_flight, 1) + self.assertEqual(self._described(), 12) + self.assertEqual( + summary, + "describe complete: 12 described, 0 current, 18 remaining (stopped at --limit 12); " + f"{12 * _IN} input + {12 * _OUT} output tokens, {12 * _EMBED} embedding tokens, " + f"${12 * _EACH_USD:.4f}", + ) + + async def test_limit_counts_a_call_that_stored_no_description(self) -> None: + # a reply the fallback's fake client served is dropped, and its call was still made + provider = _Provider(served="fake") + _, summary, _ = await self._run(provider, limit=4) + self.assertEqual(provider.calls, 4) + self.assertEqual(self._described(), 0) + self.assertIn("0 described, 0 current, 30 remaining (stopped at --limit 4)", summary) + self.assertIn(f"{4 * _IN} input + {4 * _OUT} output tokens, 0 embedding tokens", summary) + + async def test_summary_equals_the_usage_the_provider_counted(self) -> None: + provider = _Provider() + _, summary, _ = await self._run(provider) + total = _FILES * _PER_FILE + self.assertEqual(provider.calls, total) + self.assertEqual( + summary, + f"describe complete: {total} described, 0 current, 0 remaining; " + f"{total * _IN} input + {total * _OUT} output tokens, " + f"{total * _EMBED} embedding tokens, ${total * _EACH_USD:.4f}", + ) + + async def test_max_usd_stops_before_the_call_that_would_pass_it(self) -> None: + provider = _Provider() + _, summary, _ = await self._run(provider, max_usd=4.5 * _EACH_USD) + self.assertEqual(provider.calls, 4) + self.assertEqual(self._described(), 4) + self.assertIn( + f"4 described, 0 current, 26 remaining (stopped at --max-usd {4.5 * _EACH_USD:g})", + summary, + ) + self.assertTrue(summary.endswith(f"${4 * _EACH_USD:.4f}")) + + async def test_max_usd_refuses_a_model_without_a_price(self) -> None: + provider = _Provider(model="unlisted-llm") + code, summary, err = await self._run(provider, max_usd=1.0) + self.assertEqual(code, 2) + self.assertEqual((provider.calls, summary), (0, "")) + self.assertIn("--max-usd needs a price for the description model", err) + + async def test_max_usd_stops_once_a_call_reports_a_model_without_a_price(self) -> None: + provider = _Provider() + _, summary, _ = await self._run(provider, max_usd=1.0, embedder="unlisted-embedder") + self.assertEqual(provider.calls, 1) + self.assertIn("(stopped at --max-usd, no price for unlisted-embedder)", summary) + self.assertTrue(summary.endswith("embedding tokens, no price for unlisted-embedder")) + + async def test_a_model_without_a_price_prints_tokens_only(self) -> None: + provider = _Provider(model="unlisted-llm") + _, summary, _ = await self._run(provider, limit=2) + self.assertTrue( + summary.endswith( + f"{2 * _IN} input + {2 * _OUT} output tokens, {2 * _EMBED} embedding tokens, " + "no price for unlisted-llm" + ) + ) + + async def test_a_rerun_describes_nothing(self) -> None: + await self._run(_Provider()) + provider = _Provider() + _, summary, _ = await self._run(provider) + self.assertEqual(provider.calls, 0) + self.assertEqual( + summary, + "describe complete: 0 described, 30 current, 0 remaining; " + "0 input + 0 output tokens, 0 embedding tokens, $0.0000", + ) + + async def test_a_rerun_after_a_limit_describes_only_what_is_left(self) -> None: + await self._run(_Provider(), limit=12) + provider = _Provider() + _, summary, _ = await self._run(provider) + self.assertEqual(provider.calls, 18) + self.assertIn("18 described, 12 current, 0 remaining;", summary) diff --git a/tests/unit/test_code_description_provider_guard.py b/tests/unit/test_code_description_provider_guard.py index ca754aa6e27..72a56596ba0 100644 --- a/tests/unit/test_code_description_provider_guard.py +++ b/tests/unit/test_code_description_provider_guard.py @@ -123,7 +123,9 @@ async def test_cli_rejects_fake_descriptions_before_embedding_or_insert(self) -> ), insert_rows=AsyncMock(), ) - args = argparse.Namespace(top_pct=100, suffix="", concurrency=1, limit=0) + args = argparse.Namespace( + top_pct=100, suffix="", concurrency=1, limit=0, max_usd=0.0 + ) with ( patch.object(code_maintenance, "connect_code_plane", new_callable=AsyncMock), patch.object( diff --git a/tests/unit/test_code_embed_exclude.py b/tests/unit/test_code_embed_exclude.py index d4ed6a92455..194c09da272 100644 --- a/tests/unit/test_code_embed_exclude.py +++ b/tests/unit/test_code_embed_exclude.py @@ -264,7 +264,7 @@ async def nothing(*_: Any, **__: Any) -> Any: monkeypatch.setattr("server.llm.client.get_llm_client", _LLM) monkeypatch.setattr("server.code.app.index.describe._describe_chunk", describe_chunk) monkeypatch.setattr("server.code.app.index.describe._card_for", nothing) - args = SimpleNamespace(top_pct=100.0, suffix="", concurrency=2, limit=0) + args = SimpleNamespace(top_pct=100.0, suffix="", concurrency=2, limit=0, max_usd=0.0) assert asyncio.run(cm._describe(args)) == 0 # type: ignore[arg-type] assert described == ["pkg/x.py"] assert [r["path"] for r in written] == ["pkg/x.py"] From a232dd98533708ca5d8256b66ee7f17dc4e11ed3 Mon Sep 17 00:00:00 2001 From: Lareb Zafar Date: Mon, 30 Nov 2026 19:10:01 +0530 Subject: [PATCH 2/2] `loom code describe --max-usd` runs one description at a time until one reports a cost The cap reserves the cost of the dearest description so far for each call in flight. That cost is 0 until a description reports usage, and the serial wait ended at the first settle whether or not it reported any: after a first call that failed, every waiting call was admitted against a reservation of 0. With concurrency 8 and a cap of 2.5 descriptions' price, 9 calls were made and 8 paid for. The wait now holds while a call is in flight and no description has a cost, so the same run makes 3 calls and pays for 2. Also: - the operator page states the overshoot as one difference for each dearer call in flight, and that an embedding provider reporting no usage makes the dollars a lower bound; - an unlisted embedding model of a provider that reports usage is refused before the first call, not after one paid description; - `--limit` and `--max-usd` refuse values below 0; - `settle` takes the accumulator by its type. Co-Authored-By: Claude Fable 5.2 Signed-off-by: Lareb Zafar --- docs/operations/code-index-operations.md | 10 +++- server/cli/code.py | 23 ++++++- server/cli/code_maintenance.py | 46 ++++++++++---- tests/unit/snapshots/cli_help.json | 2 +- tests/unit/snapshots/cli_tree.json | 6 +- tests/unit/test_code_describe_bounds.py | 76 ++++++++++++++++++++---- 6 files changed, 133 insertions(+), 30 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 03bb4455ea2..7b960d83744 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -330,9 +330,13 @@ Then: the most central chunks. `--limit N` starts at most N description calls. `--max-usd D` stops before a call that would take the run's spend past D dollars: it counts each call in flight, and the next one, at the cost of the dearest description so far, and - runs the first description alone to learn that cost. Only a description that costs - more than every earlier one can take the run past D, by that difference. It refuses a - description model the server's price table does not list. The last line counts the + runs one description at a time until one has reported a cost. A call that costs more + than every description before it can take the run past D, by that difference for each + such call in flight. It refuses a description model the server's price table does not + list, and an unlisted embedding model whose provider reports usage (OpenAI, Bedrock). + An embedding provider that reports no usage (Gemini, an OpenAI-compatible endpoint) + counts as 0 embedding tokens: the dollars are then a lower bound, and `--max-usd` + caps the description calls only. The last line counts the chunks described, already described and remaining in the selected files, the tokens the provider calls reported and their price from the price table (tokens only for a model the table does not list): diff --git a/server/cli/code.py b/server/cli/code.py index 0a8ba3992d7..bb9f1cdaacc 100644 --- a/server/cli/code.py +++ b/server/cli/code.py @@ -243,6 +243,22 @@ def _add_pr_history_parsers(csub: argparse._SubParsersAction[argparse.ArgumentPa p_rp.set_defaults(func=_cmd_repack) +def _count(text: str) -> int: + """An argparse type: an integer, 0 or more.""" + value = int(text) + if value < 0: + raise argparse.ArgumentTypeError("must be 0 or more") + return value + + +def _dollars(text: str) -> float: + """An argparse type: a dollar amount, 0 or more.""" + value = float(text) + if not value >= 0: # a NaN compares false and is refused with the negatives + raise argparse.ArgumentTypeError("must be 0 or more") + return value + + def _add_describe_parser(csub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: """`loom code describe`: LLM one-liners for the top-PageRank chunks.""" p_desc = csub.add_parser("describe", help="LLM contextual one-liners for top-PageRank chunks.") @@ -250,16 +266,17 @@ def _add_describe_parser(csub: argparse._SubParsersAction[argparse.ArgumentParse p_desc.add_argument("--top-pct", type=float, default=20.0) p_desc.add_argument( "--limit", - type=int, + type=_count, default=0, help="most chunks this run describes (0 = all in pct); a rerun skips described chunks", ) p_desc.add_argument( "--max-usd", - type=float, + type=_dollars, default=0.0, help="stop before a description that would take this run's provider spend past " - "this many dollars (0 = no cap); needs a description model the price table lists", + "this many dollars (0 = no cap); needs a price for the description model and for an " + "embedding model that reports usage", ) p_desc.add_argument( "--suffix", diff --git a/server/cli/code_maintenance.py b/server/cli/code_maintenance.py index 958c05b122e..3ac61cc97b7 100644 --- a/server/cli/code_maintenance.py +++ b/server/cli/code_maintenance.py @@ -12,11 +12,14 @@ import sys import time from dataclasses import dataclass, field -from typing import Any +from typing import TYPE_CHECKING, Any from server.cli._ch import OrgFree, connect_code_plane, connect_declared, reads, writes from server.cli.code_run import _identity, _note, _repo_cfg +if TYPE_CHECKING: + from server.observability.cost_accumulator import _Accumulator + log = logging.getLogger("loom.cli.code") @@ -456,6 +459,11 @@ class _DescribeRun: unpriced: set[str] = field(default_factory=set) stopped: str = "" # the bound that refused a description + def unpriced_in_flight(self) -> bool: + """A capped run has a call in flight and no description has reported a cost yet: + the next call would reserve nothing.""" + return bool(self.max_usd) and not self.dearest and self.started > self.finished + def admit(self) -> bool: """Count one more description as started, or name the bound that refuses it. No await separates the check from the count, so concurrent calls cannot pass a bound @@ -474,7 +482,7 @@ def admit(self) -> bool: return True return False - def settle(self, spent: Any, described: bool) -> None: + def settle(self, spent: _Accumulator, described: bool) -> None: """Count one finished description and the usage its provider calls reported.""" from server.observability.cost_accumulator import is_priced @@ -503,6 +511,22 @@ def summary(self) -> str: ) +# The embedding providers whose clients report the tokens they billed. An unpriced model +# of any other provider stops a capped run when its first call reports usage. +_USAGE_REPORTING_EMBEDDERS = ("openai", "bedrock") + + +def _unpriced_under_cap(llm_model: str, embed_model: str) -> list[str]: + """The models a `--max-usd` run would pay for that the price table does not list.""" + from server.embedding.embedder import provider_for + from server.observability.cost_accumulator import is_priced + + capped = [llm_model] + if provider_for(embed_model) in _USAGE_REPORTING_EMBEDDERS: + capped.append(embed_model) + return [model for model in capped if not is_priced(model)] + + async def _describe(args: argparse.Namespace) -> int: """Generate contextual one-liners for chunks in the top PageRank files and re-embed them (context_text changes with the description). @@ -523,10 +547,11 @@ async def _describe(args: argparse.Namespace) -> int: repo = CodeRepo() embedder = get_embedder() llm = get_llm_client() - if args.max_usd and not cost_accumulator.is_priced(llm.model): + unpriced = _unpriced_under_cap(llm.model, embedder.model_name) if args.max_usd else [] + if unpriced: print( - f"--max-usd needs a price for the description model, and the price table " - f"has none for {llm.model!r}", + f"--max-usd needs a price for each model it caps, and the price table has " + f"none for {', '.join(unpriced)}", file=sys.stderr, ) return 2 @@ -550,7 +575,7 @@ async def _describe(args: argparse.Namespace) -> int: sem = asyncio.Semaphore(max(1, args.concurrency)) run = _DescribeRun(args.limit, args.max_usd, embedder.model_name) - first_settled = asyncio.Event() + settled = asyncio.Event() async def _write(path: str, live: dict[str, Any], card: str) -> bool: chunk = Chunk( @@ -593,9 +618,10 @@ async def _write(path: str, live: dict[str, Any], card: str) -> bool: async def _one(path: str, live: dict[str, Any], card: str) -> None: async with sem: - if run.max_usd and run.started and not run.finished: - # the first description runs alone: its cost is what each later call reserves - await first_settled.wait() + while run.unpriced_in_flight(): + # one description at a time until one has a cost for the later calls to reserve + settled.clear() + await settled.wait() if not run.admit(): return described = False @@ -605,7 +631,7 @@ async def _one(path: str, live: dict[str, Any], card: str) -> None: described = await _write(path, live, card) finally: run.settle(spent, described) - first_settled.set() + settled.set() if described and run.described % 200 == 0: print(f" {run.described} chunks described", flush=True) diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index ca5ba4c0c73..bca5240a6c9 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -56,7 +56,7 @@ ], "loom code describe": [ "usage: loom code describe [-h] [--org ORG] [--namespace NAMESPACE] [--top-pct TOP_PCT] [--limit LIMIT] [--max-usd MAX_USD] [--suffix SUFFIX] [--concurrency CONCURRENCY]", - "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE --top-pct TOP_PCT --limit LIMIT most chunks this run describes (0 = all in pct); a rerun skips described chunks --max-usd MAX_USD stop before a description that would take this run's provider spend past this many dollars (0 = no cap); needs a description model the price table lists --suffix SUFFIX only files with this suffix (e.g. .cpp — implementation files move conceptual retrieval; headers dominate PageRank) --concurrency CONCURRENCY" + "options: -h, --help show this help message and exit --org ORG default: LOOM_CODE_ORG --namespace NAMESPACE default: LOOM_CODE_NAMESPACE --top-pct TOP_PCT --limit LIMIT most chunks this run describes (0 = all in pct); a rerun skips described chunks --max-usd MAX_USD stop before a description that would take this run's provider spend past this many dollars (0 = no cap); needs a price for the description model and for an embedding model that reports usage --suffix SUFFIX only files with this suffix (e.g. .cpp — implementation files move conceptual retrieval; headers dominate PageRank) --concurrency CONCURRENCY" ], "loom code answers-purge": [ "usage: loom code answers-purge [-h] [--llm-model LLM_MODEL] [--all] [--apply | --dry-run] [--org ORG] [--namespace NAMESPACE]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 2f26b3da870..193c44ca191 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -1704,7 +1704,7 @@ "const": null, "choices": null, "nargs": null, - "type": "builtins:int", + "type": "server.cli.code:_count", "required": false, "help": "most chunks this run describes (0 = all in pct); a rerun skips described chunks", "metavar": null @@ -1719,9 +1719,9 @@ "const": null, "choices": null, "nargs": null, - "type": "builtins:float", + "type": "server.cli.code:_dollars", "required": false, - "help": "stop before a description that would take this run's provider spend past this many dollars (0 = no cap); needs a description model the price table lists", + "help": "stop before a description that would take this run's provider spend past this many dollars (0 = no cap); needs a price for the description model and for an embedding model that reports usage", "metavar": null }, { diff --git a/tests/unit/test_code_describe_bounds.py b/tests/unit/test_code_describe_bounds.py index 08c95f59408..32959fd60ed 100644 --- a/tests/unit/test_code_describe_bounds.py +++ b/tests/unit/test_code_describe_bounds.py @@ -10,7 +10,7 @@ from typing import Any from unittest.mock import AsyncMock, Mock, patch -from server.cli import code_maintenance +from server.cli import code, code_maintenance from server.code.app.index import describe from server.llm.client import LLMResult from server.observability import cost_accumulator @@ -67,18 +67,26 @@ class _Provider: provider = "primary" - def __init__(self, model: str = _LLM, served: str = "primary") -> None: + def __init__( + self, model: str = _LLM, served: str = "primary", *, fails: int = 0, later_in: int = _IN + ) -> None: self.model, self.served = model, served + self.fails = fails # the first calls that raise and report nothing + self.later_in = later_in # the input tokens of every call after the first self.calls = self.in_flight = self.most_in_flight = 0 async def complete(self, _system: str, _user: str, max_tokens: int = 1024) -> LLMResult: self.calls += 1 + nth = self.calls self.in_flight += 1 self.most_in_flight = max(self.most_in_flight, self.in_flight) await asyncio.sleep(0) # let the other definitions in flight reach their own call self.in_flight -= 1 - cost_accumulator.report_llm(self.model, _IN, _OUT) - return LLMResult("Returns a number.", _IN, _OUT, self.served, self.model) + if nth <= self.fails: + raise RuntimeError("provider unavailable") + tokens_in = _IN if nth == 1 else self.later_in + cost_accumulator.report_llm(self.model, tokens_in, _OUT) + return LLMResult("Returns a number.", tokens_in, _OUT, self.served, self.model) class _Embedder: @@ -101,6 +109,7 @@ async def _run( limit: int = 0, max_usd: float = 0.0, embedder: str = _EMBEDDER, + embed_provider: str = "openai", ) -> tuple[int, str, str]: args = argparse.Namespace( top_pct=100.0, suffix="", concurrency=8, limit=limit, max_usd=max_usd @@ -118,6 +127,7 @@ async def _run( ), patch("server.core.ch.get_client", return_value=object()), patch("server.embedding.embedder.get_embedder", return_value=_Embedder(embedder)), + patch("server.embedding.embedder.provider_for", return_value=embed_provider), patch("server.llm.client.get_llm_client", return_value=provider), patch.object(describe, "_card_for", new_callable=AsyncMock, return_value=""), redirect_stdout(out), @@ -178,16 +188,49 @@ async def test_max_usd_stops_before_the_call_that_would_pass_it(self) -> None: ) self.assertTrue(summary.endswith(f"${4 * _EACH_USD:.4f}")) + async def test_max_usd_stays_serial_until_a_description_has_a_cost(self) -> None: + # the first call fails and reports nothing, so the calls after it have no cost to reserve + provider = _Provider(fails=1) + _, summary, _ = await self._run(provider, max_usd=2.5 * _EACH_USD) + self.assertEqual((provider.calls, provider.most_in_flight), (3, 1)) + self.assertEqual(self._described(), 2) + self.assertTrue(summary.endswith(f"${2 * _EACH_USD:.4f}")) + + async def test_max_usd_overshoot_is_one_difference_for_each_call_in_flight(self) -> None: + # 3 calls fit under the cap at the first description's cost, and each then costs more + dear_in = 3 * _IN + dear_usd = _EACH_USD + (dear_in - _IN) / 1000 * _PRICES[_LLM][0] + provider = _Provider(later_in=dear_in) + cap = 4.5 * _EACH_USD + _, summary, _ = await self._run(provider, max_usd=cap) + self.assertEqual((provider.calls, provider.most_in_flight), (4, 3)) + spent = _EACH_USD + 3 * dear_usd + self.assertTrue(summary.endswith(f"${spent:.4f}")) + self.assertGreater(spent, cap) + self.assertLessEqual(spent - cap, 3 * (dear_usd - _EACH_USD)) + async def test_max_usd_refuses_a_model_without_a_price(self) -> None: - provider = _Provider(model="unlisted-llm") - code, summary, err = await self._run(provider, max_usd=1.0) - self.assertEqual(code, 2) - self.assertEqual((provider.calls, summary), (0, "")) - self.assertIn("--max-usd needs a price for the description model", err) + for llm, embedder, named in ( + ("unlisted-llm", _EMBEDDER, "unlisted-llm"), + (_LLM, "unlisted-embedder", "unlisted-embedder"), + ): + with self.subTest(named): + provider = _Provider(model=llm) + code, summary, err = await self._run(provider, max_usd=1.0, embedder=embedder) + self.assertEqual(code, 2) + self.assertEqual((provider.calls, summary), (0, "")) + self.assertIn( + "--max-usd needs a price for each model it caps, and the price table " + f"has none for {named}\n", + err, + ) async def test_max_usd_stops_once_a_call_reports_a_model_without_a_price(self) -> None: + # an embedding provider not known to report usage, whose call reports it all the same provider = _Provider() - _, summary, _ = await self._run(provider, max_usd=1.0, embedder="unlisted-embedder") + _, summary, _ = await self._run( + provider, max_usd=1.0, embedder="unlisted-embedder", embed_provider="compatible" + ) self.assertEqual(provider.calls, 1) self.assertIn("(stopped at --max-usd, no price for unlisted-embedder)", summary) self.assertTrue(summary.endswith("embedding tokens, no price for unlisted-embedder")) @@ -219,3 +262,16 @@ async def test_a_rerun_after_a_limit_describes_only_what_is_left(self) -> None: _, summary, _ = await self._run(provider) self.assertEqual(provider.calls, 18) self.assertIn("18 described, 12 current, 0 remaining;", summary) + + +class DescribeFlagsTest(unittest.TestCase): + def test_a_bound_below_zero_is_refused(self) -> None: + parser = argparse.ArgumentParser() + code._add_describe_parser(parser.add_subparsers()) + for flag in ("--limit", "--max-usd"): + err = StringIO() + with self.subTest(flag), self.assertRaises(SystemExit), redirect_stderr(err): + parser.parse_args(["describe", flag, "-1"]) + self.assertIn(f"argument {flag}: must be 0 or more", err.getvalue()) + args = parser.parse_args(["describe", "--limit", "3", "--max-usd", "0.5"]) + self.assertEqual((args.limit, args.max_usd), (3, 0.5))