sql-dialect-master 1.1.7__tar.gz → 1.1.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. {sql_dialect_master-1.1.7/sql_dialect_master.egg-info → sql_dialect_master-1.1.8}/PKG-INFO +4 -2
  2. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/README.md +2 -1
  3. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/main.py +31 -4
  4. sql_dialect_master-1.1.8/backend/api/metrics.py +171 -0
  5. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/middleware.py +8 -1
  6. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/workers.py +34 -2
  7. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/config.py +12 -0
  8. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/metadata.py +2 -2
  9. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/pyproject.toml +18 -1
  10. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8/sql_dialect_master.egg-info}/PKG-INFO +4 -2
  11. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/sql_dialect_master.egg-info/SOURCES.txt +1 -0
  12. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/sql_dialect_master.egg-info/requires.txt +1 -0
  13. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/LICENSE +0 -0
  14. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/__init__.py +0 -0
  15. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/__init__.py +0 -0
  16. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/auth.py +0 -0
  17. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/client_identity.py +0 -0
  18. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/rate_limit_store.py +0 -0
  19. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/api/readiness.py +0 -0
  20. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/__init__.py +0 -0
  21. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/cache.py +0 -0
  22. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/column_hint_validation.py +0 -0
  23. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/constants.py +0 -0
  24. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/exceptions.py +0 -0
  25. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/function_call_scanner.py +0 -0
  26. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/function_semantics.py +0 -0
  27. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/functions_db.json +0 -0
  28. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/functions_lookup.py +0 -0
  29. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql.py +0 -0
  30. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/__init__.py +0 -0
  31. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/aggregations.py +0 -0
  32. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/boolean_conditions.py +0 -0
  33. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/core_extract.py +0 -0
  34. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/evidence.py +0 -0
  35. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/mappings.py +0 -0
  36. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/relations.py +0 -0
  37. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/templates.py +0 -0
  38. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_components/tokenizer.py +0 -0
  39. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_legacy.py +0 -0
  40. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/__init__.py +0 -0
  41. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/aggregations.py +0 -0
  42. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/clause_extract.py +0 -0
  43. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/dialect.py +0 -0
  44. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/intent.py +0 -0
  45. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/ir.py +0 -0
  46. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/models.py +0 -0
  47. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/orchestrator.py +0 -0
  48. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/predicates.py +0 -0
  49. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/renderer.py +0 -0
  50. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/resolution.py +0 -0
  51. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/suggestions.py +0 -0
  52. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/templates.py +0 -0
  53. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/nl2sql_pipeline/validation.py +0 -0
  54. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/p1_sql_scanner.py +0 -0
  55. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/p2_data_validation.py +0 -0
  56. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/parser.py +0 -0
  57. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/post_processor.py +0 -0
  58. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/rules.py +0 -0
  59. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/semantic_diff.py +0 -0
  60. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/sql_statements.py +0 -0
  61. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/transpiler.py +0 -0
  62. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/type_mapping.json +0 -0
  63. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/core/type_mapping.py +0 -0
  64. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/utils/__init__.py +0 -0
  65. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/backend/utils/validators.py +0 -0
  66. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/setup.cfg +0 -0
  67. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/sql_dialect_master.egg-info/dependency_links.txt +0 -0
  68. {sql_dialect_master-1.1.7 → sql_dialect_master-1.1.8}/sql_dialect_master.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sql-dialect-master
3
- Version: 1.1.7
3
+ Version: 1.1.8
4
4
  Summary: SQL Dialect Master - Multi-database SQL conversion engine
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -10,6 +10,7 @@ Requires-Dist: fastapi>=0.115.0
10
10
  Requires-Dist: uvicorn>=0.30.0
11
11
  Requires-Dist: pydantic>=2.9.0
12
12
  Requires-Dist: pydantic-settings>=2.0.0
13
+ Requires-Dist: prometheus-client<1.0.0,>=0.20.0
13
14
  Provides-Extra: dev
14
15
  Requires-Dist: hypothesis>=6.112.0; extra == "dev"
15
16
  Requires-Dist: pytest>=8.3.0; extra == "dev"
@@ -35,7 +36,7 @@ Dynamic: license-file
35
36
 
36
37
  Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
37
38
 
38
- Current release: 1.1.7
39
+ Current release: 1.1.8
39
40
 
40
41
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
41
42
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -372,3 +373,4 @@ public catalog responses use short `private` caching. Full deployment details
372
373
  will be documented in `docs/deployment.md`.
373
374
 
374
375
  See [`docs/deployment.md`](docs/deployment.md) for production deployment guidance.
376
+ Metrics configuration and scraping guidance are documented in the same guide.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
4
4
 
5
- Current release: 1.1.7
5
+ Current release: 1.1.8
6
6
 
7
7
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
8
8
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -339,3 +339,4 @@ public catalog responses use short `private` caching. Full deployment details
339
339
  will be documented in `docs/deployment.md`.
340
340
 
341
341
  See [`docs/deployment.md`](docs/deployment.md) for production deployment guidance.
342
+ Metrics configuration and scraping guidance are documented in the same guide.
@@ -30,6 +30,7 @@ from fastapi.responses import JSONResponse
30
30
  from pydantic import BaseModel, ConfigDict, Field
31
31
 
32
32
  from backend.api.auth import require_api_access
33
+ from backend.api.metrics import MetricsMiddleware, configure_runtime_metrics, metrics_response, record_transpile_request
33
34
  from backend.api.rate_limit_store import InMemoryRateLimitStore
34
35
  from backend.api.readiness import health_probe_response
35
36
  from backend.api.workers import BoundedWorkerPool, WorkerCapacityError
@@ -303,6 +304,12 @@ func_encyclopedia = FunctionEncyclopedia()
303
304
  type_mapper = TypeMapper()
304
305
  nl2sql_generator = NL2SQLGenerator()
305
306
 
307
+ configure_runtime_metrics(
308
+ transpiler_provider=lambda: transpiler,
309
+ worker_provider=_get_worker_pool,
310
+ limiter_provider=lambda: rate_limiter,
311
+ )
312
+
306
313
  # Request timing middleware with logging
307
314
  @app.middleware("http")
308
315
  async def add_process_time_header(request: Request, call_next):
@@ -320,6 +327,11 @@ async def add_process_time_header(request: Request, call_next):
320
327
  response.status_code, process_time)
321
328
  return response
322
329
 
330
+
331
+ # This is the outermost application middleware, so it also observes short
332
+ # circuit responses returned by rate limiting and worker-capacity guards.
333
+ app.add_middleware(MetricsMiddleware)
334
+
323
335
  # Dialect info for enhanced responses (from centralized config)
324
336
  DIALECT_INFO = get_dialect_api_info()
325
337
 
@@ -460,6 +472,10 @@ class APIResponse(BaseModel):
460
472
 
461
473
  # === API Endpoints ===
462
474
 
475
+ @app.get("/metrics", include_in_schema=False)
476
+ async def metrics_endpoint(request: Request):
477
+ return await metrics_response(request)
478
+
463
479
  @app.get("/", tags=["system"])
464
480
  async def root():
465
481
  """
@@ -560,11 +576,13 @@ async def convert_sql(request: ConvertRequest):
560
576
  source_dialect = request.source_dialect.strip().lower()
561
577
  target_dialect = request.target_dialect.strip().lower()
562
578
  if source_dialect not in SUPPORTED_DIALECTS:
579
+ record_transpile_request("unknown", "unknown", "validation_error")
563
580
  raise HTTPException(
564
581
  status_code=400,
565
582
  detail=f"Unsupported source dialect: {request.source_dialect}. Supported: {SUPPORTED_DIALECTS}"
566
583
  )
567
584
  if target_dialect not in SUPPORTED_DIALECTS:
585
+ record_transpile_request(source_dialect, "unknown", "validation_error")
568
586
  raise HTTPException(
569
587
  status_code=400,
570
588
  detail=f"Unsupported target dialect: {request.target_dialect}. Supported: {SUPPORTED_DIALECTS}"
@@ -572,12 +590,21 @@ async def convert_sql(request: ConvertRequest):
572
590
 
573
591
  # sqlglot parsing/transpilation is CPU-bound. Keep it off the event loop
574
592
  # so one large request cannot stall unrelated async requests.
575
- result = await _run_cpu_bound(
576
- transpiler.transpile,
577
- request.sql,
593
+ try:
594
+ result = await _run_cpu_bound(
595
+ transpiler.transpile,
596
+ request.sql,
597
+ source_dialect,
598
+ target_dialect,
599
+ request.pretty,
600
+ )
601
+ except HTTPException:
602
+ record_transpile_request(source_dialect, target_dialect, "error")
603
+ raise
604
+ record_transpile_request(
578
605
  source_dialect,
579
606
  target_dialect,
580
- request.pretty,
607
+ "success" if result.success else "error",
581
608
  )
582
609
  return ConvertResponse(
583
610
  success=result.success,
@@ -0,0 +1,171 @@
1
+ """Protected Prometheus metrics for the API process."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import secrets
6
+ from collections.abc import Callable
7
+
8
+ from fastapi import Request
9
+ from fastapi.responses import PlainTextResponse, Response
10
+ from prometheus_client import (
11
+ CONTENT_TYPE_LATEST,
12
+ CollectorRegistry,
13
+ Counter,
14
+ Gauge,
15
+ Histogram,
16
+ generate_latest,
17
+ )
18
+ from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily
19
+
20
+ from backend.core.config import settings
21
+ from backend.core.metadata import PROJECT_VERSION
22
+
23
+ REGISTRY = CollectorRegistry(auto_describe=True)
24
+
25
+ BUILD_INFO = Gauge("sdm_build_info", "SQL Dialect Master build information", ["version"], registry=REGISTRY)
26
+ BUILD_INFO.labels(version=PROJECT_VERSION).set(1)
27
+
28
+ HTTP_REQUESTS = Counter(
29
+ "sdm_http_requests_total",
30
+ "HTTP requests handled by the API",
31
+ ["method", "route", "status_class"],
32
+ registry=REGISTRY,
33
+ )
34
+ HTTP_DURATION = Histogram(
35
+ "sdm_http_request_duration_seconds",
36
+ "HTTP request duration in seconds",
37
+ ["method", "route", "status_class"],
38
+ registry=REGISTRY,
39
+ )
40
+ RATE_LIMIT_REJECTIONS = Counter(
41
+ "sdm_rate_limit_rejections_total",
42
+ "Rate-limited requests",
43
+ registry=REGISTRY,
44
+ )
45
+ TRANSPILE_REQUESTS = Counter(
46
+ "sdm_transpile_requests_total",
47
+ "Conversion requests by dialect pair and result",
48
+ ["source", "target", "result"],
49
+ registry=REGISTRY,
50
+ )
51
+
52
+ _transpiler_provider: Callable[[], object] | None = None
53
+ _worker_provider: Callable[[], object] | None = None
54
+ _limiter_provider: Callable[[], object] | None = None
55
+
56
+
57
+ def configure_runtime_metrics(*, transpiler_provider=None, worker_provider=None, limiter_provider=None) -> None:
58
+ """Register process-local runtime providers used when /metrics is scraped."""
59
+ global _transpiler_provider, _worker_provider, _limiter_provider
60
+ _transpiler_provider = transpiler_provider
61
+ _worker_provider = worker_provider
62
+ _limiter_provider = limiter_provider
63
+
64
+
65
+ class RuntimeCollector:
66
+ """Read low-frequency runtime snapshots without copying them per request."""
67
+
68
+ def collect(self):
69
+ if _transpiler_provider is not None:
70
+ try:
71
+ stats = _transpiler_provider().get_stats()
72
+ cache = stats.get("cache", {})
73
+ if cache.get("enabled", True) is not False:
74
+ yield CounterMetricFamily("sdm_transpile_cache_hits_total", "Transpiler cache hits", value=cache.get("hits", 0))
75
+ yield CounterMetricFamily("sdm_transpile_cache_misses_total", "Transpiler cache misses", value=cache.get("misses", 0))
76
+ yield CounterMetricFamily("sdm_transpile_cache_evictions_total", "Transpiler cache evictions", value=cache.get("evictions", 0))
77
+ yield GaugeMetricFamily("sdm_transpile_cache_size", "Current transpiler cache size", value=cache.get("size", 0))
78
+ except Exception:
79
+ pass
80
+
81
+ if _worker_provider is not None:
82
+ try:
83
+ stats = _worker_provider().stats()
84
+ yield GaugeMetricFamily("sdm_api_worker_capacity", "API worker pool capacity", value=stats["capacity"])
85
+ yield GaugeMetricFamily("sdm_api_worker_in_use", "API worker slots in use", value=stats["in_use"])
86
+ yield CounterMetricFamily("sdm_api_worker_rejections_total", "API worker capacity rejections", value=stats["rejections"])
87
+ yield CounterMetricFamily("sdm_api_request_timeouts_total", "API request timeouts", value=stats["timeouts"])
88
+ except Exception:
89
+ pass
90
+
91
+ if _limiter_provider is not None:
92
+ try:
93
+ stats = _limiter_provider().get_stats()
94
+ if stats.get("backend") == "memory":
95
+ yield GaugeMetricFamily("sdm_rate_limit_active_clients", "Active in-memory rate-limit clients", value=stats.get("active_clients", 0))
96
+ except Exception:
97
+ pass
98
+
99
+
100
+ REGISTRY.register(RuntimeCollector())
101
+
102
+
103
+ def normalize_method(method: str) -> str:
104
+ return method if method in {"GET", "POST", "HEAD", "OPTIONS"} else "other"
105
+
106
+
107
+ def route_template(request: Request) -> str:
108
+ route = request.scope.get("route")
109
+ template = getattr(route, "path_format", None) or getattr(route, "path", None)
110
+ return template if template else "other"
111
+
112
+
113
+ def status_class(status_code: int) -> str:
114
+ return f"{status_code // 100}xx" if 100 <= status_code < 600 else "other"
115
+
116
+
117
+ def record_http_request(request: Request, status_code: int, duration: float) -> None:
118
+ if request.url.path == "/metrics":
119
+ return
120
+ labels = (normalize_method(request.method), route_template(request), status_class(status_code))
121
+ HTTP_REQUESTS.labels(*labels).inc()
122
+ HTTP_DURATION.labels(*labels).observe(duration)
123
+
124
+
125
+ def record_rate_limit_rejection() -> None:
126
+ RATE_LIMIT_REJECTIONS.inc()
127
+
128
+
129
+ def record_transpile_request(source: str, target: str, result: str) -> None:
130
+ TRANSPILE_REQUESTS.labels(source=source, target=target, result=result).inc()
131
+
132
+
133
+ def _authorized(request: Request) -> bool:
134
+ configured = settings.metrics_token
135
+ expected = configured.get_secret_value().strip() if configured else ""
136
+ supplied = request.headers.get("X-Metrics-Token", "")
137
+ return bool(expected and supplied and secrets.compare_digest(supplied, expected))
138
+
139
+
140
+ async def metrics_response(request: Request) -> Response:
141
+ if not settings.metrics_enabled:
142
+ return Response(status_code=404)
143
+ if not _authorized(request):
144
+ return Response(status_code=401, content="Metrics token required")
145
+ return PlainTextResponse(generate_latest(REGISTRY), media_type=CONTENT_TYPE_LATEST)
146
+
147
+
148
+ class MetricsMiddleware:
149
+ """ASGI middleware that records final HTTP status and elapsed time."""
150
+
151
+ def __init__(self, app):
152
+ self.app = app
153
+
154
+ async def __call__(self, scope, receive, send):
155
+ if scope.get("type") != "http":
156
+ await self.app(scope, receive, send)
157
+ return
158
+ import time
159
+
160
+ started = time.perf_counter()
161
+ status_code = 500
162
+
163
+ async def send_wrapper(message):
164
+ nonlocal status_code
165
+ if message.get("type") == "http.response.start":
166
+ status_code = message.get("status", 500)
167
+ await send(message)
168
+
169
+ await self.app(scope, receive, send_wrapper)
170
+ request = Request(scope)
171
+ record_http_request(request, status_code, time.perf_counter() - started)
@@ -20,6 +20,7 @@ from starlette.concurrency import run_in_threadpool
20
20
  from backend.core.exceptions import ErrorCode
21
21
 
22
22
  from .client_identity import resolve_client_ip
23
+ from .metrics import record_rate_limit_rejection
23
24
  from .rate_limit_store import InMemoryRateLimitStore, RateLimitStore, create_rate_limit_store
24
25
  from .readiness import health_probe_response
25
26
 
@@ -108,7 +109,7 @@ class RateLimitMiddleware(BaseHTTPMiddleware):
108
109
 
109
110
  async def dispatch(self, request: Request, call_next) -> Response:
110
111
  is_health_probe = (
111
- request.url.path in {"/health", "/", "/ready", "/health/deep"}
112
+ request.url.path in {"/health", "/", "/ready", "/health/deep", "/metrics"}
112
113
  and request.method in {"GET", "HEAD"}
113
114
  )
114
115
  # Browser CORS preflight requests carry no business payload and are
@@ -133,6 +134,7 @@ class RateLimitMiddleware(BaseHTTPMiddleware):
133
134
  is_allowed, remaining, reset_time = await run_in_threadpool(self.limiter.is_allowed, client_id)
134
135
  rate_limit_checked = True
135
136
  if not is_allowed:
137
+ record_rate_limit_rejection()
136
138
  logger.warning("Rate limit exceeded for client: %s", _sanitize_log_value(client_id))
137
139
  return JSONResponse(
138
140
  status_code=429,
@@ -164,6 +166,9 @@ class RateLimitMiddleware(BaseHTTPMiddleware):
164
166
  if is_health_probe:
165
167
  if request.url.path in {"/ready", "/health/deep"}:
166
168
  return await health_probe_response(request)
169
+ if request.url.path == "/metrics":
170
+ from .metrics import metrics_response
171
+ return await metrics_response(request)
167
172
  return await call_next(request)
168
173
  response = await call_next(request)
169
174
  if rate_limit_checked:
@@ -386,6 +391,8 @@ class CacheControlMiddleware(BaseHTTPMiddleware):
386
391
  if request.method == "OPTIONS":
387
392
  return None
388
393
  path = request.url.path
394
+ if path == "/metrics":
395
+ return "no-store"
389
396
  if path in {"/docs", "/redoc", "/openapi.json"}:
390
397
  return None
391
398
  if request.method == "POST" and path.startswith("/api/"):
@@ -24,22 +24,54 @@ class BoundedWorkerPool:
24
24
  self._slots = BoundedSemaphore(workers + queue_size)
25
25
  self._executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="sdm-api")
26
26
  self._shutdown_lock = Lock()
27
+ self._stats_lock = Lock()
28
+ self._capacity = workers + queue_size
29
+ self._in_use = 0
30
+ self._rejections = 0
31
+ self._timeouts = 0
27
32
  self._shutdown = False
28
33
 
29
34
  async def run(self, function, *args, timeout: float):
30
35
  if not self._slots.acquire(blocking=False):
36
+ with self._stats_lock:
37
+ self._rejections += 1
31
38
  raise WorkerCapacityError("Request processing capacity is exhausted")
39
+ with self._stats_lock:
40
+ self._in_use += 1
32
41
  try:
33
42
  future = self._executor.submit(function, *args)
34
43
  except BaseException:
35
44
  self._slots.release()
45
+ with self._stats_lock:
46
+ self._in_use -= 1
36
47
  raise
37
- future.add_done_callback(lambda _future: self._slots.release())
48
+
49
+ def release_slot(_future):
50
+ self._slots.release()
51
+ with self._stats_lock:
52
+ self._in_use -= 1
53
+
54
+ future.add_done_callback(release_slot)
38
55
  wrapped = asyncio.wrap_future(future)
39
56
  # A timed-out caller no longer awaits this result. Retrieve exceptions
40
57
  # to avoid an unhandled-future warning when background work later fails.
41
58
  wrapped.add_done_callback(lambda completed: None if completed.cancelled() else completed.exception())
42
- return await asyncio.wait_for(asyncio.shield(wrapped), timeout=timeout)
59
+ try:
60
+ return await asyncio.wait_for(asyncio.shield(wrapped), timeout=timeout)
61
+ except asyncio.TimeoutError:
62
+ with self._stats_lock:
63
+ self._timeouts += 1
64
+ raise
65
+
66
+ def stats(self) -> dict[str, int]:
67
+ """Return a thread-safe snapshot of pool capacity counters."""
68
+ with self._stats_lock:
69
+ return {
70
+ "capacity": self._capacity,
71
+ "in_use": self._in_use,
72
+ "rejections": self._rejections,
73
+ "timeouts": self._timeouts,
74
+ }
43
75
 
44
76
  def shutdown(self) -> None:
45
77
  """Cancel queued work; already-running calls retain their slots."""
@@ -276,6 +276,10 @@ class AppSettings(BaseSettings):
276
276
  # Readiness probes. SecretStr keeps the value out of settings reprs and
277
277
  # structured logs while still allowing deployment through SDM_ env vars.
278
278
  health_probe_token: Optional[SecretStr] = None
279
+
280
+ # Prometheus metrics are opt-in and use a dedicated secret.
281
+ metrics_enabled: bool = False
282
+ metrics_token: Optional[SecretStr] = None
279
283
 
280
284
  # Security settings
281
285
  security_check_enabled: bool = True
@@ -292,6 +296,14 @@ class AppSettings(BaseSettings):
292
296
  self.parser_max_sql_length = self.transpiler_max_sql_length
293
297
  return self
294
298
 
299
+ @model_validator(mode="after")
300
+ def _validate_metrics_token(self) -> "AppSettings":
301
+ """Require a non-blank dedicated token when metrics are enabled."""
302
+ token = self.metrics_token.get_secret_value().strip() if self.metrics_token else ""
303
+ if self.metrics_enabled and not token:
304
+ raise ValueError("metrics_token is required when metrics_enabled is true")
305
+ return self
306
+
295
307
  @field_validator("log_level", mode="before")
296
308
  @classmethod
297
309
  def _normalize_log_level(cls, value: str) -> str:
@@ -17,8 +17,8 @@ Design rules:
17
17
  from __future__ import annotations
18
18
 
19
19
  # ── Release version facts (sole source of truth) ────────────────────────
20
- PROJECT_VERSION = "1.1.7"
21
- API_VERSION = "1.1.7"
20
+ PROJECT_VERSION = "1.1.8"
21
+ API_VERSION = "1.1.8"
22
22
  # Frontend v2 architecture — independent of the product release version.
23
23
  FRONTEND_ARCHITECTURE_VERSION = 2
24
24
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sql-dialect-master"
3
- version = "1.1.7"
3
+ version = "1.1.8"
4
4
  description = "SQL Dialect Master - Multi-database SQL conversion engine"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -10,6 +10,7 @@ dependencies = [
10
10
  "uvicorn>=0.30.0",
11
11
  "pydantic>=2.9.0",
12
12
  "pydantic-settings>=2.0.0",
13
+ "prometheus-client>=0.20.0,<1.0.0",
13
14
  ]
14
15
 
15
16
  [project.optional-dependencies]
@@ -51,3 +52,19 @@ exclude = ["backend.tests*", "backend.benchmarks*"]
51
52
  testpaths = ["backend/tests"]
52
53
  python_files = ["test_*.py"]
53
54
  addopts = "-v --tb=short"
55
+
56
+ [tool.coverage.run]
57
+ source = ["backend"]
58
+ omit = [
59
+ "backend/tests/*",
60
+ "backend/benchmarks/*",
61
+ ]
62
+
63
+ [tool.coverage.report]
64
+ show_missing = true
65
+ skip_covered = false
66
+ fail_under = 93
67
+ exclude_lines = [
68
+ "pragma: no cover",
69
+ "if __name__ == .__main__.:",
70
+ ]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sql-dialect-master
3
- Version: 1.1.7
3
+ Version: 1.1.8
4
4
  Summary: SQL Dialect Master - Multi-database SQL conversion engine
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
@@ -10,6 +10,7 @@ Requires-Dist: fastapi>=0.115.0
10
10
  Requires-Dist: uvicorn>=0.30.0
11
11
  Requires-Dist: pydantic>=2.9.0
12
12
  Requires-Dist: pydantic-settings>=2.0.0
13
+ Requires-Dist: prometheus-client<1.0.0,>=0.20.0
13
14
  Provides-Extra: dev
14
15
  Requires-Dist: hypothesis>=6.112.0; extra == "dev"
15
16
  Requires-Dist: pytest>=8.3.0; extra == "dev"
@@ -35,7 +36,7 @@ Dynamic: license-file
35
36
 
36
37
  Enterprise-grade multi-database SQL conversion engine supporting 12 database dialects.
37
38
 
38
- Current release: 1.1.7
39
+ Current release: 1.1.8
39
40
 
40
41
  [![Python 3.11+](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
41
42
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
@@ -372,3 +373,4 @@ public catalog responses use short `private` caching. Full deployment details
372
373
  will be documented in `docs/deployment.md`.
373
374
 
374
375
  See [`docs/deployment.md`](docs/deployment.md) for production deployment guidance.
376
+ Metrics configuration and scraping guidance are documented in the same guide.
@@ -6,6 +6,7 @@ backend/api/__init__.py
6
6
  backend/api/auth.py
7
7
  backend/api/client_identity.py
8
8
  backend/api/main.py
9
+ backend/api/metrics.py
9
10
  backend/api/middleware.py
10
11
  backend/api/rate_limit_store.py
11
12
  backend/api/readiness.py
@@ -3,6 +3,7 @@ fastapi>=0.115.0
3
3
  uvicorn>=0.30.0
4
4
  pydantic>=2.9.0
5
5
  pydantic-settings>=2.0.0
6
+ prometheus-client<1.0.0,>=0.20.0
6
7
 
7
8
  [dev]
8
9
  hypothesis>=6.112.0