Implement Phase 0b base project against the frozen test contract

All seven services (gateway, ledger, fraud, sanctions, insights, notifier,
audit), db/schema.sql plus optional_indexes.sql, scripts/seed.py and
smoke.py, the gateway-served frontend, and docker-compose.yml. Plain-text
stdlib logging and a weak manual X-Request-Id only -- no observability yet,
by design, per test_no_observability.py. Implements all 13 named chaos-flag
pathologies from docs/PATHOLOGIES.md behind Redis-backed runtime flags.

make smoke and make test-contract pass; make test-baseline and
make test-pathology pass except for a handful of load-sensitive tests
documented in tests/README.md rather than papered over.
This commit is contained in:
Movses Aslanyan
2026-09-05 08:12:30 +03:30
parent ccf1783779
commit 91afea92a1
51 changed files with 2757 additions and 0 deletions
View File
+77
View File
@@ -0,0 +1,77 @@
import httpx
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from common.http import downstream_client
from common.logging_config import configure_logging
from common.redis_client import redis_client
from common.settings import settings
from . import chaos
from .scoring import score
SERVICE_NAME = "fraud"
logger = configure_logging(SERVICE_NAME)
app = FastAPI(title=SERVICE_NAME)
class ScoreRequest(BaseModel):
account_id: str
holder_name: str
category_id: int | None = None
amount_minor: int
request_id: str = "unknown"
@app.get("/")
async def root():
return {"service": SERVICE_NAME, "version": "0.1.0"}
@app.get("/healthz")
async def healthz(request: Request):
if request.headers.get("X-Ledgerline-Probe") == "chatty-health":
logger.info("received chatty-health healthz probe from gateway")
return {"status": "ok", "service": SERVICE_NAME}
@app.get("/readyz")
async def readyz():
try:
await redis_client.ping()
except Exception as exc:
logger.exception(f"readyz check failed: {exc}")
return JSONResponse(status_code=503, content={"status": "unavailable"})
return {"status": "ok"}
@app.post("/internal/score")
async def score_transaction(body: ScoreRequest):
logger.info(f"scoring account {body.account_id} request_id={body.request_id}")
await redis_client.incr("fraud:calls_total")
if await chaos.blocking_event_loop_enabled():
logger.info(f"blocking_event_loop chaos engaged for request_id={body.request_id}")
chaos.synchronous_cpu_work()
async with downstream_client(body.request_id) as client:
try:
resp = await client.post(
f"{settings.sanctions_url}/internal/lookup",
json={"holder_name": body.holder_name, "request_id": body.request_id},
)
except httpx.TimeoutException:
logger.exception(f"sanctions lookup timed out for request_id={body.request_id}")
return JSONResponse(status_code=504, content={"error": "sanctions lookup timed out"})
except httpx.RequestError as exc:
logger.exception(f"sanctions lookup failed for request_id={body.request_id}: {exc}")
return JSONResponse(status_code=502, content={"error": "sanctions lookup failed"})
if resp.status_code >= 300:
logger.info(f"sanctions returned {resp.status_code} for request_id={body.request_id}")
return JSONResponse(status_code=502, content={"error": "sanctions lookup failed"})
matched = resp.json().get("matched", False)
risk_score = score(body.category_id, matched)
return {"risk_score": risk_score, "matched": matched}
+22
View File
@@ -0,0 +1,22 @@
"""blocking_event_loop -- phase-0-base-project-spec.md §7. Owned by `fraud`."""
import hashlib
import time
from common.chaos_flags import is_enabled
_CPU_WORK_SECONDS = 0.15
async def blocking_event_loop_enabled() -> bool:
return await is_enabled("blocking_event_loop")
def synchronous_cpu_work() -> None:
"""~120ms of real, synchronous, CPU-bound work run directly inside an
`async def` handler -- no run_in_executor/to_thread. This is the point:
it blocks the whole event loop, serialising every other in-flight
request on this worker for the duration."""
deadline = time.perf_counter() + _CPU_WORK_SECONDS
data = b"ledgerline-fraud-scoring"
while time.perf_counter() < deadline:
data = hashlib.sha256(data).digest()
+18
View File
@@ -0,0 +1,18 @@
import random
def category_weight(category_id: int | None) -> float:
"""A fake but deterministic-ish stand-in for merchant_categories.risk_weight
(fraud has no direct DB access -- Redis only, per phase-0-base-project-spec.md §4).
The business logic does not need to be correct, only to produce a plausible
spread of scores."""
if category_id is None:
return 0.3
return 0.01 + (category_id % 45) / 44 * 0.94
def score(category_id: int | None, matched: bool) -> float:
base = category_weight(category_id) * random.uniform(0.05, 0.3)
if matched:
return min(1.0, base + random.uniform(0.55, 0.9))
return min(1.0, base)