Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion finverify-terminal/backend/app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@
from .evaluator import build_query_response
from .financial import handle_financial_reasoning
from .router import classify_query
from .middleware import RequestIDMiddleware, install_request_id_logging

from .market import (
get_quotes,
get_market_indices,
Expand All @@ -75,6 +77,7 @@

load_dotenv()
logger = logging.getLogger(__name__)
install_request_id_logging()
financial_document_service = FinancialDocumentService()

# ---------------------------------------------------------------------------
Expand All @@ -95,7 +98,8 @@
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*", "X-FinVerify-Key"],
allow_headers=["*", "X-FinVerify-Key", "X-Request-ID"],
expose_headers=["X-Request-ID"],
)

# Attach rate limiter if available
Expand All @@ -116,6 +120,7 @@ async def _rate_limit_handler(request: Request, exc: RateLimitExceeded):
content={"detail": "Rate limit exceeded — 100 requests/minute. Please slow down."},
)

app.add_middleware(RequestIDMiddleware)
# ---------------------------------------------------------------------------
# LLM Inference — Provider-agnostic (OpenAI-compatible Chat Completions)
# ---------------------------------------------------------------------------
Expand Down
85 changes: 85 additions & 0 deletions finverify-terminal/backend/app/middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"""
Request-ID propagation and per-request logging context middleware.

Assigns a unique correlation ID (from incoming X-Request-ID header or a fresh
UUID4) to every HTTP request via contextvars so concurrent async handlers and
downstream calls (/query -> DVL -> market/RAG) emit traceable logs without
colliding.
"""

import logging
import time
import uuid
from contextvars import ContextVar

from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response

REQUEST_ID_HEADER = "X-Request-ID"

logger = logging.getLogger("finverify.request")

request_id_ctx: ContextVar[str] = ContextVar("request_id", default="-")


def get_request_id() -> str:
"""Return the active correlation ID for the current async execution context."""
return request_id_ctx.get()


class RequestIDLogFilter(logging.Filter):
"""Logging filter that attaches `request_id` to every LogRecord."""

def filter(self, record: logging.LogRecord) -> bool:
record.request_id = get_request_id()
return True


def install_request_id_logging() -> None:
"""Attach RequestIDLogFilter to the root logger and all existing handlers.

Idempotent: safe to call multiple times at startup or in tests.
"""
root_logger = logging.getLogger()
if not any(isinstance(f, RequestIDLogFilter) for f in root_logger.filters):
root_logger.addFilter(RequestIDLogFilter())

for handler in root_logger.handlers:
if not any(isinstance(f, RequestIDLogFilter) for f in handler.filters):
handler.addFilter(RequestIDLogFilter())

# Ensure even newly created handlers/loggers get `request_id` on LogRecord
old_factory = logging.getLogRecordFactory()
if not getattr(old_factory, "_has_request_id", False):
def record_factory(*args, **kwargs):
record = old_factory(*args, **kwargs)
if not hasattr(record, "request_id"):
record.request_id = get_request_id()
return record

record_factory._has_request_id = True # type: ignore[attr-defined]
logging.setLogRecordFactory(record_factory)


class RequestIDMiddleware(BaseHTTPMiddleware):
"""Generates or propagates X-Request-ID per request and echoes it in response headers."""

async def dispatch(self, request: Request, call_next) -> Response:
incoming_id = request.headers.get(REQUEST_ID_HEADER, "").strip()
req_id = incoming_id or str(uuid.uuid4())
token = request_id_ctx.set(req_id)
start = time.perf_counter()
try:
response = await call_next(request)
response.headers[REQUEST_ID_HEADER] = req_id
logger.info(
"%s %s -> %d (%.1f ms)",
request.method,
request.url.path,
response.status_code,
(time.perf_counter() - start) * 1000,
)
return response
finally:
request_id_ctx.reset(token)
81 changes: 81 additions & 0 deletions finverify-terminal/backend/tests/test_request_id_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import asyncio
import logging
import uuid

import httpx
import pytest

from app.main import app
from app.middleware import get_request_id


@pytest.mark.asyncio
async def test_generates_request_id_when_header_missing():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
resp = await client.get("/health")

assert resp.status_code == 200
req_id = resp.headers.get("X-Request-ID")
assert req_id is not None
parsed = uuid.UUID(req_id, version=4)
assert str(parsed) == req_id


@pytest.mark.asyncio
async def test_propagates_incoming_request_id_and_binds_to_logs(caplog):
custom_id = "req-trace-abc-999"
transport = httpx.ASGITransport(app=app)
with caplog.at_level(logging.INFO):
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
resp = await client.post(
"/verify",
json={"question": "What was revenue?", "raw_number": 100.0},
headers={"X-Request-ID": custom_id},
)

assert resp.status_code == 200
assert resp.headers.get("X-Request-ID") == custom_id
assert any(getattr(rec, "request_id", None) == custom_id for rec in caplog.records)
assert get_request_id() == "-"


@pytest.mark.asyncio
async def test_concurrent_requests_have_distinct_non_colliding_request_ids(caplog):
test_logger = logging.getLogger("test.concurrency")
captured: dict[str, list[str]] = {"req_a": [], "req_b": []}

@app.get("/_test/concurrent-trace")
async def _concurrent_probe(tag: str):
first_id = get_request_id()
test_logger.info("start %s", tag)
await asyncio.sleep(0.03)
second_id = get_request_id()
test_logger.info("end %s", tag)
captured[tag] = [first_id, second_id]
return {"tag": tag, "request_id": second_id}

try:
transport = httpx.ASGITransport(app=app)
with caplog.at_level(logging.INFO, logger="test.concurrency"):
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
resp_a, resp_b = await asyncio.gather(
client.get("/_test/concurrent-trace", params={"tag": "req_a"}),
client.get("/_test/concurrent-trace", params={"tag": "req_b"}),
)

id_a = resp_a.headers["X-Request-ID"]
id_b = resp_b.headers["X-Request-ID"]

assert id_a != id_b
assert captured["req_a"] == [id_a, id_a]
assert captured["req_b"] == [id_b, id_b]

logs_a = [r.request_id for r in caplog.records if "req_a" in r.getMessage()]
logs_b = [r.request_id for r in caplog.records if "req_b" in r.getMessage()]
assert logs_a == [id_a, id_a]
assert logs_b == [id_b, id_b]
finally:
app.router.routes = [
r for r in app.router.routes if getattr(r, "path", None) != "/_test/concurrent-trace"
]