Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion docs/operations/code-index-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -327,7 +327,22 @@ 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 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):
`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.

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
31 changes: 30 additions & 1 deletion server/cli/code.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,41 @@ 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.")
_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=_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=_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 price for the description model and for an "
"embedding model that reports usage",
)
p_desc.add_argument(
"--suffix",
default="",
Expand Down
231 changes: 176 additions & 55 deletions server/cli/code_maintenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,15 @@
import pathlib
import sys
import time
from typing import Any
from dataclasses import dataclass, field
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")


Expand Down Expand Up @@ -435,6 +439,94 @@ 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 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
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: _Accumulator, 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}"
)


# 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).
Expand All @@ -448,12 +540,21 @@ 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()
unpriced = _unpriced_under_cap(llm.model, embedder.model_name) if args.max_usd else []
if unpriced:
print(
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

ranked = await repo.top_summaries(org, ns, embedder.model_name, limit=100000)
n_files = max(1, int(len(ranked) * args.top_pct / 100.0))
Expand All @@ -473,82 +574,102 @@ 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)
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:
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)
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
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)
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


Expand Down
4 changes: 2 additions & 2 deletions tests/unit/snapshots/cli_help.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 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]",
Expand Down
Loading
Loading