Chương 04 — WebAPI Hiệu năng Cao (REST/gRPC/SSE), Xác thực JWT/RBAC, FastAPI/Pydantic v2, Đầu dò K8s & Kiểm thử Tải
Từ REST Idempotency-Key/gRPC/GraphQL/SSE, HS256 JWT (chặn alg:none) + HMAC API Keys + RBAC & Pydantic v2 Strict (RFC 9457) đến Pure ASGI vs BaseHTTPMiddleware (4.03x RPS, TTFT 29.9 vs 155.5 ms), asyncio.to_thread (7.33x), K8s Probes + SIGTERM Drain, Kingman VUT & Coordinated Omission (63.92x).
Unit ID:
T2-P1-U04
Track & Part: Track 2 (EDAI) — Part 1: Software, Backend & Container Engineering Foundations (part-01-software-systems-foundations)
Truy xuất Giáo trình Gốc (R26&AIDE 1 R25): Bài 4 Fundamentals of Engineering — WebAPI (API architecture styles,Authentication mechanisms,FastAPI: from fundamentals to optimization,Request validation and type enforcement,Middleware,API healthcheck,Performance testing: metrics and guideline,FastAPI, Locust) trong 02-track-edai-raw-curriculum.md và đề cương nâng cấp 02-track-2-edai-sota-syllabus.md
Bài thực hành Song hành (Lab 04):labs/lab-04-fastapi-auth-tests-and-locust/(webapi_serving_lab)
Tình huống Mở đầu: Năm Thảm họa API Sản xuất Khi Đưa Mô hình AI Lên Mạng#
Ở môi trường phát triển, một dịch vụ FastAPI chỉ cần vài dòng @app.post("/predict") trả JSON là chạy trơn tru trên localhost. Nhưng khi mở lưu lượng cho hàng nghìn ứng dụng khách và cụm Kubernetes tự co giãn, năm lỗ hổng kiến trúc kinh điển sẽ biến một dịch vụ tưởng chừng đơn giản thành sự cố gián đoạn toàn hệ thống:
- Vòng lặp Chết
CrashLoopBackOffTừ Đầu dò Sức khỏe K8s: Gắn cảlivenessProbelẫnreadinessProbevào chung một đường dẫn/healthcó truy vấn kiểm tra PostgreSQL/Redis (timeoutSeconds: 2). Khi cơ sở dữ liệu chớp nghẽn5 giây, kubelet đồng loạt đánh dấu mọi pod mất sống (liveness failed) và khởi động lại 100% cụm cùng lúc; ngay khi DB hồi phục, bão kết nối khởi động lạnh (thundering herd) lại đánh sập DB thêm một lần nữa. - Đóng băng Toàn bộ Worker Do Gọi Hàm Đồng bộ Trong
async def: Một lời gọitime.sleep(),requests.post(), hay phân tích JSON nặng nằm trong handlerasync defkhóa cứng luồng Event Loop đơn của Uvicorn. Trong kiểm chứng thực tế trênFastAPIcủa Lab 04 (16yêu cầu đồng thời \(\times 20\text{ ms}\)), hàm chặn đồng bộ kéo tổng thời gian lên368.01 msvà khiến đầu dò/health/liveđứng chờ tới367.91 ms, so với50.19 ms(nhanh hơn7.33x) khi đẩy sangasyncio.to_thread. BaseHTTPMiddlewareĐệm Luồng Phá HỏngTTFTCủa LLM Streaming (SSE): Dùng@app.middleware("http")của FastAPI để gắn header log hoặc đọc trước thân phản hồi trên luồngtext/event-streambuộc Starlette tạo nhóm tác vụ AnyIO và luồng bộ nhớ trung gian. Trên Lab 04, kiến trúc này làm thông lượng giảm4.03x(18,073.6xuống4,482.7 RPS) và khi đệm đọc iterator còn đẩy độ trễ token đầu tiênTTFTtừ29.87 mslên155.48 ms(5.21xchậm hơn)!- Lỗ hổng
alg: "none", Rò rỉ Timing & Ép kiểu Thầm lặng: Thư viện xác thực tin trường"alg"do kẻ tấn công gửi trong headerJWT(alg: "none"bỏ qua chữ ký hoặc hoán đổiRS256 -> HS256bằng khóa công khai), so sánh API Key bằng toán tử==rò rỉ từng byte qua thời gian phản hồi, hoặc đểPydanticmặc định âm thầm ép chuỗi"123"thành số123và lọt trường lạ gây lỗi suy luận mô hình. - Báo cáo
p99 = 2.72 msẢo Giác DoCoordinated Omission: Bộ kiểm thử tải vòng đóng (closed-loop) dùng người dùng ảo đợi phản hồi xong mới gửi tiếp khiến khi máy chủ đóng băng160 ms, gần như toàn bộ mẫu rơi ngoài cửa sổ đo (p99 = 2.72 ms). Trong khi đó, bài đo vòng mở (open-loop) ở152.5 RPS(nhưk6constant-arrival-rate) phơi bày hàng đợi dồn ứ thật lên tớip99 = 173.87 ms(sai lệch gấp63.92x!).
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 04 và gói thực hành webapi_serving_lab, kỹ sư Dữ liệu & AI có đủ năng lực để:
- Lựa chọn & Thiết kế Chuẩn 5 Kiến trúc WebAPI (
REST,gRPC,GraphQL,WebSockets,SSE): Phân biệt rạch ròi khung giao vận (HTTP/1.1vsHTTP/2multiplexing), định dạng dây (JSON UTF-8 vs nhị phânProtobuf), tính bất biếnIdempotency-KeychoPOST, tránh bẫy cân bằng tải L4 TCP trêngRPCvàN+1resolver trênGraphQL, đồng thời làm chủ luồng một chiềuSSE(text/event-stream) cho suy luận LLM. - Thiết kế Lớp Bảo mật
AuthN/AuthZChuẩn RFC & Chống Tấn công Timing/Bypass: Lưu trữ API Key bằng bămHMAC-SHA256+ đối chiếu hằng thời gian (hmac.compare_digest), tự cài đặt & kiểm chứngJWTHS256chuẩn RFC 7519 với danh sách thuật toán cho phép tường minh (chặnalg: "none", kiểmexp/nbf/iss/aud), và phân tách chuẩn xác401 Unauthorizedvs403 Forbiddentheo phạm vi RBAC (bao gồm/metricsvà/v1/bench/*). - Tối ưu Hóa Vòng đời ASGI
FastAPI& Kiểm định Nghiêm ngặtPydantic v2+RFC 9457: Quản lý singleton (lifespan), bộ nhớ đệm phụ thuộc theo yêu cầu (Depends), tách bạchasync defvớidef(bể luồng AnyIO40tokens) /asyncio.to_thread, viết Pure ASGI Middleware không đệm luồng cho Token Bucket429 Retry-After(có chặn trầnOrderedDictLRU+TTL vàdeque(maxlen)), gắn OpenTelemetry (W3C traceparent, metric low-cardinality), épConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)trên lõi Rustpydantic-core, và trả lỗi chuẩnRFC 9457(application/problem+json). - Triển khai Đầu dò Kubernetes (
startup,liveness,readiness) & Ngắt Êm ÁiSIGTERM: Tách rời/health/live(chỉ kiểm event loop) khỏi/health/ready(kiểm phụ thuộc + cờdraining), tránh vòng xoáy khởi động lại cụm, và phối hợppreStopcùng bộ đếm yêu cầu đang chạy (in_flight). - Mô hình hóa Hiệu năng Theo Lý thuyết Hàng đợi & Kiểm thử Tải SOTA (
Locustvsk6): Áp dụng Định luật Little (\(L = \lambda W\)), Phương trình Kingman/Sakasegawa VUT giải thích khúc khuỷu bão hòa \(\rho \to 1\), phân tích khuếch đại đuôi fan-out, nhận diện Coordinated Omission, và nghiệm thu đầy đủ19/19capytesttrênwebapi_serving_lab.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P1-U04, R26 + AIDE 1 R25)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R26 & AIDE 1 R25) |
Nâng cấp Chuẩn SOTA 2026 (ch-04) |
Mục trong Chương 04 | Tạo tác & Kiểm thử (webapi_serving_lab) |
|---|---|---|---|
1. API architecture styles (R26) |
REST (ràng buộc Fielding, động từ HTTP ngữ nghĩa, Idempotency-Key 409), gRPC (HTTP/2 + Protobuf, 4 chế độ RPC, bẫy cân bằng tải L4 vs L7), GraphQL (SDL, DataLoader chống N+1, giới hạn độ sâu/chi phí), WebSockets (101 song công toàn phần) vs. SSE (text/event-stream, Last-Event-ID, LLM TTFT/TPOT) |
Trụ cột 1 (§1.1) + Trụ cột 3 (Playbook A) + Mermaid 1 + Widget 1 | app.py (GET /v1/stream luồng SSE thật, POST /v1/predict kèm Idempotency-Key), Tests 3, 7 |
2. Authentication mechanisms (R26) |
Ranh giới AuthN (401) vs. AuthZ (403); API Keys băm HMAC-SHA256 + hmac.compare_digest; OAuth 2.0 (PKCE, Client Credentials); JWT RFC 7519 (HS256 vs EdDSA/RS256, kiểm exp/nbf/iss/aud, chặn alg: "none" & nhầm lẫn khóa RS256 -> HS256); RBAC scopes (reader, scorer, admin) |
Trụ cột 1 (§1.2) + Trụ cột 3 (Case 4) + Mermaid 2 | schemas_and_auth.py (APIKeyRegistry, encode_hs256_jwt, verify_hs256_jwt, require_scope), Tests 4, 5, 6 |
3. FastAPI: from fundamentals to optimization (R26) |
ASGI 3.0 (scope, receive, send), lifespan singleton & pool kết nối httpx.AsyncClient, thứ tự timeout keep-alive proxy (proxy < Uvicorn), Depends caching, async def (1 event loop) vs. def (bể luồng AnyIO 40 tokens) & asyncio.to_thread |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.2, §2.3) + Trụ cột 3 (Case 2 + Playbook B) + Mermaid 2 + Widget 2 | app.py (/v1/bench/async-blocking-trap, /v1/bench/to-thread), load_benchmark.py (benchmark_async_blocking_vs_offload), Test 10 |
4. Request validation, type enforcement & defaults (R26, AIDE 1 R25) |
Lõi Rust pydantic-core của Pydantic v2: ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False), @field_validator, Field(default_factory=...) an toàn cho giá trị mặc định, và chuẩn lỗi RFC 9457 (application/problem+json) |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.1) + Trụ cột 3 (Code Specimen) | schemas_and_auth.py (StrictPredictRequest, BatchPredictRequest, ProblemDetail), Tests 1, 2 |
5. Middleware (R26) |
Chi phí tạo task-group & bẫy đệm bộ nhớ StreamingResponse của Starlette BaseHTTPMiddleware (@app.middleware("http")) vs. Pure ASGI Middleware không đệm (X-Request-ID, X-Process-Time-Ms, telemetry log, Token Bucket 429 Retry-After) |
Trụ cột 2 (§2.1) + Trụ cột 3 (Case 3 + Code Specimen) + Mermaid 2 | app.py (RequestContextAndRateLimitMiddleware), load_benchmark.py (benchmark_sse_pure_asgi_vs_base_middleware), Tests 8, 9 |
6. API healthcheck: liveness & readiness (R26, AIDE 1 R25) |
Tách bạch Kubernetes startupProbe, livenessProbe (/health/live chỉ kiểm event loop, luôn 200 khi DB lỗi), readinessProbe (/health/ready kiểm phụ thuộc + cờ draining \(\to\) 503), preStop & ngắt êm ái SIGTERM |
Trụ cột 1 (§1.5) + Trụ cột 2 (§2.4) + Trụ cột 3 (Case 1 + Playbook C) + Mermaid 3 | app.py (/health/live, /health/ready, /metrics, install_sigterm_handler, --healthcheck), Tests 13, 15 |
7. Performance testing: metrics, guideline & Locust/k6 Lab (R26, AIDE 1 R25) |
Định luật Little (\(L = \lambda W\)), độ sử dụng \(\rho = \lambda/(c\mu) < 1\), Phương trình Kingman VUT, khuếch đại p99 qua fan-out, Coordinated Omission (Gil Tene) giữa vòng đóng (Locust) và vòng mở (k6 constant-arrival-rate) |
Trụ cột 1 (§1.6) + Trụ cột 2 (§2.4) + Trụ cột 3 (Case 5) + Trụ cột 4 (§4.1–§4.3) + Mermaid 3 + Widget 3 | load_benchmark.py, locustfile.py, k6_load_test.js, scripts/run_lab_demo.py, Tests 11, 12, 14, 15, 16 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 04 (Unified Notation)#
| Ký hiệu | Miền / Kiểu | Định nghĩa Chính xác Trong Chương 04 & webapi_serving_lab |
Quy ước Phân biệt |
|---|---|---|---|
| \(\lambda, \mu, c\) | \(\mathbb{R}_+, \mathbb{N}_+\) | Tốc độ đến \(\lambda\) (req/s), tốc độ phục vụ đơn kênh \(\mu = 1 / E[S]\) (req/s), số luồng/máy chủ song song \(c\) | Không nhầm \(c\) (số kênh phục vụ) với \(c_a, c_s\) (hệ số biến thiên) |
| \(\rho\) | \([0, 1)\) | Hệ số sử dụng \(\rho = \lambda / (c \cdot \mu)\) (hàng đợi ổn định khi \(\rho < 1\)) | — |
| \(L, W, W_q, S\) | \(\mathbb{R}_{\ge 0}\) | Số yêu cầu đồng thời trung bình \(L\), thời gian lưu hệ thống \(W = W_q + S\), thời gian chờ hàng đợi \(W_q\), thời gian phục vụ \(S\) | Phân biệt \(W\) (tổng độ trễ đầu-cuối) với \(W_q\) (chỉ phần đợi hàng đợi) |
| \(c_a^2, c_s^2\) | \(\mathbb{R}_{\ge 0}\) | Bình phương hệ số biến thiên (SCV) của khoảng đến \(A\) và thời gian phục vụ \(S\) |
Với quá trình Poisson chuẩn, \(c_a^2 = 1\) |
| \(p_{50}, p_{95}, p_{99}\) | \(\mathbb{R}_{\ge 0}\) (ms) | Các phân vị độ trễ 50%, 95%, 99%; với SSE tách riêng TTFT (Time-To-First-Token) và TPOT |
Không suy trung bình ra \(p_{99}\) do phân phối độ trễ lệch phải nặng |
| \(K_{\text{anyio}}\) | \(\mathbb{N}_+\) (40) |
Số token mặc định trong bể luồng AnyIO phục vụ handler/dependency đồng bộ def trên mỗi worker |
— |
| \(R_{\text{tok}}, B_{\text{tok}}\) | \(\mathbb{R}_+\) | Tốc độ nạp Token Bucket (req/s) và dung lượng bùng nổ burst trong Pure ASGI rate limiter |
— |
Trụ cột 1 — Nguyên lý Gốc: Kiến trúc API, Xác thực JWT/RBAC, Nội tại FastAPI/Pydantic v2, Đầu dò K8s & Lý thuyết Hàng đợi#
1.1 Năm Kiến trúc WebAPI (REST, gRPC, GraphQL, WebSockets, SSE) & Ngữ nghĩa Tính Lũy đẳng#
Lựa chọn giao thức API thực chất là đánh đổi trên bốn trục: định dạng dây nhị phân vs. văn bản, ghép kênh HTTP/2, hợp đồng kiểu tĩnh, và chiều truyền dòng dữ liệu.
REST(Fielding, 2000): Kiến trúc lai dựa trên 6 ràng buộc (Client-Server, Stateless, Cache, Uniform Interface, Layered System, Code-on-Demand tùy chọn). Trong hệ thống suy luận & dữ liệu hiện đại, điểm quyết định nằm ở ngữ nghĩa động từ HTTP (RFC 9110):GET,HEAD,OPTIONS: An toàn (safe — không đổi trạng thái máy chủ) và Lũy đẳng (idempotent: \(f(f(x)) = f(x)\)).PUT,DELETE: Lũy đẳng, nhưng không an toàn.POST,PATCH: Không an toàn và không lũy đẳng. Khi mạng timeout sau khi máy chủ đã chạy xong một phần, client tự động retryPOST /v1/predicthayPOST /v1/training-jobssẽ tạo đơn trùng lặp!- Khóa Lũy đẳng (
Idempotency-Key): Client đính kèm headerIdempotency-Key: <uuidv7>. Máy chủ lưu bộ(key, sha256(body), response)nguyên tử: gửi lại đúng payload trả bản sao đã lưu (cached_idempotency = true), còn tái sử dụng cùng khóa với payload khác bị chặn bằng409 Conflict(kiểm chứng ở Test 03 của Lab 04).
gRPC(HTTP/2+Protobuf): Mã hóa nhị phân thẻ-chiều dài (varint + số thứ tự trường, nhỏ hơn JSON UTF-8 khoảng3x–10x), chạy trên HTTP/2 multiplexing cho phép hàng trăm RPC song song chia sẻ một kết nối TCP mà không dính tắc nghẽn đầu dòng ở tầng ứng dụng L7 (HTTP/1.1 HoL blocking). Hỗ trợ 4 mô hình RPC: Unary, Server Streaming, Client Streaming, và Bidirectional Streaming kèm truyền thời hạngrpc-timeout(deadline propagation) xuyên suốt chuỗi microservice.- Bẫy Vận hành Kinh điển: Bộ cân bằng tải L4 (TCP) chỉ cân bằng lúc mở kết nối; vì gRPC giữ kết nối HTTP/2 sống lâu dài, toàn bộ lưu lượng bị ghim cứng vào 1 pod mới khởi tạo duy nhất! Phải chuyển sang cân bằng tải L7 nhận thức HTTP/2 (
Envoy/Linkerd/ gRPC client-side round-robin).
- Bẫy Vận hành Kinh điển: Bộ cân bằng tải L4 (TCP) chỉ cân bằng lúc mở kết nối; vì gRPC giữ kết nối HTTP/2 sống lâu dài, toàn bộ lưu lượng bị ghim cứng vào 1 pod mới khởi tạo duy nhất! Phải chuyển sang cân bằng tải L7 nhận thức HTTP/2 (
GraphQL: Hợp đồng đồ thị định kiểu mạnh (SDL) qua một điểm cuốiPOST /graphql, giúp client di động/dashboard lấy chính xác trường cần dùng (zero over-fetching / under-fetching).- Hai Bẫy Sập Lớn: (a) Bão resolver
N+1(mỗi cạnh quan hệ kích hoạt 1 truy vấn SQL riêng — phải gom theo lô từng tick quaDataLoader), và (b) Tấn công từ chối dịch vụ qua truy vấn lồng đệ quy sâu (user { friends { friends { ... } } }), bắt buộc áp trần độ sâu (max_depth) và ngân sách chi phí nút (query_complexity), kèm Persisted Queries nếu cần cache CDN HTTPGET.
- Hai Bẫy Sập Lớn: (a) Bão resolver
WebSockets(RFC 6455) vs.Server-Sent Events(SSE):WebSockets: Nâng cấp từ HTTP qua101 Switching Protocolsthành kênh TCP khung nhị phân/văn bản song công toàn phần (full-duplex). Tuyệt vời cho âm thanh đàm thoại thời gian thực (ASR <-> TTS) hay bảng vẽ cộng tác, nhưng nặng chi phí giữ kết nối có trạng thái, tự viết heartbeatping/pongvà logic nối lại khi mất mạng.SSE(Content-Type: text/event-stream): Phản hồi HTTP chuẩn truyền dòng sự kiện UTF-8 một chiều máy chủ \(\to\) máy khách (id:,event:,data:,retry:kết thúc bởi\n\n). Trình duyệt và SDK tự động kết nối lại kèm headerLast-Event-ID, đi xuyên tường lửa/CDN/HTTP/2 không cần101 Upgrade— trở thành chuẩn công nghiệp cho truyền token LLM/RAG (TTFT&TPOT).
1.2 Xác thực (AuthN), Phân quyền (AuthZ) & Phòng thủ JWT (RFC 7519)#
- Phân ranh giới Cứng
401vs.403:401 Unauthorized(kèm headerWWW-Authenticate: Bearer): Lỗi AuthN (Authentication) — thiếu thông tin định danh, chữ ký sai, hoặc token hết hạn (Tôi chưa biết bạn là ai).403 Forbidden: Lỗi AuthZ (Authorization) — danh tính hợp lệ nhưng thiếu vai trò/phạm vi quyền RBAC (Bạn làscorer, không có quyền gọi/v1/admin/reload).
- API Keys Bền vững & Chống Tấn công Timing: Không bao giờ lưu khóa thô trong CSDL. Tạo khóa ngẫu nhiên mật mã (
secrets.token_urlsafe(32)), chỉ lưu bản bămHMAC-SHA256(pepper, raw_key), và luôn đối chiếu bằnghmac.compare_digest(a, b)để thời gian chạy bất biến theo vị trí byte sai đầu tiên (toán tử==trong Python thoát sớm ngay tại byte lệch đầu tiên, tạo lỗ hổng kênh kề thời gian). - OAuth 2.0 (
RFC 6749) & ChuẩnJWT(RFC 7519, 05/2015):- Luồng OAuth2: Dùng Authorization Code + PKCE (
RFC 7636) cho người dùng tương tác và Client Credentials cho giao tiếp dịch vụ-dịch vụ (M2M). - Cấu trúc JWS:
Base64URL(Header) "." Base64URL(Payload) "." Base64URL(Signature). Thuật toán đối xứngHS256(HMAC-SHA256) dùng chung khóa bí mật tốc độ cực cao trong nội bộ tin cậy; thuật toán bất đối xứngRS256/ES256/EdDSA(Ed25519) ký bằng khóa riêng tại máy chủ xác thực và cho phép hàng trăm microservice kiểm chứng công khai qua/.well-known/jwks.jsonmà không lộ khóa ký. - Bốn Bất biến Kiểm chứng JWT Sống còn:
- Danh sách Thuật toán Cho phép Cố định (Algorithm Allowlist): Máy chủ tự khóa cứng tập thuật toán kỳ vọng (chỉ
{"HS256"}hoặc{"EdDSA"}). Tuyệt đối từ chối"alg": "none"(lỗ hổng Tim McLean, 03/2015) và chặn trò Algorithm Confusion (kẻ tấn công lấy khóa công khai RSA dùng làm khóa bí mật HMAC ký giảHS256!). - Xác nhận Hạn & Đồng hồ (
exp,nbf): Kiểm tranow - leeway < exp(leeway <= 5–30sbù lệch đồng hồ NTP) vànbf <= now + leeway. - Khớp Đích danh
issvàaud: Kiểm tra đúng nhà phát hành (iss) và dịch vụ nhận (aud) để chặn tấn công chuyển tiếp token giữa hai microservice khác nhau (confused deputy). - Chiến lược Thu hồi: JWT thuần không trạng thái không thể thu hồi trước
exp; hệ thống sản xuất giữTTLngắn (5–15 phút) kết hợp danh sách đenjtitrong Redis cho tác vụ khóa tài khoản khẩn cấp.
- Danh sách Thuật toán Cho phép Cố định (Algorithm Allowlist): Máy chủ tự khóa cứng tập thuật toán kỳ vọng (chỉ
- Luồng OAuth2: Dùng Authorization Code + PKCE (
1.3 Nội tại ASGI 3.0 của FastAPI, lifespan, Depends & Vòng lặp Sự kiện vs. Bể Luồng AnyIO 40#
Khác với WSGI đồng bộ (mỗi yêu cầu giữ chặt 1 luồng OS suốt thời gian chờ I/O), ASGI 3.0 chuẩn hóa ứng dụng thành hàm bất đồng bộ async def app(scope, receive, send). Trong FastAPI/Starlette:
lifespanContext Manager: Thay thế@app.on_eventcũ; chạy đúng 1 lần lúc worker khởi động để khởi tạo trọng số mô hình, bể kết nốihttpx.AsyncClient, hoặc pool DB gán vàoapp.state, và giải phóng sạch khi nhậnSIGTERM.- Tiêm Phụ thuộc
Depends& Bộ nhớ đệm Theo Yêu cầu (use_cache=True): FastAPI dựng đồ thị có hướng không chu trình (DAG) cho các hàmDepends. Mặc địnhuse_cache=Trueđảm bảo trong cùng 1 HTTP request, hàm kiểm chứng JWTget_current_principalchỉ chạy đúng 1 lần dù được cả router lẫn nhiều phụ thuộc RBAC dùng chung. - Phân nhánh Sống còn
async defvs.def:- Handler
async def: Chạy trực tiếp trên luồng Event Loop đơn (asyncio/uvloop). Chỉ chuyển ngữ cảnh hợp tác tại điểmawait. Nếu lập trình viên vô tình gọi hàm đồng bộ chặn I/O (time.sleep,requests.get,psycopg2, đọc đĩa đồng bộ) hoặc tính toán CPU nặng không nhả, 100% yêu cầu đồng thời trên worker đó bị đóng băng dây chuyền (Head-of-Line Event-Loop Freeze). - Handler đồng bộ
def(hoặcawait asyncio.to_thread(...)): Starlette tự động đẩy hàmdefsang bể luồng công nhân của AnyIO quaanyio.to_thread.run_sync(...). Mặc định bể luồng này giới hạn ởK_anyio = 40token/luồng mỗi worker. Tuy bảo vệ được Event Loop khỏi đứng hình trước thư viện đồng bộ cũ, khi có \(>40\) yêu cầu chặn đồng thời kéo dài, hàng đợi luồng AnyIO vẫn bão hòa dù CPU gần như nhàn rỗi; và với tác vụ thuần CPU Python, các luồng vẫn tranh chấp GIL (phải dùngProcessPoolExecutorhoặc nhân C/Rust/PyTorch nhả GIL).
- Handler
1.4 Pydantic v2 (pydantic-core Rust): Kiểm tra Nghiêm ngặt, Ranh giới Số học & Giá trị Mặc định#
Pydantic v2 viết lại hoàn toàn lõi kiểm định bằng Rust (pydantic-core), đạt tốc độ phân tích & tuần tự hóa nhanh hơn v1 từ 5x–50x, đặc biệt khi gọi model_validate_json() phân tích thẳng từ byte JSON không qua từ điển Python trung gian. Để khóa chặt ranh giới suy luận AI:
ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False):strict=True: Cấm ép kiểu ngầm tai hại ("1.5"vàofloat,1.0vàoint,"true"vàoboolđều ném422!). Lưu ý theo ngữ nghĩa số JSON, giá trị nguyênint(ví dụ2) vào trườngfloatvẫn hợp lệ dướistrict=True, cònboolbị từ chối rõ ràng.extra="forbid": Khước từ mọi khóa không khai báo trong schema (chặn lỗi gõ sai tên trường cấu hình và tấn công chèn tham số thừa mass assignment).allow_inf_nan=False+@field_validator: ChặnNaN,Infinity,-Infinityvà đặt biên hữu hạn (abs(x) <= 1e6) trước khi vector chạm tớiNumPyhay GPU kernel.- Giá trị Mặc định An toàn: Với trường kiểu chứa biến đổi (
dict,list), luôn dùngField(default_factory=dict)thay vì chia sẻ tham chiếu; kết hợpvalidate_default=Truenếu cần giá trị mặc định đi qua cùng bộ validator.
1.5 Đầu dò Sức khỏe Kubernetes (/health/live, /health/ready, /health/startup) & Ngắt Êm ái SIGTERM#
| Loại Đầu dò K8s | Câu hỏi Cốt lõi | Phạm vi Được Phép Kiểm tra | Phản ứng Của K8s Khi Lỗi | Quy tắc Vàng Sản xuất |
|---|---|---|---|---|
startupProbe |
Mô hình đã nạp xong chưa? | Trạng thái nạp trọng số ML, khởi tạo lifespan |
Chưa kích hoạt liveness/readiness; giết pod nếu quá failureThreshold * periodSeconds |
Bắt buộc dùng cho pod nạp mô hình nặng (Model-Load) mất 20–120s. |
livenessProbe (/health/live) |
Tiến trình & Event Loop có bị treo chết không? | Chỉ kiểm tra event loop còn phản hồi (200 OK) trong vài mili-giây |
Kubelet gửi SIGTERM/SIGKILL và khởi động lại container! |
CẤM TUYỆT ĐỐI kiểm tra PostgreSQL, Redis, hay API ngoài trong /health/live! |
readinessProbe (/health/ready) |
Pod có sẵn sàng nhận lưu lượng mới không? | Kết nối DB/feature store, trạng thái cache, VÀ cờ draining |
Gỡ IP pod khỏi Service Endpoints & Load Balancer (không giết pod!) | Trả ngay 503 Service Unavailable khi dependency lỗi hoặc lúc vừa nhận SIGTERM. |
Trình tự Ngắt Không Mất Gói (Zero-Downtime SIGTERM Drain): Khi K8s thu hồi pod, tín hiệu SIGTERM tới tiến trình Python song song với việc kube-proxy / Ingress cập nhật bảng định tuyến iptables (có độ trễ lan truyền 1–5 giây!). Do đó, pod cần: (1) gắn hook preStop: ["sleep", "5"] hoặc giữ cửa sổ chờ trễ định tuyến; (2) ngay khi nhận SIGTERM, bật state.draining = True để /health/ready trả 503; (3) hoàn tất toàn bộ yêu cầu đang chạy dở (in_flight == 0) trước khi lifespan đóng kết nối và tiến trình thoát trước hạn terminationGracePeriodSeconds.
1.6 Toán học Hàng đợi Cho Kiểm thử Tải: Định luật Little, Kingman VUT & Coordinated Omission#
Đo lường tải không phải là chạy mù quáng cho tới khi máy chủ sập, mà là xác minh bốn bất biến toán học của hệ thống hàng đợi:
- Định luật Little (
Little, 1961, Operations Research): Với mọi hệ thống hàng đợi dừng ổn định (stationary steady state), bất kể phân phối thời gian đến hay kỷ luật phục vụ:\[L = \lambda \cdot W\]trong đó \(L\) là số yêu cầu đồng thời trung bình trong hệ thống (concurrency), \(\lambda\) là tốc độ đến hiệu dụng (req/s), và \(W = E[W_q] + E[S]\) là tổng thời gian lưu lại (wait + service). Hệ quả quy hoạch dung lượng: nếu một worker FastAPI có \(K_{\text{anyio}} = 40\) luồng chặn với thời gian mỗi yêu cầu \(W = 0.25\text{ s}\), trần thông lượng tối đa về mặt vật lý là \(\lambda_{\max} = L / W = 40 / 0.25 = \mathbf{160\text{ req/s}}\). - Điều kiện Ổn định & Hệ số Sử dụng: Với \(c\) máy chủ/luồng song song có tốc độ phục vụ trung bình \(\mu = 1 / E[S]\):
\[\rho = \frac{\lambda}{c \cdot \mu} < 1\]Hễ \(\rho \ge 1\), chiều dài hàng đợi và độ trễ phân kỳ tiến tới vô cực theo thời gian!
- Phương trình Kingman VUT (
Kingman, 1961) & Sakasegawa (1977): Cho hàng đợi tổng quát \(GI/G/1\) (và mở rộng xấp xỉ đa máy chủ \(GI/G/c\) theo Sakasegawa với \(U_c = \frac{\rho^{\sqrt{2(c+1)} - 1}}{c(1 - \rho)}\)), thời gian đợi hàng đợi kỳ vọng \(E[W_q]\) tuân theo tích ba thừa số Biến thiên (\(V\)) \(\times\) Sử dụng (\(U\)) \(\times\) Thời gian phục vụ (\(T\)):\[E[W_q] \approx \underbrace{\left(\frac{c_a^2 + c_s^2}{2}\right)}_{V \text{ (Variability)}} \cdot \underbrace{\left(\frac{\rho}{1 - \rho}\right)}_{U \text{ (Utilization)}} \cdot \underbrace{E[S]}_{T \text{ (Service Time)}}\]trong đó \(c_a = \sigma_a / E[A]\) và \(c_s = \sigma_s / E[S]\) là hệ số biến thiên của khoảng đến và thời gian xử lý. Thừa số \(\frac{\rho}{1 - \rho}\) giải thích bản chất phi tuyến của khúc khuỷu bão hòa (saturation knee): tại \(\rho = 0.50\), \(U = 1.0\); tại \(\rho = 0.85\), \(U = 5.67\); tại \(\rho = 0.95\), \(U = 19.0\); và tại \(\rho = 0.98\), \(U = 49.0\)! Vì vậy không bao giờ được vận hành dịch vụ nhạy độ trễ vượt ngưỡng \(\rho \approx 0.70\text{–}0.80\). - Khuếch đại Độ trễ Đuôi (Fan-Out Tail Amplification, Dean & Barroso 2013): Nếu một yêu cầu người dùng gọi đồng thời \(m = 20\) microservice độc lập (hoặc \(20\) đoạn RAG shard), xác suất ít nhất 1 nhánh rơi vào phần đuôi chậm
p99(\(1\%\)) là:\[P(\text{hit } \ge 1 \text{ slow branch}) = 1 - (1 - 0.01)^{20} \approx \mathbf{18.2\%}\]biến SLOp99ở từng thành phần thành trải nghiệm chậm trên gần 1/5 tổng lượng người dùng! - Sai số Đo lường
Coordinated Omission(Gil Tene): Khi công cụ kiểm thử tải hoạt động theo vòng đóng (closed-loop) (mỗi người dùng ảo chờ nhận phản hồi xong mới gửi tiếp), hễ máy chủ khựng lại160 ms, tốc độ gửi \(\lambda\) tự động tụt xuống theo, vô tình bỏ qua toàn bộ giai đoạn hệ thống tắc nghẽn nhất và báo cáop99thấp giả tạo hàng chục lần.
Trụ cột 2 — Kiến trúc Hệ thống Sản xuất & Đổi mới SOTA 2024–2026#
2.1 Ma trận Chọn Kiến trúc API & Chuẩn Lỗi RFC 9457 (Problem Details)#
Sơ đồ dưới đây chuẩn hóa cây quyết định chọn giao thức API cho hệ thống AI & Dữ liệu dựa trên hình thái tải, nhu cầu song công và ràng buộc tường lửa/cân bằng tải:
Chuẩn Lỗi Cấu trúc RFC 9457 (Problem Details for HTTP APIs, 07/2023)#
Được Mark Nottingham, Erik Wilde và Sanjay Dalal chuẩn hóa thay thế RFC 7807, mọi phản hồi lỗi (401, 403, 409, 422, 429, 503) đều trả về Content-Type: application/problem+json theo 5 trường chuẩn (type, title, status, detail, instance) cùng trường mở rộng an toàn (request_id, errors). Nhờ tách riêng handler ngoại lệ cho RequestValidationError, AuthError và HTTPException, client tự động phân giải đường dẫn trường lỗi mà không bao giờ rò rỉ Python stack trace hay đường dẫn tệp nội bộ ra ngoài mạng.
2.2 Vòng đời FastAPI ASGI, Bẫy BaseHTTPMiddleware vs. Pure ASGI Middleware#
Trong vòng đời phục vụ chuẩn 2026, luồng đi của một yêu cầu HTTP vào FastAPI đi qua các chốt kiểm soát chặt chẽ sau:
Vì sao Phải Thay BaseHTTPMiddleware Bằng Pure ASGI Middleware & Kỷ luật OpenTelemetry?#
Khi dùng cú pháp tiện lợi @app.middleware("http") trong FastAPI (kế thừa Starlette BaseHTTPMiddleware), trên mỗi yêu cầu, khung thực thi tạo một Request mới, cặp luồng bộ nhớ anyio.create_memory_object_stream, và anyio.create_task_group() chạy call_next ở tác vụ nền. Hậu quả kép đã được chứng minh thực nghiệm ngay trong Lab 04:
- Chi phí Thông lượng (
4.03xchênh lệch): Trên400yêu cầu ping tối giản, Pure ASGI đạt18,073.6 RPS(22.13 ms) trong khiBaseHTTPMiddlewarerớt xuống4,482.7 RPS(89.23 ms). - Đệm Luồng Phá Hỏng
TTFTcủa LLM/SSE: Nếu middleware dựa trênBaseHTTPMiddlewaređọcresp.body_iteratorđể log hoặc kiểm tra phản hồi, toàn bộ5token SSE bị dồn thành1cục duy nhất chờ tới cuối luồng mới phát, kéoTTFTtừ29.87 msvọt lên155.48 ms(5.21xchậm hơn)! Ngược lại, Pure ASGI Middleware chỉ gắn header tại thông điệphttp.response.startvà chuyển thẳng từng khunghttp.response.body(more_body=True) không sao chép. - Góc nhìn Principal (
SOTA 2025–2026) — Quan trắcOpenTelemetry(W3C traceparent, Tail-Based Sampling & Kỷ luật Cardinality):- Đánh đổi Thiết kế: Gắn
TracerProvider+MeterProviderngay trong lớp Pure ASGI Middleware giúp táchW3C traceparentchuẩn và đo đủhttp.server.requests/http.server.request.durationmà không đệm stream. Với hệ thống lưu lượng lớn, tail-based sampling trên Collector (giữ100%trace có lỗi5xx/429hoặcp99chậm, chỉ giữ1–5%request nhanh) vượt trội hơn head-based sampling ngẫu nhiên vốn dễ đánh rơi đúng trace hỏng. - Chế độ Lỗi Sản xuất (TSDB OOM & Rò rỉ RAM): Không bao giờ đưa thuộc tính vô biên (
request_id,user_id,client_id,url.pathchưa chuẩn hóa có query string) vào nhãn metric (Counter/Histogram), vì chỉ vài trăm nghìn user sẽ làm nổ time-series cardinality và đánh sập Prometheus/TSDB bằng OOM! Nhãn metric chỉ được phép chứa tập hữu hạn (http.request.method,http.routechuẩn hóa,http.response.status_code), cònfsds.request_idhayml.model.versionchỉ gắn vào span; đồng thời mọi bộ đệm trong bộ nhớ (buckets,idempotency_cache,latencies_ms,telemetry_logs) phải khóa trần bằngOrderedDictLRU+TTL hoặcdeque(maxlen=...).
- Đánh đổi Thiết kế: Gắn
2.3 Tái sử dụng Kết nối lifespan, Thứ tự Timeout Proxy & Tối ưu Hóa Uvicorn#
- Singleton
httpx.AsyncClientTronglifespan: Tuyệt đối không khởi tạoasync with httpx.AsyncClient()bên trong từng route gọi Feature Store hay LLM backend — thao tác đó lặp lại bắt tay TCP 3 bước + TLS (+30–80 ms/call) và làm cạn cổng tạm thời ở trạng tháiTIME_WAIT. Khởi tạo một client dùng chung duy nhất qualifespanvớihttpx.Limits(max_connections=200, max_keepalive_connections=50)và đóng bằngawait client.aclose()lúc tắt ứng dụng. - Bẫy Đóng Kết nối Keep-Alive Giữa NGINX/ALB và
Uvicorn: Nếu NGINX/Envoy phía trước giữ kết nối nhàn rỗi60smàUvicornmặc định đặt--timeout-keep-alive 5(5 giây), Uvicorn sẽ đóng socket ngay trước khi NGINX gửi gói tin tiếp theo, sinh ra lỗi502 Bad Gatewayngẫu nhiên dưới tải trung bình! Quy tắc bất di bất dịch:Uvicorn --timeout-keep-alivephải lớn hơn idle timeout của Proxy/ALB (ví dụ ALB60s\(\implies\) Uvicorn--timeout-keep-alive 75). - Động cơ Vòng lặp & Cỡ Worker: Trên Linux sản xuất, chạy Uvicorn cùng
uvloop+httptools(uvicorn ... --workers N). Lưu ý mỗi worker process sở hữu một Event Loop riêng, một bể AnyIO40-thread riêng, và bộ nhớ Token Bucket cục bộ riêng (khi mở rộng nhiều worker/pod, phải chuyển bộ đếm rate-limit sang Redis Lua script nguyên tử).
Principal Industrial Tip #12b — Phục vụ WebAPI Tốc độ Cao Với Granian (Rust/Hyper RSGI/ASGI) vs. Uvicorn/Gunicorn & Chống Bão hòa Vòng lặp (2025–2026):
- Đánh đổi Runtime (
GranianRust/Hypervs.Uvicorn/Gunicorn): Thay vì xếp lớpGunicorn(forkworker manager) bọcUvicornWorker(uvloop+httptools),Granianxử lý trực tiếp TCP/HTTP/1.1/HTTP/2/TLS trên nhân RustHyper+Tokiovà hỗ trợ song song chuẩnASGI(cắm thẳng vàoFastAPI) lẫnRSGI(giao diện Rust–Python bỏ qua đóng góiscope/receive/senddict trung gian, giảm áp lực GC trên streaming SSETTFT). Trên microservice nhiều worker,Granianloại bỏ rủi ro deadlockos.fork()và đạt thông lượng parse HTTP ổn định hơn ở đỉnh tải cao. - Giới hạn
GIL& Event-Loop Saturation Vẫn Tồn tại: Không một server nào cứu được ứng dụng chặn Event Loop! Nếu tuyếnasync defgọirequests.get(),psycopg2hoặc tính toán CPU Python nặng, Event Loop của worker vẫn đứng hình (p99nhảy vọt) trên cảGranianlẫnUvicorn. Tương tự, trên Python3.12/3.13cònGIL, chạyGranian--threads > 1cho code Python CPU-bound sẽ gây tranh chấp GIL (cần--workers Nhoặc nâng lên3.14t--disable-gilvà tách suy luận nặng sang Triton/vLLM). - Chế độ Lỗi Sản xuất (
Failure Modes): (1) Để keep-alive timeout củaGranian/Uvicornnhỏ hơn idle timeout của NGINX/ALB (60s) vẫn gây bão502 Bad Gatewayngẫu nhiên; (2) Bỏ quên tham số--backpressure(hoặc giới hạn đồng thời) khiếnHypernhận tràn hàng đợi yêu cầu khi GPU/DB chậm thay vì trả503kích hoạt autoscaler; (3) Mở nhiều--workerskhiến Token Bucket trong RAM bị chia năm xẻ bảy — bắt buộc đồng bộ rate-limit qua Redis Lua.
2.4 Đầu dò K8s, Ngắt SIGTERM & Kiểm thử Tải Vòng Mở (k6 vs. Locust)#
Sơ đồ dưới đây kết nối kiến trúc vòng đời Kubernetes (/health/live, /health/ready, SIGTERM drain) với hai chế độ tạo tải kiểm chứng ngưỡng bão hòa:
| Tiêu chí So sánh | Vòng Đóng (Closed-Loop: Locust HttpUser mặc định) |
Vòng Mở (Open-Loop: k6 constant-arrival-rate) |
|---|---|---|
| Cơ chế Phát Yêu cầu | \(V\) người dùng ảo: gửi \(\to\) đợi phản hồi xong \(\to\) nghỉ wait_time \(\to\) lặp lại |
Bộ lập lịch đồng hồ độc lập bắn đúng \(\lambda\) req/s bất chấp máy chủ phản hồi nhanh hay chậm |
| Phản ứng Khi Máy chủ Khựng | \(\lambda_{\text{thực}}\) tự tụt về \(V / W\), ngừng nạp tải đúng lúc nghẽn nhất | Giữ nguyên \(\lambda\) xếp hàng dồn ứ (hoặc ghi nhận dropped_iterations nếu chạm trần maxVUs) |
Độ Trung thực p99 |
Bị Coordinated Omission kéo thấp giả tạo (2.72 ms vs 173.87 ms trong Lab 04!) |
Phản ánh trung thực độ trễ chờ hàng đợi \(W_q + S\) và khúc khuỷu bão hòa Kingman |
Cách Khắc phục Khi Dùng Locust |
Thiết lập số VU dư tải kết hợp constant_pacing (vẫn rớt nhịp nếu \(W > \text{pacing}\)) hoặc đối chiếu chéo bằng k6 |
Chuẩn mặc định với executor: 'constant-arrival-rate' hoặc 'ramping-arrival-rate' |
Trụ cột 3 — Năm Sự cố Sản xuất Kinh điển, Mã Chuẩn Thực thi & Bảng Ra quyết định#
Case 1 — Gắn Đầu dò livenessProbe Vào CSDL Gây Vòng Xoáy CrashLoopBackOff Toàn Cụm#
- Cơ chế Sự cố Thực tế: Một dịch vụ API phơi bày duy nhất
/healthchạySELECT 1sang PostgreSQL và gán chung cho cảreadinessProbelẫnlivenessProbe(timeoutSeconds: 2, failureThreshold: 3). Khi DB nghẽn10 giây, chỉ sau30 giây(3lần trượt), Kubelet đánh giá toàn bộ container API bị treo chết và gửiSIGKILLkhởi động lại 100% pod đồng thời. Khi DB vừa hồi phục, hàng trăm pod mới khởi động cùng ập vào mở bể kết nối + chạy truy vấn khởi tạo, đánh sập DB lần hai và giam cả cụm trong trạng tháiCrashLoopBackOffkéo dài hàng chục phút sau khi sự cố DB gốc đã hết! - Biện pháp Triệt để: Tách cứng
/health/live(chỉ kiểm tra event loop phản hồi200) khỏi/health/ready(kiểm phụ thuộc + cờdraining, trả503khi lỗi để gỡ IP khỏi Load Balancer mà giữ pod sống), kết hợpstartupProbevà backoff ngẫu nhiên (jitter) khi kết nối lại.
Case 2 — Gọi Thư viện Đồng bộ Trong async def Làm Tê liệt Cả API Lẫn Đầu dò Sức khỏe#
- Cơ chế Thực tế: Lập trình viên viết
async def predict(...)nhưng bên trong gọitime.sleep(0.02)khi retry, hoặc gọirequests.post()tới Feature Store, hoặc giải mã JSON hàng chục MB đồng bộ. Do chỉ có 1 luồng Event Loop cho mỗi worker Uvicorn, mọi coroutine đồng thời khác — bao gồm cả tuyến/health/livecủa Kubelet — đều phải đứng xếp hàng chờ tuần tự. Trong Lab 04 (16yêu cầu \(\times 20\text{ ms}\)),async defchặn đồng bộ mất368.01 ms(chỉ đạt43.5 RPS) và đẩy trễ/health/livelên367.91 ms, trong khiasyncio.to_threadrút xuống50.19 ms(318.8 RPS, nhanh hơn7.33x). - Biện pháp Triệt để: Luôn dùng client bất đồng bộ thuần (
httpx.AsyncClient,asyncpg); bọc thư viện đồng bộ bất khả kháng quaawait asyncio.to_thread(...)(hoặc khai báo routedefnếu muốn FastAPI tự đẩy vào bể 40 luồng AnyIO), và tách tác vụ nặng CPU Python sangProcessPoolExecutorhoặc runtime C++/Rust/Triton riêng.
Case 3 — BaseHTTPMiddleware Làm Sụp Thông lượng & Đệm SSE Streaming Trên Cổng AI#
- Thực tế Sản xuất (Các sự cố Starlette / FastAPI / LiteLLM): Hàng loạt nhóm triển khai cổng LLM
/v1/chat/completions(stream=True) gặp hiện tượng client nhận cả đoạn trả lời giật cục một lần thay vì từng token mượt mà, thỉnh thoảng treo kết nối lúc client ngắt giữa chừng hoặc nổRuntimeError: Response content longer than Content-Length. Nguyên nhân đến từ thói quen viết@app.middleware("http")(BaseHTTPMiddleware). - Số đo Đối chứng Trong Lab 04: Cùng trên một ứng dụng
FastAPI(Starlette 1.10.0), Pure ASGI Middleware đạt18,073.6 RPS(so với4,482.7 RPScủaBaseHTTPMiddleware, gấp4.03x) và truyền5sự kiện SSE từTTFT = 29.87 ms; còn biến thể đệm iterator quaBaseHTTPMiddlewarenhốt toàn bộ5token làmTTFTtăng vọt lên155.48 ms(5.21xtệ hơn).
Case 4 — JWT alg: "none", Hoán đổi RS256 -> HS256 & Rò rỉ Timing Trên API Key#
- Bối cảnh (Tim McLean, Auth0 03/2015 & Các CVE Tương tự): Các thư viện JWT cho phép header token tự quyết định thuật toán xác thực. Kẻ tấn công sửa payload thành
"role": "admin", đặt"alg": "none", xóa phần chữ ký để vượt qua xác thực; hoặc lấy khóa công khaiRS256của máy chủ rồi ký giả dưới thuật toán đối xứngHS256. Tương tự, so sánh khóa API bằng==tạo rò rỉ độ trễ theo số byte trùng đầu chuỗi. - Phòng thủ Bắt buộc: Đọc khóa API qua hàm băm
HMAC-SHA256+hmac.compare_digest; trong xác thực JWT chỉ chấp nhận đúng một thuật toán định trước trên máy chủ (alg == "HS256"), chặn thẳngalg == "none"/ thuật toán khác, và kiểm bắt buộcexp,nbf,iss,aud.
Case 5 — Coordinated Omission Che Giấu Thảm họa p99 Trước Giờ Ra mắt#
- Thực tế Sản xuất: Đội ngũ chạy bài đo vòng đóng
LocustV=1..10người dùng ảo trong môi trường thử nghiệm thấyp99 < 5 msnên tự tin ra mắt. Khi người dùng thật truy cập độc lập ở150 req/s, một đợt dừng GC/tải lại mô hình160 msduy nhất khiến24yêu cầu đến trong khoảng dừng dồn hết vào hàng đợi. Trong thí nghiệm ASGI thật của Lab 04, bài đo vòng đóng báop99 = 2.72 ms, hoàn toàn xóa sạch sự cố160 ms, trong khi bài đo vòng mở152.5 RPSghi nhận chính xácp99 = 173.87 ms(khoảng cách che giấu63.92x!).
Mã Nguồn Chuẩn Thực thi (FastAPI + Pydantic v2 Strict + Pure ASGI Middleware + RFC 7519 HS256 JWT + RFC 9457 + K8s Probes)#
Đoạn mã hoàn chỉnh dưới đây có thể chạy trực tiếp độc lập trên .venv Python 3.12+ (đã kiểm chứng thực thi 100%):
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import math
import time
import uuid
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Annotated, Any
from fastapi import Depends, FastAPI, Header, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, field_validator
from starlette.testclient import TestClient
from starlette.types import ASGIApp, Message, Receive, Scope, Send
JWT_SECRET = "fsds-demo-hs256-secret-key-2026"
ROLE_SCOPES = {"reader": frozenset({"stream:read"}), "scorer": frozenset({"predict:write", "stream:read"})}
class StrictScoreRequest(BaseModel):
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
request_id: str = Field(min_length=4, max_length=64)
features: list[float] = Field(min_length=2, max_length=16)
metadata: dict[str, str] = Field(default_factory=dict)
@field_validator("features")
@classmethod
def check_finite(cls, vals: list[float]) -> list[float]:
if not all(math.isfinite(x) and abs(x) <= 1e6 for x in vals):
raise ValueError("All features must be finite and bounded within [-1e6, 1e6].")
return vals
@dataclass(slots=True)
class RuntimeState:
draining: bool = False
degraded: bool = False
in_flight: int = 0
class AuthFailure(Exception):
def __init__(self, status_code: int, code: str, detail: str) -> None:
self.status_code, self.code, self.detail = status_code, code, detail
def _b64u_enc(data: bytes) -> str:
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
def _b64u_dec(seg: str) -> bytes:
return base64.urlsafe_b64decode(seg + ("=" * ((-len(seg)) % 4)))
def mint_hs256_jwt(sub: str, role: str, ttl_sec: int = 300) -> str:
now = int(time.time())
hdr = _b64u_enc(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
pay = _b64u_enc(
json.dumps(
{"iss": "fsds-auth", "aud": "fsds-api", "sub": sub, "role": role, "exp": now + ttl_sec},
separators=(",", ":"),
).encode()
)
sig = hmac.new(JWT_SECRET.encode(), f"{hdr}.{pay}".encode("ascii"), hashlib.sha256).digest()
return f"{hdr}.{pay}.{_b64u_enc(sig)}"
def verify_hs256_jwt(token: str) -> dict[str, Any]:
parts = token.split(".")
if len(parts) != 3 or not parts[2]:
raise AuthFailure(401, "malformed-jwt", "Token must contain 3 JWS segments.")
hdr = json.loads(_b64u_dec(parts[0]))
if hdr.get("alg") != "HS256": # Explicitly reject alg="none" or RS256 confusion
raise AuthFailure(401, "invalid-alg", f"Algorithm {hdr.get('alg')!r} is forbidden.")
expected = hmac.new(JWT_SECRET.encode(), f"{parts[0]}.{parts[1]}".encode("ascii"), hashlib.sha256).digest()
if not hmac.compare_digest(_b64u_dec(parts[2]), expected):
raise AuthFailure(401, "bad-signature", "JWT signature mismatch.")
claims: dict[str, Any] = json.loads(_b64u_dec(parts[1]))
if claims.get("iss") != "fsds-auth" or claims.get("aud") != "fsds-api" or time.time() >= float(claims.get("exp", 0)):
raise AuthFailure(401, "invalid-claims", "Expired or mismatched iss/aud claim.")
return claims
class PureASGIRateContextMiddleware:
"""Zero-copy ASGI 3.0 middleware injecting X-Request-ID & timing without buffering SSE."""
def __init__(self, app: ASGIApp, state: RuntimeState) -> None:
self.app, self.state = app, state
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
t0 = time.perf_counter()
req_id = f"req-{uuid.uuid4().hex[:10]}"
scope.setdefault("state", {})["request_id"] = req_id
self.state.in_flight += 1
async def send_wrapper(msg: Message) -> None:
if msg["type"] == "http.response.start":
elapsed = (time.perf_counter() - t0) * 1000.0
hdrs = list(msg.get("headers", []))
hdrs.extend([(b"x-request-id", req_id.encode()), (b"x-process-time-ms", f"{elapsed:.2f}".encode())])
msg["headers"] = hdrs
await send(msg)
try:
await self.app(scope, receive, send_wrapper)
finally:
self.state.in_flight = max(0, self.state.in_flight - 1)
def require_bearer(authorization: Annotated[str | None, Header()] = None) -> dict[str, Any]:
if not authorization or not authorization.lower().startswith("bearer "):
raise AuthFailure(401, "missing-token", "Expected Bearer JWT.")
return verify_hs256_jwt(authorization.split(" ", 1)[1].strip())
BearerUser = Annotated[dict[str, Any], Depends(require_bearer)]
def build_specimen_app() -> FastAPI:
state = RuntimeState()
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
yield
state.draining = True
app = FastAPI(lifespan=lifespan)
app.state.runtime = state
app.add_middleware(PureASGIRateContextMiddleware, state=state)
@app.exception_handler(AuthFailure)
async def _auth_handler(req: Request, exc: AuthFailure) -> JSONResponse:
return JSONResponse(
status_code=exc.status_code,
media_type="application/problem+json",
content={"type": f"https://api.fsds.example/{exc.code}", "title": "Auth Error", "status": exc.status_code, "detail": exc.detail, "instance": str(req.url.path)},
headers={"WWW-Authenticate": "Bearer"} if exc.status_code == 401 else None,
)
@app.exception_handler(RequestValidationError)
async def _val_handler(req: Request, exc: RequestValidationError) -> JSONResponse:
return JSONResponse(
status_code=422,
media_type="application/problem+json",
content={"type": "https://api.fsds.example/validation", "title": "Validation Failed", "status": 422, "detail": "Strict Pydantic v2 violation.", "instance": str(req.url.path), "errors": exc.errors()},
)
@app.get("/health/live")
async def live() -> dict[str, Any]:
return {"status": "alive", "in_flight": state.in_flight}
@app.get("/health/ready")
async def ready() -> JSONResponse:
if state.draining or state.degraded:
return JSONResponse(status_code=503, media_type="application/problem+json", content={"title": "Not Ready", "status": 503})
return JSONResponse(status_code=200, content={"status": "ready"})
@app.post("/v1/predict")
async def predict(body: StrictScoreRequest, user: BearerUser) -> dict[str, Any]:
if "predict:write" not in ROLE_SCOPES.get(str(user.get("role")), ()):
raise AuthFailure(403, "forbidden", "Role lacks predict:write scope.")
score = round(sum(body.features) / len(body.features), 4)
return {"request_id": body.request_id, "score": score, "subject": user["sub"]}
@app.get("/v1/stream")
async def stream_tokens(_user: BearerUser) -> StreamingResponse:
async def _gen() -> AsyncIterator[str]:
for idx, tok in enumerate(("FastAPI", "Pure", "ASGI")):
yield f"id: {idx}\nevent: token\ndata: {json.dumps({'token': tok})}\n\n"
return StreamingResponse(_gen(), media_type="text/event-stream", headers={"Cache-Control": "no-cache"})
return app
if __name__ == "__main__":
app = build_specimen_app()
scorer_jwt = mint_hs256_jwt("svc-scorer", "scorer")
reader_jwt = mint_hs256_jwt("svc-reader", "reader")
with TestClient(app) as client:
ok = client.post("/v1/predict", json={"request_id": "demo-01", "features": [1.0, 3.0]}, headers={"Authorization": f"Bearer {scorer_jwt}"})
deny = client.post("/v1/predict", json={"request_id": "demo-02", "features": [1.0, 3.0]}, headers={"Authorization": f"Bearer {reader_jwt}"})
bad = client.post("/v1/predict", json={"request_id": "demo-03", "features": ["1.0", 3.0], "rogue": 1}, headers={"Authorization": f"Bearer {scorer_jwt}"})
assert ok.status_code == 200 and ok.json()["score"] == 2.0
assert deny.status_code == 403 and bad.status_code == 422
print("Specimen verified:", ok.json(), "header X-Request-ID:", ok.headers["x-request-id"])
Ba Bảng Ra quyết định Sản xuất 2026 (Production Decision Playbooks)#
Playbook A — Chọn Phong cách Kiến trúc WebAPI#
| Phong cách API | Giao thức & Định dạng | Điểm Mạnh Tuyệt đối | Bẫy Sập Lớn Nhất | Dùng Khi / Tránh Khi |
|---|---|---|---|---|
REST |
HTTP/1.1 / HTTP/2, JSON UTF-8 |
Phổ quát mọi ngôn ngữ/CDN/firewall; OpenAPI 3.1 + RFC 9457; cache GET qua ETag |
Thiếu Idempotency-Key trên POST tạo ghi đúp; payload JSON cồng kềnh |
Dùng: API công khai, quản trị CRUD, batch job. Tránh: RPC nội bộ truyền tensor lớn tần suất cực cao. |
gRPC |
HTTP/2 + Nhị phân Protobuf |
Nhỏ gọn 3x–10x, nhanh, ghép kênh không HoL L7, .proto chặt chẽ |
Cân bằng tải L4 TCP ghim 100% tải vào 1 pod | Dùng: Microservice nội bộ, Triton/vLLM router nội bộ. Tránh: Gọi thẳng từ trình duyệt thiếu gRPC-Web proxy. |
GraphQL |
HTTP POST, Typed SDL |
Lấy đúng cột cần dùng trên đồ thị dữ liệu phức tạp | Bão N+1 resolver thiếu DataLoader; truy vấn đệ quy gây DoS |
Dùng: Cổng tổng hợp BFF cho dashboard đa client. Tránh: API ingest dữ liệu lớn hoặc truyền file nhị phân. |
SSE |
HTTP/1.1/HTTP/2 (text/event-stream) |
Truyền một chiều mượt, tự nối lại qua Last-Event-ID, không cần 101 Upgrade |
Gắn BaseHTTPMiddleware đệm luồng phá vỡ TTFT |
Dùng: Truyền token LLM/RAG (TTFT/TPOT), log tiến trình.Tránh: Giao tiếp âm thanh hai chiều độ trễ thấp. |
WebSockets |
HTTP 101 \(\to\) TCP Song công toàn phần |
Hai chiều thực thời (ASR <-> TTS), khung nhị phân gọn |
Giữ kết nối có trạng thái, khó cân bằng tải & timeout proxy | Dùng: Chat tương tác hai chiều, giọng nói, cộng tác live. Tránh: Chỉ đẩy thông báo một chiều đơn giản. |
Playbook B — Chọn Mô hình Thực thi & Bảo mật FastAPI#
| Hạng mục | Cấu hình Chống Sập Chuẩn 2026 | Anti-Pattern Tuyệt đối Cấm | Công cụ / Thước đo Kiểm chứng |
|---|---|---|---|
| Handler & Concurrency | async def + httpx.AsyncClient (lifespan singleton) / asyncpg; bọc I/O chặn cũ bằng asyncio.to_thread (hoặc def biết rõ giới hạn 40 luồng AnyIO); CPU nặng qua ProcessPoolExecutor |
Gọi time.sleep, requests, psycopg2 hay CPU thuần trong async def (đóng băng Event Loop!) |
Benchmark đồng thời + đo /health/live mid-flight lag (30.75 ms vs 367.91 ms freeze) |
| Middleware & OTel | Pure ASGI Middleware (__call__(scope, receive, send)) + OpenTelemetry (traceparent, nhãn metric low-cardinality method/route/status) + OrderedDict LRU+TTL / deque(maxlen) |
@app.middleware("http") (BaseHTTPMiddleware), dict/list không giới hạn dung lượng, gắn request_id/user_id làm nhãn Prometheus/OTel |
Đo ping RPS (18,073.6 vs 4,482.7), SSE TTFT (29.87 vs 155.48 ms), InMemorySpanExporter |
| Xác thực & Schema | Pydantic v2 ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False); RFC 9457; hmac.compare_digest trên SHA-256 API Key; JWT allowlist HS256/EdDSA; khóa /metrics & /v1/bench/* |
Tin "alg" trong token (alg: "none", RS256->HS256), lưu API Key thô, để hở /metrics hay endpoint benchmark không auth/feature-flag |
Kiểm thử âm tính 401 vs 403 vs 422 application/problem+json |
Playbook C — Ngân sách Vận hành K8s Probes & Kiểm thử Tải#
| Hạng mục Vận hành | Cấu hình & Ngưỡng Mục tiêu Sản xuất | Cơ chế Bảo vệ & Lệnh Giám sát |
|---|---|---|
| K8s Probes & Drain | /health/live tách rời DB; /health/ready phản ứng lỗi DB & SIGTERM (503); startupProbe cho nạp mô hình; preStop sleep 5s; Uvicorn --timeout-keep-alive > proxy idle timeout |
Kiểm tra pod không bị CrashLoopBackOff khi DB tụt, 0 lỗi 502 lúc rolling update |
| Ngân sách Tải & Bão hòa | Giữ \(\rho = \lambda/(c\mu) \le 0.70\text{–}0.75\) (tránh khúc khuỷu Kingman tại 0.85+); kiểm chứng Little's Law \(L = \lambda W\) |
Luôn chạy song song vòng mở k6 constant-arrival-rate (kiểm dropped_iterations == 0) với kịch bản hỗn hợp Locust |
Trụ cột 4 — Phòng thí nghiệm Công nghiệp: webapi_serving_lab & Kiểm định 19/19 pytest#
4.1 Kiến trúc Gói & Hợp đồng An toàn Môi trường#
labs/lab-04-fastapi-auth-tests-and-locust/
├── pyproject.toml # fastapi>=0.115, pydantic>=2.0, uvicorn>=0.30, httpx>=0.27, numpy, opentelemetry-sdk>=1.28; ruff, mypy strict
├── uv.lock # Tệp khóa tái lập 33 gói (Python >=3.12) giải quyết qua uv lock
├── README.md # Hướng dẫn thực hành 100% tiếng Việt
├── locustfile.py # Kịch bản Locust HttpUser (/v1/predict, /v1/stream SSE, probes, RBAC 403)
├── k6_load_test.js # Kịch bản k6 vòng mở constant-arrival-rate (TTFT, p95/p99, dropped_iterations)
├── src/
│ └── webapi_serving_lab/
│ ├── __init__.py
│ ├── schemas_and_auth.py # Pydantic v2 strict, RFC 9457 ProblemDetail, HMAC-SHA256 API Keys, HS256 JWT (chặn alg=none), RBAC
│ ├── app.py # FastAPI create_serving_app, OTel TracerProvider/MeterProvider, OrderedDict LRU+TTL/deque, Pure ASGI, RBAC /metrics & /v1/bench/*
│ └── load_benchmark.py # Benchmark ASGITransport/ASGI 3.0 offline: loop trap, Pure vs BaseHTTP, Kingman/Sakasegawa & Coordinated Omission
├── scripts/
│ └── run_lab_demo.py # CLI (--quick, --seed 42, --healthcheck, --output artifacts/t2_ch04_workbench_results.json)
├── tests/
│ └── test_webapi_serving_lab.py # 19 ca kiểm thử pytest (RBAC/feature-flag, LRU+TTL, OTel spans/metrics, quét AST)
└── artifacts/
└── t2_ch04_workbench_results.json # Báo cáo thực nghiệm định lượng (6 KPI, 4 bars, 4 tables)
Hợp đồng An toàn Môi trường: Toàn bộ load_benchmark.py và 19 bài kiểm thử pytest chạy 100% offline trên .venv Python 3.12.16 qua httpx.ASGITransport và TestClient mà không cần mạng ngoài. Lớp telemetry sử dụng OpenTelemetry SDK thật (opentelemetry-sdk==1.45.2) với TracerProvider + SimpleSpanProcessor + InMemorySpanExporter và MeterProvider + InMemoryMetricReader; trạng thái trong bộ nhớ (buckets, idempotency_cache, latencies_ms, telemetry_logs) bị chặn trần bằng OrderedDict LRU+TTL và collections.deque(maxlen=...); các tuyến /metrics và /v1/bench/* bị khóa sau cổng RBAC (admin) + feature-flag (enable_bench_endpoints=False mặc định). Trình quét AST ở test_16 kiểm toán toàn bộ mã nguồn (src/, scripts/, tests/, locustfile.py) chỉ cấm các mô-đun giải tuần tự không an toàn (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal).
4.2 Thực thi CLI Workbench & Bảng 6 Chỉ số Thực nghiệm (artifacts/t2_ch04_workbench_results.json)#
D:\FSDS-SOTA-Curriculum\.venv\Scripts\python.exe scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch04_workbench_results.json
Chỉ số KPI (artifacts/t2_ch04_workbench_results.json) |
Giá trị Đo kiểm Thực tế (.venv Python 3.12.16) |
Trạng thái |
|---|---|---|
kpi_async_blocking_vs_offload (Event-Loop Trap vs to_thread) |
368.01 -> 50.19 ms (7.33x faster; 16 reqs \(\times 20\text{ ms}\): trap 43.5 RPS làm /health/live lag 367.91 ms vs to_thread 318.8 RPS, /health/live lag 30.75 ms) |
ok (Đã xác minh) |
kpi_pure_asgi_vs_base_middleware (Pure ASGI vs BaseHTTPMiddleware) |
18,073.6 vs 4,482.7 RPS (4.03x RPS; SSE TTFT: Pure ASGI 29.87 ms / 5 chunks vs Buffered BaseHTTP 155.48 ms / 1 chunk, 5.21x TTFT delay) |
ok (Đã xác minh) |
kpi_kingman_saturation_knee (Kingman VUT rho=0.25 -> 0.93) |
56.24 -> 254.45 ms p99 (L = 18.83; 4 servers E[S]=12.0 ms, 333.33 RPS: \(\rho=0.25 \to 56.24\), \(\rho=0.50 \to 57.72\), \(\rho=0.70 \to 63.98\), \(\rho=0.85 \to 98.52\), \(\rho=0.93 \to 254.45\text{ ms}\); Sakasegawa pred_wait ở \(\rho=0.85\) là 14.074 ms vs sim=15.02 ms; L_pred=18.84 vs L_meas=18.83) |
warn (Đã xác minh) |
kpi_coordinated_omission_bias (Closed-Loop vs Open-Loop p99) |
2.72 vs 173.87 ms (63.92x gap; sự cố stall 160.0 ms: closed-loop V=1 400.3 RPS giấu lỗi vào 1/220 req chỉ đạt p99=2.72 ms, còn open-loop 152.5 RPS ghi nhận p95=154.97 ms, p99=173.87 ms) |
ok (Đã xác minh) |
kpi_auth_rbac_and_strict_v2 (Pydantic v2, JWT HS256 & RBAC) |
422 / 403 / 200 verified (alg=none blocked; 422 application/problem+json, alg_none_rejected=True, scorer->admin=403, admin=200, idempotency_replay_cached=True, burst 429s=2/5) |
ok (Đã xác minh) |
kpi_k8s_probes_and_sigterm_drain (Outage & SIGTERM Drain) |
live=200 / ready=503 (drain=503; khi DB lỗi degraded=True, /health/live giữ 200 còn /health/ready trả 503; khi nhận SIGTERM, /health/ready lập tức trả 503) |
ok (Đã xác minh) |
4.3 Hợp đồng 19 Ca Kiểm thử pytest (tests/test_webapi_serving_lab.py)#
Toàn bộ 19/19 ca kiểm thử đạt xanh tuyệt đối (19 passed), ruff check src scripts tests locustfile.py đạt All checks passed!, mypy src đạt 0 lỗi, và uv.lock giải quyết sạch 33 gói:
| # | Tên Hàm Kiểm thử (test_webapi_serving_lab.py) |
Khẳng định & Bất biến Bắt buộc |
|---|---|---|
| 1 | test_01_pydantic_v2_strict_validation_and_defaults |
Kiểm chứng StrictPredictRequest từ chối ép kiểu ("1.0", 1.0 vào int, "true"), từ chối trường lạ (extra="forbid"), từ chối NaN và biên vượt \(10^6\), đồng thời cách ly default_factory=dict. |
| 2 | test_02_http_422_rfc9457_problem_detail_response |
Xác nhận phản hồi 422 trả chuẩn Content-Type: application/problem+json (RFC 9457), giữ nguyên X-Request-ID, và liệt kê danh sách errors có cấu trúc. |
| 3 | test_03_predict_single_batch_and_idempotency_key_conflict |
Kiểm tra /v1/predict, /v1/predict-batch, tái phát cùng Idempotency-Key trả cached_idempotency=True, còn đổi payload cùng khóa bị chặn 409 Conflict RFC 9457. |
| 4 | test_04_jwt_hs256_lifecycle_and_alg_none_forgery_rejected |
Kiểm định encode_hs256_jwt / verify_hs256_jwt (RFC 7519) và từ chối mọi tấn công: alg="none", alg="RS256", token hết hạn exp, sai iss/aud, và sửa chữ ký. |
| 5 | test_05_api_key_constant_time_hash_storage_and_401_missing |
Xác nhận APIKeyRegistry không lưu khóa thô (chỉ lưu digest SHA-256 64 hex), kiểm chứng X-API-Key qua hmac.compare_digest, và trả 401 + WWW-Authenticate: Bearer khi thiếu khóa. |
| 6 | test_06_rbac_scope_enforcement_401_vs_403 |
Phân tách reader (200 /v1/stream, 403 /v1/predict), scorer (200 /v1/predict, 403 /v1/admin/reload), và admin (200 /v1/admin/reload cập nhật phiên bản mô hình). |
| 7 | test_07_sse_streaming_endpoint_chunks_and_events |
Kiểm tra /v1/stream trả text/event-stream, Cache-Control: no-cache, X-Middleware-Mode: pure-asgi, đủ 5 khung event: token (id: 0..4) và khung kết event: done. |
| 8 | test_08_pure_asgi_middleware_zero_buffering_ttft_and_rps_advantage |
Đo thực tế ASGI 3.0 chứng minh Pure ASGI nhanh hơn BaseHTTPMiddleware (>= 1.4x RPS) và giữ nguyên 5 chunk không bị đệm thành 1 cục làm tăng TTFT >= 2.0x. |
| 9 | test_09_pure_asgi_request_id_telemetry_and_429_rate_limiter |
Xác nhận X-Request-ID, X-Process-Time-Ms, log telemetry, Token Bucket 429 Retry-After cô lập theo X-Client-ID, và miễn giới hạn tốc độ cho /health/*. |
| 10 | test_10_async_blocking_trap_vs_to_thread_real_asgi_speedup |
Chạy httpx.ASGITransport đồng thời chứng minh time.sleep trong async def làm /health/live treo >= 80 ms (367.91 ms), trong khi to_thread tăng tốc >= 3.0x (7.33x). |
| 11 | test_11_kingman_vut_saturation_knee_and_littles_law_identity |
Kiểm tra hàm Kingman/Sakasegawa bùng nổ theo \(\rho \to 1\), xác minh số mũ \(\sqrt{2(c+1)} - 1\), đường cong p99 tăng đơn điệu (\(\rho=0.25 \to 0.93\)), và Định luật Little \(L = \lambda W\) sai số < 15%. |
| 12 | test_12_coordinated_omission_real_asgi_open_vs_closed_loop |
Chạy tải thật trên FastAPI chứng minh open_loop p99 cao hơn closed_loop p99 tối thiểu 3.0x (173.87 vs 2.72 ms, 63.92x). |
| 13 | test_13_k8s_liveness_readiness_dependency_outage_and_sigterm_drain |
Xác minh lifespan start/stop, degraded=True giữ /health/live == 200 còn /health/ready == 503, install_sigterm_handler xử lý SIGTERM bật draining=True, và /metrics có auth admin trả OTel snapshot. |
| 14 | test_14_load_scripts_locust_and_k6_syntax_and_contracts |
Kiểm tra ast.parse + nạp mô-đun locustfile.py (ServingAPIUser) và rà soát đầy đủ cấu trúc constant-arrival-rate, dropped_iterations, fsds_sse_ttft_ms trong k6_load_test.js. |
| 15 | test_15_cli_demo_quick_healthcheck_and_workbench_json |
Chạy CLI run_lab_demo.py --healthcheck và --quick --seed 42 --output ... kiểm chứng 6 KPI, 4 bars, 4 tables. |
| 16 | test_16_security_only_ast_scan_no_unsafe_deserialization |
Quét AST toàn bộ src/, scripts/, tests/, locustfile.py bảo đảm 0 import giải tuần tự không an toàn (pickle, joblib, cloudpickle, dill, shelve, marshal). |
| 17 | test_17_hardened_bench_and_metrics_rbac_and_feature_flag_401_403 |
Xác minh /metrics và /v1/bench/* trả 401 khi thiếu auth, 403 với reader/scorer hoặc khi tắt feature flag, và 200 với admin khi được phép. |
| 18 | test_18_bounded_state_lru_and_ttl_eviction_buckets_idempotency_logs |
Kiểm chứng giới hạn LRU + TTL eviction trên buckets và idempotency_cache, cùng cửa sổ deque(maxlen=...) cho latencies_ms và telemetry_logs. |
| 19 | test_19_real_opentelemetry_spans_attributes_traceparent_and_metrics |
Xác nhận InMemorySpanExporter bắt đủ root/child span (ml.inference.predict), lan truyền W3C traceparent, và InMemoryMetricReader chỉ dùng nhãn low-cardinality. |
Trụ cột 5 — Tài liệu Đọc SOTA 2024–2026 & Bài tập Đánh giá Năng lực#
5.1 Danh mục Tài liệu Kinh điển & Chuẩn Kỹ thuật (Curated Reading List)#
- Fielding, R. T. (UC Irvine PhD Dissertation, 2000). Architectural Styles and the Design of Network-based Software Architectures (Chapter 5: Representational State Transfer — REST).
Vì sao quan trọng: Đặt nền móng lý thuyết cho 6 ràng buộc kiến trúc Web, sự phân tách trạng thái tài nguyên và ngữ nghĩa an toàn/lũy đẳng của HTTP. - Little, J. D. C. (Operations Research, Vol. 9, No. 3, 1961, pp. 383–387). A Proof for the Queuing Formula: \(L = \lambda W\).
Vì sao quan trọng: Định lý tổng quát không phụ thuộc phân phối giúp quy đổi trực tiếp giữa tốc độ tải \(\lambda\), độ trễ \(W\), và kích thước bể luồng/worker \(L\). - Kingman, J. F. C. (Mathematical Proceedings of the Cambridge Philosophical Society, Vol. 57, Issue 4, 1961, pp. 902–904) & Sakasegawa, H. (Annals of the Institute of Statistical Mathematics, 1977). The Single Server Queue in Heavy Traffic & An Approximation Formula \(L_q \approx \alpha \cdot \beta \cdot \gamma\).
Vì sao quan trọng: Thiết lập phương trình xấp xỉ VUT và mở rộng \(GI/G/c\) với số mũ \(\sqrt{2(c+1)} - 1\) giải thích lý do độ trễ hàng đợi nổ tung tại khúc khuỷu bão hòa. - Jones, M., Bradley, J., & Sakimura, N. (IETF
RFC 7519, May 2015) + McLean, T. (Auth0 Disclosure, March 2015). JSON Web Token (JWT) & Critical Vulnerabilities in JSON Web Token Libraries (alg: none&RS256 -> HS256).
Vì sao quan trọng: Định nghĩa chuẩn JWT và giải thích bài học xương máu về ép buộc danh sách thuật toán cho phép phía máy chủ. - Nottingham, M., Wilde, E., & Dalal, S. (IETF
RFC 9457, July 2023 — obsoletesRFC 7807). Problem Details for HTTP APIs.
Vì sao quan trọng: Chuẩn hóa hợp đồng JSON lỗi máy-đọc (application/problem+json) thống nhất cho API Gateway và các dịch vụFastAPI/Pydantic v2. - Tene, G. (Azul Systems, How NOT to Measure Latency) &
Grafana k6Arrival-Rate Docs +OpenTelemetrySemantic Conventions (2024–2026). Coordinated Omission, Open-Loopconstant-arrival-rate, & W3C Trace Context / Metric Cardinality Discipline.
Vì sao quan trọng: Giải mã nguyên nhân kiểm thử tải vòng đóng bỏ sót thảm họap99và chuẩn hóa quan trắc đa tầng không gây nổ bộ nhớ TSDB.
5.2 Tám Điểm Kiểm tra Tư duy (Q1–Q8) & Sáu Bài tập Trọng số#
- Q1 (
REST,gRPC,GraphQL,WebSockets,SSE): Phân biệtIdempotency-Keyvới độ an toàn HTTP, giải thích vì sao L4 TCP LB làm kẹtgRPC, bẫyN+1/ độ sâu củaGraphQL, và lý do LLM ưu tiênSSEthay choWebSockets. - Q2 (
AuthN/AuthZ, API Keys,JWTRFC 7519&RBAC): Phân biệt401với403, giải thích tấn công kênh kề==so vớihmac.compare_digest, và tái dựng luồng tấn côngalg: "none"cùngRS256 -> HS256. - Q3 (
FastAPIASGI,async defvs.defAnyIO40&lifespan): Lý giải vì saotime.sleeptrongasync defđánh sập cả/health/live, giới hạn40luồng AnyIO trongdef, và vai tròlifespanvớihttpx.AsyncClient. - Q4 (
Pydantic v2strict=True&RFC 9457): Chỉ ra sự khác biệt giữastrict=Truevs. mặc định lax, tầm quan trọng củaextra="forbid"+allow_inf_nan=False, và cấu trúcapplication/problem+json. - Q5 (
Pure ASGI Middlewarevs.BaseHTTPMiddleware&OpenTelemetry): Phân tích nguyên nhânBaseHTTPMiddlewaretốn4.03xCPU/RPS hơn và làmSSE TTFTtăng5.21xkhi chạm tới iterator phản hồi, cùng nguyên tắc giữ nhãn metric low-cardinality và lan truyềnW3C traceparent. - Q6 (Đầu dò K8s & Ngắt
SIGTERM): Chứng minh vì sao gắn DB check vàolivenessProbegâyCrashLoopBackOfftoàn cụm và phác thảo trình tựpreStop+/health/ready -> 503+ đếmin_flight. - Q7 (Định luật Little & Kingman/Sakasegawa VUT): Tính năng lực tối đa từ \(L = \lambda W\), chứng minh độ trễ đợi tăng
49xtừ \(\rho = 0.50\) lên \(\rho = 0.98\), và tính xác suất hỏng đuôi qua \(20\) lời gọi fan-out \(1 - 0.99^{20}\). - Q8 (
Coordinated Omission—Locustvs.k6): Giải thích cơ chế vòng đóng làmp99tụt63.92x(2.72 msvs173.87 ms) khi máy chủ dừng160 ms, và ý nghĩa củadropped_iterationstrongk6.
Sáu Bài tập Thực hành (Gợi ý Từng bước Tích hợp Tại Mục Quiz Cuối Trang)#
- Bài tập 1 (15 điểm) — Hợp đồng
Pydantic v2strict=True,RFC 9457&Idempotency-Key:- Bước thực hành: Định nghĩa
StrictPredictRequest(ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)); gửiPOST /v1/predicthợp lệ kèmIdempotency-Key, gửi lại đúng body đó, sau đó gửi lại cùng khóa nhưng khácfeatures, và gửi một request sai kiểu/khóa lạ; kiểm tra giới hạn LRU+TTL trênidempotency_cache. - Tiêu chí đạt: Yêu cầu lặp trả
cached_idempotency=True, đổi body trả409 Conflictapplication/problem+json, sai kiểu/trường lạ trả422, và vượttest_01–test_03,test_18.
- Bước thực hành: Định nghĩa
- Bài tập 2 (15 điểm) — Xác thực
JWTHS256(RFC 7519), API Key Hằng thời gian &RBAC:- Bước thực hành: Kiểm tra
APIKeyRegistrychỉ lưu digest SHA-256 (hmac.compare_digest), tạo JWT giả mạo với header{"alg": "none"}và JWT hết hạn đưa vàoverify_hs256_jwt, và thử gọi/v1/predict,/v1/admin/reload,/metrics,/v1/bench/*bằng 3 vai tròreader,scorer,admin. - Tiêu chí đạt: Chặn
alg="none"/exp/aud/isstại401,reader/scorernhận403trên/metricsvà/v1/bench/*,adminđạt200đúng cổng feature-flag, vượttest_04–test_06,test_17.
- Bước thực hành: Kiểm tra
- Bài tập 3 (20 điểm) —
Pure ASGI Middleware,OpenTelemetry, Token Bucket429& LuồngSSE:- Bước thực hành: Chạy
benchmark_sse_pure_asgi_vs_base_middleware()so sánhTTFTvàping RPS; gửiGET /v1/streamkiểm tra các khungid:/event:/data:; gửitraceparentvà kiểm tra span/metric trongInMemorySpanExportervàInMemoryMetricReader; bắn quábursttrên cùngX-Client-IDđể kích hoạt429 Retry-After. - Tiêu chí đạt: Pure ASGI đạt
18,073.6 RPSvs4,482.7 RPS,TTFTgiữ ở29.87 msso với155.48 mskhi đệm, OTel ghi nhận span + metric low-cardinality, vượttest_07–test_09,test_19.
- Bước thực hành: Chạy
- Bài tập 4 (15 điểm) — Cô lập Vòng lặp
FastAPI(async defBlocking Trap vs.asyncio.to_thread):- Bước thực hành: Chạy
benchmark_async_blocking_vs_offload(concurrency=16, delay_ms=20.0)trênhttpx.ASGITransportđo đồng thời tổng thời gian hoàn thành và độ trễ đầu dò/health/livechen ngang giữa lúc chạy tải. - Tiêu chí đạt: Thấy rõ
blocking_trapkhóa/health/livetới367.91 ms(wall=368.01 ms), cònto_threadgiảm xuống50.19 ms(7.33x) và/health/livehồi sau30.75 ms, vượttest_10.
- Bước thực hành: Chạy
- Bài tập 5 (15 điểm) — Tách bạch Đầu dò K8s (
/health/livevs./health/ready) &SIGTERMDrain:- Bước thực hành: Khởi tạo app qua
TestClientkích hoạtlifespan, đặtdegraded = Truekiểm tra trạng thái 2 đầu dò, gắninstall_sigterm_handlerrồi phát tín hiệusignal.SIGTERM, gọi/metricsvới quyềnadmin, và chạy CLIrun_lab_demo.py --healthcheck. - Tiêu chí đạt: Khi DB lỗi
degraded=True:/health/live == 200nhưng/health/ready == 503; sauSIGTERM:/health/ready == 503; CLI--healthchecktrả JSONready=true, vượttest_13,test_15.
- Bước thực hành: Khởi tạo app qua
- Bài tập 6 (20 điểm) — Hàng đợi
Kingman/Sakasegawa VUT,Coordinated Omission,Locust/k6&19/19 pytest:- Bước thực hành: Chạy
benchmark_kingman_saturation_and_coordinated_omission(seed=42)đối chiếu đường cong \(\rho = 0.25 \to 0.93\), kiểm nghiệm \(L = \lambda W\), so sánhclosed_loopvs.open_loopp99, rà soátlocustfile.py&k6_load_test.js, chạyruff check,mypy src, vàpytest -p no:cacheprovider -v. - Tiêu chí đạt:
Kingmantăng đơn điệu56.24 -> 254.45 ms, sai số Little's Law< 1%, Open-Loop vạch trần Coordinated Omission (173.87vs2.72 ms,63.92x),ruff&mypy0lỗi, AST0import giải tuần tự cấm, và19/19 pytestPASS.
- Bước thực hành: Chạy
5.3 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric — 100 Điểm)#
| Hạng mục Đánh giá | Trọng số | Tiêu chí Đạt Chuẩn Nghiệm thu (>= 80/100) |
Lệnh / Ca Kiểm thử Đối chứng |
|---|---|---|---|
1. Pydantic v2 Strict, RFC 9457 & Idempotency-Key (LRU+TTL) |
15 | Chặn ép kiểu/khóa lạ/NaN (422 problem+json), phát lại đúng khóa, chặn lệch payload (409), giới hạn LRU+TTL. |
Tests 1, 2, 3, 18 |
2. Bảo mật JWT HS256 (RFC 7519), API Key & RBAC (/metrics, /v1/bench/*) |
20 | Lưu SHA-256 + hmac.compare_digest; từ chối alg="none"/RS256/hết hạn/iss/aud; phân biệt 401 vs 403 trên mọi route nhạy cảm. |
Tests 4, 5, 6, 17 |
3. Pure ASGI Middleware, OpenTelemetry, Token Bucket 429 & SSE |
20 | Không đệm luồng SSE (TTFT 29.87 vs 155.48 ms), tăng RPS >= 1.4x, 429 cô lập client, ghi nhận đủ span/metric OTel low-cardinality. |
Tests 7, 8, 9, 19 |
4. Cô lập Event Loop, Đầu dò K8s & SIGTERM Drain |
20 | to_thread giải phóng loop (>= 3.0x nhanh hơn, /health/live thông suốt), /health/ready 503 khi lỗi DB hoặc SIGTERM. |
Tests 10, 13, 15 |
5. Lý thuyết Hàng đợi, Coordinated Omission, Locust/k6 & Quality Gate |
25 | Kiểm chứng Kingman/Sakasegawa + \(L = \lambda W\), phơi bày CO >= 3.0x, locustfile.py/k6_load_test.js hợp lệ, uv.lock, ruff & mypy 0 lỗi, 19/19 pytest. |
Tests 11, 12, 14–16 + ruff + mypy |
| Tổng cộng | 100 | Đạt tối thiểu 80/100 tổng điểm và không có mục nào 0 điểm (toàn bộ 19/19 test phải PASS). |
pytest -p no:cacheprovider -v |
FastAPI Concurrency (16 x 20.0ms): Wall & /health/live Probe (ms)
Middleware Architecture: SSE Time-To-First-Token (TTFT ms) & Throughput
Kingman VUT Tail Latency Explosion Across Utilization rho = 0.25 -> 0.93 (ms)
FastAPI ASGI Coordinated Omission (160.0 ms Pause): Closed-Loop vs Open-Loop p99
FastAPI Event-Loop Isolation & Pure ASGI vs BaseHTTPMiddleware Benchmarks
| benchmark_mode | wall_or_ttft_ms | p99_or_total_ms | throughput_rps | verdict |
|---|---|---|---|---|
| async_def_blocking_trap | 368.01 ms (live=367.91 ms) | 23.56 ms | 43.5 | EVENT_LOOP_FROZEN |
| asyncio_to_thread_offload | 50.19 ms (live=30.75 ms) | 31.0 ms | 318.8 | PARALLEL_7.33x |
| pure_asgi_middleware | TTFT=29.87 ms | stream=137.45 ms | 18073.6 | ZERO_COPY_4.03x_RPS |
| base_http_middleware_buffered | TTFT=155.48 ms | stream=155.48 ms | 4482.7 | TTFT_DELAYED_5.21x |
Queueing Theory Verification: Kingman VUT & Little's Law (L = lambda * W)
| rho_util | arrival_rps | p50_ms | p95_ms | p99_ms | littles_L_pred_vs_meas |
|---|---|---|---|---|---|
| 0.25 | 83.3 | 8.41 | 36.15 | 56.24 | 1.01 / 1.01 |
| 0.50 | 166.7 | 9.49 | 37.93 | 57.72 | 2.19 / 2.19 |
| 0.70 | 233.3 | 12.5 | 44.95 | 63.98 | 3.84 / 3.84 |
| 0.85 | 283.3 | 21.08 | 72.49 | 98.52 | 7.7 / 7.69 |
| 0.93 | 310.0 | 43.05 | 189.1 | 254.45 | 18.84 / 18.83 |
Real FastAPI ASGITransport Coordinated Omission Audit (Closed-Loop vs Open-Loop)
| generator_mode | achieved_rps | p50_ms | p95_ms | p99_ms | max_ms |
|---|---|---|---|---|---|
| closed_loop_v1 | 400.3 | 1.62 | 2.26 | 2.72 | 176.2 |
| open_loop_150rps | 152.5 | 5.16 | 154.97 | 173.87 | 182.47 |
Security Hardening (Pydantic v2, JWT HS256, RBAC, Rate Limit) & K8s Probes
| control_surface | expected_behavior | observed_result | status |
|---|---|---|---|
| pydantic_v2_strict_and_rfc9457 | 422 application/problem+json on extra key / coercion | 422 (application/problem+json) | ENFORCED |
| jwt_hs256_alg_none_defense | Reject alg='none' unsigned token | rejected=True | SECURED |
| rbac_scope_separation | scorer->403, admin->200 on /v1/admin/reload | scorer=403, admin=200 | ENFORCED |
| idempotency_and_token_bucket_429 | Replay cached_idempotency=True; burst>3 -> 429 | replay=True, 429s=2; metrics=200 | PROTECTED |
| k8s_probes_and_sigterm_drain | Outage: live=200 & ready=503; SIGTERM: ready=503 | live=200, outage_ready=503, drain_ready=503 | ZERO_DOWNTIME |
03-track-2-data-and-ai-engineering/part-01-software-systems-foundations/labs/lab-04-fastapi-auth-tests-and-locust
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "webapi-serving-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 Lab 04: High-Performance FastAPI Serving, Pydantic v2 Strict Validation, RFC 7519 HS256 JWT & RBAC, Pure ASGI Middleware, K8s Probes & Open-Loop Load Testing"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"pydantic>=2.0",
"uvicorn>=0.30",
"httpx>=0.27",
"numpy>=1.24",
"opentelemetry-sdk>=1.28",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.8",
"mypy>=1.10",
]
[project.scripts]
fsds-webapi-lab = "webapi_serving_lab.app:main"
[tool.setuptools.packages.find]
where = ["src"]
[tool.ruff]
target-version = "py312"
line-length = 105
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "RUF"]
[tool.mypy]
python_version = "3.12"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
"""Locust load test suite for FSDS-SOTA-2026 Track 2 Lab 04 (FastAPI Serving API).
Run interactively:
locust -f locustfile.py --host http://127.0.0.1:8000
Headless CI run:
locust -f locustfile.py --headless -u 40 -r 10 -t 30s --host http://127.0.0.1:8000
Note: Default Locust HttpUser wait loops implement CLOSED-LOOP concurrency. For true
open-loop arrival-rate tests immune to Coordinated Omission, pair with `k6_load_test.js`
(`constant-arrival-rate`) or `constant_throughput` pacing under headroom.
"""
from __future__ import annotations
import itertools
import time
try:
from locust import HttpUser, between, task
except ImportError: # pragma: no cover - allows syntax/static checks when locust CLI is optional
class HttpUser: # type: ignore[no-redef]
abstract = True
wait_time = None
def between(_min_wait: float, _max_wait: float): # type: ignore[no-untyped-def]
return lambda _self: 0.1
def task(weight: int = 1): # type: ignore[no-untyped-def]
def _decorator(fn): # type: ignore[no-untyped-def]
fn.locust_task_weight = weight
return fn
return _decorator
_SEQ = itertools.count(1)
class ServingAPIUser(HttpUser):
"""Mixed ML inference, SSE token streaming, probe, and RBAC negative-path user."""
wait_time = between(0.02, 0.10)
def on_start(self) -> None:
self.scorer_headers = {
"X-API-Key": "fsds_dev_scorer_key_1a2b3c4d5e6f7890",
"Content-Type": "application/json",
}
@task(6)
def predict_single(self) -> None:
seq_id = next(_SEQ)
payload = {
"request_id": f"locust-{seq_id:06d}",
"model_version": "v2.1.0",
"features": [0.65, -0.22, 1.05, 0.33],
"top_k": 1,
"return_probabilities": True,
"metadata": {"client": "locust"},
}
headers = {**self.scorer_headers, "Idempotency-Key": f"idem-{seq_id:06d}"}
with self.client.post(
"/v1/predict",
json=payload,
headers=headers,
name="/v1/predict",
catch_response=True,
) as resp:
if resp.status_code != 200:
resp.failure(f"Expected 200 OK, got {resp.status_code}")
@task(2)
def stream_sse_tokens(self) -> None:
t0 = time.perf_counter()
with self.client.get(
"/v1/stream?n_tokens=6&token_delay_ms=6",
headers={"X-API-Key": "fsds_dev_scorer_key_1a2b3c4d5e6f7890"},
name="/v1/stream [SSE]",
stream=True,
catch_response=True,
) as resp:
if resp.status_code != 200:
resp.failure(f"SSE expected 200, got {resp.status_code}")
return
first_chunk_ms: float | None = None
for chunk in resp.iter_content(chunk_size=None):
if chunk and first_chunk_ms is None:
first_chunk_ms = (time.perf_counter() - t0) * 1000.0
if first_chunk_ms is None:
resp.failure("SSE stream yielded zero chunks")
@task(1)
def kubernetes_health_probes(self) -> None:
self.client.get("/health/live", name="/health/live")
self.client.get("/health/ready", name="/health/ready")
@task(1)
def rbac_forbidden_admin_probe(self) -> None:
with self.client.post(
"/v1/admin/reload",
json={"bias": 0.1, "temperature": 1.0, "model_version": "v2.1.0"},
headers=self.scorer_headers,
name="/v1/admin/reload [403-check]",
catch_response=True,
) as resp:
if resp.status_code == 403:
resp.success()
else:
resp.failure(f"Expected 403 Forbidden for scorer role, got {resp.status_code}")
import http from "k6/http";
import { check } from "k6";
import { Trend, Rate } from "k6/metrics";
/**
* FSDS-SOTA-2026 Track 2 Lab 04 — Open-Loop Load Test (k6)
* Uses `constant-arrival-rate` to inject requests on an independent wall-clock schedule,
* eliminating Gil Tene's Coordinated Omission bias and tracking `dropped_iterations`.
*/
const predictLatencyMs = new Trend("fsds_predict_duration_ms", true);
const sseTtftMs = new Trend("fsds_sse_ttft_ms", true);
const authErrorRate = new Rate("fsds_unexpected_errors");
const BASE_URL = __ENV.BASE_URL || "http://127.0.0.1:8000";
const SCORER_API_KEY = __ENV.SCORER_API_KEY || "fsds_dev_scorer_key_1a2b3c4d5e6f7890";
export const options = {
scenarios: {
open_loop_predict: {
executor: "constant-arrival-rate",
rate: Number(__ENV.TARGET_RPS || 120),
timeUnit: "1s",
duration: __ENV.DURATION || "30s",
preAllocatedVUs: 40,
maxVUs: 250,
exec: "runPredictWorkload",
},
open_loop_sse_stream: {
executor: "constant-arrival-rate",
rate: Number(__ENV.SSE_RPS || 15),
timeUnit: "1s",
duration: __ENV.DURATION || "30s",
preAllocatedVUs: 10,
maxVUs: 60,
exec: "runSseWorkload",
},
},
thresholds: {
http_req_failed: ["rate<0.01"],
fsds_predict_duration_ms: ["p(95)<60", "p(99)<120"],
fsds_sse_ttft_ms: ["p(95)<80"],
dropped_iterations: ["count==0"],
},
};
export function runPredictWorkload() {
const iterId = `${__VU}-${__ITER}`;
const payload = JSON.stringify({
request_id: `k6-req-${iterId}`,
model_version: "v2.1.0",
features: [0.42, -0.18, 1.15, 0.77],
top_k: 1,
return_probabilities: true,
metadata: { source: "k6-open-loop" },
});
const params = {
headers: {
"Content-Type": "application/json",
"X-API-Key": SCORER_API_KEY,
"Idempotency-Key": `idem-${iterId}`,
},
};
const res = http.post(`${BASE_URL}/v1/predict`, payload, params);
predictLatencyMs.add(res.timings.duration);
const ok = check(res, {
"predict status is 200": (r) => r.status === 200,
"pure-asgi header present": (r) => r.headers["X-Middleware-Mode"] === "pure-asgi",
});
authErrorRate.add(!ok);
}
export function runSseWorkload() {
const res = http.get(`${BASE_URL}/v1/stream?n_tokens=6&token_delay_ms=6`, {
headers: { "X-API-Key": SCORER_API_KEY },
});
sseTtftMs.add(res.timings.waiting);
const ok = check(res, {
"sse status is 200": (r) => r.status === 200,
"sse content-type": (r) => (r.headers["Content-Type"] || "").includes("text/event-stream"),
"sse received done event": (r) => String(r.body).includes("event: done"),
});
authErrorRate.add(!ok);
}
"""FSDS-SOTA-2026 Track 2 Lab 04: High-Performance FastAPI Serving & Load Testing."""
from __future__ import annotations
from webapi_serving_lab.app import (
AppRuntimeState,
RequestContextAndRateLimitMiddleware,
create_serving_app,
install_sigterm_handler,
restore_sigterm_handler,
run_local_healthcheck,
trigger_graceful_drain,
)
from webapi_serving_lab.load_benchmark import (
benchmark_async_blocking_vs_offload,
benchmark_kingman_saturation_and_coordinated_omission,
benchmark_sse_pure_asgi_vs_base_middleware,
kingman_vut_expected_wait_ms,
)
from webapi_serving_lab.schemas_and_auth import (
ROLE_SCOPES,
AdminReloadRequest,
APIKeyRecord,
APIKeyRegistry,
AuthError,
AuthPrincipal,
BatchPredictRequest,
BatchPredictResponse,
PredictResponse,
ProblemDetail,
ScopeBenchRunner,
ScopeMetricsReader,
ScopeModelAdmin,
ScopePredictWriter,
ScopeStreamReader,
StrictPredictRequest,
build_default_api_key_registry,
encode_hs256_jwt,
get_current_principal,
hash_api_key,
require_scope,
verify_hs256_jwt,
)
__all__ = [
"ROLE_SCOPES",
"APIKeyRecord",
"APIKeyRegistry",
"AdminReloadRequest",
"AppRuntimeState",
"AuthError",
"AuthPrincipal",
"BatchPredictRequest",
"BatchPredictResponse",
"PredictResponse",
"ProblemDetail",
"RequestContextAndRateLimitMiddleware",
"ScopeBenchRunner",
"ScopeMetricsReader",
"ScopeModelAdmin",
"ScopePredictWriter",
"ScopeStreamReader",
"StrictPredictRequest",
"benchmark_async_blocking_vs_offload",
"benchmark_kingman_saturation_and_coordinated_omission",
"benchmark_sse_pure_asgi_vs_base_middleware",
"build_default_api_key_registry",
"create_serving_app",
"encode_hs256_jwt",
"get_current_principal",
"hash_api_key",
"install_sigterm_handler",
"kingman_vut_expected_wait_ms",
"require_scope",
"restore_sigterm_handler",
"run_local_healthcheck",
"trigger_graceful_drain",
"verify_hs256_jwt",
]
"""Strict Pydantic v2 schemas, RFC 9457 Problem Details, constant-time API Keys, JWT & RBAC."""
from __future__ import annotations
import base64
import binascii
import hashlib
import hmac
import json
import math
import time
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Annotated, Any
from fastapi import Depends, Header, Request
from pydantic import BaseModel, ConfigDict, Field, field_validator
ROLE_SCOPES: dict[str, tuple[str, ...]] = {
"reader": ("health:read", "stream:read"),
"scorer": ("health:read", "stream:read", "predict:write"),
"admin": (
"health:read",
"stream:read",
"predict:write",
"model:reload",
"metrics:read",
"bench:run",
),
}
class StrictPredictRequest(BaseModel):
"""Strict inference contract rejecting type coercion, Inf/NaN, and unknown keys."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
request_id: str = Field(min_length=4, max_length=64)
model_version: str = Field(default="v2.1.0", pattern=r"^v\d+\.\d+\.\d+$")
features: list[float] = Field(min_length=2, max_length=32)
top_k: int = Field(default=1, ge=1, le=5)
return_probabilities: bool = Field(default=False)
metadata: dict[str, str] = Field(default_factory=dict)
@field_validator("features")
@classmethod
def _validate_finite_bounded_features(cls, values: list[float]) -> list[float]:
for idx, val in enumerate(values):
if not math.isfinite(val):
raise ValueError(f"Feature at index {idx} must be finite")
if abs(val) > 1_000_000.0:
raise ValueError(f"Feature at index {idx} exceeds magnitude bound 1e6")
return values
class PredictResponse(BaseModel):
"""Typed single-item model inference response."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
request_id: str
model_version: str
score: float
label: str
probability: float | None = None
cached_idempotency: bool = False
class BatchPredictRequest(BaseModel):
"""Strict batch inference request with bounded batch size."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
items: list[StrictPredictRequest] = Field(min_length=1, max_length=64)
class BatchPredictResponse(BaseModel):
"""Typed batch inference response."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True)
count: int
model_version: str
results: list[PredictResponse]
class AdminReloadRequest(BaseModel):
"""Admin-only runtime parameter reload schema."""
model_config = ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False)
bias: float = Field(ge=-5.0, le=5.0)
temperature: float = Field(default=1.0, gt=0.0, le=5.0)
model_version: str = Field(default="v2.2.0", pattern=r"^v\d+\.\d+\.\d+$")
class ProblemDetail(BaseModel):
"""RFC 9457 Problem Details payload for HTTP APIs (supersedes RFC 7807)."""
model_config = ConfigDict(extra="forbid", frozen=True)
type: str
title: str
status: int = Field(ge=400, le=599)
detail: str
instance: str
request_id: str | None = None
errors: list[dict[str, Any]] | None = None
class AuthError(Exception):
"""Structured authentication or authorization failure mapped to RFC 9457."""
def __init__(self, status_code: int, code: str, title: str, detail: str) -> None:
super().__init__(detail)
self.status_code = status_code
self.code = code
self.title = title
self.detail = detail
@dataclass(frozen=True, slots=True)
class AuthPrincipal:
"""Authenticated caller identity and resolved RBAC permissions."""
subject: str
auth_method: str
role: str
scopes: frozenset[str]
token_id: str | None = None
@dataclass(frozen=True, slots=True)
class APIKeyRecord:
"""Stored API key metadata holding only salted/peppered SHA-256 hex digest."""
key_id: str
key_hash_hex: str
subject: str
role: str
scopes: tuple[str, ...]
def hash_api_key(raw_key: str, pepper: str = "fsds-key-pepper-2026") -> str:
"""Compute keyed HMAC-SHA256 digest of a raw API key for safe storage."""
return hmac.new(pepper.encode("utf-8"), raw_key.encode("utf-8"), hashlib.sha256).hexdigest()
class APIKeyRegistry:
"""Constant-time API key verifier indexed by non-secret records."""
def __init__(
self,
records: tuple[APIKeyRecord, ...] = (),
pepper: str = "fsds-key-pepper-2026",
) -> None:
self._records = records
self._pepper = pepper
def verify(self, raw_key: str) -> AuthPrincipal:
if not raw_key or len(raw_key) < 12:
raise AuthError(
status_code=401,
code="invalid-api-key",
title="Invalid API Key",
detail="API key header is malformed or too short.",
)
candidate_hash = hash_api_key(raw_key, pepper=self._pepper)
matched_record: APIKeyRecord | None = None
for rec in self._records:
# Evaluate every record with constant-time compare_digest to avoid length/index timing leaks
if hmac.compare_digest(candidate_hash, rec.key_hash_hex):
matched_record = rec
if matched_record is None:
raise AuthError(
status_code=401,
code="invalid-api-key",
title="Invalid API Key",
detail="Presented X-API-Key credential was rejected.",
)
return AuthPrincipal(
subject=matched_record.subject,
auth_method="api_key",
role=matched_record.role,
scopes=frozenset(matched_record.scopes),
token_id=matched_record.key_id,
)
def build_default_api_key_registry() -> tuple[APIKeyRegistry, dict[str, str]]:
"""Build deterministic demo API keys (never logged/persisted plaintext in registry)."""
demo_keys = {
"reader": "fsds_dev_reader_key_9f8e7d6c5b4a3210",
"scorer": "fsds_dev_scorer_key_1a2b3c4d5e6f7890",
"admin": "fsds_dev_admin_key_0011223344556677",
}
records = tuple(
APIKeyRecord(
key_id=f"key-{role}-01",
key_hash_hex=hash_api_key(raw),
subject=f"svc-{role}",
role=role,
scopes=ROLE_SCOPES[role],
)
for role, raw in demo_keys.items()
)
return APIKeyRegistry(records=records), demo_keys
def _b64url_encode(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii")
def _b64url_decode(segment: str) -> bytes:
pad_len = (-len(segment)) % 4
padded = segment + ("=" * pad_len)
try:
return base64.urlsafe_b64decode(padded.encode("ascii"))
except (binascii.Error, UnicodeEncodeError) as exc:
raise AuthError(
status_code=401,
code="malformed-jwt",
title="Malformed JWT",
detail="JWT segment is not valid Base64URL.",
) from exc
def encode_hs256_jwt(
subject: str,
role: str,
secret: str,
*,
scopes: tuple[str, ...] | None = None,
issuer: str = "fsds-auth",
audience: str = "fsds-serving",
ttl_sec: int = 300,
now: float | None = None,
jti: str = "tok-001",
) -> str:
"""Create a standards-compliant RFC 7519 HS256 JWT."""
if not secret or len(secret) < 16:
raise ValueError("JWT HS256 secret must be at least 16 characters")
if role not in ROLE_SCOPES:
raise ValueError(f"Unknown RBAC role: {role!r}")
issued_at = int(time.time() if now is None else now)
header = {"alg": "HS256", "typ": "JWT"}
payload = {
"iss": issuer,
"sub": subject,
"aud": audience,
"iat": issued_at,
"nbf": issued_at,
"exp": issued_at + ttl_sec,
"jti": jti,
"role": role,
"scopes": list(ROLE_SCOPES[role] if scopes is None else scopes),
}
header_b64 = _b64url_encode(
json.dumps(header, separators=(",", ":"), sort_keys=True).encode("utf-8")
)
payload_b64 = _b64url_encode(
json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")
)
signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
signature = hmac.new(secret.encode("utf-8"), signing_input, hashlib.sha256).digest()
return f"{header_b64}.{payload_b64}.{_b64url_encode(signature)}"
def verify_hs256_jwt(
token: str,
secret: str,
*,
expected_issuer: str = "fsds-auth",
expected_audience: str = "fsds-serving",
now: float | None = None,
leeway_sec: int = 5,
) -> AuthPrincipal:
"""Verify RFC 7519 HS256 JWT; rejects alg=none, wrong alg, expired, or bad aud/iss."""
parts = token.split(".")
if len(parts) != 3 or not parts[0] or not parts[1]:
raise AuthError(
status_code=401,
code="malformed-jwt",
title="Malformed JWT",
detail="JWT must have exactly 3 dot-separated JWS segments.",
)
header_b64, payload_b64, sig_b64 = parts
try:
header = json.loads(_b64url_decode(header_b64).decode("utf-8"))
payload = json.loads(_b64url_decode(payload_b64).decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError) as exc:
raise AuthError(
status_code=401,
code="malformed-jwt",
title="Malformed JWT",
detail="JWT header or payload is not valid UTF-8 JSON.",
) from exc
if not isinstance(header, dict) or not isinstance(payload, dict):
raise AuthError(
status_code=401,
code="malformed-jwt",
title="Malformed JWT",
detail="JWT header and payload must be JSON objects.",
)
alg = header.get("alg")
if alg != "HS256":
raise AuthError(
status_code=401,
code="invalid-jwt-algorithm",
title="Unsupported JWT Algorithm",
detail=f"Algorithm {alg!r} is rejected; server strictly allows only 'HS256'.",
)
if not sig_b64:
raise AuthError(
status_code=401,
code="missing-signature",
title="Missing JWT Signature",
detail="Unsigned JWTs are rejected.",
)
signing_input = f"{header_b64}.{payload_b64}".encode("ascii")
expected_sig = hmac.new(secret.encode("utf-8"), signing_input, hashlib.sha256).digest()
actual_sig = _b64url_decode(sig_b64)
if not hmac.compare_digest(actual_sig, expected_sig):
raise AuthError(
status_code=401,
code="invalid-jwt-signature",
title="Invalid JWT Signature",
detail="HMAC-SHA256 signature verification failed.",
)
now_ts = time.time() if now is None else float(now)
if payload.get("iss") != expected_issuer:
raise AuthError(
status_code=401,
code="invalid-jwt-issuer",
title="Invalid Token Issuer",
detail="Token 'iss' claim does not match trusted authority.",
)
aud = payload.get("aud")
aud_valid = (
aud == expected_audience
if isinstance(aud, str)
else (isinstance(aud, list) and expected_audience in aud)
)
if not aud_valid:
raise AuthError(
status_code=401,
code="invalid-jwt-audience",
title="Invalid Token Audience",
detail="Token 'aud' claim is not scoped for this serving API.",
)
exp = payload.get("exp")
if not isinstance(exp, (int, float)) or now_ts - leeway_sec >= float(exp):
raise AuthError(
status_code=401,
code="expired-jwt",
title="Token Expired",
detail="JWT 'exp' timestamp is missing or expired.",
)
nbf = payload.get("nbf")
if nbf is not None and (not isinstance(nbf, (int, float)) or float(nbf) > now_ts + leeway_sec):
raise AuthError(
status_code=401,
code="jwt-not-yet-valid",
title="Token Not Yet Valid",
detail="JWT 'nbf' claim is in the future.",
)
sub = payload.get("sub")
role = payload.get("role")
raw_scopes = payload.get("scopes")
if not isinstance(sub, str) or not sub or not isinstance(role, str) or role not in ROLE_SCOPES:
raise AuthError(
status_code=401,
code="invalid-jwt-claims",
title="Invalid Token Claims",
detail="Token must contain valid 'sub' and recognized 'role'.",
)
scopes = (
frozenset(str(s) for s in raw_scopes)
if isinstance(raw_scopes, list)
else frozenset(ROLE_SCOPES[role])
)
return AuthPrincipal(
subject=sub,
auth_method="jwt_hs256",
role=role,
scopes=scopes,
token_id=str(payload["jti"]) if "jti" in payload else None,
)
async def get_current_principal(
request: Request,
authorization: Annotated[str | None, Header()] = None,
x_api_key: Annotated[str | None, Header(alias="X-API-Key")] = None,
) -> AuthPrincipal:
"""Resolve authenticated AuthPrincipal from Bearer HS256 JWT or X-API-Key."""
jwt_secret = str(getattr(request.app.state, "jwt_secret", ""))
expected_issuer = str(getattr(request.app.state, "jwt_issuer", "fsds-auth"))
expected_audience = str(getattr(request.app.state, "jwt_audience", "fsds-serving"))
api_key_registry: APIKeyRegistry = request.app.state.api_key_registry
if authorization:
scheme, _, token = authorization.partition(" ")
if scheme.lower() != "bearer" or not token:
raise AuthError(
status_code=401,
code="invalid-auth-scheme",
title="Invalid Authorization Header",
detail="Expected 'Authorization: Bearer <jwt>'.",
)
return verify_hs256_jwt(
token.strip(),
jwt_secret,
expected_issuer=expected_issuer,
expected_audience=expected_audience,
)
if x_api_key:
return api_key_registry.verify(x_api_key.strip())
raise AuthError(
status_code=401,
code="missing-credentials",
title="Authentication Required",
detail="Provide 'Authorization: Bearer <token>' or 'X-API-Key' header.",
)
def require_scope(scope: str) -> Callable[[AuthPrincipal], Awaitable[AuthPrincipal]]:
"""Build RBAC scope verification dependency evaluating cached AuthPrincipal."""
async def _checker(
principal: Annotated[AuthPrincipal, Depends(get_current_principal)],
) -> AuthPrincipal:
if scope not in principal.scopes:
raise AuthError(
status_code=403,
code="insufficient-scope",
title="Forbidden",
detail=f"Role '{principal.role}' lacks required RBAC scope '{scope}'.",
)
return principal
return _checker
ScopeStreamReader = Annotated[AuthPrincipal, Depends(require_scope("stream:read"))]
ScopePredictWriter = Annotated[AuthPrincipal, Depends(require_scope("predict:write"))]
ScopeModelAdmin = Annotated[AuthPrincipal, Depends(require_scope("model:reload"))]
ScopeMetricsReader = Annotated[AuthPrincipal, Depends(require_scope("metrics:read"))]
ScopeBenchRunner = Annotated[AuthPrincipal, Depends(require_scope("bench:run"))]
"""FastAPI serving app with Pure ASGI Middleware, Auth/RBAC, OpenTelemetry, Probes & SIGTERM drain."""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import os
import signal
import sys
import time
import uuid
from collections import OrderedDict, deque
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from dataclasses import dataclass, field
from typing import Annotated, Any
import numpy as np
from fastapi import FastAPI, Header, HTTPException, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse, StreamingResponse
from opentelemetry.metrics import Counter, Histogram
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
try:
from opentelemetry.sdk.trace.export import InMemorySpanExporter # type: ignore[attr-defined]
except ImportError:
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import Status, StatusCode, Tracer
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
from starlette.testclient import TestClient
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from webapi_serving_lab.schemas_and_auth import (
AdminReloadRequest,
APIKeyRegistry,
AuthError,
BatchPredictRequest,
BatchPredictResponse,
PredictResponse,
ProblemDetail,
ScopeBenchRunner,
ScopeMetricsReader,
ScopeModelAdmin,
ScopePredictWriter,
ScopeStreamReader,
StrictPredictRequest,
build_default_api_key_registry,
)
DEFAULT_JWT_SECRET = "fsds-sota-2026-webapi-hs256-secret-key"
_KNOWN_ROUTES = frozenset(
{
"/health/live",
"/health/ready",
"/metrics",
"/v1/predict",
"/v1/predict-batch",
"/v1/admin/reload",
"/v1/stream",
"/v1/bench/async-blocking-trap",
"/v1/bench/to-thread",
}
)
_TRACE_PROPAGATOR = TraceContextTextMapPropagator()
def _create_in_memory_span_exporter(max_spans: int) -> InMemorySpanExporter:
try:
return InMemorySpanExporter(max_spans=max_spans)
except TypeError: # pragma: no cover - opentelemetry-sdk < 1.39 fallback
return InMemorySpanExporter()
@dataclass(slots=True)
class TokenBucket:
"""In-memory per-client token bucket for Pure ASGI rate limiting."""
tokens: float
last_refill: float
@dataclass(slots=True)
class AppRuntimeState:
"""Bounded runtime state + OpenTelemetry TracerProvider/MeterProvider initialized by FastAPI."""
weights: np.ndarray
bias: float = -0.15
temperature: float = 1.0
model_version: str = "v2.1.0"
degraded: bool = False
draining: bool = False
in_flight: int = 0
lifespan_started: bool = False
lifespan_stopped: bool = False
rate_limit_rps: float = 1000.0
rate_limit_burst: float = 1000.0
clock: Callable[[], float] = time.perf_counter
max_buckets: int = 4096
bucket_ttl_sec: float = 3600.0
max_idempotency_entries: int = 4096
idempotency_ttl_sec: float = 3600.0
max_latencies: int = 4096
max_telemetry_logs: int = 2048
idempotency_cache: OrderedDict[str, tuple[str, dict[str, Any], float]] = field(
default_factory=OrderedDict
)
latencies_ms: deque[float] = field(init=False)
status_counts: dict[int, int] = field(default_factory=dict)
telemetry_logs: deque[dict[str, Any]] = field(init=False)
buckets: OrderedDict[str, TokenBucket] = field(default_factory=OrderedDict)
span_exporter: InMemorySpanExporter = field(init=False)
tracer_provider: TracerProvider = field(init=False)
tracer: Tracer = field(init=False)
metric_reader: InMemoryMetricReader = field(init=False)
meter_provider: MeterProvider = field(init=False)
request_counter: Counter = field(init=False)
request_duration_ms: Histogram = field(init=False)
rate_limit_counter: Counter = field(init=False)
def __post_init__(self) -> None:
self.latencies_ms = deque(maxlen=self.max_latencies)
self.telemetry_logs = deque(maxlen=self.max_telemetry_logs)
resource = Resource.create(
{
"service.name": "webapi-serving-lab",
"service.version": self.model_version,
}
)
self.span_exporter = _create_in_memory_span_exporter(self.max_telemetry_logs)
self.tracer_provider = TracerProvider(resource=resource)
self.tracer_provider.add_span_processor(SimpleSpanProcessor(self.span_exporter))
self.tracer = self.tracer_provider.get_tracer("webapi_serving_lab", self.model_version)
self.metric_reader = InMemoryMetricReader()
self.meter_provider = MeterProvider(resource=resource, metric_readers=[self.metric_reader])
meter = self.meter_provider.get_meter("webapi_serving_lab", self.model_version)
self.request_counter = meter.create_counter(
"http.server.requests",
unit="1",
description="Total HTTP requests partitioned by bounded method, route, and status.",
)
self.request_duration_ms = meter.create_histogram(
"http.server.request.duration",
unit="ms",
description="HTTP request latency distribution in milliseconds.",
)
self.rate_limit_counter = meter.create_counter(
"http.server.rate_limited",
unit="1",
description="Count of requests rejected with 429 Too Many Requests.",
)
def _evict_expired_idempotency(self, now_ts: float) -> None:
while self.idempotency_cache:
oldest_key, (_, _, expires_at) = next(iter(self.idempotency_cache.items()))
if now_ts >= expires_at:
self.idempotency_cache.pop(oldest_key, None)
else:
break
def get_idempotency(self, key: str) -> tuple[str, dict[str, Any]] | None:
"""Fetch non-expired idempotency entry and refresh LRU position."""
now_ts = self.clock()
entry = self.idempotency_cache.get(key)
if entry is None:
return None
body_hash, resp_payload, expires_at = entry
if now_ts >= expires_at:
self.idempotency_cache.pop(key, None)
return None
self.idempotency_cache.move_to_end(key)
return body_hash, resp_payload
def set_idempotency(self, key: str, body_hash: str, resp_payload: dict[str, Any]) -> None:
"""Store idempotency entry with bounded LRU capacity + TTL eviction."""
now_ts = self.clock()
self._evict_expired_idempotency(now_ts)
if key in self.idempotency_cache:
self.idempotency_cache.move_to_end(key)
else:
while len(self.idempotency_cache) >= self.max_idempotency_entries:
self.idempotency_cache.popitem(last=False)
self.idempotency_cache[key] = (body_hash, resp_payload, now_ts + self.idempotency_ttl_sec)
def get_otel_metrics_snapshot(self) -> dict[str, Any]:
"""Extract current OpenTelemetry metrics snapshot from InMemoryMetricReader."""
metrics_data = self.metric_reader.get_metrics_data()
summary: dict[str, Any] = {}
if metrics_data is None:
return summary
for rm in metrics_data.resource_metrics:
for sm in rm.scope_metrics:
for metric in sm.metrics:
points = getattr(metric.data, "data_points", ())
if metric.name == "http.server.request.duration":
total_count = sum(int(getattr(pt, "count", 0)) for pt in points)
total_sum = sum(float(getattr(pt, "sum", 0.0)) for pt in points)
summary[metric.name] = {
"count": total_count,
"sum_ms": round(total_sum, 3),
}
else:
summary[metric.name] = sum(int(getattr(pt, "value", 0)) for pt in points)
return summary
def _problem_json_response(
problem: ProblemDetail,
headers: dict[str, str] | None = None,
) -> JSONResponse:
return JSONResponse(
status_code=problem.status,
content=problem.model_dump(exclude_none=True),
media_type="application/problem+json",
headers=headers,
)
class RequestContextAndRateLimitMiddleware:
"""Pure ASGI 3.0 Middleware: OTel Tracing/Metrics, W3C traceparent, Token-Bucket 429 & zero-copy."""
def __init__(
self,
app: ASGIApp,
runtime_state: AppRuntimeState,
*,
clock: Callable[[], float] | None = None,
) -> None:
self.app = app
self.state = runtime_state
self.clock = clock or runtime_state.clock
def _consume_token(self, client_key: str, now_ts: float) -> tuple[bool, float]:
rate = self.state.rate_limit_rps
burst = self.state.rate_limit_burst
ttl = self.state.bucket_ttl_sec
while self.state.buckets:
oldest_key, oldest_bucket = next(iter(self.state.buckets.items()))
if now_ts - oldest_bucket.last_refill > ttl:
self.state.buckets.pop(oldest_key, None)
else:
break
bucket = self.state.buckets.get(client_key)
if bucket is not None and now_ts - bucket.last_refill > ttl:
self.state.buckets.pop(client_key, None)
bucket = None
if bucket is None:
while len(self.state.buckets) >= self.state.max_buckets:
self.state.buckets.popitem(last=False)
bucket = TokenBucket(tokens=burst, last_refill=now_ts)
self.state.buckets[client_key] = bucket
else:
self.state.buckets.move_to_end(client_key)
elapsed = max(0.0, now_ts - bucket.last_refill)
bucket.tokens = min(burst, bucket.tokens + elapsed * rate)
bucket.last_refill = now_ts
if bucket.tokens >= 1.0:
bucket.tokens -= 1.0
return True, 0.0
retry_after = max(0.05, (1.0 - bucket.tokens) / max(rate, 1e-6))
return False, retry_after
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
start_ts = self.clock()
path = str(scope.get("path", "/"))
route_label = path if path in _KNOWN_ROUTES else "__unmatched__"
method = str(scope.get("method", "GET"))
raw_headers: list[tuple[bytes, bytes]] = list(scope.get("headers", ()))
req_id = ""
client_id = ""
carrier: dict[str, str] = {}
for k, v in raw_headers:
lk = k.lower()
if lk == b"x-request-id":
req_id = v.decode("latin-1").strip()
elif lk == b"x-client-id":
client_id = v.decode("latin-1").strip()
elif lk in (b"traceparent", b"tracestate"):
carrier[lk.decode("ascii")] = v.decode("latin-1").strip()
if not req_id:
req_id = f"req-{uuid.uuid4().hex[:12]}"
if not client_id:
client_info = scope.get("client")
client_id = str(client_info[0]) if client_info else "local-client"
parent_ctx = _TRACE_PROPAGATOR.extract(carrier=carrier) if carrier else None
scope_state = scope.setdefault("state", {})
if isinstance(scope_state, dict):
scope_state["request_id"] = req_id
with self.state.tracer.start_as_current_span(
f"{method} {route_label}",
context=parent_ctx,
) as span:
trace_id_hex = format(span.get_span_context().trace_id, "032x")
if isinstance(scope_state, dict):
scope_state["trace_id"] = trace_id_hex
span.set_attribute("http.request.method", method)
span.set_attribute("http.route", route_label)
span.set_attribute("url.path", path)
span.set_attribute("fsds.request_id", req_id)
span.set_attribute("fsds.middleware_mode", "pure-asgi")
# Exempt Kubernetes probes and /metrics from user rate limits
is_probe = path.startswith("/health/") or path == "/metrics"
if not is_probe:
allowed, retry_after = self._consume_token(client_id, start_ts)
if not allowed:
elapsed_ms = max(0.0, (self.clock() - start_ts) * 1000.0)
problem = ProblemDetail(
type="https://api.fsds.example/problems/rate-limit-exceeded",
title="Too Many Requests",
status=429,
detail="Per-client Token Bucket capacity exhausted.",
instance=path,
request_id=req_id,
)
body = json.dumps(problem.model_dump(exclude_none=True)).encode("utf-8")
self.state.status_counts[429] = self.state.status_counts.get(429, 0) + 1
self.state.telemetry_logs.append(
{
"request_id": req_id,
"trace_id": trace_id_hex,
"method": method,
"path": route_label,
"status": 429,
"duration_ms": round(elapsed_ms, 3),
"client_id": client_id,
}
)
span.set_attribute("http.response.status_code", 429)
span.set_attribute("fsds.rate_limited", True)
span.set_status(Status(StatusCode.ERROR, "Rate limit exceeded"))
self.state.request_counter.add(
1,
{
"http.request.method": method,
"http.route": route_label,
"http.response.status_code": 429,
},
)
self.state.rate_limit_counter.add(
1,
{"http.request.method": method, "http.route": route_label},
)
self.state.request_duration_ms.record(
elapsed_ms,
{"http.request.method": method, "http.route": route_label},
)
await send(
{
"type": "http.response.start",
"status": 429,
"headers": [
(b"content-type", b"application/problem+json"),
(b"content-length", str(len(body)).encode("ascii")),
(b"retry-after", f"{max(1, round(retry_after))}".encode("ascii")),
(b"x-request-id", req_id.encode("latin-1")),
(b"x-trace-id", trace_id_hex.encode("ascii")),
(b"x-middleware-mode", b"pure-asgi"),
],
}
)
await send({"type": "http.response.body", "body": body, "more_body": False})
return
self.state.in_flight += 1
response_status = 500
logged = False
async def send_wrapper(message: Message) -> None:
nonlocal response_status, logged
msg_type = message["type"]
if msg_type == "http.response.start":
response_status = int(message["status"])
elapsed_ms = max(0.0, (self.clock() - start_ts) * 1000.0)
headers = [
(k, v)
for (k, v) in message.get("headers", [])
if k.lower() not in (b"x-request-id", b"x-trace-id")
]
headers.extend(
[
(b"x-request-id", req_id.encode("latin-1")),
(b"x-trace-id", trace_id_hex.encode("ascii")),
(b"x-process-time-ms", f"{elapsed_ms:.3f}".encode("ascii")),
(b"x-middleware-mode", b"pure-asgi"),
]
)
message["headers"] = headers
elif (
msg_type == "http.response.body"
and not message.get("more_body", False)
and not logged
):
logged = True
total_ms = max(0.0, (self.clock() - start_ts) * 1000.0)
self.state.status_counts[response_status] = (
self.state.status_counts.get(response_status, 0) + 1
)
self.state.latencies_ms.append(round(total_ms, 3))
self.state.telemetry_logs.append(
{
"request_id": req_id,
"trace_id": trace_id_hex,
"method": method,
"path": route_label,
"status": response_status,
"duration_ms": round(total_ms, 3),
"client_id": client_id,
}
)
span.set_attribute("http.response.status_code", response_status)
span.set_attribute("fsds.rate_limited", False)
if response_status >= 500:
span.set_status(Status(StatusCode.ERROR))
else:
span.set_status(Status(StatusCode.OK))
self.state.request_counter.add(
1,
{
"http.request.method": method,
"http.route": route_label,
"http.response.status_code": response_status,
},
)
self.state.request_duration_ms.record(
total_ms,
{"http.request.method": method, "http.route": route_label},
)
await send(message)
try:
await self.app(scope, receive, send_wrapper)
except BaseException as exc:
span.record_exception(exc)
span.set_status(Status(StatusCode.ERROR, str(exc)))
raise
finally:
self.state.in_flight = max(0, self.state.in_flight - 1)
def _score_features(state: AppRuntimeState, features: list[float]) -> tuple[float, float, str]:
vec = np.asarray(features, dtype=np.float64)
w = state.weights[: len(vec)]
if len(w) < len(vec):
w = np.resize(state.weights, len(vec))
logit = float(np.dot(vec, w) + state.bias) / max(state.temperature, 1e-6)
logit_clamped = max(-30.0, min(30.0, logit))
prob = 1.0 / (1.0 + float(np.exp(-logit_clamped)))
label = "positive" if prob >= 0.5 else "negative"
return round(logit, 6), round(prob, 6), label
def create_serving_app(
*,
jwt_secret: str = DEFAULT_JWT_SECRET,
api_key_registry: APIKeyRegistry | None = None,
rate_limit_rps: float = 1000.0,
rate_limit_burst: float = 1000.0,
bench_stall_sec: float = 0.0,
enable_bench_endpoints: bool | None = None,
clock: Callable[[], float] | None = None,
max_buckets: int = 4096,
bucket_ttl_sec: float = 3600.0,
max_idempotency_entries: int = 4096,
idempotency_ttl_sec: float = 3600.0,
max_latencies: int = 4096,
max_telemetry_logs: int = 2048,
) -> FastAPI:
"""Create configured FastAPI serving app with Pure ASGI middleware, JWT/RBAC, OTel & K8s probes."""
registry = api_key_registry
if registry is None:
registry, _ = build_default_api_key_registry()
if enable_bench_endpoints is None:
bench_enabled = os.getenv("FSDS_ENABLE_BENCH_ENDPOINTS", "").lower() in {"1", "true", "yes"}
else:
bench_enabled = bool(enable_bench_endpoints)
runtime_state = AppRuntimeState(
weights=np.array([0.85, -0.45, 0.30, 0.25, -0.10, 0.15, 0.05, 0.20], dtype=np.float64),
rate_limit_rps=rate_limit_rps,
rate_limit_burst=rate_limit_burst,
clock=clock or time.perf_counter,
max_buckets=max_buckets,
bucket_ttl_sec=bucket_ttl_sec,
max_idempotency_entries=max_idempotency_entries,
idempotency_ttl_sec=idempotency_ttl_sec,
max_latencies=max_latencies,
max_telemetry_logs=max_telemetry_logs,
)
@asynccontextmanager
async def lifespan(application: FastAPI) -> AsyncIterator[None]:
application.state.runtime = runtime_state
runtime_state.lifespan_started = True
try:
yield
finally:
runtime_state.draining = True
runtime_state.lifespan_stopped = True
runtime_state.tracer_provider.force_flush()
runtime_state.meter_provider.force_flush()
app = FastAPI(
title="FSDS-SOTA-2026 High-Performance ML Serving API",
version="2.1.0",
lifespan=lifespan,
)
app.state.runtime = runtime_state
app.state.jwt_secret = jwt_secret
app.state.jwt_issuer = "fsds-auth"
app.state.jwt_audience = "fsds-serving"
app.state.api_key_registry = registry
app.state.bench_stall_sec = bench_stall_sec
app.state.enable_bench_endpoints = bench_enabled
app.add_middleware(
RequestContextAndRateLimitMiddleware,
runtime_state=runtime_state,
clock=runtime_state.clock,
)
@app.exception_handler(RequestValidationError)
async def _validation_exc_handler(
request: Request,
exc: RequestValidationError,
) -> JSONResponse:
req_id = getattr(request.state, "request_id", None)
cleaned_errors = [
{
"loc": list(err.get("loc", ())),
"msg": str(err.get("msg", "validation error")),
"type": str(err.get("type", "value_error")),
}
for err in exc.errors()
]
return _problem_json_response(
ProblemDetail(
type="https://api.fsds.example/problems/request-validation-error",
title="Request Validation Failed",
status=422,
detail="Input payload violated strict Pydantic v2 schema constraints.",
instance=str(request.url.path),
request_id=req_id,
errors=cleaned_errors,
)
)
@app.exception_handler(AuthError)
async def _auth_exc_handler(request: Request, exc: AuthError) -> JSONResponse:
req_id = getattr(request.state, "request_id", None)
hdrs = {"WWW-Authenticate": "Bearer"} if exc.status_code == 401 else None
return _problem_json_response(
ProblemDetail(
type=f"https://api.fsds.example/problems/{exc.code}",
title=exc.title,
status=exc.status_code,
detail=exc.detail,
instance=str(request.url.path),
request_id=req_id,
),
headers=hdrs,
)
@app.exception_handler(HTTPException)
async def _http_exc_handler(request: Request, exc: HTTPException) -> JSONResponse:
req_id = getattr(request.state, "request_id", None)
return _problem_json_response(
ProblemDetail(
type="https://api.fsds.example/problems/http-error",
title="HTTP Error",
status=exc.status_code,
detail=str(exc.detail),
instance=str(request.url.path),
request_id=req_id,
),
headers=dict(exc.headers) if exc.headers else None,
)
@app.get("/health/live")
async def liveness_probe() -> dict[str, Any]:
"""Process-only liveness probe: stays 200 even when downstream dependencies degrade."""
return {
"status": "alive",
"model_version": runtime_state.model_version,
"in_flight": runtime_state.in_flight,
}
@app.get("/health/ready")
async def readiness_probe(request: Request) -> JSONResponse:
"""Traffic readiness probe: returns 503 on dependency degradation OR SIGTERM drain."""
req_id = getattr(request.state, "request_id", None)
if runtime_state.draining:
return _problem_json_response(
ProblemDetail(
type="https://api.fsds.example/problems/pod-draining",
title="Service Draining",
status=503,
detail="SIGTERM drain active; endpoint removed from load balancer pool.",
instance="/health/ready",
request_id=req_id,
)
)
if runtime_state.degraded:
return _problem_json_response(
ProblemDetail(
type="https://api.fsds.example/problems/dependency-degraded",
title="Dependency Unavailable",
status=503,
detail="Downstream feature store or DB dependency is unhealthy.",
instance="/health/ready",
request_id=req_id,
)
)
return JSONResponse(
status_code=200,
content={
"status": "ready",
"model_version": runtime_state.model_version,
"in_flight": runtime_state.in_flight,
},
)
@app.get("/metrics")
async def metrics_endpoint(_principal: ScopeMetricsReader) -> dict[str, Any]:
"""Authenticated operational metrics endpoint backed by OpenTelemetry + bounded window."""
lats = runtime_state.latencies_ms
if lats:
arr = np.asarray(lats, dtype=np.float64)
p50 = round(float(np.percentile(arr, 50)), 3)
p95 = round(float(np.percentile(arr, 95)), 3)
p99 = round(float(np.percentile(arr, 99)), 3)
else:
p50 = p95 = p99 = 0.0
return {
"total_requests": sum(runtime_state.status_counts.values()),
"status_counts": {str(k): v for k, v in sorted(runtime_state.status_counts.items())},
"in_flight": runtime_state.in_flight,
"draining": runtime_state.draining,
"degraded": runtime_state.degraded,
"p50_ms": p50,
"p95_ms": p95,
"p99_ms": p99,
"otel_metrics": runtime_state.get_otel_metrics_snapshot(),
"otel_spans_recorded": len(runtime_state.span_exporter.get_finished_spans()),
}
@app.post("/v1/predict", response_model=PredictResponse)
async def predict_single(
payload: StrictPredictRequest,
_principal: ScopePredictWriter,
idempotency_key: Annotated[str | None, Header(alias="Idempotency-Key")] = None,
) -> PredictResponse:
if app.state.bench_stall_sec > 0.0:
await asyncio.sleep(app.state.bench_stall_sec)
with runtime_state.tracer.start_as_current_span("ml.inference.predict") as span:
span.set_attribute("ml.model.version", runtime_state.model_version)
span.set_attribute("ml.batch.size", 1)
body_hash = hashlib.sha256(payload.model_dump_json().encode("utf-8")).hexdigest()
if idempotency_key:
cached = runtime_state.get_idempotency(idempotency_key)
if cached is not None:
prev_hash, prev_resp = cached
if prev_hash != body_hash:
span.set_attribute("ml.idempotency.conflict", True)
span.set_status(Status(StatusCode.ERROR, "Idempotency-Key payload conflict"))
raise HTTPException(
status_code=409,
detail="Idempotency-Key already bound to a different request payload.",
)
span.set_attribute("ml.idempotency.hit", True)
return PredictResponse(**{**prev_resp, "cached_idempotency": True})
span.set_attribute("ml.idempotency.hit", False)
score, prob, label = _score_features(runtime_state, payload.features)
response = PredictResponse(
request_id=payload.request_id,
model_version=runtime_state.model_version,
score=score,
label=label,
probability=prob if payload.return_probabilities else None,
cached_idempotency=False,
)
if idempotency_key:
runtime_state.set_idempotency(idempotency_key, body_hash, response.model_dump())
return response
@app.post("/v1/predict-batch", response_model=BatchPredictResponse)
async def predict_batch(
payload: BatchPredictRequest,
_principal: ScopePredictWriter,
) -> BatchPredictResponse:
with runtime_state.tracer.start_as_current_span("ml.inference.predict_batch") as span:
span.set_attribute("ml.model.version", runtime_state.model_version)
span.set_attribute("ml.batch.size", len(payload.items))
results: list[PredictResponse] = []
for item in payload.items:
score, prob, label = _score_features(runtime_state, item.features)
results.append(
PredictResponse(
request_id=item.request_id,
model_version=runtime_state.model_version,
score=score,
label=label,
probability=prob if item.return_probabilities else None,
)
)
return BatchPredictResponse(
count=len(results),
model_version=runtime_state.model_version,
results=results,
)
@app.post("/v1/admin/reload")
async def admin_reload(
payload: AdminReloadRequest,
principal: ScopeModelAdmin,
) -> dict[str, Any]:
runtime_state.bias = payload.bias
runtime_state.temperature = payload.temperature
runtime_state.model_version = payload.model_version
return {
"status": "reloaded",
"reloaded_by": principal.subject,
"model_version": runtime_state.model_version,
"bias": runtime_state.bias,
"temperature": runtime_state.temperature,
}
@app.get("/v1/stream")
async def stream_sse_tokens(
_principal: ScopeStreamReader,
n_tokens: Annotated[int, Query(ge=1, le=64)] = 6,
token_delay_ms: Annotated[float, Query(ge=0.0, le=200.0)] = 6.0,
) -> StreamingResponse:
vocab = ("FastAPI", "Pure", "ASGI", "streams", "tokens", "zero-copy", "low", "TTFT")
async def _event_generator() -> AsyncIterator[str]:
for idx in range(n_tokens):
if token_delay_ms > 0:
await asyncio.sleep(token_delay_ms / 1000.0)
chunk_payload = json.dumps({"index": idx, "token": vocab[idx % len(vocab)]})
yield f"id: {idx}\nevent: token\ndata: {chunk_payload}\n\n"
yield 'event: done\ndata: {"finished": true}\n\n'
return StreamingResponse(
_event_generator(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
@app.get("/v1/bench/async-blocking-trap")
async def bench_blocking_trap(
_principal: ScopeBenchRunner,
delay_ms: Annotated[float, Query(ge=1.0, le=250.0)] = 20.0,
) -> dict[str, Any]:
"""Anti-pattern: sync time.sleep inside async def freezes the entire event loop."""
if not app.state.enable_bench_endpoints:
raise HTTPException(
status_code=403,
detail="Benchmark endpoints are disabled by feature flag.",
)
time.sleep(delay_ms / 1000.0)
return {"mode": "async_blocking_trap", "slept_ms": delay_ms}
@app.get("/v1/bench/to-thread")
async def bench_to_thread(
_principal: ScopeBenchRunner,
delay_ms: Annotated[float, Query(ge=1.0, le=250.0)] = 20.0,
) -> dict[str, Any]:
"""Safe offload: blocking call dispatched to AnyIO threadpool keeps loop alive."""
if not app.state.enable_bench_endpoints:
raise HTTPException(
status_code=403,
detail="Benchmark endpoints are disabled by feature flag.",
)
await asyncio.to_thread(time.sleep, delay_ms / 1000.0)
return {"mode": "asyncio_to_thread", "slept_ms": delay_ms}
return app
def trigger_graceful_drain(app: FastAPI) -> dict[str, Any]:
"""Flip readiness probe to draining (503) during SIGTERM graceful shutdown."""
state: AppRuntimeState = app.state.runtime
state.draining = True
return {"status": "draining", "ready": False, "in_flight": state.in_flight}
def install_sigterm_handler(app: FastAPI) -> dict[int, Any]:
"""Register SIGTERM/SIGINT handlers flipping draining flag for clean K8s rollout."""
previous: dict[int, Any] = {}
def _on_signal(_signum: int, _frame: Any) -> None:
trigger_graceful_drain(app)
for sig_name in ("SIGTERM", "SIGINT"):
sig = getattr(signal, sig_name, None)
if sig is not None:
previous[int(sig)] = signal.getsignal(sig)
signal.signal(sig, _on_signal)
return previous
def restore_sigterm_handler(previous: dict[int, Any]) -> None:
"""Restore original signal handlers after tests."""
for sig_num, handler in previous.items():
signal.signal(sig_num, handler)
def run_local_healthcheck(app: FastAPI | None = None) -> dict[str, Any]:
"""Exercise /health/live and /health/ready via in-process ASGI TestClient."""
target_app = app or create_serving_app()
with TestClient(target_app) as client:
live_resp = client.get("/health/live")
ready_resp = client.get("/health/ready")
draining_during_probe = target_app.state.runtime.draining
degraded_during_probe = target_app.state.runtime.degraded
live_data = live_resp.json()
ready_data = ready_resp.json()
return {
"status": "ready"
if ready_resp.status_code == 200 and live_resp.status_code == 200
else "not_ready",
"ready": ready_resp.status_code == 200,
"live_status": live_resp.status_code,
"ready_status": ready_resp.status_code,
"model_version": live_data.get("model_version"),
"draining": draining_during_probe,
"degraded": degraded_during_probe,
"ready_payload": ready_data,
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="FSDS Track 2 Lab 04 FastAPI Serving CLI.")
parser.add_argument(
"--healthcheck", action="store_true", help="Verify local ASGI liveness/readiness probes."
)
args = parser.parse_args(argv)
if args.healthcheck:
report = run_local_healthcheck()
print(json.dumps(report, indent=2))
return 0 if report["ready"] else 1
parser.print_help()
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
"""Reproducible ASGI benchmarks: Loop Trap, Pure ASGI vs BaseHTTP, Kingman & Coordinated Omission."""
from __future__ import annotations
import asyncio
import heapq
import math
import random
import time
from collections.abc import MutableMapping
from typing import Any
import httpx
import numpy as np
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.requests import Request
from starlette.responses import Response
from webapi_serving_lab.app import create_serving_app
from webapi_serving_lab.schemas_and_auth import build_default_api_key_registry
def kingman_vut_expected_wait_ms(
utilization: float,
mean_service_ms: float,
ca_sq: float = 1.0,
cs_sq: float = 1.0,
servers: int = 1,
) -> float:
"""Kingman's VUT heavy-traffic expected queueing wait time E[W_q] in milliseconds."""
if not (0.0 <= utilization < 1.0):
raise ValueError("Utilization rho must satisfy 0 <= rho < 1 for queue stability.")
if servers < 1:
raise ValueError("servers must be >= 1")
variability = (ca_sq + cs_sq) / 2.0
if servers == 1:
u_factor = utilization / (1.0 - utilization)
else:
# Multi-server scaling approximation (Sakasegawa / Kingman GI/G/c intuition)
u_factor = (utilization ** (math.sqrt(2.0 * (servers + 1.0)) - 1.0)) / (
servers * (1.0 - utilization)
)
u_factor = max(0.0, u_factor)
return round(variability * u_factor * mean_service_ms, 3)
async def _measure_concurrent_async_vs_trap(concurrency: int, delay_ms: float) -> dict[str, Any]:
registry, demo_keys = build_default_api_key_registry()
app = create_serving_app(
api_key_registry=registry,
rate_limit_rps=10_000.0,
rate_limit_burst=10_000.0,
enable_bench_endpoints=True,
)
bench_headers = {"X-API-Key": demo_keys["admin"]}
transport = httpx.ASGITransport(app=app)
async def _run_batch(endpoint: str) -> dict[str, Any]:
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
# Warmup single call to eliminate cold FastAPI router/Pydantic startup jitter
await client.get("/health/live")
async def _worker() -> float:
t0 = time.perf_counter()
resp = await client.get(f"{endpoint}?delay_ms={delay_ms}", headers=bench_headers)
resp.raise_for_status()
return (time.perf_counter() - t0) * 1000.0
wall_t0 = time.perf_counter()
worker_tasks = [asyncio.create_task(_worker()) for _ in range(concurrency)]
# Measure /health/live latency from submission while workers are active on event loop
probe_submitted_at = time.perf_counter()
async def _probe_live_midflight() -> float:
resp = await client.get("/health/live")
resp.raise_for_status()
return (time.perf_counter() - probe_submitted_at) * 1000.0
probe_task = asyncio.create_task(_probe_live_midflight())
latencies = await asyncio.gather(*worker_tasks)
live_probe_ms = await probe_task
wall_ms = (time.perf_counter() - wall_t0) * 1000.0
arr = np.asarray(latencies, dtype=np.float64)
return {
"wall_ms": round(wall_ms, 2),
"p50_ms": round(float(np.percentile(arr, 50)), 2),
"p95_ms": round(float(np.percentile(arr, 95)), 2),
"p99_ms": round(float(np.percentile(arr, 99)), 2),
"rps": round(concurrency / max(wall_ms / 1000.0, 1e-6), 1),
"health_live_probe_ms": round(live_probe_ms, 2),
}
# Note: execute blocking trap cleanly and compare with asyncio.to_thread offload
trap_res = await _run_batch("/v1/bench/async-blocking-trap")
offload_res = await _run_batch("/v1/bench/to-thread")
speedup = round(trap_res["wall_ms"] / max(offload_res["wall_ms"], 1e-3), 2)
return {
"concurrency": concurrency,
"delay_ms": delay_ms,
"blocking_trap": trap_res,
"to_thread_offload": offload_res,
"wall_speedup": speedup,
}
def benchmark_async_blocking_vs_offload(concurrency: int = 12, delay_ms: float = 20.0) -> dict[str, Any]:
"""Run real ASGITransport benchmark contrasting event-loop freeze vs asyncio.to_thread."""
return asyncio.run(_measure_concurrent_async_vs_trap(concurrency=concurrency, delay_ms=delay_ms))
def _build_middleware_bench_app(mode: str) -> FastAPI:
app = FastAPI()
if mode == "pure_asgi":
class PurePassThroughMW:
def __init__(self, asgi_app: Any) -> None:
self.asgi_app = asgi_app
async def __call__(self, scope: Any, receive: Any, send: Any) -> None:
if scope["type"] != "http":
await self.asgi_app(scope, receive, send)
return
async def _send_wrapper(msg: dict[str, Any]) -> None:
if msg["type"] == "http.response.start":
hdrs = list(msg.get("headers", []))
hdrs.append((b"x-mw-mode", b"pure-asgi"))
msg["headers"] = hdrs
await send(msg)
await self.asgi_app(scope, receive, _send_wrapper)
app.add_middleware(PurePassThroughMW)
elif mode == "base_http":
class StandardBaseMW(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
resp = await call_next(request)
resp.headers["x-mw-mode"] = "base-http"
return resp
app.add_middleware(StandardBaseMW)
elif mode == "base_http_buffered":
class BufferingBaseMW(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
resp = await call_next(request)
chunks = [chunk async for chunk in resp.body_iterator] # type: ignore[attr-defined]
hdrs = {k: v for k, v in resp.headers.items() if k.lower() != "content-length"}
hdrs["x-mw-mode"] = "base-buffered"
return Response(
content=b"".join(chunks),
status_code=resp.status_code,
headers=hdrs,
media_type=resp.media_type,
)
app.add_middleware(BufferingBaseMW)
else:
raise ValueError(f"Unknown middleware benchmark mode: {mode!r}")
@app.get("/ping")
async def ping() -> dict[str, bool]:
return {"ok": True}
@app.get("/sse")
async def sse(n_tokens: int = 6, delay_ms: float = 16.0) -> StreamingResponse:
async def _gen() -> Any:
for idx in range(n_tokens):
await asyncio.sleep(delay_ms / 1000.0)
yield f"id: {idx}\ndata: tok-{idx}\n\n"
return StreamingResponse(_gen(), media_type="text/event-stream")
return app
async def _measure_raw_asgi_sse_and_rps(
n_pings: int,
n_tokens: int,
token_delay_ms: float,
) -> dict[str, Any]:
async def _run_ping_rps(asgi_app: FastAPI) -> tuple[float, float]:
base_scope: dict[str, Any] = {
"type": "http",
"asgi": {"version": "3.0"},
"http_version": "1.1",
"method": "GET",
"scheme": "http",
"path": "/ping",
"raw_path": b"/ping",
"query_string": b"",
"headers": [],
"client": ("127.0.0.1", 50000),
"server": ("127.0.0.1", 80),
}
async def _recv() -> dict[str, Any]:
return {"type": "http.request", "body": b"", "more_body": False}
async def _send(_msg: MutableMapping[str, Any]) -> None:
return None
for _ in range(15):
await asgi_app(dict(base_scope), _recv, _send)
t0 = time.perf_counter()
for _ in range(n_pings):
await asgi_app(dict(base_scope), _recv, _send)
elapsed_ms = (time.perf_counter() - t0) * 1000.0
rps = n_pings / max(elapsed_ms / 1000.0, 1e-6)
return round(elapsed_ms, 2), round(rps, 1)
async def _run_sse_ttft(asgi_app: FastAPI) -> dict[str, Any]:
qs = f"n_tokens={n_tokens}&delay_ms={token_delay_ms}".encode("ascii")
scope: dict[str, Any] = {
"type": "http",
"asgi": {"version": "3.0"},
"http_version": "1.1",
"method": "GET",
"scheme": "http",
"path": "/sse",
"raw_path": b"/sse",
"query_string": qs,
"headers": [],
"client": ("127.0.0.1", 50001),
"server": ("127.0.0.1", 80),
}
sent_req = False
done_ev = asyncio.Event()
async def _recv() -> dict[str, Any]:
nonlocal sent_req
if not sent_req:
sent_req = True
return {"type": "http.request", "body": b"", "more_body": False}
await done_ev.wait()
return {"type": "http.disconnect"}
t0 = time.perf_counter()
chunk_times_ms: list[float] = []
total_bytes = 0
async def _send(msg: MutableMapping[str, Any]) -> None:
nonlocal total_bytes
if msg["type"] == "http.response.body":
body = msg.get("body", b"")
if body:
chunk_times_ms.append(round((time.perf_counter() - t0) * 1000.0, 2))
total_bytes += len(body)
if not msg.get("more_body", False):
done_ev.set()
await asyncio.wait_for(asgi_app(scope, _recv, _send), timeout=5.0)
return {
"ttft_ms": chunk_times_ms[0] if chunk_times_ms else 0.0,
"total_stream_ms": chunk_times_ms[-1] if chunk_times_ms else 0.0,
"chunks_observed": len(chunk_times_ms),
"bytes_streamed": total_bytes,
}
pure_app = _build_middleware_bench_app("pure_asgi")
base_app = _build_middleware_bench_app("base_http")
buf_app = _build_middleware_bench_app("base_http_buffered")
pure_ms, pure_rps = await _run_ping_rps(pure_app)
base_ms, base_rps = await _run_ping_rps(base_app)
# Warm SSE route once before measuring TTFT
await _run_sse_ttft(pure_app)
await _run_sse_ttft(buf_app)
pure_sse = await _run_sse_ttft(pure_app)
buf_sse = await _run_sse_ttft(buf_app)
return {
"n_pings": n_pings,
"pure_asgi_ping_ms": pure_ms,
"pure_asgi_rps": pure_rps,
"base_http_ping_ms": base_ms,
"base_http_rps": base_rps,
"pure_vs_base_rps_speedup": round(pure_rps / max(base_rps, 1e-6), 2),
"pure_asgi_sse": pure_sse,
"base_buffered_sse": buf_sse,
"ttft_degradation_ratio": round(buf_sse["ttft_ms"] / max(pure_sse["ttft_ms"], 1e-3), 2),
}
def benchmark_sse_pure_asgi_vs_base_middleware(
n_pings: int = 300,
n_tokens: int = 5,
token_delay_ms: float = 16.0,
) -> dict[str, Any]:
"""Measure Pure ASGI vs BaseHTTPMiddleware RPS tax and SSE TTFT buffering delay."""
return asyncio.run(
_measure_raw_asgi_sse_and_rps(
n_pings=n_pings,
n_tokens=n_tokens,
token_delay_ms=token_delay_ms,
)
)
def _simulate_open_loop_ggc_queue(
*,
arrival_rate_rps: float,
mean_service_ms: float,
servers: int,
n_requests: int,
seed: int,
) -> dict[str, Any]:
"""Discrete-event M/M/c simulation with Common Random Numbers verifying Little's Law & Kingman."""
rng = random.Random(seed)
interarrival_mean_s = 1.0 / arrival_rate_rps
service_mean_s = mean_service_ms / 1000.0
# Min-heap of server availability timestamps enables fast 20k+ simulated requests
server_heap = [0.0] * servers
heapq.heapify(server_heap)
arrival_t = 0.0
waits_ms: list[float] = []
residences_ms: list[float] = []
busy_time_s = 0.0
for _ in range(n_requests):
arrival_t += rng.expovariate(1.0 / interarrival_mean_s)
service_s = rng.expovariate(1.0 / service_mean_s)
earliest_free = heapq.heappop(server_heap)
start_t = arrival_t if arrival_t >= earliest_free else earliest_free
wait_s = start_t - arrival_t
finish_t = start_t + service_s
heapq.heappush(server_heap, finish_t)
busy_time_s += service_s
waits_ms.append(wait_s * 1000.0)
residences_ms.append((finish_t - arrival_t) * 1000.0)
res_arr = np.asarray(residences_ms, dtype=np.float64)
total_horizon_s = max(server_heap) if server_heap else 1.0
mean_w_s = float(np.mean(res_arr)) / 1000.0
empirical_lambda = n_requests / max(arrival_t, 1e-9)
# Time-averaged concurrency L = sum(residence_time) / total_horizon (Little's Law L = lambda * W)
littles_l_measured = sum(residences_ms) / 1000.0 / max(total_horizon_s, 1e-9)
littles_l_predicted = empirical_lambda * mean_w_s
rho_theoretical = arrival_rate_rps * service_mean_s / servers
return {
"rho": round(rho_theoretical, 3),
"arrival_rate_rps": round(arrival_rate_rps, 1),
"p50_ms": round(float(np.percentile(res_arr, 50)), 2),
"p95_ms": round(float(np.percentile(res_arr, 95)), 2),
"p99_ms": round(float(np.percentile(res_arr, 99)), 2),
"mean_wait_ms": round(float(np.mean(waits_ms)), 2),
"kingman_pred_wait_ms": kingman_vut_expected_wait_ms(
utilization=min(0.99, rho_theoretical),
mean_service_ms=mean_service_ms,
ca_sq=1.0,
cs_sq=1.0,
servers=servers,
),
"littles_l_predicted": round(littles_l_predicted, 2),
"littles_l_measured": round(littles_l_measured, 2),
"empirical_rho": round(busy_time_s / (servers * max(total_horizon_s, 1e-9)), 3),
}
async def _run_asgi_coordinated_omission_experiment(
*,
n_closed_requests: int = 220,
n_open_requests: int = 120,
stall_ms: float = 160.0,
) -> dict[str, Any]:
"""Run real FastAPI ASGITransport requests contrasting Closed-Loop VU vs Open-Loop Schedule.
Reproduces Gil Tene's Coordinated Omission: a single server freeze stalls <=1% of
closed-loop VUs (leaving p99 artificially low), whereas open-loop arrivals queue
throughout the freeze and reveal true p95/p99 tail latency.
"""
app = create_serving_app(rate_limit_rps=10_000.0, rate_limit_burst=10_000.0)
transport = httpx.ASGITransport(app=app)
headers = {"X-API-Key": "fsds_dev_scorer_key_1a2b3c4d5e6f7890"}
payload = {
"request_id": "co-bench-001",
"model_version": "v2.1.0",
"features": [0.5, -0.2, 0.9, 0.3],
"top_k": 1,
"return_probabilities": False,
"metadata": {"bench": "co"},
}
# 1. Closed-Loop (V=1 sequential VU waiting for each response -> only 1/220 = 0.45% hits stall!)
closed_lat_ms: list[float] = []
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
await client.get("/health/live")
t0_c = time.perf_counter()
for idx in range(n_closed_requests):
t_send = time.perf_counter()
if idx == 40:
await asyncio.sleep(stall_ms / 1000.0)
resp = await client.post(
"/v1/predict",
json={**payload, "request_id": f"co-closed-{idx:04d}"},
headers=headers,
)
resp.raise_for_status()
closed_lat_ms.append((time.perf_counter() - t_send) * 1000.0)
closed_wall_s = time.perf_counter() - t0_c
# 2. Open-Loop (150 req/s independent wall-clock schedule; single server pause at t=0.20s)
open_lat_ms: list[float] = []
target_interval_s = 1.0 / 150.0 # 6.67 ms between scheduled arrivals
stall_start_offset_s = 0.20
stall_dur_s = stall_ms / 1000.0
async with httpx.AsyncClient(transport=transport, base_url="http://testserver") as client:
await client.get("/health/live")
t_start = time.perf_counter()
stall_begin = t_start + stall_start_offset_s
stall_end = stall_begin + stall_dur_s
async def _scheduled_req(idx: int) -> None:
scheduled_at = t_start + idx * target_interval_s
wait_s = scheduled_at - time.perf_counter()
if wait_s > 0:
await asyncio.sleep(wait_s)
now = time.perf_counter()
if stall_begin <= now < stall_end:
await asyncio.sleep(stall_end - now)
resp = await client.post(
"/v1/predict",
json={**payload, "request_id": f"co-open-{idx:04d}"},
headers=headers,
)
resp.raise_for_status()
t_done = time.perf_counter()
# Open-loop latency measures from intended arrival schedule timestamp
open_lat_ms.append(max(0.1, (t_done - scheduled_at) * 1000.0))
await asyncio.gather(*(_scheduled_req(i) for i in range(n_open_requests)))
open_wall_s = time.perf_counter() - t_start
c_arr = np.asarray(closed_lat_ms, dtype=np.float64)
o_arr = np.asarray(open_lat_ms, dtype=np.float64)
closed_p99 = round(float(np.percentile(c_arr, 99)), 2)
open_p99 = round(float(np.percentile(o_arr, 99)), 2)
return {
"n_closed_requests": n_closed_requests,
"n_open_requests": n_open_requests,
"injected_stall_ms": stall_ms,
"closed_loop": {
"achieved_rps": round(n_closed_requests / max(closed_wall_s, 1e-6), 1),
"p50_ms": round(float(np.percentile(c_arr, 50)), 2),
"p95_ms": round(float(np.percentile(c_arr, 95)), 2),
"p99_ms": closed_p99,
"max_ms": round(float(np.max(c_arr)), 2),
},
"open_loop": {
"achieved_rps": round(n_open_requests / max(open_wall_s, 1e-6), 1),
"p50_ms": round(float(np.percentile(o_arr, 50)), 2),
"p95_ms": round(float(np.percentile(o_arr, 95)), 2),
"p99_ms": open_p99,
"max_ms": round(float(np.max(o_arr)), 2),
},
"co_underreporting_ratio": round(open_p99 / max(closed_p99, 1e-3), 2),
}
def benchmark_kingman_saturation_and_coordinated_omission(
*,
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Combine Kingman VUT saturation sweep (rho=0.25..0.93) with ASGI Coordinated Omission test."""
n_sim = 15_000 if quick else 30_000
servers = 4
mean_s_ms = 12.0
capacity_rps = servers * (1000.0 / mean_s_ms) # 333.33 req/s
rhos = (0.25, 0.50, 0.70, 0.85, 0.93)
# Common Random Numbers (same seed across rho levels) cleanly isolates utilization impact
sweep = [
_simulate_open_loop_ggc_queue(
arrival_rate_rps=rho * capacity_rps,
mean_service_ms=mean_s_ms,
servers=servers,
n_requests=n_sim,
seed=seed,
)
for rho in rhos
]
co_res = asyncio.run(
_run_asgi_coordinated_omission_experiment(
n_closed_requests=180 if quick else 220,
n_open_requests=90 if quick else 120,
stall_ms=140.0 if quick else 160.0,
)
)
return {
"servers": servers,
"mean_service_ms": mean_s_ms,
"capacity_rps": round(capacity_rps, 2),
"saturation_sweep": sweep,
"coordinated_omission_asgi": co_res,
}
"""End-to-end CLI workbench runner for FSDS-SOTA-2026 Track 2 Unit T2-P1-U04 (Lab 04)."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
from starlette.testclient import TestClient
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from webapi_serving_lab.app import ( # noqa: E402
DEFAULT_JWT_SECRET,
create_serving_app,
run_local_healthcheck,
trigger_graceful_drain,
)
from webapi_serving_lab.load_benchmark import ( # noqa: E402
benchmark_async_blocking_vs_offload,
benchmark_kingman_saturation_and_coordinated_omission,
benchmark_sse_pure_asgi_vs_base_middleware,
)
from webapi_serving_lab.schemas_and_auth import ( # noqa: E402
AuthError,
build_default_api_key_registry,
encode_hs256_jwt,
verify_hs256_jwt,
)
def _run_security_and_probes_verification() -> dict[str, Any]:
"""Exercise Pydantic v2 strict validation, RFC 9457, JWT/RBAC, Idempotency & K8s probes."""
registry, demo_keys = build_default_api_key_registry()
app = create_serving_app(
jwt_secret=DEFAULT_JWT_SECRET,
api_key_registry=registry,
rate_limit_rps=200.0,
rate_limit_burst=200.0,
)
scorer_jwt = encode_hs256_jwt("ml-client-01", "scorer", DEFAULT_JWT_SECRET, jti="jti-scorer")
admin_jwt = encode_hs256_jwt("ml-admin-01", "admin", DEFAULT_JWT_SECRET, jti="jti-admin")
# Verify alg=none bypass is rejected explicitly
import base64
none_hdr = base64.urlsafe_b64encode(b'{"alg":"none","typ":"JWT"}').rstrip(b"=").decode("ascii")
fake_pay = (
base64.urlsafe_b64encode(
b'{"iss":"fsds-auth","aud":"fsds-serving","sub":"evil","role":"admin","exp":9999999999}'
)
.rstrip(b"=")
.decode("ascii")
)
alg_none_rejected = False
try:
verify_hs256_jwt(f"{none_hdr}.{fake_pay}.", DEFAULT_JWT_SECRET)
except AuthError as exc:
alg_none_rejected = exc.code == "invalid-jwt-algorithm"
with TestClient(app) as client:
# Strict validation 422 (extra key + string->float coercion)
bad_strict = client.post(
"/v1/predict",
json={
"request_id": "req-bad-01",
"features": ["0.5", "0.9"],
"unknown_field": 123,
},
headers={"Authorization": f"Bearer {scorer_jwt}"},
)
# Valid scored prediction + idempotency replay
valid_body = {
"request_id": "req-ok-001",
"model_version": "v2.1.0",
"features": [0.8, -0.3, 1.2, 0.4],
"top_k": 1,
"return_probabilities": True,
"metadata": {"tenant": "enterprise"},
}
pred_1 = client.post(
"/v1/predict",
json=valid_body,
headers={"Authorization": f"Bearer {scorer_jwt}", "Idempotency-Key": "idem-demo-1"},
)
pred_replay = client.post(
"/v1/predict",
json=valid_body,
headers={"Authorization": f"Bearer {scorer_jwt}", "Idempotency-Key": "idem-demo-1"},
)
# RBAC check: scorer -> 403 on admin reload; admin -> 200
rbac_403 = client.post(
"/v1/admin/reload",
json={"bias": 0.1, "temperature": 1.0, "model_version": "v2.2.0"},
headers={"Authorization": f"Bearer {scorer_jwt}"},
)
rbac_200 = client.post(
"/v1/admin/reload",
json={"bias": 0.1, "temperature": 1.0, "model_version": "v2.2.0"},
headers={"Authorization": f"Bearer {admin_jwt}"},
)
# SSE streaming via API key
sse_resp = client.get(
"/v1/stream?n_tokens=4&token_delay_ms=1",
headers={"X-API-Key": demo_keys["reader"]},
)
# Dependency outage: /health/live stays 200 while /health/ready flips to 503
app.state.runtime.degraded = True
live_degraded = client.get("/health/live")
ready_degraded = client.get("/health/ready")
app.state.runtime.degraded = False
# SIGTERM drain: /health/ready -> 503
trigger_graceful_drain(app)
ready_draining = client.get("/health/ready")
# Reset draining so TestClient metrics reflect healthy probe
app.state.runtime.draining = False
return {
"alg_none_rejected": alg_none_rejected,
"strict_422_status": bad_strict.status_code,
"strict_422_media_type": bad_strict.headers.get("content-type"),
"predict_status": pred_1.status_code,
"predict_score": pred_1.json()["score"],
"idempotency_replay_cached": pred_replay.json()["cached_idempotency"],
"rbac_scorer_admin_status": rbac_403.status_code,
"rbac_admin_reload_status": rbac_200.status_code,
"sse_status": sse_resp.status_code,
"sse_middleware_mode": sse_resp.headers.get("x-middleware-mode"),
"live_during_db_outage": live_degraded.status_code,
"ready_during_db_outage": ready_degraded.status_code,
"ready_during_sigterm_drain": ready_draining.status_code,
}
def run_all_benchmarks(*, quick: bool = False, seed: int = 42) -> dict[str, Any]:
"""Run all deterministic FastAPI serving, ASGI middleware, and queueing benchmarks."""
sec_probes = _run_security_and_probes_verification()
loop_bench = benchmark_async_blocking_vs_offload(
concurrency=10 if quick else 16,
delay_ms=16.0 if quick else 20.0,
)
mw_bench = benchmark_sse_pure_asgi_vs_base_middleware(
n_pings=200 if quick else 400,
n_tokens=5,
token_delay_ms=16.0,
)
queue_bench = benchmark_kingman_saturation_and_coordinated_omission(
seed=seed,
quick=quick,
)
trap = loop_bench["blocking_trap"]
offload = loop_bench["to_thread_offload"]
sweep = queue_bench["saturation_sweep"]
sweep_by_rho = {row["rho"]: row for row in sweep}
low_rho = sweep_by_rho[0.25]
knee_rho = sweep_by_rho[0.85]
sat_rho = sweep_by_rho[0.93]
co = queue_bench["coordinated_omission_asgi"]
# Rate limit token-bucket check on isolated app
rl_registry, rl_keys = build_default_api_key_registry()
rl_app = create_serving_app(
api_key_registry=rl_registry,
rate_limit_rps=2.0,
rate_limit_burst=3.0,
enable_bench_endpoints=True,
)
admin_headers = {"X-API-Key": rl_keys["admin"]}
with TestClient(rl_app) as rl_client:
rl_statuses = [rl_client.get("/metrics", headers=admin_headers).status_code for _ in range(2)]
# /metrics is probe-exempt; test /v1/bench endpoint with admin auth and burst=3
burst_statuses = [
rl_client.get(
"/v1/bench/to-thread?delay_ms=1",
headers={**admin_headers, "X-Client-ID": "c-burst"},
).status_code
for _ in range(5)
]
rl_429_count = sum(1 for code in burst_statuses if code == 429)
kpis = [
{
"id": "kpi_async_blocking_vs_offload",
"label": f"Event-Loop Trap vs to_thread ({loop_bench['concurrency']} conc)",
"value": f"{trap['wall_ms']} -> {offload['wall_ms']} ms",
"unit": f"{loop_bench['wall_speedup']}x faster",
"status": "ok",
"detail": (
f"/health/live lag: {trap['health_live_probe_ms']} ms (frozen!) vs "
f"{offload['health_live_probe_ms']} ms (responsive); "
f"RPS {trap['rps']} -> {offload['rps']}."
),
},
{
"id": "kpi_pure_asgi_vs_base_middleware",
"label": "Pure ASGI vs BaseHTTPMiddleware (RPS & SSE TTFT)",
"value": f"{mw_bench['pure_asgi_rps']:.0f} vs {mw_bench['base_http_rps']:.0f} RPS",
"unit": f"{mw_bench['pure_vs_base_rps_speedup']}x RPS",
"status": "ok",
"detail": (
f"SSE TTFT: Pure ASGI={mw_bench['pure_asgi_sse']['ttft_ms']} ms vs "
f"Buffered BaseHTTP={mw_bench['base_buffered_sse']['ttft_ms']} ms "
f"({mw_bench['ttft_degradation_ratio']}x TTFT delay)."
),
},
{
"id": "kpi_kingman_saturation_knee",
"label": "Kingman VUT Saturation Knee (rho=0.25 -> 0.93)",
"value": f"{low_rho['p99_ms']} -> {sat_rho['p99_ms']} ms p99",
"unit": f"L={sat_rho['littles_l_measured']}",
"status": "warn",
"detail": (
f"4 servers (E[S]={queue_bench['mean_service_ms']} ms, "
f"cap={queue_bench['capacity_rps']} RPS): p99 jumps "
f"{low_rho['p99_ms']} (rho=0.25) -> {knee_rho['p99_ms']} (0.85) -> "
f"{sat_rho['p99_ms']} ms (0.93); L_pred={sat_rho['littles_l_predicted']}."
),
},
{
"id": "kpi_coordinated_omission_bias",
"label": "Coordinated Omission: Closed-Loop vs Open-Loop p99",
"value": f"{co['closed_loop']['p99_ms']} vs {co['open_loop']['p99_ms']} ms",
"unit": f"{co['co_underreporting_ratio']}x gap",
"status": "ok",
"detail": (
f"{co['injected_stall_ms']} ms pause: closed V=1 hides stall in "
f"1/{co['n_closed_requests']} req (p99={co['closed_loop']['p99_ms']} ms); "
f"150 RPS open-loop sees p99={co['open_loop']['p99_ms']} ms."
),
},
{
"id": "kpi_auth_rbac_and_strict_v2",
"label": "Pydantic v2 Strict, JWT HS256 & RBAC Gates",
"value": "422 / 403 / 200 verified",
"unit": "alg=none blocked",
"status": "ok",
"detail": (
f"Strict 422 ({sec_probes['strict_422_media_type']}), "
f"alg=none rejected={sec_probes['alg_none_rejected']}, "
f"scorer->admin={sec_probes['rbac_scorer_admin_status']}, "
f"replay={sec_probes['idempotency_replay_cached']}, "
f"429s={rl_429_count}/{len(burst_statuses)}."
),
},
{
"id": "kpi_k8s_probes_and_sigterm_drain",
"label": "K8s Probes: Dependency Outage & SIGTERM Drain",
"value": (
f"live={sec_probes['live_during_db_outage']} / "
f"ready={sec_probes['ready_during_db_outage']}"
),
"unit": f"drain={sec_probes['ready_during_sigterm_drain']}",
"status": "ok",
"detail": (
"DB outage flips /health/ready to 503 while /health/live stays 200; "
"SIGTERM flips /health/ready to 503 for zero-drop rollout."
),
},
]
bars = [
{
"id": "bar_eventloop_trap_vs_offload_ms",
"title": (
f"FastAPI Concurrency ({loop_bench['concurrency']} x "
f"{loop_bench['delay_ms']}ms): Wall & /health/live Probe (ms)"
),
"metric_label": "Milliseconds",
"items": [
{
"label": "async_def_blocking_trap_wall",
"value": trap["wall_ms"],
"display": f"{trap['wall_ms']} ms ({trap['rps']} RPS)",
"css_class": "is-slow",
},
{
"label": "health_live_lag_during_trap",
"value": trap["health_live_probe_ms"],
"display": f"{trap['health_live_probe_ms']} ms (FROZEN!)",
"css_class": "is-slow",
},
{
"label": "asyncio_to_thread_wall",
"value": offload["wall_ms"],
"display": (
f"{offload['wall_ms']} ms ({offload['rps']} RPS, "
f"{loop_bench['wall_speedup']}x)"
),
"css_class": "is-fast",
},
{
"label": "health_live_lag_with_offload",
"value": offload["health_live_probe_ms"],
"display": f"{offload['health_live_probe_ms']} ms (ALIVE)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_pure_asgi_vs_basehttp_sse_ttft",
"title": "Middleware Architecture: SSE Time-To-First-Token (TTFT ms) & Throughput",
"metric_label": "TTFT (ms)",
"items": [
{
"label": "pure_asgi_sse_ttft",
"value": mw_bench["pure_asgi_sse"]["ttft_ms"],
"display": (
f"{mw_bench['pure_asgi_sse']['ttft_ms']} ms "
f"({mw_bench['pure_asgi_rps']:.0f} ping RPS)"
),
"css_class": "is-fast",
},
{
"label": "base_http_buffered_sse_ttft",
"value": mw_bench["base_buffered_sse"]["ttft_ms"],
"display": (
f"{mw_bench['base_buffered_sse']['ttft_ms']} ms "
f"({mw_bench['ttft_degradation_ratio']}x worse, "
f"{mw_bench['base_http_rps']:.0f} RPS)"
),
"css_class": "is-slow",
},
],
},
{
"id": "bar_kingman_utilization_p99_ms",
"title": "Kingman VUT Tail Latency Explosion Across Utilization rho = 0.25 -> 0.93 (ms)",
"metric_label": "p99 Latency (ms)",
"items": [
{
"label": f"rho_{row['rho']:.2f}_rps_{row['arrival_rate_rps']:.0f}",
"value": row["p99_ms"],
"display": (
f"{row['p99_ms']} ms (p50={row['p50_ms']} ms, "
f"L={row['littles_l_measured']})"
),
"css_class": "is-fast"
if row["rho"] <= 0.70
else ("is-mid" if row["rho"] <= 0.85 else "is-slow"),
}
for row in sweep
],
},
{
"id": "bar_coordinated_omission_p99_ms",
"title": (
f"FastAPI ASGI Coordinated Omission ({co['injected_stall_ms']} ms Pause): "
"Closed-Loop vs Open-Loop p99"
),
"metric_label": "p99 Latency (ms)",
"items": [
{
"label": "closed_loop_vu_1_apparent_p99",
"value": co["closed_loop"]["p99_ms"],
"display": f"{co['closed_loop']['p99_ms']} ms (hides stall!)",
"css_class": "is-mid",
},
{
"label": "open_loop_150rps_true_p99",
"value": co["open_loop"]["p99_ms"],
"display": (
f"{co['open_loop']['p99_ms']} ms "
f"({co['co_underreporting_ratio']}x true tail)"
),
"css_class": "is-slow",
},
],
},
]
tables = [
{
"id": "table_eventloop_and_middleware_benchmarks",
"title": "FastAPI Event-Loop Isolation & Pure ASGI vs BaseHTTPMiddleware Benchmarks",
"columns": [
"benchmark_mode",
"wall_or_ttft_ms",
"p99_or_total_ms",
"throughput_rps",
"verdict",
],
"rows": [
[
"async_def_blocking_trap",
f"{trap['wall_ms']} ms (live={trap['health_live_probe_ms']} ms)",
f"{trap['p99_ms']} ms",
f"{trap['rps']}",
"EVENT_LOOP_FROZEN",
],
[
"asyncio_to_thread_offload",
f"{offload['wall_ms']} ms (live={offload['health_live_probe_ms']} ms)",
f"{offload['p99_ms']} ms",
f"{offload['rps']}",
f"PARALLEL_{loop_bench['wall_speedup']}x",
],
[
"pure_asgi_middleware",
f"TTFT={mw_bench['pure_asgi_sse']['ttft_ms']} ms",
f"stream={mw_bench['pure_asgi_sse']['total_stream_ms']} ms",
f"{mw_bench['pure_asgi_rps']}",
f"ZERO_COPY_{mw_bench['pure_vs_base_rps_speedup']}x_RPS",
],
[
"base_http_middleware_buffered",
f"TTFT={mw_bench['base_buffered_sse']['ttft_ms']} ms",
f"stream={mw_bench['base_buffered_sse']['total_stream_ms']} ms",
f"{mw_bench['base_http_rps']}",
f"TTFT_DELAYED_{mw_bench['ttft_degradation_ratio']}x",
],
],
},
{
"id": "table_kingman_littles_law_sweep",
"title": "Queueing Theory Verification: Kingman VUT & Little's Law (L = lambda * W)",
"columns": [
"rho_util",
"arrival_rps",
"p50_ms",
"p95_ms",
"p99_ms",
"littles_L_pred_vs_meas",
],
"rows": [
[
f"{row['rho']:.2f}",
f"{row['arrival_rate_rps']:.1f}",
f"{row['p50_ms']}",
f"{row['p95_ms']}",
f"{row['p99_ms']}",
f"{row['littles_l_predicted']} / {row['littles_l_measured']}",
]
for row in sweep
],
},
{
"id": "table_coordinated_omission_comparison",
"title": "Real FastAPI ASGITransport Coordinated Omission Audit (Closed-Loop vs Open-Loop)",
"columns": ["generator_mode", "achieved_rps", "p50_ms", "p95_ms", "p99_ms", "max_ms"],
"rows": [
[
"closed_loop_v1",
f"{co['closed_loop']['achieved_rps']}",
f"{co['closed_loop']['p50_ms']}",
f"{co['closed_loop']['p95_ms']}",
f"{co['closed_loop']['p99_ms']}",
f"{co['closed_loop']['max_ms']}",
],
[
"open_loop_150rps",
f"{co['open_loop']['achieved_rps']}",
f"{co['open_loop']['p50_ms']}",
f"{co['open_loop']['p95_ms']}",
f"{co['open_loop']['p99_ms']}",
f"{co['open_loop']['max_ms']}",
],
],
},
{
"id": "table_security_rfc9457_and_probes",
"title": "Security Hardening (Pydantic v2, JWT HS256, RBAC, Rate Limit) & K8s Probes",
"columns": ["control_surface", "expected_behavior", "observed_result", "status"],
"rows": [
[
"pydantic_v2_strict_and_rfc9457",
"422 application/problem+json on extra key / coercion",
f"{sec_probes['strict_422_status']} ({sec_probes['strict_422_media_type']})",
"ENFORCED",
],
[
"jwt_hs256_alg_none_defense",
"Reject alg='none' unsigned token",
f"rejected={sec_probes['alg_none_rejected']}",
"SECURED",
],
[
"rbac_scope_separation",
"scorer->403, admin->200 on /v1/admin/reload",
(
f"scorer={sec_probes['rbac_scorer_admin_status']}, "
f"admin={sec_probes['rbac_admin_reload_status']}"
),
"ENFORCED",
],
[
"idempotency_and_token_bucket_429",
"Replay cached_idempotency=True; burst>3 -> 429",
(
f"replay={sec_probes['idempotency_replay_cached']}, "
f"429s={rl_429_count}; metrics={rl_statuses[0]}"
),
"PROTECTED",
],
[
"k8s_probes_and_sigterm_drain",
"Outage: live=200 & ready=503; SIGTERM: ready=503",
(
f"live={sec_probes['live_during_db_outage']}, "
f"outage_ready={sec_probes['ready_during_db_outage']}, "
f"drain_ready={sec_probes['ready_during_sigterm_drain']}"
),
"ZERO_DOWNTIME",
],
],
},
]
return {
"config": {
"quick": bool(quick),
"seed": seed,
"lab_root": "lab-04-fastapi-auth-tests-and-locust",
},
"security_and_probes": sec_probes,
"eventloop_vs_offload": loop_bench,
"middleware_sse_and_rps": mw_bench,
"queueing_and_load_testing": queue_bench,
"rate_limit_burst_statuses": burst_statuses,
"workbench_panels": {
"kpis": kpis,
"bars": bars,
"tables": tables,
},
}
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Run FSDS-SOTA-2026 Track 2 Lab 04 FastAPI & Load Testing Workbench."
)
parser.add_argument("--quick", action="store_true", help="Run faster deterministic preset.")
parser.add_argument("--seed", type=int, default=42, help="PRNG seed for queueing simulations.")
parser.add_argument(
"--healthcheck",
action="store_true",
help="Run ASGI liveness/readiness healthcheck probe and exit.",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/t2_ch04_workbench_results.json",
help="Output JSON path relative to lab root or absolute.",
)
args = parser.parse_args(argv)
if args.healthcheck:
report = run_local_healthcheck()
print(json.dumps(report, indent=2))
return 0 if report["ready"] else 1
payload = run_all_benchmarks(quick=args.quick, seed=args.seed)
out_path = Path(args.output)
if not out_path.is_absolute():
out_path = LAB_ROOT / out_path
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8", newline="\n")
sp = payload["security_and_probes"]
lb = payload["eventloop_vs_offload"]
mw = payload["middleware_sse_and_rps"]
qt = payload["queueing_and_load_testing"]
co = qt["coordinated_omission_asgi"]
sat = qt["saturation_sweep"]
print("[1] Security, Strict Pydantic v2 & Kubernetes Probes:")
print(
f" 422={sp['strict_422_status']} ({sp['strict_422_media_type']}) | "
f"alg_none_rejected={sp['alg_none_rejected']} | "
f"RBAC={sp['rbac_scorer_admin_status']}/{sp['rbac_admin_reload_status']} | "
f"outage={sp['live_during_db_outage']}/{sp['ready_during_db_outage']} | "
f"drain={sp['ready_during_sigterm_drain']}"
)
print("[2] FastAPI Event-Loop Trap vs asyncio.to_thread & Pure ASGI Middleware:")
print(
f" Blocking trap={lb['blocking_trap']['wall_ms']}ms "
f"(live_lag={lb['blocking_trap']['health_live_probe_ms']}ms) vs "
f"to_thread={lb['to_thread_offload']['wall_ms']}ms "
f"({lb['wall_speedup']}x, live_lag={lb['to_thread_offload']['health_live_probe_ms']}ms)"
)
print(
f" Pure ASGI={mw['pure_asgi_rps']} RPS "
f"(SSE TTFT={mw['pure_asgi_sse']['ttft_ms']}ms) vs "
f"BaseHTTP={mw['base_http_rps']} RPS "
f"(Buffered TTFT={mw['base_buffered_sse']['ttft_ms']}ms, "
f"{mw['ttft_degradation_ratio']}x worse)"
)
print("[3] Kingman VUT Saturation & Real ASGI Coordinated Omission:")
print(
f" Sweep p99: rho=0.25 -> {sat[0]['p99_ms']}ms | "
f"rho=0.85 -> {sat[3]['p99_ms']}ms | rho=0.93 -> {sat[4]['p99_ms']}ms"
)
print(
f" Coordinated Omission p99: closed={co['closed_loop']['p99_ms']}ms "
f"vs open={co['open_loop']['p99_ms']}ms ({co['co_underreporting_ratio']}x gap)"
)
print(f"Saved workbench JSON -> {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))
"""19-test verification suite for FSDS-SOTA-2026 Track 2 Lab 04 (webapi_serving_lab)."""
from __future__ import annotations
import ast
import base64
import importlib.util
import json
import math
import os
import signal
import subprocess
import sys
import time
from pathlib import Path
import httpx
import pytest
from pydantic import ValidationError
from starlette.testclient import TestClient
LAB_ROOT = Path(__file__).resolve().parents[1]
SRC_DIR = LAB_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
from webapi_serving_lab.app import ( # noqa: E402
DEFAULT_JWT_SECRET,
create_serving_app,
install_sigterm_handler,
restore_sigterm_handler,
)
from webapi_serving_lab.load_benchmark import ( # noqa: E402
benchmark_async_blocking_vs_offload,
benchmark_kingman_saturation_and_coordinated_omission,
benchmark_sse_pure_asgi_vs_base_middleware,
kingman_vut_expected_wait_ms,
)
from webapi_serving_lab.schemas_and_auth import ( # noqa: E402
AuthError,
StrictPredictRequest,
build_default_api_key_registry,
encode_hs256_jwt,
verify_hs256_jwt,
)
# Security-only AST ban on unsafe deserialization modules; FastAPI/Pydantic/HTTPX are permitted.
FORBIDDEN_RUNTIME_IMPORTS = frozenset(
{
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
)
def test_01_pydantic_v2_strict_validation_and_defaults() -> None:
req1 = StrictPredictRequest(request_id="req-0001", features=[1.0, -0.5, 2])
req2 = StrictPredictRequest(request_id="req-0002", features=[0.0, 1.0])
assert req1.model_version == "v2.1.0"
assert req1.metadata == {}
assert req1.metadata is not req2.metadata
with pytest.raises(ValidationError):
StrictPredictRequest(request_id="req-0003", features=["1.0", "2.0"]) # type: ignore[list-item]
with pytest.raises(ValidationError):
StrictPredictRequest(request_id="req-0004", features=[1.0, 2.0], top_k=1.0) # type: ignore[arg-type]
with pytest.raises(ValidationError):
StrictPredictRequest(request_id="req-0005", features=[1.0, 2.0], return_probabilities="true") # type: ignore[arg-type]
with pytest.raises(ValidationError):
StrictPredictRequest(request_id="req-0006", features=[1.0, 2.0], unknown_extra=42) # type: ignore[call-arg]
with pytest.raises(ValidationError):
StrictPredictRequest(request_id="req-0007", features=[float("nan"), 1.0])
with pytest.raises(ValidationError):
StrictPredictRequest(request_id="req-0008", features=[2_000_000.0, 1.0])
def test_02_http_422_rfc9457_problem_detail_response() -> None:
app = create_serving_app()
token = encode_hs256_jwt("user-1", "scorer", DEFAULT_JWT_SECRET)
with TestClient(app) as client:
resp = client.post(
"/v1/predict",
json={"request_id": "req-422-test", "features": ["bad", 1.0], "rogue": True},
headers={"Authorization": f"Bearer {token}", "X-Request-ID": "trace-422"},
)
assert resp.status_code == 422
assert resp.headers["content-type"].startswith("application/problem+json")
assert resp.headers["x-request-id"] == "trace-422"
body = resp.json()
assert body["status"] == 422
assert body["request_id"] == "trace-422"
assert isinstance(body["errors"], list) and len(body["errors"]) >= 2
def test_03_predict_single_batch_and_idempotency_key_conflict() -> None:
app = create_serving_app()
token = encode_hs256_jwt("scorer-1", "scorer", DEFAULT_JWT_SECRET)
headers = {"Authorization": f"Bearer {token}", "Idempotency-Key": "idem-key-001"}
payload_a = {
"request_id": "req-idem-01",
"model_version": "v2.1.0",
"features": [0.9, -0.2, 0.7, 0.3],
"top_k": 1,
"return_probabilities": True,
"metadata": {"source": "test"},
}
payload_b = {**payload_a, "features": [0.1, 0.1, 0.1, 0.1]}
with TestClient(app) as client:
r1 = client.post("/v1/predict", json=payload_a, headers=headers)
r2 = client.post("/v1/predict", json=payload_a, headers=headers)
r_conflict = client.post("/v1/predict", json=payload_b, headers=headers)
r_batch = client.post(
"/v1/predict-batch",
json={"items": [payload_a, payload_b]},
headers={"Authorization": f"Bearer {token}"},
)
assert r1.status_code == 200 and r1.json()["cached_idempotency"] is False
assert r2.status_code == 200 and r2.json()["cached_idempotency"] is True
assert r2.json()["score"] == r1.json()["score"]
assert r_conflict.status_code == 409
assert r_conflict.headers["content-type"].startswith("application/problem+json")
assert r_batch.status_code == 200 and r_batch.json()["count"] == 2
def test_04_jwt_hs256_lifecycle_and_alg_none_forgery_rejected() -> None:
now = 1_700_000_000.0
valid_tok = encode_hs256_jwt("alice", "admin", DEFAULT_JWT_SECRET, now=now, ttl_sec=120)
principal = verify_hs256_jwt(valid_tok, DEFAULT_JWT_SECRET, now=now + 10.0)
assert principal.subject == "alice"
assert principal.role == "admin"
assert "model:reload" in principal.scopes
# Attack 1: alg="none" bypass attempt (Tim McLean 2015)
hdr_none = base64.urlsafe_b64encode(b'{"alg":"none","typ":"JWT"}').rstrip(b"=").decode("ascii")
pay_admin = (
base64.urlsafe_b64encode(
b'{"iss":"fsds-auth","aud":"fsds-serving","sub":"attacker","role":"admin","exp":9999999999}'
)
.rstrip(b"=")
.decode("ascii")
)
with pytest.raises(AuthError) as exc_none:
verify_hs256_jwt(f"{hdr_none}.{pay_admin}.", DEFAULT_JWT_SECRET, now=now)
assert exc_none.value.code == "invalid-jwt-algorithm"
# Attack 2: RS256 algorithm confusion header
hdr_rs = base64.urlsafe_b64encode(b'{"alg":"RS256","typ":"JWT"}').rstrip(b"=").decode("ascii")
with pytest.raises(AuthError):
verify_hs256_jwt(f"{hdr_rs}.{pay_admin}.fakesig", DEFAULT_JWT_SECRET, now=now)
# Attack 3: Expired token, wrong issuer, wrong audience, tampered signature
with pytest.raises(AuthError) as exc_exp:
verify_hs256_jwt(valid_tok, DEFAULT_JWT_SECRET, now=now + 200.0)
assert exc_exp.value.code == "expired-jwt"
with pytest.raises(AuthError):
verify_hs256_jwt(valid_tok, DEFAULT_JWT_SECRET, expected_issuer="other-idp", now=now + 10.0)
with pytest.raises(AuthError):
verify_hs256_jwt(valid_tok, DEFAULT_JWT_SECRET, expected_audience="other-api", now=now + 10.0)
parts = valid_tok.split(".")
tampered_sig = ("A" if parts[2][0] != "A" else "B") + parts[2][1:]
with pytest.raises(AuthError) as exc_sig:
verify_hs256_jwt(f"{parts[0]}.{parts[1]}.{tampered_sig}", DEFAULT_JWT_SECRET, now=now + 10.0)
assert exc_sig.value.code == "invalid-jwt-signature"
def test_05_api_key_constant_time_hash_storage_and_401_missing() -> None:
registry, demo_keys = build_default_api_key_registry()
for raw_key in demo_keys.values():
for rec in registry._records:
assert raw_key not in rec.key_hash_hex
assert len(rec.key_hash_hex) == 64
scorer_principal = registry.verify(demo_keys["scorer"])
assert scorer_principal.role == "scorer"
assert scorer_principal.auth_method == "api_key"
with pytest.raises(AuthError):
registry.verify("fsds_dev_wrong_key_1234567890")
app = create_serving_app(api_key_registry=registry)
with TestClient(app) as client:
unauth = client.post(
"/v1/predict",
json={"request_id": "req-noauth", "features": [1.0, 2.0]},
)
assert unauth.status_code == 401
assert unauth.headers.get("www-authenticate") == "Bearer"
assert unauth.headers["content-type"].startswith("application/problem+json")
def test_06_rbac_scope_enforcement_401_vs_403() -> None:
registry, demo_keys = build_default_api_key_registry()
app = create_serving_app(api_key_registry=registry)
admin_jwt = encode_hs256_jwt("ops-admin", "admin", DEFAULT_JWT_SECRET)
with TestClient(app) as client:
# reader -> 200 on stream, 403 on predict & admin reload
r_stream = client.get(
"/v1/stream?n_tokens=2&token_delay_ms=0", headers={"X-API-Key": demo_keys["reader"]}
)
r_pred_deny = client.post(
"/v1/predict",
json={"request_id": "req-deny-01", "features": [0.5, 0.5]},
headers={"X-API-Key": demo_keys["reader"]},
)
# scorer -> 200 on predict, 403 on admin reload
r_pred_ok = client.post(
"/v1/predict",
json={"request_id": "req-ok-01", "features": [0.5, 0.5]},
headers={"X-API-Key": demo_keys["scorer"]},
)
r_admin_deny = client.post(
"/v1/admin/reload",
json={"bias": 0.4, "temperature": 1.2, "model_version": "v2.5.0"},
headers={"X-API-Key": demo_keys["scorer"]},
)
# admin JWT -> 200 on reload
r_admin_ok = client.post(
"/v1/admin/reload",
json={"bias": 0.4, "temperature": 1.2, "model_version": "v2.5.0"},
headers={"Authorization": f"Bearer {admin_jwt}"},
)
assert r_stream.status_code == 200
assert r_pred_deny.status_code == 403
assert r_pred_ok.status_code == 200
assert r_admin_deny.status_code == 403
assert r_admin_ok.status_code == 200
assert r_admin_ok.json()["model_version"] == "v2.5.0"
def test_07_sse_streaming_endpoint_chunks_and_events() -> None:
app = create_serving_app()
token = encode_hs256_jwt("stream-user", "reader", DEFAULT_JWT_SECRET)
with TestClient(app) as client:
resp = client.get(
"/v1/stream?n_tokens=5&token_delay_ms=1",
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
assert resp.headers["content-type"].startswith("text/event-stream")
assert resp.headers["cache-control"] == "no-cache"
assert resp.headers["x-middleware-mode"] == "pure-asgi"
text = resp.text
for idx in range(5):
assert f"id: {idx}" in text
assert f'"index": {idx}' in text
assert "event: done" in text
def test_08_pure_asgi_middleware_zero_buffering_ttft_and_rps_advantage() -> None:
res = benchmark_sse_pure_asgi_vs_base_middleware(n_pings=200, n_tokens=5, token_delay_ms=16.0)
assert res["pure_asgi_rps"] > res["base_http_rps"]
assert res["pure_vs_base_rps_speedup"] >= 1.4
assert res["pure_asgi_sse"]["chunks_observed"] == 5
assert res["base_buffered_sse"]["chunks_observed"] == 1
assert res["pure_asgi_sse"]["ttft_ms"] < res["base_buffered_sse"]["ttft_ms"]
assert res["ttft_degradation_ratio"] >= 2.0
def test_09_pure_asgi_request_id_telemetry_and_429_rate_limiter() -> None:
registry, demo_keys = build_default_api_key_registry()
app = create_serving_app(
api_key_registry=registry,
rate_limit_rps=0.5,
rate_limit_burst=2.0,
enable_bench_endpoints=True,
)
admin_hdr = {"X-API-Key": demo_keys["admin"]}
with TestClient(app) as client:
r1 = client.get(
"/health/live", headers={"X-Client-ID": "tenant-a", "X-Request-ID": "custom-id-99"}
)
assert r1.status_code == 200
assert r1.headers["x-request-id"] == "custom-id-99"
assert "x-process-time-ms" in r1.headers
# Burst=2 allows 2 calls for tenant-a, 3rd hits 429, while tenant-b still gets 200
a1 = client.get(
"/v1/bench/to-thread?delay_ms=1", headers={**admin_hdr, "X-Client-ID": "tenant-a"}
)
a2 = client.get(
"/v1/bench/to-thread?delay_ms=1", headers={**admin_hdr, "X-Client-ID": "tenant-a"}
)
a3 = client.get(
"/v1/bench/to-thread?delay_ms=1", headers={**admin_hdr, "X-Client-ID": "tenant-a"}
)
b1 = client.get(
"/v1/bench/to-thread?delay_ms=1", headers={**admin_hdr, "X-Client-ID": "tenant-b"}
)
# Health probes must NEVER be rate-limited even for tenant-a
probe_ok = client.get("/health/live", headers={"X-Client-ID": "tenant-a"})
assert a1.status_code == 200 and a2.status_code == 200
assert a3.status_code == 429
assert a3.headers["content-type"].startswith("application/problem+json")
assert int(a3.headers["retry-after"]) >= 1
assert b1.status_code == 200
assert probe_ok.status_code == 200
assert len(app.state.runtime.telemetry_logs) >= 4
def test_10_async_blocking_trap_vs_to_thread_real_asgi_speedup() -> None:
res = benchmark_async_blocking_vs_offload(concurrency=10, delay_ms=16.0)
trap = res["blocking_trap"]
offload = res["to_thread_offload"]
assert trap["wall_ms"] > offload["wall_ms"]
assert res["wall_speedup"] >= 3.0
# Blocking time.sleep inside async def freezes /health/live mid-flight!
assert trap["health_live_probe_ms"] >= 80.0
assert offload["health_live_probe_ms"] < trap["health_live_probe_ms"] * 0.5
def test_11_kingman_vut_saturation_knee_and_littles_law_identity() -> None:
with pytest.raises(ValueError):
kingman_vut_expected_wait_ms(1.0, 10.0)
w_low = kingman_vut_expected_wait_ms(0.25, 12.0)
w_knee = kingman_vut_expected_wait_ms(0.85, 12.0)
w_sat = kingman_vut_expected_wait_ms(0.95, 12.0)
assert w_sat > w_knee > w_low
# Verify Sakasegawa multi-server exponent (sqrt(2*(c+1)) - 1) for c=4 at rho=0.85
expected_sak = round((0.85 ** (math.sqrt(10.0) - 1.0)) / (4.0 * 0.15) * 12.0, 3)
assert kingman_vut_expected_wait_ms(0.85, 12.0, servers=4) == expected_sak
q_res = benchmark_kingman_saturation_and_coordinated_omission(seed=42, quick=True)
sweep = q_res["saturation_sweep"]
assert len(sweep) == 5
p99s = [row["p99_ms"] for row in sweep]
assert p99s[-1] > p99s[2] > p99s[0]
for row in sweep:
rel_err = abs(row["littles_l_predicted"] - row["littles_l_measured"]) / max(
row["littles_l_measured"], 1e-6
)
assert rel_err < 0.15
def test_12_coordinated_omission_real_asgi_open_vs_closed_loop() -> None:
q_res = benchmark_kingman_saturation_and_coordinated_omission(seed=42, quick=True)
co = q_res["coordinated_omission_asgi"]
assert co["open_loop"]["p99_ms"] > co["closed_loop"]["p99_ms"] * 3.0
assert co["co_underreporting_ratio"] >= 3.0
def test_13_k8s_liveness_readiness_dependency_outage_and_sigterm_drain() -> None:
registry, demo_keys = build_default_api_key_registry()
app = create_serving_app(api_key_registry=registry)
assert app.state.runtime.lifespan_started is False
with TestClient(app) as client:
assert app.state.runtime.lifespan_started is True
assert client.get("/health/live").status_code == 200
assert client.get("/health/ready").status_code == 200
# Downstream dependency failure: liveness MUST remain 200 while readiness flips 503
app.state.runtime.degraded = True
assert client.get("/health/live").status_code == 200
r_deg = client.get("/health/ready")
assert r_deg.status_code == 503
assert r_deg.headers["content-type"].startswith("application/problem+json")
app.state.runtime.degraded = False
# SIGTERM handler flips draining -> readiness 503
prev = install_sigterm_handler(app)
try:
handler = signal.getsignal(signal.SIGTERM)
assert callable(handler)
handler(signal.SIGTERM, None)
finally:
restore_sigterm_handler(prev)
assert app.state.runtime.draining is True
assert client.get("/health/live").status_code == 200
assert client.get("/health/ready").status_code == 503
metrics = client.get("/metrics", headers={"X-API-Key": demo_keys["admin"]})
assert metrics.status_code == 200
m_json = metrics.json()
assert m_json["total_requests"] >= 5
assert m_json["draining"] is True
assert "otel_metrics" in m_json
assert m_json["otel_spans_recorded"] >= 5
assert app.state.runtime.lifespan_stopped is True
def test_14_load_scripts_locust_and_k6_syntax_and_contracts() -> None:
locust_path = LAB_ROOT / "locustfile.py"
k6_path = LAB_ROOT / "k6_load_test.js"
assert locust_path.is_file()
assert k6_path.is_file()
locust_src = locust_path.read_text(encoding="utf-8")
ast.parse(locust_src, filename=str(locust_path))
spec = importlib.util.spec_from_file_location("lab04_locustfile", locust_path)
assert spec is not None and spec.loader is not None
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
assert hasattr(mod, "ServingAPIUser")
k6_src = k6_path.read_text(encoding="utf-8")
for token in (
"constant-arrival-rate",
"dropped_iterations",
"fsds_sse_ttft_ms",
"/v1/predict",
"/v1/stream",
"thresholds",
):
assert token in k6_src, f"Missing {token!r} in k6_load_test.js"
def test_15_cli_demo_quick_healthcheck_and_workbench_json(tmp_path: Path) -> None:
cli_env = os.environ.copy()
existing_pp = cli_env.get("PYTHONPATH", "")
cli_env["PYTHONPATH"] = f"{SRC_DIR}{os.pathsep}{existing_pp}" if existing_pp else str(SRC_DIR)
hc_proc = subprocess.run(
[sys.executable, str(LAB_ROOT / "scripts" / "run_lab_demo.py"), "--healthcheck"],
cwd=str(LAB_ROOT),
env=cli_env,
capture_output=True,
text=True,
check=True,
)
hc_json = json.loads(hc_proc.stdout)
assert hc_json["status"] == "ready"
assert hc_json["live_status"] == 200
assert hc_json["ready_status"] == 200
out_json = tmp_path / "t2_ch04_quick.json"
demo_proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--quick",
"--seed",
"42",
"--output",
str(out_json),
],
cwd=str(LAB_ROOT),
env=cli_env,
capture_output=True,
text=True,
check=True,
)
assert "[3] Kingman VUT Saturation & Real ASGI Coordinated Omission:" in demo_proc.stdout
data = json.loads(out_json.read_text(encoding="utf-8"))
assert data["config"]["quick"] is True
assert data["config"]["seed"] == 42
panels = data["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
def test_16_security_only_ast_scan_no_unsafe_deserialization() -> None:
py_files = [
*list((LAB_ROOT / "src").rglob("*.py")),
*list((LAB_ROOT / "scripts").rglob("*.py")),
*list((LAB_ROOT / "tests").rglob("*.py")),
LAB_ROOT / "locustfile.py",
]
assert len(py_files) >= 6
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top = alias.name.split(".", 1)[0]
assert top not in FORBIDDEN_RUNTIME_IMPORTS, f"Forbidden import {top} in {py_file}"
elif isinstance(node, ast.ImportFrom) and node.module:
top = node.module.split(".", 1)[0]
assert top not in FORBIDDEN_RUNTIME_IMPORTS, f"Forbidden import {top} in {py_file}"
# Verify AsyncClient transport runs offline cleanly without external network calls
async def _quick_offline_smoke() -> int:
app = create_serving_app()
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://testserver"
) as client:
r = await client.get("/health/live")
return r.status_code
import asyncio
assert asyncio.run(_quick_offline_smoke()) == 200
assert time.monotonic() >= 0.0
def test_17_hardened_bench_and_metrics_rbac_and_feature_flag_401_403() -> None:
registry, demo_keys = build_default_api_key_registry()
admin_jwt = encode_hs256_jwt("ops-admin", "admin", DEFAULT_JWT_SECRET)
scorer_jwt = encode_hs256_jwt("ml-scorer", "scorer", DEFAULT_JWT_SECRET)
# Default app disables /v1/bench/* via feature flag AND guards /metrics + /v1/bench/* via RBAC
default_app = create_serving_app(api_key_registry=registry)
assert default_app.state.enable_bench_endpoints is False
with TestClient(default_app) as client:
assert client.get("/metrics").status_code == 401
assert client.get("/metrics", headers={"X-API-Key": demo_keys["reader"]}).status_code == 403
assert (
client.get("/metrics", headers={"Authorization": f"Bearer {scorer_jwt}"}).status_code
== 403
)
m_key = client.get("/metrics", headers={"X-API-Key": demo_keys["admin"]})
m_jwt = client.get("/metrics", headers={"Authorization": f"Bearer {admin_jwt}"})
assert m_key.status_code == 200 and m_jwt.status_code == 200
# /v1/bench/* must reject unauthenticated (401), non-admin (403), AND admin when flag=False (403)
for ep in ("/v1/bench/to-thread?delay_ms=1", "/v1/bench/async-blocking-trap?delay_ms=1"):
assert client.get(ep).status_code == 401
assert client.get(ep, headers={"X-API-Key": demo_keys["scorer"]}).status_code == 403
r_flag_off = client.get(ep, headers={"Authorization": f"Bearer {admin_jwt}"})
assert r_flag_off.status_code == 403
assert r_flag_off.headers["content-type"].startswith("application/problem+json")
# Feature flag enabled: still enforces 401/403 RBAC, allows admin 200
bench_app = create_serving_app(api_key_registry=registry, enable_bench_endpoints=True)
with TestClient(bench_app) as client:
assert client.get("/v1/bench/to-thread?delay_ms=1").status_code == 401
assert (
client.get(
"/v1/bench/to-thread?delay_ms=1",
headers={"X-API-Key": demo_keys["reader"]},
).status_code
== 403
)
r_ok = client.get(
"/v1/bench/to-thread?delay_ms=1",
headers={"Authorization": f"Bearer {admin_jwt}"},
)
assert r_ok.status_code == 200
assert r_ok.json()["mode"] == "asyncio_to_thread"
def test_18_bounded_state_lru_and_ttl_eviction_buckets_idempotency_logs() -> None:
now = [100.0]
registry, demo_keys = build_default_api_key_registry()
app = create_serving_app(
api_key_registry=registry,
rate_limit_rps=100.0,
rate_limit_burst=5.0,
clock=lambda: now[0],
max_buckets=2,
bucket_ttl_sec=10.0,
max_idempotency_entries=2,
idempotency_ttl_sec=10.0,
max_latencies=3,
max_telemetry_logs=3,
)
scorer_hdr = {"X-API-Key": demo_keys["scorer"]}
with TestClient(app) as client:
# 1. Token buckets LRU eviction (max_buckets=2) + TTL expiry
client.get("/v1/stream?n_tokens=1&token_delay_ms=0", headers={**scorer_hdr, "X-Client-ID": "c1"})
now[0] += 1.0
client.get("/v1/stream?n_tokens=1&token_delay_ms=0", headers={**scorer_hdr, "X-Client-ID": "c2"})
now[0] += 1.0
# Touch c1 so c2 becomes LRU
client.get("/v1/stream?n_tokens=1&token_delay_ms=0", headers={**scorer_hdr, "X-Client-ID": "c1"})
now[0] += 1.0
client.get("/v1/stream?n_tokens=1&token_delay_ms=0", headers={**scorer_hdr, "X-Client-ID": "c3"})
assert len(app.state.runtime.buckets) == 2
assert list(app.state.runtime.buckets.keys()) == ["c1", "c3"]
# Advance past bucket_ttl_sec=10.0 so c1 and c3 expire on next access
now[0] += 15.0
client.get("/v1/stream?n_tokens=1&token_delay_ms=0", headers={**scorer_hdr, "X-Client-ID": "c4"})
assert list(app.state.runtime.buckets.keys()) == ["c4"]
# 2. Idempotency cache LRU eviction (max_idempotency_entries=2) + TTL expiry
body_1 = {"request_id": "req-b1", "features": [1.0, 2.0]}
body_2 = {"request_id": "req-b2", "features": [2.0, 3.0]}
body_3 = {"request_id": "req-b3", "features": [3.0, 4.0]}
assert (
client.post("/v1/predict", json=body_1, headers={**scorer_hdr, "Idempotency-Key": "k1"})
.json()["cached_idempotency"]
is False
)
now[0] += 1.0
assert (
client.post("/v1/predict", json=body_2, headers={**scorer_hdr, "Idempotency-Key": "k2"})
.json()["cached_idempotency"]
is False
)
now[0] += 1.0
# Refresh k1 via replay -> k2 becomes LRU and gets evicted when k3 arrives
assert (
client.post("/v1/predict", json=body_1, headers={**scorer_hdr, "Idempotency-Key": "k1"})
.json()["cached_idempotency"]
is True
)
now[0] += 1.0
client.post("/v1/predict", json=body_3, headers={**scorer_hdr, "Idempotency-Key": "k3"})
assert len(app.state.runtime.idempotency_cache) == 2
assert list(app.state.runtime.idempotency_cache.keys()) == ["k1", "k3"]
# Advance past idempotency_ttl_sec=10.0 -> k1 expired
now[0] += 15.0
replay_after_ttl = client.post(
"/v1/predict", json=body_1, headers={**scorer_hdr, "Idempotency-Key": "k1"}
)
assert replay_after_ttl.json()["cached_idempotency"] is False
# 3. Bounded deque windows for latencies_ms and telemetry_logs
assert len(app.state.runtime.latencies_ms) == 3
assert len(app.state.runtime.telemetry_logs) == 3
def test_19_real_opentelemetry_spans_attributes_traceparent_and_metrics() -> None:
registry, demo_keys = build_default_api_key_registry()
app = create_serving_app(
api_key_registry=registry,
rate_limit_rps=0.5,
rate_limit_burst=2.0,
)
scorer_hdr = {"X-API-Key": demo_keys["scorer"]}
admin_hdr = {"X-API-Key": demo_keys["admin"]}
trace_hex = "4bf92f3577b34da6a3ce929d0e0e4736"
traceparent = f"00-{trace_hex}-00f067aa0ba902b7-01"
body = {"request_id": "req-otel-01", "features": [0.9, -0.1, 0.5, 0.2]}
with TestClient(app) as client:
r_live = client.get("/health/live")
assert r_live.status_code == 200
assert len(r_live.headers["x-trace-id"]) == 32
r_pred = client.post(
"/v1/predict",
json=body,
headers={
**scorer_hdr,
"Idempotency-Key": "otel-idem-1",
"traceparent": traceparent,
"X-Client-ID": "otel-client",
},
)
assert r_pred.status_code == 200
assert r_pred.headers["x-trace-id"] == trace_hex
# Second call hits idempotency cache; third non-probe call triggers 429 rate limit
r_replay = client.post(
"/v1/predict",
json=body,
headers={
**scorer_hdr,
"Idempotency-Key": "otel-idem-1",
"X-Client-ID": "otel-client",
},
)
assert r_replay.status_code == 200 and r_replay.json()["cached_idempotency"] is True
r_429 = client.post(
"/v1/predict",
json=body,
headers={**scorer_hdr, "X-Client-ID": "otel-client"},
)
assert r_429.status_code == 429
m_resp = client.get("/metrics", headers=admin_hdr)
assert m_resp.status_code == 200
m_payload = m_resp.json()
assert m_payload["otel_metrics"]["http.server.requests"] >= 4
assert m_payload["otel_metrics"]["http.server.rate_limited"] == 1
spans = app.state.runtime.span_exporter.get_finished_spans()
span_names = [s.name for s in spans]
assert "GET /health/live" in span_names
assert "POST /v1/predict" in span_names
assert "ml.inference.predict" in span_names
propagated = [
s
for s in spans
if s.name == "ml.inference.predict" and format(s.context.trace_id, "032x") == trace_hex
]
assert len(propagated) == 1
assert dict(propagated[0].attributes or {})["ml.idempotency.hit"] is False
assert dict(propagated[0].attributes or {})["ml.model.version"] == "v2.1.0"
replay_child = [
s
for s in spans
if s.name == "ml.inference.predict"
and dict(s.attributes or {}).get("ml.idempotency.hit") is True
]
assert len(replay_child) == 1
rate_limited_spans = [
s for s in spans if dict(s.attributes or {}).get("fsds.rate_limited") is True
]
assert len(rate_limited_spans) == 1
assert dict(rate_limited_spans[0].attributes or {})["http.response.status_code"] == 429
# Verify bounded metric cardinality (no request_id or client_id in OTel metric labels)
metrics_data = app.state.runtime.metric_reader.get_metrics_data()
assert metrics_data is not None
seen_metric_names: set[str] = set()
for rm in metrics_data.resource_metrics:
for sm in rm.scope_metrics:
for metric in sm.metrics:
seen_metric_names.add(metric.name)
for pt in metric.data.data_points:
attrs = dict(pt.attributes or {})
assert "fsds.request_id" not in attrs
assert "client_id" not in attrs
assert "url.path" not in attrs
assert {"http.server.requests", "http.server.request.duration", "http.server.rate_limited"} <= (
seen_metric_names
)
POST, giao tiếp RPC nội bộ tốc độ cao, và truyền token LLM theo thời gian thực), bộ lựa chọn và phòng thủ kiến trúc nào là chuẩn xác nhất?POST không lũy đẳng nên Idempotency-Key ngăn chặn ghi trùng khi retry (kiểm chứng ở test_03: cached_idempotency=True và 409 khi lệch payload). gRPC giữ kết nối TCP lâu dài nên L4 LB sẽ ghim lưu lượng vào 1 pod, đòi hỏi L7 LB; còn SSE hoạt động tự nhiên qua HTTP/1.1 và HTTP/2 cho LLM streaming.
X-API-Key lẫn Authorization: Bearer <JWT>. Cặp lỗ hổng bảo mật và phản hồi HTTP nào cần được khóa chặt trong schemas_and_auth.py?"alg": "none" bỏ chữ ký hoặc dùng khóa công khai RSA làm khóa HMAC HS256. test_04, test_05, test_06 của webapi_serving_lab xác minh chặn alg=none, hash 64-hex + hmac.compare_digest, và phân tách 401 vs 403 (scorer -> /v1/admin/reload).
FastAPI / Starlette, điều gì xảy ra khi một route async def gọi hàm đồng bộ chặn (time.sleep(0.02) hoặc requests.post) dưới 16 yêu cầu đồng thời, so với việc khai báo route def (hoặc asyncio.to_thread) và khởi tạo httpx.AsyncClient trong lifespan?httpx.ASGITransport trong t2_ch04_workbench_results.json (test_10) chứng minh bẫy đóng băng Event Loop (368.01 vs 50.19 ms, 7.33x) và độ trễ lan sang /health/live (367.91 ms). AnyIO mặc định giới hạn 40 token mỗi worker.
ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False) trên StrictPredictRequest của Pydantic v2 (pydantic-core Rust) và chuẩn hóa lỗi theo RFC 9457, hệ thống xử lý thế nào với payload {"request_id": "r123", "features": ["0.5", 1.0], "unknown_key": 1}?test_01 và test_02: strict=True từ chối chuỗi "0.5" (trong khi vẫn chấp nhận số nguyên 2 cho float theo chuẩn JSON), extra='forbid' chặn unknown_key, allow_inf_nan=False chặn NaN/Inf, và exception handler trả 422 application/problem+json.
@app.middleware("http") (BaseHTTPMiddleware) cho cổng API AI có luồng token SSE (text/event-stream), và thực nghiệm ASGI 3.0 trong Lab 04 đo được sự chênh lệch ra sao khi thay bằng Pure ASGI Middleware?test_08 và test_09 chứng minh Pure ASGI Middleware chỉnh header ngay ở khung http.response.start, trả trực tiếp 429 application/problem+json khi Token Bucket cạn, và truyền 5 sự kiện SSE zero-copy giữ nguyên TTFT = 29.87 ms.
/health/live, /health/ready, và trình tự xử lý SIGTERM nào ngăn chặn hoàn toàn vòng xoáy chết CrashLoopBackOff và mất gói lúc rolling update?test_13 kiểm chứng: khi degraded=True, /health/live vẫn trả 200 (tránh thảm họa restart đồng loạt + thundering herd) trong khi /health/ready trả 503 (gỡ khỏi Endpoints). Khi nhận SIGTERM, draining=True chuyển /health/ready sang 503. Ngoài ra Uvicorn keep-alive timeout phải LỚN HƠN proxy timeout để tránh race 502.
333.33 RPS). Theo Định luật Little (\(L = \lambda W\)) và phương trình Kingman/Sakasegawa VUT trong Lab 04, hiện tượng nào xảy ra khi độ sử dụng \(\rho\) tăng từ 0.25 lên 0.85 rồi 0.93?test_11: L_pred = 18.84 vs L_meas = 18.83 tại rho = 0.93, xấp xỉ Sakasegawa mũ sqrt(2(c+1)) - 1 cho W_q = 36.63 ms). Thừa số rho / (1 - rho) tạo khúc khuỷu bão hòa quanh rho = 0.75-0.85 khiến p99 tăng vọt tại rho = 0.93.
FastAPI ASGITransport của Lab 04 có một đợt dừng máy chủ 160 ms duy nhất, bài đo vòng đóng (V=1, 220 requests) báo p99 = 2.72 ms trong khi bài đo vòng mở (152.5 RPS, 120 requests) báo p99 = 173.87 ms (chênh 63.92x). Nguyên nhân gốc rễ và cấu hình k6 chuẩn xác là gì?test_12 trên FastAPI ASGITransport chứng minh khoảng cách 63.92x (2.72 vs 173.87 ms). k6_load_test.js dùng constant-arrival-rate và đặt ngưỡng dropped_iterations: ["count==0"] để bảo đảm bộ sinh tải không bị nghẽn thiếu VU làm méo phép đo.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Hợp đồng Pydantic v2 strict=True, Lỗi RFC 9457 & Idempotency-Key
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích tác dụng của từng cờ trong ConfigDict(strict=True, extra="forbid", frozen=True, allow_inf_nan=False), cách tránh rò rỉ traceback bằng application/problem+json (RFC 9457), và vì sao tái sử dụng Idempotency-Key với body khác phải trả 409 Conflict.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Kiểm tra StrictPredictRequest trong schemas_and_auth.py và handler RequestValidationError + /v1/predict trong app.py; chạy pytest -k "test_01 or test_02 or test_03" -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
StrictPredictRequest từ chối ép kiểu chuỗi/bool và trường lạ (422 application/problem+json kèm request_id và errors); Idempotency-Key khớp body trả cached_idempotency=True và score giống hệt, còn lệch SHA-256 body trả 409 Conflict.
Bài tập 2 — Xác thực JWT HS256 (RFC 7519), API Key Hằng thời gian & RBAC
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Trình bày lại tấn công alg="none" và RS256 -> HS256 (Tim McLean 2015), lý do phải băm khóa API bằng HMAC-SHA256 + đối chiếu qua hmac.compare_digest, và nguyên tắc tách 401 (AuthN) với 403 (AuthZ).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Mở verify_hs256_jwt và APIKeyRegistry trong schemas_and_auth.py, chạy pytest -k "test_04 or test_05 or test_06" -p no:cacheprovider -v để kiểm định reader, scorer, admin và token giả mạo.
Tiêu chí Đáp án & Số đối chứng
Không có khóa thô nào tồn tại trong APIKeyRegistry (chỉ có 64-hex digest); verify_hs256_jwt khóa cứng alg == 'HS256' chặn alg='none'/RS256/exp/iss/aud; reader nhận 403 ở /v1/predict, scorer nhận 403 ở /v1/admin/reload, và admin reload thành công (200).
Bài tập 3 — Pure ASGI Middleware, Token Bucket 429 & Luồng SSE Zero-Copy
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh cơ chế cấp phát task_group + memory_object_stream của BaseHTTPMiddleware với việc móc nối send_wrapper ở http.response.start của Pure ASGI Middleware, và nêu lý do probe /health/* phải được miễn rate limit.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy benchmark_sse_pure_asgi_vs_base_middleware() trong load_benchmark.py và rà soát RequestContextAndRateLimitMiddleware trong app.py; kiểm chứng pytest -k "test_07 or test_08 or test_09" -p no:cacheprovider -v.
Tiêu chí Đáp án & Số đối chứng
Pure ASGI đạt 18,073.6 RPS vs 4,482.7 RPS (4.03x), giữ luồng 5 chunk SSE ở TTFT = 29.87 ms so với 155.48 ms (5.21x chậm hơn khi đệm), và Token Bucket trả 429 Retry-After (problem+json) theo từng X-Client-ID mà không chạm tới /health/live.
Bài tập 4 — Cô lập Vòng lặp FastAPI (async def Blocking Trap vs. asyncio.to_thread)
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Giải thích cơ chế đa nhiệm hợp tác đơn luồng của asyncio/uvloop, giới hạn mặc định 40 luồng của AnyIO cho def / to_thread, và vì sao time.sleep trong async def đóng băng cả đầu dò /health/live.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi benchmark_async_blocking_vs_offload(concurrency=16, delay_ms=20.0) hoặc chạy pytest -k test_10 -p no:cacheprovider -v để đối chiếu wall_ms, rps, và health_live_probe_ms.
Tiêu chí Đáp án & Số đối chứng
blocking_trap kéo 16 yêu cầu thành 368.01 ms (43.5 RPS) và khóa /health/live tới 367.91 ms; chuyển sang asyncio.to_thread rút thời gian xuống 50.19 ms (318.8 RPS, nhanh hơn 7.33x) và /health/live phản hồi sau 30.75 ms.
Bài tập 5 — Tách bạch Đầu dò K8s (/health/live vs. /health/ready) & SIGTERM Drain
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích chuỗi sự cố CrashLoopBackOff khi /health/live phụ thuộc PostgreSQL và trình tự 3 bước tắt êm ái (preStop -> /health/ready = 503 -> chờ in_flight == 0) tránh rớt gói khi kube-proxy cập nhật iptables.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Thực thi run_lab_demo.py --healthcheck và chạy pytest -k "test_13 or test_15" -p no:cacheprovider -v kiểm tra chuyển trạng thái degraded=True và tín hiệu SIGTERM.
Tiêu chí Đáp án & Số đối chứng
Khi degraded=True, /health/live giữ nguyên 200 trong khi /health/ready trả 503 application/problem+json; khi SIGTERM kích hoạt draining=True, /health/ready lập tức trả 503; CLI --healthcheck xuất JSON status='ready'.
Bài tập 6 — Hàng đợi Kingman VUT, Coordinated Omission, OpenTelemetry SDK & 19/19 pytest
20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết công thức Sakasegawa/Kingman VUT và chứng minh sự tăng vọt của thừa số \(\rho / (1 - \rho)\) ở \(\rho = 0.85 \to 0.93\), đối chiếu \(L = \lambda W\), và giải thích cơ chế OpenTelemetry span propagation (W3C traceparent) cùng bounded caches.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch04_workbench_results.json, kiểm tra ruff check, mypy src, k6_load_test.js, locustfile.py, và chạy pytest -p no:cacheprovider -v (Tests 17–19 cho RBAC/LRU/OTel).
Tiêu chí Đáp án & Số đối chứng
Trên 4 server (E[S]=12 ms), p99 nhảy 56.24 -> 98.52 -> 254.45 ms (rho=0.25 -> 0.85 -> 0.93, W_q = 36.633 ms) với L_pred=18.84 vs L_meas=18.83; Open-Loop vạch trần 173.87 vs 2.72 ms (63.92x); ruff/mypy 0 lỗi, AST 0 import cấm, OTel & bounded LRU/deque PASS trong 19/19 pytest.