Preserve Ollama metrics and add Doctor Headroom replay benchmark

This commit is contained in:
juvenal.diaz 2026-12-02 20:35:58 -06:00
parent b93ddf1df3
commit 92f81b5c47
9 changed files with 431 additions and 7 deletions

View File

@ -4,6 +4,10 @@ Assessed December 2, 2026 against checkout HEAD `ead716b` and the current
working tree. This is an integration proposal, not an installation or a
performance result. Existing unrelated AI-lab edits were preserved.
The subsequent [Doctor context lab](doctor-context-lab.md) adds an explicit,
optional Headroom replay experiment and native Ollama usage preservation.
See that guide for commands and interpretation limits.
## Recommendation
| Tool | Expected benefit here | Decision |

110
docs/doctor-context-lab.md Normal file
View File

@ -0,0 +1,110 @@
# Doctor context benchmark
The optional Headroom lab replays one saved Holmes decision. It never executes
the model's proposed tools and does not change production Doctor compression.
Use it to compare inference and context handling; it is not an end-to-end
remediation benchmark or a substitute for diagnostic review.
## Run on Debian
First capture the baseline with a saved private Holmes `conversation.json`:
```bash
./jeannie ai-lab doctor-context-bench baseline /absolute/path/to/conversation.json 3
```
The default is three repeats; one to five are supported. The last final answer
is removed, while preceding evidence and tool results are retained. The replay
uses the current local Doctor proxy and a compatible Bash schema with
`qwen2.5-coder:7b`; it does not launch Holmes or execute Bash. Native proxy
sampling defaults apply. Do not compare different inference models/settings as
if compression alone caused a change.
The command prints a private baseline report path. Then install Headroom into
its own virtual environment and compare against that exact saved request:
```bash
./jeannie ai-lab headroom-install
./jeannie ai-lab doctor-context-bench compare /absolute/path/to/baseline/report.json
```
Headroom is pinned to `headroom-ai==0.45.0`; installation downloads Python
dependencies into the AI lab's `headroom-venv`, without changing Holmes's
environment. Comparisons re-execute using that venv. `JEANNIE_AI_LAB_DIR` can
override the default `~/.local/share/homelab/ai-lab` directory. A context-lab
lock prevents overlapping benchmark commands; separately avoid other Ollama
workloads during measurement.
## Compression policy
The initial experiment uses Headroom's `mode=agent`, lossless verification,
offline operation and disabled model-based compression. Only tool content may
change. System/user messages, tool-call IDs, tool names, arguments, ordering
and other metadata must remain unchanged. An unverified or incompatible
compression result is an error, not a successful optimized run. No retrieval
tool is injected. Zero savings is a valid outcome.
Headroom uses `gpt-4o` only as a lightweight token-count estimator, avoiding
Qwen tokenizer/model downloads. This does not change the inference model.
Estimated compression counts are labeled separately from actual Ollama counts.
## Reports and interpretation
Reports are private JSON files under the lab's `reports/doctor-context-*`
directory. They contain the frozen request and responses, so keep them private:
the original conversation may contain operational data. Each report records
request and proxy source hashes. Compare reuses the original repeat count and
includes baseline responses rather than rerunning every engine.
Captured fields include actual prompt/completion counts, raw nanosecond
durations, model load and evaluation timings, stop reason, each retry request,
compression time, schema validity, and total elapsed time. Aggregate model
durations are converted to seconds; missing measurements stay null. Inspect
the proxy hashes when comparing a baseline produced by older code. Prompt
caches, cold loading and stochastic generation can affect timings; these runs
are exploratory measurements, not a statistically controlled performance claim.
Review whether the same observed facts, uncertainty, resource identities and
supported next step survive. A valid tool-call schema does not prove a correct
diagnosis, a suitable command, or a completed repair. No automatic quality score
is assigned by this benchmark.
Production local Holmes repair now also writes `ollama-metrics.jsonl` in its
existing private `doctor-k8s/repair.*` artifact directory. It records per-call
counts, durations and reasons without prompts or tool output. The proxy
preserves OpenAI-style usage and maps Ollama length termination to `length`,
while retaining the original reason under `ollama.done_reason`. Streaming
responses include usage and Ollama metadata in their final chunk. Headroom
remains confined to this explicit lab command.
## Initial Debian measurement, December 2, 2026
The attempted live `doctor cluster n8n --ai` baseline exited with code 2 because
the selected item could not be resolved. It is not an inference measurement.
A saved Holmes conversation (`repair.FtxkUhg4/conversation.json`) was therefore
used for two decision replays before the adapter changes and two with Headroom.
| Measurement | Uncompressed baseline | Headroom lossless tool mode |
| --- | --- | --- |
| Actual prompt tokens per request | 10,420 | 10,420 |
| Elapsed seconds by repeat | 236.13; 1.10 | 175.91; 0.53 |
| Completion tokens across both repeats | 6 | 1,025 |
| Stop reasons | stop; stop | length; stop |
| Schema-valid proposed tool decisions | 0 / 2 | 0 / 2 |
Headroom's estimator reported 9,917 tokens before and after, with lossless
verification. This input produced no compression benefit. Baseline responses
were whitespace; neither configuration established a usable tool decision.
Differences in model loading, prompt caching and stochastic output make these
elapsed times unsuitable as a compression speedup claim. The second variant
also uses the instrumented proxy; source hashes are recorded for both.
Private reports on Debian:
- Baseline: `~/.local/share/homelab/ai-lab/reports/doctor-context-20261203T022655Z-f9522757/report.json`
- Comparison: `~/.local/share/homelab/ai-lab/reports/doctor-context-20261203T023135Z-122b9f1e/report.json`
Directory timestamps use UTC; this measurement was taken on December 2 in
America/Mexico_City. These are a single-case exploratory benchmark, not an
assessment of Headroom across all Doctor workloads. Production compression
remains disabled.

12
jeannie
View File

@ -88,6 +88,9 @@ Build And Bootstrap
Explore the repo with Goose and Graphify.
ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench BACKEND|suite [REPEATS]|doctor-prepare|doctor-suite [REPEATS]|doctor-auto-rank REPORT|doctor-add-external REPORT RANKING MODEL|doctor-rank REPORT REVIEW} Manage AI experiments.
compose-intent {stopped|running|clear|list} [PROJECT/SERVICE...] Record Debian Compose desired state.
ai-lab headroom-install Install the pinned optional compression lab environment.
ai-lab doctor-context-bench baseline CONVERSATION [REPEATS]
ai-lab doctor-context-bench compare BASELINE Compare Headroom with a saved Doctor decision baseline.
lab-window <start|stop|status> Apply the scheduled lab power window.
deploy-omniroute Deploy the OmniRoute LLM routing gateway.
deploy-hermes Deploy the Hermes agent (git-install + venv + gateway service).
@ -335,13 +338,20 @@ case "${1:-}" in
bench) [[ $# -eq 3 && "${3}" =~ ^(ollama|cpu|vulkan|colibri|qwen-cpu)$ ]] || { echo "Usage: ./jeannie ai-lab bench {ollama|cpu|vulkan|colibri|qwen-cpu}" >&2; exit 2; } ;;
suite) [[ $# -le 3 && "${3:-3}" =~ ^([1-9]|10)$ ]] || { echo "Usage: ./jeannie ai-lab suite [REPEATS 1-10]" >&2; exit 2; } ;;
doctor-suite) [[ $# -le 3 && "${3:-2}" =~ ^[1-5]$ ]] || { echo "Usage: ./jeannie ai-lab doctor-suite [REPEATS 1-5]" >&2; exit 2; } ;;
headroom-install) [[ $# -eq 2 ]] || exit 2 ;;
doctor-context-bench) [[ $# -ge 4 && $# -le 5 && "${3}" =~ ^(baseline|compare)$ ]] || { echo "Usage: ./jeannie ai-lab doctor-context-bench {baseline CONVERSATION [REPEATS]|compare BASELINE}" >&2; exit 2; } ;;
doctor-rank) [[ $# -eq 4 ]] || { echo "Usage: ./jeannie ai-lab doctor-rank REPORT REVIEW" >&2; exit 2; } ;;
doctor-auto-rank) [[ $# -eq 3 ]] || { echo "Usage: ./jeannie ai-lab doctor-auto-rank REPORT" >&2; exit 2; } ;;
doctor-add-external) [[ $# -eq 5 ]] || { echo "Usage: ./jeannie ai-lab doctor-add-external REPORT RANKING MODEL" >&2; exit 2; } ;;
*) echo "Usage: ./jeannie ai-lab {plan|install|devices|colibri-install|colibri-prepare|bench|suite|doctor-prepare|doctor-suite|doctor-rank}" >&2; exit 2 ;;
esac
case "${2:-plan}" in install|colibri-install|colibri-prepare|doctor-prepare) record_change_journal "ai-lab" "$@" ;; esac
if [[ "${2:-plan}" == suite ]]; then
if [[ "${2:-plan}" == headroom-install ]]; then
record_change_journal "ai-lab-headroom-install"
python3 "${REPO_ROOT}/scripts/doctor-context-lab.py" install
elif [[ "${2:-plan}" == doctor-context-bench ]]; then
"${LAB_HOLMES_ADAPTER_PYTHON:-/home/jv/.local/share/pipx/venvs/holmesgpt/bin/python}" "${REPO_ROOT}/scripts/doctor-context-lab.py" "${@:3}"
elif [[ "${2:-plan}" == suite ]]; then
python3 "${REPO_ROOT}/scripts/ai-lab-suite.py" "${@:3}"
elif [[ "${2:-plan}" == doctor-prepare ]]; then
python3 "${REPO_ROOT}/scripts/doctor-model-lab.py" prepare

View File

@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""Replay a frozen Holmes decision without executing any proposed tools."""
import argparse
import copy
import fcntl
import hashlib
import importlib.metadata
import importlib.util
import io
import json
import os
from pathlib import Path
import statistics
import subprocess
import sys
import time
import uuid
from urllib.parse import urlsplit
from datetime import datetime, timezone
from unittest.mock import patch
ROOT = Path(os.environ.get('JEANNIE_AI_LAB_DIR', Path.home() / '.local/share/homelab/ai-lab'))
VERSION = '0.45.0'
TOOLS = [{'type': 'function', 'function': {'name': 'bash', 'parameters': {
'type': 'object', 'properties': {'command': {'type': 'string'},
'suggested_prefixes': {'type': 'array', 'items': {'type': 'string'}}, 'timeout': {'type': 'integer'}},
'required': ['command', 'suggested_prefixes']}}}]
def private_json(path, data):
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as stream:
json.dump(data, stream, indent=2)
def request_from_conversation(data):
messages = copy.deepcopy(data['messages'])
if messages and messages[-1].get('role') == 'assistant' and not messages[-1].get('tool_calls'):
messages.pop()
if not messages or not any(m.get('role') == 'user' for m in messages):
raise ValueError('Conversation has no user evidence')
return {'model': 'qwen2.5-coder:7b', 'messages': messages, 'tools': TOOLS,
'temperature': 0, 'seed': 42, 'stream': False}
def compress_request(request):
os.environ['HEADROOM_OFFLINE'] = '1'
from headroom import compress
before = copy.deepcopy(request['messages'])
# Use a supported lightweight estimator; actual tokens come from Ollama.
# Selecting Qwen here makes Headroom require Transformers/model downloads.
result = compress(copy.deepcopy(before), model='gpt-4o', mode='agent',
compress_user_messages=False, compress_system_messages=False,
kompress_model='disabled')
after = result.messages
if len(before) != len(after):
raise ValueError('Compression changed message count')
for old, new in zip(before, after):
# Only tool content may change. Instructions and tool-call pairing stay exact.
if old.get('role') != 'tool' and old != new:
raise ValueError('Compression changed protected message')
if {k: v for k, v in old.items() if k != 'content'} != {k: v for k, v in new.items() if k != 'content'}:
raise ValueError('Compression changed tool metadata')
if result.lossless is not True:
raise ValueError('Headroom did not verify lossless compression')
output = copy.deepcopy(request)
output['messages'] = after
return output, {'tokens_before_estimated': result.tokens_before,
'tokens_after_estimated': result.tokens_after, 'lossless': result.lossless,
'token_estimator': 'gpt-4o (not the inference model)'}
def run(request, repeats, compressed):
spec = importlib.util.spec_from_file_location('doctor_proxy', Path(__file__).with_name('ollama-tool-proxy.py'))
proxy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(proxy)
original_query = proxy.query_ollama
original_open = proxy.urllib.request.urlopen
results = []
for index in range(repeats):
upstream = []
transforms = []
def capture(*args, **kwargs):
with original_open(*args, **kwargs) as response:
raw = response.read()
data = json.loads(raw)
upstream.append({k: data.get(k) for k in ('model', 'prompt_eval_count', 'eval_count',
'total_duration', 'load_duration', 'prompt_eval_duration', 'eval_duration', 'done_reason', 'usage')})
return io.BytesIO(raw)
def query(payload):
if compressed:
start = time.monotonic()
payload, metrics = compress_request(payload)
metrics['elapsed_seconds'] = time.monotonic() - start
transforms.append(metrics)
return original_query(payload)
start = time.monotonic()
row = {'repeat': index + 1}
try:
with patch.object(proxy.urllib.request, 'urlopen', side_effect=capture), patch.object(proxy, 'query_ollama', side_effect=query):
response = proxy.complete(copy.deepcopy(request), True)
row['response'] = response
calls = response['choices'][0]['message'].get('tool_calls', [])
content = response['choices'][0]['message'].get('content')
row['response_kind'] = 'tool_call' if calls else ('text' if isinstance(content, str) and content.strip() else 'empty')
row['proposed_tool_calls'] = len(calls)
row['schema_valid'] = bool(calls) and all(proxy.adapter.convert(json.dumps({
'name': c['function']['name'], 'arguments': json.loads(c['function']['arguments'])}), request['tools']) for c in calls)
except Exception as exc:
row['error'] = type(exc).__name__ + ': ' + str(exc)[:300]
row.update(elapsed_seconds=time.monotonic() - start, upstream=upstream, compression=transforms)
results.append(row)
print(f"Repeat {index + 1}/{repeats}: {row['elapsed_seconds']:.2f}s; error={row.get('error', 'none')}", flush=True)
return results
def summarize(rows):
calls = [call for row in rows for call in row['upstream']]
def total(key):
values = [call.get(key) for call in calls]
return sum(values) if values and all(isinstance(v, int) for v in values) else None
reasons = {}
for call in calls:
reason = call.get('done_reason') or 'unknown'
reasons[reason] = reasons.get(reason, 0) + 1
return {'median_seconds': statistics.median(row['elapsed_seconds'] for row in rows),
'requests': len(calls), 'errors': sum('error' in row for row in rows),
'schema_valid_decisions': sum(row.get('schema_valid', False) for row in rows),
'empty_responses': sum(row.get('response_kind') == 'empty' or
(not row.get('error') and not row.get('response', {}).get('choices', [{}])[0].get('message', {}).get('tool_calls') and
not (row.get('response', {}).get('choices', [{}])[0].get('message', {}).get('content') or '').strip()) for row in rows),
'prompt_tokens_total': total('prompt_eval_count'), 'completion_tokens_total': total('eval_count'),
'ollama_total_seconds': total('total_duration') / 1e9 if total('total_duration') is not None else None,
'stop_reasons': reasons}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('action', choices=['install', 'baseline', 'compare'])
parser.add_argument('source', nargs='?')
parser.add_argument('repeats', nargs='?', type=int, default=3, choices=range(1, 6))
args = parser.parse_args()
venv = ROOT / 'headroom-venv'
if args.action == 'install':
ROOT.mkdir(parents=True, exist_ok=True)
subprocess.run([sys.executable, '-m', 'venv', str(venv)], check=True)
subprocess.run([str(venv / 'bin/python'), '-m', 'pip', 'install', f'headroom-ai=={VERSION}', 'jsonschema'], check=True)
return
if args.action == 'compare' and os.environ.get('JEANNIE_HEADROOM_VENV') != '1':
if not (venv / 'bin/python').is_file():
raise SystemExit('Run ./jeannie ai-lab headroom-install first')
env = dict(os.environ, JEANNIE_HEADROOM_VENV='1')
os.execve(str(venv / 'bin/python'), [str(venv / 'bin/python'), __file__, *sys.argv[1:]], env)
if not args.source:
parser.error('A conversation JSON (baseline) or baseline report JSON (compare) is required')
if args.action == 'compare' and len(sys.argv) != 3:
parser.error('compare reuses the baseline repeat count; no repeat override is accepted')
endpoint = urlsplit(os.environ.get('OLLAMA_API_BASE', 'http://127.0.0.1:11434'))
if endpoint.scheme != 'http' or endpoint.hostname not in ('127.0.0.1', 'localhost', '::1') or endpoint.username or endpoint.password:
raise ValueError('Context benchmarks require a local Ollama endpoint')
ROOT.mkdir(parents=True, exist_ok=True)
lock = (ROOT / 'doctor-context.lock').open('w')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
data = json.loads(Path(args.source).read_text())
request = request_from_conversation(data) if args.action == 'baseline' else data['request']
repeats = args.repeats if args.action == 'baseline' else data['repeats']
directory = ROOT / 'reports' / (datetime.now(timezone.utc).strftime('doctor-context-%Y%m%dT%H%M%SZ-') + uuid.uuid4().hex[:8])
directory.mkdir(parents=True, mode=0o700)
report = {'action': args.action, 'request': request, 'repeats': repeats,
'request_sha256': hashlib.sha256(json.dumps(request, sort_keys=True).encode()).hexdigest(),
'proxy_sha256': hashlib.sha256(Path(__file__).with_name('ollama-tool-proxy.py').read_bytes()).hexdigest(),
'interpretation': 'Single recorded Holmes decision replay with a compatible Bash schema; no tools executed. Schema validity is not diagnostic correctness or repair success. Times include retries, compression and model loading. Warm prompt caches and stochastic sampling may affect comparisons. Existing native Doctor proxy does not forward temperature/seed fields.'}
if args.action == 'compare':
if data.get('action') != 'baseline':
raise ValueError('Compare requires an uncompressed baseline report')
if report['request_sha256'] != data['request_sha256']:
raise ValueError('Baseline request hash mismatch')
report.update(baseline_report=str(Path(args.source).resolve()), baseline_proxy_sha256=data['proxy_sha256'],
baseline_results=data['results'], headroom_version=importlib.metadata.version('headroom-ai'))
if report['headroom_version'] != VERSION:
raise ValueError('Unexpected Headroom version; rerun headroom-install')
try:
report['results'] = run(request, repeats, args.action == 'compare')
report['summary'] = summarize(report['results'])
print(json.dumps(report['summary'], indent=2), flush=True)
if args.action == 'compare':
report['baseline_summary'] = summarize(data['results'])
finally:
private_json(directory / 'report.json', report)
print('Private report: ' + str(directory / 'report.json'))
if any('error' in row for row in report['results']):
raise SystemExit(1)
if __name__ == '__main__':
main()

View File

@ -132,7 +132,7 @@ doctor_focus_holmes_fix() {
bin="$(command -v holmes || true)"
[[ -n "${bin}" ]] || { echo "Holmes binary unavailable for local adapter." >&2; return 1; }
local adapter_python="${LAB_HOLMES_ADAPTER_PYTHON:-/home/jv/.local/share/pipx/venvs/holmesgpt/bin/python}"
JEANNIE_HOLMES_BASH_ONLY=true "${adapter_python}" "${REPO_ROOT}/scripts/ollama-tool-proxy.py" "${artifact}/proxy-port" >"${artifact}/proxy-output.txt" 2>&1 &
JEANNIE_OLLAMA_METRICS_FILE="${artifact}/ollama-metrics.jsonl" JEANNIE_HOLMES_BASH_ONLY=true "${adapter_python}" "${REPO_ROOT}/scripts/ollama-tool-proxy.py" "${artifact}/proxy-port" >"${artifact}/proxy-output.txt" 2>&1 &
proxy_pid=$!
for ((i = 0; i < 50; i++)); do
[[ ! -s "${artifact}/proxy-port" ]] || break

View File

@ -5,6 +5,7 @@ import json
import os
import re
import shlex
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
import sys
@ -26,6 +27,7 @@ def bash_only(tools):
def query_ollama(request):
started = time.monotonic()
request = dict(request)
native = request.pop("_jeannie_native", False)
if native:
@ -54,12 +56,37 @@ def query_ollama(request):
call["type"] = "function"
if not isinstance(call["function"].get("arguments"), str):
call["function"]["arguments"] = json.dumps(call["function"]["arguments"])
return {"model": result.get("model"), "choices": [{"index": 0, "message": message,
"finish_reason": "tool_calls" if message.get("tool_calls") else "stop"}]}
prompt, completion = result.get("prompt_eval_count"), result.get("eval_count")
metrics = {k: result.get(k) for k in ('prompt_eval_count', 'eval_count', 'total_duration',
'load_duration', 'prompt_eval_duration', 'eval_duration', 'done_reason')}
output = {"model": result.get("model"), "choices": [{"index": 0, "message": message,
"finish_reason": "tool_calls" if message.get("tool_calls") else
("length" if result.get("done_reason") == "length" else "stop")}],
"usage": {"prompt_tokens": prompt, "completion_tokens": completion,
"total_tokens": prompt + completion if isinstance(prompt, int) and isinstance(completion, int) else None},
"ollama": metrics}
record_metrics(output, time.monotonic() - started)
return output
url = os.environ.get("OLLAMA_API_BASE", "http://127.0.0.1:11434").rstrip("/") + "/v1/chat/completions"
upstream = urllib.request.Request(url, data=json.dumps(request).encode(), headers={"Content-Type": "application/json"})
with urllib.request.urlopen(upstream, timeout=600) as response:
return json.load(response)
result = json.load(response)
record_metrics(result, time.monotonic() - started)
return result
def record_metrics(result, elapsed):
path = os.environ.get('JEANNIE_OLLAMA_METRICS_FILE')
if not path:
return
row = {'model': result.get('model'), 'usage': result.get('usage'), 'ollama': result.get('ollama'),
'elapsed_seconds': elapsed, 'finish_reason': result['choices'][0].get('finish_reason')}
try:
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
with os.fdopen(fd, 'a') as stream:
stream.write(json.dumps(row) + '\n')
except OSError:
print('Ollama metrics could not be saved', file=sys.stderr, flush=True)
def translate(result, tools):
@ -306,7 +333,8 @@ class Handler(BaseHTTPRequestHandler):
base = {"id": result.get("id", "chatcmpl-local"), "object": "chat.completion.chunk",
"created": result.get("created", 0), "model": result.get("model", request.get("model", ""))}
for chunk in (dict(base, choices=[{"index": 0, "delta": delta, "finish_reason": None}]),
dict(base, choices=[{"index": 0, "delta": {}, "finish_reason": choice.get("finish_reason", "stop")}] )):
dict(base, usage=result.get("usage"), ollama=result.get("ollama"),
choices=[{"index": 0, "delta": {}, "finish_reason": choice.get("finish_reason", "stop")}] )):
self.wfile.write(b"data: " + json.dumps(chunk).encode() + b"\n\n")
self.wfile.write(b"data: [DONE]\n\n")
except (OSError, ValueError, KeyError, IndexError, TypeError, urllib.error.URLError):

View File

@ -122,6 +122,7 @@ validate_unit_tests() {
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_progressive_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_ai_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_ai_lab_suite.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_context_lab.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_status_focus.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_status_app_snapshot.py'
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_go_launchers.py'

View File

@ -0,0 +1,51 @@
import copy
import importlib.util
from pathlib import Path
import sys
import types
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('context_lab', Path(__file__).resolve().parents[2] / 'scripts/doctor-context-lab.py')
lab = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lab)
class ContextLabTests(unittest.TestCase):
def test_recorded_final_answer_is_removed_without_losing_tool_results(self):
original = {'messages': [{'role': 'user', 'content': 'evidence'}, {'role': 'tool', 'content': 'result'},
{'role': 'assistant', 'content': 'old answer'}]}
request = lab.request_from_conversation(original)
self.assertEqual(request['messages'][-1]['role'], 'tool')
self.assertEqual(len(original['messages']), 3)
def test_compression_rejects_changed_instructions_and_tool_pairing(self):
request = {'model': 'test', 'messages': [{'role': 'system', 'content': 'preserve'},
{'role': 'tool', 'tool_call_id': 'x', 'content': 'verbose'}]}
for field, value in [('content', 'changed'), ('role', 'user')]:
after = copy.deepcopy(request['messages'])
after[0][field] = value
result = types.SimpleNamespace(messages=after, lossless=True)
fake = types.SimpleNamespace(compress=lambda *a, **k: result)
with patch.dict(sys.modules, headroom=fake), self.assertRaises(ValueError):
lab.compress_request(request)
after = copy.deepcopy(request['messages'])
after[1]['tool_call_id'] = 'wrong'
fake = types.SimpleNamespace(compress=lambda *a, **k: types.SimpleNamespace(messages=after, lossless=True))
with patch.dict(sys.modules, headroom=fake), self.assertRaises(ValueError):
lab.compress_request(request)
def test_lossless_tool_content_change_is_accepted(self):
request = {'model': 'test', 'messages': [{'role': 'tool', 'tool_call_id': 'x', 'content': 'verbose'}]}
after = copy.deepcopy(request['messages'])
after[0]['content'] = 'dense'
result = types.SimpleNamespace(messages=after, lossless=True, tokens_before=100, tokens_after=50)
with patch.dict(sys.modules, headroom=types.SimpleNamespace(compress=lambda *a, **k: result)):
output, metrics = lab.compress_request(request)
self.assertEqual(output['messages'][0]['content'], 'dense')
self.assertEqual(request['messages'][0]['content'], 'verbose')
self.assertTrue(metrics['lossless'])
if __name__ == '__main__':
unittest.main()

View File

@ -1,6 +1,8 @@
import importlib.util
import json
import io
import os
import tempfile
from pathlib import Path
import unittest
from unittest.mock import patch
@ -15,7 +17,9 @@ PROXY_SPEC.loader.exec_module(PROXY)
class ToolAdapterTests(unittest.TestCase):
def test_native_request_sets_context_and_converts_tool_arguments(self):
response = {"model": "test", "message": {"role": "assistant", "tool_calls": [
response = {"model": "test", "prompt_eval_count": 20, "eval_count": 5,
"total_duration": 1000, "load_duration": 200, "prompt_eval_duration": 300,
"eval_duration": 500, "done_reason": "stop", "message": {"role": "assistant", "tool_calls": [
{"function": {"name": "bash", "arguments": {"command": "kubectl get pods"}}}]}}
request = {"_jeannie_native": True, "model": "test", "messages": [], "max_tokens": 512}
with patch.object(PROXY.urllib.request, "urlopen", return_value=io.BytesIO(json.dumps(response).encode())) as query:
@ -25,6 +29,27 @@ class ToolAdapterTests(unittest.TestCase):
self.assertNotIn("_jeannie_native", sent)
call = answer["choices"][0]["message"]["tool_calls"][0]
self.assertEqual(json.loads(call["function"]["arguments"])["command"], "kubectl get pods")
self.assertEqual(answer['usage'], {'prompt_tokens': 20, 'completion_tokens': 5, 'total_tokens': 25})
self.assertEqual(answer['ollama']['eval_duration'], 500)
self.assertEqual(answer['ollama']['done_reason'], 'stop')
def test_native_length_stop_and_missing_usage_are_preserved(self):
response = {'message': {'role': 'assistant', 'content': 'partial'}, 'done_reason': 'length'}
with patch.object(PROXY.urllib.request, 'urlopen', return_value=io.BytesIO(json.dumps(response).encode())):
answer = PROXY.query_ollama({'_jeannie_native': True, 'model': 'test', 'messages': []})
self.assertEqual(answer['choices'][0]['finish_reason'], 'length')
self.assertIsNone(answer['usage']['total_tokens'])
def test_metrics_artifact_excludes_model_content(self):
with tempfile.TemporaryDirectory() as directory:
target = Path(directory) / 'metrics.jsonl'
with patch.dict(os.environ, JEANNIE_OLLAMA_METRICS_FILE=str(target)):
PROXY.record_metrics({'model': 'test', 'usage': {'prompt_tokens': 10},
'choices': [{'finish_reason': 'length', 'message': {'content': 'private evidence'}}]}, 1.2)
data = target.read_text()
self.assertNotIn('private evidence', data)
self.assertEqual(json.loads(data)['finish_reason'], 'length')
self.assertEqual(target.stat().st_mode & 0o777, 0o600)
def setUp(self):
self.tools = [{"type": "function", "function": {"name": "get_status", "parameters": {