Chương 18 — Kỹ thuật Định tuyến, Ingress, API & AI Gateway (L4 Maglev, L7 P2C-EWMA, Full-Jitter + Circuit Breaker, PII Vault, Dual TPM & Semantic Cache)
Từ P2C-EWMA + Full-Jitter Backoff + Circuit Breaker + Request Hedging cắt bão retry -40.09% & giảm p99 6.38x (702.39 ms -> 110.02 ms), đến Token Rate-Limiting TPM khóa luồng + try/finally refund, Request-scoped PII Vault + Luhn, Tenant-scoped Semantic Cache (tau*=0.94, 90.0% recall, 0 FP), Envoy AI Gateway & SSE Disconnect Cancellation (81 spans).
Unit ID:
T2-P3-U06
Track & Part: Track 2 (EDAI) — Part 3: Distributed Systems, Kubernetes, Distributed Training & Cloud Infrastructure (part-03-distributed-k8s-cloud-and-gateway)
Cầu nối Hệ thống Trong Phần 3 (Ch 14–Ch 16\(\to\)Ch 18): Sau khi nắm luật vật lý phân tán (Ch 14), điều phối cụmKubernetes/Gateway API(Ch 15), huấn luyện phân tán (Ch 16) và kiến trúc mạng/chi phíGCP FinOps(Ch 17), Chương 18 xây dựng lớp mặt phẳng dữ liệu biên cho API và AI (AI Gateway) — kết nối hạ tầng phía dưới với các hệ thống suy luận LLM hiệu năng cao ở Phần 4 (Ch 20–Ch 23) và chuỗi triển khaiIaC/Istio(Ch 19).
Truy xuất Giáo trình Gốc (R47— Routing & Gateway,R30— API Gateway & NGINX): Traffic control & routing (routing strategies, load balancing, service discovery); Resilience & fallback (retry policy, circuit breakers, fallback strategies, timeout handling); Security & access management (AuthN & AuthZ, IP restriction & geo-fencing, PII handling, protocol translation); Financial & resource management (request/byte/token-based rate limit, quota & budget management, request prioritization); Other problems (semantic caching, distributed tracing, A/B test); Techstack: GCP, NGINX trong 02-track-edai-raw-curriculum.md và 02-track-2-edai-sota-syllabus.md
Xưởng Thực hành Song hành (WB-Ch18): labs/ch18-ai-gateway-routing-workbench/README.md (ai_gateway_routing_lab)
Tình huống Mở đầu: Bốn Thảm họa Biên Mạng Khi Đưa API Gateway Truyền thống Ra Đỡ Lưu lượng AI#
Một mô hình suy luận LLM đạt chất lượng cao vẫn có thể làm sập toàn bộ cụm phục vụ hoặc đốt cạn ngân sách đám mây chỉ trong vài phút nếu cổng định tuyến biên vận hành theo tư duy Web API cổ điển:
- Bão Thử lại Đồng bộ (
Retry Storm) &Round-RobinĐẩyp99Vọt702.39 ms: Khireplica-2suy giảm (ticks 15..69) vàreplica-3nhiễu đuôi24%, chiến lượcRound-Robinngây thơ vẫn bơm đều lưu lượng vào cả bốn bản sao. Kết hợp cơ chế thử lại đồng bộ không nhiễu (Naive Synchronized Retries), tổng số lượt gọi dội lên upstream bị khuếch đại1.8x(2,766lượt gọi trên1,538yêu cầu gốc, đỉnh61lượt/tick), tỷ lệ lỗi tăng vọt lên6.7%,p95 = 358.89 msvàp99 = 702.39 ms. Khi thay bằngP2C-EWMA+Full-Jitter Backoff+Circuit Breaker+Request HedgingtrongWB-Ch18, tải bão giảm40.09%(1.08x), tỷ lệ lỗi rớt xuống0.07%(99.93%thành công),p95tụt về77.3 msvàp99giảm6.38xxuống chỉ còn110.02 ms. - Bẫy Giới hạn
RPM = 60Để Lọt Payload64kToken Đốt Sạch Ngân sách: Kỹ sư đặt giới hạn60yêu cầu/phút (RPM-Only) cho từng thuê bao. Trong thử nghiệmWB-Ch18, một script xấu gửi đúng3gói64,000token (HTTP 200,192,090token) đã lọt qua trót lọt hàng ràoRPM = 60và đốt ngay\$0.9605chỉ trong vài tích tắc, đồng thời chiếm nghẽn băng thông của nhóm chat tương tác! Ngược lại, Dual Token-BucketTPM+ Trần Ngân sáchUSDchặn đứng gói64kngay tại cửa bằngHTTP 429 Too Many Requests(kèm headerRetry-After: 12), giữ chi tiêu củatenant-alphaở mức an toàn\$0.1426và bảo vệ100.0%(5/5HTTP 200) SLA cho luồng ưu tiêninteractive. - Ngưỡng
Semantic CacheThấp (\(\tau = 0.75\text{–}0.85\)) Trả Nhầm Lệnh "Hủy Thẻ" Cho Yêu cầu "Kích hoạt Thẻ": Để tiết kiệm chi phí API, một nhóm bật bộ nhớ đệm ngữ nghĩa ở ngưỡng cosine \(\tau = 0.75\) hoặc \(0.85\). Trên tập đo60truy vấn (30cặp đồng nghĩa,18cặp đảo cực tính/thực thể đối nghịch,12câu mới), ngưỡng \(\tau = 0.75\) gây ra18va chạm dương tính giả (37.5%trên tổng hit, lỗ ròng-\$3.96) và \(\tau = 0.85\) vẫn dính11va chạm (26.83%). Quét ngưỡng có hệ thống chỉ ra điểm tối ưu Pareto tại \(\tau = 0.94\): đạt0va chạm (0.0%FP, độ chính xác100.0%), giữ vững27/30(90.0%recall), tiết kiệm\$0.486và22,032.0 ms(trong khi đẩy quá cao lên \(\tau = 0.98\) làm recall sụp xuống6.67%, chỉ tiết kiệm\$0.036). - Rò rỉ
PIIThô Sang Nhà cung cấp Ngoài, Khóa Cứng Schema & Đứt Dấu Truy vết: Chuyển tiếp trực tiếp JSON khiến email, số thẻ tín dụng và số điện thoại khách hàng bay thẳng ra API công cộng; code cứng theo schema OpenAI khiến ứng dụng bất lực khi phải chuyển hướng dự phòng sang AWS Bedrock hay Google Vertex AI. CổngFastAPItrongWB-Ch18che sạch3thực thểPIIthành thẻ giữ chỗ trước khi rời biên (0rò rỉ trong payload upstream lẫn81OpenTelemetry spans), tái lập nguyên trạng cho client, dịch hai chiềuOpenAI\(\leftrightarrow\)Bedrock Converse/Vertex generateContent, bảo toànW3C traceparent, tách nhómA/Bxác định và nhân bảnShadowkhông chặn.
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 18 và xưởng thực hành ai_gateway_routing_lab (WB-Ch18), kỹ sư Dữ liệu & AI nắm vững:
- Phân tầng Mạng
L4(Maglev/TLS Passthrough) vsL7(HTTP/2,gRPC,SSEStreaming),Service Discovery& Cân bằng TảiP2C-EWMA(R47,R30): Giải thích vì saoL4làm ghim kết nốiHTTP/2multiplexing, cấu hìnhL7cho luồng tokenSSE(proxy_buffering off), phân biệtDNS,VIP/EndpointSlicevàEnvoy xDS, và chứng minh định lýPower-of-Two-Choices (P2C) + EWMAvượt trộiRound-Robin. - Thiết kế Khả năng Chịu lỗi Cấp Sản xuất (
Resilience): Dập tắt bão thử lại (Retry Storm) bằngFull-Jitter Exponential Backoff+Retry Budget, triển khai máy trạng tháiCircuit Breaker(CLOSED/OPEN/HALF_OPEN), cắt đuôip99bằngRequest Hedgingcó ngân sách, và thiết lập chuỗiModel Fallback. - Bảo mật Biên, Ẩn danh
PIICó Khả năng Đảo ngược & Chuyển đổi Giao thức (R47): Thiết kế tường ràoAuthN/AuthZ(Virtual Keys, RBAC),IP Allowlisting(CIDR),Geo-fencinglưu trú dữ liệu,PiiVaultche/tái lập tự động và bộ dịch chuẩn hóaOpenAI\(\leftrightarrow\)AWS Bedrock Converse/GCP Vertex AI. - Quản trị Tài chính AI,
Semantic Cache,W3C traceparent,A/B/Shadow& Hệ sinh thái Gateway 2026: Vận hành Dual Token-BucketTPM+ Trần Ngân sách$USD(HTTP 429+Retry-After) kèm Hàng đợi Ưu tiên (interactive>batch), tìm ngưỡng Pareto \(\tau\) cho Semantic Cache, lan truyềnW3C traceparent, và lựa chọn đúng giữaNGINX,Envoy AI GatewayvàLiteLLM.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T2-P3-U06, R47 & R30)#
Nội dung Gốc (02-track-edai-raw-curriculum.md, R47 & R30) |
Nâng cấp Chuẩn SOTA 2026 (ch-18) |
Mục trong Chương 18 | Tạo tác & Kiểm thử (ai_gateway_routing_lab) |
|---|---|---|---|
1. Traffic control & routing: routing strategies, LB, service discovery |
L4 Maglev (\(M=65537\)) vs L7 (HTTP/2/gRPC/SSE proxy_buffering off), xDS EDS, P2C-EWMA (19.35 ms p50, 0.0% lỗi) vs Round-Robin |
Trụ cột 1 (§1.1–§1.2) + Mermaid 3 | P2CEwmaLoadBalancer, RoundRobinLoadBalancer, Tests 05–06 |
2. Resilience & fallback: retry, circuit breakers, fallback, timeouts |
Dập Retry Storm (1.8x) bằng Full-Jitter Backoff + Retry Budget 25%, CircuitBreaker 3 trạng thái, Hedging (110.02 ms p99, 6.38x) & Fallback Chain |
Trụ cột 1 (§1.3) + Mermaid 2 + Widget 1 | CircuitBreaker, compute_backoff_delay_ms, run_resilience_and_lb_benchmark, Tests 03–04, 06–07 |
3. Security & access: AuthN/AuthZ, IP/Geo-fencing, PII, protocol translation |
Bearer Virtual Key, CIDR allowlist & Geo residency (403/eu-west), PiiVault (3 masked, 0 leak), OpenAI \(\leftrightarrow\) Bedrock Converse / Vertex |
Trụ cột 1 (§1.4) + Mermaid 1 | PiiVault, translate_openai_to_bedrock/vertex, Tests 10–11, 13–14, 18–19 |
4. Financial & resource: request/byte/token rate limit, budget, priority |
Vượt bẫy RPM=60 (3/3 whale 64k lọt, \$0.9605) bằng Dual TPM Bucket + USD Budget (HTTP 429 + Retry-After), đối soát 2 pha & interactive 100.0% SLA |
Trụ cột 1 (§1.5) + Widget 2 | TokenBucket, TenantPolicy, create_gateway_app, Tests 12, 15–17 |
5. Semantic caching, distributed tracing, A/B test & NGINX/Envoy/LiteLLM |
Quét Pareto \(\tau \in [0.75, 0.98]\) (\(\tau=0.94\): 0.0% FP, 90.0% recall, \$0.486 saved), W3C traceparent, A/B blake2b, Shadow, 81 OTel spans & so sánh NGINX/Envoy/LiteLLM |
Trụ cột 1 (§1.6–§1.7) + Trụ cột 2 + Widget 3 | run_semantic_cache_threshold_sweep, parse_or_create_traceparent, Tests 08–09, 20–24 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 18 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 18 & ai_gateway_routing_lab |
Giá trị Thực nghiệm WB-Ch18 (seed=42) |
|---|---|---|---|
| \(\text{score}(i), \widehat{L}_i\) | \(\text{ms}\) | Hàm chọn bản sao trong P2C-EWMA: \(\widehat{L}_i + w_q q_{\text{inflight}, i}\), với \(\widehat{L}_i \leftarrow (1-\alpha)\widehat{L}_i + \alpha L_{\text{obs}}\) |
P2C-EWMA + CB + Hedged: p99 = 110.02 ms vs Naive RR: 702.39 ms (6.38x) |
| \(t_{\text{sleep}}(a)\) | \(\text{ms}\) | Độ trễ Full-Jitter Exponential Backoff: \(\mathcal{U}(0, \min(T_{\text{cap}}, T_{\text{base}} \cdot 2^a))\) |
Cắt bão tải 1.8x \(\to\) 1.08x (-40.09% tổng lượt gọi), lỗi 6.7% \(\to\) 0.07% |
| \(S_{\text{CB}}\) | FSM State | Trạng thái Circuit Breaker: CLOSED \(\to\) OPEN (fail-fast) \(\to\) HALF_OPEN (thăm dò) |
Chuỗi kiểm chứng: CLOSED -> OPEN -> HALF_OPEN -> OPEN -> CLOSED; Fallback Bedrock |
| \(R_{\text{RPM}}, R_{\text{TPM}}, B_{\$}\) | req/m, tok/m, USD | Xô kép RPM + TPM (Dual Token-Bucket) và trần ngân sách $USD |
RPM=60 lọt 3/3 whale 64k (\$0.9605) vs TPM+USD: HTTP 429, interactive 100.0% |
| \(\tau, \text{FP}_{\text{col}}\) | \([0, 1], \%\) | Ngưỡng tương đồng cosine của Semantic Cache (\(s \ge \tau\)) và tỷ lệ va chạm dương tính giả |
\(\tau=0.75\): 18 FP (37.5%) \(\to\) \(\tau=0.94\): 0 FP (0.0%), 90.0% recall, \$0.486 |
traceparent |
W3C Header | Header chuẩn 00-<32hex trace_id>-<16hex span_id>-<flags> xuyên suốt Gateway |
Bảo toàn trace_id, sinh 81 OTel spans sạch PII, 3 Shadow Mirror, A/B xác định |
Trụ cột 1 — Nguyên lý Gốc: Định tuyến L4/L7, Cân bằng Tải P2C-EWMA, Chống Bão Thử lại, Bảo mật PII, Dual TPM & Semantic Cache#
1.1 Phân tầng L4 (Maglev) vs L7 (HTTP/2, gRPC, SSE) & Service Discovery (R47, R30)#
Mọi yêu cầu từ ứng dụng AI tới cụm mô hình đi qua ít nhất hai lớp mạng khác biệt về độ nhìn thấy (visibility) và chi phí xử lý:
- Tầng 4 (
L4— TCP/UDP,TLS Passthrough,MaglevConsistent Hashing &DSR):- Bộ cân bằng tải L4 chỉ đọc 5-tuple
(src_ip, src_port, dst_ip, dst_port, proto), không giải mã TLS và không phân tích HTTP. - Thuật toán
Maglev(Google): Tạo bảng tra cứu kích thước số nguyên tố \(M\) (chuẩn \(M = 65537\)) từ hoán vị trọng số của từng backend để định tuyến trong \(O(1)\) mà vẫn giữ tính nhất quán (consistent hashing): khi 1 backend chết hoặc thêm mới, phần lớn các kết nối TCP đang sống không bị đổi đích giữa chừng. Khi bật Direct Server Return (DSR), luồng phản hồi từ GPU server đi thẳng ra client không quay lại L4 proxy. - Bẫy L4 Đối với
HTTP/2&gRPC: VìHTTP/2vàgRPCgộp (multiplex) hàng trăm RPC song song vào một kết nối TCP duy nhất, cân bằng tải L4 sẽ ghim cứng toàn bộ lưu lượng của một client vào đúng 1 Pod dù 9 Pod khác đang rảnh! Vì vậy, L4 chỉ làm cổng biên ngoài cùng dẫn vào tầng proxy L7.
- Bộ cân bằng tải L4 chỉ đọc 5-tuple
- Tầng 7 (
L7—HTTP/1.1,HTTP/2,gRPC,SSEToken-Streaming):- Thực hiện TLS Termination tại biên, đọc đầy đủ header (
Authorization,traceparent,X-Geo-Country), URI và payload JSON để xác thực, đếm token, ẩnPII, chuyển đổi schema và cân bằng tải ở mức từng request trên kết nối dàiHTTP/2/gRPC. - Quy tắc Sống còn cho
Server-Sent Events(SSEToken-Streaming) & Lan truyền Ngắt Kết nối (Cancellation Propagation): Phản hồi LLM phát từng token quaContent-Type: text/event-stream. TrênNGINX/Envoy, bắt buộc tắt bộ đệm phản hồi (proxy_buffering offtrên NGINX,request_timeout: 0scho stream dài trên Envoy) và cấu hình ba ngưỡng thời gian tách biệt:connect_timeoutngắn (2s),read_idle_timeoutgiữa hai token liên tiếp (15s— cắt kết nối treo nếu GPU chết giữa chừng), vàstream_max_duration(180s–300s). Quan trọng không kém, khi trình duyệt/client đóng kết nối sớm (TCP FINhoặc HTTP/2RST_STREAM), AI Gateway phải lan truyền tín hiệu hủy (SSE client-disconnect cancellation propagation) ngay xuống upstreamvLLM/SGLang(proxy_ignore_client_abort offtrên NGINX; upstream HTTP/2 stream cancel trên Envoy -> gọiabort_request()), giải phóng tức thì KV-cache và tránh đốt GPU decode vô ích tới hếtmax_tokens!
- Thực hiện TLS Termination tại biên, đọc đầy đủ header (
- Khám phá Dịch vụ (
Service Discovery):- DNS (
A/SRV): Dễ bị stale connection pooling khi Pod tự co giãn (KEDA/HPAở Ch 15) thay đổi IP nhanh hơn DNS TTL. - Server-side VIP (
K8s EndpointSlice/Cilium eBPF): Tầng mạng cụm tự cập nhật danh sách Pod sẵn sàng mà client chỉ gọi một Virtual IP. - Control-Plane Push (
Envoy xDS / EDS): Mặt phẳng điều khiển đẩy danh sách endpoint khỏe mạnh tức thì (< 100 ms), kết hợp active health check và passive outlier detection (tạm loại ngay bản sao vừa trả chuỗi5xx).
- DNS (
1.2 Cân bằng Tải: Vì sao Round-Robin Thất bại & Định lý P2C-EWMA (R47)#
Round-Robin(RR) chia tuần tự \(0, 1, \dots, N-1\) bất chấp bản sao đó đang nghẽn hàng đợi, gặp GC pause hay phục vụ prompt64ktoken. Trong cụm AI có độ trễ không đồng nhất (vd.replica-2suy giảm270 mshoặcreplica-3nhiễu đuôi24%),RRtiếp tục ném lưu lượng vào nút chậm làm phình to độ trễ đuôip95/p99.Least-Requestsquét \(O(N)\) khắc phục được điểm mù tải nhưng tốn chi phí đồng bộ giữa nhiều worker và dễ gây hiệu ứng bầy đàn (herd effect) đổ dồn toàn bộ request mới vào một Pod vừa khởi động cóinflight = 0.P2C-EWMA(Power of Two Choices + Exponentially Weighted Moving Average):- Ở mỗi request, gateway lấy mẫu ngẫu nhiên 2 bản sao hợp lệ \(a, b\) trong \(O(1)\) không cần khóa toàn cục.
- Tính điểm chi phí tức thời dựa trên độ trễ trượt hàm mũ và số lượng yêu cầu đang bay theo hàng đợi Little:
\[\text{score}(i) = \widehat{L}_i(t) + w_q \cdot q_{\text{inflight}, i}(t), \qquad \widehat{L}_i \leftarrow (1 - \alpha)\widehat{L}_i + \alpha L_{\text{obs}}\]
- Theo định lý Mitzenmacher (2001), kiểm tra \(d = 2\) lựa chọn ngẫu nhiên giảm độ dài hàng đợi tối đa từ \(\Theta(\log N / \log \log N)\) (chọn ngẫu nhiên \(1\)) xuống mức siêu logarit \(\Theta(\log \log N / \log 2)\) — tiệm cận cân bằng toàn tri \(O(N)\) mà không tạo thắt cổ chai đồng bộ! Thực nghiệm
WB-Ch18chứng minhP2C-EWMAtự né được cảreplica-2đang brownout lẫnreplica-3nhiễu đuôi để giữ100.0%thành công (0.0%lỗi) và hạp95từ216.49 ms(RR) xuống183.58 ms.
1.3 Chống Bão Thử lại (Retry Storm), Circuit Breaker, Hedging & Model Fallback (R47)#
- Giải phẫu Bão Thử lại (Metastable Retry Storm): Khi hệ thống có \(L\) tầng gọi nối tiếp, mỗi tầng retry tối đa \(r\) lần với độ trễ cố định hoặc đồng bộ tức thì, hệ số khuếch đại lưu lượng đạt tới \((r+1)^L\). Trong
WB-Ch18, khireplica-2suy giảm và lưu lượng vào pha burst,Naive RR + Sync Retry Stormkhuếch đại1,538yêu cầu gốc thành2,766lượt gọi upstream (1.8x,1,228retry, đỉnh61lượt/tick) — đẩy cả các bản sao khỏe mạnh vượt ngưỡng bão hòa mềm (soft_cap = 7), gây6.7%lỗi vàp99 = 702.39 ms. - Ba Chốt Chặn Dập Bão:
Full-Jitter Exponential Backoff(Marc Brooker / AWS):\[t_{\text{sleep}}(a) \sim \mathcal{U}\!\left(0,\ \min\left(T_{\text{cap}},\ T_{\text{base}} \cdot 2^a\right)\right)\]Phân tán đều thời điểm thử lại trên toàn khoảng \([0, \text{cap}]\) thay vì dội thành sóng đồng pha.Retry Budget(20%–25%): Chặn cứng số lượt retry tối đa trong mỗi cửa sổ không vượt quá ngân sách, ngăn chặn vòng lặp sụp đổ ngay cả khi toàn cụm suy thoái.- Máy Trạng thái
Circuit Breaker(CLOSED\(\to\)OPEN\(\to\)HALF_OPEN): Khi tỷ lệ lỗi vượt ngưỡng (vd.>= 45%trên \(\ge 5\) mẫu hoặc4lỗi liên tiếp), mạch nhảy sangOPENđể ngắt nhanh (fail-fast) trong< 1 ms, bảo vệ cụm khỏi bão chờ timeout; hếtcooldown_tickschuyển sangHALF_OPENcho phép một lượng hữu hạnprobe_quotađi qua để kiểm tra hồi phục trước khi đóng lạiCLOSED.
- Cắt Đuôi Độ trễ
p99BằngRequest HedgingCó Ngân sách &Model Fallback Chain:- Theo bài báo The Tail at Scale (Dean & Barroso), với truy vấn idempotent, nếu quá ngưỡng \(\Delta_{\text{hedge}}\) (
60.0 mstrongWB-Ch18) mà bản sao chính chưa phản hồi, gateway bắn bản sao kép sang một nút khác (khống chế ngân sách hedge để tránh tự gây quá tải!) và lấy kết quả về sớm hơn: thực nghiệm bắn111hedge (1.08xtổng tải, giảm40.09%bão tải so với Naive RR) đã cắtp95từ183.58 msxuống77.3 msvàp99từ242.95 msxuống110.02 ms(6.38xnhanh hơn Naive RR Storm,2.21xnhanh hơn không có Hedging)! - Khi mạch của nhà cung cấp chính mở (
openai gpt-4o: OPEN 503), AI Gateway chuyển tiếp tự động dọc Model Fallback Chain sangaws-bedrock (claude-3-7-sonnet: CLOSED 200)\(\to\)gcp-vertex (gemini-2.5-flash).
- Theo bài báo The Tail at Scale (Dean & Barroso), với truy vấn idempotent, nếu quá ngưỡng \(\Delta_{\text{hedge}}\) (
1.4 Bảo mật Biên, Ẩn danh PII Có Khả năng Đảo ngược & Chuyển đổi Giao thức (R47)#
AuthN/AuthZBằng Virtual Keys,IP Allowlisting&Geo-fencing:- Cổng cấp Virtual Key riêng cho từng tenant/team, kiểm tra mô hình được phép gọi (
allowed_models), đối chiếu IP nguồn (X-Forwarded-For) qua danh sách CIDR (ipaddress.ip_network) và lọc quốc gia (X-Geo-Country) để trảHTTP 403ngay tại biên khi vi phạm (vd.DE/FRtự gắn chính sách lưu trúeu-west).
- Cổng cấp Virtual Key riêng cho từng tenant/team, kiểm tra mô hình được phép gọi (
- Ẩn danh & Tái lập
PIICó Khả năng Đảo ngược (Stateful Request-ScopedPiiVault+Luhn):- Trước khi định tuyến ra đám mây công cộng, một thể hiện
PiiVaultcó trạng thái duy nhất duyệt qua toàn bộpayload.messagestrong mỗi request (messages[0]email \(\to\)[PII_EMAIL_1],messages[1]email khác \(\to\)[PII_EMAIL_2], không bao giờ reset bộ đếm gây ghi đè khóa trong bảng ánh xạ!) và giữ bảng này chỉ trong phạm vi bộ nhớ của đúng request đó. Bộ nhận diện thẻ áp dụng kiểm định tổng kiểm Luhn (is_valid_luhn) để tránh bắt nhầm ID thường, đồng thời hỗ trợ định dạng SĐT quốc tế (+84909123456) và Mỹ ((555) 123-4567). Kết quả kiểm chứng trongWB-Ch18:3/3thực thể bị che trước khi qua bộ chuyển đổi upstream (0rò rỉ trong payload upstream và0rò rỉ trong81OpenTelemetry spans), sau đó tái lập hoàn chỉnh cho client.
- Trước khi định tuyến ra đám mây công cộng, một thể hiện
- Chuyển đổi Giao thức Đa Nhà cung cấp (Protocol Translation):
- Gateway nhận một chuẩn duy nhất OpenAI
ChatCompletionstừ ứng dụng nội bộ, tự động biến đổi sangAWS Bedrock Converse(systemblock riêng,inferenceConfig.maxTokens,content: [{"text": ...}]) hoặcGoogle Vertex AI generateContent(systemInstruction,contentsvớirole: "model",generationConfig.maxOutputTokens), rồi dịch ngược phản hồi (output.usagehoặccandidates.usageMetadata) về định dạng OpenAI thống nhất.
- Gateway nhận một chuẩn duy nhất OpenAI
1.5 Quản trị Tài chính AI: Vượt Bẫy RPM Bằng Dual TPM Bucket + USD Budget + Priority Queue (R47)#
- Vì sao
RPM(Requests Per Minute) Thất bại Trước LLM: Một hệ thống đặt trầnRPM = 60tưởng chừng an toàn, nhưng chỉ cần3gói64,000token (3 <= 60!) đã vượt lọt qua cổng (HTTP 200), tiêu thụ192,090token và đốt ngay\$0.9605trongWB-Ch18(250xđộ lệch tải so với một câu hỏi chat256token!). - Cơ chế Chuẩn Sản xuất 2026:
- Dual Token-Bucket (
RPM+TPM) An toàn Tuyến tính & Đồng thời (threading.Lock): Theo dõi đồng thời số request và tốc độ token mỗi phút bằng Dự trữ Hai Pha: trừ trước toàn bộprompt_tokens + max_tokens(tuyệt đối không cắt trần ở2048để tránh lỗ hổng vượt ngân sách USD!), kiểm tra chặt giá trị trả về củacluster_tpm_bucket.try_consume(chỉ hoàn trả khi cụm thực sự đã trừ token, tránh lạm phát hạn mức cụm), bọc lời gọi upstream trongtry / finallyđể vẫn hoàn trả token thừa ngay cả khi upstream văng ngoại lệ, khóa toàn bộ trạng thái chia sẻ bằngthreading.Lock, và khóa tiêu đề giả lậpX-Sim-Clock-Mssau cờapp.state.allow_test_clock(chặn giả mạo đồng hồ trên môi trường sản xuất). - Trần Ngân sách Tiền tệ (
USD Budget) & Header Chuẩn: Nếu cạn xôTPMhoặc vượt trần$USD, trả ngayHTTP 429 Too Many Requestskèm headerRetry-After(12strongWB-Ch18),X-RateLimit-Remaining-TokensvàX-Budget-Remaining-USD. - Hàng đợi Ưu tiên (
interactive>batch): Bảo lưu một phần băng thông token cụm (interactive_reserve_tokens = 12,000) để chủ động cắt tảibatch(CLUSTER_BATCH_SHEDDING_PROTECTING_INTERACTIVE) khi cận ngưỡng, bảo vệ100.0%(5/5HTTP 200) SLA cho luồng tương tác trực tuyến!
- Dual Token-Bucket (
1.6 Bộ nhớ đệm Ngữ nghĩa (Semantic Cache), W3C traceparent & Tách luồng A/B / Shadow (R47)#
- Đường cong Pareto của
Semantic Cache(\(\tau\)-Sweep):- Cache băm chính xác (Exact Cache) đạt tỷ lệ trúng rất thấp trước ngôn ngữ tự nhiên. Semantic Cache nhúng câu hỏi thành vector \(\mathbf{e}(q)\) chuẩn hóa \(L_2\) và so tích vô hướng cosine \(s = \langle \mathbf{e}(q), \mathbf{e}(k) \rangle \ge \tau\) (luôn phân vùng cứng theo
tenant_id + model + temperature <= 0.2để chống rò rỉ chéo thuê bao). - Bẫy Va chạm Cực tính (Adversarial Polarity Collision): Các cặp câu khác đúng 1 từ hành động hoặc thực thể ("Cancel my corporate credit card" vs "Activate my corporate credit card") thường đạt cosine rất cao (
0.84–0.91). Trong thí nghiệm60truy vấn củaWB-Ch18:- \(\tau = 0.75\): trúng
30/30đồng nghĩa nhưng dính tới18va chạm dương tính giả (37.5%trên tổng hit), lợi ích ròng-\$3.96. - \(\tau = 0.85\): vẫn dính
11va chạm (26.83%); \(\tau = 0.90\) còn3va chạm (9.09%). - \(\tau = 0.94\) (Điểm Tối ưu Pareto):
0va chạm (0.0%FP, độ chính xác100.0%), giữ vững27/30(90.0%recall), tiết kiệm\$0.486và22,032.0 ms! - \(\tau = 0.98\): an toàn tuyệt đối nhưng recall rơi thảm xuống
6.67%(2/30), đánh mất92.6%khoản tiết kiệm.
- \(\tau = 0.75\): trúng
- Cache băm chính xác (Exact Cache) đạt tỷ lệ trúng rất thấp trước ngôn ngữ tự nhiên. Semantic Cache nhúng câu hỏi thành vector \(\mathbf{e}(q)\) chuẩn hóa \(L_2\) và so tích vô hướng cosine \(s = \langle \mathbf{e}(q), \mathbf{e}(k) \rangle \ge \tau\) (luôn phân vùng cứng theo
- Truy vết Phân tán
W3C Trace Context(traceparent): Header chuẩn00-<32hex trace_id>-<16hex span_id>-<flags>được bảo toàntrace_id(4bf92f3577b34da6a3ce929d0e0e4736) khi gateway tạo span con chuyển tiếp xuống upstream, ghi nhận trọn vẹn81OpenTelemetry spans sạch PII vàoBoundedInMemorySpanExporter. - Phân tách Lưu lượng
A/B&ShadowQuaBackgroundTasks: NhánhA/Bbăm xác địnhblake2b(user_id) % 100để giữ nguyên mô hình cho cùng người dùng (variant_a: 7, variant_b: 2); còn luồngShadow(Traffic Mirroring) phát tác vụ bất đồng bộ thực sự qua FastAPIBackgroundTasksđể nhân bản3yêu cầu sang mô hình canary sau khi trả phản hồi chính — không tăng độ trễ hay làm lỗi client.
1.7 Kiến trúc Liên kết Hệ sinh thái Gateway Sản xuất (NGINX vs Envoy AI Gateway vs LiteLLM)#
Trong triển khai sản xuất 2025–2026, thay vì đặt proxy Python (FastAPI/LiteLLM) trực tiếp làm nút cổ chai trên mặt phẳng dữ liệu biên, kiến trúc chuẩn đặt Envoy AI Gateway làm xương sống hợp nhất:
- Kiến trúc
Envoy AI Gateway(AIGatewayRoute+AIServiceBackend+GAIE EPP): Khai báo CRDAIGatewayRouteđịnh nghĩa quy tắc định tuyến theo tên mô hình logic, fallback và cân bằng tải trọng số tới cácAIServiceBackend(vLLMnội bộ,OpenAI,AWS Bedrock,GCP Vertex), đồng thời tích hợpGateway API Inference Extension (GAIE) Endpoint Picker (EPP)thông qua giao thức streamingEnvoy ext-proc(gRPC External Processor) viết bằng Go/C++ để định tuyến theo KV-cache prefix và đếm token không cần đệm payload — loại bỏ hoàn toàn bước nhảy proxy Python chậm trên luồng dữ liệu chính trong khi vẫn giữ lan truyền ngắt kết nốiSSExuống tới vLLM!
Trụ cột 2 — Kiến trúc Hệ thống & Cẩm nang Quyết định Sản xuất (NGINX vs Envoy AI Gateway vs LiteLLM)#
| Tiêu chí Kiến trúc | NGINX / NGINX Gateway Fabric |
Envoy AI Gateway (CNCF Envoy + ext_proc) |
LiteLLM Proxy (FastAPI + Redis) |
Lựa chọn Khuyến nghị SOTA 2026 |
|---|---|---|---|---|
| Tầng Xử lý & Thông lượng | C event-loop siêu nhanh cho TLS, IP/Geo, static proxy (proxy_buffering off + hủy SSE khi client ngắt) |
C++ đa luồng, xDS, AIGatewayRoute + AIServiceBackend + GAIE EPP qua ext-proc (< 2 ms, bỏ proxy Python chậm) |
Python asyncio (FastAPI), linh hoạt nhất nhưng bị trần CPU/GIL khi quá tải biên |
Đặt NGINX/Envoy AI Gateway (ext-proc + GAIE EPP) làm mặt phẳng dữ liệu L7 chính |
| Cân bằng Tải AI & Chống Bão | Round-Robin, Least-Conn, EWMA (bản Plus) |
P2C, Maglev L4, Hedging, GAIE Endpoint Picker (EPP) theo KV-cache |
Latency-Based EWMA, Lowest-TPM, Model Fallback Chains nhiều nhà cung cấp |
Dùng P2C-EWMA + Full-Jitter + CB + Hedging (6.38x gọn p99 trong WB-Ch18) |
Đếm Token (TPM) & Ngân sách $USD |
Mạnh về RPM/bytes; muốn đếm token phải gắn NJS/Lua |
ext_proc + Rate Limit Service đọc usage từ SSE chunk cuối không đệm stream |
Tích hợp sẵn Virtual Key, TPM/RPM, đối soát 2 pha & trần $USD |
Dùng Dual TPM + $USD Budget + Priority Queue; tránh bẫy RPM-Only |
Dịch Giao thức, PII & Semantic Cache |
Không có sẵn bộ dịch OpenAI \(\leftrightarrow\) Bedrock/Vertex hay Semantic Cache | Chuẩn hóa Unified AI Schema qua filter AI Gateway / dịch vụ ext_proc |
Mạnh nhất (100+ LLM providers), hook sẵn Presidio PII & Redis Semantic Cache |
Áp dụng PiiVault request-scoped + ngưỡng Semantic Cache \(\tau = 0.94\) |
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python Độc lập (100% Khả thi Trong .venv)#
Đoạn mã dưới đây chạy hoàn toàn độc lập trong .venv (chỉ dùng numpy, pydantic và thư viện chuẩn Python), kiểm chứng trọn vẹn bốn bất biến cốt lõi của Chương 18: (1) Full-Jitter Exponential Backoff + máy trạng thái Circuit Breaker (CLOSED -> OPEN -> HALF_OPEN -> CLOSED); (2) điểm chọn P2C-EWMA; (3) quét ngưỡng Semantic Cache phát hiện va chạm đảo cực tính ở \(\tau = 0.85\) vs an toàn tuyệt đối ở \(\tau = 0.94\); và (4) PiiVault che/tái lập + dịch OpenAI -> Bedrock Converse.
from __future__ import annotations
import re
from typing import Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, ValidationError
class GatewayPolicyConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
tpm_limit: int = Field(gt=0)
semantic_tau: float = Field(ge=0.5, le=1.0)
hedge_trigger_ms: float = Field(gt=0.0)
def full_jitter_delay_ms(attempt: int, base_ms: float, cap_ms: float, rng: np.random.Generator) -> float:
upper = min(cap_ms, base_ms * float(2**attempt))
return round(float(rng.uniform(0.0, upper)), 2)
def p2c_ewma_pick(ewma_ms: list[float], inflight: list[int], rng: np.random.Generator) -> int:
i, j = [int(x) for x in rng.choice(len(ewma_ms), size=2, replace=False)]
score_i = ewma_ms[i] + 10.0 * inflight[i]
score_j = ewma_ms[j] + 10.0 * inflight[j]
return i if score_i <= score_j else j
def demo_resilience_and_p2c() -> None:
rng = np.random.default_rng(42)
delays = [full_jitter_delay_ms(a, 25.0, 350.0, rng) for a in range(4)]
assert all(0.0 <= d <= 350.0 for d in delays)
ewma = [18.5, 19.2, 265.0, 52.0] # replica-2 brownout, replica-3 noisy
inflight = [1, 1, 0, 0]
picks = [p2c_ewma_pick(ewma, inflight, rng) for _ in range(200)]
assert picks.count(2) == 0, "P2C-EWMA must avoid brownout replica-2!"
# Simple 3-state Circuit Breaker check
state: Literal["CLOSED", "OPEN", "HALF_OPEN"] = "CLOSED"
failures = 3
if failures >= 3:
state = "OPEN"
assert state == "OPEN"
state = "HALF_OPEN"
state = "CLOSED"
print(f"[1. P2C & Backoff] Full-Jitter={delays} | replica-2 picks={picks.count(2)}/200 | CB={state}")
def demo_semantic_cache_and_pii() -> None:
# Unit vectors representing positive paraphrase (cos=0.956) & polarity flip (cos=0.885)
base = np.array([1.0, 0.0, 0.0])
pos = np.array([0.956, np.sqrt(1.0 - 0.956**2), 0.0])
adv = np.array([0.885, -np.sqrt(1.0 - 0.885**2), 0.0])
sim_pos, sim_adv = float(base @ pos), float(base @ adv)
for tau, expected_fp in ((0.85, 1), (0.94, 0)):
fp = int(sim_adv >= tau)
tp = int(sim_pos >= tau)
assert fp == expected_fp and tp == 1
# Multi-message stateful PII redaction + Luhn check + tenant-scoped cache isolation check
def is_luhn(num: str) -> bool:
ds = [int(c) for c in num if c.isdigit()]
return 13 <= len(ds) <= 19 and sum(
(d * 2 - 9 if d * 2 > 9 else d * 2) if i % 2 == 1 else d
for i, d in enumerate(reversed(ds))
) % 10 == 0
assert is_luhn("4111-1111-1111-1111") is True and is_luhn("4111-2222-3333-4444") is False
email_re = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
vault, rev, cnt = {}, {}, 0
masked_msgs = []
for raw in ("Send alert to sre@company.vn.", "Backup cc to sec@company.vn and sre@company.vn."):
def _sub(m: re.Match[str]) -> str:
nonlocal cnt
val = m.group(0)
if val not in rev:
cnt += 1
tok = f"[PII_EMAIL_{cnt}]"
rev[val], vault[tok] = tok, val
return rev[val]
masked_msgs.append(email_re.sub(_sub, raw))
assert "[PII_EMAIL_1]" in masked_msgs[0] and "[PII_EMAIL_2]" in masked_msgs[1]
assert len(vault) == 2 and vault["[PII_EMAIL_1]"] == "sre@company.vn"
scoped_cache = {("tenant-a", "gpt-4o"): base}
assert ("tenant-b", "gpt-4o") not in scoped_cache
rejected = False
try:
GatewayPolicyConfig.model_validate({"tpm_limit": 40000, "semantic_tau": 0.94, "hedge_trigger_ms": 60.0, "bypass": True})
except ValidationError:
rejected = True
assert rejected is True
print(f"[2. Cache & PII] cos_pos={sim_pos:.3f}, cos_adv={sim_adv:.3f} (0 FP @ 0.94) | Multi-msg PII={len(vault)} & Tenant Isolation OK")
if __name__ == "__main__":
demo_resilience_and_p2c()
demo_semantic_cache_and_pii()
print("Pillar 3 AI Gateway & Routing Verification PASSED!")
Trụ cột 4 — Thực hành Công nghiệp (WB-Ch18: ai_gateway_routing_lab) & Kết quả Thực nghiệm#
4.1 Kiến trúc Xưởng WB-Ch18 (labs/ch18-ai-gateway-routing-workbench/)#
WB-Ch18 triển khai đầy đủ ba thực nghiệm mô phỏng xác định và dịch vụ FastAPI AI Gateway sống chạy 100% offline trong .venv:
src/ai_gateway_routing_lab/resilience_and_routing.py:- Thực nghiệm 1: So sánh bốn chiến lược định tuyến & phục hồi (
naive_rr_sync_retry,rr_full_jitter_cb,p2c_ewma_cb,p2c_ewma_cb_hedged) trên1,538yêu cầu qua cụm4bản sao (vớireplica-2suy giảm trongticks 15..69vàreplica-3nhiễu đuôi24%), kèm kiểm toán vòng đờiCircuitBreaker(CLOSED -> OPEN -> HALF_OPEN -> OPEN -> CLOSED) và chuỗi Model Fallback. - Thực nghiệm 2: Quét ngưỡng cosine \(\tau \in \{0.75, 0.85, 0.90, 0.94, 0.98\}\) trên
60truy vấn chuẩn hóa (30đồng nghĩa,18đối nghịch cực tính/thực thể,12câu mới) để định lượng điểm tối ưu Pareto.
- Thực nghiệm 1: So sánh bốn chiến lược định tuyến & phục hồi (
src/ai_gateway_routing_lab/ai_gateway_service.py:- Thực nghiệm 3 (
create_gateway_app+TestClient): Dịch vụFastAPIAI Gateway thực thi chuỗi lọc hoàn chỉnh:BearerAuthN/AuthZ,CIDRIP Allowlist & Geo-fencing (403),PiiVaultche/tái lập 3 loại thực thể, DualTPMBucket +$USDBudget +Priority Queue(429 + Retry-After), chuyển đổi OpenAI \(\leftrightarrow\) AWS Bedrock Converse & GCP Vertex AI,W3C traceparent, phân táchA/Bxác định,Shadowmirroring vàBoundedInMemorySpanExporter.
- Thực nghiệm 3 (
4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch18_wb18_results.json, seed=42)#
Thực nghiệm (ai_gateway_routing_lab) |
Thông số Đo được (Xác định seed=42) |
Bất biến Kỹ thuật Được Chứng minh |
|---|---|---|
Exp 1A — Bão Thử lại vs Full-Jitter + CB |
Naive RR Storm: 1.8x (2,766 req), 6.7% lỗi, p99 702.39 ms vs RR+FJ+CB: 1.01x, 0.07% lỗi, p99 250.91 ms (r2 mở mạch 5 lần) |
Full-Jitter + Retry Budget 25% + Circuit Breaker triệt tiêu bão tự khuếch đại |
Exp 1B — P2C-EWMA & Request Hedging |
P2C-EWMA+CB: 100.0% OK (0.0% lỗi), p95 = 183.58 ms \(\to\) thêm Hedging (111 hedge, 1.08x, -40.09% tải bão): p95 = 77.3 ms, p99 = 110.02 ms (6.38x nhanh hơn Naive) |
P2C-EWMA né nút chậm, còn Hedging có ngân sách cắt gọn gai trễ đuôi p99 |
Exp 2 — Quét Ngưỡng Semantic Cache (\(\tau\)) |
\(\tau=0.75\): 18 va chạm (-\$3.96); \(\tau=0.85\): 11 va chạm; \(\tau=0.90\): 3 va chạm; \(\tau=0.94\): 0 va chạm (0.0% FP), 90.0% recall, \$0.486 & 22,032.0 ms saved; \(\tau=0.98\): rớt còn 6.67% |
Chọn đúng điểm Pareto \(\tau = 0.94\) loại bỏ hoàn toàn va chạm đảo cực tính mà giữ nguyên giá trị tiết kiệm |
Exp 3A — Bẫy RPM=60 vs Dual TPM + Priority |
RPM=60 để lọt 3/3 gói 64k (192,090 token, \$0.9605) vs Dual TPM + Budget: chặn ngay HTTP 429 (Retry-After: 12), giữ spend = \$0.1426, interactive 100.0% (5/5 200) |
Giới hạn token hai pha + hàng đợi ưu tiên chặn tấn công whale payload & bảo vệ chat |
Exp 3B — PII Vault, Dịch Giao thức & OTel |
Che 3 PII ([PII_EMAIL_1], [PII_CARD_1], [PII_PHONE_1], 0 leak upstream/OTel), tái lập nguyên trạng; dịch openai: 7, bedrock: 1, vertex: 1; W3C traceparent; 81 OTel spans, 3 Shadow |
Cô lập dữ liệu nhạy cảm khỏi đám mây ngoài và hợp nhất quan sát xuyên nhà cung cấp |
4.3 Quy trình Kiểm định Tự động (30/30 Test Cases Pass, 0 Skipped, 0 # type: ignore)#
cd 03-track-2-data-and-ai-engineering/part-03-distributed-k8s-cloud-and-gateway/labs/ch18-ai-gateway-routing-workbench
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch18_wb18_results.json
ruff check src scripts tests
mypy src tests
pytest -p no:cacheprovider -v
uv lock --check
Trụ cột 5 — Danh mục Tài liệu SOTA (7 Tài liệu) & Bài tập Chuyên sâu#
5.1 Tài liệu Đọc Kinh điển & Frontier 2024–2026#
- Eisenbud, D. E. et al. (Google, NSDI 2016). Maglev: A Fast and Reliable Software Network Load Balancer. — Nền tảng bảng tra hoán vị \(O(1)\) cho cân bằng tải L4 nhất quán tốc độ dây.
- Mitzenmacher, M. (IEEE TPDS 2001) & Envoy Proxy Maintainers (2024–2026). The Power of Two Choices in Randomized Load Balancing & Envoy P2C Peak-EWMA / Retry Budgets. — Cơ sở toán học giảm hàm mũ độ dài hàng đợi cực đại xuống \(\Theta(\log \log N / \log 2)\) mà không cần khóa toàn cục.
- Dean, J. & Barroso, L. A. (Google, CACM 2013). The Tail at Scale. — Kinh điển về cắt độ trễ đuôi
p99bằngHedged Requestsvà cô lập nhiễu cục bộ. - Brooker, M. (AWS Architecture Blog, 2015–2024). Exponential Backoff and Jitter & Timeouts, Retries, and Backoff with Jitter. — Chứng minh định lượng vì sao
Full Jittervượt trội No Jitter và Equal Jitter trong dập bão thử lại. - Envoy AI Gateway & Kubernetes SIG Network (
GAIE, 2025–2026). Envoy AI Gateway (ext_procToken Rate Limiting & Schema Translation) and Gateway API Inference Extension. — Kiến trúc mặt phẳng dữ liệu L7 C++ cho LLM token streaming, fallback và prefix routing. - BerriAI (
LiteLLM) & NGINX Engineering (2024–2026). Unified Multi-Provider LLM Proxy Architecture (OpenAI, AWS Bedrock Converse, GCP Vertex AI) & NGINX Streaming SSE Tuning. — Thiết kế cổng chuyển đổi giao thức, quản trị ngân sách Virtual Key và cấu hình biênproxy_buffering off. - W3C Trace Context Working Group & OpenTelemetry (2024–2026). W3C
traceparentSpecification & Semantic Cache Collision Prevention in Production LLMs. — Lan truyền vết phân tán xuyên ranh giới đa nhà cung cấp và chống va chạm dương tính giả trong Semantic Cache.
5.2 Sáu Bài tập Tự luận & Thực hành (ex1 – ex6) Kèm Thang điểm (Grading Rubric)#
-
Bài tập 1 (
ex1, 15%) — Kiến trúcL4 MaglevvsL7 SSE& Bất đẳng thứcP2C-EWMA: Giải thích nguyên nhân L4 consistent hashing làm nghẽn cục bộ các kết nốiHTTP/2/gRPCmultiplexing, liệt kê ba tham số timeout bắt buộc cho luồngSSEtrênNGINX/Envoy, và chứng minh bằng trực giác định lý Mitzenmacher vì saoP2C-EWMAcắtp95từ216.49 msxuống183.58 msvà đạt100.0%thành công trongWB-Ch18(Tests 05–06).Thang điểm: Đúng cơ chế L4 vs L7/HTTP2/SSE (
5%), đúng công thức & hành viP2C-EWMA(5%), passTests 05–06(5%). -
Bài tập 2 (
ex2, 20%) — Dập Tắt Bão Thử lại (Retry Storm),Circuit BreakerFSM &Hedging: Dẫn xuất hệ số khuếch đại \((r+1)^L\) củaNaive Synchronized Retries, phân tích vòng chuyển trạng tháiCLOSED -> OPEN -> HALF_OPEN(Test 03), và chứng minh tại saoRequest Hedgingkhông giới hạn ngân sách tự gây bão tải cònHedgingcó ngân sách trongWB-Ch18cắtp996.38xtừ702.39 msxuống110.02 ms(Tests 04, 06–07).Thang điểm: Đúng công thức
Full Jitter&CircuitBreakerFSM (7%), phân tích chính xác bẫy hedging quá ngân sách & Fallback Chain (7%), passTests 03–04, 06–07(6%). -
Bài tập 3 (
ex3, 20%) — Tối ưu Ngưỡng Pareto \(\tau\) ChoSemantic CacheChống Va chạm Cực tính: Giải thích vì sao cặp câu đối nghịch ("hủy thẻ" vs "kích hoạt thẻ") dễ đạt cosine0.84–0.91, phân tích bảng quét \(\tau \in \{0.75, 0.85, 0.90, 0.94, 0.98\}\) (18FP tại0.75vs0FP tại0.94với\$0.486saved vs6.67%recall tại0.98), và chứng minh tính chất đơn điệu qua kiểm thửHypothesis(Tests 08–09).Thang điểm: Phân tích đúng đánh đổi Precision/Recall & lợi ích ròng (
8%), nêu rõ khóa phân vùng chống rò rỉ đa thuê bao (6%), passTests 08–09(6%). -
Bài tập 4 (
ex4, 15%) — Giải BẫyRPM=60BằngDual TPM Bucket+USD Budget+Priority Queue: Chứng minh vì saoRPM = 60để lọt3/3gói64ktoken (192,090token,\$0.9605), giải thích cơ chế dự trữ & đối soát hai pha (pre-flight reserve / post-flight refund) trongTokenBucket, và cách giữ100.0%SLA chointeractivebằngcluster_tpm_bucket(Tests 12, 15–17).Thang điểm: Đúng bất biến
TokenBucket& hoàn trả hai pha (5%), đúng logic cắt tảibatchbảo vệinteractive(5%), passTests 12, 15–17(5%). -
Bài tập 5 (
ex5, 15%) — Bảo mật Biên,PiiVaultĐảo ngược & Dịch Giao thứcOpenAI\(\leftrightarrow\)Bedrock/Vertex: Phân tích chuỗi phòng thủ tại cổngFastAPI(401API Key,403CIDR IP / Geo-fence,eu-westresidency), cơ chế che[PII_EMAIL_1]/[PII_CARD_1]/[PII_PHONE_1]trước upstream & tái lập đầu ra, và ánh xạ từng trường JSON giữaOpenAI,AWS Bedrock ConversevàGCP Vertex AI(Tests 10–11, 13–14, 18–19).Thang điểm: Đúng kiến trúc
PiiVaultkhông lưu vết (5%), đúng ánh xạ 3 giao thức (5%), passTests 10–11, 13–14, 18–19(5%). -
Bài tập 6 (
ex6, 15%) —W3C traceparent,A/B/BackgroundTasksShadow,OpenTelemetry&Envoy AI Gateway: Kiểm chứng quaTestClientkhả năng bảo toànW3C traceparent, bămA/Bxác địnhblake2b, nhân bảnShadowbất đồng bộ quaBackgroundTasks, thu81OTel spans sạchPII,0# type: ignorevà đề xuất kiến trúcNGINX + Envoy AI Gateway (AIGatewayRoute + AIServiceBackend + GAIE EPP)kèm lan truyền ngắt kết nốiSSE(Tests 01, 20–30).Thang điểm: Đúng cơ chế
traceparent+A/B/BackgroundTasksShadow (5%), đúng kiến trúcEnvoy AI Gateway+ hủySSE(5%), passTests 01, 20–30+ruff/mypy/uv(5%).
5.3 Tám Câu hỏi Trắc nghiệm Khái niệm (q1 – q8, Đồng bộ quiz_and_hints.json)#
- (
q1—L4 MaglevvsL7 HTTP/2&SSEStreaming): Tại sao cân bằng tải L4 hoạt động rất hiệu quả ở biên ngoài nhưng lại gây nghẽn nóng cục bộ khi đối mặt với lưu lượngHTTP/2/gRPChoặc làm hỏng luồngSSEnếu cấu hình sai? - (
q2— Cân bằng TảiRound-RobinvsP2C-EWMA): Theo định lý Power of Two Choices và công thức điểm chi phí trongWB-Ch18,P2C-EWMAvượt trộiRound-Robinở điểm nào khi cụm xuất hiện nút suy giảm hay nhiễu đuôi? - (
q3—Retry StormvsFull-Jitter+Circuit Breaker+Hedging): Trong Thực nghiệm 1 củaWB-Ch18(1,538yêu cầu gốc), sự kết hợpFull-Jitter Backoff,Retry Budget,Circuit BreakervàRequest Hedgingcó ngân sách cải thiện thông số tải bão vàp99như thế nào? - (
q4— BẫyRPM=60vsDual TPM Bucket+USD Budget+Priority Queue): Điều gì xảy ra khi dùng giới hạnRPM = 60cho workload LLM có payload64ktoken, và cơ chế đối soát hai pha + hàng đợi ưu tiên giải quyết triệt để ra sao? - (
q5— NgưỡngSemantic Cache& Chống Va chạm Cực tính): Trong bài quét ngưỡng \(\tau \in [0.75, 0.98]\) củaWB-Ch18, vì sao \(\tau = 0.94\) lại là điểm vận hành Pareto tối ưu thay vì \(\tau = 0.75\) hay \(\tau = 0.98\)? - (
q6— Bảo mật Biên &PiiVaultĐảo ngược): Chuỗi bảo vệ dữ liệu trongcreate_gateway_app()xử lýIP Allowlist,Geo-fencingvàPiiVaulttheo trình tự nào để bảo đảm0rò rỉ dữ liệu nhạy cảm? - (
q7— Chuyển đổi Giao thứcOpenAI\(\leftrightarrow\)Bedrock Converse/Vertex AI): Các trường cấu trúc nào thay đổi khiAI Gatewaydịch một yêu cầuOpenAI ChatCompletionssangAWS Bedrock ConversevàGoogle Vertex AI generateContent? - (
q8—W3C traceparent,A/B/Shadow& Hệ sinh tháiNGINX/Envoy AI Gateway/LiteLLM): Vai trò phân tầng giữaNGINX,Envoy AI GatewayvàLiteLLMcùng cơ chếW3C traceparentvàShadow MirroringtrongWB-Ch18hoạt động như thế nào?
p99 Latency (ms): Naive RR Storm vs Full-Jitter CB vs P2C-EWMA + Hedging
Semantic Cache False-Positive Collisions Across Cosine Threshold tau
Whale 64k-Token Attack Spend (USD): RPM=60 Trap vs Dual TPM + Budget
Upstream Request Amplification Factor (x Primary Requests)
L7 Load Balancing & Resilience Benchmark (4 Replicas, r2 Degraded)
| strategy | p50_p95_p99_ms | storm_amp_x | success_fail_pct |
|---|---|---|---|
| Naive RR + Sync Retry Storm (No Jitter/CB) | 21.0 / 358.89 / 702.39 ms | 1.8x (2766 req) | 93.3% OK / 6.7% fail |
| RR + Full-Jitter Backoff + Circuit Breaker | 20.12 / 216.49 / 250.91 ms | 1.01x (1549 req) | 99.93% OK / 0.07% fail |
| P2C-EWMA + Full-Jitter + Circuit Breaker | 19.35 / 183.58 / 242.95 ms | 1.0x (1545 req) | 100.0% OK / 0.0% fail |
| P2C-EWMA + Full-Jitter + CB + Request Hedging | 19.66 / 77.3 / 110.02 ms | 1.08x (1657 req) | 99.93% OK / 0.07% fail |
Semantic Cache Sweep (60 Eval: 30 Paraphrase / 18 Polarity-Flip / 12 Novel)
| threshold_tau | true_hits_recall | fp_collisions | usd_ms_saved |
|---|---|---|---|
| tau = 0.75 | 30/30 (100.0%) | 18 (37.5% on hits) | $0.54 | 24480.0 ms |
| tau = 0.85 | 30/30 (100.0%) | 11 (26.83% on hits) | $0.54 | 24480.0 ms |
| tau = 0.90 | 30/30 (100.0%) | 3 (9.09% on hits) | $0.54 | 24480.0 ms |
| tau = 0.94 | 27/30 (90.0%) | 0 (0.0% on hits) | $0.486 | 22032.0 ms |
| tau = 0.98 | 2/30 (6.67%) | 0 (0.0% on hits) | $0.036 | 1632.0 ms |
Financial Governance & Priority: RPM=60 Trap vs Dual TPM + USD Budget
| policy_mode | whale_64k_outcome | interactive_sla | alpha_spend_usd |
|---|---|---|---|
| RPM-Only (60 req/min) | 3/3 HTTP 200 (Leaked 192090 tok) | Contended by batch whales | $0.9605 |
| Dual TPM + USD Budget + Priority | HTTP 429 (Retry-After=12s) | 100.0% (5/5 HTTP 200) | $0.1426 (Budget Guarded) |
FastAPI AI Gateway Security, PII Vault, Translation & OTel Audit
| capability | verified_mechanism | observed_output | status |
|---|---|---|---|
| Edge AuthN / IP / Geo-Fence | CIDR Allowlist + X-Geo-Country | IP=403 | Geo=403 | DE=eu-west | PASS |
| Reversible PII Vault | Mask before upstream + Rehydrate reply | 3 masked | up_leak=False | otel_leak=False | PASS |
| OpenAI <-> Bedrock / Vertex | Converse & generateContent adapters | counts={'openai': 7, 'aws-bedrock': 1, 'gcp-vertex': 1} | PASS |
| W3C traceparent & A/B/Shadow | BoundedInMemorySpanExporter + blake2b | live_spans=81 | shadow=3 | ab={'variant_a': 7, 'variant_b': 2} | PASS |
03-track-2-data-and-ai-engineering/part-03-distributed-k8s-cloud-and-gateway/labs/ch18-ai-gateway-routing-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "ai-gateway-routing-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 WB-Ch18: AI Gateway Engineering, L4/L7 P2C-EWMA Load Balancing, Full-Jitter Retry & Circuit Breaker, Hedging, Semantic Cache Threshold Sweep, Reversible PII Vault, OpenAI/Bedrock/Vertex Protocol Translation & TPM Governance"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"httpx>=0.27",
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[project.scripts]
fsds-ai-gateway-lab = "ai_gateway_routing_lab.ai_gateway_service: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.mypy.overrides]]
module = [
"hypothesis",
"hypothesis.*",
]
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
"""FSDS-SOTA-2026 WB-Ch18: Routing, Ingress, API & AI Gateway Engineering Lab."""
from ai_gateway_routing_lab.ai_gateway_service import (
GatewayState,
PiiVault,
TenantPolicy,
TokenBucket,
create_gateway_app,
run_gateway_service_experiment,
translate_bedrock_to_openai,
translate_openai_to_bedrock,
translate_openai_to_vertex,
translate_vertex_to_openai,
)
from ai_gateway_routing_lab.resilience_and_routing import (
BoundedInMemorySpanExporter,
CircuitBreaker,
CircuitBreakerConfig,
LoadBalancerConfig,
P2CEwmaLoadBalancer,
RetryPolicyConfig,
RoundRobinLoadBalancer,
SemanticCacheEntry,
SemanticCacheSweepConfig,
compute_backoff_delay_ms,
create_in_memory_telemetry,
run_resilience_and_lb_benchmark,
run_semantic_cache_threshold_sweep,
summarize_finished_spans,
)
__all__ = [
"BoundedInMemorySpanExporter",
"CircuitBreaker",
"CircuitBreakerConfig",
"GatewayState",
"LoadBalancerConfig",
"P2CEwmaLoadBalancer",
"PiiVault",
"RetryPolicyConfig",
"RoundRobinLoadBalancer",
"SemanticCacheEntry",
"SemanticCacheSweepConfig",
"TenantPolicy",
"TokenBucket",
"compute_backoff_delay_ms",
"create_gateway_app",
"create_in_memory_telemetry",
"run_gateway_service_experiment",
"run_resilience_and_lb_benchmark",
"run_semantic_cache_threshold_sweep",
"summarize_finished_spans",
"translate_bedrock_to_openai",
"translate_openai_to_bedrock",
"translate_openai_to_vertex",
"translate_vertex_to_openai",
]
"""L4/L7 Load Balancing (P2C-EWMA), Full-Jitter CB/Hedging & Semantic Cache Sweep."""
from __future__ import annotations
import hashlib
import threading
from collections import deque
from collections.abc import Sequence
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from pydantic import BaseModel, ConfigDict, Field
class BoundedInMemorySpanExporter(SpanExporter):
"""Thread-safe bounded FIFO OpenTelemetry span exporter backed by deque(maxlen=256)."""
def __init__(self, maxlen: int = 256) -> None:
self._spans: deque[ReadableSpan] = deque(maxlen=maxlen)
self._lock = threading.Lock()
self._stopped = False
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
if self._stopped:
return SpanExportResult.FAILURE
with self._lock:
self._spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
self._stopped = True
def force_flush(self, timeout_millis: int = 30000) -> bool:
return True
def get_finished_spans(self) -> tuple[ReadableSpan, ...]:
with self._lock:
return tuple(self._spans)
def clear(self) -> None:
with self._lock:
self._spans.clear()
def create_in_memory_telemetry(
service_name: str = "fsds-wb18-ai-gateway",
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, trace.Tracer]:
"""Create a real OpenTelemetry TracerProvider backed by BoundedInMemorySpanExporter."""
exporter = BoundedInMemorySpanExporter(maxlen=256)
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("ai_gateway_routing_lab")
return provider, exporter, tracer
def summarize_finished_spans(
exporter: BoundedInMemorySpanExporter | InMemorySpanExporter,
) -> dict[str, Any]:
"""Serialize captured OpenTelemetry spans into JSON-safe artifact records."""
spans = exporter.get_finished_spans()
return {
"span_count": len(spans),
"span_names": [span.name for span in spans],
"spans": [
{
"name": span.name,
"status": span.status.status_code.name,
"attributes": dict(span.attributes or {}),
}
for span in spans
],
}
# ---------------------------------------------------------------------------
# Pydantic Strict Configurations
# ---------------------------------------------------------------------------
class LoadBalancerConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
n_replicas: int = Field(default=4, ge=2, le=32)
ewma_alpha: float = Field(default=0.30, gt=0.0, le=1.0)
initial_ewma_ms: float = Field(default=22.0, gt=0.0)
class RetryPolicyConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
max_retries: int = Field(default=3, ge=0, le=8)
base_delay_ms: float = Field(default=25.0, gt=0.0)
cap_delay_ms: float = Field(default=400.0, gt=0.0)
backoff_mode: Literal["fixed", "full_jitter"] = "full_jitter"
retry_budget_ratio: float = Field(default=0.20, ge=0.0, le=1.0)
class CircuitBreakerConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
window_size: int = Field(default=12, ge=4, le=200)
min_samples: int = Field(default=5, ge=2, le=50)
failure_rate_threshold: float = Field(default=0.35, gt=0.0, le=1.0)
consecutive_failure_threshold: int = Field(default=4, ge=2, le=50)
cooldown_ticks: int = Field(default=10, ge=1, le=200)
half_open_probes: int = Field(default=3, ge=1, le=20)
class SemanticCacheSweepConfig(BaseModel):
model_config = ConfigDict(extra="forbid")
thresholds: list[float] = Field(default_factory=lambda: [0.75, 0.85, 0.90, 0.94, 0.98])
upstream_call_usd: float = Field(default=0.018, gt=0.0)
upstream_latency_ms: float = Field(default=820.0, gt=0.0)
cache_lookup_ms: float = Field(default=4.0, ge=0.0)
# ---------------------------------------------------------------------------
# Experiment 1: Circuit Breaker FSM, Full-Jitter Backoff, P2C-EWMA & Hedging
# ---------------------------------------------------------------------------
class CircuitBreaker:
"""Deterministic 3-state Circuit Breaker FSM (`CLOSED` -> `OPEN` -> `HALF_OPEN`)."""
def __init__(self, replica_id: str, config: CircuitBreakerConfig | None = None) -> None:
self.replica_id = replica_id
self.config = config or CircuitBreakerConfig()
self.state: Literal["CLOSED", "OPEN", "HALF_OPEN"] = "CLOSED"
self._outcomes: deque[bool] = deque(maxlen=self.config.window_size)
self._consecutive_failures = 0
self._opened_at_tick = -1
self._half_open_probes_issued = 0
self._half_open_successes = 0
self.open_transitions = 0
self.half_open_transitions = 0
self.rejected_while_open = 0
def is_available(self, now_tick: int) -> bool:
"""Read-only availability check (advances `OPEN` -> `HALF_OPEN` when cooldown expires)."""
if self.state == "CLOSED":
return True
if self.state == "OPEN":
if now_tick - self._opened_at_tick >= self.config.cooldown_ticks:
self.state = "HALF_OPEN"
self.half_open_transitions += 1
self._half_open_probes_issued = 0
self._half_open_successes = 0
return True
return False
return self._half_open_probes_issued < self.config.half_open_probes
def allow_request(self, now_tick: int) -> bool:
"""Claim a request permit at `now_tick` (increments probe counter when `HALF_OPEN`)."""
if not self.is_available(now_tick):
self.rejected_while_open += 1
return False
if self.state == "HALF_OPEN":
self._half_open_probes_issued += 1
return True
def record_success(self, now_tick: int) -> None:
"""Record a successful upstream response."""
_ = now_tick
if self.state == "HALF_OPEN":
self._half_open_successes += 1
if self._half_open_successes >= self.config.half_open_probes:
self.state = "CLOSED"
self._outcomes.clear()
self._consecutive_failures = 0
self._half_open_probes_issued = 0
self._half_open_successes = 0
return
if self.state == "CLOSED":
self._consecutive_failures = 0
self._outcomes.append(True)
def record_failure(self, now_tick: int) -> None:
"""Record an upstream error/timeout and trip circuit if threshold is breached."""
if self.state == "HALF_OPEN":
self._trip_open(now_tick)
return
if self.state == "OPEN":
return
self._consecutive_failures += 1
self._outcomes.append(False)
n_samples = len(self._outcomes)
fail_rate = (
sum(1 for ok in self._outcomes if not ok) / n_samples if n_samples > 0 else 0.0
)
if self._consecutive_failures >= self.config.consecutive_failure_threshold or (
n_samples >= self.config.min_samples and fail_rate >= self.config.failure_rate_threshold
):
self._trip_open(now_tick)
def _trip_open(self, now_tick: int) -> None:
self.state = "OPEN"
self._opened_at_tick = now_tick
self._half_open_probes_issued = 0
self._half_open_successes = 0
self.open_transitions += 1
def compute_backoff_delay_ms(
attempt: int,
base_ms: float,
cap_ms: float,
mode: Literal["fixed", "full_jitter"],
rng: np.random.Generator,
) -> float:
"""Compute retry backoff delay using synchronized fixed delay or AWS Full Jitter."""
exp_window = min(cap_ms, base_ms * float(2**attempt))
if mode == "fixed":
return round(exp_window, 2)
return round(float(rng.uniform(0.0, exp_window)), 2)
class RoundRobinLoadBalancer:
"""Stateless cyclic Round-Robin backend selector ignoring replica latency and queue depth."""
def __init__(self, n_replicas: int) -> None:
self.n_replicas = n_replicas
self._cursor = 0
def select(self, eligible: Sequence[int]) -> int:
if not eligible:
raise ValueError("No eligible backend replicas available")
for _ in range(self.n_replicas):
cand = self._cursor % self.n_replicas
self._cursor = (self._cursor + 1) % self.n_replicas
if cand in eligible:
return cand
return eligible[0]
class P2CEwmaLoadBalancer:
"""Power-of-Two-Choices (`P2C`) minimizing `ewma_latency_ms + queue_weight * inflight`."""
def __init__(self, config: LoadBalancerConfig | None = None) -> None:
self.config = config or LoadBalancerConfig()
self.ewma_ms: list[float] = [self.config.initial_ewma_ms] * self.config.n_replicas
self.inflight: list[int] = [0] * self.config.n_replicas
def score(self, idx: int) -> float:
return self.ewma_ms[idx] + 10.0 * float(self.inflight[idx])
def select(self, eligible: Sequence[int], rng: np.random.Generator) -> int:
if not eligible:
raise ValueError("No eligible backend replicas available")
if len(eligible) == 1:
return eligible[0]
picked = rng.choice(eligible, size=2, replace=False)
a, b = int(picked[0]), int(picked[1])
return a if self.score(a) <= self.score(b) else b
def begin_request(self, idx: int) -> None:
self.inflight[idx] += 1
def finish_request(self, idx: int, observed_latency_ms: float) -> None:
self.inflight[idx] = max(0, self.inflight[idx] - 1)
alpha = self.config.ewma_alpha
self.ewma_ms[idx] = (1.0 - alpha) * self.ewma_ms[idx] + alpha * observed_latency_ms
@dataclass(frozen=True, slots=True)
class _StrategyProfile:
key: str
label: str
lb_mode: Literal["round_robin", "p2c_ewma"]
backoff_mode: Literal["fixed", "full_jitter"]
use_circuit_breaker: bool
use_retry_budget: bool
use_hedging: bool
max_retries: int
retry_layers: int
def _simulate_routing_strategy(profile: _StrategyProfile, seed: int) -> dict[str, Any]:
"""Run a deterministic discrete-tick L7 gateway + 4-replica cluster simulation."""
rng = np.random.default_rng(seed)
n_replicas = 4
total_ticks = 90
base_rps_per_tick = 15
replica_soft_cap = 7 # 3 healthy replicas = 21 cap (handles burst=19 cleanly when r2 opens)
tick_duration_ms = 50.0
hedge_trigger_ms = 60.0
client_deadline_ms = 350.0
lb_cfg = LoadBalancerConfig(n_replicas=n_replicas, ewma_alpha=0.20, initial_ewma_ms=20.0)
rr_lb = RoundRobinLoadBalancer(n_replicas=n_replicas)
p2c_lb = P2CEwmaLoadBalancer(lb_cfg)
cb_cfg = CircuitBreakerConfig(
window_size=12,
min_samples=5,
failure_rate_threshold=0.45,
consecutive_failure_threshold=4,
cooldown_ticks=12,
half_open_probes=3,
)
breakers = [CircuitBreaker(f"replica-{i}", cb_cfg) for i in range(n_replicas)]
# Retry queue items: (scheduled_tick, req_id, attempt, accumulated_ms)
retry_queue: list[tuple[int, int, int, float]] = []
completed_rids: set[int] = set()
completed_latencies: list[float] = []
client_success = 0
client_failed = 0
fallback_served = 0
total_primary_requests = 0
total_upstream_attempts = 0
total_retries_fired = 0
total_hedges_fired = 0
peak_tick_attempts = 0
r2_skipped_ticks = 0
def _record_outcome(rid: int, ok: bool, latency_ms: float) -> None:
nonlocal client_success, client_failed
if rid in completed_rids:
return
completed_rids.add(rid)
if ok and latency_ms <= client_deadline_ms:
client_success += 1
else:
client_failed += 1
completed_latencies.append(latency_ms)
req_counter = 0
for tick in range(total_ticks):
# Workload burst in ticks 18..64; replica-2 degraded in ticks 15..69
arrivals_now = 19 if 18 <= tick <= 64 else base_rps_per_tick
r2_degraded = 15 <= tick <= 69
if profile.use_circuit_breaker and breakers[2].state == "OPEN":
r2_skipped_ticks += 1
due_retries = [item for item in retry_queue if item[0] <= tick]
retry_queue = [item for item in retry_queue if item[0] > tick]
new_work: list[tuple[int, int, float]] = []
for _ in range(arrivals_now):
req_counter += 1
total_primary_requests += 1
new_work.append((req_counter, 0, 0.0))
tick_work = [(rid, att, acc) for (_, rid, att, acc) in due_retries] + new_work
replica_load = [0] * n_replicas
tick_completions: list[tuple[int, float]] = []
tick_attempts = 0
max_retries_this_tick = (
max(2, round(arrivals_now * 0.25)) if profile.use_retry_budget else 10_000
)
max_hedges_this_tick = max(2, round(arrivals_now * 0.18))
retries_used_this_tick = 0
hedges_used_this_tick = 0
for rid, attempt, acc_ms in tick_work:
if rid in completed_rids:
continue
if attempt > 0:
if retries_used_this_tick >= max_retries_this_tick:
_record_outcome(rid, False, acc_ms + 30.0)
continue
retries_used_this_tick += 1
if profile.use_circuit_breaker:
eligible = [idx for idx in range(n_replicas) if breakers[idx].is_available(tick)]
else:
eligible = list(range(n_replicas))
if not eligible:
fallback_served += 1
_record_outcome(rid, True, acc_ms + 85.0)
continue
if profile.lb_mode == "round_robin":
chosen = rr_lb.select(eligible)
else:
chosen = p2c_lb.select(eligible, rng)
if profile.use_circuit_breaker and not breakers[chosen].allow_request(tick):
fallback_served += 1
_record_outcome(rid, True, acc_ms + 85.0)
continue
# Keep request in-flight for the tick so P2C-EWMA sees concurrency q_i(t)
p2c_lb.begin_request(chosen)
replica_load[chosen] += 1
tick_attempts += 1
total_upstream_attempts += 1
overload = max(0, replica_load[chosen] - replica_soft_cap)
if chosen == 2 and r2_degraded:
base_lat = 270.0 + float(rng.normal(0.0, 22.0))
err_prob = min(0.96, 0.85 + 0.06 * overload)
else:
# Replica-3 has noisy-neighbor stalls (24% chance 190-255 ms); r0/r1 only 3%
if chosen == 3:
is_r3_stall = float(rng.random()) < 0.24
base_lat = (
float(rng.uniform(190.0, 255.0))
if is_r3_stall
else float(rng.uniform(32.0, 48.0))
)
else:
is_tail = float(rng.random()) < 0.035
base_lat = (
float(rng.uniform(145.0, 185.0))
if is_tail
else float(rng.uniform(14.0, 22.0))
)
base_lat += 20.0 * overload + (65.0 * ((overload - 3) ** 1.5) if overload > 3 else 0.0)
err_prob = min(0.92, 0.002 + (0.28 * (overload - 3) if overload > 3 else 0.0))
obs_lat = max(8.0, base_lat)
failed_call = float(rng.random()) < err_prob
tick_completions.append((chosen, obs_lat))
if (
profile.use_hedging
and not failed_call
and obs_lat > hedge_trigger_ms
and hedges_used_this_tick < max_hedges_this_tick
and len(eligible) > 1
):
alt_eligible = [idx for idx in eligible if idx != chosen]
hedge_node = p2c_lb.select(alt_eligible, rng)
if not profile.use_circuit_breaker or breakers[hedge_node].allow_request(tick):
hedges_used_this_tick += 1
p2c_lb.begin_request(hedge_node)
replica_load[hedge_node] += 1
tick_attempts += 1
total_upstream_attempts += 1
total_hedges_fired += 1
h_overload = max(0, replica_load[hedge_node] - replica_soft_cap)
if hedge_node == 2 and r2_degraded:
h_lat = 250.0
h_fail = True
else:
h_tail = float(rng.random()) < 0.03
h_lat = (
float(rng.uniform(44.0, 58.0))
if h_tail
else float(rng.uniform(14.0, 22.0))
)
h_lat += 16.0 * h_overload
h_fail = float(rng.random()) < 0.01
tick_completions.append((hedge_node, h_lat))
if not h_fail:
if profile.use_circuit_breaker:
breakers[hedge_node].record_success(tick)
obs_lat = min(obs_lat, hedge_trigger_ms + h_lat)
else:
if profile.use_circuit_breaker:
breakers[hedge_node].record_failure(tick)
if not failed_call:
if profile.use_circuit_breaker:
breakers[chosen].record_success(tick)
_record_outcome(rid, True, acc_ms + obs_lat)
else:
if profile.use_circuit_breaker:
breakers[chosen].record_failure(tick)
if attempt < profile.max_retries:
fanout = profile.retry_layers if profile.backoff_mode == "fixed" else 1
for _ in range(fanout):
delay_ms = compute_backoff_delay_ms(
attempt=attempt,
base_ms=25.0,
cap_ms=350.0,
mode=profile.backoff_mode,
rng=rng,
)
tick_offset = (
0
if profile.backoff_mode == "fixed"
else max(1, round(delay_ms / tick_duration_ms))
)
retry_queue.append(
(tick + tick_offset, rid, attempt + 1, acc_ms + obs_lat + delay_ms)
)
total_retries_fired += 1
else:
if profile.use_circuit_breaker:
fallback_served += 1
_record_outcome(rid, True, acc_ms + obs_lat + 65.0)
else:
_record_outcome(rid, False, acc_ms + obs_lat)
# Uncoordinated synchronous multi-layer retry storm within the same tick
if profile.backoff_mode == "fixed":
same_tick_waves = [item for item in retry_queue if item[0] == tick]
retry_queue = [item for item in retry_queue if item[0] > tick]
wave_cap = 0
while same_tick_waves and wave_cap < 4:
wave_cap += 1
next_wave: list[tuple[int, int, int, float]] = []
for _t, rid, att, acc in same_tick_waves:
chosen = rr_lb.select(list(range(n_replicas)))
replica_load[chosen] += 1
tick_attempts += 1
total_upstream_attempts += 1
overload = max(0, replica_load[chosen] - replica_soft_cap)
err_p = (
min(0.96, 0.85 + 0.06 * overload)
if (chosen == 2 and r2_degraded)
else min(0.95, 0.25 + 0.30 * overload)
)
w_lat = (270.0 if (chosen == 2 and r2_degraded) else 48.0) + 95.0 * (
overload**1.6
)
if float(rng.random()) >= err_p:
_record_outcome(rid, True, acc + w_lat)
elif att < profile.max_retries:
for _ in range(profile.retry_layers):
total_retries_fired += 1
next_wave.append((tick, rid, att + 1, acc + w_lat + 65.0))
else:
_record_outcome(rid, False, acc + w_lat)
same_tick_waves = next_wave
for idx, lat in tick_completions:
p2c_lb.finish_request(idx, lat)
peak_tick_attempts = max(peak_tick_attempts, tick_attempts)
for _t, rid, _att, acc in retry_queue:
if rid in completed_rids:
continue
if profile.use_circuit_breaker:
fallback_served += 1
_record_outcome(rid, True, acc + 65.0)
else:
_record_outcome(rid, False, acc + 120.0)
lat_arr = np.array(completed_latencies, dtype=float)
total_outcomes = max(1, client_success + client_failed)
success_rate_pct = round((client_success / total_outcomes) * 100.0, 2)
failure_rate_pct = round((client_failed / total_outcomes) * 100.0, 2)
storm_amp_x = round(total_upstream_attempts / max(1, total_primary_requests), 2)
return {
"strategy": profile.key,
"label": profile.label,
"primary_requests": total_primary_requests,
"total_upstream_attempts": total_upstream_attempts,
"storm_amplification_x": storm_amp_x,
"retries_fired": total_retries_fired,
"hedges_fired": total_hedges_fired,
"peak_tick_attempts": peak_tick_attempts,
"success_rate_pct": success_rate_pct,
"failure_rate_pct": failure_rate_pct,
"fallback_served": fallback_served,
"p50_latency_ms": round(float(np.percentile(lat_arr, 50)), 2),
"p95_latency_ms": round(float(np.percentile(lat_arr, 95)), 2),
"p99_latency_ms": round(float(np.percentile(lat_arr, 99)), 2),
"r2_cb_open_transitions": breakers[2].open_transitions,
"r2_cb_half_open_transitions": breakers[2].half_open_transitions,
"r2_cb_open_ticks": r2_skipped_ticks,
}
def run_resilience_and_lb_benchmark(seed: int = 42) -> dict[str, Any]:
"""Compare Naive RR Retry Storm vs Full-Jitter+CB vs P2C-EWMA vs P2C-EWMA+Hedging."""
profiles = [
_StrategyProfile(
key="naive_rr_sync_retry",
label="Naive RR + Sync Retry Storm (No Jitter/CB)",
lb_mode="round_robin",
backoff_mode="fixed",
use_circuit_breaker=False,
use_retry_budget=False,
use_hedging=False,
max_retries=3,
retry_layers=2,
),
_StrategyProfile(
key="rr_full_jitter_cb",
label="RR + Full-Jitter Backoff + Circuit Breaker",
lb_mode="round_robin",
backoff_mode="full_jitter",
use_circuit_breaker=True,
use_retry_budget=True,
use_hedging=False,
max_retries=2,
retry_layers=1,
),
_StrategyProfile(
key="p2c_ewma_cb",
label="P2C-EWMA + Full-Jitter + Circuit Breaker",
lb_mode="p2c_ewma",
backoff_mode="full_jitter",
use_circuit_breaker=True,
use_retry_budget=True,
use_hedging=False,
max_retries=2,
retry_layers=1,
),
_StrategyProfile(
key="p2c_ewma_cb_hedged",
label="P2C-EWMA + Full-Jitter + CB + Request Hedging",
lb_mode="p2c_ewma",
backoff_mode="full_jitter",
use_circuit_breaker=True,
use_retry_budget=True,
use_hedging=True,
max_retries=2,
retry_layers=1,
),
]
results = {p.key: _simulate_routing_strategy(p, seed=seed) for p in profiles}
naive = results["naive_rr_sync_retry"]
rr_fj = results["rr_full_jitter_cb"]
p2c = results["p2c_ewma_cb"]
hedged = results["p2c_ewma_cb_hedged"]
# Explicit CircuitBreaker FSM lifecycle audit (CLOSED -> OPEN -> HALF_OPEN -> OPEN -> CLOSED)
cb = CircuitBreaker(
"openai-primary",
CircuitBreakerConfig(
window_size=6,
min_samples=4,
failure_rate_threshold=0.50,
consecutive_failure_threshold=3,
cooldown_ticks=5,
half_open_probes=2,
),
)
states_trace: list[str] = [cb.state]
for tick in range(3):
assert cb.allow_request(tick)
cb.record_failure(tick)
states_trace.append(cb.state) # OPEN
blocked_at_tick_4 = not cb.allow_request(4)
assert blocked_at_tick_4
assert cb.allow_request(8) # cooldown elapsed -> HALF_OPEN
states_trace.append(cb.state)
cb.record_failure(8) # probe failure re-opens
states_trace.append(cb.state)
assert cb.allow_request(14)
cb.record_success(14)
assert cb.allow_request(14)
cb.record_success(14)
states_trace.append(cb.state) # CLOSED
# Model Fallback Chain simulation
fallback_chain = [
{"provider": "openai", "model": "gpt-4o", "cb_state": "OPEN", "status": 503},
{"provider": "aws-bedrock", "model": "claude-3-7-sonnet", "cb_state": "CLOSED", "status": 200},
{"provider": "gcp-vertex", "model": "gemini-2.5-flash", "cb_state": "CLOSED", "status": 200},
]
selected_fallback = next(item for item in fallback_chain if item["cb_state"] == "CLOSED")
p99_reduction_vs_naive_x = round(
float(naive["p99_latency_ms"]) / max(1.0, float(hedged["p99_latency_ms"])),
2,
)
p99_hedging_gain_x = round(
float(p2c["p99_latency_ms"]) / max(1.0, float(hedged["p99_latency_ms"])),
2,
)
storm_load_reduction_pct = round(
(
(int(naive["total_upstream_attempts"]) - int(hedged["total_upstream_attempts"]))
/ max(1, int(naive["total_upstream_attempts"]))
)
* 100.0,
2,
)
return {
"seed": seed,
"strategies": list(results.values()),
"by_key": results,
"summary": {
"naive_storm_amplification_x": naive["storm_amplification_x"],
"hedged_storm_amplification_x": hedged["storm_amplification_x"],
"storm_load_reduction_pct": storm_load_reduction_pct,
"naive_p99_ms": naive["p99_latency_ms"],
"rr_full_jitter_p99_ms": rr_fj["p99_latency_ms"],
"p2c_ewma_p99_ms": p2c["p99_latency_ms"],
"hedged_p99_ms": hedged["p99_latency_ms"],
"p99_reduction_vs_naive_x": p99_reduction_vs_naive_x,
"p99_hedging_gain_x": p99_hedging_gain_x,
"naive_failure_rate_pct": naive["failure_rate_pct"],
"hedged_failure_rate_pct": hedged["failure_rate_pct"],
},
"circuit_breaker_fsm_audit": {
"states_trace": states_trace,
"blocked_during_open": blocked_at_tick_4,
"open_transitions": cb.open_transitions,
"half_open_transitions": cb.half_open_transitions,
},
"fallback_chain_audit": {
"chain": fallback_chain,
"resolved_provider": selected_fallback["provider"],
"resolved_model": selected_fallback["model"],
},
}
# ---------------------------------------------------------------------------
# Experiment 2: Semantic Cache Similarity Threshold Sweep (tau in [0.75, 0.98])
# ---------------------------------------------------------------------------
@dataclass(frozen=True, slots=True)
class SemanticCacheEntry:
cache_id: str
tenant_id: str
model: str
intent_label: str
canonical_prompt: str
cached_response: str
embedding: np.ndarray[tuple[int], np.dtype[np.float64]]
@dataclass(frozen=True, slots=True)
class _EvalQuery:
query_id: str
category: Literal["positive_paraphrase", "adversarial_polarity_flip", "unrelated_novel"]
prompt: str
expected_intent: str
target_cache_id: str | None
embedding: np.ndarray[tuple[int], np.dtype[np.float64]]
tenant_id: str = "tenant-enterprise"
model: str = "gpt-4o"
class TenantScopedSemanticCache:
"""Namespace-isolated semantic cache keyed strictly by `(tenant_id, model)`."""
def __init__(self, entries: Sequence[SemanticCacheEntry] = ()) -> None:
self._buckets: dict[tuple[str, str], list[SemanticCacheEntry]] = {}
self._mats: dict[tuple[str, str], np.ndarray[Any, np.dtype[np.float64]]] = {}
for entry in entries:
self.add_entry(entry)
def add_entry(self, entry: SemanticCacheEntry) -> None:
key = (entry.tenant_id, entry.model)
self._buckets.setdefault(key, []).append(entry)
self._mats.pop(key, None)
def lookup(
self,
tenant_id: str,
model: str,
query_embedding: np.ndarray[tuple[int], np.dtype[np.float64]],
threshold_tau: float,
) -> tuple[SemanticCacheEntry | None, float]:
"""Search only entries scoped to `(tenant_id, model)` preventing cross-tenant leakage."""
key = (tenant_id, model)
bucket = self._buckets.get(key)
if not bucket:
return None, 0.0
mat = self._mats.get(key)
if mat is None:
mat = np.stack([e.embedding for e in bucket], axis=0)
self._mats[key] = mat
sims = mat @ query_embedding
best_idx = int(np.argmax(sims))
best_sim = float(sims[best_idx])
if best_sim >= threshold_tau:
return bucket[best_idx], best_sim
return None, best_sim
def _unit_vec_from_seed(tag: str, dim: int = 128) -> np.ndarray[tuple[int], np.dtype[np.float64]]:
digest = hashlib.blake2b(tag.encode("utf-8"), digest_size=16).digest()
seed_int = int.from_bytes(digest, "little")
rng = np.random.default_rng(seed_int)
vec = rng.normal(0.0, 1.0, size=dim)
norm = float(np.linalg.norm(vec))
return (vec / max(norm, 1e-12)).astype(np.float64)
def _blend_with_target_cosine(
base_vec: np.ndarray[tuple[int], np.dtype[np.float64]],
ortho_tag: str,
target_cosine: float,
) -> np.ndarray[tuple[int], np.dtype[np.float64]]:
"""Construct unit vector whose cosine similarity with `base_vec` equals `target_cosine`."""
raw = _unit_vec_from_seed(ortho_tag, dim=int(base_vec.shape[0]))
proj = raw - float(np.dot(raw, base_vec)) * base_vec
proj_norm = float(np.linalg.norm(proj))
ortho = proj / max(proj_norm, 1e-12)
sin_theta = float(np.sqrt(max(0.0, 1.0 - target_cosine**2)))
blended = target_cosine * base_vec + sin_theta * ortho
return (blended / float(np.linalg.norm(blended))).astype(np.float64)
def build_semantic_cache_benchmark_dataset(
seed: int = 42,
) -> tuple[list[SemanticCacheEntry], list[_EvalQuery]]:
"""Create 12 cached intents and 60 deterministic evaluation queries."""
rng = np.random.default_rng(seed)
base_specs = [
(
"card_cancel",
"Cancel my corporate credit card immediately",
"Card cancellation flow triggered.",
),
(
"mfa_reset",
"How do I reset my MFA authenticator token?",
"MFA reset link sent to verified device.",
),
(
"grant_prod",
"Grant read-only IAM access to prod analytics",
"Read-only prod IAM policy documented.",
),
(
"refund_order",
"Issue full refund for duplicate invoice #901",
"Duplicate invoice refund SOP returned.",
),
(
"wire_alpha",
"Wire USD 5000 settlement to vendor Alpha",
"Vendor Alpha wire approval checklist.",
),
(
"delete_cache",
"Purge stale Redis keys from session cluster",
"Redis flush scan pattern returned.",
),
(
"enable_sso",
"Enable SAML SSO enforcement for engineering",
"Okta SAML SSO rollout instructions.",
),
(
"rotate_keys",
"Rotate production service account API keys",
"Zero-downtime API key rotation guide.",
),
(
"pause_gpu",
"Pause idle A100 training node pool at night",
"GKE node pool scale-down script.",
),
(
"export_pii",
"Export anonymized GDPR audit report to GCS",
"GDPR export command with KMS check.",
),
(
"increase_tpm",
"Raise tenant TPM rate limit to 500k tokens",
"Enterprise TPM quota request form.",
),
(
"enable_tls",
"Enforce strict mTLS between gateway and pods",
"Envoy strict mTLS PeerAuthentication YAML.",
),
]
entries: list[SemanticCacheEntry] = []
for idx, (intent, prompt, resp) in enumerate(base_specs):
emb = _unit_vec_from_seed(f"cache-entry-{seed}-{idx}-{intent}")
entries.append(
SemanticCacheEntry(
cache_id=f"cache-{idx:02d}",
tenant_id="tenant-enterprise",
model="gpt-4o",
intent_label=intent,
canonical_prompt=prompt,
cached_response=resp,
embedding=emb,
)
)
queries: list[_EvalQuery] = []
# 30 positive paraphrases across tight [0.984..0.987], mid [0.946..0.975], loose [0.914..0.929]
pos_cosines = (
[float(rng.uniform(0.946, 0.975)) for _ in range(24)]
+ [0.984, 0.987]
+ [0.914, 0.922, 0.929, 0.952]
)
for idx, cos_val in enumerate(pos_cosines):
ent = entries[idx % len(entries)]
q_emb = _blend_with_target_cosine(ent.embedding, f"pos-{seed}-{idx}", cos_val)
queries.append(
_EvalQuery(
query_id=f"q-pos-{idx:02d}",
category="positive_paraphrase",
prompt=f"Paraphrase #{idx}: {ent.canonical_prompt}",
expected_intent=ent.intent_label,
target_cache_id=ent.cache_id,
embedding=q_emb,
)
)
# 18 adversarial polarity/entity flips that fool low thresholds (0.75, 0.85, 0.90)
# e.g. "Activate my corporate credit card" vs "Cancel my corporate credit card"
adv_templates = [
(0, "Activate my corporate credit card immediately", 0.885),
(1, "Disable MFA requirement on my account permanently", 0.872),
(2, "Grant full admin write access to prod analytics", 0.916),
(3, "Cancel customer refund for invoice #901", 0.864),
(4, "Wire USD 5000 settlement to vendor Beta instead", 0.908),
(5, "Persist Redis keys to cold archive without delete", 0.812),
(6, "Disable SAML SSO enforcement for engineering", 0.892),
(7, "Deactivate all production service account API keys", 0.878),
(8, "Scale up 8 additional A100 nodes immediately", 0.794),
(9, "Export raw unmasked PII customer records publicly", 0.848),
(10, "Throttle tenant TPM rate limit down to 10k tokens", 0.861),
(11, "Disable TLS verification between gateway and pods", 0.911),
(0, "Freeze corporate credit card dispute chargeback", 0.778),
(2, "Revoke all IAM access from analytics service", 0.856),
(4, "Cancel wire transfer to vendor Alpha now", 0.889),
(6, "Bypass SSO login using emergency local password", 0.835),
(7, "Expose legacy API key in plaintext debug endpoint", 0.768),
(11, "Downgrade gateway listener to unencrypted HTTP", 0.842),
]
for idx, (entry_idx, adv_prompt, cos_val) in enumerate(adv_templates):
ent = entries[entry_idx]
q_emb = _blend_with_target_cosine(ent.embedding, f"adv-{seed}-{idx}", cos_val)
queries.append(
_EvalQuery(
query_id=f"q-adv-{idx:02d}",
category="adversarial_polarity_flip",
prompt=adv_prompt,
expected_intent=f"NOT_{ent.intent_label}",
target_cache_id=ent.cache_id,
embedding=q_emb,
)
)
# 12 unrelated novel queries (< 0.65 cosine)
for idx in range(12):
nov_emb = _unit_vec_from_seed(f"novel-unrelated-{seed}-{idx}")
queries.append(
_EvalQuery(
query_id=f"q-nov-{idx:02d}",
category="unrelated_novel",
prompt=f"Unrelated domain question #{idx}: Explain Triton autotuning config.",
expected_intent=f"novel_{idx}",
target_cache_id=None,
embedding=nov_emb,
)
)
return entries, queries
def run_semantic_cache_threshold_sweep(
seed: int = 42,
config: SemanticCacheSweepConfig | None = None,
) -> dict[str, Any]:
"""Sweep cosine thresholds `tau` to quantify true savings vs false-positive collisions."""
cfg = config or SemanticCacheSweepConfig()
entries, queries = build_semantic_cache_benchmark_dataset(seed=seed)
cache = TenantScopedSemanticCache(entries)
n_total = len(queries)
n_pos = sum(1 for q in queries if q.category == "positive_paraphrase")
n_neg = n_total - n_pos
sweep_rows: list[dict[str, Any]] = []
for tau in cfg.thresholds:
true_hits = 0
fp_collisions = 0
false_negatives = 0
true_misses = 0
for q in queries:
matched, _best_sim = cache.lookup(q.tenant_id, q.model, q.embedding, threshold_tau=tau)
if matched is not None:
if q.category == "positive_paraphrase" and matched.intent_label == q.expected_intent:
true_hits += 1
else:
fp_collisions += 1
else:
if q.category == "positive_paraphrase":
false_negatives += 1
else:
true_misses += 1
total_hits = true_hits + fp_collisions
hit_rate_pct = round((total_hits / n_total) * 100.0, 2)
true_recall_pct = round((true_hits / max(1, n_pos)) * 100.0, 2)
fp_on_hits_pct = round((fp_collisions / max(1, total_hits)) * 100.0, 2) if total_hits else 0.0
fp_on_neg_pct = round((fp_collisions / max(1, n_neg)) * 100.0, 2)
precision_pct = round((true_hits / max(1, total_hits)) * 100.0, 2) if total_hits else 100.0
safe_usd_saved = round(true_hits * cfg.upstream_call_usd, 4)
latency_saved_ms = round(true_hits * (cfg.upstream_latency_ms - cfg.cache_lookup_ms), 1)
collision_risk_penalty_usd = round(fp_collisions * 0.25, 4)
net_utility_usd = round(safe_usd_saved - collision_risk_penalty_usd, 4)
sweep_rows.append(
{
"threshold_tau": tau,
"true_hits": true_hits,
"false_positive_collisions": fp_collisions,
"false_negatives": false_negatives,
"true_misses": true_misses,
"raw_hit_rate_pct": hit_rate_pct,
"true_hit_recall_pct": true_recall_pct,
"precision_pct": precision_pct,
"false_positive_collision_rate_pct": fp_on_hits_pct,
"adversarial_collision_rate_pct": fp_on_neg_pct,
"safe_usd_saved": safe_usd_saved,
"latency_saved_ms": latency_saved_ms,
"net_utility_usd": net_utility_usd,
}
)
zero_fp_rows = [row for row in sweep_rows if row["false_positive_collisions"] == 0]
optimal = max(
zero_fp_rows if zero_fp_rows else sweep_rows,
key=lambda r: (float(r["safe_usd_saved"]), -float(r["threshold_tau"])),
)
return {
"seed": seed,
"dataset_summary": {
"cached_intents": len(entries),
"total_queries": n_total,
"positive_paraphrases": n_pos,
"adversarial_polarity_flips": sum(
1 for q in queries if q.category == "adversarial_polarity_flip"
),
"unrelated_novel": sum(1 for q in queries if q.category == "unrelated_novel"),
},
"sweep": sweep_rows,
"optimal_operating_point": optimal,
}
"""Live FastAPI AI Gateway: TPM/USD Budget, Priority Queue, PII Vault & Protocol Translation."""
from __future__ import annotations
import argparse
import hashlib
import ipaddress
import json
import math
import re
import threading
from collections.abc import Sequence
from dataclasses import dataclass, field
from typing import Any, Literal
from fastapi import BackgroundTasks, FastAPI, Header, HTTPException, Request, Response, status
from fastapi.responses import JSONResponse
from fastapi.testclient import TestClient
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from pydantic import BaseModel, ConfigDict, Field
from ai_gateway_routing_lab.resilience_and_routing import (
BoundedInMemorySpanExporter,
create_in_memory_telemetry,
summarize_finished_spans,
)
# ---------------------------------------------------------------------------
# 1. Pydantic v2 Strict Schemas & Protocol Translators (OpenAI <-> Bedrock/Vertex)
# ---------------------------------------------------------------------------
class ChatMessage(BaseModel):
model_config = ConfigDict(extra="forbid")
role: Literal["system", "user", "assistant"]
content: str = Field(min_length=1)
class OpenAIChatRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model: str = Field(min_length=2)
messages: list[ChatMessage] = Field(min_length=1)
max_tokens: int = Field(default=512, ge=1, le=128_000)
temperature: float = Field(default=0.2, ge=0.0, le=2.0)
user_id: str = Field(default="anon-user", min_length=1)
priority: Literal["interactive", "batch"] = "interactive"
def estimate_token_count(text: str) -> int:
"""Deterministic subword-like token estimator (~4 chars/token, min 1)."""
return max(1, math.ceil(len(text) / 4.0))
def translate_openai_to_bedrock(payload: OpenAIChatRequest) -> dict[str, Any]:
"""Translate canonical OpenAI ChatCompletions payload to AWS Bedrock Converse schema."""
system_blocks: list[dict[str, str]] = []
converse_msgs: list[dict[str, Any]] = []
for msg in payload.messages:
if msg.role == "system":
system_blocks.append({"text": msg.content})
else:
converse_msgs.append({"role": msg.role, "content": [{"text": msg.content}]})
if not converse_msgs:
converse_msgs.append({"role": "user", "content": [{"text": "Proceed."}]})
out: dict[str, Any] = {
"modelId": payload.model,
"messages": converse_msgs,
"inferenceConfig": {
"maxTokens": payload.max_tokens,
"temperature": payload.temperature,
},
}
if system_blocks:
out["system"] = system_blocks
return out
def translate_bedrock_to_openai(
bedrock_resp: dict[str, Any],
model: str,
req_id: str,
) -> dict[str, Any]:
"""Translate AWS Bedrock Converse response back into canonical OpenAI ChatCompletions JSON."""
text = str(bedrock_resp["output"]["message"]["content"][0]["text"])
usage = bedrock_resp["usage"]
in_tok = int(usage["inputTokens"])
out_tok = int(usage["outputTokens"])
return {
"id": req_id,
"object": "chat.completion",
"model": model,
"provider": "aws-bedrock",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": text},
"finish_reason": str(bedrock_resp.get("stopReason", "end_turn")),
}
],
"usage": {
"prompt_tokens": in_tok,
"completion_tokens": out_tok,
"total_tokens": in_tok + out_tok,
},
}
def translate_openai_to_vertex(payload: OpenAIChatRequest) -> dict[str, Any]:
"""Translate canonical OpenAI ChatCompletions payload to Google Vertex AI generateContent schema."""
sys_parts: list[dict[str, str]] = []
contents: list[dict[str, Any]] = []
for msg in payload.messages:
if msg.role == "system":
sys_parts.append({"text": msg.content})
else:
v_role = "model" if msg.role == "assistant" else "user"
contents.append({"role": v_role, "parts": [{"text": msg.content}]})
if not contents:
contents.append({"role": "user", "parts": [{"text": "Proceed."}]})
out: dict[str, Any] = {
"contents": contents,
"generationConfig": {
"maxOutputTokens": payload.max_tokens,
"temperature": payload.temperature,
},
}
if sys_parts:
out["systemInstruction"] = {"parts": sys_parts}
return out
def translate_vertex_to_openai(
vertex_resp: dict[str, Any],
model: str,
req_id: str,
) -> dict[str, Any]:
"""Translate Google Vertex AI generateContent response into canonical OpenAI ChatCompletions JSON."""
cand = vertex_resp["candidates"][0]
text = str(cand["content"]["parts"][0]["text"])
meta = vertex_resp["usageMetadata"]
in_tok = int(meta["promptTokenCount"])
out_tok = int(meta["candidatesTokenCount"])
return {
"id": req_id,
"object": "chat.completion",
"model": model,
"provider": "gcp-vertex",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": text},
"finish_reason": str(cand.get("finishReason", "STOP")),
}
],
"usage": {
"prompt_tokens": in_tok,
"completion_tokens": out_tok,
"total_tokens": in_tok + out_tok,
},
}
# ---------------------------------------------------------------------------
# 2. Reversible PII Masking & Rehydration Vault (Request-Scoped Ephemeral)
# ---------------------------------------------------------------------------
def is_valid_luhn(card_number: str) -> bool:
"""Validate ISO/IEC 7812 payment card numbers using the Luhn mod-10 checksum."""
digits_only = re.sub(r"[-\s]", "", card_number)
if not digits_only.isdigit() or not (13 <= len(digits_only) <= 19):
return False
total = 0
for idx, ch in enumerate(reversed(digits_only)):
val = int(ch)
if idx % 2 == 1:
val *= 2
if val > 9:
val -= 9
total += val
return total % 10 == 0
class PiiVault:
"""Stateful request-scoped reversible PII redactor with Luhn card validation."""
_EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b")
_CARD_RE = re.compile(
r"(?<!\+)(?<!\d)(?:"
r"\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{1,4}"
r"|\d{4}[-\s]?\d{6}[-\s]?\d{5}"
r"|[3456]\d{12,18}"
r")(?!\d)"
)
_PHONE_RE = re.compile(
r"(?:"
r"(?<!\w)\+\d{7,15}\b"
r"|(?<!\w)\+\d{1,3}(?:[-\s]?\(?\d{2,4}\)?){2,4}\b"
r"|(?<!\w)\(\d{3}\)[-\s]?\d{3}[-\s]?\d{4}\b"
r"|\b\d{3}[-\s]\d{3}[-\s]\d{3,4}\b"
r")"
)
def __init__(self) -> None:
self.vault: dict[str, str] = {}
self._reverse_lookup: dict[str, str] = {}
self._counters: dict[str, int] = {"EMAIL": 0, "CARD": 0, "PHONE": 0}
def redact_text(self, text: str) -> str:
"""Redact PII spans in `text` while preserving counters/tokens across messages."""
def _replace(kind: str, pattern: re.Pattern[str], source: str) -> str:
def _sub(match: re.Match[str]) -> str:
raw = match.group(0)
if kind == "CARD" and not is_valid_luhn(raw):
return raw
if raw in self._reverse_lookup:
return self._reverse_lookup[raw]
self._counters[kind] += 1
token = f"[PII_{kind}_{self._counters[kind]}]"
self.vault[token] = raw
self._reverse_lookup[raw] = token
return token
return pattern.sub(_sub, source)
masked = _replace("EMAIL", self._EMAIL_RE, text)
masked = _replace("CARD", self._CARD_RE, masked)
masked = _replace("PHONE", self._PHONE_RE, masked)
return masked
@classmethod
def redact(cls, text: str) -> tuple[str, dict[str, str]]:
"""Replace PII spans in a single string and return `(masked_text, vault_map)`."""
instance = cls()
masked = instance.redact_text(text)
return masked, dict(instance.vault)
@classmethod
def redact_messages(
cls, messages: Sequence[ChatMessage]
) -> tuple[list[ChatMessage], dict[str, str]]:
"""Redact PII across all `messages` with ONE stateful vault preventing collisions."""
instance = cls()
masked_messages = [
ChatMessage(role=m.role, content=instance.redact_text(m.content)) for m in messages
]
return masked_messages, dict(instance.vault)
@staticmethod
def rehydrate(text: str, vault: dict[str, str]) -> str:
"""Restore original PII values into the returned LLM response using `vault`."""
restored = text
for token, raw in vault.items():
restored = restored.replace(token, raw)
return restored
# ---------------------------------------------------------------------------
# 3. Deterministic Token-Bucket Rate Limiter, Budget & W3C Traceparent
# ---------------------------------------------------------------------------
class TokenBucket:
"""Deterministic leaky/token bucket driven by simulated `clock_ms` (zero wall-clock sleep)."""
def __init__(self, capacity: float, refill_per_ms: float, initial: float | None = None) -> None:
self.capacity = float(capacity)
self.refill_per_ms = float(refill_per_ms)
self.tokens = float(capacity if initial is None else initial)
self.last_clock_ms = 0.0
def _refill(self, clock_ms: float) -> None:
if clock_ms > self.last_clock_ms:
elapsed = clock_ms - self.last_clock_ms
self.tokens = min(self.capacity, self.tokens + elapsed * self.refill_per_ms)
self.last_clock_ms = clock_ms
def try_consume(self, amount: float, clock_ms: float) -> tuple[bool, float]:
"""Attempt to consume `amount` tokens; returns `(allowed, retry_after_sec)`."""
self._refill(clock_ms)
if self.tokens >= amount:
self.tokens -= amount
return True, 0.0
deficit = amount - self.tokens
retry_ms = deficit / max(self.refill_per_ms, 1e-6)
return False, max(1.0, round(retry_ms / 1000.0, 2))
def refund(self, amount: float) -> None:
"""Post-flight reconciliation returning unused reserved completion tokens."""
if amount > 0.0:
self.tokens = min(self.capacity, self.tokens + amount)
@dataclass
class TenantPolicy:
tenant_id: str
api_key: str
allowed_models: tuple[str, ...]
allowed_cidrs: tuple[str, ...]
blocked_countries: tuple[str, ...]
rpm_limit: int
tpm_limit: int
usd_budget: float
usd_spent: float = 0.0
rpm_bucket: TokenBucket = field(init=False)
tpm_bucket: TokenBucket = field(init=False)
def __post_init__(self) -> None:
self.rpm_bucket = TokenBucket(
capacity=float(self.rpm_limit), refill_per_ms=self.rpm_limit / 60_000.0
)
self.tpm_bucket = TokenBucket(
capacity=float(self.tpm_limit), refill_per_ms=self.tpm_limit / 60_000.0
)
_TRACEPARENT_RE = re.compile(r"^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$")
def parse_or_create_traceparent(header_val: str | None, seq: int) -> tuple[str, str, str]:
"""Parse W3C `traceparent` or create deterministic `(trace_id, gw_header, up_header)`."""
if header_val:
m = _TRACEPARENT_RE.match(header_val.strip().lower())
if m and m.group(1) != "0" * 32 and m.group(2) != "0" * 16:
trace_id = m.group(1)
flags = m.group(3)
gw_id = hashlib.blake2b(f"{trace_id}-gw-{seq}".encode(), digest_size=8).hexdigest()
up_id = hashlib.blake2b(f"{trace_id}-up-{seq}".encode(), digest_size=8).hexdigest()
return trace_id, f"00-{trace_id}-{gw_id}-{flags}", f"00-{trace_id}-{up_id}-{flags}"
trace_id = hashlib.blake2b(f"fsds-wb18-trace-{seq}".encode(), digest_size=16).hexdigest()
gw_id = hashlib.blake2b(f"fsds-wb18-gw-{seq}".encode(), digest_size=8).hexdigest()
up_id = hashlib.blake2b(f"fsds-wb18-up-{seq}".encode(), digest_size=8).hexdigest()
return trace_id, f"00-{trace_id}-{gw_id}-01", f"00-{trace_id}-{up_id}-01"
def assign_ab_bucket(user_id: str, variant_b_pct: int = 20) -> Literal["variant_a", "variant_b"]:
"""Deterministic sticky A/B traffic splitting via blake2b hash mod 100."""
digest = hashlib.blake2b(user_id.encode("utf-8"), digest_size=4).digest()
bucket = int.from_bytes(digest, "little") % 100
return "variant_b" if bucket < variant_b_pct else "variant_a"
# ---------------------------------------------------------------------------
# 4. Gateway State & Simulated Upstream Adapters
# ---------------------------------------------------------------------------
@dataclass
class GatewayState:
tenants_by_key: dict[str, TenantPolicy]
tracer: trace.Tracer
exporter: BoundedInMemorySpanExporter
provider: TracerProvider
cluster_tpm_bucket: TokenBucket
interactive_reserve_tokens: float = 12_000.0
usd_per_1k_tokens: float = 0.005
allow_test_clock: bool = False
server_clock_ms: float = 0.0
simulate_upstream_error_next: bool = False
lock: threading.Lock = field(default_factory=threading.Lock)
request_seq: int = 0
total_requests: int = 0
blocked_403_count: int = 0
throttled_429_count: int = 0
pii_redacted_entities_total: int = 0
ab_counts: dict[str, int] = field(default_factory=lambda: {"variant_a": 0, "variant_b": 0})
shadow_mirrored_count: int = 0
shadow_log: list[dict[str, Any]] = field(default_factory=list)
provider_translation_counts: dict[str, int] = field(
default_factory=lambda: {"openai": 0, "aws-bedrock": 0, "gcp-vertex": 0}
)
audit_log: list[dict[str, Any]] = field(default_factory=list)
def _default_gateway_state() -> GatewayState:
provider, exporter, tracer = create_in_memory_telemetry("fsds-wb18-ai-gateway-service")
tenants = [
TenantPolicy(
tenant_id="tenant-alpha",
api_key="sk-gw-alpha-001",
allowed_models=("gpt-4o", "claude-3-7-sonnet", "gemini-2.5-flash"),
allowed_cidrs=("10.0.0.0/8", "192.168.0.0/16", "127.0.0.1/32"),
blocked_countries=("KP", "XX"),
rpm_limit=60,
tpm_limit=40_000,
usd_budget=0.50,
),
TenantPolicy(
tenant_id="tenant-interactive",
api_key="sk-gw-interactive-002",
allowed_models=("gpt-4o", "claude-3-7-sonnet", "gemini-2.5-flash"),
allowed_cidrs=("10.0.0.0/8", "127.0.0.1/32"),
blocked_countries=("KP", "XX"),
rpm_limit=60,
tpm_limit=80_000,
usd_budget=2.00,
),
]
return GatewayState(
tenants_by_key={t.api_key: t for t in tenants},
tracer=tracer,
exporter=exporter,
provider=provider,
cluster_tpm_bucket=TokenBucket(capacity=50_000.0, refill_per_ms=50_000.0 / 60_000.0),
)
def _invoke_simulated_provider(
provider_name: Literal["openai", "aws-bedrock", "gcp-vertex"],
translated_req: dict[str, Any],
model: str,
req_id: str,
prompt_tokens: int,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""Simulate upstream OpenAI / AWS Bedrock / GCP Vertex provider on masked payloads only."""
if provider_name == "aws-bedrock":
last_text = str(translated_req["messages"][-1]["content"][0]["text"])
preview = last_text[:120]
raw_resp = {
"output": {
"message": {
"role": "assistant",
"content": [{"text": f"[Bedrock:{model}] Verified masked inquiry: {preview}"}],
}
},
"stopReason": "end_turn",
"usage": {"inputTokens": prompt_tokens, "outputTokens": 28},
}
return raw_resp, translate_bedrock_to_openai(raw_resp, model=model, req_id=req_id)
if provider_name == "gcp-vertex":
last_text = str(translated_req["contents"][-1]["parts"][0]["text"])
preview = last_text[:120]
vertex_raw_resp: dict[str, Any] = {
"candidates": [
{
"content": {
"role": "model",
"parts": [{"text": f"[Vertex:{model}] Processed masked: {preview}"}],
},
"finishReason": "STOP",
}
],
"usageMetadata": {
"promptTokenCount": prompt_tokens,
"candidatesTokenCount": 24,
"totalTokenCount": prompt_tokens + 24,
},
}
return vertex_raw_resp, translate_vertex_to_openai(
vertex_raw_resp, model=model, req_id=req_id
)
last_text = str(translated_req["messages"][-1]["content"])
preview = last_text[:120]
openai_resp = {
"id": req_id,
"object": "chat.completion",
"model": model,
"provider": "openai",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": f"[OpenAI:{model}] Completed masked request: {preview}",
},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": prompt_tokens,
"completion_tokens": 30,
"total_tokens": prompt_tokens + 30,
},
}
return openai_resp, openai_resp
def _ip_allowed(client_ip: str, cidrs: tuple[str, ...]) -> bool:
try:
addr = ipaddress.ip_address(client_ip.strip())
except ValueError:
return False
return any(addr in ipaddress.ip_network(cidr, strict=False) for cidr in cidrs)
def _select_provider(
model: str, explicit_header: str | None
) -> Literal["openai", "aws-bedrock", "gcp-vertex"]:
if explicit_header == "openai":
return "openai"
if explicit_header == "aws-bedrock":
return "aws-bedrock"
if explicit_header == "gcp-vertex":
return "gcp-vertex"
lower = model.lower()
if "claude" in lower or "bedrock" in lower:
return "aws-bedrock"
if "gemini" in lower or "vertex" in lower:
return "gcp-vertex"
return "openai"
# ---------------------------------------------------------------------------
# 5. Live FastAPI Application Factory
# ---------------------------------------------------------------------------
def _dispatch_shadow_mirror(
gw: GatewayState,
provider_name: Literal["openai", "aws-bedrock", "gcp-vertex"],
translated_req: dict[str, Any],
shadow_model: str,
req_id: str,
upstream_traceparent: str,
prompt_tokens: int,
) -> None:
"""Execute non-blocking shadow canary mirroring inside FastAPI BackgroundTasks."""
with gw.tracer.start_as_current_span("gateway.shadow_mirror") as sh_span:
sh_span.set_attribute("shadow.target_model", shadow_model)
sh_span.set_attribute("shadow.non_blocking", True)
sh_span.set_attribute("shadow.background_task", True)
sh_span.set_attribute("upstream.traceparent", upstream_traceparent)
_raw_s, _canon_s = _invoke_simulated_provider(
provider_name=provider_name,
translated_req=translated_req,
model=shadow_model,
req_id=f"{req_id}-shadow",
prompt_tokens=prompt_tokens,
)
with gw.lock:
gw.shadow_mirrored_count += 1
gw.shadow_log.append(
{
"req_id": req_id,
"shadow_model": shadow_model,
"provider": provider_name,
"traceparent": upstream_traceparent,
"status": "mirrored_async",
}
)
def create_gateway_app(
state: GatewayState | None = None,
*,
allow_test_clock: bool | None = None,
) -> FastAPI:
"""Create the live FastAPI AI Gateway application with full pipeline observability."""
gw = state or _default_gateway_state()
if allow_test_clock is not None:
gw.allow_test_clock = allow_test_clock
app = FastAPI(title="FSDS-SOTA-2026 AI Gateway (WB-Ch18)", version="0.1.0")
app.state.gateway = gw
app.state.allow_test_clock = gw.allow_test_clock
@app.get("/health")
def health() -> dict[str, Any]:
with gw.lock:
return {
"status": "ok",
"total_requests": gw.total_requests,
"throttled_429": gw.throttled_429_count,
"blocked_403": gw.blocked_403_count,
}
@app.get("/v1/gateway/metrics")
def gateway_metrics() -> dict[str, Any]:
with gw.lock:
return {
"total_requests": gw.total_requests,
"blocked_403_count": gw.blocked_403_count,
"throttled_429_count": gw.throttled_429_count,
"pii_redacted_entities_total": gw.pii_redacted_entities_total,
"ab_counts": dict(gw.ab_counts),
"shadow_mirrored_count": gw.shadow_mirrored_count,
"shadow_log_count": len(gw.shadow_log),
"provider_translation_counts": dict(gw.provider_translation_counts),
"cluster_tpm_remaining": round(gw.cluster_tpm_bucket.tokens, 2),
"tenants": {
t.tenant_id: {
"rpm_remaining": round(t.rpm_bucket.tokens, 2),
"tpm_remaining": round(t.tpm_bucket.tokens, 2),
"usd_spent": round(t.usd_spent, 6),
"usd_budget": t.usd_budget,
}
for t in gw.tenants_by_key.values()
},
}
@app.post("/v1/chat/completions")
def chat_completions(
payload: OpenAIChatRequest,
request: Request,
response: Response,
background_tasks: BackgroundTasks,
authorization: str | None = Header(default=None),
x_forwarded_for: str | None = Header(default="10.0.1.25"),
x_geo_country: str | None = Header(default="VN"),
x_rate_policy: str | None = Header(default="tpm_dual_budget"),
x_target_provider: str | None = Header(default=None),
x_shadow_mirror: str | None = Header(default="false"),
x_sim_clock_ms: float = Header(default=0.0),
traceparent: str | None = Header(default=None),
) -> JSONResponse:
with gw.lock:
gw.request_seq += 1
gw.total_requests += 1
seq_now = gw.request_seq
req_id = f"chatcmpl-wb18-{seq_now:04d}"
trace_id, gw_tp, up_tp = parse_or_create_traceparent(traceparent, seq_now)
# Gate simulated clock injection behind explicit app.state.allow_test_clock flag
allow_clock = bool(getattr(request.app.state, "allow_test_clock", False))
effective_clock_ms = max(0.0, float(x_sim_clock_ms)) if allow_clock else gw.server_clock_ms
with gw.tracer.start_as_current_span("gateway.request") as root_span:
root_span.set_attribute("gateway.req_id", req_id)
root_span.set_attribute("w3c.trace_id", trace_id)
root_span.set_attribute("gateway.priority", payload.priority)
# Stage 1: AuthN / AuthZ / IP Allowlist / Geo-Fence
with gw.tracer.start_as_current_span("gateway.security_auth") as sec_span:
token = (authorization or "").removeprefix("Bearer ").strip()
tenant = gw.tenants_by_key.get(token)
if tenant is None:
with gw.lock:
gw.blocked_403_count += 1
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="INVALID_API_KEY",
)
if payload.model not in tenant.allowed_models:
with gw.lock:
gw.blocked_403_count += 1
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="MODEL_NOT_AUTHORIZED",
)
client_ip = (x_forwarded_for or "").split(",")[0].strip()
if not _ip_allowed(client_ip, tenant.allowed_cidrs):
with gw.lock:
gw.blocked_403_count += 1
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="IP_NOT_ALLOWLISTED",
)
geo_code = (x_geo_country or "US").strip().upper()
if geo_code in tenant.blocked_countries:
with gw.lock:
gw.blocked_403_count += 1
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="GEO_FENCE_BLOCKED",
)
residency = "eu-west" if geo_code in ("DE", "FR", "NL") else "global"
sec_span.set_attribute("tenant.id", tenant.tenant_id)
sec_span.set_attribute("geo.residency", residency)
# Stage 2: Single stateful PiiVault across all messages in request
with gw.tracer.start_as_current_span("gateway.pii_redact") as pii_span:
masked_messages, merged_vault = PiiVault.redact_messages(payload.messages)
pii_count = len(merged_vault)
with gw.lock:
gw.pii_redacted_entities_total += pii_count
pii_span.set_attribute("pii.redacted_entities", pii_count)
masked_payload = OpenAIChatRequest(
model=payload.model,
messages=masked_messages,
max_tokens=payload.max_tokens,
temperature=payload.temperature,
user_id=payload.user_id,
priority=payload.priority,
)
# Stage 3: Financial & Token Control (`rpm_only` trap vs `tpm_dual_budget` + Priority)
prompt_tokens = sum(estimate_token_count(m.content) for m in masked_messages)
reserved_tokens = prompt_tokens + payload.max_tokens
est_cost_usd = (reserved_tokens / 1000.0) * gw.usd_per_1k_tokens
policy_mode = (x_rate_policy or "tpm_dual_budget").strip().lower()
tenant_tpm_consumed = False
cluster_tpm_consumed = False
with gw.tracer.start_as_current_span("gateway.rate_limit_and_budget") as rl_span:
rl_span.set_attribute("rate_policy.mode", policy_mode)
rl_span.set_attribute("tokens.prompt", prompt_tokens)
rl_span.set_attribute("tokens.reserved", reserved_tokens)
with gw.lock:
rpm_ok, rpm_retry = tenant.rpm_bucket.try_consume(1.0, effective_clock_ms)
if not rpm_ok:
gw.throttled_429_count += 1
return JSONResponse(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
content={"detail": "RPM_LIMIT_EXCEEDED", "policy": policy_mode},
headers={"Retry-After": str(math.ceil(rpm_retry))},
)
if policy_mode == "tpm_dual_budget":
# Protect interactive traffic by gating batch when cluster TPM drops to reserve
if payload.priority == "batch" and (
gw.cluster_tpm_bucket.tokens - reserved_tokens
< gw.interactive_reserve_tokens
):
gw.throttled_429_count += 1
return JSONResponse(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
content={
"detail": "CLUSTER_BATCH_SHEDDING_PROTECTING_INTERACTIVE",
"policy": policy_mode,
},
headers={"Retry-After": "12"},
)
tpm_ok, tpm_retry = tenant.tpm_bucket.try_consume(
float(reserved_tokens), effective_clock_ms
)
if not tpm_ok:
gw.throttled_429_count += 1
return JSONResponse(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
content={
"detail": "TPM_TOKEN_BUCKET_EXCEEDED",
"prompt_tokens": prompt_tokens,
"remaining_tpm": round(tenant.tpm_bucket.tokens, 1),
},
headers={
"Retry-After": str(math.ceil(tpm_retry)),
"X-RateLimit-Remaining-Tokens": str(
int(tenant.tpm_bucket.tokens)
),
},
)
tenant_tpm_consumed = True
if tenant.usd_spent + est_cost_usd > tenant.usd_budget:
tenant.tpm_bucket.refund(float(reserved_tokens))
tenant_tpm_consumed = False
gw.throttled_429_count += 1
rem_usd = max(0.0, tenant.usd_budget - tenant.usd_spent)
return JSONResponse(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
content={
"detail": "TENANT_USD_BUDGET_EXCEEDED",
"usd_spent": round(tenant.usd_spent, 4),
"usd_budget": tenant.usd_budget,
},
headers={
"Retry-After": "60",
"X-Budget-Remaining-USD": f"{rem_usd:.4f}",
},
)
cluster_ok, cluster_retry = gw.cluster_tpm_bucket.try_consume(
float(reserved_tokens), effective_clock_ms
)
if not cluster_ok:
tenant.tpm_bucket.refund(float(reserved_tokens))
tenant_tpm_consumed = False
gw.throttled_429_count += 1
return JSONResponse(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
content={
"detail": "CLUSTER_TPM_CAPACITY_EXCEEDED",
"policy": policy_mode,
"remaining_cluster_tpm": round(gw.cluster_tpm_bucket.tokens, 1),
},
headers={"Retry-After": str(math.ceil(cluster_retry))},
)
cluster_tpm_consumed = True
# Stage 4: A/B Bucketing, Protocol Translation & Simulated Upstream Call with try/finally
ab_group = assign_ab_bucket(payload.user_id, variant_b_pct=20)
target_provider = _select_provider(payload.model, x_target_provider)
with gw.lock:
gw.ab_counts[ab_group] += 1
gw.provider_translation_counts[target_provider] += 1
raw_upstream_resp: dict[str, Any] | None = None
canonical_resp: dict[str, Any] | None = None
translated_req: dict[str, Any] = {}
actual_cost = 0.0
tenant_spent_snapshot = 0.0
remaining_tokens_snapshot = 0
try:
with gw.tracer.start_as_current_span("gateway.protocol_translate_and_route") as rt_span:
if target_provider == "aws-bedrock":
translated_req = translate_openai_to_bedrock(masked_payload)
elif target_provider == "gcp-vertex":
translated_req = translate_openai_to_vertex(masked_payload)
else:
translated_req = masked_payload.model_dump()
with gw.lock:
should_fail = gw.simulate_upstream_error_next
if should_fail:
gw.simulate_upstream_error_next = False
if should_fail:
raise RuntimeError("SIMULATED_UPSTREAM_FAILURE")
raw_upstream_resp, canonical_resp = _invoke_simulated_provider(
provider_name=target_provider,
translated_req=translated_req,
model=payload.model,
req_id=req_id,
prompt_tokens=prompt_tokens,
)
rt_span.set_attribute("upstream.provider", target_provider)
rt_span.set_attribute("ab.bucket", ab_group)
rt_span.set_attribute("upstream.traceparent", up_tp)
finally:
# Post-flight token & USD reconciliation guaranteed even on upstream exceptions
actual_total_tokens = (
int(canonical_resp["usage"]["total_tokens"])
if canonical_resp is not None
else 0
)
unused_tokens = max(0, reserved_tokens - actual_total_tokens)
actual_cost = (actual_total_tokens / 1000.0) * gw.usd_per_1k_tokens
with gw.lock:
if policy_mode == "tpm_dual_budget":
if tenant_tpm_consumed:
tenant.tpm_bucket.refund(float(unused_tokens))
if cluster_tpm_consumed:
gw.cluster_tpm_bucket.refund(float(unused_tokens))
if canonical_resp is not None:
tenant.usd_spent += actual_cost
tenant_spent_snapshot = tenant.usd_spent
remaining_tokens_snapshot = int(tenant.tpm_bucket.tokens)
assert canonical_resp is not None and raw_upstream_resp is not None
# Stage 5: Asynchronous Non-Blocking Shadow Traffic Mirroring via FastAPI BackgroundTasks
shadow_triggered = (x_shadow_mirror or "").strip().lower() == "true"
if shadow_triggered:
background_tasks.add_task(
_dispatch_shadow_mirror,
gw,
target_provider,
translated_req,
f"{payload.model}-canary",
req_id,
up_tp,
prompt_tokens,
)
# Stage 6: Reversible PII Rehydration
with gw.tracer.start_as_current_span("gateway.pii_rehydrate") as reh_span:
upstream_content = str(canonical_resp["choices"][0]["message"]["content"])
rehydrated_content = PiiVault.rehydrate(upstream_content, merged_vault)
canonical_resp["choices"][0]["message"]["content"] = rehydrated_content
reh_span.set_attribute("pii.rehydrated", pii_count > 0)
canonical_resp["gateway_meta"] = {
"tenant_id": tenant.tenant_id,
"policy_mode": policy_mode,
"priority": payload.priority,
"residency": residency,
"ab_bucket": ab_group,
"shadow_mirrored": shadow_triggered,
"trace_id": trace_id,
"traceparent_gateway": gw_tp,
"traceparent_upstream": up_tp,
"pii_redacted_count": pii_count,
"upstream_saw_masked_payload": translated_req,
"upstream_raw_response_keys": sorted(raw_upstream_resp.keys()),
"actual_cost_usd": round(actual_cost, 6),
"tenant_usd_spent": round(tenant_spent_snapshot, 6),
}
with gw.lock:
gw.audit_log.append(
{
"req_id": req_id,
"provider": target_provider,
"trace_id": trace_id,
"ab_bucket": ab_group,
"pii_redacted_count": pii_count,
}
)
resp_headers = {
"traceparent": gw_tp,
"X-Traceparent-Upstream": up_tp,
"X-RateLimit-Remaining-Tokens": str(remaining_tokens_snapshot),
"X-Budget-Remaining-USD": f"{max(0.0, tenant.usd_budget - tenant_spent_snapshot):.4f}",
}
_ = response
return JSONResponse(
status_code=status.HTTP_200_OK, content=canonical_resp, headers=resp_headers
)
return app
# ---------------------------------------------------------------------------
# 6. End-to-End FastAPI Gateway Verification & Comparison Experiment (Exp 3)
# ---------------------------------------------------------------------------
def run_gateway_service_experiment(seed: int = 42) -> dict[str, Any]:
"""Drive live FastAPI AI Gateway via TestClient for Exp 3 benchmarks."""
_ = seed
# Sub-experiment A: RPM=60 trap (allows whale 64k payload) vs TPM Dual Bucket + Priority
rpm_app = create_gateway_app(allow_test_clock=True)
rpm_client = TestClient(rpm_app)
whale_64k_prompt = "whale payload token " * 12_800 # 256,000 chars -> 64,000 tokens!
rpm_whale_statuses: list[int] = []
for idx in range(3):
r = rpm_client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-alpha-001",
"X-Rate-Policy": "rpm_only",
"X-Sim-Clock-Ms": str(idx * 100.0),
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": whale_64k_prompt}],
"max_tokens": 512,
"user_id": f"whale-{idx}",
"priority": "batch",
},
)
rpm_whale_statuses.append(r.status_code)
rpm_metrics = rpm_client.get("/v1/gateway/metrics").json()
rpm_alpha_spent = float(rpm_metrics["tenants"]["tenant-alpha"]["usd_spent"])
# Sub-experiment B: Full SOTA AI Gateway (TPM + Budget + Priority + PII + W3C + A/B/Shadow)
sota_app = create_gateway_app(allow_test_clock=True)
sota_client = TestClient(sota_app)
# 1) Whale 64k batch payload blocked immediately by TPM Dual Bucket (HTTP 429 + Retry-After)
whale_blocked_resp = sota_client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-alpha-001",
"X-Rate-Policy": "tpm_dual_budget",
"X-Sim-Clock-Ms": "0",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": whale_64k_prompt}],
"max_tokens": 512,
"user_id": "whale-user",
"priority": "batch",
},
)
whale_retry_after = whale_blocked_resp.headers.get("Retry-After")
# 2) Interactive priority chat calls pass cleanly (100% SLA) while batch excess is shed
interactive_statuses: list[int] = []
for idx in range(5):
resp_i = sota_client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"X-Rate-Policy": "tpm_dual_budget",
"X-Sim-Clock-Ms": str(10.0 + idx),
"X-Shadow-Mirror": "true" if idx % 2 == 0 else "false",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": f"Summarize deployment checklist item #{idx}"}],
"max_tokens": 256,
"user_id": f"engineer-{idx:02d}",
"priority": "interactive",
},
)
interactive_statuses.append(resp_i.status_code)
# 3) Reversible PII Masking & Rehydration + W3C traceparent preservation
incoming_traceparent = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01"
pii_prompt = (
"Send receipt to alice.nguyen@fintech.vn, card 4111-1111-1111-1111, phone +84 909-123-456."
)
pii_resp = sota_client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"traceparent": incoming_traceparent,
"X-Geo-Country": "DE",
"X-Sim-Clock-Ms": "20",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": pii_prompt}],
"max_tokens": 256,
"user_id": "alice-eu",
"priority": "interactive",
},
)
pii_json = pii_resp.json()
upstream_masked_json = json.dumps(pii_json["gateway_meta"]["upstream_saw_masked_payload"])
rehydrated_reply = str(pii_json["choices"][0]["message"]["content"])
# 4) Protocol Translation: OpenAI -> AWS Bedrock Converse & GCP Vertex AI
bedrock_resp = sota_client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-interactive-002", "X-Sim-Clock-Ms": "30"},
json={
"model": "claude-3-7-sonnet",
"messages": [
{"role": "system", "content": "Be concise."},
{"role": "user", "content": "Explain Maglev L4 consistent hashing."},
],
"max_tokens": 128,
"user_id": "bob-arch",
"priority": "interactive",
},
).json()
vertex_resp = sota_client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-interactive-002", "X-Sim-Clock-Ms": "40"},
json={
"model": "gemini-2.5-flash",
"messages": [
{"role": "system", "content": "Respond in JSON bullets."},
{"role": "user", "content": "Compare Envoy AI Gateway vs NGINX."},
],
"max_tokens": 128,
"user_id": "carol-sre",
"priority": "interactive",
},
).json()
# 5) IP Allowlist & Geo-fence blocking (403)
ip_blocked = sota_client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"X-Forwarded-For": "203.0.113.99",
"X-Sim-Clock-Ms": "50",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello"}],
},
)
geo_blocked = sota_client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"X-Geo-Country": "XX",
"X-Sim-Clock-Ms": "60",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello"}],
},
)
# 6) Exhaust tenant-alpha USD budget using legitimate smaller chunks
alpha_small_statuses: list[int] = []
for idx in range(5):
r_a = sota_client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-alpha-001",
"X-Rate-Policy": "tpm_dual_budget",
"X-Sim-Clock-Ms": str(70_000.0 + idx * 60_000.0),
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "token " * 19_000}],
"max_tokens": 100,
"user_id": "alpha-batch",
"priority": "batch",
},
)
alpha_small_statuses.append(r_a.status_code)
sota_metrics = sota_client.get("/v1/gateway/metrics").json()
gw_state: GatewayState = sota_app.state.gateway
otel_summary = summarize_finished_spans(gw_state.exporter)
# Verify zero raw PII leaked in OTel spans
otel_serialized = json.dumps(otel_summary)
pii_leaked_in_otel = any(
raw in otel_serialized
for raw in ("alice.nguyen@fintech.vn", "4111-1111-1111-1111", "909-123-456")
)
interactive_sla_pct = round(
(sum(1 for sc in interactive_statuses if sc == 200) / len(interactive_statuses)) * 100.0, 2
)
sota_alpha_spent = round(float(sota_metrics["tenants"]["tenant-alpha"]["usd_spent"]), 4)
return {
"rpm_trap_vs_tpm_budget": {
"rpm_only_whale_statuses": rpm_whale_statuses,
"rpm_only_whale_allowed_count": sum(1 for sc in rpm_whale_statuses if sc == 200),
"rpm_only_alpha_usd_spent": round(rpm_alpha_spent, 4),
"rpm_only_alpha_tokens_consumed": 3 * (64_000 + 30),
"tpm_whale_blocked_status": whale_blocked_resp.status_code,
"tpm_whale_retry_after_sec": whale_retry_after,
"tpm_alpha_budget_exhaustion_statuses": alpha_small_statuses,
"interactive_statuses": interactive_statuses,
"interactive_sla_pct": interactive_sla_pct,
"sota_alpha_usd_spent": sota_alpha_spent,
},
"pii_vault_audit": {
"redacted_entities_in_prompt": pii_json["gateway_meta"]["pii_redacted_count"],
"upstream_masked_has_placeholders": (
"[PII_EMAIL_1]" in upstream_masked_json
and "[PII_CARD_1]" in upstream_masked_json
and "[PII_PHONE_1]" in upstream_masked_json
),
"upstream_raw_pii_leaked": any(
raw in upstream_masked_json
for raw in ("alice.nguyen@fintech.vn", "4111-1111-1111-1111", "909-123-456")
),
"rehydrated_output_restored": (
"alice.nguyen@fintech.vn" in rehydrated_reply
and "4111-1111-1111-1111" in rehydrated_reply
and "+84 909-123-456" in rehydrated_reply
),
"otel_raw_pii_leaked": pii_leaked_in_otel,
"geo_residency": pii_json["gateway_meta"]["residency"],
},
"protocol_translation": {
"bedrock_provider": bedrock_resp["provider"],
"bedrock_upstream_keys": bedrock_resp["gateway_meta"]["upstream_raw_response_keys"],
"bedrock_translated_keys": sorted(
bedrock_resp["gateway_meta"]["upstream_saw_masked_payload"].keys()
),
"vertex_provider": vertex_resp["provider"],
"vertex_upstream_keys": vertex_resp["gateway_meta"]["upstream_raw_response_keys"],
"vertex_translated_keys": sorted(
vertex_resp["gateway_meta"]["upstream_saw_masked_payload"].keys()
),
"provider_translation_counts": sota_metrics["provider_translation_counts"],
},
"security_edge_audit": {
"ip_blocked_status": ip_blocked.status_code,
"geo_blocked_status": geo_blocked.status_code,
},
"tracing_ab_shadow": {
"incoming_trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",
"preserved_trace_id": pii_json["gateway_meta"]["trace_id"],
"traceparent_gateway": pii_json["gateway_meta"]["traceparent_gateway"],
"traceparent_upstream": pii_json["gateway_meta"]["traceparent_upstream"],
"ab_counts": sota_metrics["ab_counts"],
"shadow_mirrored_count": sota_metrics["shadow_mirrored_count"],
},
"otel_telemetry": otel_summary,
}
def main() -> None:
parser = argparse.ArgumentParser(description="WB-Ch18 AI Gateway Service Smoke Check")
parser.add_argument("--seed", type=int, default=42)
args = parser.parse_args()
summary = run_gateway_service_experiment(seed=args.seed)
print(json.dumps(summary["rpm_trap_vs_tpm_budget"], indent=2))
if __name__ == "__main__":
main()
"""Deterministic CLI runner generating artifacts/t2_ch18_wb18_results.json for WB-Ch18."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import ai_gateway_routing_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from ai_gateway_routing_lab.ai_gateway_service import run_gateway_service_experiment
from ai_gateway_routing_lab.resilience_and_routing import (
create_in_memory_telemetry,
run_resilience_and_lb_benchmark,
run_semantic_cache_threshold_sweep,
summarize_finished_spans,
)
def run_full_workbench_suite(seed: int = 42) -> dict[str, Any]:
"""Execute all 3 WB-Ch18 AI Gateway experiments and assemble workbench_panels."""
_provider, exporter, tracer = create_in_memory_telemetry("fsds-wb-ch18-suite")
with tracer.start_as_current_span("wb18.benchmark.suite") as root_span:
root_span.set_attribute("wb.seed", seed)
with tracer.start_as_current_span("wb18.exp1_resilience_and_lb") as sp1:
exp1 = run_resilience_and_lb_benchmark(seed=seed)
s1 = exp1["summary"]
sp1.set_attribute("lb.naive_p99_ms", s1["naive_p99_ms"])
sp1.set_attribute("lb.hedged_p99_ms", s1["hedged_p99_ms"])
sp1.set_attribute("lb.p99_reduction_x", s1["p99_reduction_vs_naive_x"])
with tracer.start_as_current_span("wb18.exp2_semantic_cache_sweep") as sp2:
exp2 = run_semantic_cache_threshold_sweep(seed=seed)
opt = exp2["optimal_operating_point"]
sp2.set_attribute("cache.optimal_tau", opt["threshold_tau"])
sp2.set_attribute(
"cache.optimal_fp_pct", opt["false_positive_collision_rate_pct"]
)
sp2.set_attribute("cache.optimal_usd_saved", opt["safe_usd_saved"])
with tracer.start_as_current_span("wb18.exp3_live_fastapi_gateway") as sp3:
exp3 = run_gateway_service_experiment(seed=seed)
rl = exp3["rpm_trap_vs_tpm_budget"]
pii = exp3["pii_vault_audit"]
sp3.set_attribute("gateway.rpm_whale_allowed", rl["rpm_only_whale_allowed_count"])
sp3.set_attribute("gateway.tpm_whale_status", rl["tpm_whale_blocked_status"])
sp3.set_attribute("gateway.pii_redacted", pii["redacted_entities_in_prompt"])
sp3.set_attribute(
"gateway.live_otel_spans", exp3["otel_telemetry"]["span_count"]
)
suite_otel = summarize_finished_spans(exporter)
s1 = exp1["summary"]
by_strat = exp1["by_key"]
naive_s = by_strat["naive_rr_sync_retry"]
rr_fj_s = by_strat["rr_full_jitter_cb"]
p2c_s = by_strat["p2c_ewma_cb"]
hedged_s = by_strat["p2c_ewma_cb_hedged"]
sweep_rows = exp2["sweep"]
opt_cache = exp2["optimal_operating_point"]
low_tau_row = next(r for r in sweep_rows if r["threshold_tau"] == 0.75)
rl_res = exp3["rpm_trap_vs_tpm_budget"]
pii_res = exp3["pii_vault_audit"]
edge_res = exp3["security_edge_audit"]
tr_res = exp3["tracing_ab_shadow"]
proto_res = exp3["protocol_translation"]
live_otel_count = int(exp3["otel_telemetry"]["span_count"])
hedged_amp = s1["hedged_storm_amplification_x"]
naive_amp = s1["naive_storm_amplification_x"]
fp_075 = low_tau_row["false_positive_collisions"]
workbench_panels: dict[str, Any] = {
"kpis": [
{
"id": "kpi_p2c_hedged_p99_drop",
"label": "P2C-EWMA + CB + Hedging p99 Latency",
"value": f"{s1['hedged_p99_ms']}ms vs {s1['naive_p99_ms']}ms",
"unit": f"({s1['p99_reduction_vs_naive_x']}x faster p99)",
"status": "ok",
"detail": (
"Replaces blind Round-Robin + sync retry storm with P2C-EWMA, Full-Jitter "
"Backoff, Circuit Breaker & Hedged Requests."
),
},
{
"id": "kpi_retry_storm_suppression",
"label": "Retry Storm Load Suppression",
"value": f"{hedged_amp}x vs {naive_amp}x",
"unit": f"(-{s1['storm_load_reduction_pct']}% load)",
"status": "ok",
"detail": (
"Full-Jitter + 25% Retry Budget + Circuit Breaker eliminates cascading storm "
"amplification and drops request failures."
),
},
{
"id": "kpi_semantic_cache_pareto",
"label": "Semantic Cache Sweet Spot (tau=0.94)",
"value": f"0.0% FP | ${opt_cache['safe_usd_saved']}",
"unit": f"({opt_cache['true_hit_recall_pct']}% recall)",
"status": "ok",
"detail": (
f"Threshold tau={opt_cache['threshold_tau']} eliminates polarity collisions "
f"(vs {fp_075} collisions at tau=0.75) while saving latency & USD."
),
},
{
"id": "kpi_rpm_vs_tpm_budget_guard",
"label": "Dual TPM + USD Budget vs RPM=60 Trap",
"value": f"HTTP {rl_res['tpm_whale_blocked_status']} Blocked",
"unit": f"(vs {rl_res['rpm_only_whale_allowed_count']}/3 Whale Leaks)",
"status": "ok",
"detail": (
"Blocks 64k-token whale payloads with HTTP 429 + Retry-After while keeping "
f"interactive priority SLA at {rl_res['interactive_sla_pct']}%."
),
},
{
"id": "kpi_pii_and_protocol_translation",
"label": "Reversible PII Vault & Multi-Provider",
"value": f"{pii_res['redacted_entities_in_prompt']} PII Masked",
"unit": "(0 Leaks | OpenAI/Bedrock/Vertex)",
"status": "ok",
"detail": (
"Redacts email/card/phone before upstream dispatch, rehydrates response cleanly, "
"and translates OpenAI <-> Bedrock Converse & GCP Vertex AI."
),
},
{
"id": "kpi_w3c_otel_ab_shadow",
"label": "W3C traceparent, OTel & A/B/Shadow",
"value": f"{live_otel_count} OTel Spans",
"unit": f"({tr_res['shadow_mirrored_count']} Shadow Mirror)",
"status": "ok",
"detail": (
"Preserves W3C traceparent across gateway hops, runs deterministic A/B splits "
"and async shadow teeing with 0 raw PII in spans."
),
},
],
"bars": [
{
"id": "bar_lb_resilience_p99_ms",
"title": "p99 Latency (ms): Naive RR Storm vs Full-Jitter CB vs P2C-EWMA + Hedging",
"metric_label": "p99 Latency (ms)",
"items": [
{
"label": "naive_rr_sync_retry_storm",
"value": naive_s["p99_latency_ms"],
"display": (
f"{naive_s['p99_latency_ms']}ms ({naive_s['failure_rate_pct']}% "
f"fail, {naive_s['storm_amplification_x']}x storm)"
),
"css_class": "is-slow",
},
{
"label": "rr_full_jitter_circuit_breaker",
"value": rr_fj_s["p99_latency_ms"],
"display": (
f"{rr_fj_s['p99_latency_ms']}ms "
f"({rr_fj_s['failure_rate_pct']}% fail)"
),
"css_class": "is-mid",
},
{
"label": "p2c_ewma_full_jitter_cb",
"value": p2c_s["p99_latency_ms"],
"display": (
f"{p2c_s['p99_latency_ms']}ms "
f"({p2c_s['failure_rate_pct']}% fail)"
),
"css_class": "is-mid",
},
{
"label": "p2c_ewma_cb_hedged",
"value": hedged_s["p99_latency_ms"],
"display": (
f"{hedged_s['p99_latency_ms']}ms "
f"({s1['p99_reduction_vs_naive_x']}x faster, "
f"{hedged_s['failure_rate_pct']}% fail)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_semantic_cache_collision_vs_tau",
"title": "Semantic Cache False-Positive Collisions Across Cosine Threshold tau",
"metric_label": "Adversarial Collisions (Count)",
"items": [
{
"label": f"tau_{str(row['threshold_tau']).replace('.', '_')}",
"value": row["false_positive_collisions"],
"display": (
f"{row['false_positive_collisions']} collisions "
f"({row['true_hits']} true hits, ${row['safe_usd_saved']} saved)"
),
"css_class": (
"is-fast"
if row["false_positive_collisions"] == 0
and row["threshold_tau"] == 0.94
else ("is-mid" if row["false_positive_collisions"] <= 3 else "is-slow")
),
}
for row in sweep_rows
],
},
{
"id": "bar_rpm_trap_vs_tpm_budget_spend",
"title": "Whale 64k-Token Attack Spend (USD): RPM=60 Trap vs Dual TPM + Budget",
"metric_label": "Whale Spend ($USD)",
"items": [
{
"label": "rpm_only_60_trap",
"value": rl_res["rpm_only_alpha_usd_spent"],
"display": (
f"${rl_res['rpm_only_alpha_usd_spent']} "
f"({rl_res['rpm_only_whale_allowed_count']}/3 whale 64k leaked)"
),
"css_class": "is-slow",
},
{
"label": "dual_tpm_and_usd_budget",
"value": rl_res["sota_alpha_usd_spent"],
"display": (
f"${rl_res['sota_alpha_usd_spent']} "
"(whale HTTP 429 blocked, 100% interactive SLA)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_upstream_storm_amplification",
"title": "Upstream Request Amplification Factor (x Primary Requests)",
"metric_label": "Upstream Multiplier (x)",
"items": [
{
"label": "naive_sync_retry_storm",
"value": naive_s["storm_amplification_x"],
"display": (
f"{naive_s['storm_amplification_x']}x "
f"({naive_s['total_upstream_attempts']} attempts)"
),
"css_class": "is-slow",
},
{
"label": "rr_full_jitter_cb",
"value": rr_fj_s["storm_amplification_x"],
"display": (
f"{rr_fj_s['storm_amplification_x']}x "
f"({rr_fj_s['total_upstream_attempts']} attempts)"
),
"css_class": "is-mid",
},
{
"label": "p2c_ewma_cb_hedged",
"value": hedged_s["storm_amplification_x"],
"display": (
f"{hedged_s['storm_amplification_x']}x "
f"({hedged_s['total_upstream_attempts']} attempts)"
),
"css_class": "is-fast",
},
],
},
],
"tables": [
{
"id": "table_lb_and_resilience_strategies",
"title": "L7 Load Balancing & Resilience Benchmark (4 Replicas, r2 Degraded)",
"columns": ["strategy", "p50_p95_p99_ms", "storm_amp_x", "success_fail_pct"],
"rows": [
[
str(row["label"]),
(
f"{row['p50_latency_ms']} / {row['p95_latency_ms']} / "
f"{row['p99_latency_ms']} ms"
),
f"{row['storm_amplification_x']}x ({row['total_upstream_attempts']} req)",
f"{row['success_rate_pct']}% OK / {row['failure_rate_pct']}% fail",
]
for row in exp1["strategies"]
],
},
{
"id": "table_semantic_cache_sweep",
"title": (
"Semantic Cache Sweep (60 Eval: 30 Paraphrase / 18 Polarity-Flip / 12 Novel)"
),
"columns": ["threshold_tau", "true_hits_recall", "fp_collisions", "usd_ms_saved"],
"rows": [
[
f"tau = {row['threshold_tau']:.2f}",
f"{row['true_hits']}/30 ({row['true_hit_recall_pct']}%)",
(
f"{row['false_positive_collisions']} "
f"({row['false_positive_collision_rate_pct']}% on hits)"
),
f"${row['safe_usd_saved']} | {row['latency_saved_ms']} ms",
]
for row in sweep_rows
],
},
{
"id": "table_rate_limit_and_priority_governance",
"title": "Financial Governance & Priority: RPM=60 Trap vs Dual TPM + USD Budget",
"columns": [
"policy_mode",
"whale_64k_outcome",
"interactive_sla",
"alpha_spend_usd",
],
"rows": [
[
"RPM-Only (60 req/min)",
(
f"{rl_res['rpm_only_whale_allowed_count']}/3 HTTP 200 "
f"(Leaked {rl_res['rpm_only_alpha_tokens_consumed']} tok)"
),
"Contended by batch whales",
f"${rl_res['rpm_only_alpha_usd_spent']}",
],
[
"Dual TPM + USD Budget + Priority",
(
f"HTTP {rl_res['tpm_whale_blocked_status']} "
f"(Retry-After={rl_res['tpm_whale_retry_after_sec']}s)"
),
f"{rl_res['interactive_sla_pct']}% (5/5 HTTP 200)",
f"${rl_res['sota_alpha_usd_spent']} (Budget Guarded)",
],
],
},
{
"id": "table_security_protocol_and_observability",
"title": "FastAPI AI Gateway Security, PII Vault, Translation & OTel Audit",
"columns": ["capability", "verified_mechanism", "observed_output", "status"],
"rows": [
[
"Edge AuthN / IP / Geo-Fence",
"CIDR Allowlist + X-Geo-Country",
(
f"IP={edge_res['ip_blocked_status']} | "
f"Geo={edge_res['geo_blocked_status']} | "
f"DE={pii_res['geo_residency']}"
),
"PASS",
],
[
"Reversible PII Vault",
"Mask before upstream + Rehydrate reply",
(
f"{pii_res['redacted_entities_in_prompt']} masked | "
f"up_leak={pii_res['upstream_raw_pii_leaked']} | "
f"otel_leak={pii_res['otel_raw_pii_leaked']}"
),
"PASS",
],
[
"OpenAI <-> Bedrock / Vertex",
"Converse & generateContent adapters",
f"counts={proto_res['provider_translation_counts']}",
"PASS",
],
[
"W3C traceparent & A/B/Shadow",
"BoundedInMemorySpanExporter + blake2b",
(
f"live_spans={live_otel_count} | "
f"shadow={tr_res['shadow_mirrored_count']} | "
f"ab={tr_res['ab_counts']}"
),
"PASS",
],
],
},
],
}
return {
"unit_id": "T2-P3-U06",
"lab_id": "ch18-ai-gateway-routing-workbench",
"seed": seed,
"exp1_resilience_and_lb": exp1,
"exp2_semantic_cache_sweep": exp2,
"exp3_live_fastapi_gateway": exp3,
"suite_otel_telemetry": suite_otel,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run WB-Ch18 AI Gateway Workbench Suite")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--output",
type=Path,
default=Path("artifacts/t2_ch18_wb18_results.json"),
)
args = parser.parse_args()
results = run_full_workbench_suite(seed=args.seed)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(results, indent=2, ensure_ascii=False), encoding="utf-8")
s1 = results["exp1_resilience_and_lb"]["summary"]
opt = results["exp2_semantic_cache_sweep"]["optimal_operating_point"]
rl = results["exp3_live_fastapi_gateway"]["rpm_trap_vs_tpm_budget"]
otel_cnt = results["exp3_live_fastapi_gateway"]["otel_telemetry"]["span_count"]
print(f"[WB-Ch18] Output saved to: {args.output}")
print(
f"[Exp 1] Naive RR p99={s1['naive_p99_ms']}ms ({s1['naive_storm_amplification_x']}x "
f"storm) vs P2C+CB+Hedged p99={s1['hedged_p99_ms']}ms "
f"({s1['p99_reduction_vs_naive_x']}x faster)"
)
print(
f"[Exp 2] Optimal Semantic Cache tau={opt['threshold_tau']} -> "
f"FP={opt['false_positive_collision_rate_pct']}%, "
f"Recall={opt['true_hit_recall_pct']}%, "
f"Saved=${opt['safe_usd_saved']} / {opt['latency_saved_ms']}ms"
)
print(
f"[Exp 3] RPM=60 leaked {rl['rpm_only_whale_allowed_count']}/3 whales "
f"(${rl['rpm_only_alpha_usd_spent']}) | Dual TPM blocked HTTP "
f"{rl['tpm_whale_blocked_status']} (Retry-After={rl['tpm_whale_retry_after_sec']}s), "
f"Interactive SLA={rl['interactive_sla_pct']}%, OTel spans={otel_cnt}"
)
if __name__ == "__main__":
main()
"""Automated verification suite (30 tests, 0 skips) for WB-Ch18: AI Gateway & Routing."""
from __future__ import annotations
import ast
import concurrent.futures
import io
import json
import tokenize
from pathlib import Path
from typing import Any
import numpy as np
import pytest
from fastapi.testclient import TestClient
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from ai_gateway_routing_lab.ai_gateway_service import (
ChatMessage,
OpenAIChatRequest,
PiiVault,
TokenBucket,
assign_ab_bucket,
create_gateway_app,
is_valid_luhn,
parse_or_create_traceparent,
run_gateway_service_experiment,
translate_bedrock_to_openai,
translate_openai_to_bedrock,
translate_openai_to_vertex,
translate_vertex_to_openai,
)
from ai_gateway_routing_lab.resilience_and_routing import (
CircuitBreaker,
CircuitBreakerConfig,
LoadBalancerConfig,
P2CEwmaLoadBalancer,
RetryPolicyConfig,
RoundRobinLoadBalancer,
SemanticCacheEntry,
SemanticCacheSweepConfig,
TenantScopedSemanticCache,
compute_backoff_delay_ms,
run_resilience_and_lb_benchmark,
run_semantic_cache_threshold_sweep,
)
from scripts.run_lab_demo import run_full_workbench_suite
LAB_ROOT = Path(__file__).resolve().parents[1]
def test_01_ast_safety_no_type_ignore_no_wall_sleep_or_disk_artifacts() -> None:
forbidden_modules = {"pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
forbidden_calls = {"eval", "exec"}
py_files = [
*sorted((LAB_ROOT / "src").rglob("*.py")),
*sorted((LAB_ROOT / "scripts").rglob("*.py")),
*sorted((LAB_ROOT / "tests").rglob("*.py")),
]
assert len(py_files) >= 5
forbidden_comment = "type:" + " ignore"
for py_file in py_files:
source = py_file.read_text(encoding="utf-8")
with io.StringIO(source) as buf:
for tok in tokenize.generate_tokens(buf.readline):
if tok.type == tokenize.COMMENT and forbidden_comment in tok.string:
raise AssertionError(f"Forbidden type-ignore comment found in {py_file}")
tree = ast.parse(source, filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
assert root_mod not in forbidden_modules
assert root_mod != "time"
elif isinstance(node, ast.ImportFrom) and node.module:
root_mod = node.module.split(".")[0]
assert root_mod not in forbidden_modules
assert root_mod != "time"
elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls
for pat in ("*.png", "*.parquet", "*.duckdb*"):
leftover = list(LAB_ROOT.rglob(pat))
assert not leftover, f"Unexpected leftover files matching {pat}: {leftover}"
def test_02_pydantic_strict_configs_and_request_schemas_forbid_extra() -> None:
assert LoadBalancerConfig(n_replicas=4).n_replicas == 4
assert RetryPolicyConfig(max_retries=3).max_retries == 3
assert CircuitBreakerConfig(cooldown_ticks=10).cooldown_ticks == 10
assert len(SemanticCacheSweepConfig().thresholds) == 5
for cls, bad_payload in (
(LoadBalancerConfig, {"n_replicas": 4, "unknown": 1}),
(RetryPolicyConfig, {"max_retries": 2, "extra": True}),
(CircuitBreakerConfig, {"cooldown_ticks": 5, "bogus": "x"}),
(SemanticCacheSweepConfig, {"thresholds": [0.9], "extra_key": 1}),
(
OpenAIChatRequest,
{
"model": "gpt-4o",
"messages": [{"role": "user", "content": "hi"}],
"injected_field": 123,
},
),
):
with pytest.raises(ValidationError):
cls.model_validate(bad_payload)
def test_03_circuit_breaker_fsm_transitions_closed_open_half_open() -> None:
cfg = CircuitBreakerConfig(
window_size=6,
min_samples=4,
failure_rate_threshold=0.5,
consecutive_failure_threshold=3,
cooldown_ticks=5,
half_open_probes=2,
)
cb = CircuitBreaker("r2", cfg)
assert cb.state == "CLOSED"
for tick in range(3):
assert cb.allow_request(tick) is True
cb.record_failure(tick)
open_state: str = cb.state
assert open_state == "OPEN"
assert cb.open_transitions == 1
assert cb.allow_request(4) is False
assert cb.rejected_while_open == 1
# After cooldown (2 + 5 = 7), transitions to HALF_OPEN
assert cb.allow_request(7) is True
half_state: str = cb.state
assert half_state == "HALF_OPEN"
cb.record_failure(7)
reopened_state: str = cb.state
assert reopened_state == "OPEN"
assert cb.open_transitions == 2
# Recover via consecutive half-open probe successes
assert cb.allow_request(12) is True
cb.record_success(12)
assert cb.allow_request(12) is True
cb.record_success(12)
recovered_state: str = cb.state
assert recovered_state == "CLOSED"
@given(
attempt=st.integers(min_value=0, max_value=6),
base_ms=st.floats(min_value=5.0, max_value=50.0, allow_nan=False, allow_infinity=False),
cap_ms=st.floats(min_value=100.0, max_value=1000.0, allow_nan=False, allow_infinity=False),
seed=st.integers(min_value=1, max_value=10_000),
)
@settings(max_examples=40, database=None)
def test_04_full_jitter_backoff_always_within_envelope(
attempt: int, base_ms: float, cap_ms: float, seed: int
) -> None:
rng = np.random.default_rng(seed)
upper = min(cap_ms, base_ms * float(2**attempt))
jitter_delay = compute_backoff_delay_ms(attempt, base_ms, cap_ms, "full_jitter", rng)
fixed_delay = compute_backoff_delay_ms(attempt, base_ms, cap_ms, "fixed", rng)
assert 0.0 <= jitter_delay <= upper + 0.01
assert abs(fixed_delay - round(upper, 2)) <= 0.01
def test_05_p2c_ewma_beats_round_robin_on_degraded_node_avoidance() -> None:
lb = P2CEwmaLoadBalancer(LoadBalancerConfig(n_replicas=4, ewma_alpha=0.5, initial_ewma_ms=20.0))
lb.begin_request(2)
lb.finish_request(2, 320.0)
lb.begin_request(2)
assert lb.score(2) > lb.score(0)
rr = RoundRobinLoadBalancer(4)
picks = [rr.select([0, 1, 2, 3]) for _ in range(4)]
assert picks == [0, 1, 2, 3]
def test_06_exp1_retry_storm_vs_full_jitter_cb_p2c_and_hedging() -> None:
res = run_resilience_and_lb_benchmark(seed=42)
by_key = res["by_key"]
naive = by_key["naive_rr_sync_retry"]
rr_fj = by_key["rr_full_jitter_cb"]
p2c = by_key["p2c_ewma_cb"]
hedged = by_key["p2c_ewma_cb_hedged"]
assert naive["storm_amplification_x"] >= 1.8
assert hedged["storm_amplification_x"] < naive["storm_amplification_x"]
assert hedged["failure_rate_pct"] < naive["failure_rate_pct"]
assert rr_fj["p99_latency_ms"] < naive["p99_latency_ms"]
assert p2c["p99_latency_ms"] < rr_fj["p99_latency_ms"]
assert hedged["p99_latency_ms"] < p2c["p99_latency_ms"]
assert hedged["hedges_fired"] > 0
assert rr_fj["r2_cb_open_transitions"] >= 1
assert res["circuit_breaker_fsm_audit"]["open_transitions"] >= 2
def test_07_fallback_chain_routes_to_first_closed_provider() -> None:
res = run_resilience_and_lb_benchmark(seed=42)
fb = res["fallback_chain_audit"]
assert fb["resolved_provider"] == "aws-bedrock"
assert fb["resolved_model"] == "claude-3-7-sonnet"
def test_08_exp2_semantic_cache_sweep_identifies_optimal_tau_094() -> None:
res = run_semantic_cache_threshold_sweep(seed=42)
by_tau = {row["threshold_tau"]: row for row in res["sweep"]}
assert by_tau[0.75]["false_positive_collisions"] >= 10
assert by_tau[0.85]["false_positive_collisions"] >= 5
assert by_tau[0.90]["false_positive_collisions"] >= 1
assert by_tau[0.94]["false_positive_collisions"] == 0
assert by_tau[0.94]["false_positive_collision_rate_pct"] == 0.0
assert by_tau[0.94]["true_hit_recall_pct"] >= 80.0
assert by_tau[0.94]["safe_usd_saved"] > by_tau[0.98]["safe_usd_saved"]
assert res["optimal_operating_point"]["threshold_tau"] == 0.94
@given(
t_low=st.floats(min_value=0.70, max_value=0.88),
t_high=st.floats(min_value=0.89, max_value=0.99),
)
@settings(max_examples=20, database=None)
def test_09_semantic_cache_threshold_monotonicity_property(t_low: float, t_high: float) -> None:
res = run_semantic_cache_threshold_sweep(
seed=42,
config=SemanticCacheSweepConfig(thresholds=[round(t_low, 3), round(t_high, 3)]),
)
low_row, high_row = res["sweep"][0], res["sweep"][1]
assert high_row["false_positive_collisions"] <= low_row["false_positive_collisions"]
assert high_row["true_hits"] <= low_row["true_hits"]
def test_10_pii_vault_reversible_redaction_and_rehydration() -> None:
text = (
"Email alice@corp.io and backup alice@corp.io, card 4532-1111-2222-3336, "
"call +84 912-345-678."
)
masked, vault = PiiVault.redact(text)
assert "alice@corp.io" not in masked
assert "4532-1111-2222-3336" not in masked
assert "912-345-678" not in masked
assert masked.count("[PII_EMAIL_1]") == 2
assert "[PII_CARD_1]" in masked
assert "[PII_PHONE_1]" in masked
assert PiiVault.rehydrate(masked, vault) == text
def test_11_protocol_translation_openai_bedrock_and_vertex_roundtrip() -> None:
req = OpenAIChatRequest(
model="claude-3-7-sonnet",
messages=[
ChatMessage(role="system", content="Be brief."),
ChatMessage(role="user", content="Hello Bedrock"),
],
max_tokens=200,
temperature=0.1,
)
bedrock_req = translate_openai_to_bedrock(req)
assert bedrock_req["system"] == [{"text": "Be brief."}]
assert bedrock_req["inferenceConfig"]["maxTokens"] == 200
oai_from_br = translate_bedrock_to_openai(
{
"output": {"message": {"role": "assistant", "content": [{"text": "Hi!"}]}},
"stopReason": "end_turn",
"usage": {"inputTokens": 10, "outputTokens": 5},
},
model="claude-3-7-sonnet",
req_id="req-1",
)
assert oai_from_br["provider"] == "aws-bedrock"
assert oai_from_br["usage"]["total_tokens"] == 15
vertex_req = translate_openai_to_vertex(req)
assert vertex_req["systemInstruction"] == {"parts": [{"text": "Be brief."}]}
assert vertex_req["generationConfig"]["maxOutputTokens"] == 200
oai_from_vx = translate_vertex_to_openai(
{
"candidates": [{"content": {"parts": [{"text": "Hi Vertex"}]}, "finishReason": "STOP"}],
"usageMetadata": {"promptTokenCount": 12, "candidatesTokenCount": 8},
},
model="gemini-2.5-flash",
req_id="req-2",
)
assert oai_from_vx["provider"] == "gcp-vertex"
assert oai_from_vx["usage"]["total_tokens"] == 20
@given(
cap=st.floats(min_value=100.0, max_value=1000.0, allow_nan=False, allow_infinity=False),
consume=st.floats(min_value=1.0, max_value=150.0, allow_nan=False, allow_infinity=False),
dt_ms=st.floats(min_value=0.0, max_value=60_000.0, allow_nan=False, allow_infinity=False),
)
@settings(max_examples=30, database=None)
def test_12_token_bucket_bounds_invariant(cap: float, consume: float, dt_ms: float) -> None:
bucket = TokenBucket(capacity=cap, refill_per_ms=cap / 60_000.0)
ok, retry = bucket.try_consume(consume, clock_ms=dt_ms)
assert 0.0 <= bucket.tokens <= cap + 1e-6
if ok:
assert retry == 0.0
else:
assert retry >= 1.0
def test_13_live_fastapi_health_authn_and_authz() -> None:
client = TestClient(create_gateway_app())
assert client.get("/health").status_code == 200
unauth = client.post(
"/v1/chat/completions",
json={"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]},
)
assert unauth.status_code == 401
bad_model = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-alpha-001"},
json={"model": "unauthorized-model-x", "messages": [{"role": "user", "content": "hi"}]},
)
assert bad_model.status_code == 403
def test_14_live_fastapi_ip_allowlisting_and_geofencing() -> None:
client = TestClient(create_gateway_app())
bad_ip = client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"X-Forwarded-For": "198.51.100.77",
},
json={"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]},
)
assert bad_ip.status_code == 403
assert bad_ip.json()["detail"] == "IP_NOT_ALLOWLISTED"
bad_geo = client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"X-Geo-Country": "KP",
},
json={"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]},
)
assert bad_geo.status_code == 403
assert bad_geo.json()["detail"] == "GEO_FENCE_BLOCKED"
eu_ok = client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"X-Geo-Country": "DE",
},
json={"model": "gpt-4o", "messages": [{"role": "user", "content": "hi"}]},
)
assert eu_ok.status_code == 200
assert eu_ok.json()["gateway_meta"]["residency"] == "eu-west"
def test_15_live_fastapi_rpm_trap_vs_dual_tpm_whale_blocking() -> None:
res = run_gateway_service_experiment(seed=42)
rl = res["rpm_trap_vs_tpm_budget"]
assert rl["rpm_only_whale_allowed_count"] == 3
assert rl["rpm_only_alpha_tokens_consumed"] > 190_000
assert rl["tpm_whale_blocked_status"] == 429
assert int(rl["tpm_whale_retry_after_sec"]) >= 1
assert rl["interactive_sla_pct"] == 100.0
def test_16_live_fastapi_priority_queue_protects_interactive_under_load() -> None:
app = create_gateway_app(allow_test_clock=True)
client = TestClient(app)
# Consume 39k cluster tokens via interactive call, leaving < 12k interactive reserve
r1 = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-interactive-002", "X-Sim-Clock-Ms": "0"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "data " * 31_000}],
"max_tokens": 512,
"priority": "interactive",
},
)
assert r1.status_code == 200
# Now cluster tokens remaining ~11k (< 12k interactive reserve): batch must be shed with 429
batch_resp = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-interactive-002", "X-Sim-Clock-Ms": "1"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "batch summary job"}],
"max_tokens": 256,
"priority": "batch",
},
)
assert batch_resp.status_code == 429
assert batch_resp.json()["detail"] == "CLUSTER_BATCH_SHEDDING_PROTECTING_INTERACTIVE"
# Interactive request still succeeds using the reserved headroom
inter_resp = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-interactive-002", "X-Sim-Clock-Ms": "2"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "urgent interactive chat"}],
"max_tokens": 128,
"priority": "interactive",
},
)
assert inter_resp.status_code == 200
def test_17_live_fastapi_usd_budget_enforcement_and_postflight_refund() -> None:
app = create_gateway_app(allow_test_clock=True)
client = TestClient(app)
resp = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-alpha-001", "X-Sim-Clock-Ms": "0"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "short query"}],
"max_tokens": 2000,
"priority": "interactive",
},
)
assert resp.status_code == 200
# Verify post-flight refund restored unused max_tokens out of 40,000 TPM
rem_tokens = int(resp.headers["X-RateLimit-Remaining-Tokens"])
assert rem_tokens > 39_900
res = run_gateway_service_experiment(seed=42)
statuses = res["rpm_trap_vs_tpm_budget"]["tpm_alpha_budget_exhaustion_statuses"]
assert 429 in statuses
def test_18_live_fastapi_pii_masking_and_rehydration_end_to_end() -> None:
res = run_gateway_service_experiment(seed=42)
pii = res["pii_vault_audit"]
assert pii["redacted_entities_in_prompt"] == 3
assert pii["upstream_masked_has_placeholders"] is True
assert pii["upstream_raw_pii_leaked"] is False
assert pii["rehydrated_output_restored"] is True
assert pii["otel_raw_pii_leaked"] is False
def test_19_live_fastapi_bedrock_and_vertex_translation_end_to_end() -> None:
res = run_gateway_service_experiment(seed=42)
proto = res["protocol_translation"]
assert proto["bedrock_provider"] == "aws-bedrock"
assert "inferenceConfig" in proto["bedrock_translated_keys"]
assert "output" in proto["bedrock_upstream_keys"]
assert proto["vertex_provider"] == "gcp-vertex"
assert "generationConfig" in proto["vertex_translated_keys"]
assert "usageMetadata" in proto["vertex_upstream_keys"]
def test_20_w3c_traceparent_preservation_and_generation() -> None:
tid, gw_tp, up_tp = parse_or_create_traceparent(
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
seq=1,
)
assert tid == "4bf92f3577b34da6a3ce929d0e0e4736"
assert gw_tp.startswith(f"00-{tid}-")
assert up_tp.startswith(f"00-{tid}-")
assert gw_tp != up_tp
gen_tid, gen_gw, _gen_up = parse_or_create_traceparent("invalid-header", seq=2)
assert len(gen_tid) == 32
assert gen_gw.startswith(f"00-{gen_tid}-")
def test_21_deterministic_ab_split_and_shadow_mirroring() -> None:
assert assign_ab_bucket("user-42") == assign_ab_bucket("user-42")
buckets = {assign_ab_bucket(f"user-{i}") for i in range(100)}
assert buckets == {"variant_a", "variant_b"}
res = run_gateway_service_experiment(seed=42)
assert res["tracing_ab_shadow"]["shadow_mirrored_count"] >= 3
assert sum(res["tracing_ab_shadow"]["ab_counts"].values()) >= 8
def test_22_otel_bounded_exporter_captures_at_least_six_clean_spans() -> None:
res = run_gateway_service_experiment(seed=42)
otel = res["otel_telemetry"]
assert otel["span_count"] >= 6
assert "gateway.request" in otel["span_names"]
assert "gateway.pii_redact" in otel["span_names"]
assert "gateway.rate_limit_and_budget" in otel["span_names"]
assert "gateway.protocol_translate_and_route" in otel["span_names"]
def test_23_seed_42_determinism_across_repeated_runs() -> None:
run_a = run_full_workbench_suite(seed=42)
run_b = run_full_workbench_suite(seed=42)
assert run_a["exp1_resilience_and_lb"] == run_b["exp1_resilience_and_lb"]
assert run_a["exp2_semantic_cache_sweep"] == run_b["exp2_semantic_cache_sweep"]
assert run_a["exp3_live_fastapi_gateway"] == run_b["exp3_live_fastapi_gateway"]
assert run_a["workbench_panels"] == run_b["workbench_panels"]
def test_24_workbench_panels_schema_and_suite_artifact_contract() -> None:
suite: dict[str, Any] = run_full_workbench_suite(seed=42)
encoded = json.dumps(suite)
assert len(encoded) > 2000
panels = suite["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
for kpi in panels["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"} <= set(kpi.keys())
for bar in panels["bars"]:
assert {"id", "title", "metric_label", "items"} <= set(bar.keys())
assert len(bar["items"]) >= 2
for tbl in panels["tables"]:
assert {"id", "title", "columns", "rows"} <= set(tbl.keys())
assert len(tbl["rows"]) >= 2
def test_25_stateful_multi_message_pii_vault_luhn_and_intl_phones() -> None:
assert is_valid_luhn("4111-1111-1111-1111") is True
assert is_valid_luhn("4111-2222-3333-4444") is False
msgs = [
ChatMessage(
role="user",
content=(
"Primary alice@a.com, card 4111-1111-1111-1111, US phone (555) 123-4567"
),
),
ChatMessage(
role="user",
content=(
"Secondary bob@b.com, non-luhn ref 4111-2222-3333-4444, "
"VN phone +84909123456, order req-99887766, repeat alice@a.com"
),
),
]
masked_msgs, vault = PiiVault.redact_messages(msgs)
assert "[PII_EMAIL_1]" in masked_msgs[0].content
assert "[PII_CARD_1]" in masked_msgs[0].content
assert "[PII_PHONE_1]" in masked_msgs[0].content
assert "[PII_EMAIL_2]" in masked_msgs[1].content
assert "[PII_PHONE_2]" in masked_msgs[1].content
assert "[PII_EMAIL_1]" in masked_msgs[1].content
assert "4111-2222-3333-4444" in masked_msgs[1].content
assert "req-99887766" in masked_msgs[1].content
assert vault["[PII_EMAIL_1]"] == "alice@a.com"
assert vault["[PII_EMAIL_2]"] == "bob@b.com"
assert vault["[PII_PHONE_1]"] == "(555) 123-4567"
assert vault["[PII_PHONE_2]"] == "+84909123456"
client = TestClient(create_gateway_app())
resp = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-interactive-002"},
json={
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Contact alice@a.com"},
{"role": "user", "content": "Also cc bob@b.com and +84909123456"},
],
"max_tokens": 128,
},
)
assert resp.status_code == 200
body = resp.json()
assert body["gateway_meta"]["pii_redacted_count"] == 3
masked_sent = json.dumps(body["gateway_meta"]["upstream_saw_masked_payload"])
assert "[PII_EMAIL_1]" in masked_sent
assert "[PII_EMAIL_2]" in masked_sent
assert "[PII_PHONE_1]" in masked_sent
assert "alice@a.com" not in masked_sent and "bob@b.com" not in masked_sent
def test_26_full_max_tokens_reservation_closes_usd_budget_overrun() -> None:
app = create_gateway_app()
gw = app.state.gateway
gw.tenants_by_key["sk-gw-alpha-001"].usd_budget = 0.05
client = TestClient(app)
# 16,000 max_tokens => est_cost > $0.08 > $0.05 budget (must NOT be capped at 2048!)
resp = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-alpha-001"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Generate a long report."}],
"max_tokens": 16_000,
"priority": "interactive",
},
)
assert resp.status_code == 429
assert resp.json()["detail"] == "TENANT_USD_BUDGET_EXCEEDED"
def test_27_cluster_tpm_check_and_try_finally_exception_refund() -> None:
app = create_gateway_app()
gw = app.state.gateway
gw.cluster_tpm_bucket = TokenBucket(capacity=200.0, refill_per_ms=0.0)
client = TestClient(app)
# Cluster bucket only has 200 tokens, requesting 520 tokens must return 429 & NOT inflate cluster
blocked = client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-alpha-001"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Hello"}],
"max_tokens": 512,
"priority": "interactive",
},
)
assert blocked.status_code == 429
assert blocked.json()["detail"] == "CLUSTER_TPM_CAPACITY_EXCEEDED"
assert gw.cluster_tpm_bucket.tokens == pytest.approx(200.0)
assert gw.tenants_by_key["sk-gw-alpha-001"].tpm_bucket.tokens == pytest.approx(40_000.0)
# Restore cluster capacity & simulate upstream exception -> finally must refund full reservation
gw.cluster_tpm_bucket = TokenBucket(capacity=50_000.0, refill_per_ms=0.0)
gw.simulate_upstream_error_next = True
err_client = TestClient(app, raise_server_exceptions=False)
err_resp = err_client.post(
"/v1/chat/completions",
headers={"Authorization": "Bearer sk-gw-alpha-001"},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Trigger upstream error"}],
"max_tokens": 1000,
"priority": "interactive",
},
)
assert err_resp.status_code == 500
assert gw.cluster_tpm_bucket.tokens == pytest.approx(50_000.0)
assert gw.tenants_by_key["sk-gw-alpha-001"].tpm_bucket.tokens == pytest.approx(40_000.0)
def test_28_untrusted_x_sim_clock_header_ignored_when_prod_mode() -> None:
app = create_gateway_app() # allow_test_clock=False by default
gw = app.state.gateway
gw.tenants_by_key["sk-gw-alpha-001"].tpm_bucket.tokens = 100.0
client = TestClient(app)
spoofed = client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-alpha-001",
"X-Sim-Clock-Ms": "999999999",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": "Attempt clock spoof"}],
"max_tokens": 500,
"priority": "interactive",
},
)
assert spoofed.status_code == 429
assert spoofed.json()["detail"] == "TPM_TOKEN_BUCKET_EXCEEDED"
def test_29_semantic_cache_strict_tenant_and_model_namespace_isolation() -> None:
vec = np.ones(16, dtype=np.float64) / 4.0
cache = TenantScopedSemanticCache(
[
SemanticCacheEntry(
cache_id="c-alpha-gpt4o",
tenant_id="tenant-alpha",
model="gpt-4o",
intent_label="secret_alpha",
canonical_prompt="Confidential prompt",
cached_response="Alpha secret answer",
embedding=vec,
)
]
)
hit, sim = cache.lookup("tenant-alpha", "gpt-4o", vec, threshold_tau=0.94)
assert hit is not None and hit.cache_id == "c-alpha-gpt4o" and sim == pytest.approx(1.0)
cross_tenant_hit, _ = cache.lookup("tenant-beta", "gpt-4o", vec, threshold_tau=0.50)
cross_model_hit, _ = cache.lookup("tenant-alpha", "claude-3-7-sonnet", vec, threshold_tau=0.50)
assert cross_tenant_hit is None
assert cross_model_hit is None
def test_30_thread_safe_concurrent_requests_and_background_shadow_tasks() -> None:
app = create_gateway_app()
client = TestClient(app)
def _post_one(idx: int) -> int:
r = client.post(
"/v1/chat/completions",
headers={
"Authorization": "Bearer sk-gw-interactive-002",
"X-Shadow-Mirror": "true",
},
json={
"model": "gpt-4o",
"messages": [{"role": "user", "content": f"Concurrent req {idx}"}],
"max_tokens": 64,
"user_id": f"conc-{idx}",
"priority": "interactive",
},
)
return int(r.status_code)
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
statuses = list(pool.map(_post_one, range(8)))
assert statuses == [200] * 8
metrics = client.get("/v1/gateway/metrics").json()
assert metrics["total_requests"] == 8
assert metrics["shadow_mirrored_count"] == 8
assert metrics["shadow_log_count"] == 8
L4 Maglev (TLS passthrough) gây nóng cục bộ với HTTP/2/gRPC multiplexing, và cấu hình L7 cho luồng SSE LLM cần bổ sung cơ chế nào?L4 Maglev (M=65537) định tuyến theo 5-tuple TCP nên hàng trăm RPC HTTP/2/gRPC trên 1 kết nối bị ghim vào 1 Pod. Ở L7 phục vụ SSE, bắt buộc tắt proxy_buffering, tách connect/read_idle/stream_max timeout và lan truyền hủy khi client ngắt (proxy_ignore_client_abort off / HTTP/2 RST_STREAM -> abort_request() giải phóng KV-cache).
4 bản sao của WB-Ch18 (Tests 05–06), tại sao P2C-EWMA vượt trội Round-Robin khi replica-2 suy giảm và replica-3 có nhiễu đuôi 24%?Tests 05–06 và §1.2: Round-Robin mù trước tải thực tế (93.3% OK khi bão retry, 216.49 ms p95 dù đã gắn CB). Theo định lý Mitzenmacher, P2C-EWMA chỉ kiểm tra 2 ứng viên ngẫu nhiên O(1) theo ewma_ms + 10 * inflight, né được cả replica-2 lẫn replica-3 để đạt 100.0% thành công và hạ p95 còn 183.58 ms.
1,538 yêu cầu gốc) của WB-Ch18, kết hợp Full-Jitter Backoff, Retry Budget, Circuit Breaker và Request Hedging có ngân sách thay đổi cục diện ra sao?Tests 03–04, 06: Naive RR + Sync Retry khuếch đại tải 1.8x (2,766 lượt, 6.7% lỗi, p99 = 702.39 ms). Full-Jitter (Uniform(0, min(cap, base*2^a))) + Retry Budget 25% + CircuitBreaker (CLOSED/OPEN/HALF_OPEN) + 111 hedge có ngân sách giảm tải 40.09%, hạ lỗi về 0.07% và kéo p99 xuống 110.02 ms (6.38x).
create_gateway_app() trong WB-Ch18 (Tests 15–17), điều gì xảy ra trước payload 64,000 token ở chế độ RPM = 60 so với Dual TPM Bucket + USD Budget + Priority?Tests 15–17: RPM=60 chỉ đếm request nên cho lọt 3/3 gói 64k (192,090 token, đốt 0.9605 USD). Ngược lại, Dual TPM + USD Budget dự trữ đủ prompt_tokens + max_tokens đồng bộ bằng threading.Lock (kiểm tra kết quả cluster_tpm_bucket.try_consume), chặn vượt hạn mức bằng HTTP 429 (Retry-After: 12), hoàn trả phần dư trong khối try / finally, khóa chi phí 0.1426 USD và giữ 100.0% (5/5) SLA interactive (cùng X-Sim-Clock-Ms chỉ mở khi bật allow_test_clock).
60 truy vấn của Thực nghiệm 2 (30 đồng nghĩa, 18 đảo cực tính như "hủy thẻ" vs "kích hoạt thẻ", 12 mới), kết quả quét ngưỡng tau và khóa phân tách cache trong WB-Ch18 (Tests 08–09) khẳng định điều gì?Tests 08–09: Ở tau = 0.75 dính 18 va chạm (37.5% trên hit, lỗ -3.96 USD); ở 0.85 dính 11 va chạm; ở 0.90 còn 3 va chạm. Điểm tau = 0.94 đạt 0 va chạm (0.0% FP), 90.0% recall (0.486 USD / 22,032.0 ms saved), còn 0.98 rớt xuống 6.67% recall. Cache thực chiến luôn phải cô lập theo tenant_id, model và chỉ áp dụng khi temperature <= 0.2 để chống rò rỉ dữ liệu chéo giữa các thuê bao.
FastAPI AI Gateway của WB-Ch18 (Tests 10, 13–14, 18) xử lý kiểm soát biên và dữ liệu PII nhạy cảm xuyên suốt mọi lượt hội thoại theo cơ chế nào?Tests 10, 13–14, 18: Cổng kiểm tra 401 API key, 403 IP_NOT_ALLOWLISTED & GEO_FENCE_BLOCKED (DE -> eu-west), sau đó dùng một PiiVault gắn vòng đời của cả request chạy xuyên suốt tất cả payload.messages (cấp nối tiếp [PII_EMAIL_1], [PII_EMAIL_2], kiểm tra chữ số thẻ bằng thuật toán Luhn is_valid_luhn, 0 leak upstream & 0 leak OTel) trước khi tái lập trả client.
OpenAI ChatCompletions sang AWS Bedrock Converse và GCP Vertex AI generateContent trong WB-Ch18 (Tests 11, 19), cặp chuyển đổi nào đúng?Tests 11, 19: Bedrock Converse tách system riêng, bọc nội dung thành [{"text": ...}] và chuyển tham số vào inferenceConfig.maxTokens; Vertex AI dùng systemInstruction, đổi vai trò assistant sang "model" trong contents và đặt cấu hình trong generationConfig.maxOutputTokens, rồi cả hai được dịch ngược về choices + usage chuẩn OpenAI.
WB-Ch18 (Tests 20–22) và hệ sinh thái cổng AI sản xuất (NGINX, Envoy AI Gateway, GAIE EPP, LiteLLM), phát biểu nào mô tả đúng nhất?Tests 20–22 và Trụ cột 2: Cổng bảo toàn trace_id của W3C traceparent, ghi 81 OTel spans sạch PII, chia A/B bám dính bằng blake2b(user_id) % 100, nhân bản Shadow bất đồng bộ không chặn qua FastAPI BackgroundTasks (3 mirrors). Thực chiến 2026 đặt NGINX / Envoy AI Gateway (AIGatewayRoute, AIServiceBackend, GAIE EPP qua ext_proc, hỗ trợ hủy SSE khi client ngắt) ở biên và LiteLLM điều phối đa nhà cung cấp.
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 — Kiến trúc L4 Maglev vs L7 SSE Cancellation và Bất đẳng thức P2C-EWMA 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích cách HTTP/2/gRPC gộp nhiều luồng trên 1 kết nối TCP làm vô hiệu 5-tuple L4, cách đặt proxy_buffering off + proxy_ignore_client_abort off (hủy SSE RST_STREAM/abort_request()) + 3 tầng timeout, và ewma_ms + 10 * inflight.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_05 or test_06" -v và kiểm tra lớp P2CEwmaLoadBalancer trong src/ai_gateway_routing_lab/resilience_and_routing.py.
Tiêu chí Đáp án & Số đối chứng
L4 Maglev (M=65537) ghim toàn bộ HTTP/2 multiplexing vào 1 Pod. Ở L7, tắt đệm SSE kèm lan truyền hủy khi client ngắt kết nối và thay Round-Robin bằng P2C-EWMA (O(1) lấy mẫu 2 nút) né replica-2 brownout và replica-3 nhiễu đuôi để đạt 100.0% thành công và hạ p95 từ 216.49 ms xuống 183.58 ms.
Bài tập 2 — Dập Bão Thử lại, Circuit Breaker FSM và Request Hedging 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Lần theo công thức Uniform(0, min(cap, base * 2^attempt)), sơ đồ chuyển trạng thái CLOSED -> OPEN -> HALF_OPEN -> CLOSED, và lý do Hedging cần đặt trần ngân sách (<= 18%, trigger 60 ms).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_03 or test_04 or test_06 or test_07" -v và đọc bảng exp1_resilience_and_lb trong artifacts/t2_ch18_wb18_results.json.
Tiêu chí Đáp án & Số đối chứng
Naive RR + Sync Retry khuếch đại tải 1.8x (2,766 lượt gọi, 6.7% lỗi, p99 = 702.39 ms). Full-Jitter + Retry Budget 25% + CircuitBreaker + 111 Hedged Requests giảm 40.09% tổng tải bão (1.08x), hạ lỗi còn 0.07% và cắt p99 6.38x xuống 110.02 ms, kèm Fallback Chain định tuyến sang aws-bedrock.
Bài tập 3 — Tối ưu Ngưỡng Pareto cho Semantic Cache Cô lập Thuê bao 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
So sánh độ tương đồng cosine của cặp đồng nghĩa (0.914–0.987) với cặp đảo cực tính như "Cancel card" vs "Activate card" (0.768–0.916) và buộc khóa cache phải tách theo tenant_id + model + temperature <= 0.2.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_08 or test_09" -v và đối chiếu mảng sweep trong exp2_semantic_cache_sweep.
Tiêu chí Đáp án & Số đối chứng
Tại tau = 0.75 và 0.85 xảy ra 18 và 11 va chạm dương tính giả (lỗ ròng -3.96 USD và -2.21 USD). Ngưỡng tau = 0.94 cô lập theo tenant_id + model (temperature <= 0.2) đạt 0 va chạm (0.0% FP, 100.0% precision) và giữ 27/30 (90.0% recall), tiết kiệm 0.486 USD và 22,032.0 ms, vượt xa tau = 0.98 (6.67% recall).
Bài tập 4 — Vượt Bẫy RPM=60 Bằng Dual TPM Bucket, threading.Lock và try/finally Refund 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Theo dõi pha dự trữ toàn bộ prompt_tokens + max_tokens dưới khóa threading.Lock, kiểm tra kết quả cluster_tpm_bucket.try_consume, hoàn trả phần dư trong khối try / finally, ngưỡng interactive_reserve_tokens = 12,000 và cờ app.state.allow_test_clock.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_12 or test_15 or test_16 or test_17" -v và xem rpm_trap_vs_tpm_budget trong artifacts/t2_ch18_wb18_results.json.
Tiêu chí Đáp án & Số đối chứng
RPM=60 để lọt 3/3 gói 64k (192,090 token, đốt 0.9605 USD). Dual TPM + USD Budget giữ đủ prompt_tokens + max_tokens dưới threading.Lock, chặn vượt mức bằng HTTP 429 (Retry-After: 12), hoàn trả phần dư qua try / finally, khóa chi tiêu tenant alpha tại 0.1426 USD và giữ 100.0% (5/5) SLA cho interactive.
Bài tập 5 — Bảo mật Biên, Request-Scoped PiiVault Luhn và Dịch Đa Nhà cung cấp 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra thứ tự lọc 401/403 (API Key, CIDR IP, Geo-fence), một PiiVault theo vòng đời request chạy qua toàn bộ payload.messages ([PII_EMAIL_1], [PII_EMAIL_2]) kèm kiểm tra Luhn is_valid_luhn, và translate_openai_to_bedrock / translate_openai_to_vertex.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_10 or test_11 or test_13 or test_14 or test_18 or test_19" -v.
Tiêu chí Đáp án & Số đối chứng
Cổng chặn IP ngoài CIDR và quốc gia KP/XX bằng 403, ánh xạ DE -> eu-west, dùng một PiiVault gắn cả request che xuyên suốt mọi tin nhắn (cùng Luhn card check, 0 leak upstream & OTel) và tái lập hoàn chỉnh cho client, đồng thời dịch hai chiều chuẩn xác giữa OpenAI, AWS Bedrock Converse và GCP Vertex AI.
Bài tập 6 — W3C traceparent, Shadow BackgroundTasks, Envoy AI Gateway và Kiểm định 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Đối chiếu parse_or_create_traceparent, assign_ab_bucket (blake2b mod 100), nhân bản Shadow bất đồng bộ qua FastAPI BackgroundTasks, và kiến trúc NGINX / Envoy AI Gateway (AIGatewayRoute, AIServiceBackend, GAIE EPP qua ext_proc) + LiteLLM.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy trọn bộ run_lab_demo.py, ruff check src scripts tests, mypy src tests, pytest -p no:cacheprovider -v, và uv lock --check.
Tiêu chí Đáp án & Số đối chứng
Gateway bảo toàn trace_id 4bf92f3577b34da6a3ce929d0e0e4736 trên traceparent, ghi 81 OTel spans sạch PII vào BoundedInMemorySpanExporter, chia A/B bám dính (variant_a: 7, variant_b: 2), bắn 3 Shadow bất đồng bộ qua BackgroundTasks, 0 # type: ignore và đạt 30/30 pytest pass (0 skip).