Repository navigation
Add eval 311: CPU throttling caused by cache-key mismatch bug #2310
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
aantn
wants to merge
11
commits into
master
Choose a base branch
from
claude/cpu-throttling-bug-eval-m2dev7
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
205e008
Add eval 283: CPU throttling caused by a bug in application code
claude fb2a664
Address review feedback on eval 283
claude 52ab65f
Merge remote-tracking branch 'origin/master' into claude/cpu-throttli…
claude 8ba0190
Merge master and renumber eval 283 -> 289 to resolve collisions
claude 2d4d25c
Address CodeRabbit review on the renumbered fixture
claude 2942bd3
Pin gitlab-mcp init container to mcp SDK 1.x
claude e81f57a
Merge remote-tracking branch 'origin/master' into claude/cpu-throttli…
claude 3adf5d5
Merge master and renumber eval 289 -> 296 to resolve new collision
claude 7cc5add
Merge origin/master into claude/cpu-throttling-bug-eval-m2dev7
claude 269cae2
Merge origin/master into claude/cpu-throttling-bug-eval-m2dev7
claude 8c85eee
Renumber eval 296 -> 311 to resolve collision with master's 296_dagst…
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
tests/llm/fixtures/test_ask_holmes/289_cpu_throttling_code_bug/app/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| # quote-service | ||
|
|
||
| Shipping quote API for the logistics platform. | ||
|
|
||
| ## Endpoints | ||
|
|
||
| - `GET /api/v1/quote?origin=<code>&dest=<code>&weight_kg=<kg>` — returns the | ||
| cheapest carrier and rate for a route | ||
| - `GET /healthz` — liveness/readiness | ||
|
|
||
| ## Design notes | ||
|
|
||
| Carrier rate cards refresh at most once per day, so the tariff matrix for a | ||
| route is computed once and cached in memory (`tariff_engine.py`). Computing a | ||
| matrix is CPU-heavy (rate interpolation across the full zone grid for every | ||
| carrier and weight break); serving a quote from the cached matrix takes | ||
| microseconds. | ||
|
|
||
| ## Deployment | ||
|
|
||
| Runs as `quote-service` in Kubernetes. Internal batch consumers (rate sync) | ||
| refresh quotes on a fixed set of routes throughout the day. |
119 changes: 119 additions & 0 deletions
119
tests/llm/fixtures/test_ask_holmes/289_cpu_throttling_code_bug/app/server.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,119 @@ | ||
| """HTTP entrypoint for the quote service. | ||
|
|
||
| GET /api/v1/quote?origin=<code>&dest=<code>&weight_kg=<kg> returns the | ||
| cheapest carrier rate for a route. Tariff matrices are cached per route | ||
| (rate cards refresh daily), so steady-state requests should be served | ||
| from cache in well under a millisecond. | ||
| """ | ||
|
|
||
| import json | ||
| import logging | ||
| import math | ||
| import os | ||
| import time | ||
| from datetime import datetime, timezone | ||
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | ||
| from urllib.parse import parse_qs, urlparse | ||
|
|
||
| from tariff_engine import CARRIERS, WEIGHT_BREAKS_KG, TariffEngine | ||
|
|
||
| LOG_PATH = os.environ.get("LOG_PATH", "/var/log/quote-service.log") | ||
|
|
||
| logger = logging.getLogger("quote_service.http") | ||
| engine = TariffEngine() | ||
|
|
||
|
|
||
| class JsonFormatter(logging.Formatter): | ||
| def format(self, record: logging.LogRecord) -> str: | ||
| return json.dumps( | ||
| { | ||
| "timestamp": datetime.now(timezone.utc).isoformat(), | ||
| "level": record.levelname, | ||
| "logger": record.name, | ||
| "message": record.getMessage(), | ||
| "pod": os.environ.get("HOSTNAME", "quote-service"), | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def setup_logging() -> None: | ||
| handlers = [logging.StreamHandler(), logging.FileHandler(LOG_PATH)] | ||
| for handler in handlers: | ||
| handler.setFormatter(JsonFormatter()) | ||
| logging.basicConfig(level=logging.INFO, handlers=handlers) | ||
|
|
||
|
|
||
| class QuoteHandler(BaseHTTPRequestHandler): | ||
| def log_message(self, message_format: str, *args) -> None: | ||
| # Access logging is done in do_GET with timings; silence the default. | ||
| pass | ||
|
|
||
| def _send(self, code: int, payload: dict) -> None: | ||
| body = json.dumps(payload).encode() | ||
| self.send_response(code) | ||
| self.send_header("Content-Type", "application/json") | ||
| self.send_header("Content-Length", str(len(body))) | ||
| self.end_headers() | ||
| self.wfile.write(body) | ||
|
|
||
| def do_GET(self) -> None: | ||
| parsed = urlparse(self.path) | ||
| if parsed.path == "/healthz": | ||
| self._send(200, {"status": "ok"}) | ||
| return | ||
| if parsed.path != "/api/v1/quote": | ||
| self._send(404, {"error": "not found"}) | ||
| return | ||
|
|
||
| params = parse_qs(parsed.query) | ||
| origin = params.get("origin", [""])[0].strip().upper() | ||
| dest = params.get("dest", [""])[0].strip().upper() | ||
| try: | ||
| weight_kg = float(params.get("weight_kg", ["1"])[0]) | ||
| except ValueError: | ||
| self._send(400, {"error": "weight_kg must be a number"}) | ||
| return | ||
| if not math.isfinite(weight_kg) or weight_kg <= 0: | ||
| self._send(400, {"error": "weight_kg must be a positive finite number"}) | ||
| return | ||
| if len(origin) != 3 or len(dest) != 3: | ||
| self._send(400, {"error": "origin and dest must be 3-letter codes"}) | ||
| return | ||
|
|
||
| started = time.monotonic() | ||
| matrix = engine.get_matrix(origin, dest) | ||
| quote = engine.cheapest(matrix, weight_kg) | ||
| elapsed_ms = int((time.monotonic() - started) * 1000) | ||
| logger.info( | ||
| "GET /api/v1/quote origin=%s dest=%s weight_kg=%s -> %s %.2f EUR in %dms", | ||
| origin, | ||
| dest, | ||
| weight_kg, | ||
| quote["carrier"], | ||
| quote["rate_eur"], | ||
| elapsed_ms, | ||
| ) | ||
| self._send( | ||
| 200, | ||
| { | ||
| "origin": origin, | ||
| "dest": dest, | ||
| "weight_kg": weight_kg, | ||
| "quote": quote, | ||
| "took_ms": elapsed_ms, | ||
| }, | ||
| ) | ||
|
|
||
|
|
||
| def main() -> None: | ||
| setup_logging() | ||
| logger.info( | ||
| "quote-service starting on :8080 (%d carriers, %d weight breaks)", | ||
| len(CARRIERS), | ||
| len(WEIGHT_BREAKS_KG), | ||
| ) | ||
| ThreadingHTTPServer(("0.0.0.0", 8080), QuoteHandler).serve_forever() | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| main() |
112 changes: 112 additions & 0 deletions
112
tests/llm/fixtures/test_ask_holmes/289_cpu_throttling_code_bug/app/tariff_engine.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| """Tariff computation for the quote service. | ||
|
|
||
| Carrier rate cards refresh at most once per day, so the full tariff | ||
| matrix for a route is computed once and cached in memory. Steady-state | ||
| quote requests are expected to be served from that cache. | ||
| """ | ||
|
|
||
| import logging | ||
| import math | ||
| import threading | ||
| import time | ||
|
|
||
| logger = logging.getLogger("quote_service.tariff") | ||
|
|
||
| CARRIERS = [ | ||
| "northwind", | ||
| "baltic-express", | ||
| "cargolux-freight", | ||
| "transalpine", | ||
| "seabridge", | ||
| ] | ||
|
|
||
| WEIGHT_BREAKS_KG = [0.5, 1, 2, 5, 10, 20, 50, 100, 250, 500] | ||
|
|
||
| # Base rates are interpolated over the full zone grid so surcharges stay | ||
| # consistent with the carrier rate cards. | ||
| ZONE_GRID_RESOLUTION = 250 | ||
|
|
||
|
|
||
| def _route_seed(origin: str, dest: str) -> int: | ||
| return sum(ord(c) * (i + 1) for i, c in enumerate(origin + dest)) | ||
|
|
||
|
|
||
| def compute_tariff_matrix(origin: str, dest: str) -> dict: | ||
| """Build the carrier x weight-break rate matrix for a route. | ||
|
|
||
| Interpolates base rates across the zone grid for every carrier and | ||
| weight break. This is the expensive path - callers are expected to | ||
| cache the result per route. | ||
| """ | ||
| seed = _route_seed(origin, dest) | ||
| matrix = {} | ||
| for carrier_idx, carrier in enumerate(CARRIERS): | ||
| rates = {} | ||
| for weight in WEIGHT_BREAKS_KG: | ||
| acc = 0.0 | ||
| for zone_row in range(ZONE_GRID_RESOLUTION): | ||
| for zone_col in range(ZONE_GRID_RESOLUTION): | ||
| cell = (seed * 31 + carrier_idx * zone_row + zone_col) % 977 | ||
| acc += math.sqrt(cell + 1.0) | ||
| base = acc / (ZONE_GRID_RESOLUTION * ZONE_GRID_RESOLUTION) | ||
| rates[str(weight)] = round( | ||
| base * (1.0 + math.log1p(weight)) + carrier_idx * 1.75, 2 | ||
| ) | ||
| matrix[carrier] = rates | ||
| return matrix | ||
|
|
||
|
|
||
| class TariffEngine: | ||
| """Serves tariff matrices with an in-memory per-route cache.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| self._cache = {} | ||
| self._lock = threading.Lock() | ||
|
|
||
| @staticmethod | ||
| def _cache_key(origin: str, dest: str) -> str: | ||
| """Canonical cache key for a route.""" | ||
| return f"{origin.upper()}:{dest.upper()}" | ||
|
|
||
| def get_matrix(self, origin: str, dest: str) -> dict: | ||
| key = self._cache_key(origin, dest) | ||
| with self._lock: | ||
| cached = self._cache.get(key) | ||
| if cached is not None: | ||
| return cached | ||
|
|
||
| started = time.monotonic() | ||
| matrix = compute_tariff_matrix(origin, dest) | ||
| elapsed_ms = int((time.monotonic() - started) * 1000) | ||
| if elapsed_ms > 500: | ||
| logger.warning( | ||
| "compute_tariff_matrix took %dms for route %s-%s", | ||
| elapsed_ms, | ||
| origin, | ||
| dest, | ||
| ) | ||
|
|
||
| with self._lock: | ||
| self._cache[f"{origin.upper()}->{dest.upper()}"] = matrix | ||
| return matrix | ||
|
|
||
| @staticmethod | ||
| def cheapest(matrix: dict, weight_kg: float) -> dict: | ||
| """Pick the cheapest carrier at the smallest weight break >= weight_kg.""" | ||
| chosen_break = WEIGHT_BREAKS_KG[-1] | ||
| for wb in WEIGHT_BREAKS_KG: | ||
| if weight_kg <= wb: | ||
| chosen_break = wb | ||
| break | ||
| best_carrier = None | ||
| best_rate = None | ||
| for carrier, rates in matrix.items(): | ||
| rate = rates[str(chosen_break)] | ||
| if best_rate is None or rate < best_rate: | ||
| best_carrier = carrier | ||
| best_rate = rate | ||
| return { | ||
| "carrier": best_carrier, | ||
| "rate_eur": best_rate, | ||
| "weight_break_kg": chosen_break, | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.