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
261 changes: 248 additions & 13 deletions src/codexray/judge/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,267 @@

Spec: spec.md §8.

Writes the prose for findings the report will show (job B) and one-line module
descriptions (job C), and simulates fixes on a copy of the map. The AI never detects,
counts or ranks, and the report must stay complete with zero AI calls: every finding
type has a template sentence built from facts alone (spec.md §8.7).
Writes checked AI text for the findings the report shows (job B) and two-sentence module
descriptions (job C), and simulates fixes on a copy of the module matrix. The AI never
detects, counts or ranks, and the report stays complete with zero AI calls: a finding
whose answers all fail their checks keeps its template judgement.

Reads: candidate_findings, nodes, edges; code slices by blob_sha.
Writes: judgements/ (one cached response per cache key), usage.json,
Reads: candidate_findings and decisions.yaml (through the report's own ranking), nodes,
edges, links, definitions, commits, file_changes; code by blob_sha from the clone
in repos/<repo_id>.
Writes: judgements/findings/*.json (one Judgement per judged finding),
judgements/simulations.json, judgements/descriptions.json, judgements/cache/
(one gateway answer file per cache key), judgements/calls.json (this run's calls,
cache hits included),
usage.json (every call that reached the gateway, kept across runs) and
simulation_batch.json.
Settings: settings/judge.yaml.
AI: jobs B and C through the gateway. The key comes from the environment only.

Every response goes through the checks in spec.md §8.4 before any of it is stored.
Records: core.contracts.Judgement, Simulation, BatchSimulation, UsageEntry.

Starting point: probes/gateway_check.py.
Run it from the folder that holds `repos/`, like `codexray report`.
"""

from __future__ import annotations

import hashlib
import itertools
import json
import shutil
import threading
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from datetime import date
from typing import Any

from codexray.core.errors import NotBuiltYet
from codexray.core.runs import RunPaths

LANE = "judge"
SPEC = "§8"


def run(run: RunPaths, settings: dict[str, Any]) -> None:
"""Entry point called by the command line. Safe to re-run."""
raise NotBuiltYet(LANE, SPEC, "AI text for shown findings, and fix simulation")
"""Entry point called by the command line. Safe to re-run; answers come from the cache."""
from codexray.analyze.findings import _months_before
from codexray.core import contracts, db
from codexray.core.errors import CodeXrayError
from codexray.core.runs import write_json
from codexray.decisions import registry
from codexray.judge.client import Gateway
from codexray.judge.jobs import (
describe_module,
exceptions_checker,
judge_finding,
simulate,
)
from codexray.judge.packet import Sources, build_packet
from codexray.judge.simulation import simulate_batch
from codexray.model.rollup import file_links, load_tree, roll_up
from codexray.report import assemble
from codexray.repository import CLONES_DIR

judge = settings["judge"]
if not run.manifest.is_file() or not run.decisions.is_file():
raise CodeXrayError("this run has not been analysed yet; run `codexray analyze` first")
manifest = contracts.Manifest.model_validate(json.loads(run.manifest.read_text("utf-8")))
if "model" not in manifest.coverage:
raise CodeXrayError("this run has no map yet; run `codexray model` first")
clone_dir = CLONES_DIR / run.repo_id
if not clone_dir.is_dir():
raise CodeXrayError(
f"the clone {clone_dir} is missing; run `codexray judge` from the folder that "
"holds repos/"
)
decisions = registry.load_decisions(run.decisions)
by_id = {d.id: d for d in decisions}

con = db.connect(run.db, read_only=True)
try:
repo = manifest.repo
end = next((s for s in assemble.snapshots(con, repo) if s.role == "end"), None)
if end is None:
raise CodeXrayError(f"the run has no END snapshot for {repo}")
tree = load_tree(con, repo, end.sha)
findings, _ = assemble.assemble(con, manifest, settings, by_id, tree, end, {})
files = file_links(con, repo, end.sha)
modules = roll_up(tree, files, "module")

def module_of(node_id: str) -> str | None:
if node_id not in tree.level:
return None
lifted = tree.lift(node_id, "module")
return lifted if tree.level.get(lifted) == "module" else None

sources = Sources(con, repo, end.sha, end.date, clone_dir, tree, modules)
calls_dir = run.judgements / "calls"
shutil.rmtree(calls_dir, ignore_errors=True)
local = threading.local()
numbers = itertools.count()
lock = threading.Lock()

def gateway() -> Gateway:
"""One client per worker thread, each with its own ledger file."""
if not hasattr(local, "gateway"):
with lock:
index = next(numbers)
local.gateway = Gateway(
judge, run.judgements / "cache", calls_dir / f"{index}.json"
)
return local.gateway

judged_types = set(judge["job_b"]["types"])
chosen = [f for f in findings if f.type in judged_types][
: int(judge["job_b"]["max_findings"])
]
# Packets are built in order on the one database connection; only the calls run in
# parallel. A finding's votes stay in one worker, so no two workers share a cache file.
work = []
for finding in chosen:
template = finding.judgement or contracts.Judgement.model_validate(
{"finding_id": finding.id}
)
packet, text = build_packet(
finding, by_id.get(finding.decision_id or ""), sources, judge["packet"]
)
work.append((finding, template, packet, text))
workers = int(judge["workers"])
with ThreadPoolExecutor(max_workers=workers) as pool:
results = list(
pool.map(lambda w: judge_finding(gateway(), w[2], w[3], w[0], w[1], judge)[0], work)
)
judgements = {w[0].id: judgement for w, judgement in zip(work, results, strict=True)}
passed = sum(j.status == "ai" for j in judgements.values())

# Simulations: every finding's shown fix, then every cheap-loop move together.
exceptions_of = exceptions_checker(decisions)
simulations: dict[str, Any] = {}
moves = []
for finding in findings:
shown = judgements.get(finding.id) or finding.judgement
if shown is None:
continue
simulation, move = simulate(
finding, shown.fix, modules, files, module_of, exceptions_of
)
simulations[finding.id] = contracts.to_plain(simulation)
if move is not None and finding.type == "cheap_loop":
if simulation.target_link_removed and not simulation.new_exceptions:
moves.append(move)
batch = simulate_batch(modules, moves, exceptions_of) if moves else None

# Job C: one description per module.
window_start = _months_before(
date.fromisoformat(end.date), int(judge["job_c"]["window_months"])
)
module_facts = [
_module_facts(
con, repo, end.sha, module, tree, modules, window_start, end.date, judge["job_c"]
)
for module in sorted(n for n, level in tree.level.items() if level == "module")
]
with ThreadPoolExecutor(max_workers=workers) as pool:
described = list(pool.map(lambda m: describe_module(gateway(), m, judge), module_facts))
descriptions = [d for d in described if d is not None]
finally:
con.close()

folder = run.judgements / "findings"
for finding_id, judgement in sorted(judgements.items()):
name = hashlib.sha256(finding_id.encode("utf-8")).hexdigest()[:24]
write_json(folder / f"{name}.json", contracts.to_plain(judgement))
write_json(run.judgements / "simulations.json", dict(sorted(simulations.items())))
write_json(
run.judgements / "descriptions.json",
[contracts.to_plain(d) for d in sorted(descriptions, key=lambda d: d.node_id)],
)
if batch is not None:
write_json(run.simulation_batch, contracts.to_plain(batch))
calls = _merge_usage(run)

fresh = sum(
1 for c in calls if not c["served_from_cache"] and (c["input_tokens"] or c["output_tokens"])
)
print(
f"judge: {len(chosen)} findings judged ({passed} with a checked AI answer, "
f"{len(chosen) - passed} kept the template), {len(descriptions)} module descriptions, "
f"{len(moves)} cheap-loop fixes in the batch; {len(calls)} calls this run, "
f"{fresh} answered by the gateway"
)


def _module_facts(con, repo, sha, module, tree, modules, since, until, limits): # noqa: ANN001
"""Public names, neighbours and most changed files of one module (job C's packet)."""
from codexray.judge.jobs import ModuleFacts

path_module = {}
for file_id, path in con.execute(
"SELECT id, path FROM nodes WHERE repo = ? AND snapshot_sha = ? AND level = 'file'",
[repo, sha],
).fetchall():
lifted = tree.lift(file_id, "module") if file_id in tree.level else None
path_module[path] = (file_id, lifted)
names: Counter[str] = Counter()
for src, dst, name in con.execute(
"SELECT src_path, dst_path, name FROM links WHERE repo = ? AND snapshot_sha = ? "
"AND name IS NOT NULL",
[repo, sha],
).fetchall():
a, b = path_module.get(src, (None, None))[1], path_module.get(dst, (None, None))[1]
if b == module and a != module:
names[name] += 1
top_names = sorted(names, key=lambda n: (-names[n], n))[: int(limits["max_names"])]
k = int(limits["max_neighbours"])
uses = sorted(
((b, n) for (a, b), n in modules.items() if a == module and b != module),
key=lambda x: (-x[1], x[0]),
)[:k]
used_by = sorted(
((a, n) for (a, b), n in modules.items() if b == module and a != module),
key=lambda x: (-x[1], x[0]),
)[:k]
own = sorted(p for p, (_, m) in path_module.items() if m == module)
changed = con.execute(
"SELECT f.canonical_path, count(DISTINCT c.sha) FROM file_changes f "
"JOIN commits c ON c.repo = f.repo AND c.sha = f.sha "
"WHERE f.repo = ? AND NOT c.is_bot "
"AND c.committer_date >= ?::DATE AND c.committer_date < ?::DATE "
"AND f.canonical_path IN (SELECT unnest(?::VARCHAR[])) "
"GROUP BY 1 ORDER BY 2 DESC, 1 LIMIT ?",
[repo, since.isoformat(), until, own, int(limits["max_changed_files"])],
).fetchall()
return ModuleFacts(module, top_names, uses, used_by, [(p, int(n)) for p, n in changed])


def _merge_usage(run: RunPaths) -> list[dict[str, Any]]:
"""Add this run's answered calls to `usage.json`, the ledger of every call the gateway
answered for this run folder. Cache hits and calls that failed before an answer (no
tokens) are not added, so a re-run answered from the cache leaves it unchanged."""
from codexray.core import contracts
from codexray.core.runs import write_json

calls_dir = run.judgements / "calls"
calls = [
call
for path in sorted(calls_dir.glob("*.json"))
for call in json.loads(path.read_text("utf-8"))["calls"]
]
calls.sort(key=lambda c: (c["job"], c["subject"], c["cache_key"], c["served_from_cache"]))
write_json(run.judgements / "calls.json", {"schema": "codexray.usage/1", "calls": calls})
shutil.rmtree(calls_dir, ignore_errors=True)
ledger = []
if run.usage.is_file():
ledger = json.loads(run.usage.read_text("utf-8"))["calls"]
ledger += [
c for c in calls if not c["served_from_cache"] and (c["input_tokens"] or c["output_tokens"])
]
ledger.sort(
key=lambda c: (
c["job"],
c["subject"],
c["cache_key"],
c["input_tokens"],
c["output_tokens"],
)
)
usage = contracts.UsageFile.model_validate({"calls": ledger})
write_json(run.usage, contracts.to_plain(usage))
return calls
Loading