Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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
16 changes: 16 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,22 @@ Budget accordingly when looping.
- `anthropic/<model>` prefix in `model:` — litellm's Anthropic provider hits
`/api/v1/v1/messages` (doubled path) and 404s; use `openai/anthropic/<model>` instead
- Assuming Anthropic / OpenAI keys are present — only `OPENROUTER_API_KEY` is available
- GitHub release downloads (`github.com/<org>/<repo>/releases/download/...`) — the
network policy returns 403, which breaks `setup-sandbox-k8s.sh`'s static-jq fetch.
Workaround: pre-place `/tmp/jq` as an executable `sh` script that emulates the one
invocation the runc wrapper makes (`jq "del(.process.oomScoreAdj)" FILE`) via
`sed -E 's/"oomScoreAdj"[[:space:]]*:[[:space:]]*-[0-9]+/"oomScoreAdj":0/g' "$2"` —
the setup script skips the download when `/tmp/jq` is already executable
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
- CPU limit enforcement — pods' CFS quotas are never applied in the sandbox k3s
(`cpu.cfs_quota_us` stays `-1`), so real CPU throttling cannot occur and cAdvisor
exposes NO `container_cpu_cfs_*` metrics (usage metrics are fine). Evals that
assert on real throttling (e.g. 289) need a stand-in exporter feeding those
series to the Prometheus service in the sandbox; on real clusters they work as-is
- `pip install` inside cluster pods — the sandbox MITMs pypi.org with its internal
CA, so pip fails TLS verification. Workaround: create a ConfigMap from
`/root/.ccr/ca-bundle.crt`, mount it into the container, and set
`PIP_CERT=/path/to/ca.crt` (used for eval 254/289-style init containers that
pip-install the `mcp` package)

**Caveats and gotchas (things that DO work but with strings attached):**

Expand Down
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.
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()
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,
}
Loading
Loading