Chương 26 — Bản thiết kế Đồ án Tổng hợp Kỹ nghệ Hệ thống Dữ liệu & AI Chuẩn Sản xuất (RecSys-MLops, Card-Fraud-Platform & Agentic-LLM-Platform)
Tích hợp toàn trình RecSys-MLops và Card-Fraud-Platform cùng Agentic-LLM: tối ưu E2E p99 12.89x–16.5x và giảm 76.63%–90.34% FinOps TCO, vượt 6/6 kịch bản bơm lỗi (Watermarks, PIT #15, Bursty GPU 10x, MCP Sandbox, Canary mSPRT #16, Nhãn trễ KM IPCW #17), 6 miền 100 điểm ngưỡng >= 80 & 6 HD (14 spans).
Unit ID:
T2-P5-U03
Track & Part: Track 2 (EDAI) — Part 5: MLOps, LLMOps, CI/CD & Full-Stack Observability (part-05-mlops-cicd-and-observability)
Cầu nối Xuyên Track (Part 1–5\(\to\)Final Engineering Project): Sau khi nắm vững nền tảng Linux/Python/WebAPI/Docker (Phần 1), đường ống dữ liệu streaming/Lakehouse/Feature Store (Phần 2), hạ tầng phân tán K8s/IaC/Vault/AI Gateway (Phần 3), động cơ phục vụML/LLMđa GPU (Phần 4), vàCI/CD/CT+ Quan sát toàn phần + Nhãn trễSRE(Chương 24 & Chương 25), Chương 26 tổng hợp trọn vẹn năm mặt phẳng kỹ thuật thành một kiến trúc tham chiếu sản xuất thống nhất cho Dự án Cuối khóa (capstones-production-platform).
Truy xuất Giáo trình Gốc (Final Coursework — Engineering Project& Chuyên đề#15–#35): Thiết kế và triển khai hệ thống Data + ML/LLM/Agent có khả năng mở rộng, tin cậy cao, bảo mật (Sandbox,Vault,mTLS), tối ưu chi phí (FinOps), xử lý dữ liệu đến muộn, đồng nhất đặc trưng (#15), canary (#16), nhãn trễ (#17) và phục vụSLO(#18–#35) 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-Ch26): labs/ch26-production-platform-capstone-workbench/README.md (production_platform_capstone_lab)
Tình huống Mở đầu: Vì sao Các Hệ thống "Chạy Xanh Trên Laptop" Đều Sập Khi Hợp nhất Ra Sản xuất?#
Khi ghép từng mảnh rời rạc từ Phần 1–5 thành một nền tảng sản xuất thực tế như hệ thống gợi ý RecSys-MLops, hệ thống chống gian lận thẻ card-fraud-platform, hay trợ lý tác nhân Agentic-LLM-Platform, 90% sự cố nghiêm trọng không nằm trong mô hình mà phát sinh tại bốn điểm đứt gãy xuyên tầng:
- Cộng hưởng Hàng đợi Xuyên Tầng Làm Vỡ Đuôi
p99& Đốt Gấp10xNgân sáchFinOps: Trong thực nghiệm mô phỏng4,000yêu cầu củaWB-Ch26(seed=42), một kiến trúc nguyên khối không tối ưu (naive_monolith) chạmp99 = 10233.99 ms(2.0%đạtSLO <= 900 ms,$1248.65/1M reqs) choAgentic-LLM-Platform;p99 = 1186.86 ms(4.88%đạtSLO <= 120 ms,$47.72/1M reqs) choRecSys-MLops; vàp99 = 510.99 ms(0.0%đạtSLO <= 45 ms,$32.62/1M reqs) choCard-Fraud-Platform. Chỉ khi tối ưu đồng bộ cache ngữ nghĩa/đặc trưng, tách rờiPrefill/Decode,MicrobatchingvàSpot + Quantized FinOps,SOTA 2026 Platformmới rútp99xuống794.22 ms(12.89xnhanh hơn,-90.34%TCO),86.34 ms(13.75x,-76.63%TCO) và30.97 ms(16.5x,-73.02%TCO)! - Sáu Đòn Tấn công & Suy thoái Sản xuất Mà Kiểm thử Đơn vị Không Bao giờ Bắt Được:
- Gói tin ngân hàng đến muộn
3–17.5phút làm watermark ngây thơ1phút đánh rơi694/6,000sự kiện (11.79%sai lệch doanh thu). - Nối đặc trưng lịch sử không khóa thời gian (
PIT #15) làm rò rỉ29.07%dữ liệu tương lai (offline AUC = 0.841ảo \(\to\)online AUC = 0.7846). - Bão tải
10xđẩyGoodputcụm GPU tĩnh sụp xuống15.58%(p99 = 2509.15 ms). - Agent
MCPchạy không sandbox chỉ chặn được2/8(25.0%) vector tấn công và để rò3bí mật quaSSRF/env. - Phát hành
Big-Bang 100%làm hỏng3,000yêu cầu (351lỗi) thay vì ngắt tự động ở nấc5%(SPRT,-99.2%bán kính nổ). - Nhãn gian lận (
chargeback) trễ trung vị28ngày tạo ảo giác90.53%(+24.49 pp) so với độ chính xác thật66.04%(#17).
- Gói tin ngân hàng đến muộn
- Điểm Cao Về Tính năng Nhưng Bị Phủ quyết Vì Lỗ hổng Bảo mật / Rò rỉ (
Hard Disqualifiers): Một bài nộp Capstone (insecure_latest_agent_submission) có thể đạt83.0/100điểm thô trên6miền kỹ thuật (>= 80.0), nhưng chỉ cần để Agent chạy thiếu sandbox hoặc dùng thẻ:latest, cổng kiểm định vẫn đánh rớtDISQUALIFIED(0.0điểm hiệu lực)! - Thiếu Hợp đồng Sẵn sàng
FastAPI+OTelKhông RòPII: Khi tích hợp hệ thống giám sát, chỉ cần một chuỗi nhật ký hoặc thuộc tínhOpenTelemetryđể lọt email, số thẻ haysk-...API key, toàn bộ bản phát hành phải bị từ chối ở cổngCI.
Mục tiêu Học tập (Learning Objectives)#
Sau Chương 26 và WB-Ch26 (production_platform_capstone_lab), kỹ sư Hệ thống Dữ liệu & AI làm chủ năm năng lực cấp Kiến trúc sư Nền tảng:
- Hợp nhất Toàn bộ Kiến trúc Năm Mặt phẳng Track 2: Thiết kế và kết nối trơn tru
Data/Lakehouse/PIT (#15)\(\leftrightarrow\)K8s/IaC/Vault/MCP Sandbox\(\leftrightarrow\)AI Gateway/vLLM Serving (#18–#35)\(\leftrightarrow\)4-Way Versioning/Canary (#16)\(\leftrightarrow\)OTel/Langfuse/Late-Label SRE (#17). - Định lượng Độ trễ Đuôi Xuyên Tầng & Ngân sách
FinOps TCO: Phân tích mô hình cộng hưởng nghẽn hàng đợiM/G/1, tối ưu tỷ lệ trúngSemantic Cache/Feastvà chiến lược GPU (Spot + FP8 + Disagg P/D) cho ba mẫu hình thực chiếnRecSys-MLops,Card-Fraud-Platform, vàAgentic-LLM-Platform. - Tổng hợp Kiến trúc Tham chiếu
RecSys-MLops&card-fraud-platform: Ánh xạ chính xác các yêu cầu nghiệp vụ thực tế từ hai kho mã chuẩn của chương trình vào từng thành phần công nghệ cụ thể (Flink,ClickHouse,Feast,Triton,vLLM,MCP Sandbox,Evidently,IPCW/HT). - Thiết kế Bộ Kiểm thử Tiêm lỗi
6Kịch bản Sẵn sàng Sản xuất: Triển khai bài kiểm chứng tự động cho Dữ liệu trễ (Ch 10),PIT Skew (#15), Bão GPU10x (#21/#22), Cô lậpMCP Sandbox, Hoàn tácSPRT (#16)và Giám sát Nhãn trễ (#17). - Vận hành Thang điểm
100Điểm Phủ quyết Cứng & Dịch vụ Kiểm soátFastAPI+OTel: Xây dựng cổng/health/live,/health/ready,/audit/e2e,/metrics, kiểm toán tệp cấu hình YAML (0:latest,127.0.0.1,0bí mật) và xác minh0rò rỉPIItrên cây spanOpenTelemetry.
Bảng Truy xuất Tổng hợp Toàn Khóa Track 2 (Unit T2-P5-U03)#
Mặt phẳng Nền tảng (Track 2) |
Chương & Chuyên đề Nguồn | Trọng tâm Áp dụng Trong Đồ án Capstone | Tạo tác & Kiểm chứng (WB-Ch26) |
|---|---|---|---|
1. Dữ liệu, Streaming & PIT (Part 2, #15) |
Ch 07–12, Ch 11 (#15) |
Kafka KRaft + Debezium CDC \(\to\) Flink Event-Time (18m horizon) \(\to\) Iceberg + ClickHouse + Feast Redis nối ASOF PIT (0.0% rò rỉ) |
capstone_platform_topology.yaml, S1 & S2, Tests 10–11 |
2. K8s, IaC, Vault, mTLS & MCP Sandbox (Part 1 & 3) |
Ch 06, Ch 15, Ch 19 | 19 ảnh chính thức ghim phiên bản (0 :latest, python:3.12.8-slim-bookworm), cổng host 127.0.0.1:, Vault lease động, Istio STRICT mTLS, MCP Sandbox (cap_drop=ALL, read_only_root_fs, pids_limit: 64, egress_allowlist DNS nội bộ .svc.cluster.local) |
audit_topology_yaml, S4, Tests 03–04, 13, 30 |
3. AI Gateway & Phục vụ ML/LLM (Part 3–4, #18–#35) |
Ch 18, Ch 20–23 | P2C-EWMA, Dual TPM/USD, Semantic Cache (0.94), KEDA + Admission Control, Disagg P/D, FP8, Wide-EP, Load-Bounded (1.25x), Piecewise CUDA Graphs |
simulate_archetype_e2e, S3, Tests 05–09, 12 |
4. MLOps, Phiên bản 4 Chiều & Canary (Part 5, #16) |
Ch 24 (#16) |
Khóa SHA-256 4 chiều (Git/DVC/MLflow 3.0/Prompt), cổng Worst-Slice + ECE + p99, Shadow Mirror & Canary SPRT/mSPRT cắt -99.2% bán kính nổ |
S5, evaluate_capstone_rubric, Tests 14, 16–19, 29–30 |
5. Quan sát Toàn phần, Nhãn Trễ & SRE (Part 5, #17) |
Ch 25 (#17) |
2-tier OTel Collector (loadbalancing \(\to\) tail_sampling) + Prom 3.0 (nhãn lực lượng thấp, Native Histograms) + ELK + Jaeger + Langfuse (v1.37+, RAGAS), KM-IPCW + Pred PSI + Audit HT (-39d), FastAPI live /audit/e2e & 0 PII leak |
S6, create_capstone_app, Tests 15, 20–31 |
6. Bảo vệ Live Chaos & Kiểm toán FinOps TCO |
final-engineering-capstone-spec.md (§5–§7) |
Bảo vệ trực tiếp 6/6 kịch bản bơm lỗi (S1–S6), kiểm toán TCO /1M reqs & /1M tokens (-73% đến -90%), chấm theo chuẩn thống nhất >= 80.0 / 100 |
run_failure_injection_suite, Tests 10–15, 25–31 |
Bảng Ký hiệu Thống nhất Xuyên suốt Chương 26 (Unified Notation)#
| Ký hiệu | Miền / Đơn vị | Định nghĩa Chính xác Trong Chương 26 & production_platform_capstone_lab |
Giá trị Thực nghiệm WB-Ch26 (seed=42) |
|---|---|---|---|
| \(T_{\text{E2E}}(p_{99})\) | \(\text{ms}\) | Phân vị 99% độ trễ xuyên \(K=4\) chặng có tính nghẽn hàng đợi \(\phi(\rho_k)\) và cache \(h_{\text{cache}}\) |
RecSys: 86.34, Fraud: 30.97, Agentic: 794.22 |
| \(\text{TCO}_{1\text{M}}\) | \(\text{USD}/10^6\) | Tổng chi phí sở hữu cho \(10^6\) yêu cầu (GPU + Data/Feature + Gateway/Egress + Obs/Audit) |
RecSys: $11.15 (-76.63%), Fraud: $8.80, Agentic: $120.57 (-90.34%) |
| \(\phi(\rho_k)\) | Hệ số \(\ge 1\) | Hệ số khuếch đại độ trễ hàng đợi M/G/1 \(1 + \frac{\rho_k^2}{1 - \min(\rho_k, 0.96)}\) | Đẩy Naive \(\rho=0.89\) thành nổ đuôi 10233.99 ms |
| \(\text{Leak}_{\text{PIT}}, \text{PSI}\) | \(\%, [0, \infty)\) | Tỷ lệ rò rỉ tương lai ở tập huấn luyện (#15) và phân kỳ đặc trưng huấn luyện–phục vụ |
Naive: 29.07% leak (0.0699) vs SOTA: 0.0% (0.001) |
| \(R_{\text{blast}}, \Lambda_n\) | \(\%\), Log-odds | Giảm bán kính nổ của Progressive Canary + Wald SPRT/mSPRT (#16) tại biên dừng \(A = 4.554\) |
Ngắt bước 5% (LLR = 4.698), giảm 99.2% bán kính nổ |
| \(S_{\text{cap}}, D_{\text{hard}}\) | \([0, 100]\), Cờ | Điểm Capstone qua 6 miền (15, 15, 20, 15, 15, 20) (đạt >= 80.0) và 6 điều kiện loại trực tiếp (HD-1..HD-6) |
Flagship: 96.4/100 (CERTIFIED); Insecure 83.0 \(\to\) 0.0 (DISQUALIFIED) |
Trụ cột 1 — Kiến trúc Tổng thể Năm Mặt phẳng, Kinh tế Học E2E & Tổng hợp RecSys-MLops / card-fraud-platform#
1.1 Bản đồ Kiến trúc Hợp nhất Năm Mặt phẳng Track 2#
Một nền tảng Data + AI chuẩn sản xuất SOTA 2026 không phải tập hợp các script tách rời, mà là một vòng phản hồi khép kín qua năm mặt phẳng liên kết bằng hợp đồng dữ liệu, hợp đồng bảo mật và định danh truy vết trace_id:
1.2 Toán học Cộng hưởng Độ trễ Xuyên Tầng & Tổng Chi phí FinOps TCO#
Giả sử một yêu cầu đi qua \(K\) tầng nối tiếp \(S_1, \dots, S_K\). Với xác suất trúng bộ nhớ đệm tầng biên \(h_{\text{cache}} \in [0, 1)\), độ trễ đầu-cuối tuân theo phân phối hỗn hợp:
trong đó hệ số khuếch đại nghẽn hàng đợi \(\phi(\rho_k) = 1 + \frac{\rho_k^2}{1 - \min(\rho_k, 0.96)}\) giải thích vì sao giữ mức tải \(\rho_k \approx 0.88\) tưởng tiết kiệm máy lại đánh sập toàn hệ thống:
- Ở \(\rho = 0.45\), hệ số nghẽn là \(\phi(0.45) = 1.37\times\).
- Khi thiếu
Microbatchinghoặc thiếuAdmission Controlđẩy \(\rho \to 0.89\), hệ số nghẽn vọt lên \(\phi(0.89) = 8.20\times\) — nhân gấp6xđộ trễ gốc ở từng tầng và cộng hưởng thành thảm họap99!
Song song với độ trễ, phương trình FinOps TCO cho mỗi 1,000,000 yêu cầu phơi bày cấu trúc chi phí thực tế:
Bốn đòn bẩy đồng thời trong SOTA 2026 (Semantic/Feature Cache, Spot + Reserved GPU giảm \(\sim 55\%\) đơn giá giờ, FP8/Microbatching/Disagg P/D tăng 3–4x RPS/GPU, và Tail-Based Sampling + Data Locality) không chỉ hạ p99 từ 12.89x đến 16.5x mà còn cắt 73%–90% tổng chi phí vận hành.
1.3 Tổng hợp Kiến trúc Ba Mẫu hình Thực chiến: RecSys-MLops, card-fraud-platform & Agentic-LLM-Platform#
| Tiêu chí Kiến trúc | RecSys-MLops (itsmekhoathekid/RecSys-MLops) |
Card-Fraud-Platform (cvinhnguyen/card-fraud-platform) |
Agentic-LLM-Platform (SOTA 2026 Agentic Stack) |
|---|---|---|---|
Ngân sách SLO Đuôi |
p99 <= 120.0 ms |
p99 <= 45.0 ms (ngặt nhất) |
p99 <= 900.0 ms (đa lượt MCP + LLM) |
| Điểm Nghẽn Mật độ Cao | Truy vấn đặc trưng tuần tự + chấm điểm 200 ứng viên không microbatch |
Nối PIT trễ + tổng hợp cửa sổ trượt không Flink RocksDB |
Vòng lặp Prefill chặn Decode + MCP thiếu cache/sandbox + GPU On-Demand |
| Chốt chặn Kỹ thuật Chủ đạo | Feast + ClickHouse song song, ANN HNSW, Triton microbatching + 38% cache + MCP giải thích có sandbox |
Kafka + Debezium + Flink 18m watermark, ASOF PIT (0% leak), ONNX ensemble, #17 IPCW + Audit HT |
Envoy AI Gateway (SemCache 34%, Dual TPM/USD), MCP Sandbox, Disagg P/D + FP8 + CUDA Graphs |
Kết quả Đo WB-Ch26 (Naive \(\to\) SOTA) |
p99: 1186.86 -> 86.34 ms (13.75x), SLO: 4.88% -> 100.0%, TCO: $47.72 -> $11.15 (-76.63%) |
p99: 510.99 -> 30.97 ms (16.5x), SLO: 0.0% -> 100.0%, TCO: $32.62 -> $8.80 (-73.02%) |
p99: 10233.99 -> 794.22 ms (12.89x), SLO: 2.0% -> 99.78%, TCO: $1248.65 -> $120.57 (-90.34%) |
Trụ cột 2 — Kiểm toán Tiêm lỗi 6 Kịch bản, Thang điểm 100 Điểm Phủ quyết Cứng & Cổng FastAPI + OTel#
2.1 Sáu Kịch bản Tiêm lỗi Bắt buộc Trước Khi Cấp phép Sản xuất#
Thay vì chỉ trình diễn happy path, mọi đồ án Capstone phải vượt qua cả 6 bài kiểm chứng tiêm lỗi thực địa trong end_to_end_architecture_audit.py:
Kịch bản (WB-Ch26) |
Tác nhân Gây sự cố Đưa vào | Kết quả Hệ thống Ngây thơ | Kết quả SOTA 2026 Platform |
|---|---|---|---|
S1: Dữ liệu Đến Trễ (Ch 10) |
12% trong 6,000 sự kiện đến trễ 3–17.5 phút |
Watermark 1m rơi 694 sự kiện (88.43% đủ, 11.79% MAPE) |
Event-Time 10m + 8m allowedLateness + DLQ đạt 100.0% (0 rơi, 0.0% MAPE) |
S2: Lệch PIT (#15, Ch 11) |
28% bản ghi cập nhật sau giờ giao dịch (look-ahead) |
Rò 29.07% tương lai, tụt AUC 0.841 -> 0.7846 (PSI=0.0699) |
Nối ASOF PIT: 0.0% rò rỉ, AUC 0.7846 -> 0.7841 (PSI = 0.001) |
S3: Bão GPU 10x (#21/#22) |
Bùng nổ 2,400 yêu cầu (1,500 interactive + 900 batch) |
Cụm tĩnh vỡ 15.58% Goodput, p99 = 2509.15 ms |
KEDA + Admission Control (xả 60.89% batch) giữ 100.0% Goodput (101.06 ms) |
S4: Cô lập MCP Sandbox |
8 vector tấn công (env dump, SSRF 169.254, /etc, K8s token, DNS exfil...) |
Chặn 2/8 (25.0%), rò 3 bí mật |
cap_drop=ALL + RO root + seccomp + pids_limit: 64 + DNS egress_allowlist (.svc.cluster.local, cấm 127.0.0.1 trong container) chặn 8/8 (100.0%), 0 rò rỉ |
S5: Hoàn tác SPRT (#16, Ch 24) |
Đẩy bản lỗi 12% error rate trên 3,000 lượt |
Big-Bang 100% dính trọn 351 lỗi |
Progressive Canary + SPRT (A=4.554) ngắt ở bước 5% (LLR=4.698), -99.2% bán kính nổ (348 lỗi được cứu) |
S6: Nhãn Trễ (#17, Ch 25) |
Y=0 về ~4.2d, Y=1 trễ ~28.3d dưới Silent Drift |
Naive = 90.53% (+24.49 pp ảo giác so với 66.04%) |
Pred PSI = 0.4511, dH = +0.1159, KM-IPCW = 79.08%, Audit HT = 62.95% (3.09 pp lỗi, sớm 39 ngày) |
2.2 Thang điểm Kiến trúc 6 Miền 100 Điểm (Đạt >= 80.0) Kèm 6 Lỗi Phủ quyết (HD-1..HD-6)#
Một nền tảng có điểm trung bình cao vẫn gây thảm họa nếu vi phạm ranh giới an toàn cốt lõi. Do đó capstone_service_and_rubric.py và final-engineering-capstone-spec.md dùng duy nhất một hợp đồng chấm điểm thống nhất: 6 miền (15, 15, 20, 15, 15, 20) = 100 điểm, ngưỡng đạt >= 80.0 / 100, kết hợp 6 điều kiện phủ quyết tuyệt đối (HD-1..HD-6) và kiểm toán hành vi audit_behavioral_submission:
Trụ cột 3 — Công nghệ 2026 & Mã nguồn Python Độc lập (100% Khả thi Trong .venv)#
Đoạn mã độc lập dưới đây chạy trực tiếp trong .venv (numpy, fastapi, opentelemetry-sdk, pydantic, TestClient), tái hiện trọn vẹn ba bất biến đầu-cuối của Chương 26: (1) Hiệu năng & TCO Agentic-LLM-Platform vs Naive Monolith; (2) Hai chốt chặn sống còn PIT Skew (#15) + Canary Wald SPRT (#16); và (3) Dịch vụ kiểm soát sẵn sàng FastAPI (/health/ready, /audit/e2e, /metrics) với cây 4 span OpenTelemetry, kiểm định Hard Disqualifier và 0 rò rỉ PII.
from __future__ import annotations
import json
import math
import re
from collections.abc import Sequence
import numpy as np
from fastapi import FastAPI
from fastapi.testclient import TestClient
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor, SpanExporter, SpanExportResult
class LocalSpanCollector(SpanExporter):
def __init__(self) -> None:
self.spans: list[ReadableSpan] = []
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
self.spans.extend(spans)
return SpanExportResult.SUCCESS
def shutdown(self) -> None:
return None
def simulate_e2e_tier(mean_ms: float, rho: float, cache_hit: float, gpu_hr_usd: float, rps: float, seed: int) -> tuple[float, float]:
rng = np.random.default_rng(seed)
n = 3000
cong = 1.0 + (rho * rho) / (1.0 - min(rho, 0.96))
sigma = 0.42 if rho > 0.7 else 0.24
mu = math.log(mean_ms * cong) - 0.5 * sigma * sigma
raw_ms = rng.lognormal(mean=mu, sigma=sigma, size=n)
e2e = np.where(rng.random(n) < cache_hit, 12.5, raw_ms)
p99 = float(np.percentile(e2e, 99))
tco_gpu = (gpu_hr_usd * 1_000_000.0 / (rps * 3600.0)) * (1.0 - cache_hit)
return round(p99, 2), round(tco_gpu, 2)
def demo_pillar3_capstone(seed: int = 42) -> None:
# 1. Cross-Layer E2E p99 & GPU FinOps TCO (Naive vs SOTA)
naive_p99, naive_tco = simulate_e2e_tier(520.0, rho=0.88, cache_hit=0.02, gpu_hr_usd=28.0, rps=6.5, seed=seed)
sota_p99, sota_tco = simulate_e2e_tier(255.0, rho=0.52, cache_hit=0.34, gpu_hr_usd=13.6, rps=24.5, seed=seed + 1)
assert sota_p99 < naive_p99 / 5.0 and sota_tco < naive_tco / 5.0
print(f"[1. E2E + FinOps] Naive p99={naive_p99}ms (${naive_tco}/1M) -> SOTA p99={sota_p99}ms (${sota_tco}/1M)")
# 2. Canary Wald SPRT Auto-Rollback (#16)
rng = np.random.default_rng(seed)
p0, p1, boundary_a = 0.01, 0.08, math.log(0.95 / 0.01)
llr, exposed, errs = 0.0, 0, 0
for is_err in rng.random(3000) < 0.12:
exposed += 1
if bool(is_err):
errs += 1
llr += math.log(p1 / p0)
else:
llr += math.log((1.0 - p1) / (1.0 - p0))
if llr >= boundary_a:
break
blast_cut = (1.0 - exposed / 3000.0) * 100.0
assert blast_cut > 95.0
print(f"[2. SPRT Rollback] Tripped after {exposed}/3000 reqs ({errs} errs, LLR={llr:.2f}) -> -{blast_cut:.2f}% blast radius")
# 3. Live FastAPI Capstone Audit (6 Domains, >= 80, 6 HD, perf_counter) + OTel Zero-PII
import time
collector = LocalSpanCollector()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(collector))
tracer = provider.get_tracer("pillar3_capstone")
app = FastAPI()
@app.post("/audit/e2e")
def audit_endpoint(payload: dict[str, object]) -> dict[str, object]:
t0 = time.perf_counter()
note = re.sub(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", "[REDACTED_EMAIL]", str(payload.get("note", "")))
unsandboxed = bool(payload.get("unsandboxed_mcp", False))
raw_score = float(payload.get("raw_score", 95.0))
status = "DISQUALIFIED" if unsandboxed else ("CERTIFIED_PRODUCTION_READY" if raw_score >= 80.0 else "NEEDS_REMEDIATION")
with tracer.start_as_current_span("capstone.audit.request") as sp:
sp.set_attribute("capstone.status", status)
sp.set_attribute("capstone.effective_score", 0.0 if unsandboxed else raw_score)
sp.set_attribute("capstone.trace_note_redacted", note)
elapsed_ms = max(0.001, (time.perf_counter() - t0) * 1000.0)
return {"status": status, "note": note, "duration_ms": round(elapsed_ms, 3)}
with TestClient(app) as client:
r_ok = client.post("/audit/e2e", json={"raw_score": 80.0, "unsandboxed_mcp": False, "note": "owner an.nguyen@example.com"})
r_mid = client.post("/audit/e2e", json={"raw_score": 79.0, "unsandboxed_mcp": False, "note": "borderline"})
r_bad = client.post("/audit/e2e", json={"raw_score": 83.0, "unsandboxed_mcp": True, "note": "unsafe mcp"})
assert r_ok.json()["status"] == "CERTIFIED_PRODUCTION_READY" and r_ok.json()["duration_ms"] > 0.0
assert r_mid.json()["status"] == "NEEDS_REMEDIATION"
assert r_bad.json()["status"] == "DISQUALIFIED"
dumped = json.dumps([dict(s.attributes or {}) for s in collector.spans])
assert "an.nguyen@example.com" not in dumped and len(collector.spans) == 3
print(f"[3. Live Audit + OTel] Spans={len(collector.spans)} | >=80 Threshold, Hard Disqualifier & Zero PII verified!")
if __name__ == "__main__":
demo_pillar3_capstone(seed=42)
print("Pillar 3 Capstone End-to-End Verification PASSED!")
Trụ cột 4 — Thực hành Công nghiệp (WB-Ch26: production_platform_capstone_lab) & Kết quả Thực nghiệm#
4.1 Kiến trúc Hai Tầng WB-Ch26 (labs/ch26-production-platform-capstone-workbench/)#
- Tầng 1 — Cấu hình Hạ tầng Hợp nhất Năm Mặt phẳng (
configs/capstone_platform_topology.yaml):- Khai báo
19dịch vụ xuyên suốtingestion_lakehouse(Kafka KRaft,Debezium,Flink,Iceberg/MinIO,ClickHouse,Feast/Redis,Airflow),security_k8s_sandbox(Vault,Istio ambient mTLS,mcp_tool_sandboxdùng ảnh chính thứcpython:3.12.8-slim-bookwormkèmcap_drop: [ALL],read_only_root_fs: true,run_as_uid: 65532,pids_limit: 64,egress_allowlisttrỏ DNS nội bộclickhouse.data-platform.svc.cluster.local:8123&redis.serving-platform.svc.cluster.local:6379),gateway_and_serving(Envoy AI Gateway,vLLM Disagg P/D,Triton),mlops_cicd_canary(MLflow 3.0,@champion/@challenger,SPRT/mSPRT [1, 5, 25, 50, 100]), vàobservability_sre(2-tier OTel Collector,Prometheus 3.2 Native Histograms,Jaeger,Langfuse,Elasticsearch). - Toàn bộ
19/19ảnh chính thức ghim phiên bản (0:latest,0image giả định),100%cổng host khóa về127.0.0.1:, và0bí mật văn bản thuần.
- Khai báo
- Tầng 2 — Gói Python
production_platform_capstone_lab(src/production_platform_capstone_lab/):end_to_end_architecture_audit.py: Mô phỏng xác định4,000yêu cầu/mỗi tầng choRecSys-MLops,Card-Fraud-Platform, vàAgentic-LLM-Platform, bộ tiêm lỗi6kịch bản (S1–S6) kèm kiểm chứng chính sách hành vievaluate_mcp_sandbox_policy, Kaplan–Meier IPCW, và kiểm toán hành viaudit_behavioral_submission.capstone_service_and_rubric.py: Động cơ chấm điểm thống nhất6miền(15, 15, 20, 15, 15, 20)=100điểm (đạt>= 80.0 / 100) kèm6điều kiện loại trực tiếp (HD-1..HD-6), bộ kiểm toánaudit_topology_yaml, và dịch vụFastAPIsống (/health/live,/health/ready,/audit/e2eđo bằngtime.perf_counter(),/metrics) phátOpenTelemetry SDKspans sạchPII.
4.2 Tóm tắt Kết quả Đo đạc Thực nghiệm (artifacts/t2_ch26_wb26_results.json, seed=42)#
Thực nghiệm (production_platform_capstone_lab) |
Thông số Đo được (Xác định seed=42) |
Bất biến Kỹ thuật Được Chứng minh |
|---|---|---|
Exp 1 (E2E Latency & FinOps TCO — 3 Mẫu hình) |
RecSys-MLops: p99 1186.86 -> 86.34 ms (13.75x), SLO 4.88% -> 100.0%, TCO $47.72 -> $11.15 (-76.63%); Card-Fraud: p99 510.99 -> 30.97 ms (16.5x), SLO 0.0% -> 100.0%, TCO $32.62 -> $8.80 (-73.02%); Agentic-LLM: p99 10233.99 -> 794.22 ms (12.89x), SLO 2.0% -> 99.78%, TCO $1248.65 -> $120.57 (-90.34%) |
Tối ưu đồng bộ cache + hàng đợi + Disagg P/D + Spot/FP8 giải quyết đồng thời đuôi p99 và ngân sách FinOps |
Exp 2 (6/6 Failure-Injection Suite) |
S1 Watermark: 88.43% -> 100.0% (0 rơi); S2 PIT #15: 29.07% -> 0.0% rò rỉ (PSI=0.001); S3 10x Surge: 15.58% -> 100.0% Goodput (101.06 ms); S4 MCP Sandbox: 25.0% -> 100.0% (8/8 chặn, 0 leak, DNS-only egress); S5 SPRT #16: ngắt ở 5% (LLR=4.698, -99.2% blast, cứu 348 lỗi); S6 Nhãn trễ #17: Naive 90.53% (+24.49 pp) vs KM-IPCW 79.08% & Audit HT 62.95% (3.09 pp err, sớm 39d) |
Mỗi lớp trong 5 mặt phẳng đều có chốt chặn định lượng chống gãy đổ thực tế |
Exp 3 (100-Pt 6-Domain Rubric & Behavioral/YAML Audit) |
sota_flagship_submission: 96.4/100 (CERTIFIED_PRODUCTION_READY, ngưỡng >= 80.0); insecure_latest_agent_submission: điểm thô 83.0 nhưng bị phủ quyết về 0.0 (DISQUALIFIED); naive_monolith_submission: 45.5 -> 0.0 (4 disqualifiers); wb26_behavioral_topology_audit: 100.0/100; Topology: 19/19 dịch vụ chính thức (0 :latest, 0 bí mật, 127.0.0.1:, DNS egress_allowlist) |
Bảo mật & tính toàn vẹn dữ liệu có quyền phủ quyết tuyệt đối trước điểm hiệu năng |
Exp 4 (Live FastAPI + OTel + 0 PII) |
/health/live=200, /health/ready=200 (và 503 khi hỏng), /audit/e2e đo bằng time.perf_counter(), /metrics hợp lệ; 9 live + 5 suite = 14 OTel spans, 0 PII leaks |
Tự động hóa kiểm thử sẵn sàng sản xuất và vệ sinh telemetry trong CI |
4.3 Quy trình Kiểm định Tự động (32/32 Test Cases Pass, 0 Skipped, 0 # type: ignore)#
cd 03-track-2-data-and-ai-engineering/part-05-mlops-cicd-and-observability/labs/ch26-production-platform-capstone-workbench
PYTHONPATH=src python scripts/run_lab_demo.py --seed 42 --output artifacts/t2_ch26_wb26_results.json
ruff check src scripts tests
mypy --strict src tests
pytest -p no:cacheprovider -v
uv lock --check
Trụ cột 5 — Danh mục Tài liệu SOTA (6 Tài liệu) & Bài tập Chuyên sâu#
5.1 Tài liệu Đọc Kinh điển & Frontier 2022–2026#
- Huyen, Chip (2022–2025). Designing Machine Learning Systems & AI Engineering (O'Reilly). — Khung tư duy thiết kế nền tảng AI đầu-cuối, xử lý nhãn đến trễ (
#17), đồng nhất đặc trưng (#15), và phân tầng đánh đổi chi phí–độ trễ. - Kleppmann, Martin (O'Reilly). Designing Data-Intensive Applications. — Nền tảng lý thuyết về Event Time, Watermark, lưu trữ nhật ký bất biến, đồng thuận phân tán và chống mất dữ liệu.
- Beyer, Jones, Petoff & Murphy (Google SRE Workbook). Implementing SLOs & Multiwindow Multi-Burn-Rate Alerting. — Toán học ngân sách lỗi, đóng băng triển khai và quản trị độ tin cậy toàn hệ thống.
- vLLM / SGLang / Kwon et al. (SOSP 2023–2026). PagedAttention, RadixAttention, Disaggregated Prefill–Decode & Wide-EP Serving (
#18–#35). — Hệ thống phục vụ LLM đạt mục tiêu GoodputTTFT/TPOTvà tối ưu hóa phần cứng GPU. - Anthropic Model Context Protocol (MCP) & Cloud-Native Sandbox Architecture (2025–2026). Least-Privilege Tool Execution in Containers. — Thiết kế container không đặc quyền (
cap_drop: ALL,read_only_root_fs,seccomp, danh sách cho phépegress) và cấp khóa ngắn hạn quaHashiCorp Vault. - FSDS Track 2 Reference Architectures. RecSys-MLops và card-fraud-platform — Hai hình mẫu kiến trúc tham chiếu thực chiến cho hệ thống gợi ý đa chặng và chống gian lận thời gian thực.
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, 20%) — Tối ưu Độ trễ Đuôi Xuyên Tầng & Ngân sáchFinOps TCO(RecSys,Card-Fraud,Agentic-LLM): Dùng kết quảExp 1(Tests 05–09), phân tích vì sao tăng tải \(\rho\) từ0.45lên0.89trong công thức \(\phi(\rho)\) làmp99củaAgentic-LLM-Platformvọt lên10233.99 ms, và chứng minh cách tổ hợpSemantic Cache(34%) +Disagg P/D+Spot/FP8cắt TCO tới90.34%xuống$120.57/1M reqs.Thang điểm: Dẫn xuất đúng ảnh hưởng \(\phi(\rho)\) lên tích lũy chặng (
7%), giải trình cấu phần TCO cho cả3mẫu hình (7%), passTests 05–09(6%). -
Bài tập 2 (
ex2, 15%) — Xử lý Dữ liệu TrễFlink& Chống Rò rỉPoint-in-Time(S1&S2): Đối chiếuS1(late_data_watermark) vàS2(pit_training_serving_skew,#15,Tests 10–11): giải thích cơ chế khiến watermark1phút đánh rơi694giao dịch (11.79%MAPE) và cơ chế khiến phép nối không khóa thời gian làm rò29.07%tương lai (AUC 0.841 -> 0.7846).Thang điểm: Thiết kế đúng
Event Time + allowedLateness + DLQ(5%), chứng minh bất biếnASOF PIT\(t_{\text{feat}} \le t_{\text{event}} - \delta\) (5%), passTests 10–11(5%). -
Bài tập 3 (
ex3, 15%) — Điều khiển Thu nạp Bão10xGPU & Cô lậpMCP Sandbox(S3&S4): TrongS3(Tests 12) vàS4(Tests 13), giải thích tại saoAdmission Controlxả tải60.89%luồng batch lại cứu được100.0%Goodputtương tác dưới500 ms; đồng thời phân tích8vector tấn công lênMCPvà vai trò từng cờ bảo mật (cap_drop: [ALL],read_only_root_fs,egress_allowlist,Vault).Thang điểm: Chứng minh cơ chế bảo vệ đuôi tương tác (
5%), phân tích trọn vẹn8vector tấn côngMCP(5%), passTests 12–13(5%). -
Bài tập 4 (
ex4, 15%) — Hoàn tácCanary SPRT(#16) & Giám sát Nhãn Trễ (#17) (S5&S6): Phân tích kết quảS5(Tests 14) khiWald SPRTngắt bản hồi quy ngay ở bước5%(LLR = 4.698 >= 4.554, giảm99.2%bán kính nổ) vàS6(Tests 15) khiActive Audit HT(3.09 pplỗi) cộngPrediction PSI = 0.4511phát hiện trôi thầm lặng sớm39ngày so với ảo giác+24.49 ppcủaNaive.Thang điểm: Tính đúng ngưỡng
SPRT& bán kính nổ (5%), giải trình chuỗiIPCW+Proxy+Audit HT(5%), passTests 14–15(5%). -
Bài tập 5 (
ex5, 20%) — Thang điểm6Miền100Điểm (>= 80.0,6Phủ quyết) & Dịch vụFastAPI+OTelSạchPII: Phân tích lý doinsecure_latest_agent_submissionđạt83.0/100điểm thô trên6miền(15, 15, 20, 15, 15, 20)(>= 80.0) vẫn bị giáng về0.0(DISQUALIFIED,Tests 16–21); kiểm chứng luồng/health/live,/health/ready(200vs503),/audit/e2e(đo bằngtime.perf_counter(), hỗ trợbehavioral_evidence,4span phân cấp,0PII leak), và/metricstrênTestClient(Tests 22–24, 29–32).Thang điểm: Chứng minh tính hợp lý kỹ thuật của
Hard DisqualifiersHD-1..HD-6(7%), phân tích cây spanOTel& bảo vệPrometheus(7%), passTests 16–24, 29–32(6%). -
Bài tập 6 (
ex6, 15%) — Kiểm toán Cấu hình Toàn cụmYAML& Kiểm thử Tính Xác định (CI Gate): Kiểm tra cấu hìnhcapstone_platform_topology.yaml(19dịch vụ chính thức,0:latest,127.0.0.1:host bind, DNS-onlyegress_allowlist,0bí mật,Tests 03–04), thử nghiệm giả mạo tiêm:latest/0.0.0.0/sk-.../127.0.0.1trongegress_allowlist, và chạy sạch toàn bộ bộ kiểm địnhruff,mypy --strict,32pytest,uv lock --check(Tests 01–04, 25–32).Thang điểm: Phân tích đúng cơ chế chặn giả mạo YAML (
5%), thực thi đầy đủ chuỗi lệnh kiểm định CI (5%), passTests 01–04, 25–32(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— Cộng hưởng Hàng đợi & Tối ưuAgentic-LLM-Platform): TrongExp 1củaWB-Ch26, yếu tố nào giúpSOTA 2026 Platformcắt độ trễp99củaAgentic-LLM-Platformtừ10233.99 msxuống794.22 ms(12.89x) và giảm90.34%chi phíTCO? - (
q2— So sánh Điểm NghẽnRecSys-MLops&Card-Fraud-Platform): TheoWB-Ch26 Exp 1, điểm khác biệt cốt lõi về ngân sáchSLOvà cách tối ưu giữaRecSys-MLopsvớiCard-Fraud-Platformlà gì? - (
q3— Xử lý Dữ liệu TrễS1& Đồng nhấtPIT #15S2): Trong bộ tiêm lỗiS1vàS2, điều gì xảy ra với kiến trúc ngây thơ và cơ chế nào bảo toàn100.0%dữ liệu cùng0.0%rò rỉ tương lai? - (
q4— Bão GPU10x& Kiểm soát Thu nạp Ưu tiênS3): Khi lưu lượng tăng đột biến10xtrongS3(SLO = 500 ms), vì saoSOTA 2026 Platformchủ động từ chối một phần yêu cầubatch(60.89%) thay vì nhồi tất cả vào hàng đợi GPU? - (
q5— Cô lập Container Công cụMCP SandboxS4): Trong bài kiểm tra8vector tấn công lênMCPởS4, bộ biện pháp nào giúpSOTA MCP Sandboxchặn tuyệt đối8/8(100.0%) cuộc tấn công với0bí mật rò rỉ? - (
q6— Hoàn tácCanary SPRT#16& Nhãn Trễ#17S5–S6): Sự phối hợp giữaProgressive Canary + Wald SPRT(S5) vàActive Audit HT + Proxy PSI(S6) giải quyết hai bài toán rủi ro hậu phát hành nào trongWB-Ch26? - (
q7— Thang điểm6Miền100Điểm Kèm6Hard Disqualifiers): TrongExp 3, vì sao bài nộpinsecure_latest_agent_submissionđạt83.0/100(>= 80.0) điểm thô trên6miền(15, 15, 20, 15, 15, 20)vẫn bị cổng chấm điểm gán kết quảDISQUALIFIED(0.0điểm hiệu lực)? - (
q8— Dịch vụ Kiểm soátFastAPI, Cây SpanOTel& Vệ sinhYAML/PII): Bộ kiểm thửrun_capstone_service_and_otel_checksvàaudit_topology_yamltrongWB-Ch26xác minh những hợp đồng sản xuất bắt buộc nào?
Cross-Layer E2E p99 Latency Speedup (Naive Monolith / SOTA 2026)
FinOps TCO Comparison Across Archetypes ($ USD / 1M Requests)
6-Scenario Production Resilience: Naive vs SOTA 2026 Guarded (%)
100-Point Hard-Gated Capstone Scorecard Effective Scores
Exp 1: Cross-Layer E2E Latency (ms), SLO Satisfaction & FinOps TCO
| archetype_id | naive_p99_slo | sota_p99_slo | tco_naive_vs_sota | speedup_savings |
|---|---|---|---|---|
| RecSys-MLops | 1186.86 ms (4.88%) | 86.34 ms (100.0%) | $47.72 -> $11.15 | 13.75x | -76.63% |
| Card-Fraud-Platform | 510.99 ms (0.0%) | 30.97 ms (100.0%) | $32.62 -> $8.8 | 16.5x | -73.02% |
| Agentic-LLM-Platform | 10233.99 ms (2.0%) | 794.22 ms (99.78%) | $1248.65 -> $120.57 | 12.89x | -90.34% |
Exp 2: 6-Scenario Production Failure-Injection Audit Matrix
| scenario_id | naive_failure_mode | sota_2026_outcome | status |
|---|---|---|---|
| S1 late_data_watermark | Completeness=88.43%, MAPE=11.79% | Completeness=100.0%, MAPE=0.0% | PASS |
| S2 pit_training_serving_skew (#15) | Leak=29.07%, PSI=0.0699 | Leak=0.0%, PSI=0.001 | PASS |
| S3 bursty_gpu_surge_10x (#21/#22) | Goodput=15.58%, p99=2509.15 ms | Goodput=100.0%, p99=101.06 ms | PASS |
| S4 mcp_agent_sandbox_isolation | Blocked=25.0%, Leaks=3 | Blocked=100.0%, Leaks=0 | PASS |
| S5 canary_sprt_rollback (#16) | Exposed=3000, Fails=351 | Trips@5%, -99.2% blast | PASS |
| S6 delayed_label_ipcw_proxy (#17) | Naive=90.53% (+24.49 pp) | AuditHT=62.95% (3.09 pp err, -39d) | PASS |
Exp 3: 100-Point Hard-Gated Capstone Submission Benchmarks
| submission_id | archetype_id | raw_vs_effective | disqualifiers | verdict |
|---|---|---|---|---|
| sota_flagship_submission | Agentic-LLM-Platform | 96.4 -> 96.4 | none | CERTIFIED_PRODUCTION_READY |
| insecure_latest_agent_submission | RecSys-MLops | 83.0 -> 0.0 | latest_container_tag_used, unsandboxed_mcp_execution | DISQUALIFIED |
| naive_monolith_submission | Card-Fraud-Platform | 45.5 -> 0.0 | plaintext_secrets_present, pit_future_leakage_detected, missing_canary_rollback, missing_telemetry_or_pii_leak | DISQUALIFIED |
Exp 4: Live FastAPI Readiness, OTel Spans, PII Guard & YAML Audit
| component | verified_scope | observed_result | status |
|---|---|---|---|
| Topology YAML Security Audit | configs/capstone_platform_topology.yaml | 19 services, 19 pinned imgs, 0 :latest, 0 secrets, 127.0.0.1 | PASS |
| Live FastAPI /health/ready & /metrics | TestClient + Prometheus low-card metrics | ready=200, prom_ok=True | PASS |
| OpenTelemetry Spans & Zero PII Leak | /audit/e2e hierarchical spans + PII probe | 9 live + 5 suite spans, 0 PII leaks | PASS |
03-track-2-data-and-ai-engineering/part-05-mlops-cicd-and-observability/labs/ch26-production-platform-capstone-workbench
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "production-platform-capstone-lab"
version = "0.1.0"
description = "FSDS-SOTA-2026 Track 2 WB-Ch26: End-to-End Production Data, ML, LLM & Agent Capstone Blueprint Workbench (Cross-Layer E2E Latency/FinOps, 6-Scenario Failure Injection, 100-Point Hard-Gated Rubric, Live FastAPI Readiness & OTel Zero-PII Audit)"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115",
"httpx>=0.27",
"numpy>=1.26",
"opentelemetry-sdk>=1.28",
"pydantic>=2.0",
"pyyaml>=6.0",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[project.scripts]
fsds-capstone-lab = "production_platform_capstone_lab.capstone_service_and_rubric:main"
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src", "."]
addopts = "-v"
[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 = [
"yaml",
"hypothesis",
"hypothesis.*",
]
ignore_missing_imports = true
platform:
name: fsds-sota-2026-capstone-platform
version: "2026.1.0"
archetypes:
- RecSys-MLops
- Card-Fraud-Platform
- Agentic-LLM-Platform
bind_policy: loopback_only
services:
kafka_kraft:
plane: ingestion_lakehouse
image: apache/kafka:3.8.1
bind: 127.0.0.1:9092
replicas: 3
acks: all
auth_ref: ${KAFKA_SASL_SCRAM_REF:-vault://secret/data/kafka/local-dev}
debezium_cdc:
plane: ingestion_lakehouse
image: quay.io/debezium/connect:2.7.3.Final
bind: 127.0.0.1:8083
slot_name: fsds_pg_wal_slot
flink_stream_engine:
plane: ingestion_lakehouse
image: apache/flink:1.20.0-scala_2.12-java17
bind: 127.0.0.1:8081
watermark_strategy: bounded_out_of_orderness_10m
allowed_lateness_minutes: 8
state_backend: rocksdb_incremental
iceberg_minio_lakehouse:
plane: ingestion_lakehouse
image: minio/minio:RELEASE.2025-02-07T23-21-09Z
bind: 127.0.0.1:9000
table_format: apache_iceberg_v2
pit_asof_join_enforced: true
clickhouse_olap:
plane: ingestion_lakehouse
image: clickhouse/clickhouse-server:24.12-alpine
bind: 127.0.0.1:8123
feast_redis_online:
plane: ingestion_lakehouse
image: redis:7.4.2-alpine
bind: 127.0.0.1:6379
pit_parity_check_enabled: true
airflow_orchestrator:
plane: ingestion_lakehouse
image: apache/airflow:2.10.4-python3.12
bind: 127.0.0.1:8080
data_contract_circuit_breaker: true
vault_secrets_manager:
plane: security_k8s_sandbox
image: hashicorp/vault:1.18.4
bind: 127.0.0.1:8200
dynamic_lease_ttl_seconds: 900
istio_ambient_mtls:
plane: security_k8s_sandbox
image: docker.io/istio/pilot:1.24.2
bind: 127.0.0.1:15014
mtls_mode: STRICT
mcp_tool_sandbox:
plane: security_k8s_sandbox
image: python:3.12.8-slim-bookworm
bind: 127.0.0.1:8443
read_only_root_fs: true
run_as_non_root: true
run_as_uid: 65532
cap_drop:
- ALL
seccomp_profile: RuntimeDefault
pids_limit: 64
egress_allowlist:
- clickhouse.data-platform.svc.cluster.local:8123
- redis.serving-platform.svc.cluster.local:6379
auth_ref: ${MCP_VAULT_TOKEN_REF:-vault://secret/data/mcp/ephemeral}
envoy_ai_gateway:
plane: gateway_and_serving
image: docker.io/envoyproxy/gateway:v1.2.4
bind: 127.0.0.1:8000
load_balancer: p2c_ewma
semantic_cache_tau: 0.94
rate_limit_mode: dual_tpm_usd
pii_vault_redaction: true
vllm_disagg_serving:
plane: gateway_and_serving
image: vllm/vllm-openai:v0.7.3
bind: 127.0.0.1:8001
kv_cache_mode: paged_radix_prefix
disaggregated_prefill_decode: true
quantization: fp8_w8a8
piecewise_cuda_graphs: true
cache_aware_load_bound_factor: 1.25
triton_ml_serving:
plane: gateway_and_serving
image: nvcr.io/nvidia/tritonserver:25.01-py3
bind: 127.0.0.1:8002
dynamic_microbatching: true
mlflow_registry:
plane: mlops_cicd_canary
image: ghcr.io/mlflow/mlflow:v2.20.2
bind: 127.0.0.1:5000
four_way_sha256_manifest: true
model_aliases:
- champion
- challenger
canary_rollback_monitors:
- wald_sprt
- msprt
canary_sprt_steps_pct:
- 1
- 5
- 25
- 50
- 100
otel_collector:
plane: observability_sre
image: otel/opentelemetry-collector-contrib:0.119.0
bind: 127.0.0.1:4317
two_tier_loadbalancing_trace_id: true
genai_semantic_conventions: "1.37+"
ragas_eval_telemetry: true
pii_redaction_processor: true
tail_based_sampling: true
prometheus_tsdb:
plane: observability_sre
image: prom/prometheus:v3.2.0
bind: 127.0.0.1:9090
native_histograms_enabled: true
low_rps_zero_guard: true
forbid_high_cardinality_labels:
- user_id
- request_id
- trace_id
- span_id
- session_id
- email
slo_target: 0.999
burn_rate_critical_1h_5m: 14.4
jaeger_tracing:
plane: observability_sre
image: jaegertracing/all-in-one:1.66.0
bind: 127.0.0.1:16686
langfuse_llm_obs:
plane: observability_sre
image: langfuse/langfuse:3.25.0
bind: 127.0.0.1:3000
auth_ref: ${LANGFUSE_AUTH_REF:-vault://secret/data/langfuse/local-dev}
elasticsearch_logs:
plane: observability_sre
image: docker.elastic.co/elasticsearch/elasticsearch:8.17.2
bind: 127.0.0.1:9200
"""FSDS-SOTA-2026 Track 2 WB-Ch26: Production Platform Capstone Lab."""
from production_platform_capstone_lab.capstone_service_and_rubric import (
DOMAIN_WEIGHTS,
FORBIDDEN_HIGH_CARDINALITY_LABELS,
HARD_DISQUALIFIERS,
PASS_THRESHOLD_SCORE,
CapstoneAuditRequest,
CapstoneRubricSubmission,
PrometheusCapstoneMetrics,
audit_topology_yaml,
create_capstone_app,
create_in_memory_telemetry,
evaluate_capstone_rubric,
redact_pii,
run_capstone_rubric_benchmarks,
run_capstone_service_and_otel_checks,
)
from production_platform_capstone_lab.end_to_end_architecture_audit import (
ARCHETYPE_SPECS,
CapstoneBehavioralEvidence,
audit_behavioral_submission,
evaluate_mcp_sandbox_policy,
run_cross_layer_e2e_tco_suite,
run_failure_injection_suite,
simulate_archetype_e2e,
)
__all__ = [
"ARCHETYPE_SPECS",
"DOMAIN_WEIGHTS",
"FORBIDDEN_HIGH_CARDINALITY_LABELS",
"HARD_DISQUALIFIERS",
"PASS_THRESHOLD_SCORE",
"CapstoneAuditRequest",
"CapstoneBehavioralEvidence",
"CapstoneRubricSubmission",
"PrometheusCapstoneMetrics",
"audit_behavioral_submission",
"audit_topology_yaml",
"create_capstone_app",
"create_in_memory_telemetry",
"evaluate_capstone_rubric",
"evaluate_mcp_sandbox_policy",
"redact_pii",
"run_capstone_rubric_benchmarks",
"run_capstone_service_and_otel_checks",
"run_cross_layer_e2e_tco_suite",
"run_failure_injection_suite",
"simulate_archetype_e2e",
]
"""Cross-Layer E2E Latency/FinOps TCO Simulator & 6-Scenario Production Failure-Injection Auditor."""
from __future__ import annotations
import heapq
import math
import re
from collections import deque
from typing import Any
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
class StageLatencyConfig(BaseModel):
"""Latency distribution and utilization profile for one pipeline stage."""
model_config = ConfigDict(extra="forbid")
name: str
mean_ms: float = Field(gt=0.0)
sigma_log: float = Field(ge=0.05, le=1.5)
utilization_rho: float = Field(ge=0.05, lt=0.96)
tail_spike_prob: float = Field(ge=0.0, le=0.5)
tail_spike_ms: float = Field(ge=0.0)
class TierPlatformSpec(BaseModel):
"""Per-tier configuration (naive_monolith vs sota_2026_platform) for an archetype."""
model_config = ConfigDict(extra="forbid")
tier_id: str
cache_hit_rate: float = Field(ge=0.0, le=0.95)
cache_fastpath_ms: float = Field(gt=0.0)
stages: tuple[StageLatencyConfig, ...]
gpu_hourly_usd: float = Field(gt=0.0)
throughput_rps_per_gpu: float = Field(gt=0.0)
data_feature_usd_per_1m: float = Field(ge=0.0)
gateway_egress_usd_per_1m: float = Field(ge=0.0)
obs_audit_usd_per_1m: float = Field(ge=0.0)
class ArchetypePlatformSpec(BaseModel):
"""Complete platform spec comparing naive vs SOTA 2026 for a Track 2 capstone archetype."""
model_config = ConfigDict(extra="forbid")
archetype_id: str
reference_repo: str
slo_target_ms: float = Field(gt=0.0)
naive_monolith: TierPlatformSpec
sota_2026_platform: TierPlatformSpec
ARCHETYPE_SPECS: dict[str, ArchetypePlatformSpec] = {
"RecSys-MLops": ArchetypePlatformSpec(
archetype_id="RecSys-MLops",
reference_repo="https://github.com/itsmekhoathekid/RecSys-MLops",
slo_target_ms=120.0,
naive_monolith=TierPlatformSpec(
tier_id="naive_monolith",
cache_hit_rate=0.05,
cache_fastpath_ms=14.0,
stages=(
StageLatencyConfig(
name="gateway_auth",
mean_ms=11.0,
sigma_log=0.38,
utilization_rho=0.68,
tail_spike_prob=0.02,
tail_spike_ms=42.0,
),
StageLatencyConfig(
name="feast_clickhouse_fetch",
mean_ms=44.0,
sigma_log=0.45,
utilization_rho=0.84,
tail_spike_prob=0.04,
tail_spike_ms=115.0,
),
StageLatencyConfig(
name="ann_candidate_retrieval",
mean_ms=28.0,
sigma_log=0.35,
utilization_rho=0.76,
tail_spike_prob=0.02,
tail_spike_ms=65.0,
),
StageLatencyConfig(
name="heavy_ranking_and_rerank",
mean_ms=46.0,
sigma_log=0.42,
utilization_rho=0.86,
tail_spike_prob=0.045,
tail_spike_ms=130.0,
),
),
gpu_hourly_usd=3.20,
throughput_rps_per_gpu=62.0,
data_feature_usd_per_1m=18.50,
gateway_egress_usd_per_1m=7.40,
obs_audit_usd_per_1m=8.20,
),
sota_2026_platform=TierPlatformSpec(
tier_id="sota_2026_platform",
cache_hit_rate=0.38,
cache_fastpath_ms=6.5,
stages=(
StageLatencyConfig(
name="gateway_auth",
mean_ms=4.8,
sigma_log=0.22,
utilization_rho=0.42,
tail_spike_prob=0.002,
tail_spike_ms=12.0,
),
StageLatencyConfig(
name="feast_clickhouse_fetch",
mean_ms=11.5,
sigma_log=0.24,
utilization_rho=0.48,
tail_spike_prob=0.004,
tail_spike_ms=22.0,
),
StageLatencyConfig(
name="ann_candidate_retrieval",
mean_ms=9.2,
sigma_log=0.20,
utilization_rho=0.45,
tail_spike_prob=0.003,
tail_spike_ms=18.0,
),
StageLatencyConfig(
name="heavy_ranking_and_rerank",
mean_ms=17.5,
sigma_log=0.25,
utilization_rho=0.52,
tail_spike_prob=0.005,
tail_spike_ms=28.0,
),
),
gpu_hourly_usd=1.45,
throughput_rps_per_gpu=185.0,
data_feature_usd_per_1m=6.10,
gateway_egress_usd_per_1m=1.40,
obs_audit_usd_per_1m=2.30,
),
),
"Card-Fraud-Platform": ArchetypePlatformSpec(
archetype_id="Card-Fraud-Platform",
reference_repo="https://github.com/cvinhnguyen/card-fraud-platform",
slo_target_ms=45.0,
naive_monolith=TierPlatformSpec(
tier_id="naive_monolith",
cache_hit_rate=0.0,
cache_fastpath_ms=8.0,
stages=(
StageLatencyConfig(
name="gateway_pii_guard",
mean_ms=7.5,
sigma_log=0.35,
utilization_rho=0.66,
tail_spike_prob=0.025,
tail_spike_ms=28.0,
),
StageLatencyConfig(
name="flink_pit_online_features",
mean_ms=24.0,
sigma_log=0.44,
utilization_rho=0.85,
tail_spike_prob=0.05,
tail_spike_ms=70.0,
),
StageLatencyConfig(
name="online_xgb_nn_ensemble",
mean_ms=18.5,
sigma_log=0.38,
utilization_rho=0.81,
tail_spike_prob=0.03,
tail_spike_ms=48.0,
),
StageLatencyConfig(
name="sync_rule_and_audit_sink",
mean_ms=12.0,
sigma_log=0.40,
utilization_rho=0.78,
tail_spike_prob=0.035,
tail_spike_ms=42.0,
),
),
gpu_hourly_usd=1.80,
throughput_rps_per_gpu=160.0,
data_feature_usd_per_1m=14.80,
gateway_egress_usd_per_1m=5.20,
obs_audit_usd_per_1m=9.50,
),
sota_2026_platform=TierPlatformSpec(
tier_id="sota_2026_platform",
cache_hit_rate=0.12,
cache_fastpath_ms=3.2,
stages=(
StageLatencyConfig(
name="gateway_pii_guard",
mean_ms=3.1,
sigma_log=0.18,
utilization_rho=0.38,
tail_spike_prob=0.002,
tail_spike_ms=7.0,
),
StageLatencyConfig(
name="flink_pit_online_features",
mean_ms=5.4,
sigma_log=0.21,
utilization_rho=0.46,
tail_spike_prob=0.003,
tail_spike_ms=11.0,
),
StageLatencyConfig(
name="online_xgb_nn_ensemble",
mean_ms=6.2,
sigma_log=0.20,
utilization_rho=0.49,
tail_spike_prob=0.003,
tail_spike_ms=10.5,
),
StageLatencyConfig(
name="async_otel_audit_sink",
mean_ms=2.4,
sigma_log=0.16,
utilization_rho=0.32,
tail_spike_prob=0.001,
tail_spike_ms=5.0,
),
),
gpu_hourly_usd=0.85,
throughput_rps_per_gpu=520.0,
data_feature_usd_per_1m=4.30,
gateway_egress_usd_per_1m=0.95,
obs_audit_usd_per_1m=3.15,
),
),
"Agentic-LLM-Platform": ArchetypePlatformSpec(
archetype_id="Agentic-LLM-Platform",
reference_repo="https://github.com/itsmekhoathekid/RecSys-MLops",
slo_target_ms=900.0,
naive_monolith=TierPlatformSpec(
tier_id="naive_monolith",
cache_hit_rate=0.02,
cache_fastpath_ms=28.0,
stages=(
StageLatencyConfig(
name="ai_gateway_semantic_cache",
mean_ms=24.0,
sigma_log=0.32,
utilization_rho=0.64,
tail_spike_prob=0.02,
tail_spike_ms=95.0,
),
StageLatencyConfig(
name="mcp_tool_container",
mean_ms=195.0,
sigma_log=0.46,
utilization_rho=0.82,
tail_spike_prob=0.045,
tail_spike_ms=480.0,
),
StageLatencyConfig(
name="vllm_prefill_decode_pool",
mean_ms=410.0,
sigma_log=0.48,
utilization_rho=0.89,
tail_spike_prob=0.06,
tail_spike_ms=920.0,
),
StageLatencyConfig(
name="guardrail_langfuse_otel",
mean_ms=36.0,
sigma_log=0.35,
utilization_rho=0.72,
tail_spike_prob=0.025,
tail_spike_ms=110.0,
),
),
gpu_hourly_usd=28.0,
throughput_rps_per_gpu=6.5,
data_feature_usd_per_1m=32.0,
gateway_egress_usd_per_1m=18.0,
obs_audit_usd_per_1m=26.0,
),
sota_2026_platform=TierPlatformSpec(
tier_id="sota_2026_platform",
cache_hit_rate=0.34,
cache_fastpath_ms=12.5,
stages=(
StageLatencyConfig(
name="ai_gateway_semantic_cache",
mean_ms=10.5,
sigma_log=0.20,
utilization_rho=0.38,
tail_spike_prob=0.002,
tail_spike_ms=22.0,
),
StageLatencyConfig(
name="mcp_tool_sandbox",
mean_ms=82.0,
sigma_log=0.24,
utilization_rho=0.46,
tail_spike_prob=0.004,
tail_spike_ms=95.0,
),
StageLatencyConfig(
name="vllm_disagg_pd_cuda_graph",
mean_ms=215.0,
sigma_log=0.26,
utilization_rho=0.58,
tail_spike_prob=0.006,
tail_spike_ms=170.0,
),
StageLatencyConfig(
name="guardrail_langfuse_otel",
mean_ms=14.0,
sigma_log=0.19,
utilization_rho=0.36,
tail_spike_prob=0.002,
tail_spike_ms=24.0,
),
),
gpu_hourly_usd=13.60,
throughput_rps_per_gpu=24.5,
data_feature_usd_per_1m=9.80,
gateway_egress_usd_per_1m=3.40,
obs_audit_usd_per_1m=5.60,
),
),
}
def _congestion_multiplier(rho: float) -> float:
"""M/G/1-style queueing contention factor growing smoothly as rho approaches 1."""
clamped = min(max(rho, 0.01), 0.96)
return 1.0 + (clamped * clamped) / (1.0 - clamped)
def simulate_archetype_e2e(
archetype_id: str,
tier: str,
n_requests: int = 4000,
seed: int = 42,
cache_hit_override: float | None = None,
load_rho_override: float | None = None,
) -> dict[str, Any]:
"""Simulate cross-layer E2E latency percentiles and FinOps TCO for an archetype tier."""
if archetype_id not in ARCHETYPE_SPECS:
raise ValueError(f"Unknown archetype_id: {archetype_id}")
if tier not in ("naive_monolith", "sota_2026_platform"):
raise ValueError(f"Unknown tier: {tier}")
spec = ARCHETYPE_SPECS[archetype_id]
tier_spec = spec.naive_monolith if tier == "naive_monolith" else spec.sota_2026_platform
rng = np.random.default_rng(seed)
cache_hit = tier_spec.cache_hit_rate if cache_hit_override is None else float(cache_hit_override)
cache_hit = min(max(cache_hit, 0.0), 0.95)
is_cache_hit = rng.random(n_requests) < cache_hit
stage_p95: dict[str, float] = {}
downstream_total = np.zeros(n_requests, dtype=np.float64)
for st in tier_spec.stages:
rho = st.utilization_rho if load_rho_override is None else float(load_rho_override)
mult = _congestion_multiplier(rho)
mu = math.log(st.mean_ms * mult) - 0.5 * (st.sigma_log**2)
base_samples = rng.lognormal(mean=mu, sigma=st.sigma_log, size=n_requests)
spikes = np.where(
rng.random(n_requests) < st.tail_spike_prob,
st.tail_spike_ms * (0.65 + 0.7 * rng.random(n_requests)),
0.0,
)
stage_vals = base_samples + spikes
stage_p95[st.name] = round(float(np.percentile(stage_vals, 95)), 2)
downstream_total += stage_vals
fastpath = rng.normal(
loc=tier_spec.cache_fastpath_ms,
scale=tier_spec.cache_fastpath_ms * 0.12,
size=n_requests,
)
fastpath = np.maximum(fastpath, 1.0)
e2e_ms = np.where(is_cache_hit, fastpath, downstream_total)
p50_ms = round(float(np.percentile(e2e_ms, 50)), 2)
p95_ms = round(float(np.percentile(e2e_ms, 95)), 2)
p99_ms = round(float(np.percentile(e2e_ms, 99)), 2)
mean_ms = round(float(np.mean(e2e_ms)), 2)
slo_sat = round(float(np.mean(e2e_ms <= spec.slo_target_ms) * 100.0), 2)
reqs_per_gpu_hour = tier_spec.throughput_rps_per_gpu * 3600.0
effective_miss_ratio = 1.0 - cache_hit
gpu_compute_usd = (tier_spec.gpu_hourly_usd * 1_000_000.0 / reqs_per_gpu_hour) * effective_miss_ratio
total_tco_usd = (
gpu_compute_usd
+ tier_spec.data_feature_usd_per_1m
+ tier_spec.gateway_egress_usd_per_1m
+ tier_spec.obs_audit_usd_per_1m
)
return {
"archetype_id": archetype_id,
"tier": tier,
"reference_repo": spec.reference_repo,
"n_requests": n_requests,
"slo_target_ms": spec.slo_target_ms,
"cache_hit_rate_pct": round(cache_hit * 100.0, 2),
"p50_ms": p50_ms,
"p95_ms": p95_ms,
"p99_ms": p99_ms,
"mean_ms": mean_ms,
"slo_satisfaction_pct": slo_sat,
"stage_p95_ms": stage_p95,
"finops_tco_usd_per_1m": round(total_tco_usd, 2),
"tco_breakdown_usd": {
"gpu_compute_usd": round(gpu_compute_usd, 2),
"data_feature_usd": round(tier_spec.data_feature_usd_per_1m, 2),
"gateway_egress_usd": round(tier_spec.gateway_egress_usd_per_1m, 2),
"obs_audit_usd": round(tier_spec.obs_audit_usd_per_1m, 2),
},
"effective_goodput_rps_per_gpu": round(
tier_spec.throughput_rps_per_gpu * (slo_sat / 100.0) / max(effective_miss_ratio, 0.2),
2,
),
}
def run_cross_layer_e2e_tco_suite(seed: int = 42, n_requests: int = 4000) -> dict[str, Any]:
"""Run deterministic E2E latency & FinOps TCO comparison across all 3 flagship archetypes."""
comparisons: list[dict[str, Any]] = []
by_archetype: dict[str, dict[str, Any]] = {}
for idx, archetype_id in enumerate(ARCHETYPE_SPECS):
naive = simulate_archetype_e2e(
archetype_id=archetype_id,
tier="naive_monolith",
n_requests=n_requests,
seed=seed + idx * 10,
)
sota = simulate_archetype_e2e(
archetype_id=archetype_id,
tier="sota_2026_platform",
n_requests=n_requests,
seed=seed + idx * 10 + 1,
)
p99_speedup_x = round(naive["p99_ms"] / max(sota["p99_ms"], 1e-6), 2)
tco_savings_pct = round(
(1.0 - sota["finops_tco_usd_per_1m"] / max(naive["finops_tco_usd_per_1m"], 1e-6)) * 100.0,
2,
)
slo_gain_pp = round(sota["slo_satisfaction_pct"] - naive["slo_satisfaction_pct"], 2)
entry = {
"archetype_id": archetype_id,
"slo_target_ms": naive["slo_target_ms"],
"naive_monolith": naive,
"sota_2026_platform": sota,
"p99_speedup_x": p99_speedup_x,
"tco_savings_pct": tco_savings_pct,
"slo_gain_pp": slo_gain_pp,
}
comparisons.append(entry)
by_archetype[archetype_id] = entry
return {
"seed": seed,
"n_requests_per_tier": n_requests,
"comparisons": comparisons,
"by_archetype": by_archetype,
}
def _binary_roc_auc(y_true: np.ndarray, y_score: np.ndarray) -> float:
pos = y_score[y_true == 1]
neg = y_score[y_true == 0]
if pos.size == 0 or neg.size == 0:
return 0.5
diffs = pos[:, None] - neg[None, :]
wins = float(np.sum(diffs > 0.0) + 0.5 * np.sum(diffs == 0.0))
return wins / float(pos.size * neg.size)
def _compute_psi(ref: np.ndarray, cur: np.ndarray, bins: int = 10) -> float:
quantiles = np.linspace(0.0, 1.0, bins + 1)
edges = np.quantile(ref, quantiles)
edges[0] = -np.inf
edges[-1] = np.inf
# Guarantee strictly increasing interior edges if duplicated
for idx in range(1, len(edges) - 1):
if edges[idx] <= edges[idx - 1]:
edges[idx] = edges[idx - 1] + 1e-6
ref_counts, _ = np.histogram(ref, bins=edges)
cur_counts, _ = np.histogram(cur, bins=edges)
eps = 1e-6
p = np.maximum(ref_counts / float(max(ref.size, 1)), eps)
q = np.maximum(cur_counts / float(max(cur.size, 1)), eps)
return float(np.sum((q - p) * np.log(q / p)))
def _inject_late_data_watermark(rng: np.random.Generator) -> dict[str, Any]:
"""Scenario 1: Late data arrival & out-of-order stream watermark recovery (Ch 10)."""
n_events = 6000
amounts = rng.lognormal(mean=3.8, sigma=0.7, size=n_events)
is_delayed_tail = rng.random(n_events) < 0.12
lags_min = np.where(
is_delayed_tail,
rng.uniform(3.0, 17.5, size=n_events),
rng.uniform(0.05, 0.92, size=n_events),
)
naive_kept = lags_min <= 1.0
sota_kept = lags_min <= 18.0
total_rev = float(np.sum(amounts))
naive_rev = float(np.sum(amounts[naive_kept]))
sota_rev = float(np.sum(amounts[sota_kept]))
return {
"scenario_id": "late_data_watermark",
"title": "Late Data Watermark & Out-of-Order Recovery (Ch 10)",
"n_events": n_events,
"naive": {
"watermark_horizon_min": 1.0,
"completeness_pct": round(float(np.mean(naive_kept) * 100.0), 2),
"dropped_events": int(np.sum(~naive_kept)),
"aggregate_mape_pct": round(abs(total_rev - naive_rev) / total_rev * 100.0, 2),
},
"sota_2026": {
"watermark_horizon_min": 18.0,
"completeness_pct": round(float(np.mean(sota_kept) * 100.0), 2),
"dropped_events": int(np.sum(~sota_kept)),
"aggregate_mape_pct": round(abs(total_rev - sota_rev) / total_rev * 100.0, 2),
},
"passed": bool(float(np.mean(sota_kept) * 100.0) >= 99.5),
}
def _inject_pit_skew(rng: np.random.Generator) -> dict[str, Any]:
"""Scenario 2: Point-in-Time Training-Serving Skew (#15, Ch 11)."""
n_rows = 3000
x_valid = rng.normal(0.0, 1.0, size=n_rows)
y_prob = 1.0 / (1.0 + np.exp(-(1.35 * x_valid - 0.6)))
y_true = (rng.random(n_rows) < y_prob).astype(np.int64)
# Post-event label-correlated velocity update creates future leakage if ASOF is skipped
future_flag = rng.random(n_rows) < 0.28
leaked_feature = np.where(future_flag, x_valid + 1.85 * y_true - 0.4, x_valid)
# Naive model relies heavily on leaked future signal; online serving has only causal x_valid
naive_offline_score = 0.65 * leaked_feature + 0.35 * x_valid
naive_online_score = 0.65 * (x_valid - 0.25) + 0.35 * x_valid
# SOTA ASOF PIT join trains solely on causal x_valid
sota_offline_score = 1.0 * x_valid
sota_online_score = 1.0 * (x_valid + rng.normal(0.0, 0.04, size=n_rows))
naive_off_auc = _binary_roc_auc(y_true, naive_offline_score)
naive_on_auc = _binary_roc_auc(y_true, naive_online_score)
sota_off_auc = _binary_roc_auc(y_true, sota_offline_score)
sota_on_auc = _binary_roc_auc(y_true, sota_online_score)
naive_psi = _compute_psi(leaked_feature, x_valid)
sota_psi = _compute_psi(x_valid, x_valid + rng.normal(0.0, 0.04, size=n_rows))
return {
"scenario_id": "pit_training_serving_skew",
"title": "Point-in-Time Training-Serving Skew (#15, Ch 11)",
"n_rows": n_rows,
"naive": {
"future_leakage_pct": round(float(np.mean(future_flag) * 100.0), 2),
"offline_auc": round(naive_off_auc, 4),
"online_auc": round(naive_on_auc, 4),
"auc_drop": round(naive_off_auc - naive_on_auc, 4),
"train_serve_psi": round(naive_psi, 4),
},
"sota_2026": {
"future_leakage_pct": 0.0,
"offline_auc": round(sota_off_auc, 4),
"online_auc": round(sota_on_auc, 4),
"auc_drop": round(max(0.0, sota_off_auc - sota_on_auc), 4),
"train_serve_psi": round(sota_psi, 4),
},
"passed": bool(sota_psi < 0.05 and abs(sota_off_auc - sota_on_auc) < 0.02),
}
def _simulate_naive_fifo_gpus(
arrivals_ms: NDArray[np.float64],
service_ms: NDArray[np.float64],
num_gpus: int,
) -> NDArray[np.float64]:
"""Simulate a static G/G/c FIFO GPU pool and return per-request latencies (ms)."""
gpu_free: list[float] = [0.0] * num_gpus
heapq.heapify(gpu_free)
latencies = np.empty(arrivals_ms.size, dtype=np.float64)
for idx in range(arrivals_ms.size):
arr_t = float(arrivals_ms[idx])
svc_t = float(service_ms[idx])
free_t = heapq.heappop(gpu_free)
start_t = max(arr_t, free_t)
finish_t = start_t + svc_t
latencies[idx] = finish_t - arr_t
heapq.heappush(gpu_free, finish_t)
return latencies
def _simulate_priority_keda_gpus(
arrivals_ms: NDArray[np.float64],
service_ms: NDArray[np.float64],
is_interactive: NDArray[np.bool_],
prewarm_gpus: int,
keda_extra_gpus: int,
keda_ready_ms: float,
admission_rho_cap: float = 0.85,
) -> tuple[NDArray[np.float64], int]:
"""Simulate KEDA scale-out, strict interactive>batch priority & HTTP 429 batch shedding."""
total = arrivals_ms.size
busy: list[float] = []
free_gpus = prewarm_gpus
total_gpus = prewarm_gpus
keda_scaled = False
inter_q: deque[tuple[float, float]] = deque()
batch_q: deque[tuple[float, float]] = deque()
inter_latencies: list[float] = []
batch_shed = 0
idx = 0
t_now = 0.0
while idx < total or inter_q or batch_q or busy:
while free_gpus > 0 and (inter_q or batch_q):
if inter_q:
req_arr, req_svc = inter_q.popleft()
fin_t = t_now + req_svc
inter_latencies.append(fin_t - req_arr)
else:
req_arr, req_svc = batch_q.popleft()
fin_t = t_now + req_svc
heapq.heappush(busy, fin_t)
free_gpus -= 1
next_arr = float(arrivals_ms[idx]) if idx < total else float("inf")
next_fin = busy[0] if busy else float("inf")
next_keda = keda_ready_ms if not keda_scaled else float("inf")
t_next = min(next_arr, next_fin, next_keda)
if math.isinf(t_next):
break
t_now = t_next
while busy and busy[0] <= t_now + 1e-9:
heapq.heappop(busy)
free_gpus += 1
if not keda_scaled and t_now >= keda_ready_ms - 1e-9:
free_gpus += keda_extra_gpus
total_gpus += keda_extra_gpus
keda_scaled = True
while idx < total and float(arrivals_ms[idx]) <= t_now + 1e-9:
a_t = float(arrivals_ms[idx])
s_t = float(service_ms[idx])
if bool(is_interactive[idx]):
inter_q.append((a_t, s_t))
else:
in_flight = len(busy) + len(inter_q) + len(batch_q)
if in_flight >= int(admission_rho_cap * total_gpus):
batch_shed += 1
else:
batch_q.append((a_t, s_t))
idx += 1
return np.array(inter_latencies, dtype=np.float64), batch_shed
def _inject_bursty_gpu_surge(rng: np.random.Generator) -> dict[str, Any]:
"""Scenario 3: 10x Bursty GPU Surge Discrete-Event Priority Queue Simulation (#21/#22)."""
n_interactive = 1500
n_batch = 900
total_reqs = n_interactive + n_batch
slo_ms = 500.0
# 10x arrival shock: 240 req/s Poisson burst (10x of 24 req/s steady-state baseline)
is_inter = np.concatenate((np.ones(n_interactive, dtype=bool), np.zeros(n_batch, dtype=bool)))
rng.shuffle(is_inter)
inter_arrivals_ms = rng.exponential(scale=1000.0 / 240.0, size=total_reqs)
arrivals_ms = np.cumsum(inter_arrivals_ms)
service_ms = np.where(
is_inter,
rng.lognormal(mean=math.log(48.0), sigma=0.28, size=total_reqs),
rng.lognormal(mean=math.log(78.0), sigma=0.32, size=total_reqs),
)
# Naive static 12-GPU FIFO cluster (~196 req/s capacity < 240 req/s arrival shock -> queue buildup)
naive_all = _simulate_naive_fifo_gpus(arrivals_ms, service_ms, num_gpus=12)
naive_inter = naive_all[is_inter]
naive_goodput = float(np.mean(naive_all <= slo_ms) * 100.0)
naive_inter_p99 = float(np.percentile(naive_inter, 99))
# SOTA: 10 pre-warmed GPUs + KEDA scale-out (+4 GPUs after 1.5s Model-Load) + priority + HTTP 429
sota_inter, batch_shed = _simulate_priority_keda_gpus(
arrivals_ms=arrivals_ms,
service_ms=service_ms,
is_interactive=is_inter,
prewarm_gpus=10,
keda_extra_gpus=4,
keda_ready_ms=1500.0,
admission_rho_cap=0.85,
)
sota_inter_goodput = float(np.mean(sota_inter <= slo_ms) * 100.0)
sota_inter_p99 = float(np.percentile(sota_inter, 99))
batch_shed_pct = (batch_shed / float(n_batch)) * 100.0
return {
"scenario_id": "bursty_gpu_surge_10x",
"title": "10x Bursty GPU Surge & Priority Admission Control (#21/#22)",
"slo_ms": slo_ms,
"naive": {
"goodput_pct": round(naive_goodput, 2),
"interactive_p99_ms": round(naive_inter_p99, 2),
"batch_shed_pct": 0.0,
},
"sota_2026": {
"interactive_goodput_pct": round(sota_inter_goodput, 2),
"interactive_p99_ms": round(sota_inter_p99, 2),
"batch_gracefully_shed_pct": round(batch_shed_pct, 2),
},
"passed": bool(sota_inter_goodput >= 95.0 and sota_inter_p99 <= slo_ms),
}
_SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$")
_FORBIDDEN_CONTAINER_EGRESS = (
"127.0.0.1",
"localhost",
"0.0.0.0",
"169.254.169.254",
"*",
)
def _is_valid_service_dns_egress(entries: list[str]) -> bool:
"""Ensure container egress allowlist targets cluster service DNS names rather than loopback/IMDS."""
if not entries:
return False
for entry in entries:
lowered = entry.strip().lower()
if not lowered or any(bad in lowered for bad in _FORBIDDEN_CONTAINER_EGRESS):
return False
host_part = lowered.split(":", maxsplit=1)[0]
if "." not in host_part:
return False
return True
def evaluate_mcp_sandbox_policy(sandbox_cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Evaluate 8 concrete MCP attack vectors behaviorally against container security policy."""
cfg = sandbox_cfg or {}
cap_drop = [str(c).upper() for c in (cfg.get("cap_drop") or [])]
read_only = cfg.get("read_only_root_fs") is True
non_root = cfg.get("run_as_non_root") is True and int(cfg.get("run_as_uid", 0) or 0) >= 1000
seccomp_ok = str(cfg.get("seccomp_profile", "")) in {"RuntimeDefault", "Localhost"}
pids_val = int(cfg.get("pids_limit", 0) or 0)
pids_ok = 0 < pids_val <= 256
egress_list = [str(x) for x in (cfg.get("egress_allowlist") or [])]
egress_ok = _is_valid_service_dns_egress(egress_list)
auth_ref = str(cfg.get("auth_ref", ""))
vault_ok = auth_ref.startswith("vault://") or ("vault://" in auth_ref and "${" in auth_ref)
control_status = {
"seccomp_no_shell": seccomp_ok and read_only,
"egress_allowlist": egress_ok,
"read_only_root_fs": read_only,
"cap_drop_all_no_sa": "ALL" in cap_drop,
"cgroup_pids_limit": pids_ok,
"non_root_uid_ns": non_root,
"vault_ephemeral_scope": vault_ok,
}
probes: tuple[dict[str, str], ...] = (
{"id": "shell_env_dump", "vector": "rce", "control": "seccomp_no_shell"},
{"id": "ssrf_cloud_metadata_169_254", "vector": "ssrf", "control": "egress_allowlist"},
{"id": "filesystem_write_etc", "vector": "fs_escape", "control": "read_only_root_fs"},
{"id": "read_k8s_sa_token", "vector": "secret_leak", "control": "cap_drop_all_no_sa"},
{"id": "dns_exfil_unknown_domain", "vector": "exfiltration", "control": "egress_allowlist"},
{"id": "fork_bomb_cgroup_exhaust", "vector": "dos", "control": "cgroup_pids_limit"},
{"id": "path_traversal_host_proc", "vector": "fs_escape", "control": "non_root_uid_ns"},
{"id": "cross_tenant_vault_token", "vector": "secret_leak", "control": "vault_ephemeral_scope"},
)
outcomes = {p["id"]: bool(control_status.get(p["control"], False)) for p in probes}
blocked = sum(1 for p in probes if outcomes[p["id"]])
leaks = sum(
1
for p in probes
if p["vector"] in ("secret_leak", "exfiltration") and not outcomes[p["id"]]
)
return {
"total_probes": len(probes),
"attacks_blocked": blocked,
"attacks_blocked_pct": round(blocked / len(probes) * 100.0, 2),
"secret_exfiltrations": leaks,
"egress_dns_only": egress_ok,
"probe_outcomes": outcomes,
"passed": bool(blocked == len(probes) and leaks == 0),
}
def _inject_mcp_sandbox_probes(sandbox_cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Scenario 4: Unsandboxed vs Sandboxed MCP Agent Isolation (8 behavioral probes)."""
naive_cfg: dict[str, Any] = {
"read_only_root_fs": True,
"run_as_non_root": False,
"run_as_uid": 0,
"cap_drop": [],
"seccomp_profile": "RuntimeDefault",
"pids_limit": 0,
"egress_allowlist": ["0.0.0.0:0"],
"auth_ref": "sk-plaintext-static-env",
}
naive_res = evaluate_mcp_sandbox_policy(naive_cfg)
default_sota_cfg: dict[str, Any] = {
"read_only_root_fs": True,
"run_as_non_root": True,
"run_as_uid": 65532,
"cap_drop": ["ALL"],
"seccomp_profile": "RuntimeDefault",
"pids_limit": 64,
"egress_allowlist": [
"clickhouse.data-platform.svc.cluster.local:8123",
"redis.serving-platform.svc.cluster.local:6379",
],
"auth_ref": "${MCP_VAULT_TOKEN_REF:-vault://secret/data/mcp/ephemeral}",
}
sota_res = evaluate_mcp_sandbox_policy(sandbox_cfg or default_sota_cfg)
return {
"scenario_id": "mcp_agent_sandbox_isolation",
"title": "Unsandboxed vs Sandboxed MCP Agent Isolation (Ch 13/15/19)",
"total_probes": sota_res["total_probes"],
"naive": {
"attacks_blocked": naive_res["attacks_blocked"],
"attacks_blocked_pct": naive_res["attacks_blocked_pct"],
"secret_exfiltrations": naive_res["secret_exfiltrations"],
},
"sota_2026": {
"attacks_blocked": sota_res["attacks_blocked"],
"attacks_blocked_pct": sota_res["attacks_blocked_pct"],
"secret_exfiltrations": sota_res["secret_exfiltrations"],
"egress_dns_only": sota_res["egress_dns_only"],
},
"passed": sota_res["passed"],
}
def _inject_canary_sprt_rollback(rng: np.random.Generator) -> dict[str, Any]:
"""Scenario 5: Canary Regression Automated Wald SPRT Rollback (#16, Ch 24)."""
total_window_reqs = 3000
regressed_err_rate = 0.12
p0, p1 = 0.01, 0.08
alpha, beta = 0.01, 0.05
boundary_a = math.log((1.0 - beta) / alpha)
# Big-Bang 100% exposes all requests before manual rollback
big_bang_errors = int(np.sum(rng.random(total_window_reqs) < regressed_err_rate))
# Progressive Canary 1% (20 reqs) -> 5% (80 reqs) -> SPRT checks per request
stages_pct = ((1, 20), (5, 80), (25, 400), (50, 800), (100, 1700))
exposed = 0
canary_errors = 0
llr = 0.0
tripped_at_pct: int | None = None
for pct, stage_n in stages_pct:
errs = rng.random(stage_n) < regressed_err_rate
for is_err in errs:
exposed += 1
if bool(is_err):
canary_errors += 1
llr += math.log(p1 / p0)
else:
llr += math.log((1.0 - p1) / (1.0 - p0))
if llr >= boundary_a:
tripped_at_pct = pct
break
if tripped_at_pct is not None:
break
blast_reduction_pct = round((1.0 - exposed / float(total_window_reqs)) * 100.0, 2)
return {
"scenario_id": "canary_sprt_rollback",
"title": "Canary Regression Automated SPRT Rollback (#16, Ch 24)",
"sprt_boundary_a": round(boundary_a, 3),
"naive_big_bang": {
"exposed_requests": total_window_reqs,
"failed_requests": big_bang_errors,
"blast_radius_pct": 100.0,
},
"sota_canary_sprt": {
"tripped_at_step_pct": tripped_at_pct,
"sprt_llr_at_trip": round(llr, 3),
"exposed_requests": exposed,
"failed_requests": canary_errors,
"blast_radius_reduction_pct": blast_reduction_pct,
"errors_prevented": big_bang_errors - canary_errors,
},
"passed": bool(
tripped_at_pct is not None and tripped_at_pct <= 5 and blast_reduction_pct >= 94.0
),
}
def _fit_kaplan_meier_arrival_cdf(
observed_times: NDArray[np.float64],
event_observed: NDArray[np.bool_],
) -> tuple[NDArray[np.float64], NDArray[np.float64]]:
"""Vectorized Kaplan-Meier product-limit survival CDF estimator F_KM(t)."""
order = np.argsort(observed_times, kind="mergesort")
t_sorted = observed_times[order]
e_sorted = event_observed[order].astype(np.int64)
uniq_t, first_idx = np.unique(t_sorted, return_index=True)
d_counts = np.add.reduceat(e_sorted, first_idx)
ev_mask = d_counts > 0
if not np.any(ev_mask):
return np.array([0.0], dtype=np.float64), np.array([0.0], dtype=np.float64)
n_risk = (observed_times.size - first_idx[ev_mask]).astype(np.float64)
surv = np.cumprod(1.0 - d_counts[ev_mask].astype(np.float64) / np.maximum(n_risk, 1.0))
t_grid = np.concatenate((np.array([0.0], dtype=np.float64), uniq_t[ev_mask].astype(np.float64)))
cdf_grid = np.concatenate((np.array([0.0], dtype=np.float64), np.clip(1.0 - surv, 0.0, 1.0)))
return t_grid, cdf_grid
def _eval_kaplan_meier_cdf(
t_grid: NDArray[np.float64],
cdf_grid: NDArray[np.float64],
query_ages: NDArray[np.float64],
) -> NDArray[np.float64]:
"""Evaluate Kaplan-Meier arrival CDF at arbitrary query ages."""
ages = np.maximum(0.0, query_ages)
pos = np.clip(np.searchsorted(t_grid, ages, side="right") - 1, 0, cdf_grid.size - 1)
return cdf_grid[pos]
def _inject_delayed_label_ipcw_proxy(rng: np.random.Generator) -> dict[str, Any]:
"""Scenario 6: Delayed-Label Right-Censoring KM-IPCW + Proxy + Audit HT (#17, Ch 25)."""
n_cohort = 2500
p_hat = np.clip(rng.beta(1.6, 4.2, size=n_cohort), 0.02, 0.98)
y_hat = (p_hat >= 0.5).astype(np.int64)
# Silent Concept Drift degrades true accuracy sharply
y_true = np.where(
y_hat == 0,
(rng.random(n_cohort) < 0.35).astype(np.int64),
(rng.random(n_cohort) < 0.71).astype(np.int64),
)
ages = rng.uniform(0.5, 6.5, size=n_cohort)
mat_y0 = 1.0 - np.exp(-np.power(ages / 5.5, 1.35))
mat_y1 = 1.0 - np.exp(-np.power(ages / 36.0, 1.55))
arrived = rng.random(n_cohort) < np.where(y_true == 1, mat_y1, mat_y0)
# Fit class-conditional Kaplan-Meier survival curves from an independent historical cohort
km_rng = np.random.default_rng(42077)
hist_n = 18000
hist_y = (km_rng.random(hist_n) < float(np.mean(y_true))).astype(np.int64)
hist_u = np.clip(km_rng.random(hist_n), 1e-6, 0.999)
hist_d0 = 5.5 * np.power(-np.log(1.0 - hist_u), 1.0 / 1.35)
hist_d1 = 36.0 * np.power(-np.log(1.0 - hist_u), 1.0 / 1.55)
hist_delays = np.where(hist_y == 1, hist_d1, hist_d0)
hist_censor = km_rng.uniform(0.5, 60.0, size=hist_n)
hist_obs = np.round(np.minimum(hist_delays, hist_censor), 2)
hist_ev = hist_delays <= hist_censor
km_t0, km_c0 = _fit_kaplan_meier_arrival_cdf(hist_obs[hist_y == 0], hist_ev[hist_y == 0])
km_t1, km_c1 = _fit_kaplan_meier_arrival_cdf(hist_obs[hist_y == 1], hist_ev[hist_y == 1])
correct = (y_hat == y_true).astype(np.float64)
true_acc = float(np.mean(correct) * 100.0)
naive_acc = float(np.mean(correct[arrived]) * 100.0)
km_arr_cdf0 = _eval_kaplan_meier_cdf(km_t0, km_c0, ages[arrived])
km_arr_cdf1 = _eval_kaplan_meier_cdf(km_t1, km_c1, ages[arrived])
w_ipcw = 1.0 / np.maximum(0.08, np.where(y_true[arrived] == 1, km_arr_cdf1, km_arr_cdf0))
ipcw_acc = float(np.sum(w_ipcw * correct[arrived]) / np.sum(w_ipcw) * 100.0)
# Label-free proxy shift vs pre-drift beta(1.1, 5.2) baseline
p_ref = np.clip(rng.beta(1.1, 5.2, size=n_cohort), 0.02, 0.98)
pred_psi = _compute_psi(p_ref, p_hat)
ent_ref = float(np.mean(-p_ref * np.log(p_ref) - (1.0 - p_ref) * np.log(1.0 - p_ref)))
ent_cur = float(np.mean(-p_hat * np.log(p_hat) - (1.0 - p_hat) * np.log(1.0 - p_hat)))
# Stratified Horvitz-Thompson active audit (150 samples = 6.0%)
strata = np.where(p_hat < 0.35, 0, np.where(p_hat <= 0.65, 1, 2))
ht_sum = 0.0
for sid, k in ((0, 68), (1, 52), (2, 30)):
idx_s = np.flatnonzero(strata == sid)
chosen = rng.choice(idx_s, size=min(idx_s.size, k), replace=False)
ht_sum += float(np.sum(correct[chosen])) / (float(chosen.size) / float(idx_s.size))
audit_ht_acc = ht_sum / float(n_cohort) * 100.0
audit_err_pp = round(abs(audit_ht_acc - true_acc), 2)
naive_detect_day = 60
sota_detect_day = 21 if (pred_psi >= 0.15 and audit_err_pp < 5.0) else naive_detect_day
detection_lead_days = naive_detect_day - sota_detect_day
return {
"scenario_id": "delayed_label_ipcw_proxy",
"title": "Delayed-Label Right-Censoring KM-IPCW + Proxy Early Alert (#17, Ch 25)",
"true_accuracy_pct": round(true_acc, 2),
"naive": {
"observed_accuracy_pct": round(naive_acc, 2),
"optimism_bias_pp": round(naive_acc - true_acc, 2),
"detection_delay_days": naive_detect_day,
},
"sota_2026": {
"ipcw_accuracy_pct": round(ipcw_acc, 2),
"ipcw_estimator": "kaplan_meier_product_limit",
"prediction_psi": round(pred_psi, 4),
"entropy_delta_nats": round(ent_cur - ent_ref, 4),
"active_audit_ht_accuracy_pct": round(audit_ht_acc, 2),
"audit_error_pp": audit_err_pp,
"detection_lead_days": detection_lead_days,
},
"passed": bool((naive_acc - true_acc) > 15.0 and audit_err_pp < 5.0 and pred_psi >= 0.15),
}
def run_failure_injection_suite(
seed: int = 42,
mcp_sandbox_cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Execute all 6 production failure-injection scenarios deterministically."""
rng = np.random.default_rng(seed)
scenarios = [
_inject_late_data_watermark(rng),
_inject_pit_skew(rng),
_inject_bursty_gpu_surge(rng),
_inject_mcp_sandbox_probes(mcp_sandbox_cfg),
_inject_canary_sprt_rollback(rng),
_inject_delayed_label_ipcw_proxy(rng),
]
passed_count = sum(1 for sc in scenarios if sc["passed"])
return {
"seed": seed,
"total_scenarios": len(scenarios),
"passed_scenarios": passed_count,
"all_passed": passed_count == len(scenarios),
"scenarios": scenarios,
"by_id": {str(sc["scenario_id"]): sc for sc in scenarios},
}
class CapstoneBehavioralEvidence(BaseModel):
"""Structural & operational telemetry evidence verified behaviorally (zero keyword matching)."""
model_config = ConfigDict(extra="forbid")
submission_id: str
archetype_id: str = Field(pattern="^(RecSys-MLops|Card-Fraud-Platform|Agentic-LLM-Platform)$")
# Domain 1: Data, Lakehouse & PIT (#15) - max 15
watermark_minutes: float = Field(ge=0.0, le=60.0)
allowed_lateness_minutes: float = Field(ge=0.0, le=60.0)
dlq_enabled: bool
pit_asof_enforced: bool
# Domain 2: Infra, K8s, Vault/mTLS & MCP Sandbox - max 15
plaintext_secret_count: int = Field(ge=0)
latest_tag_count: int = Field(ge=0)
loopback_host_binds: bool
vault_dynamic_leases: bool
istio_strict_mtls: bool
mcp_sandbox_config: dict[str, Any]
# Domain 3: AI Gateway & LLM/ML Serving (#18-#35) - max 20
cache_hit_rate: float = Field(ge=0.0, le=0.95)
target_load_rho: float = Field(ge=0.05, lt=0.96)
admission_control_enabled: bool
dual_tpm_usd_budget: bool
# Domain 4: 4-Way Versioning, Multi-slice Gate & Canary SPRT/mSPRT (#16) - max 15
git_sha256: str
dvc_sha256: str
mlflow_sha256: str
prompt_sha256: str
mlflow_aliases_configured: bool
canary_rollback_monitor: str = Field(pattern="^(wald_sprt|msprt|big_bang|none)$")
# Domain 5: Observability, Late Labels #17 & SRE - max 15
otel_pii_redaction_enabled: bool
forbidden_high_card_labels: int = Field(ge=0)
otel_genai_v1_37_plus: bool
ragas_eval_enabled: bool
prometheus_native_histograms: bool
sre_multi_window_burn_rate: bool
active_audit_ht_enabled: bool
# Domain 6: Live Chaos Defense & FinOps TCO - max 20
finops_tco_verified: bool
chaos_scenarios_passed: int = Field(ge=0, le=6)
def audit_behavioral_submission(
evidence: CapstoneBehavioralEvidence,
seed: int = 42,
) -> dict[str, Any]:
"""Score a capstone architecture submission via structural invariants & live simulations."""
fi = run_failure_injection_suite(seed=seed, mcp_sandbox_cfg=evidence.mcp_sandbox_config)
e2e = simulate_archetype_e2e(
archetype_id=evidence.archetype_id,
tier="sota_2026_platform",
n_requests=1000,
seed=seed,
cache_hit_override=evidence.cache_hit_rate,
load_rho_override=evidence.target_load_rho,
)
naive_e2e = simulate_archetype_e2e(
archetype_id=evidence.archetype_id,
tier="naive_monolith",
n_requests=1000,
seed=seed,
)
mcp_res = fi["by_id"]["mcp_agent_sandbox_isolation"]["sota_2026"]
# Domain 1 (15 pts): Late data window >= 15m + DLQ + ASOF PIT
d1 = 0.0
if evidence.watermark_minutes + evidence.allowed_lateness_minutes >= 15.0:
d1 += 5.0
if evidence.dlq_enabled:
d1 += 3.0
if evidence.pit_asof_enforced and fi["by_id"]["pit_training_serving_skew"]["passed"]:
d1 += 7.0
# Domain 2 (15 pts): Topology hygiene + 8-probe behavioral MCP Sandbox evaluation
d2 = 0.0
if evidence.latest_tag_count == 0 and evidence.plaintext_secret_count == 0:
d2 += 3.0
if evidence.loopback_host_binds and evidence.vault_dynamic_leases and evidence.istio_strict_mtls:
d2 += 4.0
d2 += round(8.0 * (float(mcp_res["attacks_blocked"]) / 8.0), 2)
# Domain 3 (20 pts): Measured E2E SLO satisfaction + Admission Control + Dual TPM/USD
d3 = 0.0
slo_ratio = min(1.0, float(e2e["slo_satisfaction_pct"]) / 98.0)
d3 += round(12.0 * slo_ratio, 2)
if evidence.admission_control_enabled:
d3 += 4.0
if evidence.dual_tpm_usd_budget:
d3 += 4.0
# Domain 4 (15 pts): 4 valid 64-hex SHA-256 digests + MLflow Aliases + SPRT/mSPRT
sha_ok = all(
bool(_SHA256_HEX_RE.match(h.strip().lower()))
for h in (
evidence.git_sha256,
evidence.dvc_sha256,
evidence.mlflow_sha256,
evidence.prompt_sha256,
)
)
d4 = 0.0
if sha_ok:
d4 += 6.0
if evidence.mlflow_aliases_configured:
d4 += 3.0
if evidence.canary_rollback_monitor in {"wald_sprt", "msprt"}:
d4 += 6.0
# Domain 5 (15 pts): OTel v1.37+, RAGAS, Prom Native Hist, Zero PII, SRE & #17 HT Audit
d5 = 0.0
if evidence.otel_pii_redaction_enabled and evidence.forbidden_high_card_labels == 0:
d5 += 4.0
if evidence.otel_genai_v1_37_plus and evidence.ragas_eval_enabled:
d5 += 4.0
if evidence.prometheus_native_histograms and evidence.sre_multi_window_burn_rate:
d5 += 4.0
if evidence.active_audit_ht_enabled:
d5 += 3.0
# Domain 6 (20 pts): Live Chaos Defense scenarios passed + measured FinOps TCO savings
tco_savings = 1.0 - float(e2e["finops_tco_usd_per_1m"]) / max(
float(naive_e2e["finops_tco_usd_per_1m"]), 1e-6
)
d6 = round(12.0 * (float(evidence.chaos_scenarios_passed) / 6.0), 2)
if evidence.finops_tco_verified and tco_savings >= 0.45:
d6 += 8.0
elif evidence.finops_tco_verified and tco_savings > 0.0:
d6 += round(8.0 * (tco_savings / 0.45), 2)
disqualifiers = {
"plaintext_secrets_present": evidence.plaintext_secret_count > 0,
"latest_container_tag_used": evidence.latest_tag_count > 0,
"pit_future_leakage_detected": not evidence.pit_asof_enforced,
"unsandboxed_mcp_execution": not (
mcp_res["attacks_blocked"] == 8 and mcp_res["secret_exfiltrations"] == 0
),
"missing_canary_rollback": evidence.canary_rollback_monitor in {"big_bang", "none"},
"missing_telemetry_or_pii_leak": (
not evidence.otel_pii_redaction_enabled or evidence.forbidden_high_card_labels > 0
),
}
return {
"submission_id": evidence.submission_id,
"archetype_id": evidence.archetype_id,
"data_lakehouse_pit": round(min(15.0, d1), 2),
"security_k8s_sandbox": round(min(15.0, d2), 2),
"gateway_and_serving": round(min(20.0, d3), 2),
"mlops_cicd_canary": round(min(15.0, d4), 2),
"observability_late_labels_sre": round(min(15.0, d5), 2),
"live_chaos_and_finops": round(min(20.0, d6), 2),
"measured_e2e_p99_ms": e2e["p99_ms"],
"measured_e2e_slo_pct": e2e["slo_satisfaction_pct"],
"measured_tco_savings_pct": round(tco_savings * 100.0, 2),
"mcp_attacks_blocked": mcp_res["attacks_blocked"],
"mcp_egress_dns_only": mcp_res["egress_dns_only"],
"four_way_sha256_valid": sha_ok,
**disqualifiers,
}
"""100-Point Hard-Gated Capstone Scorecard, Topology YAML Audit & Live FastAPI + OTel Service."""
from __future__ import annotations
import json
import re
import threading
import time
from collections import deque
from collections.abc import Sequence
from pathlib import Path
from typing import Any
import yaml
from fastapi import FastAPI, Response, status
from fastapi.responses import PlainTextResponse
from fastapi.testclient import TestClient
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 pydantic import BaseModel, ConfigDict, Field, model_validator
from production_platform_capstone_lab.end_to_end_architecture_audit import (
CapstoneBehavioralEvidence,
audit_behavioral_submission,
evaluate_mcp_sandbox_policy,
simulate_archetype_e2e,
)
DOMAIN_WEIGHTS: dict[str, int] = {
"data_lakehouse_pit": 15,
"security_k8s_sandbox": 15,
"gateway_and_serving": 20,
"mlops_cicd_canary": 15,
"observability_late_labels_sre": 15,
"live_chaos_and_finops": 20,
}
PASS_THRESHOLD_SCORE: float = 80.0
HARD_DISQUALIFIERS: tuple[str, ...] = (
"plaintext_secrets_present",
"latest_container_tag_used",
"pit_future_leakage_detected",
"unsandboxed_mcp_execution",
"missing_canary_rollback",
"missing_telemetry_or_pii_leak",
)
FORBIDDEN_HIGH_CARDINALITY_LABELS: frozenset[str] = frozenset(
{"user_id", "request_id", "trace_id", "span_id", "session_id", "email"}
)
_PII_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
_PII_CARD_RE = re.compile(r"\b(?:\d[ -]*?){13,19}\b")
_PII_PHONE_RE = re.compile(r"(?<!\d)(?:\+?\d{1,3}[-.\s]?)?(?:\(?\d{3}\)?[-.\s]?)\d{3}[-.\s]?\d{4}(?!\d)")
_PII_SECRET_RE = re.compile(
r"\b(?:Bearer\s+[A-Za-z0-9._-]{8,}|sk-[A-Za-z0-9_-]{8,}|AKIA[0-9A-Z]{16}|ghp_[A-Za-z0-9]{12,})\b"
)
def _is_valid_luhn(digits: str) -> bool:
"""Validate 13-19 digit payment PAN using the Mod-10 Luhn checksum."""
if not (13 <= len(digits) <= 19) or not digits.isdigit():
return False
total = 0
for idx, ch in enumerate(reversed(digits)):
val = int(ch)
if idx % 2 == 1:
val *= 2
if val > 9:
val -= 9
total += val
return (total % 10) == 0
def _redact_card_if_luhn(match: re.Match[str]) -> str:
raw = match.group(0)
digits = re.sub(r"[^0-9]", "", raw)
if _is_valid_luhn(digits):
return "[REDACTED_CARD]"
return raw
def redact_pii(text: str) -> str:
"""Redact credentials, emails, Luhn-valid payment cards, and phone numbers prior to OTel/logs."""
cleaned = _PII_SECRET_RE.sub("[REDACTED_SECRET]", text)
cleaned = _PII_EMAIL_RE.sub("[REDACTED_EMAIL]", cleaned)
cleaned = _PII_CARD_RE.sub(_redact_card_if_luhn, cleaned)
cleaned = _PII_PHONE_RE.sub("[REDACTED_PHONE]", cleaned)
return cleaned
class CapstoneRubricSubmission(BaseModel):
"""Structured submission evaluated against the unified 6-domain 100-point rubric."""
model_config = ConfigDict(extra="forbid")
submission_id: str
archetype_id: str = Field(pattern="^(RecSys-MLops|Card-Fraud-Platform|Agentic-LLM-Platform)$")
data_lakehouse_pit: float = Field(ge=0.0, le=15.0)
security_k8s_sandbox: float = Field(ge=0.0, le=15.0)
gateway_and_serving: float = Field(ge=0.0, le=20.0)
mlops_cicd_canary: float = Field(ge=0.0, le=15.0)
observability_late_labels_sre: float = Field(ge=0.0, le=15.0)
live_chaos_and_finops: float = Field(ge=0.0, le=20.0)
plaintext_secrets_present: bool = False
latest_container_tag_used: bool = False
pit_future_leakage_detected: bool = False
unsandboxed_mcp_execution: bool = False
missing_canary_rollback: bool = False
missing_telemetry_or_pii_leak: bool = False
class CapstoneAuditRequest(BaseModel):
"""Live FastAPI /audit/e2e payload accepting explicit rubric scores or behavioral evidence."""
model_config = ConfigDict(extra="forbid")
submission: CapstoneRubricSubmission | None = None
behavioral_evidence: CapstoneBehavioralEvidence | None = None
trace_note: str = Field(default="routine_capstone_gate_audit", max_length=512)
seed: int = Field(default=42, ge=0, le=100_000)
@model_validator(mode="after")
def _require_submission_or_evidence(self) -> CapstoneAuditRequest:
if self.submission is None and self.behavioral_evidence is None:
raise ValueError("Provide at least one of 'submission' or 'behavioral_evidence'")
return self
def evaluate_capstone_rubric(submission: CapstoneRubricSubmission) -> dict[str, Any]:
"""Compute weighted 6-domain 100-point score (>= 80.0 pass) with 6 hard disqualifiers."""
domain_scores = {
"data_lakehouse_pit": round(submission.data_lakehouse_pit, 2),
"security_k8s_sandbox": round(submission.security_k8s_sandbox, 2),
"gateway_and_serving": round(submission.gateway_and_serving, 2),
"mlops_cicd_canary": round(submission.mlops_cicd_canary, 2),
"observability_late_labels_sre": round(submission.observability_late_labels_sre, 2),
"live_chaos_and_finops": round(submission.live_chaos_and_finops, 2),
}
raw_total = round(sum(domain_scores.values()), 2)
triggered_disqualifiers = [
flag for flag in HARD_DISQUALIFIERS if bool(getattr(submission, flag))
]
min_domain = min(domain_scores.values())
if triggered_disqualifiers:
status_verdict = "DISQUALIFIED"
certified = False
elif raw_total >= PASS_THRESHOLD_SCORE:
status_verdict = "CERTIFIED_PRODUCTION_READY"
certified = True
else:
status_verdict = "NEEDS_REMEDIATION"
certified = False
effective_score = 0.0 if triggered_disqualifiers else raw_total
return {
"submission_id": submission.submission_id,
"archetype_id": submission.archetype_id,
"domain_weights": DOMAIN_WEIGHTS,
"pass_threshold_score": PASS_THRESHOLD_SCORE,
"domain_scores": domain_scores,
"min_domain_score": min_domain,
"raw_total_score": raw_total,
"effective_score": effective_score,
"triggered_disqualifiers": triggered_disqualifiers,
"disqualifier_count": len(triggered_disqualifiers),
"status": status_verdict,
"production_ready": certified,
"deploy_gate_open": certified,
}
def run_capstone_rubric_benchmarks() -> dict[str, Any]:
"""Evaluate 3 canonical capstone submissions proving >=80 gating and 6 hard disqualifiers."""
submissions = (
CapstoneRubricSubmission(
submission_id="sota_flagship_submission",
archetype_id="Agentic-LLM-Platform",
data_lakehouse_pit=14.4,
security_k8s_sandbox=14.6,
gateway_and_serving=19.4,
mlops_cicd_canary=14.2,
observability_late_labels_sre=14.5,
live_chaos_and_finops=19.3,
),
CapstoneRubricSubmission(
submission_id="insecure_latest_agent_submission",
archetype_id="RecSys-MLops",
data_lakehouse_pit=13.5,
security_k8s_sandbox=10.5,
gateway_and_serving=17.0,
mlops_cicd_canary=13.0,
observability_late_labels_sre=12.5,
live_chaos_and_finops=16.5,
unsandboxed_mcp_execution=True,
latest_container_tag_used=True,
),
CapstoneRubricSubmission(
submission_id="naive_monolith_submission",
archetype_id="Card-Fraud-Platform",
data_lakehouse_pit=7.5,
security_k8s_sandbox=6.0,
gateway_and_serving=9.5,
mlops_cicd_canary=7.0,
observability_late_labels_sre=6.5,
live_chaos_and_finops=9.0,
plaintext_secrets_present=True,
pit_future_leakage_detected=True,
missing_canary_rollback=True,
missing_telemetry_or_pii_leak=True,
),
)
results = [evaluate_capstone_rubric(sub) for sub in submissions]
return {
"domain_weights": DOMAIN_WEIGHTS,
"pass_threshold_score": PASS_THRESHOLD_SCORE,
"hard_disqualifiers": list(HARD_DISQUALIFIERS),
"submissions": results,
"by_id": {str(r["submission_id"]): r for r in results},
}
def audit_topology_yaml(config_path: Path) -> dict[str, Any]:
"""Verify topology YAML has official pinned images, loopback binds, DNS egress & 0 secrets."""
raw_text = config_path.read_text(encoding="utf-8")
parsed = yaml.safe_load(raw_text)
if not isinstance(parsed, dict) or "services" not in parsed:
raise ValueError("Invalid topology YAML structure: missing 'services' mapping")
services = parsed["services"]
if not isinstance(services, dict):
raise ValueError("'services' must be a YAML mapping")
latest_tags: list[str] = []
placeholder_images: list[str] = []
non_loopback_binds: list[str] = []
pinned_images: list[str] = []
for svc_name, svc_cfg in services.items():
if not isinstance(svc_cfg, dict):
continue
image = str(svc_cfg.get("image", ""))
if image:
if "fsds-sota/" in image:
placeholder_images.append(f"{svc_name}:{image}")
if image.endswith(":latest") or ":" not in image:
latest_tags.append(f"{svc_name}:{image}")
else:
pinned_images.append(image)
bind_addr = str(svc_cfg.get("bind", ""))
if bind_addr and not bind_addr.startswith("127.0.0.1:"):
non_loopback_binds.append(f"{svc_name}:{bind_addr}")
secret_hits = _PII_SECRET_RE.findall(raw_text)
if "0.0.0.0" in raw_text:
non_loopback_binds.append("literal_0.0.0.0_found")
sandbox = services.get("mcp_tool_sandbox", {})
sandbox_dict = sandbox if isinstance(sandbox, dict) else {}
sandbox_eval = evaluate_mcp_sandbox_policy(sandbox_dict)
sandbox_hardened = bool(sandbox_eval["passed"] and sandbox_eval["egress_dns_only"])
all_passed = (
len(latest_tags) == 0
and len(placeholder_images) == 0
and len(non_loopback_binds) == 0
and len(secret_hits) == 0
and sandbox_hardened
and len(pinned_images) >= 15
)
return {
"config_path": str(config_path),
"services_count": len(services),
"pinned_images_count": len(pinned_images),
"latest_tags_found": latest_tags,
"placeholder_images_found": placeholder_images,
"non_loopback_binds": non_loopback_binds,
"plaintext_secrets_found": len(secret_hits),
"mcp_sandbox_hardened": sandbox_hardened,
"mcp_egress_dns_only": bool(sandbox_eval["egress_dns_only"]),
"all_passed": all_passed,
}
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-capstone-control-plane",
) -> tuple[TracerProvider, BoundedInMemorySpanExporter, trace.Tracer]:
"""Create an isolated TracerProvider attached to a BoundedInMemorySpanExporter."""
exporter = BoundedInMemorySpanExporter(maxlen=256)
provider = TracerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer(service_name)
return provider, exporter, tracer
class PrometheusCapstoneMetrics:
"""Low-cardinality Prometheus text exposition store blocking high-cardinality labels."""
def __init__(self) -> None:
self.audits_by_status: dict[tuple[str, str], int] = {}
self.latest_score_by_archetype: dict[str, float] = {}
self.duration_buckets: dict[float, int] = {0.025: 0, 0.05: 0, 0.1: 0, 0.25: 0, 1.0: 0}
self.duration_sum: float = 0.0
self.duration_count: int = 0
@staticmethod
def validate_labels(labels: dict[str, str]) -> None:
bad = set(labels.keys()) & FORBIDDEN_HIGH_CARDINALITY_LABELS
if bad:
raise ValueError(f"High-cardinality Prometheus labels forbidden: {sorted(bad)}")
def record_audit(
self,
archetype_id: str,
status_verdict: str,
effective_score: float,
duration_sec: float,
) -> None:
labels = {"archetype": archetype_id, "status": status_verdict}
self.validate_labels(labels)
key = (archetype_id, status_verdict)
self.audits_by_status[key] = self.audits_by_status.get(key, 0) + 1
self.latest_score_by_archetype[archetype_id] = effective_score
for le in self.duration_buckets:
if duration_sec <= le:
self.duration_buckets[le] += 1
self.duration_sum += duration_sec
self.duration_count += 1
def render_exposition(self) -> str:
lines: list[str] = [
"# HELP fsds_capstone_audits_total Total capstone E2E audits processed",
"# TYPE fsds_capstone_audits_total counter",
]
for (arch, st), count in sorted(self.audits_by_status.items()):
lines.append(
f'fsds_capstone_audits_total{{archetype="{arch}",status="{st}"}} {count}'
)
lines.extend(
[
"# HELP fsds_capstone_readiness_score Latest effective capstone readiness score",
"# TYPE fsds_capstone_readiness_score gauge",
]
)
for arch, sc in sorted(self.latest_score_by_archetype.items()):
lines.append(f'fsds_capstone_readiness_score{{archetype="{arch}"}} {sc:.2f}')
lines.extend(
[
"# HELP fsds_capstone_audit_duration_seconds Audit latency histogram",
"# TYPE fsds_capstone_audit_duration_seconds histogram",
]
)
for le, cnt in sorted(self.duration_buckets.items()):
lines.append(f'fsds_capstone_audit_duration_seconds_bucket{{le="{le}"}} {cnt}')
lines.append(f'fsds_capstone_audit_duration_seconds_bucket{{le="+Inf"}} {self.duration_count}')
lines.append(f"fsds_capstone_audit_duration_seconds_sum {self.duration_sum:.6f}")
lines.append(f"fsds_capstone_audit_duration_seconds_count {self.duration_count}")
return "\n".join(lines) + "\n"
def create_capstone_app(
topology_path: Path,
exporter: BoundedInMemorySpanExporter | None = None,
readiness_override: bool | None = None,
) -> tuple[FastAPI, BoundedInMemorySpanExporter, PrometheusCapstoneMetrics]:
"""Create the live FastAPI Capstone Readiness & Telemetry Audit API."""
if exporter is None:
_provider, active_exporter, tracer = create_in_memory_telemetry()
else:
active_exporter = exporter
provider = TracerProvider(
resource=Resource.create({"service.name": "fsds-capstone-control-plane"})
)
provider.add_span_processor(SimpleSpanProcessor(active_exporter))
tracer = provider.get_tracer("fsds-capstone-control-plane")
metrics = PrometheusCapstoneMetrics()
app = FastAPI(title="FSDS-SOTA-2026 Capstone Control Plane", version="2026.1.0")
@app.get("/health/live")
def health_live() -> dict[str, str]:
return {"status": "alive", "service": "fsds-capstone-control-plane"}
@app.get("/health/ready")
def health_ready(response: Response) -> dict[str, Any]:
with tracer.start_as_current_span("capstone.health.ready") as span:
cfg_audit = audit_topology_yaml(topology_path)
is_ready = cfg_audit["all_passed"] if readiness_override is None else readiness_override
span.set_attribute("capstone.topology_passed", bool(cfg_audit["all_passed"]))
span.set_attribute("capstone.ready", bool(is_ready))
if not is_ready:
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return {"status": "not_ready", "topology_audit": cfg_audit}
return {"status": "ready", "topology_audit": cfg_audit}
@app.post("/audit/e2e")
def audit_e2e(payload: CapstoneAuditRequest) -> dict[str, Any]:
req_started = time.perf_counter()
safe_note = redact_pii(payload.trace_note)
behavioral_audit: dict[str, Any] | None = None
if payload.behavioral_evidence is not None:
behavioral_audit = audit_behavioral_submission(
payload.behavioral_evidence,
seed=payload.seed,
)
active_submission = CapstoneRubricSubmission(
submission_id=str(behavioral_audit["submission_id"]),
archetype_id=str(behavioral_audit["archetype_id"]),
data_lakehouse_pit=float(behavioral_audit["data_lakehouse_pit"]),
security_k8s_sandbox=float(behavioral_audit["security_k8s_sandbox"]),
gateway_and_serving=float(behavioral_audit["gateway_and_serving"]),
mlops_cicd_canary=float(behavioral_audit["mlops_cicd_canary"]),
observability_late_labels_sre=float(
behavioral_audit["observability_late_labels_sre"]
),
live_chaos_and_finops=float(behavioral_audit["live_chaos_and_finops"]),
plaintext_secrets_present=bool(behavioral_audit["plaintext_secrets_present"]),
latest_container_tag_used=bool(behavioral_audit["latest_container_tag_used"]),
pit_future_leakage_detected=bool(
behavioral_audit["pit_future_leakage_detected"]
),
unsandboxed_mcp_execution=bool(behavioral_audit["unsandboxed_mcp_execution"]),
missing_canary_rollback=bool(behavioral_audit["missing_canary_rollback"]),
missing_telemetry_or_pii_leak=bool(
behavioral_audit["missing_telemetry_or_pii_leak"]
),
)
else:
assert payload.submission is not None
active_submission = payload.submission
with tracer.start_as_current_span("capstone.audit.request") as root_sp:
root_sp.set_attribute("capstone.submission_id", active_submission.submission_id)
root_sp.set_attribute("capstone.archetype_id", active_submission.archetype_id)
root_sp.set_attribute("capstone.trace_note_redacted", safe_note)
with tracer.start_as_current_span("capstone.topology.verify") as top_sp:
cfg_audit = audit_topology_yaml(topology_path)
top_sp.set_attribute("capstone.services_count", cfg_audit["services_count"])
top_sp.set_attribute("capstone.latest_tags_count", len(cfg_audit["latest_tags_found"]))
with tracer.start_as_current_span("capstone.failure_injection.check") as fi_sp:
e2e_sota = simulate_archetype_e2e(
archetype_id=active_submission.archetype_id,
tier="sota_2026_platform",
n_requests=1000,
seed=payload.seed,
)
fi_sp.set_attribute("capstone.e2e_p99_ms", e2e_sota["p99_ms"])
fi_sp.set_attribute("capstone.finops_tco_usd", e2e_sota["finops_tco_usd_per_1m"])
with tracer.start_as_current_span("capstone.rubric.score") as rb_sp:
rubric = evaluate_capstone_rubric(active_submission)
rb_sp.set_attribute("capstone.effective_score", rubric["effective_score"])
rb_sp.set_attribute("capstone.status", rubric["status"])
rb_sp.set_attribute("capstone.disqualifiers", rubric["disqualifier_count"])
root_sp.set_attribute("capstone.deploy_gate_open", rubric["deploy_gate_open"])
elapsed_sec = max(1e-6, time.perf_counter() - req_started)
root_sp.set_attribute("capstone.audit_duration_ms", round(elapsed_sec * 1000.0, 3))
metrics.record_audit(
archetype_id=active_submission.archetype_id,
status_verdict=str(rubric["status"]),
effective_score=float(rubric["effective_score"]),
duration_sec=elapsed_sec,
)
return {
"rubric": rubric,
"behavioral_audit": behavioral_audit,
"sota_e2e_snapshot": e2e_sota,
"topology_passed": cfg_audit["all_passed"],
"trace_note_redacted": safe_note,
"audit_duration_ms": round(elapsed_sec * 1000.0, 3),
}
@app.get("/metrics", response_class=PlainTextResponse)
def prometheus_metrics() -> str:
return metrics.render_exposition()
return app, active_exporter, metrics
def run_capstone_service_and_otel_checks(lab_root: Path | None = None) -> dict[str, Any]:
"""Run live FastAPI checks verifying OTel spans, /metrics, /health/ready & zero PII leak."""
root = lab_root or Path(__file__).resolve().parents[2]
topology_path = root / "configs" / "capstone_platform_topology.yaml"
app, exporter, _metrics = create_capstone_app(topology_path=topology_path)
pii_probe = (
"Audit for an.nguyen@example.com card 4111-2222-3333-4448 "
"phone +1-415-555-0199 secret sk-testsecretkey999"
)
flagship_payload = {
"submission": {
"submission_id": "flagship_live_check",
"archetype_id": "Agentic-LLM-Platform",
"data_lakehouse_pit": 14.4,
"security_k8s_sandbox": 14.6,
"gateway_and_serving": 19.4,
"mlops_cicd_canary": 14.2,
"observability_late_labels_sre": 14.5,
"live_chaos_and_finops": 19.3,
},
"trace_note": pii_probe,
"seed": 42,
}
disqualified_payload = {
"submission": {
"submission_id": "insecure_live_check",
"archetype_id": "Card-Fraud-Platform",
"data_lakehouse_pit": 13.5,
"security_k8s_sandbox": 10.5,
"gateway_and_serving": 18.0,
"mlops_cicd_canary": 13.0,
"observability_late_labels_sre": 12.5,
"live_chaos_and_finops": 16.5,
"unsandboxed_mcp_execution": True,
},
"trace_note": "check_hard_disqualifier",
"seed": 42,
}
with TestClient(app) as client:
live_resp = client.get("/health/live")
ready_resp = client.get("/health/ready")
audit_ok = client.post("/audit/e2e", json=flagship_payload)
audit_bad = client.post("/audit/e2e", json=disqualified_payload)
metrics_resp = client.get("/metrics")
assert live_resp.status_code == 200
assert ready_resp.status_code == 200
assert audit_ok.status_code == 200
assert audit_bad.status_code == 200
assert metrics_resp.status_code == 200
spans = exporter.get_finished_spans()
serialized_spans = json.dumps([dict(s.attributes or {}) for s in spans])
pii_markers = ("an.nguyen@example.com", "4111-2222-3333-4448", "415-555-0199", "sk-testsecretkey999")
pii_leaks = sum(1 for marker in pii_markers if marker in serialized_spans)
metrics_text = metrics_resp.text
prom_ok = (
"fsds_capstone_audits_total" in metrics_text
and "fsds_capstone_readiness_score" in metrics_text
and 'le="+Inf"' in metrics_text
)
return {
"health_live_status": live_resp.status_code,
"health_ready_status": ready_resp.status_code,
"flagship_verdict": audit_ok.json()["rubric"]["status"],
"disqualified_verdict": audit_bad.json()["rubric"]["status"],
"otel_span_count": len(spans),
"span_names": [s.name for s in spans],
"pii_leaks_count": pii_leaks,
"prometheus_checks_passed": prom_ok,
}
def main() -> None:
root = Path(__file__).resolve().parents[2]
res = run_capstone_service_and_otel_checks(lab_root=root)
from production_platform_capstone_lab.end_to_end_architecture_audit import (
run_failure_injection_suite,
)
fi = run_failure_injection_suite(seed=42)
print(
f"Capstone Live Check: ready={res['health_ready_status']} | "
f"OTel spans={res['otel_span_count']} | PII leaks={res['pii_leaks_count']} | "
f"Failure scenarios passed={fi['passed_scenarios']}/{fi['total_scenarios']}"
)
"""Deterministic CLI runner generating artifacts/t2_ch26_wb26_results.json."""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from pathlib import Path
from typing import Any
import yaml
def _ensure_src_on_path() -> None:
src_dir = str(Path(__file__).resolve().parents[1] / "src")
if src_dir not in sys.path:
sys.path.insert(0, src_dir)
def run_full_lab_suite(seed: int = 42, lab_root: Path | None = None) -> dict[str, Any]:
"""Execute all WB-Ch26 capstone simulations & live checks deterministically."""
_ensure_src_on_path()
from production_platform_capstone_lab.capstone_service_and_rubric import (
audit_topology_yaml,
create_in_memory_telemetry,
run_capstone_rubric_benchmarks,
run_capstone_service_and_otel_checks,
)
from production_platform_capstone_lab.end_to_end_architecture_audit import (
CapstoneBehavioralEvidence,
audit_behavioral_submission,
run_cross_layer_e2e_tco_suite,
run_failure_injection_suite,
)
root = lab_root or Path(__file__).resolve().parents[1]
topology_path = root / "configs" / "capstone_platform_topology.yaml"
parsed_topo = yaml.safe_load(topology_path.read_text(encoding="utf-8"))
topo_sandbox_cfg = dict(dict(parsed_topo.get("services", {})).get("mcp_tool_sandbox", {}))
_provider, suite_exp, tracer = create_in_memory_telemetry("fsds-wb26-suite")
with tracer.start_as_current_span("wb26.capstone.suite") as root_span:
root_span.set_attribute("capstone.seed", seed)
with tracer.start_as_current_span("wb26.exp1_e2e_latency_tco") as sp1:
exp1_e2e = run_cross_layer_e2e_tco_suite(seed=seed, n_requests=4000)
agentic = exp1_e2e["by_archetype"]["Agentic-LLM-Platform"]
sp1.set_attribute("e2e.agentic_p99_speedup_x", agentic["p99_speedup_x"])
sp1.set_attribute("e2e.agentic_tco_savings_pct", agentic["tco_savings_pct"])
with tracer.start_as_current_span("wb26.exp2_failure_injection") as sp2:
exp2_fi = run_failure_injection_suite(seed=seed, mcp_sandbox_cfg=topo_sandbox_cfg)
sp2.set_attribute("fi.passed_scenarios", exp2_fi["passed_scenarios"])
sp2.set_attribute("fi.total_scenarios", exp2_fi["total_scenarios"])
with tracer.start_as_current_span("wb26.exp3_rubric_and_topology") as sp3:
exp3_rubric = run_capstone_rubric_benchmarks()
exp3_topo = audit_topology_yaml(topology_path)
sota_ev = CapstoneBehavioralEvidence(
submission_id="wb26_behavioral_topology_audit",
archetype_id="Agentic-LLM-Platform",
watermark_minutes=10.0,
allowed_lateness_minutes=8.0,
dlq_enabled=True,
pit_asof_enforced=True,
plaintext_secret_count=int(exp3_topo["plaintext_secrets_found"]),
latest_tag_count=len(exp3_topo["latest_tags_found"]),
loopback_host_binds=len(exp3_topo["non_loopback_binds"]) == 0,
vault_dynamic_leases=True,
istio_strict_mtls=True,
mcp_sandbox_config=topo_sandbox_cfg,
cache_hit_rate=0.34,
target_load_rho=0.50,
admission_control_enabled=True,
dual_tpm_usd_budget=True,
git_sha256=hashlib.sha256(b"git-commit-wb26").hexdigest(),
dvc_sha256=hashlib.sha256(b"dvc-lock-wb26").hexdigest(),
mlflow_sha256=hashlib.sha256(b"mlflow-logged-model-wb26").hexdigest(),
prompt_sha256=hashlib.sha256(b"prompt-eval-suite-wb26").hexdigest(),
mlflow_aliases_configured=True,
canary_rollback_monitor="msprt",
otel_pii_redaction_enabled=True,
forbidden_high_card_labels=0,
otel_genai_v1_37_plus=True,
ragas_eval_enabled=True,
prometheus_native_histograms=True,
sre_multi_window_burn_rate=True,
active_audit_ht_enabled=True,
finops_tco_verified=True,
chaos_scenarios_passed=int(exp2_fi["passed_scenarios"]),
)
exp3_behav = audit_behavioral_submission(sota_ev, seed=seed)
sp3.set_attribute(
"rubric.flagship_score",
exp3_rubric["by_id"]["sota_flagship_submission"]["effective_score"],
)
sp3.set_attribute("topology.all_passed", exp3_topo["all_passed"])
with tracer.start_as_current_span("wb26.exp4_live_fastapi_otel") as sp4:
exp4_live = run_capstone_service_and_otel_checks(lab_root=root)
sp4.set_attribute("live.otel_spans", exp4_live["otel_span_count"])
sp4.set_attribute("live.pii_leaks", exp4_live["pii_leaks_count"])
suite_spans = suite_exp.get_finished_spans()
suite_otel = {
"span_count": len(suite_spans),
"span_names": [s.name for s in suite_spans],
"spans": [
{
"name": s.name,
"status": s.status.status_code.name,
"attributes": dict(s.attributes or {}),
}
for s in suite_spans
],
}
recsys = exp1_e2e["by_archetype"]["RecSys-MLops"]
fraud = exp1_e2e["by_archetype"]["Card-Fraud-Platform"]
llm = exp1_e2e["by_archetype"]["Agentic-LLM-Platform"]
fi_by = exp2_fi["by_id"]
fi_late = fi_by["late_data_watermark"]
fi_pit = fi_by["pit_training_serving_skew"]
fi_surge = fi_by["bursty_gpu_surge_10x"]
fi_mcp = fi_by["mcp_agent_sandbox_isolation"]
fi_sprt = fi_by["canary_sprt_rollback"]
fi_delay = fi_by["delayed_label_ipcw_proxy"]
rub_flag = exp3_rubric["by_id"]["sota_flagship_submission"]
rub_insec = exp3_rubric["by_id"]["insecure_latest_agent_submission"]
workbench_panels = {
"kpis": [
{
"id": "kpi_agentic_e2e_tco",
"label": "Agentic-LLM SOTA E2E p99 & FinOps TCO",
"value": f"{llm['sota_2026_platform']['p99_ms']} ms",
"unit": (
f"({llm['p99_speedup_x']}x faster | "
f"-{llm['tco_savings_pct']}% TCO)"
),
"status": "ok",
"detail": (
f"Tuned Semantic Cache + Disagg P/D + CUDA Graphs cuts p99 from "
f"{llm['naive_monolith']['p99_ms']} ms to {llm['sota_2026_platform']['p99_ms']} ms "
f"(${llm['sota_2026_platform']['finops_tco_usd_per_1m']}/1M reqs)."
),
},
{
"id": "kpi_fraud_pit_and_slo",
"label": "Card-Fraud-Platform p99 SLO & PIT Skew (#15)",
"value": f"{fraud['sota_2026_platform']['p99_ms']} ms",
"unit": (
f"({fraud['sota_2026_platform']['slo_satisfaction_pct']}% <= 45ms | "
f"{fi_pit['sota_2026']['future_leakage_pct']}% PIT leak)"
),
"status": "ok",
"detail": (
f"ASOF PIT eliminates {fi_pit['naive']['future_leakage_pct']}% future leakage "
f"(PSI={fi_pit['sota_2026']['train_serve_psi']}) and cuts TCO by "
f"{fraud['tco_savings_pct']}%."
),
},
{
"id": "kpi_recsys_tco_and_slo",
"label": "RecSys-MLops Multi-Stage SLO & TCO Savings",
"value": f"-{recsys['tco_savings_pct']}% TCO",
"unit": (
f"(${recsys['sota_2026_platform']['finops_tco_usd_per_1m']}/1M | "
f"{recsys['sota_2026_platform']['slo_satisfaction_pct']}% SLO)"
),
"status": "ok",
"detail": (
f"Feast/ClickHouse + Microbatching + Cache lowers p99 from "
f"{recsys['naive_monolith']['p99_ms']} ms to "
f"{recsys['sota_2026_platform']['p99_ms']} ms."
),
},
{
"id": "kpi_failure_injection_suite",
"label": "6-Scenario Production Failure-Injection Suite",
"value": f"{exp2_fi['passed_scenarios']}/{exp2_fi['total_scenarios']} PASS",
"unit": (
f"(MCP {fi_mcp['sota_2026']['attacks_blocked_pct']}% | "
f"Canary -{fi_sprt['sota_canary_sprt']['blast_radius_reduction_pct']}%)"
),
"status": "ok",
"detail": (
f"Late Watermark={fi_late['sota_2026']['completeness_pct']}%, "
f"10x Surge Goodput={fi_surge['sota_2026']['interactive_goodput_pct']}%, "
f"Delayed-Label Audit MAE={fi_delay['sota_2026']['audit_error_pp']} pp."
),
},
{
"id": "kpi_capstone_rubric_gating",
"label": "100-Pt 6-Domain Rubric (>=80 Pass, 6 HD Veto)",
"value": f"{rub_flag['effective_score']}/100",
"unit": (
f"(Flagship CERTIFIED >=80 | Insecure 83pt -> {rub_insec['status']})"
),
"status": "ok",
"detail": (
f"6-domain (15,15,20,15,15,20) rubric with 6 Hard Disqualifiers vetoes "
f"insecure submissions ({rub_insec['raw_total_score']} raw -> "
f"{rub_insec['effective_score']} effective)."
),
},
{
"id": "kpi_live_fastapi_otel_zero_pii",
"label": "Live FastAPI Control Plane + OTel & Zero PII",
"value": f"{exp4_live['otel_span_count']}+{suite_otel['span_count']} Spans",
"unit": (
f"({exp4_live['pii_leaks_count']} PII leaks | "
f"{exp3_topo['pinned_images_count']} pinned imgs)"
),
"status": "ok",
"detail": (
f"HTTP {exp4_live['health_ready_status']} /health/ready, Prometheus /metrics clean, "
f"{exp3_topo['services_count']} topology services on 127.0.0.1 with 0 :latest tags."
),
},
],
"bars": [
{
"id": "bar_e2e_p99_speedup_by_archetype",
"title": "Cross-Layer E2E p99 Latency Speedup (Naive Monolith / SOTA 2026)",
"metric_label": "Speedup (x)",
"items": [
{
"label": arch["archetype_id"],
"value": arch["p99_speedup_x"],
"display": (
f"{arch['p99_speedup_x']}x "
f"({arch['naive_monolith']['p99_ms']} -> "
f"{arch['sota_2026_platform']['p99_ms']} ms)"
),
"css_class": "is-fast",
}
for arch in exp1_e2e["comparisons"]
],
},
{
"id": "bar_finops_tco_usd_per_1m",
"title": "FinOps TCO Comparison Across Archetypes ($ USD / 1M Requests)",
"metric_label": "USD / 1M",
"items": [
item
for arch in exp1_e2e["comparisons"]
for item in (
{
"label": f"{arch['archetype_id']} (Naive)",
"value": arch["naive_monolith"]["finops_tco_usd_per_1m"],
"display": f"${arch['naive_monolith']['finops_tco_usd_per_1m']}/1M",
"css_class": "is-slow",
},
{
"label": f"{arch['archetype_id']} (SOTA)",
"value": arch["sota_2026_platform"]["finops_tco_usd_per_1m"],
"display": (
f"${arch['sota_2026_platform']['finops_tco_usd_per_1m']}/1M "
f"(-{arch['tco_savings_pct']}%)"
),
"css_class": "is-fast",
},
)
],
},
{
"id": "bar_failure_injection_resilience",
"title": "6-Scenario Production Resilience: Naive vs SOTA 2026 Guarded (%)",
"metric_label": "Score (%)",
"items": [
{
"label": "S1 Watermark Completeness",
"value": fi_late["sota_2026"]["completeness_pct"],
"display": (
f"{fi_late['sota_2026']['completeness_pct']}% "
f"(vs Naive {fi_late['naive']['completeness_pct']}%)"
),
"css_class": "is-fast",
},
{
"label": "S3 10x Surge Goodput",
"value": fi_surge["sota_2026"]["interactive_goodput_pct"],
"display": (
f"{fi_surge['sota_2026']['interactive_goodput_pct']}% "
f"(vs Naive {fi_surge['naive']['goodput_pct']}%)"
),
"css_class": "is-fast",
},
{
"label": "S4 MCP Sandbox Blocked",
"value": fi_mcp["sota_2026"]["attacks_blocked_pct"],
"display": (
f"{fi_mcp['sota_2026']['attacks_blocked_pct']}% "
f"(vs Naive {fi_mcp['naive']['attacks_blocked_pct']}%)"
),
"css_class": "is-fast",
},
{
"label": "S5 SPRT Blast Reduction",
"value": fi_sprt["sota_canary_sprt"]["blast_radius_reduction_pct"],
"display": (
f"{fi_sprt['sota_canary_sprt']['blast_radius_reduction_pct']}% "
f"(Trips @{fi_sprt['sota_canary_sprt']['tripped_at_step_pct']}%)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_capstone_rubric_effective_scores",
"title": "100-Point Hard-Gated Capstone Scorecard Effective Scores",
"metric_label": "Effective Score",
"items": [
{
"label": str(sub["submission_id"]),
"value": sub["effective_score"],
"display": (
f"{sub['effective_score']}/100 "
f"(raw {sub['raw_total_score']} -> {sub['status']})"
),
"css_class": "is-fast" if sub["production_ready"] else "is-slow",
}
for sub in exp3_rubric["submissions"]
],
},
],
"tables": [
{
"id": "table_e2e_archetype_comparison",
"title": "Exp 1: Cross-Layer E2E Latency (ms), SLO Satisfaction & FinOps TCO",
"columns": [
"archetype_id",
"naive_p99_slo",
"sota_p99_slo",
"tco_naive_vs_sota",
"speedup_savings",
],
"rows": [
[
str(c["archetype_id"]),
(
f"{c['naive_monolith']['p99_ms']} ms "
f"({c['naive_monolith']['slo_satisfaction_pct']}%)"
),
(
f"{c['sota_2026_platform']['p99_ms']} ms "
f"({c['sota_2026_platform']['slo_satisfaction_pct']}%)"
),
(
f"${c['naive_monolith']['finops_tco_usd_per_1m']} -> "
f"${c['sota_2026_platform']['finops_tco_usd_per_1m']}"
),
f"{c['p99_speedup_x']}x | -{c['tco_savings_pct']}%",
]
for c in exp1_e2e["comparisons"]
],
},
{
"id": "table_failure_injection_6_scenarios",
"title": "Exp 2: 6-Scenario Production Failure-Injection Audit Matrix",
"columns": ["scenario_id", "naive_failure_mode", "sota_2026_outcome", "status"],
"rows": [
[
"S1 late_data_watermark",
(
f"Completeness={fi_late['naive']['completeness_pct']}%, "
f"MAPE={fi_late['naive']['aggregate_mape_pct']}%"
),
(
f"Completeness={fi_late['sota_2026']['completeness_pct']}%, "
f"MAPE={fi_late['sota_2026']['aggregate_mape_pct']}%"
),
"PASS" if fi_late["passed"] else "FAIL",
],
[
"S2 pit_training_serving_skew (#15)",
(
f"Leak={fi_pit['naive']['future_leakage_pct']}%, "
f"PSI={fi_pit['naive']['train_serve_psi']}"
),
(
f"Leak={fi_pit['sota_2026']['future_leakage_pct']}%, "
f"PSI={fi_pit['sota_2026']['train_serve_psi']}"
),
"PASS" if fi_pit["passed"] else "FAIL",
],
[
"S3 bursty_gpu_surge_10x (#21/#22)",
(
f"Goodput={fi_surge['naive']['goodput_pct']}%, "
f"p99={fi_surge['naive']['interactive_p99_ms']} ms"
),
(
f"Goodput={fi_surge['sota_2026']['interactive_goodput_pct']}%, "
f"p99={fi_surge['sota_2026']['interactive_p99_ms']} ms"
),
"PASS" if fi_surge["passed"] else "FAIL",
],
[
"S4 mcp_agent_sandbox_isolation",
(
f"Blocked={fi_mcp['naive']['attacks_blocked_pct']}%, "
f"Leaks={fi_mcp['naive']['secret_exfiltrations']}"
),
(
f"Blocked={fi_mcp['sota_2026']['attacks_blocked_pct']}%, "
f"Leaks={fi_mcp['sota_2026']['secret_exfiltrations']}"
),
"PASS" if fi_mcp["passed"] else "FAIL",
],
[
"S5 canary_sprt_rollback (#16)",
(
f"Exposed={fi_sprt['naive_big_bang']['exposed_requests']}, "
f"Fails={fi_sprt['naive_big_bang']['failed_requests']}"
),
(
f"Trips@{fi_sprt['sota_canary_sprt']['tripped_at_step_pct']}%, "
f"-{fi_sprt['sota_canary_sprt']['blast_radius_reduction_pct']}% blast"
),
"PASS" if fi_sprt["passed"] else "FAIL",
],
[
"S6 delayed_label_ipcw_proxy (#17)",
(
f"Naive={fi_delay['naive']['observed_accuracy_pct']}% "
f"(+{fi_delay['naive']['optimism_bias_pp']} pp)"
),
(
f"AuditHT={fi_delay['sota_2026']['active_audit_ht_accuracy_pct']}% "
f"({fi_delay['sota_2026']['audit_error_pp']} pp err, "
f"-{fi_delay['sota_2026']['detection_lead_days']}d)"
),
"PASS" if fi_delay["passed"] else "FAIL",
],
],
},
{
"id": "table_capstone_rubric_scorecards",
"title": "Exp 3: 100-Point Hard-Gated Capstone Submission Benchmarks",
"columns": [
"submission_id",
"archetype_id",
"raw_vs_effective",
"disqualifiers",
"verdict",
],
"rows": [
[
str(sub["submission_id"]),
str(sub["archetype_id"]),
f"{sub['raw_total_score']} -> {sub['effective_score']}",
", ".join(sub["triggered_disqualifiers"]) or "none",
str(sub["status"]),
]
for sub in exp3_rubric["submissions"]
],
},
{
"id": "table_live_service_and_topology_audit",
"title": "Exp 4: Live FastAPI Readiness, OTel Spans, PII Guard & YAML Audit",
"columns": ["component", "verified_scope", "observed_result", "status"],
"rows": [
[
"Topology YAML Security Audit",
"configs/capstone_platform_topology.yaml",
(
f"{exp3_topo['services_count']} services, "
f"{exp3_topo['pinned_images_count']} pinned imgs, "
f"0 :latest, 0 secrets, 127.0.0.1"
),
"PASS" if exp3_topo["all_passed"] else "FAIL",
],
[
"Live FastAPI /health/ready & /metrics",
"TestClient + Prometheus low-card metrics",
(
f"ready={exp4_live['health_ready_status']}, "
f"prom_ok={exp4_live['prometheus_checks_passed']}"
),
"PASS",
],
[
"OpenTelemetry Spans & Zero PII Leak",
"/audit/e2e hierarchical spans + PII probe",
(
f"{exp4_live['otel_span_count']} live + "
f"{suite_otel['span_count']} suite spans, "
f"{exp4_live['pii_leaks_count']} PII leaks"
),
"PASS" if exp4_live["pii_leaks_count"] == 0 else "FAIL",
],
],
},
],
}
return {
"unit_id": "T2-P5-U03",
"lab_id": "ch26-production-platform-capstone-workbench",
"seed": seed,
"exp1_e2e_latency_and_tco": exp1_e2e,
"exp2_failure_injection": exp2_fi,
"exp3_capstone_rubric": exp3_rubric,
"exp3_behavioral_audit": exp3_behav,
"exp3_topology_audit": exp3_topo,
"exp4_live_fastapi_otel": exp4_live,
"suite_otel_telemetry": suite_otel,
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(
description="Run WB-Ch26 Production Engineering Capstone Workbench Suite."
)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument(
"--output",
type=Path,
default=Path("artifacts/t2_ch26_wb26_results.json"),
)
args = parser.parse_args()
lab_root = Path(__file__).resolve().parents[1]
report = run_full_lab_suite(seed=args.seed, lab_root=lab_root)
out_path = args.output if args.output.is_absolute() else lab_root / args.output
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(report, indent=2), encoding="utf-8")
llm = report["exp1_e2e_latency_and_tco"]["by_archetype"]["Agentic-LLM-Platform"]
fi = report["exp2_failure_injection"]
live = report["exp4_live_fastapi_otel"]
print(
f"Saved {out_path} | Agentic p99={llm['sota_2026_platform']['p99_ms']}ms "
f"({llm['p99_speedup_x']}x, -{llm['tco_savings_pct']}% TCO) "
f"| FI={fi['passed_scenarios']}/{fi['total_scenarios']} "
f"| OTel Spans={live['otel_span_count']}+{report['suite_otel_telemetry']['span_count']} "
f"| PII Leaks={live['pii_leaks_count']}"
)
if __name__ == "__main__":
main()
"""Automated verification suite (32 tests, 0 skips) for WB-Ch26 Production Capstone Lab."""
from __future__ import annotations
import ast
import hashlib
import io
import json
import subprocess
import sys
import tokenize
from pathlib import Path
from typing import Any
import pytest
import yaml
from fastapi.testclient import TestClient
from hypothesis import given, settings
from hypothesis import strategies as st
from pydantic import ValidationError
from production_platform_capstone_lab.capstone_service_and_rubric import (
DOMAIN_WEIGHTS,
HARD_DISQUALIFIERS,
PASS_THRESHOLD_SCORE,
CapstoneAuditRequest,
CapstoneRubricSubmission,
PrometheusCapstoneMetrics,
audit_topology_yaml,
create_capstone_app,
evaluate_capstone_rubric,
redact_pii,
run_capstone_rubric_benchmarks,
run_capstone_service_and_otel_checks,
)
from production_platform_capstone_lab.end_to_end_architecture_audit import (
ARCHETYPE_SPECS,
CapstoneBehavioralEvidence,
StageLatencyConfig,
audit_behavioral_submission,
evaluate_mcp_sandbox_policy,
run_cross_layer_e2e_tco_suite,
simulate_archetype_e2e,
)
from scripts.run_lab_demo import run_full_lab_suite
LAB_ROOT = Path(__file__).resolve().parents[1]
TOPOLOGY_YAML = LAB_ROOT / "configs" / "capstone_platform_topology.yaml"
@pytest.fixture(scope="module")
def full_suite_42() -> dict[str, Any]:
return run_full_lab_suite(seed=42, lab_root=LAB_ROOT)
def test_01_ast_safety_no_type_ignore_no_sleep_no_pickle_or_binaries() -> None:
forbidden_modules = {"pickle", "cPickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
forbidden_calls = {"eval", "exec", "sleep"}
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 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:
assert alias.name.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.ImportFrom) and node.module:
assert node.module.split(".")[0] not in forbidden_modules
elif isinstance(node, ast.Call):
if isinstance(node.func, ast.Name):
assert node.func.id not in forbidden_calls
elif isinstance(node.func, ast.Attribute):
assert node.func.attr != "sleep"
for pat in ("*.png", "*.parquet", "*.duckdb*"):
assert not list(LAB_ROOT.rglob(pat))
def test_02_pydantic_strict_models_reject_extra_fields() -> None:
with pytest.raises(ValidationError):
StageLatencyConfig.model_validate(
{
"name": "s",
"mean_ms": 5.0,
"sigma_log": 0.2,
"utilization_rho": 0.5,
"tail_spike_prob": 0.01,
"tail_spike_ms": 10.0,
"extra_rogue": 1,
}
)
with pytest.raises(ValidationError):
CapstoneRubricSubmission.model_validate(
{
"submission_id": "bad",
"archetype_id": "RecSys-MLops",
"data_lakehouse_pit": 14.0,
"security_k8s_sandbox": 14.0,
"gateway_and_serving": 18.0,
"mlops_cicd_canary": 14.0,
"observability_late_labels_sre": 14.0,
"live_chaos_and_finops": 18.0,
"injected_field": True,
}
)
with pytest.raises(ValidationError):
CapstoneAuditRequest.model_validate(
{
"submission": {
"submission_id": "ok",
"archetype_id": "Card-Fraud-Platform",
"data_lakehouse_pit": 14.0,
"security_k8s_sandbox": 14.0,
"gateway_and_serving": 18.0,
"mlops_cicd_canary": 14.0,
"observability_late_labels_sre": 14.0,
"live_chaos_and_finops": 18.0,
},
"unexpected": "x",
}
)
def test_03_topology_yaml_hygiene_pinned_images_loopback_and_sandbox() -> None:
audit = audit_topology_yaml(TOPOLOGY_YAML)
assert audit["all_passed"] is True
assert audit["services_count"] >= 18
assert audit["pinned_images_count"] >= 18
assert audit["latest_tags_found"] == []
assert audit["placeholder_images_found"] == []
assert audit["non_loopback_binds"] == []
assert audit["plaintext_secrets_found"] == 0
assert audit["mcp_sandbox_hardened"] is True
assert audit["mcp_egress_dns_only"] is True
def test_04_topology_yaml_tamper_detection_catches_latest_bind_and_secret(tmp_path: Path) -> None:
base = yaml.safe_load(TOPOLOGY_YAML.read_text(encoding="utf-8"))
# Inject :latest
tamper_latest = json.loads(json.dumps(base))
tamper_latest["services"]["envoy_ai_gateway"]["image"] = "docker.io/envoyproxy/gateway:latest"
p1 = tmp_path / "latest.yaml"
p1.write_text(yaml.safe_dump(tamper_latest), encoding="utf-8")
assert audit_topology_yaml(p1)["all_passed"] is False
# Inject 0.0.0.0 bind
tamper_bind = json.loads(json.dumps(base))
tamper_bind["services"]["envoy_ai_gateway"]["bind"] = "0.0.0.0:8000"
p2 = tmp_path / "bind.yaml"
p2.write_text(yaml.safe_dump(tamper_bind), encoding="utf-8")
assert audit_topology_yaml(p2)["all_passed"] is False
# Inject static API secret
tamper_sec = json.loads(json.dumps(base))
tamper_sec["services"]["langfuse_llm_obs"]["auth_ref"] = "sk-hardcodedleaksecret12345"
p3 = tmp_path / "secret.yaml"
p3.write_text(yaml.safe_dump(tamper_sec), encoding="utf-8")
assert audit_topology_yaml(p3)["all_passed"] is False
# Disable sandbox read_only_root_fs
tamper_sb = json.loads(json.dumps(base))
tamper_sb["services"]["mcp_tool_sandbox"]["read_only_root_fs"] = False
p4 = tmp_path / "sandbox.yaml"
p4.write_text(yaml.safe_dump(tamper_sb), encoding="utf-8")
assert audit_topology_yaml(p4)["all_passed"] is False
# Inject container loopback 127.0.0.1 in egress_allowlist (H15 violation)
tamper_egress = json.loads(json.dumps(base))
tamper_egress["services"]["mcp_tool_sandbox"]["egress_allowlist"] = ["127.0.0.1:8123"]
p5 = tmp_path / "egress_loopback.yaml"
p5.write_text(yaml.safe_dump(tamper_egress), encoding="utf-8")
assert audit_topology_yaml(p5)["all_passed"] is False
# Inject unapproved placeholder registry fsds-sota/ image
tamper_ph = json.loads(json.dumps(base))
tamper_ph["services"]["mcp_tool_sandbox"]["image"] = "ghcr.io/fsds-sota/mcp-sandbox:2.6.0"
p6 = tmp_path / "placeholder.yaml"
p6.write_text(yaml.safe_dump(tamper_ph), encoding="utf-8")
assert audit_topology_yaml(p6)["all_passed"] is False
def test_05_e2e_recsys_mlops_sota_improves_p99_slo_and_tco(full_suite_42: dict[str, Any]) -> None:
rec = full_suite_42["exp1_e2e_latency_and_tco"]["by_archetype"]["RecSys-MLops"]
assert rec["sota_2026_platform"]["p99_ms"] < rec["naive_monolith"]["p99_ms"]
assert rec["sota_2026_platform"]["slo_satisfaction_pct"] >= 99.0
assert rec["tco_savings_pct"] >= 50.0
def test_06_e2e_card_fraud_platform_meets_45ms_slo(full_suite_42: dict[str, Any]) -> None:
fraud = full_suite_42["exp1_e2e_latency_and_tco"]["by_archetype"]["Card-Fraud-Platform"]
assert fraud["sota_2026_platform"]["p99_ms"] <= 45.0
assert fraud["sota_2026_platform"]["slo_satisfaction_pct"] >= 99.0
assert fraud["p99_speedup_x"] >= 3.0
def test_07_e2e_agentic_llm_platform_tco_and_latency_speedup(full_suite_42: dict[str, Any]) -> None:
llm = full_suite_42["exp1_e2e_latency_and_tco"]["by_archetype"]["Agentic-LLM-Platform"]
assert llm["sota_2026_platform"]["p99_ms"] <= 900.0
assert llm["p99_speedup_x"] >= 3.0
assert llm["tco_savings_pct"] >= 70.0
def test_08_invalid_archetype_or_tier_raises_value_error() -> None:
with pytest.raises(ValueError, match="Unknown archetype_id"):
simulate_archetype_e2e("Unknown-Arch", "sota_2026_platform")
with pytest.raises(ValueError, match="Unknown tier"):
simulate_archetype_e2e("RecSys-MLops", "mystery_tier")
@given(
low_rho=st.floats(min_value=0.15, max_value=0.45),
high_rho=st.floats(min_value=0.70, max_value=0.92),
cache_low=st.floats(min_value=0.05, max_value=0.25),
cache_high=st.floats(min_value=0.45, max_value=0.80),
)
@settings(max_examples=20)
def test_09_hypothesis_monotonic_latency_congestion_and_cache_tco_savings(
low_rho: float,
high_rho: float,
cache_low: float,
cache_high: float,
) -> None:
r_low = simulate_archetype_e2e(
"Agentic-LLM-Platform",
"sota_2026_platform",
n_requests=800,
seed=42,
load_rho_override=low_rho,
)
r_high = simulate_archetype_e2e(
"Agentic-LLM-Platform",
"sota_2026_platform",
n_requests=800,
seed=42,
load_rho_override=high_rho,
)
assert r_high["p95_ms"] > r_low["p95_ms"]
c_low = simulate_archetype_e2e(
"RecSys-MLops",
"sota_2026_platform",
n_requests=800,
seed=42,
cache_hit_override=cache_low,
)
c_high = simulate_archetype_e2e(
"RecSys-MLops",
"sota_2026_platform",
n_requests=800,
seed=42,
cache_hit_override=cache_high,
)
assert c_high["tco_breakdown_usd"]["gpu_compute_usd"] < c_low["tco_breakdown_usd"]["gpu_compute_usd"]
def test_10_failure_s1_late_data_watermark_recovery(full_suite_42: dict[str, Any]) -> None:
s1 = full_suite_42["exp2_failure_injection"]["by_id"]["late_data_watermark"]
assert s1["passed"] is True
assert s1["naive"]["completeness_pct"] < 90.0
assert s1["sota_2026"]["completeness_pct"] >= 99.5
assert s1["sota_2026"]["aggregate_mape_pct"] <= 0.5
def test_11_failure_s2_pit_training_serving_skew_eliminated(full_suite_42: dict[str, Any]) -> None:
s2 = full_suite_42["exp2_failure_injection"]["by_id"]["pit_training_serving_skew"]
assert s2["passed"] is True
assert s2["naive"]["future_leakage_pct"] >= 20.0
assert s2["sota_2026"]["future_leakage_pct"] == 0.0
assert s2["sota_2026"]["train_serve_psi"] < 0.05
def test_12_failure_s3_bursty_10x_gpu_surge_admission_control(full_suite_42: dict[str, Any]) -> None:
s3 = full_suite_42["exp2_failure_injection"]["by_id"]["bursty_gpu_surge_10x"]
assert s3["passed"] is True
assert s3["naive"]["goodput_pct"] < 40.0
assert s3["sota_2026"]["interactive_goodput_pct"] >= 95.0
assert s3["sota_2026"]["interactive_p99_ms"] <= s3["slo_ms"]
def test_13_failure_s4_mcp_sandbox_blocks_all_eight_probes(full_suite_42: dict[str, Any]) -> None:
s4 = full_suite_42["exp2_failure_injection"]["by_id"]["mcp_agent_sandbox_isolation"]
assert s4["passed"] is True
assert s4["naive"]["secret_exfiltrations"] > 0
assert s4["sota_2026"]["attacks_blocked"] == s4["total_probes"] == 8
assert s4["sota_2026"]["attacks_blocked_pct"] == 100.0
assert s4["sota_2026"]["secret_exfiltrations"] == 0
def test_14_failure_s5_canary_sprt_automated_rollback(full_suite_42: dict[str, Any]) -> None:
s5 = full_suite_42["exp2_failure_injection"]["by_id"]["canary_sprt_rollback"]
assert s5["passed"] is True
assert s5["sota_canary_sprt"]["tripped_at_step_pct"] <= 5
assert s5["sota_canary_sprt"]["blast_radius_reduction_pct"] >= 95.0
assert s5["sota_canary_sprt"]["errors_prevented"] >= 250
def test_15_failure_s6_delayed_label_ipcw_and_active_audit_ht(full_suite_42: dict[str, Any]) -> None:
s6 = full_suite_42["exp2_failure_injection"]["by_id"]["delayed_label_ipcw_proxy"]
assert s6["passed"] is True
assert s6["naive"]["optimism_bias_pp"] > 15.0
assert s6["sota_2026"]["prediction_psi"] >= 0.15
assert s6["sota_2026"]["audit_error_pp"] < 5.0
assert s6["sota_2026"]["detection_lead_days"] == 39
def test_16_rubric_flagship_submission_certified_production_ready() -> None:
res = run_capstone_rubric_benchmarks()["by_id"]["sota_flagship_submission"]
assert res["raw_total_score"] >= 95.0
assert res["effective_score"] == res["raw_total_score"]
assert res["disqualifier_count"] == 0
assert res["status"] == "CERTIFIED_PRODUCTION_READY"
assert res["production_ready"] is True
assert res["deploy_gate_open"] is True
def test_17_rubric_hard_disqualifiers_veto_high_raw_score() -> None:
insec = run_capstone_rubric_benchmarks()["by_id"]["insecure_latest_agent_submission"]
assert insec["raw_total_score"] >= 80.0
assert insec["effective_score"] == 0.0
assert insec["status"] == "DISQUALIFIED"
assert insec["production_ready"] is False
assert insec["deploy_gate_open"] is False
assert set(insec["triggered_disqualifiers"]) == {
"unsandboxed_mcp_execution",
"latest_container_tag_used",
}
def test_18_rubric_needs_remediation_without_disqualifiers() -> None:
sub = CapstoneRubricSubmission(
submission_id="incomplete_but_safe",
archetype_id="RecSys-MLops",
data_lakehouse_pit=12.5,
security_k8s_sandbox=12.5,
gateway_and_serving=15.0,
mlops_cicd_canary=12.0,
observability_late_labels_sre=12.0,
live_chaos_and_finops=15.0,
)
res = evaluate_capstone_rubric(sub)
assert res["raw_total_score"] == 79.0
assert res["disqualifier_count"] == 0
assert res["status"] == "NEEDS_REMEDIATION"
assert res["production_ready"] is False
sub_pass = CapstoneRubricSubmission(
submission_id="just_passing_80",
archetype_id="RecSys-MLops",
data_lakehouse_pit=12.0,
security_k8s_sandbox=12.0,
gateway_and_serving=16.0,
mlops_cicd_canary=12.0,
observability_late_labels_sre=12.0,
live_chaos_and_finops=16.0,
)
res_pass = evaluate_capstone_rubric(sub_pass)
assert res_pass["raw_total_score"] == 80.0
assert res_pass["status"] == "CERTIFIED_PRODUCTION_READY"
@given(flag_idx=st.integers(min_value=0, max_value=len(HARD_DISQUALIFIERS) - 1))
@settings(max_examples=18)
def test_19_hypothesis_any_hard_disqualifier_forces_disqualified(flag_idx: int) -> None:
kwargs: dict[str, Any] = {
"submission_id": "prop_check",
"archetype_id": "Agentic-LLM-Platform",
"data_lakehouse_pit": 15.0,
"security_k8s_sandbox": 15.0,
"gateway_and_serving": 20.0,
"mlops_cicd_canary": 15.0,
"observability_late_labels_sre": 15.0,
"live_chaos_and_finops": 20.0,
}
kwargs[HARD_DISQUALIFIERS[flag_idx]] = True
out = evaluate_capstone_rubric(CapstoneRubricSubmission(**kwargs))
assert out["status"] == "DISQUALIFIED"
assert out["effective_score"] == 0.0
assert out["deploy_gate_open"] is False
def test_20_pii_redaction_strips_email_card_phone_and_tokens() -> None:
raw = (
"Email an.nguyen@example.com card 4111-2222-3333-4448 "
"phone +1-415-555-0199 auth Bearer tokensecret123 sk-testsecret999 AKIA1234567890ABCDEF"
)
cleaned = redact_pii(raw)
for sensitive in (
"an.nguyen@example.com",
"4111-2222-3333-4448",
"415-555-0199",
"tokensecret123",
"sk-testsecret999",
"AKIA1234567890ABCDEF",
):
assert sensitive not in cleaned
assert "[REDACTED_EMAIL]" in cleaned
assert "[REDACTED_CARD]" in cleaned
assert "[REDACTED_SECRET]" in cleaned
def test_21_prometheus_high_cardinality_guardrail_rejects_user_and_trace_labels() -> None:
prom = PrometheusCapstoneMetrics()
for bad_key in ("user_id", "request_id", "trace_id", "email"):
with pytest.raises(ValueError, match="High-cardinality"):
prom.validate_labels({"archetype": "RecSys-MLops", bad_key: "abc"})
def test_22_live_fastapi_health_live_and_ready_200_vs_503() -> None:
app_ok, _, _ = create_capstone_app(topology_path=TOPOLOGY_YAML)
with TestClient(app_ok) as c_ok:
assert c_ok.get("/health/live").status_code == 200
assert c_ok.get("/health/ready").status_code == 200
app_bad, _, _ = create_capstone_app(topology_path=TOPOLOGY_YAML, readiness_override=False)
with TestClient(app_bad) as c_bad:
r_bad = c_bad.get("/health/ready")
assert r_bad.status_code == 503
assert r_bad.json()["status"] == "not_ready"
def test_23_live_fastapi_audit_e2e_emits_hierarchical_otel_spans_and_zero_pii() -> None:
res = run_capstone_service_and_otel_checks(lab_root=LAB_ROOT)
assert res["health_live_status"] == 200
assert res["health_ready_status"] == 200
assert res["flagship_verdict"] == "CERTIFIED_PRODUCTION_READY"
assert res["disqualified_verdict"] == "DISQUALIFIED"
assert res["otel_span_count"] == 9
assert res["pii_leaks_count"] == 0
assert res["prometheus_checks_passed"] is True
def test_24_live_fastapi_metrics_exposition_format() -> None:
app, _, _ = create_capstone_app(topology_path=TOPOLOGY_YAML)
payload = {
"submission": {
"submission_id": "metrics_probe",
"archetype_id": "RecSys-MLops",
"data_lakehouse_pit": 14.0,
"security_k8s_sandbox": 14.5,
"gateway_and_serving": 19.0,
"mlops_cicd_canary": 14.0,
"observability_late_labels_sre": 14.5,
"live_chaos_and_finops": 19.0,
},
"trace_note": "check_metrics",
"seed": 42,
}
with TestClient(app) as client:
assert client.post("/audit/e2e", json=payload).status_code == 200
m_resp = client.get("/metrics")
assert m_resp.status_code == 200
txt = m_resp.text
expected_counter = (
'fsds_capstone_audits_total{archetype="RecSys-MLops",'
'status="CERTIFIED_PRODUCTION_READY"} 1'
)
assert expected_counter in txt
assert 'fsds_capstone_readiness_score{archetype="RecSys-MLops"} 95.00' in txt
assert 'fsds_capstone_audit_duration_seconds_bucket{le="+Inf"} 1' in txt
def test_25_archetype_specs_cover_all_three_flagships() -> None:
assert set(ARCHETYPE_SPECS.keys()) == {
"RecSys-MLops",
"Card-Fraud-Platform",
"Agentic-LLM-Platform",
}
e2e = run_cross_layer_e2e_tco_suite(seed=42, n_requests=1000)
assert len(e2e["comparisons"]) == 3
def test_26_full_suite_workbench_panels_contract(full_suite_42: dict[str, Any]) -> None:
panels = full_suite_42["workbench_panels"]
assert len(panels["kpis"]) == 6
assert len(panels["bars"]) == 4
assert len(panels["tables"]) == 4
assert full_suite_42["suite_otel_telemetry"]["span_count"] == 5
assert full_suite_42["exp2_failure_injection"]["all_passed"] is True
def test_27_full_suite_deterministic_reproducibility(full_suite_42: dict[str, Any]) -> None:
repeat = run_full_lab_suite(seed=42, lab_root=LAB_ROOT)
assert repeat["exp1_e2e_latency_and_tco"] == full_suite_42["exp1_e2e_latency_and_tco"]
assert repeat["exp2_failure_injection"] == full_suite_42["exp2_failure_injection"]
assert repeat["exp3_capstone_rubric"] == full_suite_42["exp3_capstone_rubric"]
def test_28_cli_run_lab_demo_generates_valid_json(tmp_path: Path) -> None:
out_file = tmp_path / "wb26_out.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--output",
str(out_file),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "PII Leaks=0" in proc.stdout
loaded = json.loads(out_file.read_text(encoding="utf-8"))
assert loaded["unit_id"] == "T2-P5-U03"
assert loaded["exp4_live_fastapi_otel"]["otel_span_count"] == 9
def test_29_unified_6domain_rubric_contract_and_real_perf_counter_timing() -> None:
assert DOMAIN_WEIGHTS == {
"data_lakehouse_pit": 15,
"security_k8s_sandbox": 15,
"gateway_and_serving": 20,
"mlops_cicd_canary": 15,
"observability_late_labels_sre": 15,
"live_chaos_and_finops": 20,
}
assert sum(DOMAIN_WEIGHTS.values()) == 100
assert PASS_THRESHOLD_SCORE == 80.0
assert len(HARD_DISQUALIFIERS) == 6
assert "missing_canary_rollback" in HARD_DISQUALIFIERS
app, _, prom = create_capstone_app(topology_path=TOPOLOGY_YAML)
payload = {
"submission": {
"submission_id": "timing_probe",
"archetype_id": "Agentic-LLM-Platform",
"data_lakehouse_pit": 14.0,
"security_k8s_sandbox": 14.0,
"gateway_and_serving": 19.0,
"mlops_cicd_canary": 14.0,
"observability_late_labels_sre": 14.0,
"live_chaos_and_finops": 19.0,
},
"trace_note": "real_timing_check",
"seed": 42,
}
with TestClient(app) as client:
r1 = client.post("/audit/e2e", json=payload).json()
r2 = client.post("/audit/e2e", json=payload).json()
assert r1["audit_duration_ms"] > 0.0
assert r2["audit_duration_ms"] > 0.0
assert prom.duration_sum > 0.0
assert not (
abs(prom.duration_sum - 0.084) < 1e-6 and abs(r1["audit_duration_ms"] - 42.0) < 1e-3
)
def test_30_behavioral_audit_and_mcp_sandbox_reject_loopback_and_big_bang() -> None:
topo = yaml.safe_load(TOPOLOGY_YAML.read_text(encoding="utf-8"))
sandbox_cfg = dict(topo["services"]["mcp_tool_sandbox"])
ok_mcp = evaluate_mcp_sandbox_policy(sandbox_cfg)
assert ok_mcp["attacks_blocked"] == 8
assert ok_mcp["egress_dns_only"] is True
assert ok_mcp["passed"] is True
bad_sandbox = json.loads(json.dumps(sandbox_cfg))
bad_sandbox["egress_allowlist"] = ["127.0.0.1:8123", "169.254.169.254:80"]
bad_mcp = evaluate_mcp_sandbox_policy(bad_sandbox)
assert bad_mcp["egress_dns_only"] is False
assert bad_mcp["passed"] is False
ev_good = CapstoneBehavioralEvidence(
submission_id="behav_sota",
archetype_id="Agentic-LLM-Platform",
watermark_minutes=10.0,
allowed_lateness_minutes=8.0,
dlq_enabled=True,
pit_asof_enforced=True,
plaintext_secret_count=0,
latest_tag_count=0,
loopback_host_binds=True,
vault_dynamic_leases=True,
istio_strict_mtls=True,
mcp_sandbox_config=sandbox_cfg,
cache_hit_rate=0.34,
target_load_rho=0.50,
admission_control_enabled=True,
dual_tpm_usd_budget=True,
git_sha256=hashlib.sha256(b"g").hexdigest(),
dvc_sha256=hashlib.sha256(b"d").hexdigest(),
mlflow_sha256=hashlib.sha256(b"m").hexdigest(),
prompt_sha256=hashlib.sha256(b"p").hexdigest(),
mlflow_aliases_configured=True,
canary_rollback_monitor="msprt",
otel_pii_redaction_enabled=True,
forbidden_high_card_labels=0,
otel_genai_v1_37_plus=True,
ragas_eval_enabled=True,
prometheus_native_histograms=True,
sre_multi_window_burn_rate=True,
active_audit_ht_enabled=True,
finops_tco_verified=True,
chaos_scenarios_passed=6,
)
scored_good = audit_behavioral_submission(ev_good, seed=42)
rubric_good = evaluate_capstone_rubric(
CapstoneRubricSubmission(
**{
k: scored_good[k]
for k in (
"submission_id",
"archetype_id",
*DOMAIN_WEIGHTS.keys(),
*HARD_DISQUALIFIERS,
)
}
)
)
assert rubric_good["status"] == "CERTIFIED_PRODUCTION_READY"
assert rubric_good["effective_score"] >= 95.0
# Mutate behavioral fields: big_bang rollout (HD-5) + bad sandbox egress + bad SHA
ev_bad = ev_good.model_copy(
update={
"submission_id": "behav_bad",
"mcp_sandbox_config": bad_sandbox,
"canary_rollback_monitor": "big_bang",
"git_sha256": "short-hash",
}
)
scored_bad = audit_behavioral_submission(ev_bad, seed=42)
assert scored_bad["unsandboxed_mcp_execution"] is True
assert scored_bad["missing_canary_rollback"] is True
assert scored_bad["four_way_sha256_valid"] is False
def test_31_live_audit_e2e_accepts_behavioral_evidence_and_uses_km_ipcw(
full_suite_42: dict[str, Any],
) -> None:
s6 = full_suite_42["exp2_failure_injection"]["by_id"]["delayed_label_ipcw_proxy"]
assert s6["sota_2026"]["ipcw_estimator"] == "kaplan_meier_product_limit"
topo = yaml.safe_load(TOPOLOGY_YAML.read_text(encoding="utf-8"))
sandbox_cfg = dict(topo["services"]["mcp_tool_sandbox"])
app, _, _ = create_capstone_app(topology_path=TOPOLOGY_YAML)
payload = {
"behavioral_evidence": {
"submission_id": "api_behavioral_probe",
"archetype_id": "Card-Fraud-Platform",
"watermark_minutes": 10.0,
"allowed_lateness_minutes": 8.0,
"dlq_enabled": True,
"pit_asof_enforced": True,
"plaintext_secret_count": 0,
"latest_tag_count": 0,
"loopback_host_binds": True,
"vault_dynamic_leases": True,
"istio_strict_mtls": True,
"mcp_sandbox_config": sandbox_cfg,
"cache_hit_rate": 0.12,
"target_load_rho": 0.44,
"admission_control_enabled": True,
"dual_tpm_usd_budget": True,
"git_sha256": hashlib.sha256(b"g1").hexdigest(),
"dvc_sha256": hashlib.sha256(b"d1").hexdigest(),
"mlflow_sha256": hashlib.sha256(b"m1").hexdigest(),
"prompt_sha256": hashlib.sha256(b"p1").hexdigest(),
"mlflow_aliases_configured": True,
"canary_rollback_monitor": "msprt",
"otel_pii_redaction_enabled": True,
"forbidden_high_card_labels": 0,
"otel_genai_v1_37_plus": True,
"ragas_eval_enabled": True,
"prometheus_native_histograms": True,
"sre_multi_window_burn_rate": True,
"active_audit_ht_enabled": True,
"finops_tco_verified": True,
"chaos_scenarios_passed": 6,
},
"trace_note": "behavioral_api_test",
"seed": 42,
}
with TestClient(app) as client:
resp = client.post("/audit/e2e", json=payload)
assert resp.status_code == 200
body = resp.json()
assert body["behavioral_audit"] is not None
assert body["rubric"]["status"] == "CERTIFIED_PRODUCTION_READY"
assert body["rubric"]["effective_score"] >= 95.0
def test_32_luhn_pii_redaction_preserves_timestamps_and_non_luhn_ids() -> None:
raw = (
"ts_ns=1732459384123456789 trace_dec=9876543210123456 "
"bad_pan=4111-2222-3333-4444 valid_pan=4532-1111-2222-3336"
)
cleaned = redact_pii(raw)
assert "ts_ns=1732459384123456789" in cleaned
assert "trace_dec=9876543210123456" in cleaned
assert "bad_pan=4111-2222-3333-4444" in cleaned
assert "4532-1111-2222-3336" not in cleaned
assert "valid_pan=[REDACTED_CARD]" in cleaned
Exp 1 của WB-Ch26 (Agentic-LLM-Platform, seed=42), yếu tố nào giúp kiến trúc SOTA 2026 Platform cắt độ trễ p99 từ 10233.99 ms xuống 794.22 ms (12.89x) và giảm 90.34% TCO?M/G/1, tải cao (rho=0.89) làm hệ số nghẽn phi(rho) khuếch đại độ trễ qua từng chặng. Kiến trúc SOTA 2026 Platform kết hợp Semantic Cache (34% bypass GPU), MCP Sandbox gọn nhẹ, Disagg P/D + FP8 + Piecewise CUDA Graphs, và GPU Spot + Reserved, hạ p99 xuống 794.22 ms (99.78% đạt SLO 900 ms) và giảm TCO từ $1248.65 xuống $120.57/1M reqs (-90.34%).
RecSys-MLops và Card-Fraud-Platform trong Exp 1 của WB-Ch26, đặc điểm kiến trúc cốt lõi của từng hệ thống là gì?RecSys-MLops có ngân sách SLO p99 <= 120 ms, giải quyết bằng Feast + ClickHouse, ANN HNSW, dynamic microbatching và 38% cache (86.34 ms, 298.39 rps/GPU, -76.63% TCO). Ngược lại Card-Fraud-Platform chịu trần khắc nghiệt p99 <= 45 ms, dựa vào Flink RocksDB + ASOF PIT (30.97 ms, 590.91 rps/GPU, 100% SLO, -73.02% TCO) và giám sát nhãn trễ #17.
S1 (late_data_watermark) và S2 (pit_training_serving_skew, #15) của WB-Ch26, vì sao hệ thống ngây thơ thất bại nặng và giải pháp SOTA khắc phục ra sao?S1, watermark 1 phút đánh rơi 694/6,000 giao dịch đến trễ (88.43% đủ, 11.79% MAPE), trong khi Event-Time 10m + 8m allowedLateness + DLQ khôi phục 100.0% (0.0% MAPE). Ở S2, nối không khóa thời gian gây 29.07% rò rỉ tương lai (AUC 0.841 -> 0.7846, PSI=0.0699), còn ASOF PIT đưa rò rỉ về 0.0% và PSI = 0.001.
S3 (bursty_gpu_surge_10x, SLO = 500 ms), chiến lược KEDA + Admission Control bảo vệ trải nghiệm người dùng khi lưu lượng tăng vọt 10x như thế nào?10x, cụm tĩnh FIFO bị bão hòa làm Goodput sụp xuống 15.58% (p99 = 2509.15 ms). Ngược lại, SOTA 2026 kết hợp KEDA theo độ sâu hàng đợi, bể GPU ấm sẵn và Priority Admission Control xả có kiểm soát 60.89% tải nền batch (429 Retry-After), giữ trọn 100.0% Goodput tương tác với p99 = 101.06 ms <= 500 ms.
8 vector tấn công lên công cụ Agent trong kịch bản S4 (mcp_agent_sandbox_isolation), cấu hình hộp cát MCP chuẩn SOTA 2026 ngăn chặn rò rỉ bí mật và RCE bằng tổ hợp nào?Naive chỉ chặn được 2/8 (25.0%) và bị 3 vụ rò rỉ bí mật qua SSRF, biến môi trường và token. SOTA MCP Sandbox kết hợp cap_drop: [ALL], read_only_root_fs: true, non-root UID 65532, seccomp, pids_limit: 64, egress_allowlist chỉ cho phép DNS nội bộ (.svc.cluster.local) và token Vault ngắn hạn — chặn sạch 8/8 (100.0%) và 0 rò rỉ.
S5 (#16) và S6 (#17) của WB-Ch26, hai cơ chế bảo vệ nào giúp giảm thiểu thiệt hại do lỗi mô hình hoặc trôi khái niệm thầm lặng?S5, Wald SPRT (boundary A = 4.554) phát hiện lỗi ngay ở nấc 5% (LLR = 4.698, 24 lượt gọi, 3 lỗi), cắt 99.2% bán kính nổ (348 lỗi được cứu so với 3,000/351 Big-Bang). Ở S6, trong khi Naive báo ảo 90.53% (+24.49 pp so với thật 66.04%), Kaplan–Meier IPCW (79.08%), Pred PSI (0.4511) và Active Audit HT (62.95%, 3.09 pp lỗi) báo sớm 39 ngày.
Exp 3 của WB-Ch26, vì sao bài nộp insecure_latest_agent_submission đạt 83.0/100 điểm thô trên 6 miền kỹ thuật (15, 15, 20, 15, 15, 20) vẫn bị evaluate_capstone_rubric giáng kết quả về DISQUALIFIED?100 điểm gồm 6 miền trọng số (15, 15, 20, 15, 15, 20) với ngưỡng đạt >= 80.0/100 cùng 6 điều kiện loại trực tiếp (HD-1..HD-6: plaintext_secrets_present, latest_container_tag_used, pit_future_leakage_detected, unsandboxed_mcp_execution, missing_canary_rollback, missing_telemetry_or_pii_leak). Chỉ cần dính 1 phủ quyết, điểm hiệu lực tụt về 0.0, DISQUALIFIED, deploy_gate_open = False.
run_capstone_service_and_otel_checks và audit_topology_yaml trong capstone_service_and_rubric.py (Tests 16–32) xác minh những bất biến sản xuất bắt buộc nào?audit_topology_yaml xác minh 19/19 ảnh chính thức ghim phiên bản (python:3.12.8-slim-bookworm, 0 :latest), bind 127.0.0.1:, 0 bí mật, pids_limit: 64 và egress_allowlist chỉ DNS .svc.cluster.local (wb26_behavioral_topology_audit = 100.0). run_capstone_service_and_otel_checks kiểm chứng /health/ready (200/503), /audit/e2e đo bằng time.perf_counter(), /metrics, 9 live + 5 suite OTel spans và 0 rò rỉ PII (kiểm tra thẻ Luhn).
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 — Phân tích Độ trễ Đuôi Xuyên Tầng và Ngân sách FinOps TCO (3 Mẫu hình) 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra công thức _congestion_multiplier(rho) và cấu phần chi phí tco_breakdown_usd trong simulate_archetype_e2e của end_to_end_architecture_audit.py.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_05 or test_06 or test_07 or test_09" -v và đối chiếu exp1_e2e_latency_and_tco trong artifacts/t2_ch26_wb26_results.json.
Tiêu chí Đáp án & Số đối chứng
Hệ số phi(rho) tăng phi tuyến khi rho -> 0.89, khiến Naive vỡ SLO ở cả 3 mẫu hình (RecSys 1186.86ms, Fraud 510.99ms, Agentic 10233.99ms). Tối ưu đồng bộ cache (38%/12%/34%), tải rho, Disagg P/D và Spot/FP8 đưa p99 về 86.34ms / 30.97ms / 794.22ms (13.75x/16.5x/12.89x) và giảm TCO -76.63% / -73.02% / -90.34%.
Bài tập 2 — Xử lý Dữ liệu Đến Trễ Flink và Chống Rò rỉ Point-in-Time (#15) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Quan sát ngưỡng lags_min <= 1.0 vs 18.0 trong _inject_late_data_watermark và phép nối rò rỉ future_flag trong _inject_pit_skew.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_10 or test_11" -v và đối chiếu S1 & S2 trong exp2_failure_injection.
Tiêu chí Đáp án & Số đối chứng
Trong S1, watermark 1m đánh rơi 694 sự kiện (88.43% đủ, 11.79% MAPE), còn Event-Time 10m + 8m allowedLateness + DLQ khôi phục 100.0% (0.0% MAPE). Trong S2, nối không khóa thời gian làm rò 29.07% tương lai (AUC 0.841 -> 0.7846, PSI=0.0699); ASOF PIT đưa rò rỉ về 0.0% và PSI = 0.001.
Bài tập 3 — Điều khiển Thu nạp Bão 10x GPU và Cô lập MCP Sandbox 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xem cách _inject_bursty_gpu_surge tách luồng interactive vs batch, và bảng 8 vector tấn công cùng pids_limit: 64 và DNS egress_allowlist (.svc.cluster.local) trong configs/capstone_platform_topology.yaml.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_12 or test_13" -v và kiểm tra cấu hình mcp_tool_sandbox.
Tiêu chí Đáp án & Số đối chứng
Khi bão 10x, xả tải có kiểm soát 60.89% luồng batch giữ nguyên 100.0% Goodput tương tác (p99 = 101.06 ms <= 500 ms vs 2509.15 ms của Naive). Trên MCP Sandbox, tổ hợp cap_drop: [ALL], read_only_root_fs, seccomp, pids_limit: 64, DNS-only egress_allowlist (.svc.cluster.local) và Vault chặn 8/8 (100.0%) vector và 0 rò rỉ.
Bài tập 4 — Hoàn tác Tự động Canary SPRT (#16) và Giám sát Nhãn Trễ KM-IPCW (#17) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Theo dõi tích lũy log-likelihood ratio llr trước biên dừng A = 4.554 trong _inject_canary_sprt_rollback và ước lượng Kaplan–Meier IPCW trong _inject_delayed_label_ipcw_proxy.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_14 or test_15" -v và đối chiếu S5 & S6 trong artifacts/t2_ch26_wb26_results.json.
Tiêu chí Đáp án & Số đối chứng
Wald SPRT ngắt hồi quy ngay ở bước 5% (LLR = 4.698, chỉ 24 yêu cầu / 3 lỗi), giảm 99.2% bán kính nổ (348 lỗi được cứu). Trên nhãn trễ #17, Naive ảo giác 90.53% (+24.49 pp so với 66.04%), còn Kaplan–Meier IPCW = 79.08%, Pred PSI = 0.4511 và Active Audit HT = 62.95% (3.09 pp lỗi) báo động sớm 39 ngày.
Bài tập 5 — Rubric 6 Miền 100 Điểm (>= 80.0/100), 6 HD và /audit/e2e Live 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Xem evaluate_capstone_rubric (6 miền 15, 15, 20, 15, 15, 20 = 100, ngưỡng >= 80.0/100), 6 HARD_DISQUALIFIERS (HD-1..HD-6), đường dẫn /audit/e2e (time.perf_counter()), redact_pii (Luhn) và PrometheusCapstoneMetrics.validate_labels.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy pytest -k "test_16 or test_17 or test_18 or test_19 or test_20 or test_21 or test_22 or test_23 or test_24 or test_25 or test_26 or test_32" -v.
Tiêu chí Đáp án & Số đối chứng
Hợp đồng thống nhất 6 miền (15, 15, 20, 15, 15, 20) = 100 (đạt >= 80.0/100) và 6 Hard Disqualifiers (HD-1..HD-6): sota_flagship_submission đạt 96.4/100 (CERTIFIED_PRODUCTION_READY); insecure_latest_agent_submission (83.0 thô) bị 0.0 DISQUALIFIED vì dính HD-4 + HD-2. Live FastAPI kiểm chứng /health/ready, /audit/e2e (perf_counter()), /metrics, 9+5 OTel spans (0 PII Luhn) và wb26_behavioral_topology_audit = 100.0.
Bài tập 6 — Kiểm toán Topology YAML 19 Ảnh Ghim Chính thức và Tính Xác định CI 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra audit_topology_yaml (19 ảnh chính thức ghim phiên bản như python:3.12.8-slim-bookworm, DNS egress_allowlist, pids_limit: 64) và các ca giả mạo :latest, 0.0.0.0, sk-..., tắt read_only_root_fs.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy đầy đủ run_lab_demo.py --seed 42, 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
audit_topology_yaml xác nhận 19/19 ảnh chính thức ghim tag (python:3.12.8-slim-bookworm, 0 :latest), bind 127.0.0.1:, 0 bí mật tĩnh, MCP Sandbox (pids_limit: 64, DNS .svc.cluster.local) và từ chối mọi tệp bị giả mạo; toàn bộ 32/32 pytest (0 skip, 0 # type: ignore), ruff, mypy strict và uv.lock đều đạt chuẩn xác định.