"""Bounded one-process llama.cpp completion adapter for the hello syntax fixture.""" import hashlib import json import os from pathlib import Path import re import subprocess LOCK = Path(__file__).with_name("model-lock.json") PROMPT_TOKENS = re.compile(r"prompt eval time\s*=.*?/\s*(\d+) tokens") SAMPLED_TOKENS = re.compile(r"samplers time\s*=.*?/\s*(\d+) tokens") def _sha256(path): digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def propose(source): lock = json.loads(LOCK.read_text(encoding="utf-8")) model = Path(os.environ["REVIEWER_MODEL_PATH"]) executable = Path(os.environ["REVIEWER_LLAMA_COMPLETION"]) if not model.is_file(): raise FileNotFoundError("model file missing") if _sha256(model) != lock["quantized_sha256"]: raise ValueError("model checksum mismatch") if not executable.is_file(): raise FileNotFoundError("llama-completion executable missing") if source not in ('print("hello"', 'print("hello"\n'): raise ValueError("real-model adapter only supports the hello fixture") prompt = lock["prompt_template"].format(source_line=source.rstrip("\n")) command = [str(executable), "-m", str(model), "-p", prompt, "-n", str(lock["max_output_tokens"]), "-c", str(lock["context_tokens"]), "-b", str(lock["batch_tokens"]), "-ub", str(lock["microbatch_tokens"]), "-t", str(lock["threads"]), "-tb", str(lock["threads"]), "--temp", str(lock["temperature"]), "--seed", str(lock["seed"]), "--no-conversation", "--simple-io", "--no-display-prompt", "--no-warmup", "--color", "off", "-r", "\n"] try: result = subprocess.run(command, capture_output=True, timeout=30, check=False) except subprocess.TimeoutExpired as exc: raise TimeoutError("llama-completion exceeded 30 seconds") from exc if len(result.stdout) > 1_000_000 or len(result.stderr) > 1_000_000: raise ValueError("runtime output exceeded size limit") if result.returncode: raise RuntimeError(f"llama-completion exited {result.returncode}") raw = result.stdout.decode("utf-8") runtime_log = result.stderr.decode("utf-8", errors="replace") prompt_match = PROMPT_TOKENS.search(runtime_log) sampled_match = SAMPLED_TOKENS.search(runtime_log) input_tokens = int(prompt_match.group(1)) if prompt_match else None output_tokens = (int(sampled_match.group(1)) - input_tokens if sampled_match and input_tokens is not None else None) if output_tokens is not None and output_tokens < 0: raise ValueError("runtime token counters inconsistent") log_path = os.environ.get("REVIEWER_RUNTIME_LOG") if log_path: Path(log_path).write_text(runtime_log, encoding="utf-8") # Only surrounding whitespace is removed. Internal text survives to the # reviewer's exact allowed-edit validator, and raw stdout is retained. candidate = raw.strip(" \t\r\n") + ("\n" if source.endswith("\n") else "") return {"candidate": candidate, "model_id": lock["base_model_id"], "model_revision": lock["base_model_revision"], "input_tokens": input_tokens, "output_tokens": output_tokens, "raw_response": raw, "runtime_response": {"prompt": prompt, "raw_stdout": raw, "prompt_eval_tokens": input_tokens, "sampler_total_tokens": int(sampled_match.group(1)) if sampled_match else None, "output_tokens_method": "sampler_total_tokens - prompt_eval_tokens", "runtime_log_counter_lines": [line for line in runtime_log.splitlines() if "common_perf_print:" in line and ("samplers time" in line or "prompt eval time" in line)]}}