Skip to content

Commit fbd476f

Browse files
committed
fix(api): guard Prometheus metric definitions to prevent duplicate registration on module reload
1 parent 50cc4a2 commit fbd476f

1 file changed

Lines changed: 13 additions & 16 deletions

File tree

api/app.py

Lines changed: 13 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
import tensorflow as tf # noqa: F401 (ensures TF is initialised before model load)
3434
from fastapi import FastAPI, Header, HTTPException, Request
3535
from fastapi.middleware.cors import CORSMiddleware
36-
from prometheus_client import REGISTRY, Counter, Histogram
36+
from prometheus_client import Counter, Histogram
3737
from prometheus_fastapi_instrumentator import Instrumentator
3838
from pydantic import BaseModel, Field
3939

@@ -56,8 +56,6 @@
5656
API_KEY = os.environ.get("KANX_API_KEY", "").strip() # "" disables auth
5757
RATE_LIMIT_RPM = int(os.environ.get("KANX_RATE_LIMIT_RPM", "0")) # 0 disables
5858

59-
# Clear Prometheus registry to avoid duplicate metrics when module is reloaded in tests
60-
REGISTRY.clear()
6159

6260
# ---------------------------------------------------------------------------
6361
# Thread-safe model registry
@@ -125,19 +123,18 @@ def _build_fresh_from_config(config_path: str) -> tf.keras.Model:
125123
model(tf.zeros((1, cfg.model.layers[0]), dtype=tf.float32))
126124
return model
127125

128-
MODEL_REGISTRY = ModelRegistry()
129-
130-
kanx_inference_total = Counter(
131-
"kanx_inference_total",
132-
"Total successful inference requests handled by kanx.",
133-
["backend", "batch_size"],
134-
)
135-
kanx_inference_latency_seconds = Histogram(
136-
"kanx_inference_latency_seconds",
137-
"Inference latency for /api/predict in seconds.",
138-
["backend", "batch_size"],
139-
)
140-
126+
if "kanx_inference_total" not in globals():
127+
kanx_inference_total = Counter(
128+
"kanx_inference_total",
129+
"Total successful inference requests handled by kanx.",
130+
["backend", "batch_size"],
131+
)
132+
if "kanx_inference_latency_seconds" not in globals():
133+
kanx_inference_latency_seconds = Histogram(
134+
"kanx_inference_latency_seconds",
135+
"Inference latency for /api/predict in seconds.",
136+
["backend", "batch_size"],
137+
)
141138

142139
def _bucket_batch_size(batch_size: int) -> str:
143140
if batch_size <= 1:

0 commit comments

Comments
 (0)