Replace X-Request-Id with the trace ID and retire the guard suite

Step 6: downstream_client() no longer sends X-Request-Id, and request_id
is gone from the internal request bodies, models, function signatures
and log lines; correlation now travels as traceparent. The gateway's
public request_id stays (the contract tests require it) but is now the
trace ID, 32 hex digits and still a valid UUID, so the value the
frontend shows can be pasted into Tempo.

Step 7: delete tests/test_no_observability.py. It guarded the Phase 0
"no observability" state, which Phase 3 ends by design.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Movses Aslanyan
2026-10-13 19:48:27 +03:30
co-authored by Claude Opus 5.5
parent 1ab425dc44
commit 7ddb614ded
7 changed files with 38 additions and 140 deletions
+13 -6
View File
@@ -7,6 +7,7 @@ from fastapi import FastAPI, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, field_validator
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.instrumentation.utils import suppress_instrumentation
@@ -34,9 +35,7 @@ app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
# A shared, connection-pooling client for the simple read-only proxy routes
# below -- opening a fresh httpx.AsyncClient (and TCP connection) per request
# is real, needless overhead under concurrent load. orchestrator.py's
# downstream_client() stays per-request since it carries per-transaction
# headers (X-Request-Id).
# is real, needless overhead under concurrent load.
_proxy_client = httpx.AsyncClient(
timeout=settings.downstream_timeout_seconds,
limits=httpx.Limits(max_connections=100, max_keepalive_connections=50),
@@ -115,14 +114,22 @@ async def account_insights(account_id: str):
@app.post("/api/transactions", status_code=201)
async def submit_transaction(body: TransactionRequest):
request_id = str(uuid.uuid4())
request_id = _request_id()
try:
result = await orchestrator.create_transaction(body.model_dump(), request_id)
result = await orchestrator.create_transaction(body.model_dump())
except UpstreamFailure as exc:
return JSONResponse(
status_code=exc.status_code, content={"error": exc.message, "request_id": request_id}
)
return JSONResponse(status_code=201, content=result)
return JSONResponse(status_code=201, content={**result, "request_id": request_id})
def _request_id() -> str:
"""The response's `request_id` is the trace ID: paste it into Tempo to get
the whole request. 32 hex digits, which is still a valid UUID. Falls back to
a random one if no span is recording (telemetry not set up)."""
ctx = trace.get_current_span().get_span_context()
return format(ctx.trace_id, "032x") if ctx.is_valid else uuid.uuid4().hex
@app.get("/api/health/all")
+7 -9
View File
@@ -74,22 +74,22 @@ async def _run_chatty_health_probe(client: httpx.AsyncClient) -> None:
pass
async def create_transaction(payload: dict, request_id: str) -> dict:
async def create_transaction(payload: dict) -> dict:
start = time.perf_counter()
logger.info(f"start transaction for account {payload['account_id']} request_id={request_id}")
logger.info(f"start transaction for account {payload['account_id']}")
retry_storm = await chaos.retry_storm_enabled()
no_batching = await chaos.no_batching_enabled()
chatty_health = await chaos.chatty_health_enabled()
async with downstream_client(request_id) as client:
async with downstream_client() as client:
if chatty_health:
await _run_chatty_health_probe(client)
create_resp = await _post(
client,
f"{settings.ledger_url}/internal/transactions",
{**payload, "request_id": request_id},
payload,
)
if create_resp.status_code == 404:
raise UpstreamFailure(404, "account not found")
@@ -105,7 +105,6 @@ async def create_transaction(payload: dict, request_id: str) -> dict:
"account_id": created["account_id"],
"holder_name": created["holder_name"],
"category_id": created["category_id"],
"request_id": request_id,
}
if no_batching:
@@ -125,7 +124,7 @@ async def create_transaction(payload: dict, request_id: str) -> dict:
settle_resp = await _post(
client,
f"{settings.ledger_url}/internal/transactions/{tx_id}/{action}",
{"risk_score": risk_score, "request_id": request_id},
{"risk_score": risk_score},
)
if settle_resp.status_code >= 300:
raise UpstreamFailure(502, "ledger failed to finalise the transaction")
@@ -166,10 +165,10 @@ async def create_transaction(payload: dict, request_id: str) -> dict:
if summary_resp.status_code == 200:
summary = summary_resp.json()
except httpx.RequestError:
logger.exception(f"insights summary unavailable for request_id={request_id}")
logger.exception(f"insights summary unavailable for transaction {tx_id}")
elapsed_ms = (time.perf_counter() - start) * 1000
logger.info(f"finished transaction {tx_id} status={settled['status']} request_id={request_id}")
logger.info(f"finished transaction {tx_id} status={settled['status']}")
return {
"transaction_id": tx_id,
@@ -177,6 +176,5 @@ async def create_transaction(payload: dict, request_id: str) -> dict:
"risk_score": risk_score,
"balance_minor": settled["balance_minor"],
"summary": summary,
"request_id": request_id,
"elapsed_ms": elapsed_ms,
}